summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--CONTRIBUTING.markdown10
-rw-r--r--amd.html.markdown424
-rw-r--r--cs-cz/css.html.markdown2
-rw-r--r--cs-cz/markdown.html.markdown10
-rw-r--r--cue.html.markdown4
-rw-r--r--de-de/csharp-de.html.markdown1780
-rw-r--r--de-de/dynamic-programming-de.html.markdown1
-rw-r--r--de-de/elixir-de.html.markdown846
-rw-r--r--de-de/elm-de.html.markdown2
-rw-r--r--de-de/javascript-de.html.markdown1050
-rw-r--r--de-de/make-de.html.markdown526
-rw-r--r--de-de/nix-de.html.markdown5
-rw-r--r--de-de/pug-de.html.markdown2
-rw-r--r--de-de/pyqt-de.html.markdown8
-rw-r--r--de-de/rst-de.html.markdown6
-rw-r--r--de-de/sql-de.html.markdown116
-rw-r--r--de-de/swift-de.html.markdown2
-rw-r--r--de-de/visualbasic-de.html.markdown2
-rw-r--r--docker.html.markdown562
-rw-r--r--el-gr/haskell-gr.html.markdown476
-rw-r--r--elixir.html.markdown19
-rw-r--r--es-es/amd-es.html.markdown6
-rw-r--r--es-es/docker-es.html.markdown334
-rw-r--r--es-es/elixir-es.html.markdown18
-rw-r--r--es-es/forth-es.html.markdown2
-rw-r--r--es-es/git-es.html.markdown2
-rw-r--r--es-es/powershell-es.html.markdown6
-rw-r--r--es-es/pyqt-es.html.markdown6
-rw-r--r--es-es/python-es.html.markdown2
-rw-r--r--es-es/raku-es.html.markdown2
-rw-r--r--es-es/self-es.html.markdown1
-rw-r--r--es-es/visualbasic-es.html.markdown2
-rw-r--r--es-es/wolfram-es.html.markdown2
-rw-r--r--fa-ir/css-fa.html.markdown50
-rw-r--r--fr-fr/elixir-fr.html.markdown2
-rw-r--r--fr-fr/git-fr.html.markdown2
-rw-r--r--fr-fr/markdown-fr.html.markdown57
-rw-r--r--fr-fr/pyqt-fr.html.markdown10
-rw-r--r--fr-fr/wolfram-fr.html.markdown2
-rw-r--r--hd-hd/amd.html.markdown10
-rw-r--r--hd-hd/d.html.markdown16
-rw-r--r--hjson.html.markdown2
-rw-r--r--httpie.html.markdown2
-rw-r--r--hu-hu/pythonlegacy-hu.html.markdown2
-rw-r--r--id-id/coffeescript-id.html.markdown2
-rw-r--r--id-id/markdown.html.markdown12
-rw-r--r--id-id/pyqt-id.html.markdown6
-rw-r--r--id-id/rst-id.html.markdown6
-rw-r--r--it-it/elixir-it.html.markdown18
-rw-r--r--it-it/markdown.html.markdown23
-rw-r--r--it-it/pyqt-it.html.markdown8
-rw-r--r--it-it/rst-it.html.markdown6
-rw-r--r--it-it/toml-it.html.markdown552
-rw-r--r--ja-jp/python-jp.html.markdown13
-rw-r--r--ja-jp/rust-jp.html.markdown351
-rw-r--r--ko-kr/markdown-kr.html.markdown53
-rw-r--r--lsf/lambda-calculus-lsf.html.markdown91
-rw-r--r--lsf/latex-lsf.html.markdown146
-rw-r--r--make.html.markdown492
-rw-r--r--markdown.html.markdown33
-rw-r--r--mercury.html.markdown2
-rw-r--r--montilang.html.markdown2
-rw-r--r--neat.html.markdown297
-rw-r--r--nix.html.markdown5
-rw-r--r--nl-nl/markdown-nl.html.markdown10
-rw-r--r--opengl.html.markdown1530
-rw-r--r--osl.html.markdown2
-rw-r--r--powershell.html.markdown59
-rw-r--r--pt-br/amd-pt.html.markdown7
-rw-r--r--pt-br/csharp-pt.html.markdown4
-rw-r--r--pt-br/css-pt.html.markdown242
-rw-r--r--pt-br/elixir-pt.html.markdown18
-rw-r--r--pt-br/httpie-pt.html.markdown122
-rw-r--r--pt-br/make-pt.html.markdown490
-rw-r--r--pt-br/markdown-pt.html.markdown39
-rw-r--r--pt-br/pug-pt.html.markdown2
-rw-r--r--pt-br/pyqt-pt.html.markdown6
-rw-r--r--pt-br/self-pt.html.markdown1
-rw-r--r--[-rwxr-xr-x]pt-br/stylus-pt.html.markdown0
-rw-r--r--pt-br/visualbasic-pt.html.markdown2
-rw-r--r--pt-pt/swift-pt.html.markdown2
-rw-r--r--pug.html.markdown2
-rw-r--r--pyqt.html.markdown20
-rw-r--r--python.html.markdown8
-rw-r--r--qsharp.html.markdown2
-rw-r--r--ro-ro/elixir-ro.html.markdown4
-rw-r--r--rst.html.markdown6
-rw-r--r--ru-ru/asymptotic-notation-ru.html.markdown450
-rw-r--r--ru-ru/binary-search-ru.html.markdown2
-rw-r--r--ru-ru/c++-ru.html.markdown2
-rw-r--r--ru-ru/c-ru.html.markdown2
-rw-r--r--ru-ru/css-ru.html.markdown6
-rw-r--r--ru-ru/elixir-ru.html.markdown2
-rw-r--r--ru-ru/forth-ru.html.markdown4
-rw-r--r--ru-ru/haml-ru.html.markdown10
-rw-r--r--ru-ru/haskell-ru.html.markdown4
-rw-r--r--ru-ru/html-ru.html.markdown58
-rw-r--r--ru-ru/javascript-ru.html.markdown2
-rw-r--r--ru-ru/learnvisualbasic-ru.html.markdown2
-rw-r--r--ru-ru/linker-ru.html.markdown24
-rw-r--r--ru-ru/markdown-ru.html.markdown49
-rw-r--r--ru-ru/php-ru.html.markdown22
-rw-r--r--ru-ru/pyqt-ru.html.markdown16
-rw-r--r--ru-ru/qt-ru.html.markdown2
-rw-r--r--ru-ru/sql-ru.html.markdown6
-rw-r--r--ru-ru/swift-ru.html.markdown2
-rw-r--r--ru-ru/tcl-ru.html.markdown584
-rw-r--r--ru-ru/tmux-ru.html.markdown2
-rw-r--r--ru-ru/typescript-ru.html.markdown4
-rw-r--r--ru-ru/vim-ru.html.markdown6
-rw-r--r--ru-ru/xml-ru.html.markdown2
-rw-r--r--ru-ru/yaml-ru.html.markdown10
-rw-r--r--sk-sk/elixir-sk.html.markdown16
-rw-r--r--sk-sk/git-sk.html.markdown3
-rw-r--r--sv-se/nix-sv.html.markdown5
-rw-r--r--swift.html.markdown2
-rw-r--r--[-rwxr-xr-x]toml.html.markdown0
-rw-r--r--tr-tr/git-tr.html.markdown2
-rw-r--r--tr-tr/sql-tr.html.markdown248
-rw-r--r--tr-tr/swift-tr.html.markdown2
-rw-r--r--uk-ua/bash-ua.html.markdown20
-rw-r--r--[-rwxr-xr-x]vala.html.markdown0
-rw-r--r--vi-vn/git-vi.html.markdown774
-rw-r--r--vi-vn/markdown-vi.html.markdown42
-rw-r--r--vi-vn/objective-c-vi.html.markdown632
-rw-r--r--visualbasic.html.markdown2
-rw-r--r--wolfram.html.markdown2
-rw-r--r--yaml.html.markdown2
-rw-r--r--zh-cn/c++-cn.html.markdown1144
-rw-r--r--zh-cn/crystal-cn.html.markdown2
-rw-r--r--zh-cn/elisp-cn.html.markdown690
-rw-r--r--zh-cn/elixir-cn.html.markdown2
-rw-r--r--zh-cn/markdown-cn.html.markdown16
-rw-r--r--zh-cn/matlab-cn.html.markdown1008
-rw-r--r--zh-cn/pyqt-cn.html.markdown6
-rw-r--r--zh-cn/swift-cn.html.markdown2
-rw-r--r--zh-cn/visualbasic-cn.html.markdown2
-rw-r--r--zh-cn/wolfram-cn.html.markdown2
-rw-r--r--zh-cn/zfs-cn.html.markdown2
-rw-r--r--zh-tw/elixir-tw.html.markdown16
-rw-r--r--zig.html.markdown135
141 files changed, 9187 insertions, 7952 deletions
diff --git a/CONTRIBUTING.markdown b/CONTRIBUTING.markdown
index 430ecea0..f3556efa 100644
--- a/CONTRIBUTING.markdown
+++ b/CONTRIBUTING.markdown
@@ -34,7 +34,7 @@ review them more effectively and/or individually.
* **Use UTF-8**
* For translations (or EN articles with non-ASCII characters) please ensure
your file is UTF-8 encoded.
- * Try to leave out the byte-order-mark at the start of the file (in Vim, use
+ * Leave out the byte-order-mark (BOM) at the start of the file (in Vim, use
`:set nobomb`).
* You can check if the file contains a BOM on Linux/Unix systems by running
`file language.html.markdown` You will see this if it uses a BOM:
@@ -58,7 +58,7 @@ Other fields:
*tool* or *Algorithms & Data Structures*. Defaults to *language* if omitted.
* **filename**: The filename for this article's code. It will be fetched, mashed
together, and made downloadable.
- * For non-English articles, *filename* should have a language-specific
+ * For non-English articles, *filename* should have a language-specific
suffix.
* **lang**: For translations, the human language this article is in. For
categorization, mostly.
@@ -76,7 +76,11 @@ lang: ep-ep
*--
```
-### Should I add myself as a Contributor?
+### Syntax highlighter
+
+[Rouge](https://github.com/rouge-ruby/rouge/wiki/List-of-supported-languages-and-lexers) is used for syntax highlighting.
+
+### Should I add myself as a contributor?
If you want to add yourself to contributors, keep in mind that contributors get
equal billing, and the first contributor usually wrote the whole article. Please
diff --git a/amd.html.markdown b/amd.html.markdown
index d7fb41ba..fc8f20a4 100644
--- a/amd.html.markdown
+++ b/amd.html.markdown
@@ -1,212 +1,212 @@
----
-category: tool
-tool: amd
-contributors:
- - ["Frederik Ring", "https://github.com/m90"]
-filename: learnamd.js
----
-
-## Getting Started with AMD
-
-The **Asynchronous Module Definition** API specifies a mechanism for defining
-JavaScript modules such that the module and its dependencies can be asynchronously
-loaded. This is particularly well suited for the browser environment where
-synchronous loading of modules incurs performance, usability, debugging, and
-cross-domain access problems.
-
-### Basic concept
-```javascript
-// The basic AMD API consists of nothing but two methods: `define` and `require`
-// and is all about module definition and consumption:
-// `define(id?, dependencies?, factory)` defines a module
-// `require(dependencies, callback)` imports a set of dependencies and
-// consumes them in the passed callback
-
-// Let's start by using define to define a new named module
-// that has no dependencies. We'll do so by passing a name
-// and a factory function to define:
-define('awesomeAMD', function(){
- var isAMDAwesome = function(){
- return true;
- };
- // The return value of a module's factory function is
- // what other modules or require calls will receive when
- // requiring our `awesomeAMD` module.
- // The exported value can be anything, (constructor) functions,
- // objects, primitives, even undefined (although that won't help too much).
- return isAMDAwesome;
-});
-
-// Now, let's define another module that depends upon our `awesomeAMD` module.
-// Notice that there's an additional argument defining our
-// module's dependencies now:
-define('loudmouth', ['awesomeAMD'], function(awesomeAMD){
- // dependencies will be passed to the factory's arguments
- // in the order they are specified
- var tellEveryone = function(){
- if (awesomeAMD()){
- alert('This is sOoOo rad!');
- } else {
- alert('Pretty dull, isn\'t it?');
- }
- };
- return tellEveryone;
-});
-
-// As we do know how to use define now, let's use `require` to
-// kick off our program. `require`'s signature is `(arrayOfDependencies, callback)`.
-require(['loudmouth'], function(loudmouth){
- loudmouth();
-});
-
-// To make this tutorial run code, let's implement a very basic
-// (non-asynchronous) version of AMD right here on the spot:
-function define(name, deps, factory){
- // notice how modules without dependencies are handled
- define[name] = require(factory ? deps : [], factory || deps);
-}
-
-function require(deps, callback){
- var args = [];
- // first let's retrieve all the dependencies needed
- // by the require call
- for (var i = 0; i < deps.length; i++){
- args[i] = define[deps[i]];
- }
- // satisfy all the callback's dependencies
- return callback.apply(null, args);
-}
-// you can see this code in action here: http://jsfiddle.net/qap949pd/
-```
-
-### Real-world usage with require.js
-
-In contrast to the introductory example, `require.js` (the most popular AMD library) actually implements the **A** in **AMD**, enabling you to load modules and their dependencies asynchronously via XHR:
-
-```javascript
-/* file: app/main.js */
-require(['modules/someClass'], function(SomeClass){
- // the callback is deferred until the dependency is loaded
- var thing = new SomeClass();
-});
-console.log('So here we are, waiting!'); // this will run first
-```
-
-By convention, you usually store one module in one file. `require.js` can resolve module names based on file paths, so you don't have to name your modules, but can simply reference them using their location. In the example `someClass` is assumed to be in the `modules` folder, relative to your configuration's `baseUrl`:
-
-* app/
- * main.js
- * modules/
- * someClass.js
- * someHelpers.js
- * ...
- * daos/
- * things.js
- * ...
-
-This means we can define `someClass` without specifying a module id:
-
-```javascript
-/* file: app/modules/someClass.js */
-define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){
- // module definition, of course, will also happen asynchronously
- function SomeClass(){
- this.method = function(){/**/};
- // ...
- }
- return SomeClass;
-});
-```
-To alter the default path mapping behavior use `requirejs.config(configObj)` in your `main.js`:
-
-```javascript
-/* file: main.js */
-requirejs.config({
- baseUrl : 'app',
- paths : {
- // you can also load modules from other locations
- jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min',
- coolLibFromBower : '../bower_components/cool-lib/coollib'
- }
-});
-require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolLib, helpers){
- // a `main` file needs to call require at least once,
- // otherwise no code will ever run
- coolLib.doFancyStuffWith(helpers.transform($('#foo')));
-});
-```
-`require.js`-based apps will usually have a single entry point (`main.js`) that is passed to the `require.js` script tag as a data-attribute. It will be automatically loaded and executed on pageload:
-
-```html
-<!DOCTYPE html>
-<html>
-<head>
- <title>A hundred script tags? Never again!</title>
-</head>
-<body>
- <script src="require.js" data-main="app/main"></script>
-</body>
-</html>
-```
-
-### Optimizing a whole project using r.js
-
-Many people prefer using AMD for sane code organization during development, but still want to ship a single script file in production instead of performing hundreds of XHRs on page load.
-
-`require.js` comes with a script called `r.js` (that you will probably run in node.js, although Rhino is supported too) that can analyse your project's dependency graph, and build a single file containing all your modules (properly named), minified and ready for consumption.
-
-Install it using `npm`:
-```shell
-$ npm install requirejs -g
-```
-
-Now you can feed it with a configuration file:
-```shell
-$ r.js -o app.build.js
-```
-
-For our above example the configuration might look like:
-```javascript
-/* file : app.build.js */
-({
- name : 'main', // name of the entry point
- out : 'main-built.js', // name of the file to write the output to
- baseUrl : 'app',
- paths : {
- // `empty:` tells r.js that this should still be loaded from the CDN, using
- // the location specified in `main.js`
- jquery : 'empty:',
- coolLibFromBower : '../bower_components/cool-lib/coollib'
- }
-})
-```
-
-To use the built file in production, simply swap `data-main`:
-```html
-<script src="require.js" data-main="app/main-built"></script>
-```
-
-An incredibly detailed [overview of build options](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is available in the GitHub repo.
-
-### Topics not covered in this tutorial
-* [Loader plugins / transforms](http://requirejs.org/docs/plugins.html)
-* [CommonJS style loading and exporting](http://requirejs.org/docs/commonjs.html)
-* [Advanced configuration](http://requirejs.org/docs/api.html#config)
-* [Shim configuration (loading non-AMD modules)](http://requirejs.org/docs/api.html#config-shim)
-* [CSS loading and optimizing with require.js](http://requirejs.org/docs/optimization.html#onecss)
-* [Using almond.js for builds](https://github.com/jrburke/almond)
-
-### Further reading:
-
-* [Official Spec](https://github.com/amdjs/amdjs-api/wiki/AMD)
-* [Why AMD?](http://requirejs.org/docs/whyamd.html)
-* [Universal Module Definition](https://github.com/umdjs/umd)
-
-### Implementations:
-
-* [require.js](http://requirejs.org)
-* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/)
-* [cujo.js](http://cujojs.com/)
-* [curl.js](https://github.com/cujojs/curl)
-* [lsjs](https://github.com/zazl/lsjs)
-* [mmd](https://github.com/alexlawrence/mmd)
+---
+category: tool
+tool: amd
+contributors:
+ - ["Frederik Ring", "https://github.com/m90"]
+filename: learnamd.js
+---
+
+## Getting Started with AMD
+
+The **Asynchronous Module Definition** API specifies a mechanism for defining
+JavaScript modules such that the module and its dependencies can be asynchronously
+loaded. This is particularly well suited for the browser environment where
+synchronous loading of modules incurs performance, usability, debugging, and
+cross-domain access problems.
+
+### Basic concept
+```javascript
+// The basic AMD API consists of nothing but two methods: `define` and `require`
+// and is all about module definition and consumption:
+// `define(id?, dependencies?, factory)` defines a module
+// `require(dependencies, callback)` imports a set of dependencies and
+// consumes them in the passed callback
+
+// Let's start by using define to define a new named module
+// that has no dependencies. We'll do so by passing a name
+// and a factory function to define:
+define('awesomeAMD', function(){
+ var isAMDAwesome = function(){
+ return true;
+ };
+ // The return value of a module's factory function is
+ // what other modules or require calls will receive when
+ // requiring our `awesomeAMD` module.
+ // The exported value can be anything, (constructor) functions,
+ // objects, primitives, even undefined (although that won't help too much).
+ return isAMDAwesome;
+});
+
+// Now, let's define another module that depends upon our `awesomeAMD` module.
+// Notice that there's an additional argument defining our
+// module's dependencies now:
+define('loudmouth', ['awesomeAMD'], function(awesomeAMD){
+ // dependencies will be passed to the factory's arguments
+ // in the order they are specified
+ var tellEveryone = function(){
+ if (awesomeAMD()){
+ alert('This is sOoOo rad!');
+ } else {
+ alert('Pretty dull, isn\'t it?');
+ }
+ };
+ return tellEveryone;
+});
+
+// As we do know how to use define now, let's use `require` to
+// kick off our program. `require`'s signature is `(arrayOfDependencies, callback)`.
+require(['loudmouth'], function(loudmouth){
+ loudmouth();
+});
+
+// To make this tutorial run code, let's implement a very basic
+// (non-asynchronous) version of AMD right here on the spot:
+function define(name, deps, factory){
+ // notice how modules without dependencies are handled
+ define[name] = require(factory ? deps : [], factory || deps);
+}
+
+function require(deps, callback){
+ var args = [];
+ // first let's retrieve all the dependencies needed
+ // by the require call
+ for (var i = 0; i < deps.length; i++){
+ args[i] = define[deps[i]];
+ }
+ // satisfy all the callback's dependencies
+ return callback.apply(null, args);
+}
+// you can see this code in action here: http://jsfiddle.net/qap949pd/
+```
+
+### Real-world usage with require.js
+
+In contrast to the introductory example, `require.js` (the most popular AMD library) actually implements the **A** in **AMD**, enabling you to load modules and their dependencies asynchronously via XHR:
+
+```javascript
+/* file: app/main.js */
+require(['modules/someClass'], function(SomeClass){
+ // the callback is deferred until the dependency is loaded
+ var thing = new SomeClass();
+});
+console.log('So here we are, waiting!'); // this will run first
+```
+
+By convention, you usually store one module in one file. `require.js` can resolve module names based on file paths, so you don't have to name your modules, but can simply reference them using their location. In the example `someClass` is assumed to be in the `modules` folder, relative to your configuration's `baseUrl`:
+
+* app/
+ * main.js
+ * modules/
+ * someClass.js
+ * someHelpers.js
+ * ...
+ * daos/
+ * things.js
+ * ...
+
+This means we can define `someClass` without specifying a module id:
+
+```javascript
+/* file: app/modules/someClass.js */
+define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){
+ // module definition, of course, will also happen asynchronously
+ function SomeClass(){
+ this.method = function(){/**/};
+ // ...
+ }
+ return SomeClass;
+});
+```
+To alter the default path mapping behavior use `requirejs.config(configObj)` in your `main.js`:
+
+```javascript
+/* file: main.js */
+requirejs.config({
+ baseUrl : 'app',
+ paths : {
+ // you can also load modules from other locations
+ jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min',
+ coolLibFromBower : '../bower_components/cool-lib/coollib'
+ }
+});
+require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolLib, helpers){
+ // a `main` file needs to call require at least once,
+ // otherwise no code will ever run
+ coolLib.doFancyStuffWith(helpers.transform($('#foo')));
+});
+```
+`require.js`-based apps will usually have a single entry point (`main.js`) that is passed to the `require.js` script tag as a data-attribute. It will be automatically loaded and executed on pageload:
+
+```html
+<!DOCTYPE html>
+<html>
+<head>
+ <title>A hundred script tags? Never again!</title>
+</head>
+<body>
+ <script src="require.js" data-main="app/main"></script>
+</body>
+</html>
+```
+
+### Optimizing a whole project using r.js
+
+Many people prefer using AMD for sane code organization during development, but still want to ship a single script file in production instead of performing hundreds of XHRs on page load.
+
+`require.js` comes with a script called `r.js` (that you will probably run in node.js, although Rhino is supported too) that can analyse your project's dependency graph, and build a single file containing all your modules (properly named), minified and ready for consumption.
+
+Install it using `npm`:
+```shell
+$ npm install requirejs -g
+```
+
+Now you can feed it with a configuration file:
+```shell
+$ r.js -o app.build.js
+```
+
+For our above example the configuration might look like:
+```javascript
+/* file : app.build.js */
+({
+ name : 'main', // name of the entry point
+ out : 'main-built.js', // name of the file to write the output to
+ baseUrl : 'app',
+ paths : {
+ // `empty:` tells r.js that this should still be loaded from the CDN, using
+ // the location specified in `main.js`
+ jquery : 'empty:',
+ coolLibFromBower : '../bower_components/cool-lib/coollib'
+ }
+})
+```
+
+To use the built file in production, simply swap `data-main`:
+```html
+<script src="require.js" data-main="app/main-built"></script>
+```
+
+An incredibly detailed [overview of build options](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is available in the GitHub repo.
+
+### Topics not covered in this tutorial
+* [Loader plugins / transforms](http://requirejs.org/docs/plugins.html)
+* [CommonJS style loading and exporting](http://requirejs.org/docs/commonjs.html)
+* [Advanced configuration](http://requirejs.org/docs/api.html#config)
+* [Shim configuration (loading non-AMD modules)](http://requirejs.org/docs/api.html#config-shim)
+* [CSS loading and optimizing with require.js](http://requirejs.org/docs/optimization.html#onecss)
+* [Using almond.js for builds](https://github.com/jrburke/almond)
+
+### Further reading:
+
+* [Official Spec](https://github.com/amdjs/amdjs-api/wiki/AMD)
+* [Why AMD?](http://requirejs.org/docs/whyamd.html)
+* [Universal Module Definition](https://github.com/umdjs/umd)
+
+### Implementations:
+
+* [require.js](http://requirejs.org)
+* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/)
+* [cujo.js](http://cujojs.com/)
+* [curl.js](https://github.com/cujojs/curl)
+* [lsjs](https://github.com/zazl/lsjs)
+* [mmd](https://github.com/alexlawrence/mmd)
diff --git a/cs-cz/css.html.markdown b/cs-cz/css.html.markdown
index 54a0a08e..ed69c73a 100644
--- a/cs-cz/css.html.markdown
+++ b/cs-cz/css.html.markdown
@@ -220,9 +220,11 @@ p { vlastnost: hodnota !important; }
```
a tento element
+
```xml
<p style='/*F*/ vlastnost:hodnota;' trida='trida1 trida2' attr='hodnota' />
```
+
Priorita stylu je následující. Pamatujte, priorita pro každou **vlastnost**, ne pro celý blok.
* `E` má nejvyšší prioritu kvůli slůvku `!important`. Je doporučováno se úplně vyhnout jeho použití.
diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown
index 50a69107..e1a96f32 100644
--- a/cs-cz/markdown.html.markdown
+++ b/cs-cz/markdown.html.markdown
@@ -215,7 +215,7 @@ Pro ještě hlubší odsazení můžete přidat další 4 mezery nebo další ta
```md
moje_pole.each do |i|
- puts i
+ puts i
end
```
@@ -228,11 +228,13 @@ Honza neměl tušení, co dělá funkce `go_to()`!
V Markdownu od GitHubu, můžete použít speciální syntaxi pro kód:
-<pre><code class="highlight">&#x60;&#x60;&#x60;ruby
+````md
+```ruby
def neco
- puts "Ahoj světe!"
+ puts "Ahoj světe!"
end
-&#x60;&#x60;&#x60;</code></pre>
+```
+````
Text výše nepotřebuje čtyřmezerové odsazení a parser navíc použije zvýraznění
syntaxe pro zvolený jazyk.
diff --git a/cue.html.markdown b/cue.html.markdown
index a1b76ada..a1ff0822 100644
--- a/cue.html.markdown
+++ b/cue.html.markdown
@@ -1,7 +1,7 @@
---
name: CUE
category: language
-language: cue
+language: CUE
filename: learncue.cue
contributors:
- ["Daniel Cox", "https://github.com/danielpcox"]
@@ -24,7 +24,7 @@ disposition: "oblivious"
Now we can unify and export to JSON:
```bash
-% cue export name.cue disposition.cue
+% cue export name.cue disposition.cue
{
"name": "Daniel",
"disposition": "oblivious"
diff --git a/de-de/csharp-de.html.markdown b/de-de/csharp-de.html.markdown
index 18a23017..662c2e76 100644
--- a/de-de/csharp-de.html.markdown
+++ b/de-de/csharp-de.html.markdown
@@ -1,890 +1,890 @@
----
-language: C#
-contributors:
- - ["Irfan Charania", "https://github.com/irfancharania"]
- - ["Max Yankov", "https://github.com/golergka"]
- - ["Melvyn Laïly", "http://x2a.yt"]
- - ["Shaun McCarthy", "http://www.shaunmccarthy.com"]
-translators:
- - ["Frederik Ring", "https://github.com/m90"]
-filename: LearnCSharp-de.cs
-lang: de-de
----
-C# ist eine elegante, typsichere und objektorientierte Sprache, mit der Entwickler eine Vielzahl sicherer und robuster Anwendungen erstellen können, die im .NET Framework ausgeführt werden.
-
-[Mehr über C# erfährst du hier.](http://msdn.microsoft.com/de-de/library/vstudio/z1zx9t92.aspx)
-
-```c#
-// Einzeilige Kommentare starten mit zwei Schrägstrichen: //
-/*
-Mehrzeile Kommentare wie in C Schrägstrich / Stern
-*/
-/// <summary>
-/// XML-Kommentare können zur automatisierten Dokumentation verwendet werden
-/// </summary>
-
-// Zu Beginn werden die in der Datei verwendeten Namespaces aufgeführt
-using System;
-using System.Collections.Generic;
-using System.Data.Entity;
-using System.Dynamic;
-using System.Linq;
-using System.Linq.Expressions;
-using System.Net;
-using System.Threading.Tasks;
-using System.IO;
-
-// definiert einen Namespace um Code in "packages" zu organisieren
-namespace Learning
-{
- // Jede .cs-Datei sollte zumindest eine Klasse mit dem Namen der Datei
- // enthalten. Das ist zwar nicht zwingend erforderlich, es anders zu
- // handhaben führt aber unweigerlich ins Chaos (wirklich)!
- public class LearnCSharp
- {
- // Zuerst erklärt dieses Tutorial die Syntax-Grundlagen,
- // wenn du bereits Java oder C++ programmieren kannst:
- // lies bei "Interessante Features" weiter!
- public static void Syntax()
- {
- // Mit Console.WriteLine kannst du einfachen Text ausgeben:
- Console.WriteLine("Hallo Welt");
- Console.WriteLine(
- "Integer: " + 10 +
- " Double: " + 3.14 +
- " Boolean: " + true);
-
- // Console.Write erzeugt keinen Zeilenumbruch
- Console.Write("Hallo ");
- Console.Write("Welt");
-
- ///////////////////////////////////////////////////
- // Typen & Variablen
- ///////////////////////////////////////////////////
-
- // Deklariere eine Variable mit <Typ> <Name>
-
- // Sbyte - Vorzeichenbehaftete 8-Bit Ganzzahl
- // (-128 <= sbyte <= 127)
- sbyte fooSbyte = 100;
-
- // Byte - Vorzeichenlose 8-Bit Ganzzahl
- // (0 <= byte <= 255)
- byte fooByte = 100;
-
- // Short - 16-Bit Ganzzahl
- // Vorzeichenbehaftet - (-32,768 <= short <= 32,767)
- // Vorzeichenlos - (0 <= ushort <= 65,535)
- short fooShort = 10000;
- ushort fooUshort = 10000;
-
- // Integer - 32-bit Ganzzahl
- int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647)
- uint fooUint = 1; // (0 <= uint <= 4,294,967,295)
-
- // Long - 64-bit Ganzzahl
- long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
- ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615)
- // Ganze Zahlen werden standardmäßig - je nach Größe - als int oder
- // uint behandelt. Ein nachgestelltes L markiert den Wert als long
- // oder ulong.
-
- // Double - Double-precision 64-bit IEEE 754 Fließkommazahl
- double fooDouble = 123.4; // Genauigkeit: 15-16 Stellen
-
- // Float - Single-precision 32-bit IEEE 754 Fließkommazahl
- float fooFloat = 234.5f; // Genauigkeit: 7 Stellen
- // Das nachgestellte f zeigt an dass es sich um einen Wert vom Typ
- // float handelt
-
- // Decimal - ein 128-Bit-Datentyp mit größerer Genauigkeit als
- // andere Fließkommatypen, und somit bestens geeignet für
- // die Berechnung von Geld- und Finanzwerten
- decimal fooDecimal = 150.3m;
-
- // Boolean - true & false
- bool fooBoolean = true; // oder false
-
- // Char - Ein einzelnes 16-Bit Unicode Zeichen
- char fooChar = 'A';
-
- // Strings - im Gegensatz zu allen vorhergehenden Basistypen, die
- // alle Werttypen sind, ist String ein Referenztyp. Strings sind
- // somit nullable, Werttypen sind dies nicht.
- string fooString = "\"maskiere\" Anführungszeichen, und füge \n (Umbrüche) und \t (Tabs) hinzu";
- Console.WriteLine(fooString);
-
- // Jeder Buchstabe eines Strings kann über seinen Index
- // referenziert werden:
- char charFromString = fooString[1]; // => 'e'
- // Strings sind unveränderlich:
- // `fooString[1] = 'X';` funktioniert nicht
-
- // Ein Vergleich zweier Strings, unter Berücksichtigung der
- // aktuellen, sprachspezifischen Gegebenheiten (also z.B. a,ä,b,c
- // in deutschsprachigen Umgebungen), und ohne Beachtung von
- // Groß- und Kleinschreibung:
- string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase);
-
- // Formatierung, genau wie "sprintf"
- string fooFs = string.Format("Mikrofon Check, {0} {1}, {0} {1:0.0}", 1, 2);
-
- // Datumsangaben und Formatierung
- DateTime fooDate = DateTime.Now;
- Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy"));
-
- // Durch ein vorangestelltes @ lässt sich ein mehrzeiliger String
- // schreiben. Um " zu maskieren benutzt man ""
- string bazString = @"Hier geht es
-zur nächsten Zeile, ""Wahnsinn!"", die Massen waren kaum zu bändigen";
-
- // Die Keywords const oder readonly kennzeichnen eine
- // unveränderliche Variable/Konstante. Die Werte von Konstanten
- // werden übrigens bereits zur Compile-Zeit berechnet.
- const int HOURS_I_WORK_PER_WEEK = 9001;
-
- ///////////////////////////////////////////////////
- // Datenstrukturen
- ///////////////////////////////////////////////////
-
- // Arrays - Index beginnt bei Null
- // Die Größe des Arrays wird bei der Deklaration festgelegt.
- // Die syntaktische Struktur um ein neues Array zu erzeugen sieht
- // folgendermaßen aus:
- // <datatype>[] <varname> = new <datatype>[<array size>];
- int[] intArray = new int[10];
-
- // Arrays können auch über ein Array-Literal deklariert werden:
- int[] y = { 9000, 1000, 1337 };
-
- // Indizierung eines Arrays - Zugriff auf ein bestimmtes Element
- Console.WriteLine("intArray @ 0: " + intArray[0]);
- // Arrays sind veränderbar
- intArray[1] = 1;
-
- // Listen
- // Durch ihre größere Flexibilität kommen Listen in C# weit
- // häufiger zum Einsatz als Arrays. Eine Liste wird so deklariert:
- // List<datatype> <varname> = new List<datatype>();
- List<int> intList = new List<int>();
- List<string> stringList = new List<string>();
- List<int> z = new List<int> { 9000, 1000, 1337 };
- // Die <> kennzeichnen "Generics", mehr dazu unter "Coole Sachen"
-
- // Listen haben keinen Default-Wert.
- // Bevor auf einen Index zugegriffen werden kann, muss dieser
- // auch gesetzt worden sein:
- intList.Add(1);
- Console.WriteLine("intList @ 0: " + intList[0]);
-
- // Andere interessante Datenstrukturen sind:
- // Stack/Queue
- // Dictionary (entspricht einer Hash Map)
- // HashSet
- // Read-only Collections
- // Tuple (.Net 4+)
-
- ///////////////////////////////////////
- // Operatoren
- ///////////////////////////////////////
- Console.WriteLine("\n->Operatoren");
-
- // kurze Schreibweise um mehrere Deklarationen zusammenzufassen:
- // (Benutzung vom C# Styleguide aber ausdrücklich abgeraten!)
- int i1 = 1, i2 = 2;
-
- // Arithmetik funktioniert wie erwartet:
- Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3
-
- // Modulo
- Console.WriteLine("11%3 = " + (11 % 3)); // => 2
-
- // Vergleiche
- Console.WriteLine("3 == 2? " + (3 == 2)); // => false
- Console.WriteLine("3 != 2? " + (3 != 2)); // => true
- Console.WriteLine("3 > 2? " + (3 > 2)); // => true
- Console.WriteLine("3 < 2? " + (3 < 2)); // => false
- Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true
- Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true
-
- // Bitweise Operatoren
- /*
- ~ Unäres bitweises NICHT
- << Verschieben nach links
- >> Verschieben nach rechts
- & Bitweises UND
- ^ Bitweises exklusives ODER
- | Bitweises inklusives ODER
- */
-
- // Inkremente
- int i = 0;
- Console.WriteLine("\n->Inkrement / Dekrement");
- Console.WriteLine(i++); //i = 1. Post-Inkrement
- Console.WriteLine(++i); //i = 2. Pre-Inkrement
- Console.WriteLine(i--); //i = 1. Post-Dekrement
- Console.WriteLine(--i); //i = 0. Pre-Dekrement
-
- ///////////////////////////////////////
- // Kontrollstrukturen
- ///////////////////////////////////////
- Console.WriteLine("\n->Kontrollstrukturen");
-
- // If-Statements funktionieren wie in C
- int j = 10;
- if (j == 10)
- {
- Console.WriteLine("Ich werde ausgegeben");
- }
- else if (j > 10)
- {
- Console.WriteLine("Ich nicht");
- }
- else
- {
- Console.WriteLine("Ich leider auch nicht");
- }
-
- // Ternärer Operator
- // Anstatt eines einfachen if/else lässt sich auch folgendes schreiben:
- // <condition> ? <true> : <false>
- int zumVergleich = 17;
- string isTrue = zumVergleich == 17 ? "Ja" : "Nein";
-
- // while-Schleife
- int fooWhile = 0;
- while (fooWhile < 100)
- {
- // Wird 100mal wiederholt, fooWhile 0->99
- fooWhile++;
- }
-
- // do-while-Schleife
- int fooDoWhile = 0;
- do
- {
- // Wird 100mal wiederholt, fooDoWhile 0->99
- fooDoWhile++;
- } while (fooDoWhile < 100);
-
- //for-Schleifen => for(<start_statement>; <conditional>; <step>)
- for (int fooFor = 0; fooFor < 10; fooFor++)
- {
- // Wird 10mal wiederholt, fooFor 0->9
- }
-
- // foreach-Schleife
- // Die normale Syntax für eine foreach-Schleife lautet:
- // foreach(<iteratorType> <iteratorName> in <enumerable>)
- // foreach kann mit jedem Objekt verwendet werden das IEnumerable
- // oder IEnumerable<T> implementiert. Alle Auflistungs-Typen
- // (Array, List, Dictionary...) im .NET Framework implementieren
- // eines dieser beiden Interfaces.
-
- foreach (char character in "Hallo Welt".ToCharArray())
- {
- // Ein Durchgang für jedes Zeichen im String
- }
- // (ToCharArray() könnte man hier übrigens auch weglassen,
- // da String IEnumerable bereits implementiert)
-
- // Switch Struktur
- // Ein Switch funktioniert mit byte, short, char und int Datentypen.
- // Auch Aufzählungstypen können verwendet werden, genau wie
- // die Klasse String, und ein paar Sonderklassen, die Wrapper für
- // Primitives sind: Character, Byte, Short und Integer
- int month = 3;
- string monthString;
- switch (month)
- {
- case 1:
- monthString = "Januar";
- break;
- case 2:
- monthString = "Februar";
- break;
- case 3:
- monthString = "März";
- break;
- // Man kann für mehrere Fälle auch das selbe Verhalten
- // definieren. Jeder Block muss aber mit einem break-Statement
- // abgeschlossen werden. Einzelne Fälle können über
- // `goto case x` erreicht werden
- case 6:
- case 7:
- case 8:
- monthString = "Sommer!!";
- break;
- default:
- monthString = "Irgendein anderer Monat";
- break;
- }
-
- ///////////////////////////////////////
- // Umwandlung von Datentypen und Typecasting
- ///////////////////////////////////////
-
- // Umwandlung
-
- // von String nach Integer
- // bei einem Fehler wirft diese Code eine Exception
- int.Parse("123"); //gibt die Ganzzahl 123 zurück
-
- // TryParse gibt bei einem Fehler den Default-Wert zurück
- // (im Fall von int: 0)
- int tryInt;
- if (int.TryParse("123", out tryInt)) // gibt true oder false zurück
- {
- Console.WriteLine(tryInt); // 123
- }
-
- // von Integer nach String
- // Die Klasse Convert stellt Methoden zur Konvertierung von
- // unterschiedlichsten Daten zur Verfügung:
- Convert.ToString(123); // "123"
- // oder
- tryInt.ToString(); // "123"
- }
-
- ///////////////////////////////////////
- // Klassen
- ///////////////////////////////////////
- public static void Classes()
- {
-
- // Benutze das new-Keyword um eine Instanz einer Klasse zu erzeugen
- Bicycle trek = new Bicycle();
-
- // So werden Methoden der Instanz aufgerufen
- trek.SpeedUp(3); // Es empfiehlt sich immer Getter und Setter zu benutzen
- trek.Cadence = 100;
-
- // ToString ist eine Konvention über die man üblicherweiser
- // Informationen über eine Instanz erhält
- Console.WriteLine("Infos zu trek: " + trek.ToString());
-
- // Wir instantiieren ein neues Hochrad
- PennyFarthing funbike = new PennyFarthing(1, 10);
- Console.WriteLine("Infos zu funbike: " + funbike.ToString());
-
- Console.Read();
- } // Ende der Methode main
-
- // Main als Konsolenstartpunkt
- // Eine Konsolenanwendung muss eine Methode Main als Startpunkt besitzen
- public static void Main(string[] args)
- {
- OtherInterestingFeatures();
- }
-
- ///////////////////////////////////////
- // Interessante Features
- ///////////////////////////////////////
-
- // Methodensignaturen
-
- public // Sichtbarkeit
- static // Erlaubt einen Zugriff auf der Klasse (nicht auf einer Instanz)
- int // Typ des Rückgabewerts,
- MethodSignatures(
- // Erstes Argument, erwartet int
- int maxCount,
- // setzt sich selbst auf 0 wenn kein anderer Wert übergeben wird
- int count = 0,
- int another = 3,
- // enthält alle weiteren der Methode übergebenen Parameter (quasi Splats)
- params string[] otherParams
- )
- {
- return -1;
- }
-
- // Methoden können überladen werden, solange sie eindeutige
- // Signaturen haben
- public static void MethodSignatures(string maxCount)
- {
- }
-
- // Generische Typen
- // Die Typen für TKey und TValue werden erst beim Aufruf der Methode
- // festgelegt. Diese Methode emuliert z.B. SetDefault aus Python:
- public static TValue SetDefault<TKey, TValue>(
- IDictionary<TKey, TValue> dictionary,
- TKey key,
- TValue defaultItem)
- {
- TValue result;
- if (!dictionary.TryGetValue(key, out result))
- {
- return dictionary[key] = defaultItem;
- }
- return result;
- }
-
- // Möglichen Typen lassen sich auch über ihr Interface beschränken:
- public static void IterateAndPrint<T>(T toPrint) where T: IEnumerable<int>
- {
- // Da T ein IEnumerable ist können wir foreach benutzen
- foreach (var item in toPrint)
- {
- // Item ist ein int
- Console.WriteLine(item.ToString());
- }
- }
-
- public static void OtherInterestingFeatures()
- {
- // Optionale Parameter
- MethodSignatures(3, 1, 3, "Ein paar", "extra", "Strings");
- // setzt explizit einen bestimmten Parameter, andere werden übersprungen
- MethodSignatures(3, another: 3);
-
- // Erweiterungsmethoden
- int i = 3;
- i.Print(); // Weiter unten definiert
-
- // Nullables - perfekt für die Interaktion mit
- // Datenbanken / Rückgabewerten
- // Jeder Wert (d.h. keine Klassen) kann durch das Nachstellen eines ?
- // nullable gemacht werden: <type>? <varname> = <value>
- int? nullable = null; // Die explizite Langform wäre Nullable<int>
- Console.WriteLine("Mein Nullable: " + nullable);
- bool hasValue = nullable.HasValue; // true wenn nicht null
-
- // ?? ist "syntaktischer Zucker" um einen Defaultwert für den Fall
- // dass die Variable null ist festzulegen.
- int notNullable = nullable ?? 0; // 0
-
- // Implizit typisierte Variablen
- // Man kann auch den Typ einer Variable auch vom Compiler
- // bestimmen lassen:
- var magic = "magic ist zur Compile-Zeit ein String, folglich geht keine Typsicherheit verloren";
- magic = 9; // funktioniert nicht da magic vom Typ String ist
-
- // Generics
- var phonebook = new Dictionary<string, string>() {
- {"Resi", "08822 / 43 67"} // Fügt einen Eintrag zum Telefonbuch hinzu
- };
-
- // Hier könnte man auch unser generisches SetDefault von
- // weiter oben benutzen:
- Console.WriteLine(SetDefault<string,string>(phonebook, "Xaver", "kein Telefon")); // kein Telefon
- // TKey und TValue müssen nicht zwingend angegeben werden, da sie
- // auch implizit vom Compiler ermittelt werden können
- Console.WriteLine(SetDefault(phonebook, "Resi", "kein Telefon")); // 08822 / 43 67
-
- // Lambdas - konzise Syntax für Inline-Funktionen
- Func<int, int> square = (x) => x * x; // Das letzte Element vom Typ T ist der Rückgabewert
- Console.WriteLine(square(3)); // 9
-
- // Disposables - einfaches Management von nicht verwalteten Ressourcen
- // So gut wie alle Objekte die auf nicht verwaltete Ressourcen
- // (Dateien, Geräte, ...) zugreifen, implementieren das Interface
- // IDisposable. Das using Statement stellt sicher dass die vom
- // IDisposable benutzten Ressourcen nach der Benutzung wieder
- // freigegeben werden:
- using (StreamWriter writer = new StreamWriter("log.txt"))
- {
- writer.WriteLine("Alles bestens!");
- // Am Ende des Codeblocks werden die Ressourcen wieder
- // freigegeben - auch im Falle einer Exception
- }
-
- // Parallel Klasse
- // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
- var websites = new string[] {
- "http://www.google.com", "http://www.reddit.com",
- "http://www.shaunmccarthy.com"
- };
- var responses = new Dictionary<string, string>();
-
- // Für jeden Request wird ein neuer Thread erzeugt, der nächste
- // Schritt wird erst nach Beendigung aller Tasks ausgeführt
- Parallel.ForEach(websites,
- // maximal 3 Threads gleichzeitig
- new ParallelOptions() {MaxDegreeOfParallelism = 3},
- website =>
- {
- // Hier folgt eine langwierige, asynchrone Operation
- using (var r = WebRequest.Create(new Uri(website)).GetResponse())
- {
- responses[website] = r.ContentType;
- }
- });
-
- // Dieser Code wird erst nach Beendigung aller Requests ausgeführt
- foreach (var key in responses.Keys)
- {
- Console.WriteLine("{0}:{1}", key, responses[key]);
- }
-
- // Dynamische Objekte (gut um mit anderen Sprachen zu arbeiten)
- dynamic student = new ExpandoObject();
- // hier muss keine Typ angegeben werden
- student.FirstName = "Christian";
-
- // Einem solchen Objekt kann man sogar Methoden zuordnen.
- // Das Beispiel gibt einen String zurück und erwartet einen String
- student.Introduce = new Func<string, string>(
- (introduceTo) => string.Format("Hallo {0}, das ist {1}", student.FirstName, introduceTo));
- Console.WriteLine(student.Introduce("Bettina"));
-
- // IQueryable<T> - So gut wie alle Aufzählungstypen implementieren
- // dieses Interface, welches eine Vielzahl von funktionalen Methoden
- // wie Map / Filter / Reduce zur Verfügung stellt:
- var bikes = new List<Bicycle>();
- // sortiert die Liste
- bikes.Sort();
- // sortiert nach Anzahl Räder
- bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels));
- var result = bikes
- // diese Filter können auch aneinandergehängt werden
- .Where(b => b.Wheels > 3) // (gibt ein IQueryable des vorherigen Typs zurück)
- .Where(b => b.IsBroken && b.HasTassles)
- // diese Zuordnung gibt ein IQueryable<String> zurück
- .Select(b => b.ToString());
-
- // "Reduce" - addiert alle Räder der Aufzählung zu einem Wert
- var sum = bikes.Sum(b => b.Wheels);
-
- // So erzeugt man ein implizit typisiertes Objekt, basierend auf
- // den Parametern der Elemente:
- var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles });
- // Auch wenn wir es hier nicht demonstrieren können:
- // In einer IDE wie VisualStudio kriegen wir hier sogar TypeAhead,
- // da der Compiler in der Lage ist, die passenden Typen zu erkennen.
- foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome))
- {
- Console.WriteLine(bikeSummary.Name);
- }
-
- // AsParallel-Methode
- // Jetzt kommen die Schmankerl! Die AsParallel-Methode kombiniert
- // LINQ und parallele Operationen:
- var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name);
- // Diese Berechnung passiert parallel! Benötigte Threads werden
- // automatisch erzeugt, und die Rechenlast unter ihnen aufgeteilt.
- // Ein Traum für die Verarbeitung von großen Datenmengen
- // auf mehreren Cores!
-
- // LINQ - bildet einen Datenspeicher auf IQueryable<T> Objekte ab
- // LinqToSql beispielsweise speichert und liest aus einer
- // SQL-Datenbank, LinqToXml aus einem XML-Dokument.
- // LINQ-Operationen werden "lazy" ausgeführt.
- var db = new BikeRepository();
-
- // Die verzögerte Ausführung ist optimal für Datenbankabfragen
- var filter = db.Bikes.Where(b => b.HasTassles); // noch keine Abfrage
- // Es können noch mehr Filter hinzugefügt werden (auch mit
- // Bedingungen) - ideal für z.B. "erweiterte Suchen"
- if (42 > 6)
- {
- filter = filter.Where(b => b.IsBroken); // immer noch keine Abfrage
- }
-
- var query = filter
- .OrderBy(b => b.Wheels)
- .ThenBy(b => b.Name)
- .Select(b => b.Name); // auch hier: immer noch keine Abfrage
-
- // Erst hier wird die Datenbankabfrage wirklich ausgeführt,
- // limitiert auf die Elemente die der foreach-Loop verwendet
- foreach (string bike in query)
- {
- Console.WriteLine(result);
- }
-
- }
-
- } // Ende der Klasse LearnCSharp
-
- // Eine .cs-Datei kann auch mehrere Klassen enthalten
-
- public static class Extensions
- {
- // Erweiterungsmethoden
- public static void Print(this object obj)
- {
- Console.WriteLine(obj.ToString());
- }
- }
-
- // Syntax zur Deklaration einer Klasse:
- // <public/private/protected/internal> class <class name>{
- // // Datenfelder, Konstruktoren und Methoden leben alle
- // // innerhalb dieser Deklaration
- // }
-
- public class Bicycle
- {
- // Felder/Variablen der Klasse "Bicycle"
- // Das Keyword public macht das Member von überall zugänglich
- public int Cadence
- {
- get // get definiert eine Methode um die Eigenschaft abzurufen
- {
- return _cadence;
- }
- set // set definiert eine Methode um die Eigenschaft zu setzen
- {
- _cadence = value; // value ist der dem Setter übergebene Wert
- }
- }
- private int _cadence;
-
- // Das Keyword protected macht das Member nur für die Klasse selbst
- // und ihre Subklassen zugänglich
- protected virtual int Gear
- {
- get; // erzeugt eine Eigenschaft für die kein "Zwischenwert" benötigt wird
- set;
- }
-
- // Das Keyword internal macht das Member innerhalb der Assembly zugänglich
- internal int Wheels
- {
- get;
- private set; // get/set kann auch über Keywords modifiziert werden
- }
-
- int _speed; // Member ohne vorangestellte Keywords sind standardmäßig
- // private, sie sind nur innerhalb der Klasse zugänglich.
- // Man kann aber natürlich auch das Keyword private benutzen.
- private string Name { get; set; }
-
- // Ein Enum ist ein klar definierter Satz an benannten Konstanten.
- // Eigentlich ordnet es diese Konstanten nur bestimmten Werten zu
- // (einer int-Zahl, solange nicht anders angegeben). Mögliche Typen für
- // die Werte eines Enums sind byte, sbyte, short, ushort, int, uint,
- // long, oder ulong. Alle Werte in einem Enum sind eindeutig.
- public enum BikeBrand
- {
- Colnago,
- EddyMerckx,
- Bianchi = 42, // so kann man den Wert explizit setzen
- Kynast // 43
- }
- // Nachdem dieser Typ in der Klasse "Bicycle" definiert ist,
- // sollte Code ausserhalb der Klasse den Typen als Bicycle.Brand referenzieren
-
- // Nachdem das Enum deklariert ist, können wir den Typen verwenden:
- public BikeBrand Brand;
-
- // Als static gekennzeichnete Member gehören dem Typ selbst,
- // nicht seinen Instanzen. Man kann sie also ohne Referenz zu einem
- // Objekt benutzen
- // Console.WriteLine("Schon " + Bicycle.BicyclesCreated + " Fahrräder, nur für dieses Tutorial!");
- static public int BicyclesCreated = 0;
-
- // readonly-Werte werden zur Laufzeit gesetzt
- // Ihr Wert kann nur bei ihrer Deklaration, oder in einem Konstruktor
- // festgelegt werden
- readonly bool _hasCardsInSpokes = false; // readonly und private
-
- // Konstruktoren bestimmen was bei einer Instantiierung passiert.
- // Das ist ein Default-Konstruktor:
- public Bicycle()
- {
- // Member der Klasse können über das Keyword this erreicht werden
- this.Gear = 1;
- // oft ist das aber gar nicht nötig
- Cadence = 50;
- _speed = 5;
- Name = "Bonanzarad";
- Brand = BikeBrand.Kynast;
- BicyclesCreated++;
- }
-
- // Das ist ein spezifischer Konstruktor (d.h. er erwartet Argumente):
- public Bicycle(int startCadence, int startSpeed, int startGear,
- string name, bool hasCardsInSpokes, BikeBrand brand)
- : base() // ruft zuerst den "base"-Konstruktor auf
- {
- Gear = startGear;
- Cadence = startCadence;
- _speed = startSpeed;
- Name = name;
- _hasCardsInSpokes = hasCardsInSpokes;
- Brand = brand;
- }
-
- // Konstruktoren können aneinandergehängt werden:
- public Bicycle(int startCadence, int startSpeed, BikeBrand brand) :
- this(startCadence, startSpeed, 0, "richtig große Räder", true, brand)
- {
- }
-
- // Syntax für Methoden:
- // <public/private/protected> <return type> <function name>(<args>)
-
- // Klassen können Getter und Setter für Werte definieren,
- // oder diese Werte direkt als Eigenschaft implementieren
- // (in C# der bevorzugte Weg)
-
- // Parameter von Methoden können Default-Werte haben.
- // "SpeedUp" kann man also auch ohne Parameter aufrufen:
- public void SpeedUp(int increment = 1)
- {
- _speed += increment;
- }
-
- public void SlowDown(int decrement = 1)
- {
- _speed -= decrement;
- }
-
- // Eigenschaften mit get/set
- // wenn es nur um den Zugriff auf Daten geht, ist eine Eigenschaft zu
- // empfehlen. Diese können Getter und Setter haben, oder auch nur
- // einen Getter bzw. einen Setter
- private bool _hasTassles; // private Variable
- public bool HasTassles // öffentliches Interface
- {
- get { return _hasTassles; }
- set { _hasTassles = value; }
- }
-
- // Das kann man auch kürzer schreiben:
- // Dieser Syntax erzeugt automatisch einen hinterlegten Wert,
- // (entsprechend `private bool _isBroken`) der gesetzt
- // bzw. zurückgegeben wird:
- public bool IsBroken { get; private set; }
- public int FrameSize
- {
- get;
- // für Getter und Setter kann der Zugriff auch einzeln
- // beschränkt werden, FrameSize kann also nur von innerhalb
- // der Klasse "Bicycle" gesetzt werden
- private set;
- }
-
- // Diese Methode gibt eine Reihe an Informationen über das Objekt aus:
- public virtual string ToString()
- {
- return "Gang: " + Gear +
- " Kadenz: " + Cadence +
- " Geschwindigkeit: " + _speed +
- " Name: " + Name +
- " Hipster-Karten zwischen den Speichen: " + (_hasCardsInSpokes ? "Na klar!" : "Bloß nicht!") +
- "\n------------------------------\n"
- ;
- }
-
- // Auch Methoden können als static gekennzeichnet werden, nützlich
- // beispielsweise für Helper-Methoden
- public static bool DidWeCreateEnoughBicyclesYet()
- {
- // In einer statischen Methode können wir natürlich auch nur
- // statische Member der Klasse referenzieren
- return BicyclesCreated > 9000;
- }
- // Wenn eine Klasse nur statische Member enthält, kann es eine gute Idee
- // sein die Klasse selbst als static zu kennzeichnen
-
- } // Ende der Klasse "Bicycle"
-
- // "PennyFarthing" ist eine Unterklasse von "Bicycle"
- class PennyFarthing : Bicycle
- {
- // (Hochräder - englisch Penny Farthing - sind diese antiken Fahrräder
- // mit riesigem Vorderrad. Sie haben keine Gangschaltung.)
-
- // hier wird einfach der Elternkonstruktor aufgerufen
- public PennyFarthing(int startCadence, int startSpeed) :
- base(startCadence, startSpeed, 0, "Hochrad", true, BikeBrand.EddyMerckx)
- {
- }
-
- protected override int Gear
- {
- get
- {
- return 0;
- }
- set
- {
- throw new ArgumentException("Ein Hochrad hat keine Gangschaltung, doh!");
- }
- }
-
- public override string ToString()
- {
- string result = "Hochrad ";
- result += base.ToString(); // ruft die "base"-Version der Methode auf
- return result;
- }
- }
-
- // Interfaces (auch Schnittstellen genant) definieren nur die Signaturen
- // ihrer Member, enthalten aber auf keinen Fall ihre Implementierung:
- interface IJumpable
- {
- // Alle Member eines Interfaces sind implizit public
- void Jump(int meters);
- }
-
- interface IBreakable
- {
- // Interfaces können Eigenschaften, Methoden und Events definieren
- bool Broken { get; }
- }
-
- // Eine Klasse kann nur von einer Klasse erben, kann aber eine beliebige
- // Anzahl von Interfaces implementieren
- class MountainBike : Bicycle, IJumpable, IBreakable
- {
- int damage = 0;
-
- public void Jump(int meters)
- {
- damage += meters;
- }
-
- public bool Broken
- {
- get
- {
- return damage > 100;
- }
- }
- }
-
- // Das hier stellt eine Datenbankverbindung für das LinqToSql-Beispiel her.
- // EntityFramework Code First ist großartig
- // (ähnlich zu Ruby's ActiveRecord, aber bidirektional)
- // http://msdn.microsoft.com/de-de/data/jj193542.aspx
- public class BikeRepository : DbSet
- {
- public BikeRepository()
- : base()
- {
- }
-
- public DbSet<Bicycle> Bikes { get; set; }
- }
-} // Ende des Namespaces
-```
-
-## In dieser Übersicht nicht enthalten sind die Themen:
-
- * Flags
- * Attributes
- * Statische Eigenschaften
- * Exceptions, Abstraction
- * ASP.NET (Web Forms/MVC/WebMatrix)
- * Winforms
- * Windows Presentation Foundation (WPF)
-
-## Zum Weiterlesen gibt es viele gute Anlaufpunkte:
-
- * [DotNetPerls](http://www.dotnetperls.com)
- * [C# in Depth](http://manning.com/skeet2)
- * [Programming C#](http://shop.oreilly.com/product/0636920024064.do)
- * [LINQ](http://shop.oreilly.com/product/9780596519254.do)
- * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx)
- * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials)
- * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/overview/exploring-webmatrix)
- * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials)
- * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208)
-
-[C# Coding Conventions](http://msdn.microsoft.com/de-de/library/vstudio/ff926074.aspx)
+---
+language: C#
+contributors:
+ - ["Irfan Charania", "https://github.com/irfancharania"]
+ - ["Max Yankov", "https://github.com/golergka"]
+ - ["Melvyn Laïly", "http://x2a.yt"]
+ - ["Shaun McCarthy", "http://www.shaunmccarthy.com"]
+translators:
+ - ["Frederik Ring", "https://github.com/m90"]
+filename: LearnCSharp-de.cs
+lang: de-de
+---
+C# ist eine elegante, typsichere und objektorientierte Sprache, mit der Entwickler eine Vielzahl sicherer und robuster Anwendungen erstellen können, die im .NET Framework ausgeführt werden.
+
+[Mehr über C# erfährst du hier.](http://msdn.microsoft.com/de-de/library/vstudio/z1zx9t92.aspx)
+
+```c#
+// Einzeilige Kommentare starten mit zwei Schrägstrichen: //
+/*
+Mehrzeile Kommentare wie in C Schrägstrich / Stern
+*/
+/// <summary>
+/// XML-Kommentare können zur automatisierten Dokumentation verwendet werden
+/// </summary>
+
+// Zu Beginn werden die in der Datei verwendeten Namespaces aufgeführt
+using System;
+using System.Collections.Generic;
+using System.Data.Entity;
+using System.Dynamic;
+using System.Linq;
+using System.Linq.Expressions;
+using System.Net;
+using System.Threading.Tasks;
+using System.IO;
+
+// definiert einen Namespace um Code in "packages" zu organisieren
+namespace Learning
+{
+ // Jede .cs-Datei sollte zumindest eine Klasse mit dem Namen der Datei
+ // enthalten. Das ist zwar nicht zwingend erforderlich, es anders zu
+ // handhaben führt aber unweigerlich ins Chaos (wirklich)!
+ public class LearnCSharp
+ {
+ // Zuerst erklärt dieses Tutorial die Syntax-Grundlagen,
+ // wenn du bereits Java oder C++ programmieren kannst:
+ // lies bei "Interessante Features" weiter!
+ public static void Syntax()
+ {
+ // Mit Console.WriteLine kannst du einfachen Text ausgeben:
+ Console.WriteLine("Hallo Welt");
+ Console.WriteLine(
+ "Integer: " + 10 +
+ " Double: " + 3.14 +
+ " Boolean: " + true);
+
+ // Console.Write erzeugt keinen Zeilenumbruch
+ Console.Write("Hallo ");
+ Console.Write("Welt");
+
+ ///////////////////////////////////////////////////
+ // Typen & Variablen
+ ///////////////////////////////////////////////////
+
+ // Deklariere eine Variable mit <Typ> <Name>
+
+ // Sbyte - Vorzeichenbehaftete 8-Bit Ganzzahl
+ // (-128 <= sbyte <= 127)
+ sbyte fooSbyte = 100;
+
+ // Byte - Vorzeichenlose 8-Bit Ganzzahl
+ // (0 <= byte <= 255)
+ byte fooByte = 100;
+
+ // Short - 16-Bit Ganzzahl
+ // Vorzeichenbehaftet - (-32,768 <= short <= 32,767)
+ // Vorzeichenlos - (0 <= ushort <= 65,535)
+ short fooShort = 10000;
+ ushort fooUshort = 10000;
+
+ // Integer - 32-bit Ganzzahl
+ int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647)
+ uint fooUint = 1; // (0 <= uint <= 4,294,967,295)
+
+ // Long - 64-bit Ganzzahl
+ long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
+ ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615)
+ // Ganze Zahlen werden standardmäßig - je nach Größe - als int oder
+ // uint behandelt. Ein nachgestelltes L markiert den Wert als long
+ // oder ulong.
+
+ // Double - Double-precision 64-bit IEEE 754 Fließkommazahl
+ double fooDouble = 123.4; // Genauigkeit: 15-16 Stellen
+
+ // Float - Single-precision 32-bit IEEE 754 Fließkommazahl
+ float fooFloat = 234.5f; // Genauigkeit: 7 Stellen
+ // Das nachgestellte f zeigt an dass es sich um einen Wert vom Typ
+ // float handelt
+
+ // Decimal - ein 128-Bit-Datentyp mit größerer Genauigkeit als
+ // andere Fließkommatypen, und somit bestens geeignet für
+ // die Berechnung von Geld- und Finanzwerten
+ decimal fooDecimal = 150.3m;
+
+ // Boolean - true & false
+ bool fooBoolean = true; // oder false
+
+ // Char - Ein einzelnes 16-Bit Unicode Zeichen
+ char fooChar = 'A';
+
+ // Strings - im Gegensatz zu allen vorhergehenden Basistypen, die
+ // alle Werttypen sind, ist String ein Referenztyp. Strings sind
+ // somit nullable, Werttypen sind dies nicht.
+ string fooString = "\"maskiere\" Anführungszeichen, und füge \n (Umbrüche) und \t (Tabs) hinzu";
+ Console.WriteLine(fooString);
+
+ // Jeder Buchstabe eines Strings kann über seinen Index
+ // referenziert werden:
+ char charFromString = fooString[1]; // => 'e'
+ // Strings sind unveränderlich:
+ // `fooString[1] = 'X';` funktioniert nicht
+
+ // Ein Vergleich zweier Strings, unter Berücksichtigung der
+ // aktuellen, sprachspezifischen Gegebenheiten (also z.B. a,ä,b,c
+ // in deutschsprachigen Umgebungen), und ohne Beachtung von
+ // Groß- und Kleinschreibung:
+ string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase);
+
+ // Formatierung, genau wie "sprintf"
+ string fooFs = string.Format("Mikrofon Check, {0} {1}, {0} {1:0.0}", 1, 2);
+
+ // Datumsangaben und Formatierung
+ DateTime fooDate = DateTime.Now;
+ Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy"));
+
+ // Durch ein vorangestelltes @ lässt sich ein mehrzeiliger String
+ // schreiben. Um " zu maskieren benutzt man ""
+ string bazString = @"Hier geht es
+zur nächsten Zeile, ""Wahnsinn!"", die Massen waren kaum zu bändigen";
+
+ // Die Keywords const oder readonly kennzeichnen eine
+ // unveränderliche Variable/Konstante. Die Werte von Konstanten
+ // werden übrigens bereits zur Compile-Zeit berechnet.
+ const int HOURS_I_WORK_PER_WEEK = 9001;
+
+ ///////////////////////////////////////////////////
+ // Datenstrukturen
+ ///////////////////////////////////////////////////
+
+ // Arrays - Index beginnt bei Null
+ // Die Größe des Arrays wird bei der Deklaration festgelegt.
+ // Die syntaktische Struktur um ein neues Array zu erzeugen sieht
+ // folgendermaßen aus:
+ // <datatype>[] <varname> = new <datatype>[<array size>];
+ int[] intArray = new int[10];
+
+ // Arrays können auch über ein Array-Literal deklariert werden:
+ int[] y = { 9000, 1000, 1337 };
+
+ // Indizierung eines Arrays - Zugriff auf ein bestimmtes Element
+ Console.WriteLine("intArray @ 0: " + intArray[0]);
+ // Arrays sind veränderbar
+ intArray[1] = 1;
+
+ // Listen
+ // Durch ihre größere Flexibilität kommen Listen in C# weit
+ // häufiger zum Einsatz als Arrays. Eine Liste wird so deklariert:
+ // List<datatype> <varname> = new List<datatype>();
+ List<int> intList = new List<int>();
+ List<string> stringList = new List<string>();
+ List<int> z = new List<int> { 9000, 1000, 1337 };
+ // Die <> kennzeichnen "Generics", mehr dazu unter "Coole Sachen"
+
+ // Listen haben keinen Default-Wert.
+ // Bevor auf einen Index zugegriffen werden kann, muss dieser
+ // auch gesetzt worden sein:
+ intList.Add(1);
+ Console.WriteLine("intList @ 0: " + intList[0]);
+
+ // Andere interessante Datenstrukturen sind:
+ // Stack/Queue
+ // Dictionary (entspricht einer Hash Map)
+ // HashSet
+ // Read-only Collections
+ // Tuple (.Net 4+)
+
+ ///////////////////////////////////////
+ // Operatoren
+ ///////////////////////////////////////
+ Console.WriteLine("\n->Operatoren");
+
+ // kurze Schreibweise um mehrere Deklarationen zusammenzufassen:
+ // (Benutzung vom C# Styleguide aber ausdrücklich abgeraten!)
+ int i1 = 1, i2 = 2;
+
+ // Arithmetik funktioniert wie erwartet:
+ Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3
+
+ // Modulo
+ Console.WriteLine("11%3 = " + (11 % 3)); // => 2
+
+ // Vergleiche
+ Console.WriteLine("3 == 2? " + (3 == 2)); // => false
+ Console.WriteLine("3 != 2? " + (3 != 2)); // => true
+ Console.WriteLine("3 > 2? " + (3 > 2)); // => true
+ Console.WriteLine("3 < 2? " + (3 < 2)); // => false
+ Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true
+ Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true
+
+ // Bitweise Operatoren
+ /*
+ ~ Unäres bitweises NICHT
+ << Verschieben nach links
+ >> Verschieben nach rechts
+ & Bitweises UND
+ ^ Bitweises exklusives ODER
+ | Bitweises inklusives ODER
+ */
+
+ // Inkremente
+ int i = 0;
+ Console.WriteLine("\n->Inkrement / Dekrement");
+ Console.WriteLine(i++); //i = 1. Post-Inkrement
+ Console.WriteLine(++i); //i = 2. Pre-Inkrement
+ Console.WriteLine(i--); //i = 1. Post-Dekrement
+ Console.WriteLine(--i); //i = 0. Pre-Dekrement
+
+ ///////////////////////////////////////
+ // Kontrollstrukturen
+ ///////////////////////////////////////
+ Console.WriteLine("\n->Kontrollstrukturen");
+
+ // If-Statements funktionieren wie in C
+ int j = 10;
+ if (j == 10)
+ {
+ Console.WriteLine("Ich werde ausgegeben");
+ }
+ else if (j > 10)
+ {
+ Console.WriteLine("Ich nicht");
+ }
+ else
+ {
+ Console.WriteLine("Ich leider auch nicht");
+ }
+
+ // Ternärer Operator
+ // Anstatt eines einfachen if/else lässt sich auch folgendes schreiben:
+ // <condition> ? <true> : <false>
+ int zumVergleich = 17;
+ string isTrue = zumVergleich == 17 ? "Ja" : "Nein";
+
+ // while-Schleife
+ int fooWhile = 0;
+ while (fooWhile < 100)
+ {
+ // Wird 100mal wiederholt, fooWhile 0->99
+ fooWhile++;
+ }
+
+ // do-while-Schleife
+ int fooDoWhile = 0;
+ do
+ {
+ // Wird 100mal wiederholt, fooDoWhile 0->99
+ fooDoWhile++;
+ } while (fooDoWhile < 100);
+
+ //for-Schleifen => for(<start_statement>; <conditional>; <step>)
+ for (int fooFor = 0; fooFor < 10; fooFor++)
+ {
+ // Wird 10mal wiederholt, fooFor 0->9
+ }
+
+ // foreach-Schleife
+ // Die normale Syntax für eine foreach-Schleife lautet:
+ // foreach(<iteratorType> <iteratorName> in <enumerable>)
+ // foreach kann mit jedem Objekt verwendet werden das IEnumerable
+ // oder IEnumerable<T> implementiert. Alle Auflistungs-Typen
+ // (Array, List, Dictionary...) im .NET Framework implementieren
+ // eines dieser beiden Interfaces.
+
+ foreach (char character in "Hallo Welt".ToCharArray())
+ {
+ // Ein Durchgang für jedes Zeichen im String
+ }
+ // (ToCharArray() könnte man hier übrigens auch weglassen,
+ // da String IEnumerable bereits implementiert)
+
+ // Switch Struktur
+ // Ein Switch funktioniert mit byte, short, char und int Datentypen.
+ // Auch Aufzählungstypen können verwendet werden, genau wie
+ // die Klasse String, und ein paar Sonderklassen, die Wrapper für
+ // Primitives sind: Character, Byte, Short und Integer
+ int month = 3;
+ string monthString;
+ switch (month)
+ {
+ case 1:
+ monthString = "Januar";
+ break;
+ case 2:
+ monthString = "Februar";
+ break;
+ case 3:
+ monthString = "März";
+ break;
+ // Man kann für mehrere Fälle auch das selbe Verhalten
+ // definieren. Jeder Block muss aber mit einem break-Statement
+ // abgeschlossen werden. Einzelne Fälle können über
+ // `goto case x` erreicht werden
+ case 6:
+ case 7:
+ case 8:
+ monthString = "Sommer!!";
+ break;
+ default:
+ monthString = "Irgendein anderer Monat";
+ break;
+ }
+
+ ///////////////////////////////////////
+ // Umwandlung von Datentypen und Typecasting
+ ///////////////////////////////////////
+
+ // Umwandlung
+
+ // von String nach Integer
+ // bei einem Fehler wirft diese Code eine Exception
+ int.Parse("123"); //gibt die Ganzzahl 123 zurück
+
+ // TryParse gibt bei einem Fehler den Default-Wert zurück
+ // (im Fall von int: 0)
+ int tryInt;
+ if (int.TryParse("123", out tryInt)) // gibt true oder false zurück
+ {
+ Console.WriteLine(tryInt); // 123
+ }
+
+ // von Integer nach String
+ // Die Klasse Convert stellt Methoden zur Konvertierung von
+ // unterschiedlichsten Daten zur Verfügung:
+ Convert.ToString(123); // "123"
+ // oder
+ tryInt.ToString(); // "123"
+ }
+
+ ///////////////////////////////////////
+ // Klassen
+ ///////////////////////////////////////
+ public static void Classes()
+ {
+
+ // Benutze das new-Keyword um eine Instanz einer Klasse zu erzeugen
+ Bicycle trek = new Bicycle();
+
+ // So werden Methoden der Instanz aufgerufen
+ trek.SpeedUp(3); // Es empfiehlt sich immer Getter und Setter zu benutzen
+ trek.Cadence = 100;
+
+ // ToString ist eine Konvention über die man üblicherweiser
+ // Informationen über eine Instanz erhält
+ Console.WriteLine("Infos zu trek: " + trek.ToString());
+
+ // Wir instantiieren ein neues Hochrad
+ PennyFarthing funbike = new PennyFarthing(1, 10);
+ Console.WriteLine("Infos zu funbike: " + funbike.ToString());
+
+ Console.Read();
+ } // Ende der Methode main
+
+ // Main als Konsolenstartpunkt
+ // Eine Konsolenanwendung muss eine Methode Main als Startpunkt besitzen
+ public static void Main(string[] args)
+ {
+ OtherInterestingFeatures();
+ }
+
+ ///////////////////////////////////////
+ // Interessante Features
+ ///////////////////////////////////////
+
+ // Methodensignaturen
+
+ public // Sichtbarkeit
+ static // Erlaubt einen Zugriff auf der Klasse (nicht auf einer Instanz)
+ int // Typ des Rückgabewerts,
+ MethodSignatures(
+ // Erstes Argument, erwartet int
+ int maxCount,
+ // setzt sich selbst auf 0 wenn kein anderer Wert übergeben wird
+ int count = 0,
+ int another = 3,
+ // enthält alle weiteren der Methode übergebenen Parameter (quasi Splats)
+ params string[] otherParams
+ )
+ {
+ return -1;
+ }
+
+ // Methoden können überladen werden, solange sie eindeutige
+ // Signaturen haben
+ public static void MethodSignatures(string maxCount)
+ {
+ }
+
+ // Generische Typen
+ // Die Typen für TKey und TValue werden erst beim Aufruf der Methode
+ // festgelegt. Diese Methode emuliert z.B. SetDefault aus Python:
+ public static TValue SetDefault<TKey, TValue>(
+ IDictionary<TKey, TValue> dictionary,
+ TKey key,
+ TValue defaultItem)
+ {
+ TValue result;
+ if (!dictionary.TryGetValue(key, out result))
+ {
+ return dictionary[key] = defaultItem;
+ }
+ return result;
+ }
+
+ // Möglichen Typen lassen sich auch über ihr Interface beschränken:
+ public static void IterateAndPrint<T>(T toPrint) where T: IEnumerable<int>
+ {
+ // Da T ein IEnumerable ist können wir foreach benutzen
+ foreach (var item in toPrint)
+ {
+ // Item ist ein int
+ Console.WriteLine(item.ToString());
+ }
+ }
+
+ public static void OtherInterestingFeatures()
+ {
+ // Optionale Parameter
+ MethodSignatures(3, 1, 3, "Ein paar", "extra", "Strings");
+ // setzt explizit einen bestimmten Parameter, andere werden übersprungen
+ MethodSignatures(3, another: 3);
+
+ // Erweiterungsmethoden
+ int i = 3;
+ i.Print(); // Weiter unten definiert
+
+ // Nullables - perfekt für die Interaktion mit
+ // Datenbanken / Rückgabewerten
+ // Jeder Wert (d.h. keine Klassen) kann durch das Nachstellen eines ?
+ // nullable gemacht werden: <type>? <varname> = <value>
+ int? nullable = null; // Die explizite Langform wäre Nullable<int>
+ Console.WriteLine("Mein Nullable: " + nullable);
+ bool hasValue = nullable.HasValue; // true wenn nicht null
+
+ // ?? ist "syntaktischer Zucker" um einen Defaultwert für den Fall
+ // dass die Variable null ist festzulegen.
+ int notNullable = nullable ?? 0; // 0
+
+ // Implizit typisierte Variablen
+ // Man kann auch den Typ einer Variable auch vom Compiler
+ // bestimmen lassen:
+ var magic = "magic ist zur Compile-Zeit ein String, folglich geht keine Typsicherheit verloren";
+ magic = 9; // funktioniert nicht da magic vom Typ String ist
+
+ // Generics
+ var phonebook = new Dictionary<string, string>() {
+ {"Resi", "08822 / 43 67"} // Fügt einen Eintrag zum Telefonbuch hinzu
+ };
+
+ // Hier könnte man auch unser generisches SetDefault von
+ // weiter oben benutzen:
+ Console.WriteLine(SetDefault<string,string>(phonebook, "Xaver", "kein Telefon")); // kein Telefon
+ // TKey und TValue müssen nicht zwingend angegeben werden, da sie
+ // auch implizit vom Compiler ermittelt werden können
+ Console.WriteLine(SetDefault(phonebook, "Resi", "kein Telefon")); // 08822 / 43 67
+
+ // Lambdas - konzise Syntax für Inline-Funktionen
+ Func<int, int> square = (x) => x * x; // Das letzte Element vom Typ T ist der Rückgabewert
+ Console.WriteLine(square(3)); // 9
+
+ // Disposables - einfaches Management von nicht verwalteten Ressourcen
+ // So gut wie alle Objekte die auf nicht verwaltete Ressourcen
+ // (Dateien, Geräte, ...) zugreifen, implementieren das Interface
+ // IDisposable. Das using Statement stellt sicher dass die vom
+ // IDisposable benutzten Ressourcen nach der Benutzung wieder
+ // freigegeben werden:
+ using (StreamWriter writer = new StreamWriter("log.txt"))
+ {
+ writer.WriteLine("Alles bestens!");
+ // Am Ende des Codeblocks werden die Ressourcen wieder
+ // freigegeben - auch im Falle einer Exception
+ }
+
+ // Parallel Klasse
+ // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
+ var websites = new string[] {
+ "http://www.google.com", "http://www.reddit.com",
+ "http://www.shaunmccarthy.com"
+ };
+ var responses = new Dictionary<string, string>();
+
+ // Für jeden Request wird ein neuer Thread erzeugt, der nächste
+ // Schritt wird erst nach Beendigung aller Tasks ausgeführt
+ Parallel.ForEach(websites,
+ // maximal 3 Threads gleichzeitig
+ new ParallelOptions() {MaxDegreeOfParallelism = 3},
+ website =>
+ {
+ // Hier folgt eine langwierige, asynchrone Operation
+ using (var r = WebRequest.Create(new Uri(website)).GetResponse())
+ {
+ responses[website] = r.ContentType;
+ }
+ });
+
+ // Dieser Code wird erst nach Beendigung aller Requests ausgeführt
+ foreach (var key in responses.Keys)
+ {
+ Console.WriteLine("{0}:{1}", key, responses[key]);
+ }
+
+ // Dynamische Objekte (gut um mit anderen Sprachen zu arbeiten)
+ dynamic student = new ExpandoObject();
+ // hier muss keine Typ angegeben werden
+ student.FirstName = "Christian";
+
+ // Einem solchen Objekt kann man sogar Methoden zuordnen.
+ // Das Beispiel gibt einen String zurück und erwartet einen String
+ student.Introduce = new Func<string, string>(
+ (introduceTo) => string.Format("Hallo {0}, das ist {1}", student.FirstName, introduceTo));
+ Console.WriteLine(student.Introduce("Bettina"));
+
+ // IQueryable<T> - So gut wie alle Aufzählungstypen implementieren
+ // dieses Interface, welches eine Vielzahl von funktionalen Methoden
+ // wie Map / Filter / Reduce zur Verfügung stellt:
+ var bikes = new List<Bicycle>();
+ // sortiert die Liste
+ bikes.Sort();
+ // sortiert nach Anzahl Räder
+ bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels));
+ var result = bikes
+ // diese Filter können auch aneinandergehängt werden
+ .Where(b => b.Wheels > 3) // (gibt ein IQueryable des vorherigen Typs zurück)
+ .Where(b => b.IsBroken && b.HasTassles)
+ // diese Zuordnung gibt ein IQueryable<String> zurück
+ .Select(b => b.ToString());
+
+ // "Reduce" - addiert alle Räder der Aufzählung zu einem Wert
+ var sum = bikes.Sum(b => b.Wheels);
+
+ // So erzeugt man ein implizit typisiertes Objekt, basierend auf
+ // den Parametern der Elemente:
+ var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles });
+ // Auch wenn wir es hier nicht demonstrieren können:
+ // In einer IDE wie VisualStudio kriegen wir hier sogar TypeAhead,
+ // da der Compiler in der Lage ist, die passenden Typen zu erkennen.
+ foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome))
+ {
+ Console.WriteLine(bikeSummary.Name);
+ }
+
+ // AsParallel-Methode
+ // Jetzt kommen die Schmankerl! Die AsParallel-Methode kombiniert
+ // LINQ und parallele Operationen:
+ var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name);
+ // Diese Berechnung passiert parallel! Benötigte Threads werden
+ // automatisch erzeugt, und die Rechenlast unter ihnen aufgeteilt.
+ // Ein Traum für die Verarbeitung von großen Datenmengen
+ // auf mehreren Cores!
+
+ // LINQ - bildet einen Datenspeicher auf IQueryable<T> Objekte ab
+ // LinqToSql beispielsweise speichert und liest aus einer
+ // SQL-Datenbank, LinqToXml aus einem XML-Dokument.
+ // LINQ-Operationen werden "lazy" ausgeführt.
+ var db = new BikeRepository();
+
+ // Die verzögerte Ausführung ist optimal für Datenbankabfragen
+ var filter = db.Bikes.Where(b => b.HasTassles); // noch keine Abfrage
+ // Es können noch mehr Filter hinzugefügt werden (auch mit
+ // Bedingungen) - ideal für z.B. "erweiterte Suchen"
+ if (42 > 6)
+ {
+ filter = filter.Where(b => b.IsBroken); // immer noch keine Abfrage
+ }
+
+ var query = filter
+ .OrderBy(b => b.Wheels)
+ .ThenBy(b => b.Name)
+ .Select(b => b.Name); // auch hier: immer noch keine Abfrage
+
+ // Erst hier wird die Datenbankabfrage wirklich ausgeführt,
+ // limitiert auf die Elemente die der foreach-Loop verwendet
+ foreach (string bike in query)
+ {
+ Console.WriteLine(result);
+ }
+
+ }
+
+ } // Ende der Klasse LearnCSharp
+
+ // Eine .cs-Datei kann auch mehrere Klassen enthalten
+
+ public static class Extensions
+ {
+ // Erweiterungsmethoden
+ public static void Print(this object obj)
+ {
+ Console.WriteLine(obj.ToString());
+ }
+ }
+
+ // Syntax zur Deklaration einer Klasse:
+ // <public/private/protected/internal> class <class name>{
+ // // Datenfelder, Konstruktoren und Methoden leben alle
+ // // innerhalb dieser Deklaration
+ // }
+
+ public class Bicycle
+ {
+ // Felder/Variablen der Klasse "Bicycle"
+ // Das Keyword public macht das Member von überall zugänglich
+ public int Cadence
+ {
+ get // get definiert eine Methode um die Eigenschaft abzurufen
+ {
+ return _cadence;
+ }
+ set // set definiert eine Methode um die Eigenschaft zu setzen
+ {
+ _cadence = value; // value ist der dem Setter übergebene Wert
+ }
+ }
+ private int _cadence;
+
+ // Das Keyword protected macht das Member nur für die Klasse selbst
+ // und ihre Subklassen zugänglich
+ protected virtual int Gear
+ {
+ get; // erzeugt eine Eigenschaft für die kein "Zwischenwert" benötigt wird
+ set;
+ }
+
+ // Das Keyword internal macht das Member innerhalb der Assembly zugänglich
+ internal int Wheels
+ {
+ get;
+ private set; // get/set kann auch über Keywords modifiziert werden
+ }
+
+ int _speed; // Member ohne vorangestellte Keywords sind standardmäßig
+ // private, sie sind nur innerhalb der Klasse zugänglich.
+ // Man kann aber natürlich auch das Keyword private benutzen.
+ private string Name { get; set; }
+
+ // Ein Enum ist ein klar definierter Satz an benannten Konstanten.
+ // Eigentlich ordnet es diese Konstanten nur bestimmten Werten zu
+ // (einer int-Zahl, solange nicht anders angegeben). Mögliche Typen für
+ // die Werte eines Enums sind byte, sbyte, short, ushort, int, uint,
+ // long, oder ulong. Alle Werte in einem Enum sind eindeutig.
+ public enum BikeBrand
+ {
+ Colnago,
+ EddyMerckx,
+ Bianchi = 42, // so kann man den Wert explizit setzen
+ Kynast // 43
+ }
+ // Nachdem dieser Typ in der Klasse "Bicycle" definiert ist,
+ // sollte Code ausserhalb der Klasse den Typen als Bicycle.Brand referenzieren
+
+ // Nachdem das Enum deklariert ist, können wir den Typen verwenden:
+ public BikeBrand Brand;
+
+ // Als static gekennzeichnete Member gehören dem Typ selbst,
+ // nicht seinen Instanzen. Man kann sie also ohne Referenz zu einem
+ // Objekt benutzen
+ // Console.WriteLine("Schon " + Bicycle.BicyclesCreated + " Fahrräder, nur für dieses Tutorial!");
+ static public int BicyclesCreated = 0;
+
+ // readonly-Werte werden zur Laufzeit gesetzt
+ // Ihr Wert kann nur bei ihrer Deklaration, oder in einem Konstruktor
+ // festgelegt werden
+ readonly bool _hasCardsInSpokes = false; // readonly und private
+
+ // Konstruktoren bestimmen was bei einer Instantiierung passiert.
+ // Das ist ein Default-Konstruktor:
+ public Bicycle()
+ {
+ // Member der Klasse können über das Keyword this erreicht werden
+ this.Gear = 1;
+ // oft ist das aber gar nicht nötig
+ Cadence = 50;
+ _speed = 5;
+ Name = "Bonanzarad";
+ Brand = BikeBrand.Kynast;
+ BicyclesCreated++;
+ }
+
+ // Das ist ein spezifischer Konstruktor (d.h. er erwartet Argumente):
+ public Bicycle(int startCadence, int startSpeed, int startGear,
+ string name, bool hasCardsInSpokes, BikeBrand brand)
+ : base() // ruft zuerst den "base"-Konstruktor auf
+ {
+ Gear = startGear;
+ Cadence = startCadence;
+ _speed = startSpeed;
+ Name = name;
+ _hasCardsInSpokes = hasCardsInSpokes;
+ Brand = brand;
+ }
+
+ // Konstruktoren können aneinandergehängt werden:
+ public Bicycle(int startCadence, int startSpeed, BikeBrand brand) :
+ this(startCadence, startSpeed, 0, "richtig große Räder", true, brand)
+ {
+ }
+
+ // Syntax für Methoden:
+ // <public/private/protected> <return type> <function name>(<args>)
+
+ // Klassen können Getter und Setter für Werte definieren,
+ // oder diese Werte direkt als Eigenschaft implementieren
+ // (in C# der bevorzugte Weg)
+
+ // Parameter von Methoden können Default-Werte haben.
+ // "SpeedUp" kann man also auch ohne Parameter aufrufen:
+ public void SpeedUp(int increment = 1)
+ {
+ _speed += increment;
+ }
+
+ public void SlowDown(int decrement = 1)
+ {
+ _speed -= decrement;
+ }
+
+ // Eigenschaften mit get/set
+ // wenn es nur um den Zugriff auf Daten geht, ist eine Eigenschaft zu
+ // empfehlen. Diese können Getter und Setter haben, oder auch nur
+ // einen Getter bzw. einen Setter
+ private bool _hasTassles; // private Variable
+ public bool HasTassles // öffentliches Interface
+ {
+ get { return _hasTassles; }
+ set { _hasTassles = value; }
+ }
+
+ // Das kann man auch kürzer schreiben:
+ // Dieser Syntax erzeugt automatisch einen hinterlegten Wert,
+ // (entsprechend `private bool _isBroken`) der gesetzt
+ // bzw. zurückgegeben wird:
+ public bool IsBroken { get; private set; }
+ public int FrameSize
+ {
+ get;
+ // für Getter und Setter kann der Zugriff auch einzeln
+ // beschränkt werden, FrameSize kann also nur von innerhalb
+ // der Klasse "Bicycle" gesetzt werden
+ private set;
+ }
+
+ // Diese Methode gibt eine Reihe an Informationen über das Objekt aus:
+ public virtual string ToString()
+ {
+ return "Gang: " + Gear +
+ " Kadenz: " + Cadence +
+ " Geschwindigkeit: " + _speed +
+ " Name: " + Name +
+ " Hipster-Karten zwischen den Speichen: " + (_hasCardsInSpokes ? "Na klar!" : "Bloß nicht!") +
+ "\n------------------------------\n"
+ ;
+ }
+
+ // Auch Methoden können als static gekennzeichnet werden, nützlich
+ // beispielsweise für Helper-Methoden
+ public static bool DidWeCreateEnoughBicyclesYet()
+ {
+ // In einer statischen Methode können wir natürlich auch nur
+ // statische Member der Klasse referenzieren
+ return BicyclesCreated > 9000;
+ }
+ // Wenn eine Klasse nur statische Member enthält, kann es eine gute Idee
+ // sein die Klasse selbst als static zu kennzeichnen
+
+ } // Ende der Klasse "Bicycle"
+
+ // "PennyFarthing" ist eine Unterklasse von "Bicycle"
+ class PennyFarthing : Bicycle
+ {
+ // (Hochräder - englisch Penny Farthing - sind diese antiken Fahrräder
+ // mit riesigem Vorderrad. Sie haben keine Gangschaltung.)
+
+ // hier wird einfach der Elternkonstruktor aufgerufen
+ public PennyFarthing(int startCadence, int startSpeed) :
+ base(startCadence, startSpeed, 0, "Hochrad", true, BikeBrand.EddyMerckx)
+ {
+ }
+
+ protected override int Gear
+ {
+ get
+ {
+ return 0;
+ }
+ set
+ {
+ throw new ArgumentException("Ein Hochrad hat keine Gangschaltung, doh!");
+ }
+ }
+
+ public override string ToString()
+ {
+ string result = "Hochrad ";
+ result += base.ToString(); // ruft die "base"-Version der Methode auf
+ return result;
+ }
+ }
+
+ // Interfaces (auch Schnittstellen genant) definieren nur die Signaturen
+ // ihrer Member, enthalten aber auf keinen Fall ihre Implementierung:
+ interface IJumpable
+ {
+ // Alle Member eines Interfaces sind implizit public
+ void Jump(int meters);
+ }
+
+ interface IBreakable
+ {
+ // Interfaces können Eigenschaften, Methoden und Events definieren
+ bool Broken { get; }
+ }
+
+ // Eine Klasse kann nur von einer Klasse erben, kann aber eine beliebige
+ // Anzahl von Interfaces implementieren
+ class MountainBike : Bicycle, IJumpable, IBreakable
+ {
+ int damage = 0;
+
+ public void Jump(int meters)
+ {
+ damage += meters;
+ }
+
+ public bool Broken
+ {
+ get
+ {
+ return damage > 100;
+ }
+ }
+ }
+
+ // Das hier stellt eine Datenbankverbindung für das LinqToSql-Beispiel her.
+ // EntityFramework Code First ist großartig
+ // (ähnlich zu Ruby's ActiveRecord, aber bidirektional)
+ // http://msdn.microsoft.com/de-de/data/jj193542.aspx
+ public class BikeRepository : DbSet
+ {
+ public BikeRepository()
+ : base()
+ {
+ }
+
+ public DbSet<Bicycle> Bikes { get; set; }
+ }
+} // Ende des Namespaces
+```
+
+## In dieser Übersicht nicht enthalten sind die Themen:
+
+ * Flags
+ * Attributes
+ * Statische Eigenschaften
+ * Exceptions, Abstraction
+ * ASP.NET (Web Forms/MVC/WebMatrix)
+ * Winforms
+ * Windows Presentation Foundation (WPF)
+
+## Zum Weiterlesen gibt es viele gute Anlaufpunkte:
+
+ * [DotNetPerls](http://www.dotnetperls.com)
+ * [C# in Depth](http://manning.com/skeet2)
+ * [Programming C#](http://shop.oreilly.com/product/0636920024064.do)
+ * [LINQ](http://shop.oreilly.com/product/9780596519254.do)
+ * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx)
+ * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials)
+ * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/overview/exploring-webmatrix)
+ * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials)
+ * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208)
+
+[C# Coding Conventions](http://msdn.microsoft.com/de-de/library/vstudio/ff926074.aspx)
diff --git a/de-de/dynamic-programming-de.html.markdown b/de-de/dynamic-programming-de.html.markdown
index 58568b3b..9cf461d0 100644
--- a/de-de/dynamic-programming-de.html.markdown
+++ b/de-de/dynamic-programming-de.html.markdown
@@ -56,6 +56,7 @@ wie `largest_sequences_so_far` und dessen Index würde eine Menge Zeit sparen.
Ein ähnliches Konzept könnte auch bei der Suche nach dem längsten Weg
in gerichteten azyklischen Graphen angewandt werden.
+
```python
for i=0 to n-1
LS[i]=1
diff --git a/de-de/elixir-de.html.markdown b/de-de/elixir-de.html.markdown
index 254cca51..4acb8e23 100644
--- a/de-de/elixir-de.html.markdown
+++ b/de-de/elixir-de.html.markdown
@@ -1,423 +1,423 @@
----
-language: elixir
-contributors:
- - ["Joao Marques", "http://github.com/mrshankly"]
-translators:
- - ["Gregor Große-Bölting", "http://www.ideen-und-soehne.de"]
-filename: learnelixir-de.ex
-lang: de-de
----
-
-Elixir ist eine moderne, funktionale Sprache für die Erlang VM. Sie ist voll
-kompatibel mit Erlang, verfügt aber über eine freundlichere Syntax und bringt
-viele Features mit.
-
-```ruby
-
-# Einzeilige Kommentare werden mit der Raute gesetzt.
-
-# Es gibt keine mehrzeiligen Kommentare;
-# es ist aber problemlos möglich mehrere einzeilige Kommentare hintereinander
-# zu setzen (so wie hier).
-
-# Mit 'iex' ruft man die Elixir-Shell auf.
-# Zum kompilieren von Modulen dient der Befehl 'elixirc'.
-
-# Beide Befehle sollten als Umgebungsvariable gesetzt sein, wenn Elixir korrekt
-# installiert wurde.
-
-## ---------------------------
-## -- Basistypen
-## ---------------------------
-
-# Es gibt Nummern:
-3 # Integer
-0x1F # Integer
-3.0 # Float
-
-# Für bessere Lesbarkeit des Codes können Unterstriche "_" als Trennzeichen verwendet werden
-1_000_000 == 1000000 # Integer
-1_000.567 == 1000.567 # Float
-
-# Atome, das sind Literale, sind Konstanten mit Namen. Sie starten mit einem
-# ':'.
-:hello # Atom
-
-# Außerdem gibt es Tupel, deren Werte im Arbeitsspeicher vorgehalten werden.
-{1,2,3} # Tupel
-
-# Die Werte innerhalb eines Tupels können mit der 'elem'-Funktion ausgelesen
-# werden:
-elem({1, 2, 3}, 0) # => 1
-
-# Listen sind als verkettete Listen implementiert.
-[1, 2, 3] # list
-
-# Auf Kopf und Rest einer Liste kann wie folgt zugegriffen werden:
-[ kopf | rest ] = [1,2,3]
-kopf # => 1
-rest # => [2, 3]
-
-# In Elixir, wie auch in Erlang, kennzeichnet '=' ein 'pattern matching'
-# (Musterabgleich) und keine Zuweisung.
-# Das heißt, dass die linke Seite auf die rechte Seite 'abgeglichen' wird.
-# Auf diese Weise kann im Beispiel oben auf Kopf und Rest der Liste zugegriffen
-# werden.
-
-# Ein Musterabgleich wird einen Fehler werfen, wenn die beiden Seiten nicht
-# zusammenpassen.
-# Im folgenden Beispiel haben die Tupel eine unterschiedliche Anzahl an
-# Elementen:
-{a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2}
-
-# Es gibt außerdem 'binaries',
-<<1,2,3>> # binary.
-
-# Strings und 'char lists'
-"hello" # String
-'hello' # Char-Liste
-
-# ... und mehrzeilige Strings
-"""
-Ich bin ein
-mehrzeiliger String.
-"""
-#=> "Ich bin ein\nmehrzeiliger String.\n"
-
-# Alles Strings werden in UTF-8 enkodiert:
-"héllò" #=> "héllò"
-
-# Eigentlich sind Strings in Wahrheit nur binaries und 'char lists' einfach
-# Listen.
-<<?a, ?b, ?c>> #=> "abc"
-[?a, ?b, ?c] #=> 'abc'
-
-# In Elixir gibt `?a` den ASCII-Integer für den Buchstaben zurück.
-?a #=> 97
-
-# Um Listen zu verbinden gibt es den Operator '++', für binaries nutzt man '<>'
-[1,2,3] ++ [4,5] #=> [1,2,3,4,5]
-'hello ' ++ 'world' #=> 'hello world'
-
-<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>>
-"hello " <> "world" #=> "hello world"
-
-## ---------------------------
-## -- Operatoren
-## ---------------------------
-
-# Einfache Arithmetik
-1 + 1 #=> 2
-10 - 5 #=> 5
-5 * 2 #=> 10
-10 / 2 #=> 5.0
-
-# In Elixir gibt der Operator '/' immer einen Float-Wert zurück.
-
-# Für Division mit ganzzahligen Ergebnis gibt es 'div'
-div(10, 2) #=> 5
-
-# Um den Rest der ganzzahligen Division zu erhalten gibt es 'rem'
-rem(10, 3) #=> 1
-
-# Natürlich gibt es auch Operatoren für Booleans: 'or', 'and' und 'not'. Diese
-# Operatoren erwarten einen Boolean als erstes Argument.
-true and true #=> true
-false or true #=> true
-# 1 and true #=> ** (ArgumentError) argument error
-
-# Elixir bietet auch '||', '&&' und '!', die Argumente jedweden Typs
-# akzeptieren. Alle Werte außer 'false' und 'nil' werden zu wahr evaluiert.
-1 || true #=> 1
-false && 1 #=> false
-nil && 20 #=> nil
-
-!true #=> false
-
-# Für Vergleiche gibt es die Operatoren `==`, `!=`, `===`, `!==`, `<=`, `>=`,
-# `<` und `>`
-1 == 1 #=> true
-1 != 1 #=> false
-1 < 2 #=> true
-
-# '===' und '!==' sind strikter beim Vergleich von Integern und Floats:
-1 == 1.0 #=> true
-1 === 1.0 #=> false
-
-# Es ist außerdem möglich zwei verschiedene Datentypen zu vergleichen:
-1 < :hello #=> true
-
-# Die gesamte Ordnung über die Datentypen ist wie folgt definiert:
-# number < atom < reference < functions < port < pid < tuple < list < bitstring
-
-# Um Joe Armstrong zu zitieren: "The actual order is not important, but that a
-# total ordering is well defined is important."
-
-## ---------------------------
-## -- Kontrollstrukturen
-## ---------------------------
-
-# Es gibt die `if`-Verzweigung
-if false do
- "Dies wird nie jemand sehen..."
-else
- "...aber dies!"
-end
-
-# ...und ebenso `unless`
-unless true do
- "Dies wird nie jemand sehen..."
-else
- "...aber dies!"
-end
-
-# Du erinnerst dich an 'pattern matching'? Viele Kontrollstrukturen in Elixir
-# arbeiten damit.
-
-# 'case' erlaubt es uns Werte mit vielerlei Mustern zu vergleichen.
-case {:one, :two} do
- {:four, :five} ->
- "Das wird nicht passen"
- {:one, x} ->
- "Das schon und außerdem wird es ':two' dem Wert 'x' zuweisen."
- _ ->
- "Dieser Fall greift immer."
-end
-
-# Es ist eine übliche Praxis '_' einen Wert zuzuweisen, sofern dieser Wert
-# nicht weiter verwendet wird.
-# Wenn wir uns zum Beispiel nur für den Kopf einer Liste interessieren:
-[kopf | _] = [1,2,3]
-kopf #=> 1
-
-# Für bessere Lesbarkeit können wir auch das Folgende machen:
-[kopf | _rest] = [:a, :b, :c]
-kopf #=> :a
-
-# Mit 'cond' können diverse Bedingungen zur selben Zeit überprüft werden. Man
-# benutzt 'cond' statt viele if-Verzweigungen zu verschachteln.
-cond do
- 1 + 1 == 3 ->
- "Ich werde nie aufgerufen."
- 2 * 5 == 12 ->
- "Ich auch nicht."
- 1 + 2 == 3 ->
- "Aber ich!"
-end
-
-# Es ist üblich eine letzte Bedingung einzufügen, die immer zu wahr evaluiert.
-cond do
- 1 + 1 == 3 ->
- "Ich werde nie aufgerufen."
- 2 * 5 == 12 ->
- "Ich auch nicht."
- true ->
- "Aber ich! (dies ist im Grunde ein 'else')"
-end
-
-# 'try/catch' wird verwendet um Werte zu fangen, die zuvor 'geworfen' wurden.
-# Das Konstrukt unterstützt außerdem eine 'after'-Klausel die aufgerufen wird,
-# egal ob zuvor ein Wert gefangen wurde.
-try do
- throw(:hello)
-catch
- nachricht -> "#{nachricht} gefangen."
-after
- IO.puts("Ich bin die 'after'-Klausel.")
-end
-#=> Ich bin die 'after'-Klausel.
-# ":hello gefangen"
-
-## ---------------------------
-## -- Module und Funktionen
-## ---------------------------
-
-# Anonyme Funktionen (man beachte den Punkt)
-square = fn(x) -> x * x end
-square.(5) #=> 25
-
-# Anonyme Funktionen unterstützen auch 'pattern' und 'guards'. Guards erlauben
-# es die Mustererkennung zu justieren und werden mit dem Schlüsselwort 'when'
-# eingeführt:
-f = fn
- x, y when x > 0 -> x + y
- x, y -> x * y
-end
-
-f.(1, 3) #=> 4
-f.(-1, 3) #=> -3
-
-# Elixir bietet zahlreiche eingebaute Funktionen. Diese sind im gleichen
-# Geltungsbereich ('scope') verfügbar.
-is_number(10) #=> true
-is_list("hello") #=> false
-elem({1,2,3}, 0) #=> 1
-
-# Mehrere Funktionen können in einem Modul gruppiert werden. Innerhalb eines
-# Moduls ist es möglich mit dem Schlüsselwort 'def' eine Funktion zu
-# definieren.
-defmodule Math do
- def sum(a, b) do
- a + b
- end
-
- def square(x) do
- x * x
- end
-end
-
-Math.sum(1, 2) #=> 3
-Math.square(3) #=> 9
-
-# Um unser einfaches Mathe-Modul zu kompilieren muss es unter 'math.ex'
-# gesichert werden. Anschließend kann es mit 'elixirc' im Terminal aufgerufen
-# werden: elixirc math.ex
-
-# Innerhalb eines Moduls definieren wir private Funktionen mit 'defp'. Eine
-# Funktion, die mit 'def' erstellt wurde, kann von anderen Modulen aufgerufen
-# werden; eine private Funktion kann nur lokal angesprochen werden.
-defmodule PrivateMath do
- def sum(a, b) do
- do_sum(a, b)
- end
-
- defp do_sum(a, b) do
- a + b
- end
-end
-
-PrivateMath.sum(1, 2) #=> 3
-# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError)
-
-# Auch Funktionsdeklarationen unterstützen 'guards' und Mustererkennung:
-defmodule Geometry do
- def area({:rectangle, w, h}) do
- w * h
- end
-
- def area({:circle, r}) when is_number(r) do
- 3.14 * r * r
- end
-end
-
-Geometry.area({:rectangle, 2, 3}) #=> 6
-Geometry.area({:circle, 3}) #=> 28.25999999999999801048
-# Geometry.area({:circle, "not_a_number"})
-#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
-
-# Wegen der Unveränderlichkeit von Variablen ist Rekursion ein wichtiger
-# Bestandteil von Elixir.
-defmodule Recursion do
- def sum_list([head | tail], acc) do
- sum_list(tail, acc + head)
- end
-
- def sum_list([], acc) do
- acc
- end
-end
-
-Recursion.sum_list([1,2,3], 0) #=> 6
-
-# Elixir-Module unterstützen Attribute. Es gibt eingebaute Attribute, ebenso
-# ist es möglich eigene Attribute hinzuzufügen.
-defmodule MyMod do
- @moduledoc """
- Dies ist ein eingebautes Attribut in einem Beispiel-Modul
- """
-
- @my_data 100 # Dies ist ein selbst-definiertes Attribut.
- IO.inspect(@my_data) #=> 100
-end
-
-## ---------------------------
-## -- 'Records' und Ausnahmebehandlung
-## ---------------------------
-
-# 'Records' sind im Grunde Strukturen, die es erlauben einem Wert einen eigenen
-# Namen zuzuweisen.
-defrecord Person, name: nil, age: 0, height: 0
-
-joe_info = Person.new(name: "Joe", age: 30, height: 180)
-#=> Person[name: "Joe", age: 30, height: 180]
-
-# Zugriff auf den Wert von 'name'
-joe_info.name #=> "Joe"
-
-# Den Wert von 'age' überschreiben
-joe_info = joe_info.age(31) #=> Person[name: "Joe", age: 31, height: 180]
-
-# Der 'try'-Block wird zusammen mit dem 'rescue'-Schlüsselwort dazu verwendet,
-# um Ausnahmen beziehungsweise Fehler zu behandeln.
-try do
- raise "Irgendein Fehler."
-rescue
- RuntimeError -> "Laufzeit-Fehler gefangen."
- _error -> "Und dies fängt jeden Fehler."
-end
-
-# Alle Ausnahmen haben das Attribut 'message'
-try do
- raise "ein Fehler"
-rescue
- x in [RuntimeError] ->
- x.message
-end
-
-## ---------------------------
-## -- Nebenläufigkeit
-## ---------------------------
-
-# Elixir beruht auf dem Aktoren-Model zur Behandlung der Nebenläufigkeit. Alles
-# was man braucht um in Elixir nebenläufige Programme zu schreiben sind drei
-# Primitive: Prozesse erzeugen, Nachrichten senden und Nachrichten empfangen.
-
-# Um einen neuen Prozess zu erzeugen nutzen wir die 'spawn'-Funktion, die
-# wiederum eine Funktion als Argument entgegen nimmt.
-f = fn -> 2 * 2 end #=> #Function<erl_eval.20.80484245>
-spawn(f) #=> #PID<0.40.0>
-
-# 'spawn' gibt eine pid (einen Identifikator des Prozesses) zurück. Diese kann
-# nun verwendet werden, um Nachrichten an den Prozess zu senden. Um
-# zu senden nutzen wir den '<-' Operator. Damit das alles Sinn macht müssen wir
-# in der Lage sein Nachrichten zu empfangen. Dies wird mit dem
-# 'receive'-Mechanismus sichergestellt:
-defmodule Geometry do
- def area_loop do
- receive do
- {:rectangle, w, h} ->
- IO.puts("Area = #{w * h}")
- area_loop()
- {:circle, r} ->
- IO.puts("Area = #{3.14 * r * r}")
- area_loop()
- end
- end
-end
-
-# Kompiliere das Modul, starte einen Prozess und gib die 'area_loop' Funktion
-# in der Shell mit, etwa so:
-pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0>
-
-# Sende eine Nachricht an die 'pid', die ein Muster im 'receive'-Ausdruck
-# erfüllt:
-pid <- {:rectangle, 2, 3}
-#=> Area = 6
-# {:rectangle,2,3}
-
-pid <- {:circle, 2}
-#=> Area = 12.56000000000000049738
-# {:circle,2}
-
-# Die Shell selbst ist ein Prozess und mit dem Schlüsselwort 'self' kann man
-# die aktuelle pid herausfinden.
-self() #=> #PID<0.27.0>
-
-```
-
-## Referenzen und weitere Lektüre
-
-* [Getting started guide](http://elixir-lang.org/getting_started/1.html) auf der [elixir Website](http://elixir-lang.org)
-* [Elixir Documentation](http://elixir-lang.org/docs/master/)
-* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) von Fred Hebert
-* "Programming Erlang: Software for a Concurrent World" von Joe Armstrong
+---
+language: Elixir
+contributors:
+ - ["Joao Marques", "http://github.com/mrshankly"]
+translators:
+ - ["Gregor Große-Bölting", "http://www.ideen-und-soehne.de"]
+filename: learnelixir-de.ex
+lang: de-de
+---
+
+Elixir ist eine moderne, funktionale Sprache für die Erlang VM. Sie ist voll
+kompatibel mit Erlang, verfügt aber über eine freundlichere Syntax und bringt
+viele Features mit.
+
+```ruby
+
+# Einzeilige Kommentare werden mit der Raute gesetzt.
+
+# Es gibt keine mehrzeiligen Kommentare;
+# es ist aber problemlos möglich mehrere einzeilige Kommentare hintereinander
+# zu setzen (so wie hier).
+
+# Mit 'iex' ruft man die Elixir-Shell auf.
+# Zum kompilieren von Modulen dient der Befehl 'elixirc'.
+
+# Beide Befehle sollten als Umgebungsvariable gesetzt sein, wenn Elixir korrekt
+# installiert wurde.
+
+## ---------------------------
+## -- Basistypen
+## ---------------------------
+
+# Es gibt Nummern:
+3 # Integer
+0x1F # Integer
+3.0 # Float
+
+# Für bessere Lesbarkeit des Codes können Unterstriche "_" als Trennzeichen verwendet werden
+1_000_000 == 1000000 # Integer
+1_000.567 == 1000.567 # Float
+
+# Atome, das sind Literale, sind Konstanten mit Namen. Sie starten mit einem
+# ':'.
+:hello # Atom
+
+# Außerdem gibt es Tupel, deren Werte im Arbeitsspeicher vorgehalten werden.
+{1,2,3} # Tupel
+
+# Die Werte innerhalb eines Tupels können mit der 'elem'-Funktion ausgelesen
+# werden:
+elem({1, 2, 3}, 0) # => 1
+
+# Listen sind als verkettete Listen implementiert.
+[1, 2, 3] # list
+
+# Auf Kopf und Rest einer Liste kann wie folgt zugegriffen werden:
+[ kopf | rest ] = [1,2,3]
+kopf # => 1
+rest # => [2, 3]
+
+# In Elixir, wie auch in Erlang, kennzeichnet '=' ein 'pattern matching'
+# (Musterabgleich) und keine Zuweisung.
+# Das heißt, dass die linke Seite auf die rechte Seite 'abgeglichen' wird.
+# Auf diese Weise kann im Beispiel oben auf Kopf und Rest der Liste zugegriffen
+# werden.
+
+# Ein Musterabgleich wird einen Fehler werfen, wenn die beiden Seiten nicht
+# zusammenpassen.
+# Im folgenden Beispiel haben die Tupel eine unterschiedliche Anzahl an
+# Elementen:
+{a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2}
+
+# Es gibt außerdem 'binaries',
+<<1,2,3>> # binary.
+
+# Strings und 'char lists'
+"hello" # String
+'hello' # Char-Liste
+
+# ... und mehrzeilige Strings
+"""
+Ich bin ein
+mehrzeiliger String.
+"""
+#=> "Ich bin ein\nmehrzeiliger String.\n"
+
+# Alles Strings werden in UTF-8 enkodiert:
+"héllò" #=> "héllò"
+
+# Eigentlich sind Strings in Wahrheit nur binaries und 'char lists' einfach
+# Listen.
+<<?a, ?b, ?c>> #=> "abc"
+[?a, ?b, ?c] #=> 'abc'
+
+# In Elixir gibt `?a` den ASCII-Integer für den Buchstaben zurück.
+?a #=> 97
+
+# Um Listen zu verbinden gibt es den Operator '++', für binaries nutzt man '<>'
+[1,2,3] ++ [4,5] #=> [1,2,3,4,5]
+'hello ' ++ 'world' #=> 'hello world'
+
+<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>>
+"hello " <> "world" #=> "hello world"
+
+## ---------------------------
+## -- Operatoren
+## ---------------------------
+
+# Einfache Arithmetik
+1 + 1 #=> 2
+10 - 5 #=> 5
+5 * 2 #=> 10
+10 / 2 #=> 5.0
+
+# In Elixir gibt der Operator '/' immer einen Float-Wert zurück.
+
+# Für Division mit ganzzahligen Ergebnis gibt es 'div'
+div(10, 2) #=> 5
+
+# Um den Rest der ganzzahligen Division zu erhalten gibt es 'rem'
+rem(10, 3) #=> 1
+
+# Natürlich gibt es auch Operatoren für Booleans: 'or', 'and' und 'not'. Diese
+# Operatoren erwarten einen Boolean als erstes Argument.
+true and true #=> true
+false or true #=> true
+# 1 and true #=> ** (ArgumentError) argument error
+
+# Elixir bietet auch '||', '&&' und '!', die Argumente jedweden Typs
+# akzeptieren. Alle Werte außer 'false' und 'nil' werden zu wahr evaluiert.
+1 || true #=> 1
+false && 1 #=> false
+nil && 20 #=> nil
+
+!true #=> false
+
+# Für Vergleiche gibt es die Operatoren `==`, `!=`, `===`, `!==`, `<=`, `>=`,
+# `<` und `>`
+1 == 1 #=> true
+1 != 1 #=> false
+1 < 2 #=> true
+
+# '===' und '!==' sind strikter beim Vergleich von Integern und Floats:
+1 == 1.0 #=> true
+1 === 1.0 #=> false
+
+# Es ist außerdem möglich zwei verschiedene Datentypen zu vergleichen:
+1 < :hello #=> true
+
+# Die gesamte Ordnung über die Datentypen ist wie folgt definiert:
+# number < atom < reference < functions < port < pid < tuple < list < bitstring
+
+# Um Joe Armstrong zu zitieren: "The actual order is not important, but that a
+# total ordering is well defined is important."
+
+## ---------------------------
+## -- Kontrollstrukturen
+## ---------------------------
+
+# Es gibt die `if`-Verzweigung
+if false do
+ "Dies wird nie jemand sehen..."
+else
+ "...aber dies!"
+end
+
+# ...und ebenso `unless`
+unless true do
+ "Dies wird nie jemand sehen..."
+else
+ "...aber dies!"
+end
+
+# Du erinnerst dich an 'pattern matching'? Viele Kontrollstrukturen in Elixir
+# arbeiten damit.
+
+# 'case' erlaubt es uns Werte mit vielerlei Mustern zu vergleichen.
+case {:one, :two} do
+ {:four, :five} ->
+ "Das wird nicht passen"
+ {:one, x} ->
+ "Das schon und außerdem wird es ':two' dem Wert 'x' zuweisen."
+ _ ->
+ "Dieser Fall greift immer."
+end
+
+# Es ist eine übliche Praxis '_' einen Wert zuzuweisen, sofern dieser Wert
+# nicht weiter verwendet wird.
+# Wenn wir uns zum Beispiel nur für den Kopf einer Liste interessieren:
+[kopf | _] = [1,2,3]
+kopf #=> 1
+
+# Für bessere Lesbarkeit können wir auch das Folgende machen:
+[kopf | _rest] = [:a, :b, :c]
+kopf #=> :a
+
+# Mit 'cond' können diverse Bedingungen zur selben Zeit überprüft werden. Man
+# benutzt 'cond' statt viele if-Verzweigungen zu verschachteln.
+cond do
+ 1 + 1 == 3 ->
+ "Ich werde nie aufgerufen."
+ 2 * 5 == 12 ->
+ "Ich auch nicht."
+ 1 + 2 == 3 ->
+ "Aber ich!"
+end
+
+# Es ist üblich eine letzte Bedingung einzufügen, die immer zu wahr evaluiert.
+cond do
+ 1 + 1 == 3 ->
+ "Ich werde nie aufgerufen."
+ 2 * 5 == 12 ->
+ "Ich auch nicht."
+ true ->
+ "Aber ich! (dies ist im Grunde ein 'else')"
+end
+
+# 'try/catch' wird verwendet um Werte zu fangen, die zuvor 'geworfen' wurden.
+# Das Konstrukt unterstützt außerdem eine 'after'-Klausel die aufgerufen wird,
+# egal ob zuvor ein Wert gefangen wurde.
+try do
+ throw(:hello)
+catch
+ nachricht -> "#{nachricht} gefangen."
+after
+ IO.puts("Ich bin die 'after'-Klausel.")
+end
+#=> Ich bin die 'after'-Klausel.
+# ":hello gefangen"
+
+## ---------------------------
+## -- Module und Funktionen
+## ---------------------------
+
+# Anonyme Funktionen (man beachte den Punkt)
+square = fn(x) -> x * x end
+square.(5) #=> 25
+
+# Anonyme Funktionen unterstützen auch 'pattern' und 'guards'. Guards erlauben
+# es die Mustererkennung zu justieren und werden mit dem Schlüsselwort 'when'
+# eingeführt:
+f = fn
+ x, y when x > 0 -> x + y
+ x, y -> x * y
+end
+
+f.(1, 3) #=> 4
+f.(-1, 3) #=> -3
+
+# Elixir bietet zahlreiche eingebaute Funktionen. Diese sind im gleichen
+# Geltungsbereich ('scope') verfügbar.
+is_number(10) #=> true
+is_list("hello") #=> false
+elem({1,2,3}, 0) #=> 1
+
+# Mehrere Funktionen können in einem Modul gruppiert werden. Innerhalb eines
+# Moduls ist es möglich mit dem Schlüsselwort 'def' eine Funktion zu
+# definieren.
+defmodule Math do
+ def sum(a, b) do
+ a + b
+ end
+
+ def square(x) do
+ x * x
+ end
+end
+
+Math.sum(1, 2) #=> 3
+Math.square(3) #=> 9
+
+# Um unser einfaches Mathe-Modul zu kompilieren muss es unter 'math.ex'
+# gesichert werden. Anschließend kann es mit 'elixirc' im Terminal aufgerufen
+# werden: elixirc math.ex
+
+# Innerhalb eines Moduls definieren wir private Funktionen mit 'defp'. Eine
+# Funktion, die mit 'def' erstellt wurde, kann von anderen Modulen aufgerufen
+# werden; eine private Funktion kann nur lokal angesprochen werden.
+defmodule PrivateMath do
+ def sum(a, b) do
+ do_sum(a, b)
+ end
+
+ defp do_sum(a, b) do
+ a + b
+ end
+end
+
+PrivateMath.sum(1, 2) #=> 3
+# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError)
+
+# Auch Funktionsdeklarationen unterstützen 'guards' und Mustererkennung:
+defmodule Geometry do
+ def area({:rectangle, w, h}) do
+ w * h
+ end
+
+ def area({:circle, r}) when is_number(r) do
+ 3.14 * r * r
+ end
+end
+
+Geometry.area({:rectangle, 2, 3}) #=> 6
+Geometry.area({:circle, 3}) #=> 28.25999999999999801048
+# Geometry.area({:circle, "not_a_number"})
+#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
+
+# Wegen der Unveränderlichkeit von Variablen ist Rekursion ein wichtiger
+# Bestandteil von Elixir.
+defmodule Recursion do
+ def sum_list([head | tail], acc) do
+ sum_list(tail, acc + head)
+ end
+
+ def sum_list([], acc) do
+ acc
+ end
+end
+
+Recursion.sum_list([1,2,3], 0) #=> 6
+
+# Elixir-Module unterstützen Attribute. Es gibt eingebaute Attribute, ebenso
+# ist es möglich eigene Attribute hinzuzufügen.
+defmodule MyMod do
+ @moduledoc """
+ Dies ist ein eingebautes Attribut in einem Beispiel-Modul
+ """
+
+ @my_data 100 # Dies ist ein selbst-definiertes Attribut.
+ IO.inspect(@my_data) #=> 100
+end
+
+## ---------------------------
+## -- 'Records' und Ausnahmebehandlung
+## ---------------------------
+
+# 'Records' sind im Grunde Strukturen, die es erlauben einem Wert einen eigenen
+# Namen zuzuweisen.
+defrecord Person, name: nil, age: 0, height: 0
+
+joe_info = Person.new(name: "Joe", age: 30, height: 180)
+#=> Person[name: "Joe", age: 30, height: 180]
+
+# Zugriff auf den Wert von 'name'
+joe_info.name #=> "Joe"
+
+# Den Wert von 'age' überschreiben
+joe_info = joe_info.age(31) #=> Person[name: "Joe", age: 31, height: 180]
+
+# Der 'try'-Block wird zusammen mit dem 'rescue'-Schlüsselwort dazu verwendet,
+# um Ausnahmen beziehungsweise Fehler zu behandeln.
+try do
+ raise "Irgendein Fehler."
+rescue
+ RuntimeError -> "Laufzeit-Fehler gefangen."
+ _error -> "Und dies fängt jeden Fehler."
+end
+
+# Alle Ausnahmen haben das Attribut 'message'
+try do
+ raise "ein Fehler"
+rescue
+ x in [RuntimeError] ->
+ x.message
+end
+
+## ---------------------------
+## -- Nebenläufigkeit
+## ---------------------------
+
+# Elixir beruht auf dem Aktoren-Model zur Behandlung der Nebenläufigkeit. Alles
+# was man braucht um in Elixir nebenläufige Programme zu schreiben sind drei
+# Primitive: Prozesse erzeugen, Nachrichten senden und Nachrichten empfangen.
+
+# Um einen neuen Prozess zu erzeugen nutzen wir die 'spawn'-Funktion, die
+# wiederum eine Funktion als Argument entgegen nimmt.
+f = fn -> 2 * 2 end #=> #Function<erl_eval.20.80484245>
+spawn(f) #=> #PID<0.40.0>
+
+# 'spawn' gibt eine pid (einen Identifikator des Prozesses) zurück. Diese kann
+# nun verwendet werden, um Nachrichten an den Prozess zu senden. Um
+# zu senden nutzen wir den '<-' Operator. Damit das alles Sinn macht müssen wir
+# in der Lage sein Nachrichten zu empfangen. Dies wird mit dem
+# 'receive'-Mechanismus sichergestellt:
+defmodule Geometry do
+ def area_loop do
+ receive do
+ {:rectangle, w, h} ->
+ IO.puts("Area = #{w * h}")
+ area_loop()
+ {:circle, r} ->
+ IO.puts("Area = #{3.14 * r * r}")
+ area_loop()
+ end
+ end
+end
+
+# Kompiliere das Modul, starte einen Prozess und gib die 'area_loop' Funktion
+# in der Shell mit, etwa so:
+pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0>
+
+# Sende eine Nachricht an die 'pid', die ein Muster im 'receive'-Ausdruck
+# erfüllt:
+pid <- {:rectangle, 2, 3}
+#=> Area = 6
+# {:rectangle,2,3}
+
+pid <- {:circle, 2}
+#=> Area = 12.56000000000000049738
+# {:circle,2}
+
+# Die Shell selbst ist ein Prozess und mit dem Schlüsselwort 'self' kann man
+# die aktuelle pid herausfinden.
+self() #=> #PID<0.27.0>
+
+```
+
+## Referenzen und weitere Lektüre
+
+* [Getting started guide](http://elixir-lang.org/getting_started/1.html) auf der [elixir Website](http://elixir-lang.org)
+* [Elixir Documentation](http://elixir-lang.org/docs/master/)
+* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) von Fred Hebert
+* "Programming Erlang: Software for a Concurrent World" von Joe Armstrong
diff --git a/de-de/elm-de.html.markdown b/de-de/elm-de.html.markdown
index 08832327..a6a8cd88 100644
--- a/de-de/elm-de.html.markdown
+++ b/de-de/elm-de.html.markdown
@@ -343,7 +343,7 @@ $ elm reactor
-- Starte das REPL (read-eval-print-loop).
$ elm repl
--- Bibliotheken werden durch den Github-Nutzernamen und ein Repository identifiziert.
+-- Bibliotheken werden durch den GitHub-Nutzernamen und ein Repository identifiziert.
-- Installieren einer neuen Bibliothek.
$ elm package install elm-lang/html
-- Diese wird der elm-package.json Datei hinzugefügt.
diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown
index f817ee9f..a71d4316 100644
--- a/de-de/javascript-de.html.markdown
+++ b/de-de/javascript-de.html.markdown
@@ -1,525 +1,525 @@
----
-language: javascript
-contributors:
- - ["Leigh Brenecki", "https://leigh.net.au"]
-translators:
- - ["ggb", "http://www.ideen-und-soehne.de"]
-filename: learnjavascript-de.js
-lang: de-de
----
-
-(Anmerkungen des Original-Autors:)
-JavaScript wurde im Jahr 1995 von Brendan Eich bei Netscape entwickelt. Ursprünglich war es als einfachere Skriptsprache für Websites gedacht, ergänzend zu Java, das für komplexere Webanwendungen verwendet wird. Die enge Integration in Websites und der in Browser eingebaute Support der Sprache haben dafür gesorgt, dass JavaScript weit häufiger für Web-Frontends verwendet wird als Java.
-
-Dabei ist JavaScript inzwischen nicht mehr auf Browser beschränkt: Node.js, ein Projekt, das eine eigene Laufzeitumgebung auf Grundlage von Google Chromes V8 mitbringt, wird derzeit immer populärer.
-
-Feedback ist herzlich Willkommen! Der ursprüngliche Autor ist unter [@excitedleigh](https://twitter.com/excitedleigh) oder [l@leigh.net.au](mailto:l@leigh.net.au) zu erreichen. Der Übersetzer unter [gregorbg@web.de](mailto:gregorbg@web.de).
-
-```js
-// Kommentare werden wie in C gesetzt: Einzeilige Kommentare starten mit zwei
-// Slashes
-/* während mehrzeilige Kommentare mit einem
-Slash und einem Stern anfangen und enden */
-
-// Statements können mit einem Semikolon beendet werden
-machWas();
-
-// ...müssen sie aber nicht, weil Semikola automatisch eingefügt werden, wenn
-// eine neue Zeile beginnt, abgesehen von einigen Ausnahmen.
-machWas()
-
-// Obwohl wir uns für den Anfang nicht um diese Ausnahmen kümmern müssen ist
-// es besser die Semikola immer zu setzen.
-
-///////////////////////////////////
-// 1. Nummern, Strings und Operationen
-
-// JavaScript hat einen Nummern-Typ (64-bit IEEE 754 double).
-3; // = 3
-1.5; // = 1.5
-
-// Beinahe alle grundlegenden arithmetischen Operationen arbeiten wie erwartet.
-1 + 1; // = 2
-0.1 + 0.2; // = 0.30000000000000004
-10 * 2; // = 20
-35 / 5; // = 7
-
-// Division funktioniert auch mit einem Ergebnis nach dem Komma.
-5 / 2; // = 2.5
-
-// Bit-weise Operationen sind auch möglich; wenn eine Bit-weise Operation
-// ausgeführt wird, wird die Fließkomma-Zahl in einen 32-bit Integer (mit
-// Vorzeichen) umgewandelt.
-1 << 2; // = 4
-
-// Die Rangfolge der Operationen kann mit Klammern erzwungen werden.
-(1 + 3) * 2; // = 8
-
-// Es gibt drei spezielle, nicht-reale Nummern-Werte:
-Infinity; // Ergebnis von z. B. 1 / 0
--Infinity; // Ergebnis von z. B. -1 / 0
-NaN; // Ergebnis von z. B. 0 / 0
-
-// Es gibt auch einen Boolean-Typ (für Wahrheitswerte).
-true;
-false;
-
-// Strings werden mit ' oder " erzeugt.
-'abc';
-"Hello, world";
-
-// Für die Negation wird das ! benutzt.
-!true; // = false
-!false; // = true
-
-// Gleichheit wird mit === geprüft.
-1 === 1; // = true
-2 === 1; // = false
-
-// Ungleichheit wird mit !== überprüft.
-1 !== 1; // = false
-2 !== 1; // = true
-
-// Andere Vergleichsoperatoren sind
-1 < 10; // = true
-1 > 10; // = false
-2 <= 2; // = true
-2 >= 2; // = true
-
-// Strings können mit + verbunden
-"Hello " + "world!"; // = "Hello world!"
-
-// und mit < und > verglichen werden.
-"a" < "b"; // = true
-
-// Für den Vergleich von Werten mit "==" wird eine Typumwandlung erzwungen...
-"5" == 5; // = true
-
-// ...solange man nicht === verwendet.
-"5" === 5; // = false
-
-// Auf einzelne Buchstaben innerhalb eines Strings kann mit der Methode
-// 'charAt' zugegriffen werden
-"This is a string".charAt(0); // = "T"
-
-// Die Methode 'substring' gibt Teilbereiche eines Strings zurück
-"Hello world".substring(0, 5); // = "Hello"
-
-// 'length' ist eine Eigenschaft und wird folglich ohne '()' benutzt
-"Hello".length; // = 5
-
-// Es gibt außerdem die Werte 'null' und 'undefined'
-null; // wird verwendet um einen vorsätzlich gewählten 'Nicht'-Wert anzuzeigen
-undefined; // wird verwendet um anzuzeigen, dass der Wert (aktuell) nicht
- // verfügbar ist (obwohl genau genommen undefined selbst einen Wert
- // darstellt)
-
-// false, null, undefined, NaN, 0 und "" sind 'falsy', d. h. alles andere ist
-// wahr. Man beachte, dass 0 falsch und "0" wahr ist, obwohl 0 == "0".
-
-///////////////////////////////////
-// 2. Variablen, Arrays und Objekte
-
-// Variablen werden mit dem Schlüsselwort 'var' und einem frei wählbaren
-// Bezeichner deklariert. JavaScript ist dynamisch typisiert, so dass man einer
-// Variable keinen Typ zuweisen muss. Die Zuweisung verwendet ein einfaches =.
-var einWert = 5;
-
- // Wenn man das Schlüsselwort 'var' weglässt, bekommt man keinen Fehler
-einAndererWert = 10;
-
-// ...aber die Variable wird im globalen Kontext erzeugt, nicht in dem Kontext,
-// in dem sie erzeugt wurde.
-
-// Variablen die erzeugt wurden ohne ihnen einen Wert zuzuweisen, erhalten den
-// Wert 'undefined'.
-var einDritterWert; // = undefined
-
-// Es existiert eine Kurzform, um mathematische Operationen mit Variablen
-// auszuführen:
-einWert += 5; // äquivalent zu einWert = einWert + 5; einWert ist nun also 10
-einWert *= 10; // einWert ist nach dieser Operation 100
-
-// Und es existiert eine weitere, sogar noch kürzere Form, um 1 zu addieren
-// oder zu subtrahieren
-einWert++; // nun ist einWert 101
-einWert--; // wieder 100
-
-// Arrays sind geordnete Listen von Werten irgendeines Typs
-var myArray = ["Hello", 45, true];
-
-// Auf einzelne Elemente eines Arrays kann zugegriffen werden, in dem der Index
-// in eckigen Klammern hinter das Array geschrieben werden. Die Indexierung
-// beginnt bei 0.
-myArray[1]; // = 45
-
-// Arrays haben keine feste Länge
-myArray.push("World");
-myArray.length; // = 4
-
-// und sind veränderlich
-myArray[3] = "Hello";
-
-// Die Objekte in JavaScript entsprechen 'dictionaries' oder 'maps' in anderen
-// Sprachen: es handelt sich um ungeordnete Schlüssel-Wert-Paare.
-var myObj = { key1: "Hello", key2: "World" };
-
-// Schlüssel sind Strings, aber es werden keine Anführungszeichen benötigt,
-// sofern es sich um reguläre JavaScript-Bezeichner handelt. Werte können von
-// jedem Typ sein.
-var myObj = { myKey: "myValue", "my other key": 4 };
-
-// Auf Attribute von Objekten kann ebenfalls mit eckigen Klammern zugegriffen
-// werden,
-myObj["my other key"]; // = 4
-
-// ... oder in dem man die Punkt-Notation verwendet, vorausgesetzt es handelt
-// sich bei dem Schlüssel um einen validen Bezeichner.
-myObj.myKey; // = "myValue"
-
-// Objekte sind veränderlich, Werte können verändert und neue Schlüssel
-// hinzugefügt werden.
-myObj.myThirdKey = true;
-
-// Der Zugriff auf einen noch nicht definierten Schlüssel, liefert ein
-// undefined.
-myObj.myFourthKey; // = undefined
-
-///////////////////////////////////
-// 3. Logik und Kontrollstrukturen
-
-// Die if-Struktur arbeitet, wie man es erwartet.
-var count = 1;
-if (count == 3){
- // wird evaluiert, wenn count gleich 3 ist
-} else if (count == 4) {
- // wird evaluiert, wenn count gleich 4 ist
-} else {
- // wird evaluiert, wenn es weder 3 noch 4 ist
-}
-
-// Genauso 'while'.
-while (true) {
- // Eine unendliche Schleife!
-}
-
-// Do-while-Scheifen arbeiten wie while-Schleifen, abgesehen davon, dass sie
-// immer mindestens einmal ausgeführt werden.
-var input;
-do {
- input = getInput();
-} while ( !isValid( input ) )
-
-// Die for-Schleife arbeitet genau wie in C und Java:
-// Initialisierung; Bedingung, unter der die Ausführung fortgesetzt wird;
-// Iteration.
-for ( var i = 0; i < 5; i++ ) {
- // wird 5-mal ausgeführt
-}
-
-// '&&' ist das logische und, '||' ist das logische oder
-if (house.size == "big" && house.colour == "blue"){
- house.contains = "bear";
- // Die Größe des Hauses ist groß und die Farbe blau.
-}
-if (colour == "red" || colour == "blue"){
- // Die Farbe ist entweder rot oder blau.
-}
-
-// Die Auswertung von '&&' und '||' erfolgt so, dass abgebrochen wird, wenn die
-// Bedingung erfüllt ist (bei oder) oder nicht-erfüllt ist (bei und). Das ist
-// nützlich, um einen Default-Wert zu setzen.
-var name = otherName || "default";
-
-// Ein 'switch' Statement prüft Gleichheit mit ===
-// ohne ein 'break' nach jedem Fall
-// werden auch die Fälle nach dem korrekten aufgerufen
-grade = 'B';
-switch (grade) {
- case 'A':
- console.log("Great job");
- break;
- case 'B':
- console.log("OK job");
- break;
- case 'C':
- console.log("You can do better");
- break;
- default:
- console.log("Oy vey");
- break;
-}
-
-///////////////////////////////////
-// 4. Funktionen, Geltungsbereich und Closures
-
-// In JavaScript werden Funktionen mit dem Schlüsselwort 'function' deklariert.
-function myFunction(thing){
- return thing.toUpperCase();
-}
-myFunction("foo"); // = "FOO"
-
-// Vorsicht: der Ausdruck der den Rückgabewert einer Funktion bildet muss
-// auf der selben Zeile beginnen auf der auch das 'return' Keyword steht
-// Sonst wird hier ein automatisches Semikolon eingefügt und die Funktion
-// gibt 'undefined' zurück
-function myFunction()
-{
- return // <- Hier wird automatisch ein Semikolon eingefügt
- {
- thisIsAn: 'object literal'
- }
-}
-myFunction(); // = undefined
-
-// In JavaScript sind Funktionen 'Bürger erster Klasse', also können sie wie
-// Variablen verwendet und als Parameter anderen Funktionen übergeben werden
-// - zum Beispiel, um einen 'event handler' zu 'beliefern'.
-function myFunction() {
- // wird ausgeführt, nachdem 5 Sekunden vergangen sind
-}
-setTimeout(myFunction, 5000);
-
-// Funktionen können auch deklariert werden, ohne ihnen einen Namen zuzuweisen.
-// Es ist möglich diese anonymen Funktionen direkt als (oder im) Argument
-// einer anderen Funktion zu definieren.
-setTimeout(function(){
- // wird ausgeführt, nachdem 5 Sekunden vergangen sind
-}, 5000);
-
-// JavaScript hat einen Geltungsbereich, der sich auf Funktionen erstreckt:
-// Funktionen haben ihren eigenen Geltungsbereich, andere Blöcke nicht.
-if(true) {
- var i = 5;
-}
-i; // = 5 - nicht undefined, wie man es von einer Sprache erwarten würde, die
- // ihren Geltungsbereich nach Blöcken richtet
-
-// Daraus ergibt sich ein bestimmtes Muster für sofort-ausführbare, anonyme
-// Funktionen, die es vermeiden, dass der globale Geltungsbereich von Variablen
-// 'verschmutzt' wird.
-(function(){
- var temporary = 5;
- // Auf eine Variable im globalen Geltungsbereich kann zugegriffen werden,
- // sofern sie im globalen Objekt definiert ist (in einem Webbrowser ist
- // dies immer das 'window'-Objekt, in anderen Umgebungen, bspw. Node.js,
- // kann das anders aussehen).
- window.permanent = 10;
-})();
-temporary; // wirft einen ReferenceError
-permanent; // = 10
-
-// Eines der mächtigsten Charakteristika von JavaScript sind Closures. Wird
-// eine Funktion innerhalb einer anderen Funktion definiert, dann hat die
-// innere Funktion Zugriff auf alle Variablen der äußeren Funktion, sogar dann,
-// wenn die äußere Funktion beendet wurde.
-function sayHelloInFiveSeconds(name){
- var prompt = "Hello, " + name + "!";
- function inner(){
- alert(prompt);
- }
- setTimeout(inner, 5000);
- // setTimeout wird asynchron ausgeführt. Also wird sayHelloInFiveSeconds
- // sofort verlassen und setTimeout wird die innere Funktion 'im nachhinein'
- // aufrufen. Dennoch: Weil sayHelloInFiveSeconds eine Hülle um die innere
- // Funktion bildet, hat die innere Funktion immer noch Zugriff auf die
- // Variable prompt.
-}
-sayHelloInFiveSeconds("Adam"); // wird nach 5 Sekunden ein Popup mit der
- // Nachricht "Hello, Adam!" öffnen.
-
-///////////////////////////////////
-// 5. Mehr über Objekte, Konstruktoren und Prototypen
-
-// Objekte können Funktionen enthalten.
-var myObj = {
- myFunc: function(){
- return "Hello world!";
- }
-};
-myObj.myFunc(); // = "Hello world!"
-
-// Wenn Funktionen aufgerufen werden, die zu einem Objekt gehören, können sie
-// auf das eigene Objekt mit dem Schlüsselwort 'this' zugreifen.
-myObj = {
- myString: "Hello world!",
- myFunc: function(){
- return this.myString;
- }
-};
-myObj.myFunc(); // = "Hello world!"
-
-// Worauf 'this' gesetzt wird, ist davon abhängig, wie die Funktion aufgerufen
-// wird, nicht wo sie definiert wurde. Unsere Funktion wird daher nicht
-// funktionieren, sofern sie außerhalb des Kontextes des Objekts aufgerufen
-// wird.
-var myFunc = myObj.myFunc;
-myFunc(); // = undefined
-
-// Umgekehrt ist es möglich eine Funktion einem Objekt zuzuweisen und dadurch
-// Zugriff auf den this-Kontext zu erhalten, sogar dann, wenn die Funktion dem
-// Objekt nach dessen Definition zugewiesen wird.
-var myOtherFunc = function(){
- return this.myString.toUpperCase();
-}
-myObj.myOtherFunc = myOtherFunc;
-myObj.myOtherFunc(); // = "HELLO WORLD!"
-
-// Mit den Methoden 'call' und 'apply' kann der Kontext eines Funktionsaufrufs
-// verändert werden
-
-var anotherFunc = function(s){
- return this.myString + s;
-}
-anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"
-
-// 'apply' funktioniert beiahe identisch, erwartet die übergebenen Argumente
-// aber in einem Array
-
-anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!"
-
-// Das ist hilfreich wenn man einer Funktion eine beliebige Zahl Argumente
-// übergeben kann
-
-Math.min(42, 6, 27); // = 6
-Math.min([42, 6, 27]); // = NaN (uh-oh!)
-Math.min.apply(Math, [42, 6, 27]); // = 6
-
-// 'call' und 'apply' beeinflussen aber nur den spezifischen Aufruf.
-// Um den Kontext einer Funktion dauerhaft zu ändern wird 'bind' benutzt.
-
-var boundFunc = anotherFunc.bind(myObj);
-boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!"
-
-// Mit 'bind' lassen sich Funktionen auch teilweise anwenden / "curryen".
-var product = function(a, b){ return a * b; }
-var doubler = product.bind(this, 2);
-doubler(8); // = 16
-
-// Wenn eine Funktion mit dem Schlüsselwort 'new' aufgerufen wird, dann wird
-// ein neues Objekt erzeugt. Funktionen, die darauf ausgelegt sind in dieser
-// Art aufgerufen zu werden, werden Konstruktoren genannt.
-var MyConstructor = function(){
- this.myNumber = 5;
-}
-myNewObj = new MyConstructor(); // = {myNumber: 5}
-myNewObj.myNumber; // = 5
-
-// Jedes JavaScript-Objekt hat einen Prototyp. Wenn man versucht auf eine
-// Eigenschaft des Objekts zuzugreifen, das nicht im Objekt selbst existiert,
-// schaut der Interpreter in dessen Prototyp nach.
-
-// Einige JavaScript-Implementierungen erlauben den direkten Zugriff auf den
-// Prototyp eines Objekts durch die magische Eigenschaft __proto__. Obwohl das
-// nützlich ist, um Prototypen im Allgemeinen zu erklären, ist das nicht Teil
-// des Standards; zum Standard-Weg der Nutzung von Prototypen kommen wir
-// später.
-var myObj = {
- myString: "Hello world!",
-};
-var myPrototype = {
- meaningOfLife: 42,
- myFunc: function(){
- return this.myString.toLowerCase()
- }
-};
-myObj.__proto__ = myPrototype;
-myObj.meaningOfLife; // = 42
-
-// Das funktioniert auch bei Funktionen.
-myObj.myFunc(); // = "hello world!"
-
-// Sollte die Eigenschaft nicht im Prototypen des Objekts enthalten sein, dann
-// wird im Prototypen des Prototypen nachgesehen und so weiter.
-myPrototype.__proto__ = {
- myBoolean: true
-};
-myObj.myBoolean; // = true
-
-// Dafür wird nichts hin und her kopiert; jedes Objekt speichert eine Referenz
-// auf seinen Prototypen. Das heißt wenn der Prototyp geändert wird, dann
-// werden die Änderungen überall sichtbar.
-myPrototype.meaningOfLife = 43;
-myObj.meaningOfLife; // = 43
-
-// Es wurde bereits erwähnt, dass __proto__ nicht zum Standard gehört und es
-// gibt ebenso keinen Standard-Weg, um den Prototyp eines existierenden Objekts
-// zu ändern. Es gibt dennoch zwei Wege, wie man ein neues Objekt mit einem
-// gegebenen Prototypen erzeugt.
-
-// Der erste Weg ist die Methode Object.create, die eine jüngere Ergänzung des
-// JavaScript-Standards ist und daher noch nicht in allen Implementierungen
-// verfügbar.
-var myObj = Object.create(myPrototype);
-myObj.meaningOfLife; // = 43
-
-// Der zweite Weg, der immer funktioniert, hat mit den Konstruktoren zu tun.
-// Konstruktoren haben eine Eigenschaft, die Prototyp heißt. Dabei handelt es
-// sich *nicht* um den Prototypen der Konstruktor-Funktion; stattdessen handelt
-// es sich um den Prototypen, der einem neuen Objekt mitgegeben wird, wenn es
-// mit dem Konstruktor und dem Schlüsselwort 'new' erzeugt wird.
-MyConstructor.prototype = {
- getMyNumber: function(){
- return this.myNumber
- }
-};
-var myNewObj2 = new MyConstructor();
-myNewObj2.getMyNumber(); // = 5
-
-// Alle primitiven Typen, also strings und numbers, haben auch Konstruktoren,
-// die zu dem Typ äquivalente Wrapper-Objekte erzeugen.
-var myNumber = 12;
-var myNumberObj = new Number(12);
-myNumber == myNumberObj; // = true
-
-// Genau genommen: Sie sind nicht exakt äquivalent.
-typeof myNumber; // = 'number'
-typeof myNumberObj; // = 'object'
-myNumber === myNumberObj; // = false
-if (0){
- // Dieser Teil wird nicht ausgeführt, weil 0 'falsy' ist.
-}
-
-// Das Wrapper-Objekt und die regulären, eingebauten Typen, teilen sich einen
-// Prototyp; so ist es möglich zum Beispiel einem String weitere Funktionen
-// hinzuzufügen.
-String.prototype.firstCharacter = function(){
- return this.charAt(0);
-}
-"abc".firstCharacter(); // = "a"
-
-// Diese Tatsache wird häufig bei einer Methode mit dem Namen 'polyfilling'
-// verwendet: Dabei wird ein neues Feature von JavaScript in einer älteren
-// Untermenge der Sprache integriert, so dass bestimmte Funktionen auch in
-// älteren Umgebungen und Browsern verwendet werden können.
-
-// Ein Beispiel: Es wurde erwähnt, dass die Methode Object.create nicht in
-// allen Umgebungen verfügbar ist - wir können sie dennoch verwenden, mit einem
-// 'polyfill':
-if (Object.create === undefined){ // überschreib nichts, was eventuell bereits
- // existiert
- Object.create = function(proto){
- // erstelle einen vorübergehenden Konstruktor mit dem richtigen
- // Prototypen
- var Constructor = function(){};
- Constructor.prototype = proto;
- // verwende es dann, um ein neues Objekt mit einem passenden
- // Prototypen zurückzugeben
- return new Constructor();
- }
-}
-```
-
-## Zur weiteren Lektüre (englisch)
-
-Das [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) bietet eine ausgezeichnete Dokumentation für die Verwendung von JavaScript im Browser. Es ist außerdem ein Wiki und ermöglicht es damit anderen zu helfen, wenn man selbst ein wenig Wissen angesammelt hat.
-
-MDN's [A re-introduction to JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) führt sehr viele der hier vorgestellten Konzepte im Detail aus.
-
-Dieses Tutorial hat nur die Sprache JavaScript vorgestellt; um mehr über den Einsatz in Websites zu lernen, ist es ein guter Start etwas über das [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) zu lernen.
-
-[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) ist eine tiefgehende Einführung in die kontra-intuitiven Parts der Sprache.
-
-[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) ist ein Klassiker unter den Referenzen.
-
-Zusätzlich zu direkten Beiträgen zu diesem Artikel ist der Inhalt in Anlehnung an Louie Dinh's Python-Tutorial auf dieser Seite und das [JS Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) des Mozilla Developer Network entstanden.
+---
+language: javascript
+contributors:
+ - ["Leigh Brenecki", "https://leigh.net.au"]
+translators:
+ - ["ggb", "http://www.ideen-und-soehne.de"]
+filename: learnjavascript-de.js
+lang: de-de
+---
+
+(Anmerkungen des Original-Autors:)
+JavaScript wurde im Jahr 1995 von Brendan Eich bei Netscape entwickelt. Ursprünglich war es als einfachere Skriptsprache für Websites gedacht, ergänzend zu Java, das für komplexere Webanwendungen verwendet wird. Die enge Integration in Websites und der in Browser eingebaute Support der Sprache haben dafür gesorgt, dass JavaScript weit häufiger für Web-Frontends verwendet wird als Java.
+
+Dabei ist JavaScript inzwischen nicht mehr auf Browser beschränkt: Node.js, ein Projekt, das eine eigene Laufzeitumgebung auf Grundlage von Google Chromes V8 mitbringt, wird derzeit immer populärer.
+
+Feedback ist herzlich Willkommen! Der ursprüngliche Autor ist unter [@excitedleigh](https://twitter.com/excitedleigh) oder [l@leigh.net.au](mailto:l@leigh.net.au) zu erreichen. Der Übersetzer unter [gregorbg@web.de](mailto:gregorbg@web.de).
+
+```js
+// Kommentare werden wie in C gesetzt: Einzeilige Kommentare starten mit zwei
+// Slashes
+/* während mehrzeilige Kommentare mit einem
+Slash und einem Stern anfangen und enden */
+
+// Statements können mit einem Semikolon beendet werden
+machWas();
+
+// ...müssen sie aber nicht, weil Semikola automatisch eingefügt werden, wenn
+// eine neue Zeile beginnt, abgesehen von einigen Ausnahmen.
+machWas()
+
+// Obwohl wir uns für den Anfang nicht um diese Ausnahmen kümmern müssen ist
+// es besser die Semikola immer zu setzen.
+
+///////////////////////////////////
+// 1. Nummern, Strings und Operationen
+
+// JavaScript hat einen Nummern-Typ (64-bit IEEE 754 double).
+3; // = 3
+1.5; // = 1.5
+
+// Beinahe alle grundlegenden arithmetischen Operationen arbeiten wie erwartet.
+1 + 1; // = 2
+0.1 + 0.2; // = 0.30000000000000004
+10 * 2; // = 20
+35 / 5; // = 7
+
+// Division funktioniert auch mit einem Ergebnis nach dem Komma.
+5 / 2; // = 2.5
+
+// Bit-weise Operationen sind auch möglich; wenn eine Bit-weise Operation
+// ausgeführt wird, wird die Fließkomma-Zahl in einen 32-bit Integer (mit
+// Vorzeichen) umgewandelt.
+1 << 2; // = 4
+
+// Die Rangfolge der Operationen kann mit Klammern erzwungen werden.
+(1 + 3) * 2; // = 8
+
+// Es gibt drei spezielle, nicht-reale Nummern-Werte:
+Infinity; // Ergebnis von z. B. 1 / 0
+-Infinity; // Ergebnis von z. B. -1 / 0
+NaN; // Ergebnis von z. B. 0 / 0
+
+// Es gibt auch einen Boolean-Typ (für Wahrheitswerte).
+true;
+false;
+
+// Strings werden mit ' oder " erzeugt.
+'abc';
+"Hello, world";
+
+// Für die Negation wird das ! benutzt.
+!true; // = false
+!false; // = true
+
+// Gleichheit wird mit === geprüft.
+1 === 1; // = true
+2 === 1; // = false
+
+// Ungleichheit wird mit !== überprüft.
+1 !== 1; // = false
+2 !== 1; // = true
+
+// Andere Vergleichsoperatoren sind
+1 < 10; // = true
+1 > 10; // = false
+2 <= 2; // = true
+2 >= 2; // = true
+
+// Strings können mit + verbunden
+"Hello " + "world!"; // = "Hello world!"
+
+// und mit < und > verglichen werden.
+"a" < "b"; // = true
+
+// Für den Vergleich von Werten mit "==" wird eine Typumwandlung erzwungen...
+"5" == 5; // = true
+
+// ...solange man nicht === verwendet.
+"5" === 5; // = false
+
+// Auf einzelne Buchstaben innerhalb eines Strings kann mit der Methode
+// 'charAt' zugegriffen werden
+"This is a string".charAt(0); // = "T"
+
+// Die Methode 'substring' gibt Teilbereiche eines Strings zurück
+"Hello world".substring(0, 5); // = "Hello"
+
+// 'length' ist eine Eigenschaft und wird folglich ohne '()' benutzt
+"Hello".length; // = 5
+
+// Es gibt außerdem die Werte 'null' und 'undefined'
+null; // wird verwendet um einen vorsätzlich gewählten 'Nicht'-Wert anzuzeigen
+undefined; // wird verwendet um anzuzeigen, dass der Wert (aktuell) nicht
+ // verfügbar ist (obwohl genau genommen undefined selbst einen Wert
+ // darstellt)
+
+// false, null, undefined, NaN, 0 und "" sind 'falsy', d. h. alles andere ist
+// wahr. Man beachte, dass 0 falsch und "0" wahr ist, obwohl 0 == "0".
+
+///////////////////////////////////
+// 2. Variablen, Arrays und Objekte
+
+// Variablen werden mit dem Schlüsselwort 'var' und einem frei wählbaren
+// Bezeichner deklariert. JavaScript ist dynamisch typisiert, so dass man einer
+// Variable keinen Typ zuweisen muss. Die Zuweisung verwendet ein einfaches =.
+var einWert = 5;
+
+ // Wenn man das Schlüsselwort 'var' weglässt, bekommt man keinen Fehler
+einAndererWert = 10;
+
+// ...aber die Variable wird im globalen Kontext erzeugt, nicht in dem Kontext,
+// in dem sie erzeugt wurde.
+
+// Variablen die erzeugt wurden ohne ihnen einen Wert zuzuweisen, erhalten den
+// Wert 'undefined'.
+var einDritterWert; // = undefined
+
+// Es existiert eine Kurzform, um mathematische Operationen mit Variablen
+// auszuführen:
+einWert += 5; // äquivalent zu einWert = einWert + 5; einWert ist nun also 10
+einWert *= 10; // einWert ist nach dieser Operation 100
+
+// Und es existiert eine weitere, sogar noch kürzere Form, um 1 zu addieren
+// oder zu subtrahieren
+einWert++; // nun ist einWert 101
+einWert--; // wieder 100
+
+// Arrays sind geordnete Listen von Werten irgendeines Typs
+var myArray = ["Hello", 45, true];
+
+// Auf einzelne Elemente eines Arrays kann zugegriffen werden, in dem der Index
+// in eckigen Klammern hinter das Array geschrieben werden. Die Indexierung
+// beginnt bei 0.
+myArray[1]; // = 45
+
+// Arrays haben keine feste Länge
+myArray.push("World");
+myArray.length; // = 4
+
+// und sind veränderlich
+myArray[3] = "Hello";
+
+// Die Objekte in JavaScript entsprechen 'dictionaries' oder 'maps' in anderen
+// Sprachen: es handelt sich um ungeordnete Schlüssel-Wert-Paare.
+var myObj = { key1: "Hello", key2: "World" };
+
+// Schlüssel sind Strings, aber es werden keine Anführungszeichen benötigt,
+// sofern es sich um reguläre JavaScript-Bezeichner handelt. Werte können von
+// jedem Typ sein.
+var myObj = { myKey: "myValue", "my other key": 4 };
+
+// Auf Attribute von Objekten kann ebenfalls mit eckigen Klammern zugegriffen
+// werden,
+myObj["my other key"]; // = 4
+
+// ... oder in dem man die Punkt-Notation verwendet, vorausgesetzt es handelt
+// sich bei dem Schlüssel um einen validen Bezeichner.
+myObj.myKey; // = "myValue"
+
+// Objekte sind veränderlich, Werte können verändert und neue Schlüssel
+// hinzugefügt werden.
+myObj.myThirdKey = true;
+
+// Der Zugriff auf einen noch nicht definierten Schlüssel, liefert ein
+// undefined.
+myObj.myFourthKey; // = undefined
+
+///////////////////////////////////
+// 3. Logik und Kontrollstrukturen
+
+// Die if-Struktur arbeitet, wie man es erwartet.
+var count = 1;
+if (count == 3){
+ // wird evaluiert, wenn count gleich 3 ist
+} else if (count == 4) {
+ // wird evaluiert, wenn count gleich 4 ist
+} else {
+ // wird evaluiert, wenn es weder 3 noch 4 ist
+}
+
+// Genauso 'while'.
+while (true) {
+ // Eine unendliche Schleife!
+}
+
+// Do-while-Scheifen arbeiten wie while-Schleifen, abgesehen davon, dass sie
+// immer mindestens einmal ausgeführt werden.
+var input;
+do {
+ input = getInput();
+} while ( !isValid( input ) )
+
+// Die for-Schleife arbeitet genau wie in C und Java:
+// Initialisierung; Bedingung, unter der die Ausführung fortgesetzt wird;
+// Iteration.
+for ( var i = 0; i < 5; i++ ) {
+ // wird 5-mal ausgeführt
+}
+
+// '&&' ist das logische und, '||' ist das logische oder
+if (house.size == "big" && house.colour == "blue"){
+ house.contains = "bear";
+ // Die Größe des Hauses ist groß und die Farbe blau.
+}
+if (colour == "red" || colour == "blue"){
+ // Die Farbe ist entweder rot oder blau.
+}
+
+// Die Auswertung von '&&' und '||' erfolgt so, dass abgebrochen wird, wenn die
+// Bedingung erfüllt ist (bei oder) oder nicht-erfüllt ist (bei und). Das ist
+// nützlich, um einen Default-Wert zu setzen.
+var name = otherName || "default";
+
+// Ein 'switch' Statement prüft Gleichheit mit ===
+// ohne ein 'break' nach jedem Fall
+// werden auch die Fälle nach dem korrekten aufgerufen
+grade = 'B';
+switch (grade) {
+ case 'A':
+ console.log("Great job");
+ break;
+ case 'B':
+ console.log("OK job");
+ break;
+ case 'C':
+ console.log("You can do better");
+ break;
+ default:
+ console.log("Oy vey");
+ break;
+}
+
+///////////////////////////////////
+// 4. Funktionen, Geltungsbereich und Closures
+
+// In JavaScript werden Funktionen mit dem Schlüsselwort 'function' deklariert.
+function myFunction(thing){
+ return thing.toUpperCase();
+}
+myFunction("foo"); // = "FOO"
+
+// Vorsicht: der Ausdruck der den Rückgabewert einer Funktion bildet muss
+// auf der selben Zeile beginnen auf der auch das 'return' Keyword steht
+// Sonst wird hier ein automatisches Semikolon eingefügt und die Funktion
+// gibt 'undefined' zurück
+function myFunction()
+{
+ return // <- Hier wird automatisch ein Semikolon eingefügt
+ {
+ thisIsAn: 'object literal'
+ }
+}
+myFunction(); // = undefined
+
+// In JavaScript sind Funktionen 'Bürger erster Klasse', also können sie wie
+// Variablen verwendet und als Parameter anderen Funktionen übergeben werden
+// - zum Beispiel, um einen 'event handler' zu 'beliefern'.
+function myFunction() {
+ // wird ausgeführt, nachdem 5 Sekunden vergangen sind
+}
+setTimeout(myFunction, 5000);
+
+// Funktionen können auch deklariert werden, ohne ihnen einen Namen zuzuweisen.
+// Es ist möglich diese anonymen Funktionen direkt als (oder im) Argument
+// einer anderen Funktion zu definieren.
+setTimeout(function(){
+ // wird ausgeführt, nachdem 5 Sekunden vergangen sind
+}, 5000);
+
+// JavaScript hat einen Geltungsbereich, der sich auf Funktionen erstreckt:
+// Funktionen haben ihren eigenen Geltungsbereich, andere Blöcke nicht.
+if(true) {
+ var i = 5;
+}
+i; // = 5 - nicht undefined, wie man es von einer Sprache erwarten würde, die
+ // ihren Geltungsbereich nach Blöcken richtet
+
+// Daraus ergibt sich ein bestimmtes Muster für sofort-ausführbare, anonyme
+// Funktionen, die es vermeiden, dass der globale Geltungsbereich von Variablen
+// 'verschmutzt' wird.
+(function(){
+ var temporary = 5;
+ // Auf eine Variable im globalen Geltungsbereich kann zugegriffen werden,
+ // sofern sie im globalen Objekt definiert ist (in einem Webbrowser ist
+ // dies immer das 'window'-Objekt, in anderen Umgebungen, bspw. Node.js,
+ // kann das anders aussehen).
+ window.permanent = 10;
+})();
+temporary; // wirft einen ReferenceError
+permanent; // = 10
+
+// Eines der mächtigsten Charakteristika von JavaScript sind Closures. Wird
+// eine Funktion innerhalb einer anderen Funktion definiert, dann hat die
+// innere Funktion Zugriff auf alle Variablen der äußeren Funktion, sogar dann,
+// wenn die äußere Funktion beendet wurde.
+function sayHelloInFiveSeconds(name){
+ var prompt = "Hello, " + name + "!";
+ function inner(){
+ alert(prompt);
+ }
+ setTimeout(inner, 5000);
+ // setTimeout wird asynchron ausgeführt. Also wird sayHelloInFiveSeconds
+ // sofort verlassen und setTimeout wird die innere Funktion 'im nachhinein'
+ // aufrufen. Dennoch: Weil sayHelloInFiveSeconds eine Hülle um die innere
+ // Funktion bildet, hat die innere Funktion immer noch Zugriff auf die
+ // Variable prompt.
+}
+sayHelloInFiveSeconds("Adam"); // wird nach 5 Sekunden ein Popup mit der
+ // Nachricht "Hello, Adam!" öffnen.
+
+///////////////////////////////////
+// 5. Mehr über Objekte, Konstruktoren und Prototypen
+
+// Objekte können Funktionen enthalten.
+var myObj = {
+ myFunc: function(){
+ return "Hello world!";
+ }
+};
+myObj.myFunc(); // = "Hello world!"
+
+// Wenn Funktionen aufgerufen werden, die zu einem Objekt gehören, können sie
+// auf das eigene Objekt mit dem Schlüsselwort 'this' zugreifen.
+myObj = {
+ myString: "Hello world!",
+ myFunc: function(){
+ return this.myString;
+ }
+};
+myObj.myFunc(); // = "Hello world!"
+
+// Worauf 'this' gesetzt wird, ist davon abhängig, wie die Funktion aufgerufen
+// wird, nicht wo sie definiert wurde. Unsere Funktion wird daher nicht
+// funktionieren, sofern sie außerhalb des Kontextes des Objekts aufgerufen
+// wird.
+var myFunc = myObj.myFunc;
+myFunc(); // = undefined
+
+// Umgekehrt ist es möglich eine Funktion einem Objekt zuzuweisen und dadurch
+// Zugriff auf den this-Kontext zu erhalten, sogar dann, wenn die Funktion dem
+// Objekt nach dessen Definition zugewiesen wird.
+var myOtherFunc = function(){
+ return this.myString.toUpperCase();
+}
+myObj.myOtherFunc = myOtherFunc;
+myObj.myOtherFunc(); // = "HELLO WORLD!"
+
+// Mit den Methoden 'call' und 'apply' kann der Kontext eines Funktionsaufrufs
+// verändert werden
+
+var anotherFunc = function(s){
+ return this.myString + s;
+}
+anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"
+
+// 'apply' funktioniert beiahe identisch, erwartet die übergebenen Argumente
+// aber in einem Array
+
+anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!"
+
+// Das ist hilfreich wenn man einer Funktion eine beliebige Zahl Argumente
+// übergeben kann
+
+Math.min(42, 6, 27); // = 6
+Math.min([42, 6, 27]); // = NaN (uh-oh!)
+Math.min.apply(Math, [42, 6, 27]); // = 6
+
+// 'call' und 'apply' beeinflussen aber nur den spezifischen Aufruf.
+// Um den Kontext einer Funktion dauerhaft zu ändern wird 'bind' benutzt.
+
+var boundFunc = anotherFunc.bind(myObj);
+boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!"
+
+// Mit 'bind' lassen sich Funktionen auch teilweise anwenden / "curryen".
+var product = function(a, b){ return a * b; }
+var doubler = product.bind(this, 2);
+doubler(8); // = 16
+
+// Wenn eine Funktion mit dem Schlüsselwort 'new' aufgerufen wird, dann wird
+// ein neues Objekt erzeugt. Funktionen, die darauf ausgelegt sind in dieser
+// Art aufgerufen zu werden, werden Konstruktoren genannt.
+var MyConstructor = function(){
+ this.myNumber = 5;
+}
+myNewObj = new MyConstructor(); // = {myNumber: 5}
+myNewObj.myNumber; // = 5
+
+// Jedes JavaScript-Objekt hat einen Prototyp. Wenn man versucht auf eine
+// Eigenschaft des Objekts zuzugreifen, das nicht im Objekt selbst existiert,
+// schaut der Interpreter in dessen Prototyp nach.
+
+// Einige JavaScript-Implementierungen erlauben den direkten Zugriff auf den
+// Prototyp eines Objekts durch die magische Eigenschaft __proto__. Obwohl das
+// nützlich ist, um Prototypen im Allgemeinen zu erklären, ist das nicht Teil
+// des Standards; zum Standard-Weg der Nutzung von Prototypen kommen wir
+// später.
+var myObj = {
+ myString: "Hello world!",
+};
+var myPrototype = {
+ meaningOfLife: 42,
+ myFunc: function(){
+ return this.myString.toLowerCase()
+ }
+};
+myObj.__proto__ = myPrototype;
+myObj.meaningOfLife; // = 42
+
+// Das funktioniert auch bei Funktionen.
+myObj.myFunc(); // = "hello world!"
+
+// Sollte die Eigenschaft nicht im Prototypen des Objekts enthalten sein, dann
+// wird im Prototypen des Prototypen nachgesehen und so weiter.
+myPrototype.__proto__ = {
+ myBoolean: true
+};
+myObj.myBoolean; // = true
+
+// Dafür wird nichts hin und her kopiert; jedes Objekt speichert eine Referenz
+// auf seinen Prototypen. Das heißt wenn der Prototyp geändert wird, dann
+// werden die Änderungen überall sichtbar.
+myPrototype.meaningOfLife = 43;
+myObj.meaningOfLife; // = 43
+
+// Es wurde bereits erwähnt, dass __proto__ nicht zum Standard gehört und es
+// gibt ebenso keinen Standard-Weg, um den Prototyp eines existierenden Objekts
+// zu ändern. Es gibt dennoch zwei Wege, wie man ein neues Objekt mit einem
+// gegebenen Prototypen erzeugt.
+
+// Der erste Weg ist die Methode Object.create, die eine jüngere Ergänzung des
+// JavaScript-Standards ist und daher noch nicht in allen Implementierungen
+// verfügbar.
+var myObj = Object.create(myPrototype);
+myObj.meaningOfLife; // = 43
+
+// Der zweite Weg, der immer funktioniert, hat mit den Konstruktoren zu tun.
+// Konstruktoren haben eine Eigenschaft, die Prototyp heißt. Dabei handelt es
+// sich *nicht* um den Prototypen der Konstruktor-Funktion; stattdessen handelt
+// es sich um den Prototypen, der einem neuen Objekt mitgegeben wird, wenn es
+// mit dem Konstruktor und dem Schlüsselwort 'new' erzeugt wird.
+MyConstructor.prototype = {
+ getMyNumber: function(){
+ return this.myNumber
+ }
+};
+var myNewObj2 = new MyConstructor();
+myNewObj2.getMyNumber(); // = 5
+
+// Alle primitiven Typen, also strings und numbers, haben auch Konstruktoren,
+// die zu dem Typ äquivalente Wrapper-Objekte erzeugen.
+var myNumber = 12;
+var myNumberObj = new Number(12);
+myNumber == myNumberObj; // = true
+
+// Genau genommen: Sie sind nicht exakt äquivalent.
+typeof myNumber; // = 'number'
+typeof myNumberObj; // = 'object'
+myNumber === myNumberObj; // = false
+if (0){
+ // Dieser Teil wird nicht ausgeführt, weil 0 'falsy' ist.
+}
+
+// Das Wrapper-Objekt und die regulären, eingebauten Typen, teilen sich einen
+// Prototyp; so ist es möglich zum Beispiel einem String weitere Funktionen
+// hinzuzufügen.
+String.prototype.firstCharacter = function(){
+ return this.charAt(0);
+}
+"abc".firstCharacter(); // = "a"
+
+// Diese Tatsache wird häufig bei einer Methode mit dem Namen 'polyfilling'
+// verwendet: Dabei wird ein neues Feature von JavaScript in einer älteren
+// Untermenge der Sprache integriert, so dass bestimmte Funktionen auch in
+// älteren Umgebungen und Browsern verwendet werden können.
+
+// Ein Beispiel: Es wurde erwähnt, dass die Methode Object.create nicht in
+// allen Umgebungen verfügbar ist - wir können sie dennoch verwenden, mit einem
+// 'polyfill':
+if (Object.create === undefined){ // überschreib nichts, was eventuell bereits
+ // existiert
+ Object.create = function(proto){
+ // erstelle einen vorübergehenden Konstruktor mit dem richtigen
+ // Prototypen
+ var Constructor = function(){};
+ Constructor.prototype = proto;
+ // verwende es dann, um ein neues Objekt mit einem passenden
+ // Prototypen zurückzugeben
+ return new Constructor();
+ }
+}
+```
+
+## Zur weiteren Lektüre (englisch)
+
+Das [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) bietet eine ausgezeichnete Dokumentation für die Verwendung von JavaScript im Browser. Es ist außerdem ein Wiki und ermöglicht es damit anderen zu helfen, wenn man selbst ein wenig Wissen angesammelt hat.
+
+MDN's [A re-introduction to JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) führt sehr viele der hier vorgestellten Konzepte im Detail aus.
+
+Dieses Tutorial hat nur die Sprache JavaScript vorgestellt; um mehr über den Einsatz in Websites zu lernen, ist es ein guter Start etwas über das [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) zu lernen.
+
+[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) ist eine tiefgehende Einführung in die kontra-intuitiven Parts der Sprache.
+
+[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) ist ein Klassiker unter den Referenzen.
+
+Zusätzlich zu direkten Beiträgen zu diesem Artikel ist der Inhalt in Anlehnung an Louie Dinh's Python-Tutorial auf dieser Seite und das [JS Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) des Mozilla Developer Network entstanden.
diff --git a/de-de/make-de.html.markdown b/de-de/make-de.html.markdown
index 1bae332c..3674f2f5 100644
--- a/de-de/make-de.html.markdown
+++ b/de-de/make-de.html.markdown
@@ -1,263 +1,263 @@
----
-category: tool
-tool: make
-contributors:
- - ["Robert Steed", "https://github.com/robochat"]
- - ["Stephan Fuhrmann", "https://github.com/sfuhrm"]
-translators:
- - ["Martin Schimandl", "https://github.com/Git-Jiro"]
-filename: Makefile-de
-lang: de-de
----
-
-Eine Makefile definiert einen Graphen von Regeln um ein Ziel (oder Ziele)
-zu erzeugen. Es dient dazu, die geringste Menge an Arbeit zu verrichten um
-ein Ziel in Einklang mit dem Quellcode zu bringen. Make wurde berühmterweise
-von Stuart Feldman 1976 übers Wochenende geschrieben. Make ist noch immer
-sehr verbreitet (vorallem im Unix Umfeld) obwohl es bereits sehr viel
-Konkurrenz und Kritik zu Make gibt.
-
-Es gibt eine Vielzahl an Varianten von Make, dieser Artikel beschäftigt sich
-mit der Version GNU Make. Diese Version ist Standard auf Linux.
-
-```make
-
-# Kommentare können so geschrieben werden.
-
-# Dateien sollten Makefile heißen, denn dann können sie als `make <ziel>`
-# aufgerufen werden. Ansonsten muss `make -f "dateiname" <ziel>` verwendet
-# werden.
-
-# Warnung - Es sollten nur TABULATOREN zur Einrückung im Makefile verwendet
-# werden. Niemals Leerzeichen!
-
-#-----------------------------------------------------------------------
-# Grundlagen
-#-----------------------------------------------------------------------
-
-# Eine Regel - Diese Regel wird nur abgearbeitet wenn die Datei file0.txt
-# nicht existiert.
-file0.txt:
- echo "foo" > file0.txt
- # Selbst Kommentare in der 'Rezept' Sektion werden an die Shell
- # weitergegeben. Versuche `make file0.txt` oder einfach `make`
- # die erste Regel ist die Standard-Regel.
-
-
-# Diese Regel wird nur abgearbeitet, wenn file0.txt aktueller als file1.txt ist.
-file1.txt: file0.txt
- cat file0.txt > file1.txt
- # Verwende die selben Quoting-Regeln wie die Shell
- @cat file0.txt >> file1.txt
- # @ unterdrückt die Ausgabe des Befehls an stdout.
- -@echo 'hello'
- # - bedeutet, dass Make die Abarbeitung fortsetzt auch wenn Fehler
- # passieren.
- # Versuche `make file1.txt` auf der Kommandozeile.
-
-# Eine Regel kann mehrere Ziele und mehrere Voraussetzungen haben.
-file2.txt file3.txt: file0.txt file1.txt
- touch file2.txt
- touch file3.txt
-
-# Make wird sich beschweren, wenn es mehrere Rezepte für die gleiche Regel gibt.
-# Leere Rezepte zählen nicht und können dazu verwendet werden weitere
-# Voraussetzungen hinzuzufügen.
-
-#-----------------------------------------------------------------------
-# Phony-Ziele
-#-----------------------------------------------------------------------
-
-# Ein Phony-Ziel ist ein Ziel, das keine Datei ist.
-# Es wird nie aktuell sein, daher wird Make immer versuchen, es abzuarbeiten
-all: maker process
-
-# Es ist erlaubt Dinge ausserhalb der Reihenfolge zu deklarieren.
-maker:
- touch ex0.txt ex1.txt
-
-# Um das Fehlschlagen von Phony-Regeln zu vermeiden wenn eine echte Datei den
-# selben namen wie ein Phony-Ziel hat:
-.PHONY: all maker process
-# Das ist ein spezielles Ziel. Es gibt noch ein paar mehr davon.
-
-# Eine Regel mit einem Phony-Ziel als Voraussetzung wird immer abgearbeitet
-ex0.txt ex1.txt: maker
-
-# Häufige Phony-Ziele sind: all make clean install ...
-
-#-----------------------------------------------------------------------
-# Automatische Variablen & Wildcards
-#-----------------------------------------------------------------------
-
-process: file*.txt # Eine Wildcard um Dateinamen zu vergleichen
- @echo $^ # $^ ist eine Variable die eine Liste aller
- # Voraussetzungen enthält.
- @echo $@ # Namen des Ziels ausgeben.
- #(Bei mehreren Ziel-Regeln enthält $@ den Verursacher der Abarbeitung
- #der Regel.)
- @echo $< # Die erste Voraussetzung aus der Liste
- @echo $? # Nur die Voraussetzungen, die nicht aktuell sind.
- @echo $+ # Alle Voraussetzungen inklusive Duplikate (nicht wie Üblich)
- #@echo $| # Alle 'order only' Voraussetzungen
-
-# Selbst wenn wir die Voraussetzungen der Regel aufteilen, $^ wird sie finden.
-process: ex1.txt file0.txt
-# ex1.txt wird gefunden werden, aber file0.txt wird dedupliziert.
-
-#-----------------------------------------------------------------------
-# Muster
-#-----------------------------------------------------------------------
-
-# Mit Mustern kann man make beibringen wie Dateien in andere Dateien
-# umgewandelt werden.
-
-%.png: %.svg
- inkscape --export-png $^
-
-# Muster-Vergleichs-Regeln werden nur abgearbeitet, wenn make entscheidet das
-# Ziel zu erzeugen
-
-# Verzeichnis-Pfade werden normalerweise bei Muster-Vergleichs-Regeln ignoriert.
-# Aber make wird versuchen die am besten passende Regel zu verwenden.
-small/%.png: %.svg
- inkscape --export-png --export-dpi 30 $^
-
-# Make wird die letzte Version einer Muster-Vergleichs-Regel verwenden, die es
-# findet.
-%.png: %.svg
- @echo this rule is chosen
-
-# Allerdings wird make die erste Muster-Vergleicher-Regel verwenden, die das
-# Ziel erzeugen kann.
-%.png: %.ps
- @echo this rule is not chosen if *.svg and *.ps are both present
-
-# Make hat bereits ein paar eingebaute Muster-Vergleichs-Regelen. Zum Beispiel
-# weiß Make wie man aus *.c Dateien *.o Dateien erzeugt.
-
-# Ältere Versionen von Make verwenden möglicherweise Suffix-Regeln anstatt
-# Muster-Vergleichs-Regeln.
-.png.ps:
- @echo this rule is similar to a pattern rule.
-
-# Aktivieren der Suffix-Regel
-.SUFFIXES: .png
-
-#-----------------------------------------------------------------------
-# Variablen
-#-----------------------------------------------------------------------
-# auch Makros genannt.
-
-# Variablen sind im Grunde genommen Zeichenketten-Typen.
-
-name = Ted
-name2="Sarah"
-
-echo:
- @echo $(name)
- @echo ${name2}
- @echo $name # Das funktioniert nicht, wird als $(n)ame behandelt.
- @echo $(name3) # Unbekannte Variablen werden als leere Zeichenketten behandelt.
-
-# Es git 4 Stellen um Variablen zu setzen.
-# In Reihenfolge der Priorität von höchster zu niedrigster:
-# 1: Befehls-Zeilen Argumente
-# 2: Makefile
-# 3: Shell Umbebungs-Variablen - Make importiert diese automatisch.
-# 3: MAke hat einige vordefinierte Variablen.
-
-name4 ?= Jean
-# Setze die Variable nur wenn es eine gleichnamige Umgebungs-Variable noch
-# nicht gibt.
-
-override name5 = David
-# Verhindert, dass Kommando-Zeilen Argumente diese Variable ändern können.
-
-name4 +=grey
-# Werte an eine Variable anhängen (inkludiert Leerzeichen).
-
-# Muster-Spezifische Variablen Werte (GNU Erweiterung).
-echo: name2 = Sara # Wahr innerhalb der passenden Regel und auch innerhalb
- # rekursiver Voraussetzungen (ausser wenn es den Graphen zerstören
- # kann, wenn es zu kompilizert wird!)
-
-# Ein paar Variablen, die von Make automatisch definiert werden.
-echo_inbuilt:
- echo $(CC)
- echo ${CXX}
- echo $(FC)
- echo ${CFLAGS}
- echo $(CPPFLAGS)
- echo ${CXXFLAGS}
- echo $(LDFLAGS)
- echo ${LDLIBS}
-
-#-----------------------------------------------------------------------
-# Variablen 2
-#-----------------------------------------------------------------------
-
-# Der erste Typ von Variablen wird bei jeder Verwendung ausgewertet.
-# Das kann aufwendig sein, daher exisitert ein zweiter Typ von Variablen.
-# Diese werden nur einmal ausgewertet. (Das ist eine GNU make Erweiterung)
-
-var := hello
-var2 ::= $(var) hello
-#:= und ::= sind äquivalent.
-
-# Diese Variablen werden prozedural ausgwertet (in der Reihenfolge in der sie
-# auftauchen), die stehen daher im wiederspruch zum Rest der Sprache!
-
-# Das funktioniert nicht
-var3 ::= $(var4) and good luck
-var4 ::= good night
-
-#-----------------------------------------------------------------------
-# Funktionen
-#-----------------------------------------------------------------------
-
-# Make verfügt über eine Vielzahl von Funktionen.
-
-sourcefiles = $(wildcard *.c */*.c)
-objectfiles = $(patsubst %.c,%.o,$(sourcefiles))
-
-# Das Format ist $(func arg0,arg1,arg2...)
-
-# Ein paar Beispiele
-ls: * src/*
- @echo $(filter %.txt, $^)
- @echo $(notdir $^)
- @echo $(join $(dir $^),$(notdir $^))
-
-#-----------------------------------------------------------------------
-# Direktiven
-#-----------------------------------------------------------------------
-
-# Inkludiere andere Makefile, sehr praktisch für platformspezifischen Code
-include foo.mk
-
-sport = tennis
-# Konditionale kompiliereung
-report:
-ifeq ($(sport),tennis)
- @echo 'game, set, match'
-else
- @echo "They think it's all over; it is now"
-endif
-
-# Es gibt auch ifneq, ifdef, ifndef
-
-foo = true
-
-ifdef $(foo)
-bar = 'hello'
-endif
-```
-
-
-### Mehr Resourcen
-
-+ [gnu make documentation](https://www.gnu.org/software/make/manual/)
-+ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/)
-+ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)
-
+---
+category: tool
+tool: make
+contributors:
+ - ["Robert Steed", "https://github.com/robochat"]
+ - ["Stephan Fuhrmann", "https://github.com/sfuhrm"]
+translators:
+ - ["Martin Schimandl", "https://github.com/Git-Jiro"]
+filename: Makefile-de
+lang: de-de
+---
+
+Eine Makefile definiert einen Graphen von Regeln um ein Ziel (oder Ziele)
+zu erzeugen. Es dient dazu, die geringste Menge an Arbeit zu verrichten um
+ein Ziel in Einklang mit dem Quellcode zu bringen. Make wurde berühmterweise
+von Stuart Feldman 1976 übers Wochenende geschrieben. Make ist noch immer
+sehr verbreitet (vorallem im Unix Umfeld) obwohl es bereits sehr viel
+Konkurrenz und Kritik zu Make gibt.
+
+Es gibt eine Vielzahl an Varianten von Make, dieser Artikel beschäftigt sich
+mit der Version GNU Make. Diese Version ist Standard auf Linux.
+
+```make
+
+# Kommentare können so geschrieben werden.
+
+# Dateien sollten Makefile heißen, denn dann können sie als `make <ziel>`
+# aufgerufen werden. Ansonsten muss `make -f "dateiname" <ziel>` verwendet
+# werden.
+
+# Warnung - Es sollten nur TABULATOREN zur Einrückung im Makefile verwendet
+# werden. Niemals Leerzeichen!
+
+#-----------------------------------------------------------------------
+# Grundlagen
+#-----------------------------------------------------------------------
+
+# Eine Regel - Diese Regel wird nur abgearbeitet wenn die Datei file0.txt
+# nicht existiert.
+file0.txt:
+ echo "foo" > file0.txt
+ # Selbst Kommentare in der 'Rezept' Sektion werden an die Shell
+ # weitergegeben. Versuche `make file0.txt` oder einfach `make`
+ # die erste Regel ist die Standard-Regel.
+
+
+# Diese Regel wird nur abgearbeitet, wenn file0.txt aktueller als file1.txt ist.
+file1.txt: file0.txt
+ cat file0.txt > file1.txt
+ # Verwende die selben Quoting-Regeln wie die Shell
+ @cat file0.txt >> file1.txt
+ # @ unterdrückt die Ausgabe des Befehls an stdout.
+ -@echo 'hello'
+ # - bedeutet, dass Make die Abarbeitung fortsetzt auch wenn Fehler
+ # passieren.
+ # Versuche `make file1.txt` auf der Kommandozeile.
+
+# Eine Regel kann mehrere Ziele und mehrere Voraussetzungen haben.
+file2.txt file3.txt: file0.txt file1.txt
+ touch file2.txt
+ touch file3.txt
+
+# Make wird sich beschweren, wenn es mehrere Rezepte für die gleiche Regel gibt.
+# Leere Rezepte zählen nicht und können dazu verwendet werden weitere
+# Voraussetzungen hinzuzufügen.
+
+#-----------------------------------------------------------------------
+# Phony-Ziele
+#-----------------------------------------------------------------------
+
+# Ein Phony-Ziel ist ein Ziel, das keine Datei ist.
+# Es wird nie aktuell sein, daher wird Make immer versuchen, es abzuarbeiten
+all: maker process
+
+# Es ist erlaubt Dinge ausserhalb der Reihenfolge zu deklarieren.
+maker:
+ touch ex0.txt ex1.txt
+
+# Um das Fehlschlagen von Phony-Regeln zu vermeiden wenn eine echte Datei den
+# selben namen wie ein Phony-Ziel hat:
+.PHONY: all maker process
+# Das ist ein spezielles Ziel. Es gibt noch ein paar mehr davon.
+
+# Eine Regel mit einem Phony-Ziel als Voraussetzung wird immer abgearbeitet
+ex0.txt ex1.txt: maker
+
+# Häufige Phony-Ziele sind: all make clean install ...
+
+#-----------------------------------------------------------------------
+# Automatische Variablen & Wildcards
+#-----------------------------------------------------------------------
+
+process: file*.txt # Eine Wildcard um Dateinamen zu vergleichen
+ @echo $^ # $^ ist eine Variable die eine Liste aller
+ # Voraussetzungen enthält.
+ @echo $@ # Namen des Ziels ausgeben.
+ #(Bei mehreren Ziel-Regeln enthält $@ den Verursacher der Abarbeitung
+ #der Regel.)
+ @echo $< # Die erste Voraussetzung aus der Liste
+ @echo $? # Nur die Voraussetzungen, die nicht aktuell sind.
+ @echo $+ # Alle Voraussetzungen inklusive Duplikate (nicht wie Üblich)
+ #@echo $| # Alle 'order only' Voraussetzungen
+
+# Selbst wenn wir die Voraussetzungen der Regel aufteilen, $^ wird sie finden.
+process: ex1.txt file0.txt
+# ex1.txt wird gefunden werden, aber file0.txt wird dedupliziert.
+
+#-----------------------------------------------------------------------
+# Muster
+#-----------------------------------------------------------------------
+
+# Mit Mustern kann man make beibringen wie Dateien in andere Dateien
+# umgewandelt werden.
+
+%.png: %.svg
+ inkscape --export-png $^
+
+# Muster-Vergleichs-Regeln werden nur abgearbeitet, wenn make entscheidet das
+# Ziel zu erzeugen
+
+# Verzeichnis-Pfade werden normalerweise bei Muster-Vergleichs-Regeln ignoriert.
+# Aber make wird versuchen die am besten passende Regel zu verwenden.
+small/%.png: %.svg
+ inkscape --export-png --export-dpi 30 $^
+
+# Make wird die letzte Version einer Muster-Vergleichs-Regel verwenden, die es
+# findet.
+%.png: %.svg
+ @echo this rule is chosen
+
+# Allerdings wird make die erste Muster-Vergleicher-Regel verwenden, die das
+# Ziel erzeugen kann.
+%.png: %.ps
+ @echo this rule is not chosen if *.svg and *.ps are both present
+
+# Make hat bereits ein paar eingebaute Muster-Vergleichs-Regelen. Zum Beispiel
+# weiß Make wie man aus *.c Dateien *.o Dateien erzeugt.
+
+# Ältere Versionen von Make verwenden möglicherweise Suffix-Regeln anstatt
+# Muster-Vergleichs-Regeln.
+.png.ps:
+ @echo this rule is similar to a pattern rule.
+
+# Aktivieren der Suffix-Regel
+.SUFFIXES: .png
+
+#-----------------------------------------------------------------------
+# Variablen
+#-----------------------------------------------------------------------
+# auch Makros genannt.
+
+# Variablen sind im Grunde genommen Zeichenketten-Typen.
+
+name = Ted
+name2="Sarah"
+
+echo:
+ @echo $(name)
+ @echo ${name2}
+ @echo $name # Das funktioniert nicht, wird als $(n)ame behandelt.
+ @echo $(name3) # Unbekannte Variablen werden als leere Zeichenketten behandelt.
+
+# Es git 4 Stellen um Variablen zu setzen.
+# In Reihenfolge der Priorität von höchster zu niedrigster:
+# 1: Befehls-Zeilen Argumente
+# 2: Makefile
+# 3: Shell Umbebungs-Variablen - Make importiert diese automatisch.
+# 3: MAke hat einige vordefinierte Variablen.
+
+name4 ?= Jean
+# Setze die Variable nur wenn es eine gleichnamige Umgebungs-Variable noch
+# nicht gibt.
+
+override name5 = David
+# Verhindert, dass Kommando-Zeilen Argumente diese Variable ändern können.
+
+name4 +=grey
+# Werte an eine Variable anhängen (inkludiert Leerzeichen).
+
+# Muster-Spezifische Variablen Werte (GNU Erweiterung).
+echo: name2 = Sara # Wahr innerhalb der passenden Regel und auch innerhalb
+ # rekursiver Voraussetzungen (ausser wenn es den Graphen zerstören
+ # kann, wenn es zu kompilizert wird!)
+
+# Ein paar Variablen, die von Make automatisch definiert werden.
+echo_inbuilt:
+ echo $(CC)
+ echo ${CXX}
+ echo $(FC)
+ echo ${CFLAGS}
+ echo $(CPPFLAGS)
+ echo ${CXXFLAGS}
+ echo $(LDFLAGS)
+ echo ${LDLIBS}
+
+#-----------------------------------------------------------------------
+# Variablen 2
+#-----------------------------------------------------------------------
+
+# Der erste Typ von Variablen wird bei jeder Verwendung ausgewertet.
+# Das kann aufwendig sein, daher exisitert ein zweiter Typ von Variablen.
+# Diese werden nur einmal ausgewertet. (Das ist eine GNU make Erweiterung)
+
+var := hello
+var2 ::= $(var) hello
+#:= und ::= sind äquivalent.
+
+# Diese Variablen werden prozedural ausgwertet (in der Reihenfolge in der sie
+# auftauchen), die stehen daher im wiederspruch zum Rest der Sprache!
+
+# Das funktioniert nicht
+var3 ::= $(var4) and good luck
+var4 ::= good night
+
+#-----------------------------------------------------------------------
+# Funktionen
+#-----------------------------------------------------------------------
+
+# Make verfügt über eine Vielzahl von Funktionen.
+
+sourcefiles = $(wildcard *.c */*.c)
+objectfiles = $(patsubst %.c,%.o,$(sourcefiles))
+
+# Das Format ist $(func arg0,arg1,arg2...)
+
+# Ein paar Beispiele
+ls: * src/*
+ @echo $(filter %.txt, $^)
+ @echo $(notdir $^)
+ @echo $(join $(dir $^),$(notdir $^))
+
+#-----------------------------------------------------------------------
+# Direktiven
+#-----------------------------------------------------------------------
+
+# Inkludiere andere Makefile, sehr praktisch für platformspezifischen Code
+include foo.mk
+
+sport = tennis
+# Konditionale kompiliereung
+report:
+ifeq ($(sport),tennis)
+ @echo 'game, set, match'
+else
+ @echo "They think it's all over; it is now"
+endif
+
+# Es gibt auch ifneq, ifdef, ifndef
+
+foo = true
+
+ifdef $(foo)
+bar = 'hello'
+endif
+```
+
+
+### Mehr Resourcen
+
++ [gnu make documentation](https://www.gnu.org/software/make/manual/)
++ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/)
++ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)
+
diff --git a/de-de/nix-de.html.markdown b/de-de/nix-de.html.markdown
index ffe8dffc..a55a91c7 100644
--- a/de-de/nix-de.html.markdown
+++ b/de-de/nix-de.html.markdown
@@ -356,6 +356,9 @@ with builtins; [
* [Susan Potter - Nix Cookbook - Nix By Example]
(https://ops.functionalalgebra.com/nix-by-example/)
-
+
+* [Zero to Nix - Nix Tutorial]
+ (https://zero-to-nix.com/)
+
* [Rommel Martinez - A Gentle Introduction to the Nix Family]
(https://web.archive.org/web/20210121042658/https://ebzzry.io/en/nix/#nix)
diff --git a/de-de/pug-de.html.markdown b/de-de/pug-de.html.markdown
index 10172d6b..ce31c648 100644
--- a/de-de/pug-de.html.markdown
+++ b/de-de/pug-de.html.markdown
@@ -205,4 +205,4 @@ mixin comment(name, kommentar)
### Zusätzliche Ressourcen
- [The Site](https://pugjs.org/)
- [The Docs](https://pugjs.org/api/getting-started.html)
-- [Github Repo](https://github.com/pugjs/pug)
+- [GitHub Repo](https://github.com/pugjs/pug)
diff --git a/de-de/pyqt-de.html.markdown b/de-de/pyqt-de.html.markdown
index 93ee20d4..3b9b6ebb 100644
--- a/de-de/pyqt-de.html.markdown
+++ b/de-de/pyqt-de.html.markdown
@@ -21,7 +21,7 @@ Diese Version wurde in pyqt erstellt.
```python
import sys
from PyQt4 import QtGui
-
+
def window():
# Erschafft ein Anwendungsobjekt.
app = QtGui.QApplication(sys.argv)
@@ -48,10 +48,10 @@ if __name__ == '__main__':
Damit wir weitere fortgeschrittene Funktionen in **pyqt** verwenden können,
müssen wir anfangen zusätzliche Elemente zu bauen.
-Hier zeigen wir wie man eine Dialog Popup Box einführt.
+Hier zeigen wir wie man eine Dialog Popup Box einführt.
Diese ist nützlich, um den Benutzer eine Entscheidung zu bestätigen oder um Informationen anzuzeigen.
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
@@ -70,7 +70,7 @@ def window():
w.setWindowTitle("PyQt Dialog")
w.show()
sys.exit(app.exec_())
-
+
# Diese Funktion soll ein Dialogfenster mit einem Knopf erschaffen.
# Der Knopf wartet bis er geklickt wird und beendet das Programm
def showdialog():
diff --git a/de-de/rst-de.html.markdown b/de-de/rst-de.html.markdown
index 072299f5..0eb2b6bf 100644
--- a/de-de/rst-de.html.markdown
+++ b/de-de/rst-de.html.markdown
@@ -86,14 +86,14 @@ erstellt werden, aber ich empfehle dir dafür die komplette Dokumentation zu les
Es gibt mehrere Möglichkeiten um Links zu machen:
-- Wenn man einen Unterstrich hinter einem Wort hinzufügt: Github_ Zusätzlich
+- Wenn man einen Unterstrich hinter einem Wort hinzufügt: GitHub_ Zusätzlich
muss man die Zielurl nach dem Text hinzufügen.
(Dies hat den Vorteil, dass man keine unnötigen Urls in lesbaren Text einfügt.
- Wenn man die vollständige Url eingibt : https://github.com/
(Dies wird automatisch in ein Link konvertiert.)
-- Wenn man es mehr Markdown ähnlich eingibt: `Github <https://github.com/>`_ .
+- Wenn man es mehr Markdown ähnlich eingibt: `GitHub <https://github.com/>`_ .
-.. _Github https://github.com/
+.. _GitHub https://github.com/
```
diff --git a/de-de/sql-de.html.markdown b/de-de/sql-de.html.markdown
new file mode 100644
index 00000000..9cb95666
--- /dev/null
+++ b/de-de/sql-de.html.markdown
@@ -0,0 +1,116 @@
+---
+language: SQL
+filename: learnsql-de.sql
+contributors:
+ - ["Bob DuCharme", "http://bobdc.com/"]
+translators:
+ - ["denniskeller", "https://github.com/denniskeller"]
+lang: de-de
+---
+
+Die Structured Query Language (SQL) ist eine ISO Standardsprache zum Erstellen und Arbeiten mit Datenbanken, die in einem Set von Tabellen gespeichert sind. Implementiereungen fügen in der Regel eigene Erweiterungen zur Sprache hinzu; [Der Vergleich von verschiedenen SQL Implementierungen](http://troels.arvin.dk/db/rdbms/) ist eine gute Referenz für Produktunterschiede.
+
+Implementierungen bieten typischerweise eine Eingabeaufforderung, in den du die hier gezeigten Befehle interaktiv eingeben kannst. Sie bieten auch einen Weg, um Serien von Befehlen in einer Skript auszuführen. (Die Anzeige, dass du fertig mit der interaktiven Eingabeaufforderung bist, ist ein gutes Beispiel für etwas, was nicht standardisiert ist. Die meisten SQL Implementierungen unterstützen die Schlüsselwörter QUIT, EXIT oder beides.
+Einige dieser Beispielbefehle gehen davon aus, dass sie die [MySQL employee sample database](https://dev.mysql.com/doc/employee/en/), verfügbar auf [github](https://github.com/datacharmer/test_db), schon geladen wurde. Die Github Dateien sind Skripte von Befehlen, ähnlich wie die entsprechenden Befehle unten, die Tabellen mit Daten über die Mitarbeiter einer fiktionale Firma erstellen und füllen. Die Syntax für die Ausführung dieser Skripte hängt von der verwendeten SQL-Implementierung ab. Ein Dienstprogramm, das man über die Betriebssystemeingabeaufforderung ausführen kann, ist typisch.
+
+
+```sql
+-- Kommentare starten mit zwei Bindestrichen. Jeder Befehl endet mit einem Semikolon.
+
+-- SQL unterscheidet nicht zwischen Groß- und Kleinschreibung bei
+-- Schlüsselwörtern. Die Beispielbefehle folgen der Konvention der
+-- Schreibweise in Großbuchstaben, damit sie leichter von Datebank-,
+-- Tabellen- und Spaltennamen zu unterscheiden sind.
+
+-- Erstellen und Löschen einer Datenbank. Bei Datenbank- und Tabellennamen
+-- wird zwischen Groß- und Kleinschreibung unterschieden.
+CREATE DATABASE someDatabase;
+DROP DATABASE someDatabase;
+
+-- Liste verfügbare Datenbanken.
+SHOW DATABASES;
+
+-- Verwende eine bestimmte Datenbank.
+USE employees;
+
+-- Wähle alle Zeilen und Spalten aus der Tabelle departmens aus der aktuellen
+-- Datenbank aus.
+-- Das Standardverhalten für den Interpreter ist die Ergebnisse auf
+-- dem Bildschirm zu scrollen.
+SELECT * FROM departments;
+
+-- Hole dir alle Zeilen aus der departments Tabelle,
+-- aber nur die dept_no und die dept_name Spalten.
+-- Das Aufteilen von Befehlen auf mehrere Zeilen ist in Ordnung.
+SELECT dept_no,
+ dept_name FROM departments;
+
+-- Hole dir alle departments Spalten, aber nur 5 Zeilen.
+SELECT * FROM departments LIMIT 5;
+
+-- Hole dir die dept_name Spaltenwerte aus der departments Tabelle,
+-- in der der Wert dept_name die Teilzeichenfolge 'en' hat.
+SELECT dept_name FROM departments WHERE dept_name LIKE '%en%';
+
+-- Hole dir alle Spalten von der departments Tabelle, in der die dept_name
+-- Spalte mit einem 'S' beginnt und exakt 4 Zeichen danach besitzt.
+SELECT * FROM departments WHERE dept_name LIKE 'S____';
+
+-- Wähle die Titelwerte aus der Titeltabelle, aber zeige keine Duplikate an.
+SELECT DISTINCT title FROM titles;
+
+-- Das Gleiche wie oben, aber sortiert nach den Titelwerten, mit Beachtung
+-- der Groß und Kleinschreibung.
+SELECT DISTINCT title FROM titles ORDER BY title;
+
+-- Zeige die Anzahl der Zeilen in der departments Tabelle an.
+SELECT COUNT(*) FROM departments;
+
+-- Zeige die Anzahl der Zeilen in der departments Tabelle an, die 'en' als
+-- Teilezeichenkette des Wertes dept_name haben.
+SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%';
+
+-- Eine Vereinigung von Informatione von mehreren Tabellen:
+-- Die titles Tabelle zeigt, wer welche Jobtitel hatte, wer welche Mitarbeiter-
+-- nummer hat, von welchen Startdatum und zu welchen Enddatum
+-- Wir rufen diese Information ab, aber anstelle der Mitarbeiternummer,
+-- verwenden wir die Mitarbeiternummer als Querverweis auf die empoyees Tabelle
+-- um die die Vor- und Nachnamen jedes Mitarbeiters zu erhalten.
+-- (und nur 10 Reihen)
+SELECT employees.first_name, employees.last_name,
+ titles.title, titles.from_date, titles.to_date
+FROM titles INNER JOIN employees ON
+ employees.emp_no = titles.emp_no LIMIT 10;
+
+-- Liste alle Tabellen in allen Datenbanken auf. Verschiedene Implementierungen
+-- stellen typischerweise einen eigenen Abkürzungsbefehl zur Verfügung für
+-- die aktuell verwendete Datenbank.
+SELECT * FROM INFORMATION_SCHEMA.TABLES
+WHERE TABLE_TYPE='BASE TABLE';
+
+-- Erstelle eine Tabelle in der aktuell verwedeten Datenbank
+-- mit dem Namen tablename1, in der die beiden Spalten angezeigt werden
+-- Es gibt viele weiteren Optionen, wie man die Spalten spezifizieren kann,
+-- wie z.B. deren Datentyp.
+CREATE TABLE tablename1 (fname VARCHAR(20), lname VARCHAR(20));
+
+-- Füge eine Zeile mit Daten in die Tabelle tablename1. Dies setzt voraus,
+-- das die Tabelle so definiert worden ist, dass sie die geeigneten
+-- Werte akzeptiert.
+INSERT INTO tablename1 VALUES('Richard','Mutt');
+
+-- Verändere den fname Wert zu 'John' für alle Zeilen,
+-- die einen lname Wert von 'Mutt' haben.
+UPDATE tablename1 SET fname='John' WHERE lname='Mutt';
+
+-- Lösche Zeilen aus der tablename1 Tabelle,
+-- deren lname Wert mit dem Wert 'M' beginnen.
+DELETE FROM tablename1 WHERE lname like 'M%';
+
+-- Lösche alle Zeilen von der tablename1 Tabelle, hinterlasse nur eine leere
+-- Tabelle.
+DELETE FROM tablename1;
+
+-- Lösche die gesamte tablename1 Tabelle.
+DROP TABLE tablename1;
+```
diff --git a/de-de/swift-de.html.markdown b/de-de/swift-de.html.markdown
index 5828b5d3..c4da99f5 100644
--- a/de-de/swift-de.html.markdown
+++ b/de-de/swift-de.html.markdown
@@ -13,7 +13,7 @@ lang: de-de
Swift ist eine Programmiersprache von Apple für die Entwicklung von iOS und macOS Applikationen. Swift wurde 2014 zu Apples WWDC Entwicklerkonferenz vorgestellt und wurde mit dem Ziel entwickelt, fehlerträchtigen Code zu vermeiden sowie mit Objective-C zu koexistieren. Es wird mit dem LLVM Compiler gebaut und ist ab Xcode 6+ verfügbar.
-Das offizielle [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) Buch von Apple ist kostenlos via iBooks verfügbar.
+Das offizielle [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) Buch von Apple ist kostenlos via Apple Books verfügbar.
Außerdem hilfreich ist Apples [Getting Started Guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), ein guter Einstiegspunkt mit komplettem Swift-Tutorial.
diff --git a/de-de/visualbasic-de.html.markdown b/de-de/visualbasic-de.html.markdown
index a0dde471..6194e906 100644
--- a/de-de/visualbasic-de.html.markdown
+++ b/de-de/visualbasic-de.html.markdown
@@ -8,7 +8,7 @@ filename: learnvisualbasic-de.vb
lang: de-de
---
-```
+```visualbasic
Module Modul1
Sub Main()
diff --git a/docker.html.markdown b/docker.html.markdown
index 17f803f4..ec6abe7e 100644
--- a/docker.html.markdown
+++ b/docker.html.markdown
@@ -1,281 +1,281 @@
----
-category: tool
-tool: docker
-filename: docker.bat
-contributors:
- - ["Ruslan López", "http://javapro.org/"]
- - ["Michael Chen", "https://github.com/ML-Chen"]
- - ["Akshita Dixit", "https://github.com/akshitadixit"]
- - ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"]
----
-
-Docker is a tool that helps you build, test, ship and run applications
-seamlessly across various machines. It replicates the environment our software
-needs on any machine. You can get Docker for your machine from
-https://docs.docker.com/get-docker/
-
-It has grown in popularity over the last decade due to being lightweight and
-fast as compared to virtual-machines that are bulky and slow. Unlike VMs, docker
-does not need a full blown OS of its own to be loaded to start and does not
-compete for resources other than what the application it is running will use.
-VMs on the other hand are pretty resource intensive on our processors, disks and
-memory hence running multiple VMs for various applications becomes a challenge
-in a limited capacity architecture.
-
-<pre>
-┌────────────────────────┐ ┌───────────────────────┐
-│ ┌───────────┐ │ │ ┌───────────┐ │
-│ │ App │ │ │ │ App │ │
-│ └───────────┘ │ │ └───────────┘ │
-│ ┌────────┐ ┌────────┐ │ │ ┌────────┐ ┌───────┐ │
-│ │ Libs │ │ Deps │ │ │ │ Libs │ │ Deps │ │
-│ └────────┘ └────────┘ │ │ └────────┘ └───────┘ │
-│ ┌───────────────────┐ │ │ ┌──────────────────┐ │
-│ │ Guest OS │ │ │ │ Guest OS │ │
-│ └───────────────────┘ │ │ └──────────────────┘ │
-│ VM1 │ │ VM2 │
-└────────────────────────┘ └───────────────────────┘
-┌──────────────────────────────────────────────────┐
-│ Hypervisor │
-└──────────────────────────────────────────────────┘
-┌──────────────────────────────────────────────────┐
-│ Host OS │
-└──────────────────────────────────────────────────┘
-┌──────────────────────────────────────────────────┐
-│ Hardware Infrastructure │
-└──────────────────────────────────────────────────┘
- (VM based architecture)
-
-┌────────────────────────┐ ┌───────────────────────┐
-│ ┌───────────┐ │ │ ┌───────────┐ │
-│ │ App │ │ │ │ App │ │
-│ └───────────┘ │ │ └───────────┘ │
-│ ┌────────┐ ┌────────┐ │ │ ┌────────┐ ┌───────┐ │
-│ │ Libs │ │ Deps │ │ │ │ Libs │ │ Deps │ │
-│ └────────┘ └────────┘ │ │ └────────┘ └───────┘ │
-│ Container1 │ │ Container2 │
-└────────────────────────┘ └───────────────────────┘
-┌──────────────────────────────────────────────────┐
-│ Docker │
-└──────────────────────────────────────────────────┘
-┌──────────────────────────────────────────────────┐
-│ OS │
-└──────────────────────────────────────────────────┘
-┌──────────────────────────────────────────────────┐
-│ Hardware Infrastructure │
-└──────────────────────────────────────────────────┘
- (Docker based architecture)
-
-</pre>
-
-Couple of terms we will encounter frequently are Docker Images and Docker
-Containers. Images are packages or templates of containers all stored in a
-container registry such as [Docker Hub](https://hub.docker.com/). Containers
-are standalone, executable instances of these images which include code,
-runtime, system tools, system libraries and settings - everything required to
-get the software up and running. Coming to Docker, it follows a client-server
-architecture wherein the CLI client communicates with the server component,
-which here is, the Docker Engine using RESTful API to issue commands.
-
-## The Docker CLI
-```bash
-# after installing Docker from https://docs.docker.com/get-docker/
-# To list available commands, either run `docker` with no parameters or execute
-# `docker help`
-$ docker
-
->>> docker [OPTIONS] COMMAND [ARG...]
- docker [ --help | -v | --version ]
-
- A self-sufficient runtime for containers.
-
- Options:
- --config string Location of client config files (default "/root/.docker")
- -c, --context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use")
- -D, --debug Enable debug mode
- --help Print usage
- -H, --host value Daemon socket(s) to connect to (default [])
- -l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
- --tls Use TLS; implied by --tlsverify
- --tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem")
- --tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem")
- --tlskey string Path to TLS key file (default "/root/.docker/key.pem")
- --tlsverify Use TLS and verify the remote
- -v, --version Print version information and quit
-
- Commands:
- attach Attach to a running container
- # […]
-
-$ docker run hello-world
-# `docker run <container-name>` is used to run a container, it will pull the
-# images from Docker Hub if they don't already exist in your system. Here the
-# docker client connects to the daemon which in turn pulls the "hello-world"
-# image from the Docker Hub. The daemon then builds a new container from the
-# image which runs the executable that produces the output streamed back to the
-# client that we see on our terminals.
-
-$ docker run -d ubuntu sleep 60s
-# The -d (or --detach) flag is when we want to run a container in the background
-# and return back to the terminal. Here we detach an ubuntu container from the
-# terminal, the output should be the id and the command exits. If we check
-# running containers, we should still see ours there:
-# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
-# 133261b4894a ubuntu "sleep 60s" 3 seconds ago Up 2 seconds vigorous_gould
-
-$ docker run <container-id> -p 3000:8000
-# The -p (or --publish) flag is used to expose port 8000 inside the container to
-# port 3000 outside the container. This is because the app inside the container
-# runs in isolation, hence the port 8000 where the app runs is private to the
-# container.
-
-$ docker run -i
-# or
-$ docker run -it
-# Docker runs our containers in a non-interactive mode i.e. they do not accept
-# inputs or work dynamically while running. The -i flag keeps input open to the
-# container, and the -t flag creates a pseudo-terminal that the shell can attach
-# to (can be combined as -it)
-
-$ docker ps -a
-# The `docker ps` command only shows running containers by default. To see all
-# containers, use the -a (or --all) flag
-# Running the above command should output something similar in the terminal:
-# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
-# 82f84bf6912b hello-world "/hello" 9 minutes ago Exited (0) 9 minutes ago eloquent_sammet
-
-
-$ docker stop hello-world
-# or
-$ docker start hello-world
-# The stop command simply stops one or more containers, and the start command
-# starts the container(s) up again! `docker start -a ubuntu` will attach our
-# detached container back to the terminal i.e. runs in the foreground
-
-$ docker create alpine
-# `docker create` creates a new container for us with the image specified (here,
-# alpine), the container does not auto-start unlike `docker run`. This command
-# is used to set up a container configuration and then `docker start` to shoot
-# it up when required. Note that the status is "Created":
-# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
-# 4c71c727c73d alpine "/bin/sh" 29 seconds ago Created naughty_ritchie
-
-$ docker rm 82f84
-# Removes one or more containers using their container ID.
-# P.S.: we can use only the first few characters of the entire ID to identify
-# containers
-
-$ docker images
-# Displays all images and their information, created here means the latest image
-# tag updated on Docker Hub:
-# REPOSITORY TAG IMAGE ID CREATED SIZE
-# ubuntu latest a8780b506fa4 9 days ago 77.8MB
-# alpine latest 9c6f07244728 3 months ago 5.54MB
-# hello-world latest feb5d9fea6a5 13 months ago 13.3kB
-
-$ docker rmi
-# Removes one or more images from your system which do not have their instances
-# (or containers as we know them) running. If the image has an attached
-# container, either delete the container first or use the -f (or --force) flag
-# to forcefully delete both the container and image.
-
-$ docker pull busybox
-# The pull command downloads the specified image on our system from Docker Hub.
-
-$ docker exec -it 7b272 bash
-# This command is used to run a command in the running container's default
-# directory. Here 7b272 was our ubuntu container and the above command would
-# help us interact with the container by opening a bash session.
-
-$ docker logs <container-id>
-# Displays the information logged by the specified container
-# root@7b27222e4bb7:/# whoami
-# root
-# root@7b27222e4bb7:/# pwd
-# /
-# root@7b27222e4bb7:/# ls
-# bin boot dev etc home lib lib32 lib64 libx3 srv sys tmp usr var
-# root@7b27222e4bb7:/# exit
-# exit
-
-# More commands can be found at https://docs.docker.com/engine/reference/commandline/docker/
-```
-## The Dockerfile
-The Dockerfile is a blueprint of a Docker image. We can mention the artifacts
-from our application along with their configurations into this file in the
-specific syntax to let anyone create a Docker image of our application.
-
-### A few things to keep in mind:
-* It is always strictly named `Dockerfile` without any extensions
-* We have to build our custom image on top of some already available Docker base
-image. (there is an empty image called `scratch` which literally lets you build
-an image from scratch)
-* All capitalised commands are part of the syntax, they are not case-sensitive
-but used like a convention
-* Below is a sample Dockerfile but you can read in depth from the [official docs](https://docs.docker.com/engine/reference/builder/).
-
-```Dockerfile
-FROM <base-image>
-# define base image
-
-ENV USERNAME='admin'\
- PWD='****'
-# optionally define environmental variables
-
-RUN apt-get update
-# run linux commands inside container env, does not affect host env
-# This executes during the time of image creation
-
-COPY <src> <target>
-# executes on the host, copies files from src (usually on the host) to target
-# on the container
-
-ENTRYPOINT ["some-script.sh"]
-# executes an entire script as an entrypoint
-
-CMD [<args>,...]
-# always part of dockerfile, introduces entry point linux command e.g.
-# `CMD node server.js`
-# This executes after image creation only when the container from the image
-# is running.
-```
-### Build your images
-Use the `docker build` command after wrapping your application into a Docker
-image to run ( or build) it.
-
-```bash
-
-$ docker build <path-to-dockerfile>
-# used to build an image from the specified Dockerfile
-# instead of path we could also specify a URL
-# -t tag is optional and used to name and tag your images for e.g.
-# `$ docker build -t my-image:0.1 ./home/app`
-# rebuild images everytime you make changes in the dockerfile
-```
-
-## Push your image to DockerHub
-If you want your application's Docker image to be made publicly available for
-any Docker user, you might wanna push it to the [Docker Hub](https://hub.docker.com/) which is a
-registry of Docker images. Make sure you have an account with a username and
-password on Docker Hub.
-
-When pushing an image to Docker Hub, we must specify our Docker Hub username
-as part of the source image name. We need to create the target image with the
-tag name of username/image-name much like GitHub repositories.
-
-```bash
-$ docker login
-# to login to Docker Hub using your username and password
-
-$ docker tag <src-image>[:<src-tag>] <target-image>[:<target-tag>]
-# this tags a local src-image to a public target-image
-# e.g. `docker tag my-sample-app:1.0.0 akshitadixit/my-sample-app`
-# if tags are not specified, they're defaulted to `latest`
-
-$ docker push <target-image>[:<target-tag>]
-# uploads our image to Docker Hub
-# e.g. `docker push akshitadixit/my-sample-app`
-# this image will be accessible under your profile's repositories as
-# `https://hub.docker.com/r/username/image-name`
-
-```
+---
+category: tool
+tool: docker
+filename: docker.bat
+contributors:
+ - ["Ruslan López", "http://javapro.org/"]
+ - ["Michael Chen", "https://github.com/ML-Chen"]
+ - ["Akshita Dixit", "https://github.com/akshitadixit"]
+ - ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"]
+---
+
+Docker is a tool that helps you build, test, ship and run applications
+seamlessly across various machines. It replicates the environment our software
+needs on any machine. You can get Docker for your machine from
+https://docs.docker.com/get-docker/
+
+It has grown in popularity over the last decade due to being lightweight and
+fast as compared to virtual-machines that are bulky and slow. Unlike VMs, docker
+does not need a full blown OS of its own to be loaded to start and does not
+compete for resources other than what the application it is running will use.
+VMs on the other hand are pretty resource intensive on our processors, disks and
+memory hence running multiple VMs for various applications becomes a challenge
+in a limited capacity architecture.
+
+<pre>
+┌────────────────────────┐ ┌───────────────────────┐
+│ ┌───────────┐ │ │ ┌───────────┐ │
+│ │ App │ │ │ │ App │ │
+│ └───────────┘ │ │ └───────────┘ │
+│ ┌────────┐ ┌────────┐ │ │ ┌────────┐ ┌───────┐ │
+│ │ Libs │ │ Deps │ │ │ │ Libs │ │ Deps │ │
+│ └────────┘ └────────┘ │ │ └────────┘ └───────┘ │
+│ ┌───────────────────┐ │ │ ┌──────────────────┐ │
+│ │ Guest OS │ │ │ │ Guest OS │ │
+│ └───────────────────┘ │ │ └──────────────────┘ │
+│ VM1 │ │ VM2 │
+└────────────────────────┘ └───────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ Hypervisor │
+└──────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ Host OS │
+└──────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ Hardware Infrastructure │
+└──────────────────────────────────────────────────┘
+ (VM based architecture)
+
+┌────────────────────────┐ ┌───────────────────────┐
+│ ┌───────────┐ │ │ ┌───────────┐ │
+│ │ App │ │ │ │ App │ │
+│ └───────────┘ │ │ └───────────┘ │
+│ ┌────────┐ ┌────────┐ │ │ ┌────────┐ ┌───────┐ │
+│ │ Libs │ │ Deps │ │ │ │ Libs │ │ Deps │ │
+│ └────────┘ └────────┘ │ │ └────────┘ └───────┘ │
+│ Container1 │ │ Container2 │
+└────────────────────────┘ └───────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ Docker │
+└──────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ OS │
+└──────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ Hardware Infrastructure │
+└──────────────────────────────────────────────────┘
+ (Docker based architecture)
+
+</pre>
+
+Couple of terms we will encounter frequently are Docker Images and Docker
+Containers. Images are packages or templates of containers all stored in a
+container registry such as [Docker Hub](https://hub.docker.com/). Containers
+are standalone, executable instances of these images which include code,
+runtime, system tools, system libraries and settings - everything required to
+get the software up and running. Coming to Docker, it follows a client-server
+architecture wherein the CLI client communicates with the server component,
+which here is, the Docker Engine using RESTful API to issue commands.
+
+## The Docker CLI
+```bash
+# after installing Docker from https://docs.docker.com/get-docker/
+# To list available commands, either run `docker` with no parameters or execute
+# `docker help`
+$ docker
+
+>>> docker [OPTIONS] COMMAND [ARG...]
+ docker [ --help | -v | --version ]
+
+ A self-sufficient runtime for containers.
+
+ Options:
+ --config string Location of client config files (default "/root/.docker")
+ -c, --context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use")
+ -D, --debug Enable debug mode
+ --help Print usage
+ -H, --host value Daemon socket(s) to connect to (default [])
+ -l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
+ --tls Use TLS; implied by --tlsverify
+ --tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem")
+ --tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem")
+ --tlskey string Path to TLS key file (default "/root/.docker/key.pem")
+ --tlsverify Use TLS and verify the remote
+ -v, --version Print version information and quit
+
+ Commands:
+ attach Attach to a running container
+ # […]
+
+$ docker run hello-world
+# `docker run <container-name>` is used to run a container, it will pull the
+# images from Docker Hub if they don't already exist in your system. Here the
+# docker client connects to the daemon which in turn pulls the "hello-world"
+# image from the Docker Hub. The daemon then builds a new container from the
+# image which runs the executable that produces the output streamed back to the
+# client that we see on our terminals.
+
+$ docker run -d ubuntu sleep 60s
+# The -d (or --detach) flag is when we want to run a container in the background
+# and return back to the terminal. Here we detach an ubuntu container from the
+# terminal, the output should be the id and the command exits. If we check
+# running containers, we should still see ours there:
+# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
+# 133261b4894a ubuntu "sleep 60s" 3 seconds ago Up 2 seconds vigorous_gould
+
+$ docker run <container-id> -p 3000:8000
+# The -p (or --publish) flag is used to expose port 8000 inside the container to
+# port 3000 outside the container. This is because the app inside the container
+# runs in isolation, hence the port 8000 where the app runs is private to the
+# container.
+
+$ docker run -i
+# or
+$ docker run -it
+# Docker runs our containers in a non-interactive mode i.e. they do not accept
+# inputs or work dynamically while running. The -i flag keeps input open to the
+# container, and the -t flag creates a pseudo-terminal that the shell can attach
+# to (can be combined as -it)
+
+$ docker ps -a
+# The `docker ps` command only shows running containers by default. To see all
+# containers, use the -a (or --all) flag
+# Running the above command should output something similar in the terminal:
+# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
+# 82f84bf6912b hello-world "/hello" 9 minutes ago Exited (0) 9 minutes ago eloquent_sammet
+
+
+$ docker stop hello-world
+# or
+$ docker start hello-world
+# The stop command simply stops one or more containers, and the start command
+# starts the container(s) up again! `docker start -a ubuntu` will attach our
+# detached container back to the terminal i.e. runs in the foreground
+
+$ docker create alpine
+# `docker create` creates a new container for us with the image specified (here,
+# alpine), the container does not auto-start unlike `docker run`. This command
+# is used to set up a container configuration and then `docker start` to shoot
+# it up when required. Note that the status is "Created":
+# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
+# 4c71c727c73d alpine "/bin/sh" 29 seconds ago Created naughty_ritchie
+
+$ docker rm 82f84
+# Removes one or more containers using their container ID.
+# P.S.: we can use only the first few characters of the entire ID to identify
+# containers
+
+$ docker images
+# Displays all images and their information, created here means the latest image
+# tag updated on Docker Hub:
+# REPOSITORY TAG IMAGE ID CREATED SIZE
+# ubuntu latest a8780b506fa4 9 days ago 77.8MB
+# alpine latest 9c6f07244728 3 months ago 5.54MB
+# hello-world latest feb5d9fea6a5 13 months ago 13.3kB
+
+$ docker rmi
+# Removes one or more images from your system which do not have their instances
+# (or containers as we know them) running. If the image has an attached
+# container, either delete the container first or use the -f (or --force) flag
+# to forcefully delete both the container and image.
+
+$ docker pull busybox
+# The pull command downloads the specified image on our system from Docker Hub.
+
+$ docker exec -it 7b272 bash
+# This command is used to run a command in the running container's default
+# directory. Here 7b272 was our ubuntu container and the above command would
+# help us interact with the container by opening a bash session.
+
+$ docker logs <container-id>
+# Displays the information logged by the specified container
+# root@7b27222e4bb7:/# whoami
+# root
+# root@7b27222e4bb7:/# pwd
+# /
+# root@7b27222e4bb7:/# ls
+# bin boot dev etc home lib lib32 lib64 libx3 srv sys tmp usr var
+# root@7b27222e4bb7:/# exit
+# exit
+
+# More commands can be found at https://docs.docker.com/engine/reference/commandline/docker/
+```
+## The Dockerfile
+The Dockerfile is a blueprint of a Docker image. We can mention the artifacts
+from our application along with their configurations into this file in the
+specific syntax to let anyone create a Docker image of our application.
+
+### A few things to keep in mind:
+* It is always strictly named `Dockerfile` without any extensions
+* We have to build our custom image on top of some already available Docker base
+image. (there is an empty image called `scratch` which literally lets you build
+an image from scratch)
+* All capitalised commands are part of the syntax, they are not case-sensitive
+but used like a convention
+* Below is a sample Dockerfile but you can read in depth from the [official docs](https://docs.docker.com/engine/reference/builder/).
+
+```Dockerfile
+FROM <base-image>
+# define base image
+
+ENV USERNAME='admin'\
+ PWD='****'
+# optionally define environmental variables
+
+RUN apt-get update
+# run linux commands inside container env, does not affect host env
+# This executes during the time of image creation
+
+COPY <src> <target>
+# executes on the host, copies files from src (usually on the host) to target
+# on the container
+
+ENTRYPOINT ["some-script.sh"]
+# executes an entire script as an entrypoint
+
+CMD [<args>,...]
+# always part of dockerfile, introduces entry point linux command e.g.
+# `CMD node server.js`
+# This executes after image creation only when the container from the image
+# is running.
+```
+### Build your images
+Use the `docker build` command after wrapping your application into a Docker
+image to run ( or build) it.
+
+```bash
+
+$ docker build <path-to-dockerfile>
+# used to build an image from the specified Dockerfile
+# instead of path we could also specify a URL
+# -t tag is optional and used to name and tag your images for e.g.
+# `$ docker build -t my-image:0.1 ./home/app`
+# rebuild images everytime you make changes in the dockerfile
+```
+
+## Push your image to DockerHub
+If you want your application's Docker image to be made publicly available for
+any Docker user, you might wanna push it to the [Docker Hub](https://hub.docker.com/) which is a
+registry of Docker images. Make sure you have an account with a username and
+password on Docker Hub.
+
+When pushing an image to Docker Hub, we must specify our Docker Hub username
+as part of the source image name. We need to create the target image with the
+tag name of username/image-name much like GitHub repositories.
+
+```bash
+$ docker login
+# to login to Docker Hub using your username and password
+
+$ docker tag <src-image>[:<src-tag>] <target-image>[:<target-tag>]
+# this tags a local src-image to a public target-image
+# e.g. `docker tag my-sample-app:1.0.0 akshitadixit/my-sample-app`
+# if tags are not specified, they're defaulted to `latest`
+
+$ docker push <target-image>[:<target-tag>]
+# uploads our image to Docker Hub
+# e.g. `docker push akshitadixit/my-sample-app`
+# this image will be accessible under your profile's repositories as
+# `https://hub.docker.com/r/username/image-name`
+
+```
diff --git a/el-gr/haskell-gr.html.markdown b/el-gr/haskell-gr.html.markdown
new file mode 100644
index 00000000..d2fed85a
--- /dev/null
+++ b/el-gr/haskell-gr.html.markdown
@@ -0,0 +1,476 @@
+---
+language: Haskell
+filename: haskell-gr.html.markdown
+contributors:
+ - ["Miltiadis Stouras", "https://github.com/mstou"]
+---
+
+Η Haskell σχεδιάστηκε για να είναι μια πρακτική, αγνή συναρτησιακή γλώσσα προγραμματισμού.
+Είναι διάσημη για τα monads και το σύστημα τύπων της, αλλά χρησιμοποιείται από πολλούς
+κυρίως για την κομψότητά της. Προσωπικά θεωρώ ότι είναι από τις πιο όμορφες, αν όχι
+η πιο όμορφη, γλώσσα προγραμματισμού.
+
+```haskell
+-- Τα σχόλια μιας γραμμής ξεκινούν με 2 παύλες.
+{- Ενώ τα σχόλια πολλών γραμμών βρίσκονται
+μέσα σε blocks σαν αυτό
+-}
+
+----------------------------------------------------
+-- 1. Πρωτόγονοι Τύποι Δεδομένων (Primitive datatype) και Τελεστές
+----------------------------------------------------
+
+-- Οι αριθμοί είναι ένα primitive datatype
+3 -- 3
+
+-- Και οι τελεστές κάνουν αυτό που θα περιμέναμε
+1 + 1 -- 2
+8 - 1 -- 7
+10 * 2 -- 20
+35 / 5 -- 7.0
+
+-- Η καθιερωμένη διαίρεση δεν είναι ακέραια
+35 / 4 -- 8.75
+
+-- Η ακέραια διαίρεση γίνεται με την συνάρτηση div
+35 `div` 4 -- 8
+
+-- Και οι boolean μεταβλητές ειναι primitives
+True
+False
+
+-- Πράξεις με booleans
+not True -- False
+not False -- True
+1 == 1 -- True
+1 /= 1 -- False
+1 < 10 -- True
+
+-- Στα παραπάνω παραδείγματα, το `not` είναι μια συνάρτηση που παίρνει ένα όρισμα
+-- Στην Haskell δεν χρειάζονται παρενθέσεις για τις κλήσεις συναρτήσεων, όλες οι παράμετροι
+-- γράφονται με κενά αμέσως μετά την συνάρτηση. Στην γενική περίπτωση,
+-- η κλήση συνάρτησης μοιάζει κάπως έτσι: func arg1 arg2 arg3...
+-- Για το πως να ορίσετε τις δικές σας συναρτήσεις διαβάστε το κεφάλαιο των συναρτήσεων παρακάτω
+
+-- Συμβολοσειρές και χαρακτήρες
+"This is a string." -- συμβολοσειρά
+'a' -- χαρακτήρας
+'You cant use single quotes for strings.' -- error!
+-- δεν μπορούμε να γράψουμε συμβολοσειρές ανάμεσα από ''
+
+-- Οι συμβολοσειρές μπορούν να συννενωθούν με την χρήση του τελεστή ++
+"Hello " ++ "world!" -- "Hello world!"
+
+-- Η συμβολοσειρά είναι ουσιαστικά μια λίστα χαρακτήρων
+['H', 'e', 'l', 'l', 'o'] -- "Hello"
+"This is a string" !! 0 -- 'T'
+
+
+----------------------------------------------------
+-- 2. Λίστες και διατεταγμένα σύνολα (tuples)
+----------------------------------------------------
+
+-- Όλα τα στοιχεία μιας λίστας πρέπει να είναι του ίδιου τύπου
+-- Οι δύο παρακάτω λίστες είναι οι ίδιες:
+[1, 2, 3, 4, 5]
+[1..5] -- διάστημα ή range
+
+-- Τα διαστήματα μπορούν να χρησιμοποιηθούν και για άλλους τύπους εκτός από αριθμούς
+['A'..'F'] -- "ABCDEF"
+
+-- Μπορούμε ακόμη να ορίσουμε και ένα βήμα
+[0,2..10] -- [0, 2, 4, 6, 8, 10]
+[5..1] -- [] (Το default βήμα της Haskell είναι το 1, επομένως η διπλανή λίστα είναι κενή)
+[5,4..1] -- [5, 4, 3, 2, 1]
+
+-- Προσπέλαση στοιχείου σε τυχαία θέση
+[1..10] !! 3 -- 4 (οι δείκτες των θέσεων ξεκινούν από το 0)
+
+-- Στην Haskell υπάρχουν και άπειρες λίστες!
+[1..] -- η λίστα των φυσικών αριθμών
+
+-- Οι άπειρες λίστες μπορούν να λειτουργούν επειδή η Haksell έχει "lazy evaluation".
+-- Αυτό σημαίνει ότι η Haskell κάνει υπολογισμούς μόνο όταν πραγματικά χρειάζεται!
+-- οπότε αν ζητήσουμε το 1000στό στοιχείο μιας άπειρης λίστας θα μας το δώσει,
+-- ξέρει ότι δεν χρειάζεται να υπολογίσει όλη την άπειρη λίστα πρώτα!
+
+[1..] !! 999 -- 1000
+
+-- Στο παραπάνω παράδειγμα η Haskell υπολόγισε τα στοιχεία 1 μέχρι 1000...τα υπόλοιπα
+-- στοιχεία της άπειρης λίστας δεν υπάρχουν ακόμα! Η Haskell θα τα υπολογίσει
+-- μόνο αν κάποια στιγμή τα χρειαστεί.
+
+-- συνένωση δύο λιστών με τον τελεστή ++ (σε γραμμικό χρόνο)
+[1..5] ++ [6..10]
+
+-- προσθήκη στοιχείου στην αρχή της λίστας (σε σταθερό χρόνο)
+0:[1..5] -- [0, 1, 2, 3, 4, 5]
+
+-- περισσότερες συναρτήσεις για τις λίστες
+head [1..5] -- 1
+tail [1..5] -- [2, 3, 4, 5]
+init [1..5] -- [1, 2, 3, 4]
+last [1..5] -- 5
+
+-- list comprehensions
+-- ένας άλλος τρόπος να ορίζουμε τις λίστες που θυμίζει πολύ τον ορισμό συνόλων στα μαθηματικά!
+[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10]
+
+-- list comprehension με συνθήκη
+[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10]
+
+-- Κάθε στοιχείο ενός tuple μπορεί να έχει διαφορετικό τύπο, όμως το tuple έχει σταθερό μέγεθος.
+-- Ένα tuple:
+("haskell", 1)
+
+-- προσπέλαση στοιχείων ενός ζεύγους στοιχείων (δηλαδή ενός tuple μεγέθους 2)
+fst ("haskell", 1) -- "haskell"
+snd ("haskell", 1) -- 1
+
+-- οι παραπάνω συναρτήσεις δεν λειτουργούν σε tuples μεγαλύτερου μεγέθους
+snd ("snd", "can't touch this", "da na na na") -- error!
+
+----------------------------------------------------
+-- 3. Συναρτήσεις
+----------------------------------------------------
+-- Μια απλή συνάρτηση που παίρνει 2 μεταβλητές a, b και επιστρέφει το άθροισμά τους
+add a b = a + b
+
+-- Προσέξτε ότι αν χρησιμοποιείτε το διαδραστικό περιβάλλον της Haskell (ghci), δηλαδή
+-- τον interpreter, θα πρέπει να προσθέσετε ενα `let` πριν τον ορισμό της συνάρτησης:
+-- let add a b = a + b
+
+-- Κλήση της συνάρτησης
+add 1 2 -- 3
+
+-- Μπορούμε να καλέσουμε την συνάρτηση και σαν τελεστή ανάμεσα στα 2 ορίσματα
+-- γράφοντας το όνομα της συνάρτησης μέσα σε backticks:
+1 `add` 2 -- 3
+
+-- Μπορούμε να ορίσουμε και συναρτήσεις που δεν έχουν γράμματα στο όνομά τους!
+-- Αυτό μας επιτρέπει να ορίσουμε δικούς μας τελεστές, όπως για παράδειγμα την ακέραια διάιρεση:
+
+(//) a b = a `div` b
+35 // 4 -- 8
+
+-- Guards: ένας εύκολος τρόπος να υλοποιήσουμε διακλαδώσεις σε μια συνάρτηση
+fib x
+ | x < 2 = 1
+ | otherwise = fib (x - 1) + fib (x - 2)
+
+-- Το ταίριασμα προτύπων (Pattern matching) είναι παρόμοιο.
+-- Εδώ δίνουμε 3 διαφορετικούς ορισμούς για την συνάρτηση fib
+-- H Haskell θα χρησιμοποιήσει αυτόματα τον πρώτο ορισμό το οποίου οι παράμετροι
+-- ταιριάζουν με τις παραμέτρους της κλήσης
+
+fib 1 = 1
+fib 2 = 2
+fib x = fib (x - 1) + fib (x - 2)
+
+-- Pattern matching σε tuples
+sndOfTriple (_, y, _) = y
+-- η κάτω παύλα χρησιμοποιείται για να μην δίνουμε ονόματα
+-- σε μεταβλητές που δεν θα χρησιμοποιήσουμε και
+-- ταιριάζει με όλους τους τύπους
+
+-- Pattern matching σε λίστες.
+-- Στο παρακάτω παράδειγμα, το `x` είναι το πρώτο στοιχείο της λίστας
+-- και τo `xs` είναι η λίστα με τα υπόλοιπα στοιχεία
+
+myMap func [] = []
+myMap func (x:xs) = func x : (myMap func xs)
+
+-- Μπορούμε να ορίσουμε και ανώνυμες συναρτήσεις (lambdas) χρησιμοποιώντας το
+-- backslash (που μοιάζει με λ) ακολουθούμενο από τις παραμέτρους:
+myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7]
+
+-- χρήση της συνάρτησης fold με μία ανώνυμη συνάρτηση
+-- Το foldl1 είναι σαν fold από αριστερά, αλλά χρησιμοποιεί σαν αρχική τιμή του
+-- accumulator το πρώτο στοιχείο της λίστας.
+foldl1 (\acc x -> acc + x) [1..5] -- 15
+
+----------------------------------------------------
+-- 4. Περισσότερες συναρτήσεις
+----------------------------------------------------
+
+-- Μερική κλήση: αν δεν περάσουμε όλες τις μεταβλητές σε μια συνάρτηση,
+-- τότε αυτή "καλείται μερικώς". Αυτό σημαίνει ότι μας επιστρέφει μια συνάρτηση
+-- η οποία παίρνει ως ορίσματα τις εναπομείνασες μεταβλητές
+
+add a b = a + b
+foo = add 10 -- η foo είναι μια συνάρτηση που περιμένει 1 αριθμό και του προσθέτει 10
+foo 5 -- 15
+
+-- Ένας άλλος τρόπος να γράψουμε το ίδιο πράγμα:
+foo = (10+)
+foo 5 -- 15
+
+-- Σύνθεση συναρτήσεων
+-- Ο τελεστής `.` χρησιμοποιείται για την σύνθεση ("αλυσίδωση") συναρτήσεων.
+-- Για παράδειγμα, η foo παρακάτω είναι μια συνάρτηση που παίρνει ως όρισμα 1 αριθμό.
+-- Πρώτα προσθέτει 10 στον αριθμό που δώσαμε και μετά πολλαπλασιάζει το αποτέλεσμα με 4
+foo = (4*) . (10+)
+
+-- 4*(10+5) = 60
+foo 5 -- 60
+
+-- διόρθωση προτεραιότητας
+-- Στην Haskell υπάρχει ο τελεστής `$`. Ο τελεστής αυτός εφαρμόζει μια συνάρτηση
+-- σε μία παράμετρο. Σε αντίθεση με την απλή εφαρμογή συνάρτησης, η οποία έχει
+-- την μεγαλύτερη πιθανή προτεραιότητα και είναι αριστερά προσεταιριστική,
+-- ο τελεστής `$` έχει την ελάχιστη προτεραιότητας και είναι δεξιά προσεταιριστικός.
+-- Λόγω της χαμηλής του προτεραιότητας, η έκφραση που βρίσκεται στα δεξιά του
+-- θα υπολογιστεί και θα περαστεί σαν παράμετρος στην συνάρτηση που βρίσκεται στα αριστερά του
+
+
+-- πριν
+even (fib 7) -- false
+
+-- ισοδύναμα
+even $ fib 7 -- false
+
+-- χρησιμοποιόντας σύνθεση συναρτήσεων
+even . fib $ 7 -- false
+
+
+----------------------------------------------------
+-- 5. Τύποι
+----------------------------------------------------
+
+-- Η Haskell έχει ένα πολύ ισχυρό σύστημα τύπων, στο οποίο κάθε έκφραση έχει έναν τύπο
+
+-- Κάποιο βασικοί τύποι:
+5 :: Integer
+"hello" :: String
+True :: Bool
+
+-- Και οι συναρτήσεις έχουν κάποιο τύπο
+-- Η συνάρτηση`not` παίρνει ένα boolean και επιστρέφει ένα boolean:
+-- not :: Bool -> Bool
+
+-- Παρακάτω βλέπετε μια συνάρτηση που παίρνει 2 ορίσματα:
+-- add :: Integer -> Integer -> Integer
+
+-- Όταν ορίζουμε μια συνάρτηση ή μεταβλητή, είναι καλή πρακτική να γράφουμε
+-- και τον τύπο της:
+double :: Integer -> Integer
+double x = x * 2
+
+----------------------------------------------------
+-- 6. Έλεγχος ροής και συνθήκες
+----------------------------------------------------
+
+-- if-expressions
+haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome"
+
+-- τα if-expressions μπορούν να πιάνουν και πολλές γραμμές
+-- αλλά η στοίχιση είναι σημαντική!
+haskell = if 1 == 1
+ then "awesome"
+ else "awful"
+
+-- case expressions: Με τον παρακάτω τρόπο θα μπορούσαμε να κάνουμε parse
+-- command line arguments
+case args of
+ "help" -> printHelp
+ "start" -> startProgram
+ _ -> putStrLn "bad args"
+
+-- Η Haskell δεν έχει βρόχους επανάληψης; αντιθέτως, χρησιμοποιούμε αναδρομή.
+-- Η συνάρτηση map εφαρμόζει μια συνάρτηση σε κάθε στοιχείο μιας λίστας
+
+map (*2) [1..5] -- [2, 4, 6, 8, 10]
+
+-- μπορούμε να κατασκευάσουμε τον βρόχο for χρησιμοποιώντας την map
+for array func = map func array
+
+-- και να τον χρησιμοποιήσουμε
+for [0..5] $ \i -> show i
+
+-- το παραπάνω θα μπορούσε να γραφτεί και έτσι:
+for [0..5] show
+
+-- Μπορούμε να χρησιμοποιήσουμε τις συναρτήσεις foldl και foldr
+-- για να υπολογίζουμε μια τιμή από μια λίστα (πχ άθροισμα ή γινόμενο)
+-- foldl <fn> <initial value> <list>
+foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43
+
+-- Η παραπάνω κλήση είναι η ίδια με:
+(2 * (2 * (2 * 4 + 1) + 2) + 3)
+
+-- Η foldl γίνεται από τα αριστερά ενώ η foldr από τα δεξιά
+foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16
+
+-- Η παραπάνω κλήση είναι τώρ:
+(2 * 1 + (2 * 2 + (2 * 3 + 4)))
+
+----------------------------------------------------
+-- 7. Τύποι δεδομένων
+----------------------------------------------------
+
+-- Με τον παρακάτω τρόπο μπορούμε να ορίζουμε δικούς μας τύπους
+-- δεδομένων στην Haskell
+
+data Color = Red | Blue | Green
+
+-- Τώρα μπορούμε να χρησιμοποιήσουμε τον τύπο μας και σε συναρτήσεις:
+
+say :: Color -> String
+say Red = "You are Red!"
+say Blue = "You are Blue!"
+say Green = "You are Green!"
+
+-- Οι τύποι δεδομένων μας μπορεί να είναι και παραμετρικοί, να δέχονται δηλαδή
+-- κάποιον τύπο ως παράμετρο
+
+data Maybe a = Nothing | Just a
+
+-- Όλες οι παρακάτω τιμές έχουν τύπο Maybe
+Just "hello" -- of type `Maybe String`
+Just 1 -- of type `Maybe Int`
+Nothing -- of type `Maybe a` for any `a`
+
+----------------------------------------------------
+-- 8. Haskell IO
+----------------------------------------------------
+
+-- Αν και το IO δεν μπορεί να εξηγηθεί σε βάθος χωρίς να εξηγήσουμε
+-- πρώτα τα monads, δεν είναι δύσκολο να το εξηγήσουμε αρκετά ώστε να μπορεί
+-- κάποιος να το χρησιμοποιήσει
+
+-- Όταν ένα πρόγραμμα Haskell εκτελείται, καλείται η συνάρτηση `main`
+-- Η συνάρτηση αυτή πρέπει να επιστρέφει τύπο `IO a` για κάποιο τύπο `a`.
+-- Για παράδειγμα:
+
+main :: IO ()
+main = putStrLn $ "Hello, sky! " ++ (say Blue)
+-- η συνάρτηση putStrLn έχει τύπο: String -> IO ()
+
+-- Είναι πιο εύκολο να χρησιμοποιήσουμε IO αν μπορούμε να γράψουμε το πρόγραμμά μας
+-- ως μια συνάρτηση από String σε String. Η συνάρτηση
+-- interact :: (String -> String) -> IO ()
+-- παίρνει ως είσοδο ένα string, τρέχει μια συνάρτηση πάνω στην είσοδο
+-- και τυπώνει την έξοδο
+
+countLines :: String -> String
+countLines = show . length . lines
+
+main' = interact countLines
+
+-- Μπορείτε να σκεφτείτε μια συνάρτηση που επιστρέφει τιμή με τύπο `IO ()`
+-- ως μια ακολουθία πράξεων, περίπου όπως και σε μια imperative γλώσσα
+-- Μπορούμε να χρησιμοποιήσουμε το `do` και να ενώσουμε αυτές τις κλήσεις
+-- Για παράδειγμα:
+
+sayHello :: IO ()
+sayHello = do
+ putStrLn "What is your name?"
+ name <- getLine -- η συνάρτηση αυτή διαβάζει μια γραμμή και την αναθέτει στην μετβαλήτη name
+ putStrLn $ "Hello, " ++ name
+
+-- Δοκιμάστε να γράψετε την συνάρτηση `interact` που θα διαβάζει μια γραμμή
+
+-- Ωστόσο ο κώδικας της συνάρτησης `sayHello` δεν θα εκτελεστεί ποτέ. Η μόνη συνάρτηση
+-- που εκτελείται όταν κάνουμε compile ένα αρχείο haskell είναι η `main`.
+-- Αν θέλετε να τρέξετε την sayHello (εκτός από το να φορτώσετε τον κώδικα στο
+-- ghci) μπορείτε να βάλετε σε σχόλια τον προηγούμενο ορισμό της main
+-- και να την ορίσετε ως:
+-- main = sayHello
+
+-- Ας προσπαθήσουμε να καταλάβουμε πως λειτουργεί η συνάρτηση `getLine`
+-- Ο τύπος της είναι:
+-- getLine :: IO String
+-- Μπορείτε να φανταστείτε ότι μια τιμή με τύπο `IO a` θα παραχθεί
+-- από ένα πρόγραμμα που παράγει μια τιμή με τύπο `a` (ενώ παράλληλα κάνει και κάτι άλλο)
+-- Μπορούμε να πάρουμε και να επαναχρησιμοποιήσουμε αυτήν την τιμή χρησιμοποιώντας
+-- το `<-`. Μπορούμε ακόμα και να φτιάξουμε την δική μας συνάρτηση με τύπο
+-- `IO String`:
+
+action :: IO String
+action = do
+ putStrLn "This is a line. Duh"
+ input1 <- getLine
+ input2 <- getLine
+ -- Ο τύπος του `do` μπλοκ είναι εκείνος της τελευταίας γραμμής.
+ -- Το `return` δεν είναι κάποια ειδική λέξη, αλλά απλώς μια συνάρτηση
+ return (input1 ++ "\n" ++ input2) -- return :: String -> IO String
+
+-- Μπορούμε να χρησιμοποιήσουμε την παραπάνω συνάρτηση ακριβώς όπως την `getLine`:
+
+main'' = do
+ putStrLn "I will echo two lines!"
+ result <- action
+ putStrLn result
+ putStrLn "This was all, folks!"
+
+-- Ο τύπος `IO` είναι παράδειγμα ενός "monad". Χρησιμοποιώντας τα monads για το
+-- ΙΟ, η Haskell καταφέρνει να είναι αγνή συναρτησιακή γλώσσα. Κάθε συνάρτηση που
+-- αλληλεπιδρά με τον έξω κόσμο (δηλαδή κάνει IO), έχει το IO (ή κάποιο άλλο monad)
+-- στον τύπο της. Αυτό μας διευκολύνει να γνωρίζουμε ποιές συναρτήσεις είναι αγνές
+-- (μαθηματικές -- δεν αλληλεπιδρούν με τον έξω κόσμο ούτε αλλάζουν κάποιο state)
+-- και ποιες δεν είναι.
+
+-- Αυτό είναι ένα πολύ ισχυρό χαρακτηριστικό γιατί είναι πολύ εύκολο να
+-- εκτελούμε παράλληλα αγνές συναρτήσεις! Οπότε η παραλληλοποίηση στην Haskell
+-- είναι αρκετά πιο εύκολη
+
+----------------------------------------------------
+-- 9. Haskell REPL
+----------------------------------------------------
+
+-- Μπορείτε να ξεκινήσετε το διαδραστικό περιβάλλον της Haskell με την εντολή `ghci`.
+-- Εδώ μπορείτε να γράψετε και να εκτελέσετε κώδικα haskell.
+-- Κάθε νέα τιμή πρέπει να ορίζεται με το `let`
+
+let foo = 5
+
+-- Μπορείτε να βρείτε τον τύπο μιας συνάρτησης με το `:t`:
+
+> :t foo
+foo :: Integer
+
+-- Οι τελεστές, όπως οι `+`, `:` και `$`, είναι επίσης συναρτήσεις.
+-- Μπορούμε να δούμε τον τύπο τους βάζοντας τους μέσα σε παρενθέσεις:
+
+> :t (:)
+(:) :: a -> [a] -> [a]
+
+-- Για περισσότερες πληροφορίες για οποιαδήποτε συνάρτηση ή τύπο,
+-- μπορείτε να χρησιμοποιήσετε το `:i`:
+
+> :i (+)
+class Num a where
+ (+) :: a -> a -> a
+ ...
+ -- Defined in ‘GHC.Num’
+infixl 6 +
+
+-- Μπορείτε επίσης να τρέξετε κάθε συνάρτηση με τύπο `IO ()`
+
+> sayHello
+What is your name?
+Friend!
+Hello, Friend!
+
+```
+
+Υπάρχουν πολλά ακόμα πράγματα να εξερευνήσετε στην Haskell, όπως τα typeclasses
+και διάφορα monads! Αυτές οι μαθηματικά ορισμένες έννοιες είναι που κάνουν την
+Haskell αυστηρή, αγνή και κομψή! Θα τελειώσουμε αυτήν την σύντομη περιήγηση με
+ένα τελευταίο παράδειγμα, η υλοποίηση της QuickSort σε Haskell:
+
+```haskell
+qsort [] = []
+qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater
+ where lesser = filter (< p) xs
+ greater = filter (>= p) xs
+```
+
+Υπάρχουν 2 παραδοσιακοί τρόποι να εγκαταστήσετε την Haskell:
+- [Cabal-based installation](http://www.haskell.org/platform/),
+- [Stack-based process](https://www.stackage.org/install).
+
+Στις παρακάτω πηγές μπορείτε να βρείτε αρκετά κομψές εισαγωγές στην Haskell
+- [Learn you a Haskell](http://learnyouahaskell.com/),
+- [Happy Learn Haskell Tutorial](http://www.happylearnhaskelltutorial.com/),
+- [Real World Haskell](http://book.realworldhaskell.org/)
diff --git a/elixir.html.markdown b/elixir.html.markdown
index 9f96be49..2748a983 100644
--- a/elixir.html.markdown
+++ b/elixir.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "https://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
@@ -13,16 +13,15 @@ It's fully compatible with Erlang, but features a more standard syntax
and many more features.
```elixir
-
# Single line comments start with a number symbol.
# There's no multi-line comment,
# but you can stack multiple comments.
-# To use the elixir shell use the `iex` command.
+# To use the Elixir shell use the `iex` command.
# Compile your modules with the `elixirc` command.
-# Both should be in your path if you installed elixir correctly.
+# Both should be in your path if you installed Elixir correctly.
## ---------------------------
## -- Basic types
@@ -50,7 +49,7 @@ elem({1, 2, 3}, 0) #=> 1
head #=> 1
tail #=> [2,3]
-# In elixir, just like in Erlang, the `=` denotes pattern matching and
+# In Elixir, just like in Erlang, the `=` denotes pattern matching and
# not an assignment.
#
# This means that the left-hand side (pattern) is matched against a
@@ -83,7 +82,7 @@ string.
<<?a, ?b, ?c>> #=> "abc"
[?a, ?b, ?c] #=> 'abc'
-# `?a` in elixir returns the ASCII integer for the letter `a`
+# `?a` in Elixir returns the ASCII integer for the letter `a`
?a #=> 97
# To concatenate lists use `++`, for binaries use `<>`
@@ -116,7 +115,7 @@ genders.gillian #=> "female"
5 * 2 #=> 10
10 / 2 #=> 5.0
-# In elixir the operator `/` always returns a float.
+# In Elixir the operator `/` always returns a float.
# To do integer division use `div`
div(10, 2) #=> 5
@@ -174,7 +173,7 @@ else
"This will"
end
-# Remember pattern matching? Many control-flow structures in elixir rely on it.
+# Remember pattern matching? Many control-flow structures in Elixir rely on it.
# `case` allows us to compare a value against many patterns:
case {:one, :two} do
@@ -307,7 +306,7 @@ Geometry.area({:circle, 3}) #=> 28.25999999999999801048
# Geometry.area({:circle, "not_a_number"})
#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
-# Due to immutability, recursion is a big part of elixir
+# Due to immutability, recursion is a big part of Elixir
defmodule Recursion do
def sum_list([head | tail], acc) do
sum_list(tail, acc + head)
@@ -382,7 +381,7 @@ end
## ---------------------------
# Elixir relies on the actor model for concurrency. All we need to write
-# concurrent programs in elixir are three primitives: spawning processes,
+# concurrent programs in Elixir are three primitives: spawning processes,
# sending messages and receiving messages.
# To start a new process we use the `spawn` function, which takes a function
diff --git a/es-es/amd-es.html.markdown b/es-es/amd-es.html.markdown
index 40aa6647..83c705c3 100644
--- a/es-es/amd-es.html.markdown
+++ b/es-es/amd-es.html.markdown
@@ -16,6 +16,7 @@ lang: es-es
El API del **Módulo de Definición Asíncrono** especifica un mecanismo para definir módulos JavaScript de manera tal que tanto el módulo como sus dependencias puedan ser cargadas de manera asíncrona. Esto es particularmente adecuado para el entorno del navegador donde la carga sincronizada de los módulos genera problemas de rendimiento, usabilidad, depuración y acceso de multi-dominios.
### Conceptos básicos
+
```javascript
// El API básico de AMD consiste en tan solo dos métodos: `define` y `require`
// y se basa en la definición y consumo de los módulos:
@@ -137,6 +138,7 @@ require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolL
coolLib.doFancyStuffWith(helpers.transform($('#foo')));
});
```
+
Las aplicaciones basadas en `require.js` usualmente tendrán un solo punto de entrada (`main.js`) que se pasa a la etiqueta del script `require.js` como un atributo de datos. Será cargado y ejecutado automáticamente al cargar la página:
```html
@@ -158,16 +160,19 @@ Muchas personas prefieren usar AMD para la organización del código durante el
`require.js` incluye un script llamado `r.js` (el que probablemente correrás en node.js, aunque Rhino también es soportado) que puede analizar el gráfico de dependencias de tu proyecto, y armar un solo fichero que contenga todos tus módulos (adecuadamente nombrados), minificado y listo para consumo.
Instálalo usando `npm`:
+
```shell
$ npm install requirejs -g
```
Ahora puedes alimentarlo con un fichero de configuración:
+
```shell
$ r.js -o app.build.js
```
Para nuestro ejemplo anterior el archivo de configuración luciría así:
+
```javascript
/* file : app.build.js */
({
@@ -184,6 +189,7 @@ Para nuestro ejemplo anterior el archivo de configuración luciría así:
```
Para usar el fichero creado en producción, simplemente intercambia `data-main`:
+
```html
<script src="require.js" data-main="app/main-built"></script>
```
diff --git a/es-es/docker-es.html.markdown b/es-es/docker-es.html.markdown
index 93e17f02..81e3cefe 100644
--- a/es-es/docker-es.html.markdown
+++ b/es-es/docker-es.html.markdown
@@ -1,167 +1,167 @@
----
-language: docker
-filename: docker-es.bat
-contributors:
- - ["Ruslan López", "http://javapro.org/"]
- - ["Michael Chen", "https://github.com/ML-Chen"]
-lang: es-es
----
-
-```bat
-:: descargar, instalar y ejecutar la imágen del hola mundo
-docker run hello-world
-
-:: Si esta es la primera vez, deberíais de poder ver el mensaje
-:: Unable to find image 'hello-world:latest' locally
-:: latest: Pulling from library/hello-world
-:: 1b930d010525: Pull complete
-:: Digest: sha256:4fe721ccc2e8dc7362278a29dc660d833570ec2682f4e4194f4ee23e415e1064
-:: Status: Downloaded newer image for hello-world:latest
-::
-:: Hello from Docker!
-:: This message shows that your installation appears to be working correctly.
-::
-:: To generate this message, Docker took the following steps:
-:: 1. The Docker client contacted the Docker daemon.
-:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
-:: (amd64)
-:: 3. The Docker daemon created a new container from that image which runs the
-:: executable that produces the output you are currently reading.
-:: 4. The Docker daemon streamed that output to the Docker client, which sent it
-:: to your terminal.
-::
-:: To try something more ambitious, you can run an Ubuntu container with:
-:: $ docker run -it ubuntu bash
-::
-:: Share images, automate workflows, and more with a free Docker ID:
-:: https://hub.docker.com/
-::
-:: For more examples and ideas, visit:
-:: https://docs.docker.com/get-started/
-:: El susodicho mensaje se podría traducir como:
-::
-:: Hola desde Docker!
-:: Este mensaje muestra que su instalación parece estar funcionando crrectamente.
-::
-:: Para generar este mensaje, Docker realizó los siguientes pasos:
-:: 1. El cliente de Docker contactó a Docker daemon.
-:: 2. El Docker daemon obtubo la imágen "hello-world" desde Docker Hub.
-:: (amd64)
-:: 3. El Docker daemon creó un nuevo contenedor a partir de esa imagen con la cual ejecuta el
-:: ejecutable que produce la salida que estás leyendo.
-:: 4. El Docker daemon transmitió dicha salida el cliente Docker, el cual
-:: la envió a tu terminal.
-::
-:: Para intentar algo más ambicioso, puede correr un contenedor Ubuntu mediante:
-:: $ docker run -it ubuntu bash
-::
-:: Comparte imágenes, automatice flujos y más con un Docker ID gratuito:
-:: https://hub.docker.com/
-
-:: ahora veamos las imágenes que se están ejecutando actualmente
-docker ps
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-
-:: veamos las imágenes que hemos ejecutado previamente
-docker ps -a
-
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-:: 4a76281f9c53 hello-world "/hello" 2 minutes ago Exited (0) 2 minutes ago
-:: happy_poincare
-:: la parte del nombre se genera automáticamente, así que probablemente sea diferente para vos
-
-:: eliminemos nuestra imagen previamente generada
-docker rm happy_poincare
-
-:: verifiquemos si realmente fue borrada
-docker ps -a
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-
-:: especifiquemos un nombre personalizado para el contenedor
-docker run --name test_container hello-world
-:: Hello from Docker!
-:: This message shows that your installation appears to be working correctly.
-::
-:: To generate this message, Docker took the following steps:
-:: 1. The Docker client contacted the Docker daemon.
-:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
-:: (amd64)
-:: 3. The Docker daemon created a new container from that image which runs the
-:: executable that produces the output you are currently reading.
-:: 4. The Docker daemon streamed that output to the Docker client, which sent it
-:: to your terminal.
-::
-:: To try something more ambitious, you can run an Ubuntu container with:
-:: $ docker run -it ubuntu bash
-::
-:: Share images, automate workflows, and more with a free Docker ID:
-:: https://hub.docker.com/
-::
-:: For more examples and ideas, visit:
-:: https://docs.docker.com/get-started/
-
-docker ps -a
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-:: d345fe1a4f41 hello-world "/hello" About a minute ago Exited (0) About a minute ago
-:: test_container
-:: tal como podeis ver el nombre es el que especificamos
-
-:: obtener los registros de un contenedor nombrado
-docker logs test_container
-:: Hello from Docker!
-:: This message shows that your installation appears to be working correctly.
-::
-:: To generate this message, Docker took the following steps:
-:: 1. The Docker client contacted the Docker daemon.
-:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
-:: (amd64)
-:: 3. The Docker daemon created a new container from that image which runs the
-:: executable that produces the output you are currently reading.
-:: 4. The Docker daemon streamed that output to the Docker client, which sent it
-:: to your terminal.
-::
-:: To try something more ambitious, you can run an Ubuntu container with:
-:: $ docker run -it ubuntu bash
-::
-:: Share images, automate workflows, and more with a free Docker ID:
-:: https://hub.docker.com/
-::
-:: For more examples and ideas, visit:
-:: https://docs.docker.com/get-started/
-
-docker rm test_container
-
-docker run ubuntu
-:: Unable to find image 'ubuntu:latest' locally
-:: latest: Pulling from library/ubuntu
-:: 2746a4a261c9: Pull complete
-:: 4c1d20cdee96: Pull complete 0d3160e1d0de: Pull complete c8e37668deea: Pull complete Digest: sha256:250cc6f3f3ffc5cdaa9d8f4946ac79821aafb4d3afc93928f0de9336eba21aa4
-:: Status: Downloaded newer image for ubuntu:latest
-
-docker ps -a
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-:: c19e9e5b000a ubuntu "/bin/bash" 5 seconds ago Exited (0) 4 seconds ago
-:: relaxed_nobel
-
-:: ejecutando un contenedor en modo interactivo
-docker run -it ubuntu
-:: root@e2cac48323d2:/# uname
-:: Linux
-:: root@e2cac48323d2:/# exit
-:: exit
-
-docker rm relaxed_nobel
-
-docker ps -a
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-:: e2cac48323d2 ubuntu "/bin/bash" 2 minutes ago Exited (0) About a minute ago
-:: nifty_goldwasser
-
-docker rm nifty_goldwasser
-```
+---
+language: docker
+filename: docker-es.bat
+contributors:
+ - ["Ruslan López", "http://javapro.org/"]
+ - ["Michael Chen", "https://github.com/ML-Chen"]
+lang: es-es
+---
+
+```bat
+:: descargar, instalar y ejecutar la imágen del hola mundo
+docker run hello-world
+
+:: Si esta es la primera vez, deberíais de poder ver el mensaje
+:: Unable to find image 'hello-world:latest' locally
+:: latest: Pulling from library/hello-world
+:: 1b930d010525: Pull complete
+:: Digest: sha256:4fe721ccc2e8dc7362278a29dc660d833570ec2682f4e4194f4ee23e415e1064
+:: Status: Downloaded newer image for hello-world:latest
+::
+:: Hello from Docker!
+:: This message shows that your installation appears to be working correctly.
+::
+:: To generate this message, Docker took the following steps:
+:: 1. The Docker client contacted the Docker daemon.
+:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
+:: (amd64)
+:: 3. The Docker daemon created a new container from that image which runs the
+:: executable that produces the output you are currently reading.
+:: 4. The Docker daemon streamed that output to the Docker client, which sent it
+:: to your terminal.
+::
+:: To try something more ambitious, you can run an Ubuntu container with:
+:: $ docker run -it ubuntu bash
+::
+:: Share images, automate workflows, and more with a free Docker ID:
+:: https://hub.docker.com/
+::
+:: For more examples and ideas, visit:
+:: https://docs.docker.com/get-started/
+:: El susodicho mensaje se podría traducir como:
+::
+:: Hola desde Docker!
+:: Este mensaje muestra que su instalación parece estar funcionando crrectamente.
+::
+:: Para generar este mensaje, Docker realizó los siguientes pasos:
+:: 1. El cliente de Docker contactó a Docker daemon.
+:: 2. El Docker daemon obtubo la imágen "hello-world" desde Docker Hub.
+:: (amd64)
+:: 3. El Docker daemon creó un nuevo contenedor a partir de esa imagen con la cual ejecuta el
+:: ejecutable que produce la salida que estás leyendo.
+:: 4. El Docker daemon transmitió dicha salida el cliente Docker, el cual
+:: la envió a tu terminal.
+::
+:: Para intentar algo más ambicioso, puede correr un contenedor Ubuntu mediante:
+:: $ docker run -it ubuntu bash
+::
+:: Comparte imágenes, automatice flujos y más con un Docker ID gratuito:
+:: https://hub.docker.com/
+
+:: ahora veamos las imágenes que se están ejecutando actualmente
+docker ps
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+
+:: veamos las imágenes que hemos ejecutado previamente
+docker ps -a
+
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+:: 4a76281f9c53 hello-world "/hello" 2 minutes ago Exited (0) 2 minutes ago
+:: happy_poincare
+:: la parte del nombre se genera automáticamente, así que probablemente sea diferente para vos
+
+:: eliminemos nuestra imagen previamente generada
+docker rm happy_poincare
+
+:: verifiquemos si realmente fue borrada
+docker ps -a
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+
+:: especifiquemos un nombre personalizado para el contenedor
+docker run --name test_container hello-world
+:: Hello from Docker!
+:: This message shows that your installation appears to be working correctly.
+::
+:: To generate this message, Docker took the following steps:
+:: 1. The Docker client contacted the Docker daemon.
+:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
+:: (amd64)
+:: 3. The Docker daemon created a new container from that image which runs the
+:: executable that produces the output you are currently reading.
+:: 4. The Docker daemon streamed that output to the Docker client, which sent it
+:: to your terminal.
+::
+:: To try something more ambitious, you can run an Ubuntu container with:
+:: $ docker run -it ubuntu bash
+::
+:: Share images, automate workflows, and more with a free Docker ID:
+:: https://hub.docker.com/
+::
+:: For more examples and ideas, visit:
+:: https://docs.docker.com/get-started/
+
+docker ps -a
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+:: d345fe1a4f41 hello-world "/hello" About a minute ago Exited (0) About a minute ago
+:: test_container
+:: tal como podeis ver el nombre es el que especificamos
+
+:: obtener los registros de un contenedor nombrado
+docker logs test_container
+:: Hello from Docker!
+:: This message shows that your installation appears to be working correctly.
+::
+:: To generate this message, Docker took the following steps:
+:: 1. The Docker client contacted the Docker daemon.
+:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
+:: (amd64)
+:: 3. The Docker daemon created a new container from that image which runs the
+:: executable that produces the output you are currently reading.
+:: 4. The Docker daemon streamed that output to the Docker client, which sent it
+:: to your terminal.
+::
+:: To try something more ambitious, you can run an Ubuntu container with:
+:: $ docker run -it ubuntu bash
+::
+:: Share images, automate workflows, and more with a free Docker ID:
+:: https://hub.docker.com/
+::
+:: For more examples and ideas, visit:
+:: https://docs.docker.com/get-started/
+
+docker rm test_container
+
+docker run ubuntu
+:: Unable to find image 'ubuntu:latest' locally
+:: latest: Pulling from library/ubuntu
+:: 2746a4a261c9: Pull complete
+:: 4c1d20cdee96: Pull complete 0d3160e1d0de: Pull complete c8e37668deea: Pull complete Digest: sha256:250cc6f3f3ffc5cdaa9d8f4946ac79821aafb4d3afc93928f0de9336eba21aa4
+:: Status: Downloaded newer image for ubuntu:latest
+
+docker ps -a
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+:: c19e9e5b000a ubuntu "/bin/bash" 5 seconds ago Exited (0) 4 seconds ago
+:: relaxed_nobel
+
+:: ejecutando un contenedor en modo interactivo
+docker run -it ubuntu
+:: root@e2cac48323d2:/# uname
+:: Linux
+:: root@e2cac48323d2:/# exit
+:: exit
+
+docker rm relaxed_nobel
+
+docker ps -a
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+:: e2cac48323d2 ubuntu "/bin/bash" 2 minutes ago Exited (0) About a minute ago
+:: nifty_goldwasser
+
+docker rm nifty_goldwasser
+```
diff --git a/es-es/elixir-es.html.markdown b/es-es/elixir-es.html.markdown
index 885165a6..37acf6ad 100644
--- a/es-es/elixir-es.html.markdown
+++ b/es-es/elixir-es.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
@@ -23,10 +23,10 @@ y otras características más.
# No hay comentarios multilinea,
# pero se pueden apilar varios comentarios.
-# Para usar el shell de elixir se usa el comando `iex`.
+# Para usar el shell de Elixir se usa el comando `iex`.
# Los módulos se compilan con el comando `elixirc`.
-# Ambos deberían estar en la ruta si elixir se instaló correctamente.
+# Ambos deberían estar en la ruta si Elixir se instaló correctamente.
## ---------------------------
## -- Tipos básicos
@@ -55,7 +55,7 @@ elem({1, 2, 3}, 0) #=> 1
head #=> 1
tail #=> [2,3]
-# En elixir, solo como Erlang, el `=` denota la coincidencia de patrones y
+# En Elixir, solo como Erlang, el `=` denota la coincidencia de patrones y
# no una asignación.
#
# This is how the above example of accessing the head and tail of a list works.
@@ -87,7 +87,7 @@ string.
<<?a, ?b, ?c>> #=> "abc"
[?a, ?b, ?c] #=> 'abc'
-# `?a` en elixir devuelve el valor ASCII para el caracter `a`
+# `?a` en Elixir devuelve el valor ASCII para el caracter `a`
?a #=> 97
# Para concatenar listas se usa `++`, para binarios `<>`
@@ -120,7 +120,7 @@ genders.gillian #=> "female"
5 * 2 #=> 10
10 / 2 #=> 5.0
-# En elixir el operador `/` siempre devuelve un número flotante
+# En Elixir el operador `/` siempre devuelve un número flotante
# Para hacer la división de número entero se debe usar `div`
div(10, 2) #=> 5
@@ -175,7 +175,7 @@ else
end
# Se acuerda de la coincidencia de patrones?
-# Muchas estructuras de control de flujo en elixir confían en ella.
+# Muchas estructuras de control de flujo en Elixir confían en ella.
# `case` permite comparar un valor con muchos patrones:
case {:one, :two} do
@@ -305,7 +305,7 @@ Geometry.area({:circle, 3}) #=> 28.25999999999999801048
# Geometry.area({:circle, "not_a_number"})
#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
-# Debido a la inmutabilidad, la recursión es una gran parte de elixir
+# Debido a la inmutabilidad, la recursión es una gran parte de Elixir
defmodule Recursion do
def sum_list([head | tail], acc) do
sum_list(tail, acc + head)
@@ -380,7 +380,7 @@ end
## ---------------------------
# Elixir confía en el modelo actor para la concurrencia. Todo lo que se necesita para escribir
-# programas concurrentes en elixir son tres primitivas: procesos de desove,
+# programas concurrentes en Elixir son tres primitivas: procesos de desove,
# envío de mensajes y recepción de mensajes.
# Para empezar un nuevo proceso se usa la función `spawn`,
diff --git a/es-es/forth-es.html.markdown b/es-es/forth-es.html.markdown
index edc5d38c..61123151 100644
--- a/es-es/forth-es.html.markdown
+++ b/es-es/forth-es.html.markdown
@@ -13,7 +13,7 @@ Forth fue criado por Charles H. Moore en los 70s. Forth es un lenguaje imperativ
Nota: Este articulo enfoca predominantemente en la Gforth implementación de Forth, pero casi todo
de lo que esta escrito aquí debe funcionar en otro sitio.
-```
+```forth
\ Este es un comentario
( Este es un comentario también pero solo esta usado cuando definiendo palabras. )
diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown
index dc0dda30..c93584d8 100644
--- a/es-es/git-es.html.markdown
+++ b/es-es/git-es.html.markdown
@@ -414,4 +414,4 @@ $ git rm /directorio/del/archivo/FooBar.c
* [Pro Git](http://www.git-scm.com/book/en/v2)
-* [Una introducción a Git y Github para principiantes (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners)
+* [Una introducción a Git y GitHub para principiantes (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners)
diff --git a/es-es/powershell-es.html.markdown b/es-es/powershell-es.html.markdown
index 9eb35967..5b12b961 100644
--- a/es-es/powershell-es.html.markdown
+++ b/es-es/powershell-es.html.markdown
@@ -34,7 +34,7 @@ $PSVersionTable
Para obtener ayuda:
-```
+```powershell
# Si necesita encontrar algún comando
Get-Command about_* # tiene por abreviación (o alias): gcm
Get-Command -Verb Add # lista todos los comandos que tienen por verbo 'Add'
@@ -51,7 +51,7 @@ Update-Help # Actualiza la ayuda (debe ser ejecutado en una consola elevada como
Acá inicia el tutorial:
-```
+```powershell
# Como ya lo notó, los comentarios empiezan con #
# Ejemplo de un simple hola mundo:
@@ -299,7 +299,7 @@ $Shortcut.Save()
Configurando el shell
-```
+```powershell
# $Profile es la ruta completa para su `Microsoft.PowerShell_profile.ps1`
# Todo el código alojado allí será ejecutado cuando se ejecuta una nueva sesión de PS
if (-not (Test-Path $Profile)) {
diff --git a/es-es/pyqt-es.html.markdown b/es-es/pyqt-es.html.markdown
index 6d4fdde7..9a5eab8c 100644
--- a/es-es/pyqt-es.html.markdown
+++ b/es-es/pyqt-es.html.markdown
@@ -16,7 +16,7 @@ Esta es una adaptación de la introducción a QT con C++ por [Aleksey Kholovchuk
```python
import sys
from PyQt4 import QtGui
-
+
def window():
# Crear el objeto de la aplicación
app = QtGui.QApplication(sys.argv)
@@ -44,7 +44,7 @@ if __name__ == '__main__':
Para poder hacer uso de las funciones más avanzades en **pyqt** necesitamos agregar elementos adicionales.
Aquí mostramos cómo introducir una caja de diálogo popup, útil para permitir al usuario confirmar su decisión o para brindarnos información.
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
@@ -63,7 +63,7 @@ def window():
w.setWindowTitle("PyQt Dialog")
w.show()
sys.exit(app.exec_())
-
+
# Esta función debería crear una ventana de diálogo con un botón
# que espera a recibir un click y luego sale del programa
def showdialog():
diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown
index 0b21e479..a8f01089 100644
--- a/es-es/python-es.html.markdown
+++ b/es-es/python-es.html.markdown
@@ -421,7 +421,7 @@ map(sumar_10, [1,2,3]) #=> [11, 12, 13]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
# Podemos usar listas por comprensión para mapeos y filtros agradables
-[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
+[sumar_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
# también hay diccionarios
{k:k**2 for k in range(3)} #=> {0: 0, 1: 1, 2: 4}
diff --git a/es-es/raku-es.html.markdown b/es-es/raku-es.html.markdown
index e916d0fd..09341056 100644
--- a/es-es/raku-es.html.markdown
+++ b/es-es/raku-es.html.markdown
@@ -1,5 +1,5 @@
---
-name: perl6
+name: Raku
category: language
language: Raku
filename: learnraku-es.raku
diff --git a/es-es/self-es.html.markdown b/es-es/self-es.html.markdown
index 11972214..1f985215 100644
--- a/es-es/self-es.html.markdown
+++ b/es-es/self-es.html.markdown
@@ -116,6 +116,7 @@ Las expresiones múltiples son separadas por un punto. ^ retorna inmediatamente.
```
Los bloques son ejecutados al enviales el mensaje 'value' y son inherentes (delegados a) sus contextos:
+
```
"returns 0"
[|x|
diff --git a/es-es/visualbasic-es.html.markdown b/es-es/visualbasic-es.html.markdown
index c677c20f..fb0b1d27 100644
--- a/es-es/visualbasic-es.html.markdown
+++ b/es-es/visualbasic-es.html.markdown
@@ -8,7 +8,7 @@ filename: learnvisualbasic-es.vb
lang: es-es
---
-```
+```visualbasic
Module Module1
Sub Main()
diff --git a/es-es/wolfram-es.html.markdown b/es-es/wolfram-es.html.markdown
index 44ec9e09..6858c286 100644
--- a/es-es/wolfram-es.html.markdown
+++ b/es-es/wolfram-es.html.markdown
@@ -15,7 +15,7 @@ El lenguaje de Wolfram tiene varias interfaces:
El código de este ejemplo se puede escribir en cualquier interfaz y editarlo con Wolfram Workbench. Cargar directamente en Matematica puede resultar incómodo porque el archivo no contiene información de formato de celda (lo que haría que el archivo sea un desastre enorme para ser leído como texto) - puede ser visto / editado pero tal vez requerira algún ajuste.
-```
+```mathematica
(* Esto es un comentario *)
(* En Mathematica en lugar de utilizar estos comentarios, puede crear una celda de texto
diff --git a/fa-ir/css-fa.html.markdown b/fa-ir/css-fa.html.markdown
index 4e222eb2..93af9132 100644
--- a/fa-ir/css-fa.html.markdown
+++ b/fa-ir/css-fa.html.markdown
@@ -29,21 +29,21 @@ filename: learncss-fa.css
<p dir='rtl'>در CSS همه توضیحات داخل ستاره-بروم نوشته میشوند زیرا CSS دستوری برای توضیحات تک خطی مثل C ندارد</p>
-```CSS
+```css
/* comments appear inside slash-asterisk, just like this line!
there are no "one-line comments"; this is the only comment style */
```
<p dir='rtl'>به طور کلی دستورات CSS بسیار ساده هستند که در آن یک انتخابگر (selector) عنصری را در روی صفحه هدف قرار میدهد.</p>
-```CSS
+```css
selector { property: value; /* more properties...*/ }
```
<p dir='rtl'>با استفاده از ستاره می توان برای همه عناصر روی صفحه استایل تعریف کرد</p>
-```CSS
+```css
* { color:red; }
```
@@ -55,129 +55,129 @@ selector { property: value; /* more properties...*/ }
<p dir='rtl'>شما میتوانید با استفاده از نام کلاس آنرا انتخاب کنید</p>
-```CSS
+```css
.some-class { }
```
<p dir='rtl'>یا با استفاده از نام دو کلاس</p>
-```CSS
+```css
.some-class.class2 { }
```
<p dir='rtl'>یا با استفاده از نام id</p>
-```CSS
+```css
#someId { }
```
<p dir='rtl'>یا با استفاده از نام خود عنصر</p>
-```CSS
+```css
div { }
```
<p dir='rtl'>یا با استفاده از `attr`</p>
-```CSS
+```css
[attr] { font-size:smaller; }
```
<p dir='rtl'>یا با استفاده از ارزشی که برای `attr` مشخص شده</p>
-```CSS
+```css
[attr='value'] { font-size:smaller; }
```
<p dir='rtl'>با استفاده از ارزشی که برای `attr` مشخص شده و آن ارزش با `val` شروع میشود در CSS3</p>
-```CSS
+```css
[attr^='val'] { font-size:smaller; }
```
<p dir='rtl'>با استفاده از ارزشی که برای `attr` مشخص شده و آن ارزش با `ue` به پایان میرسد در CSS3</p>
-```CSS
+```css
[attr$='ue'] { font-size:smaller; }
```
<p dir='rtl'>یا با انتخاب بوسیله یکی از ارزشهایی که در لیست `otherAttr` بوسیله فاصله از هم جدا شده اند در CSS3</p>
-```CSS
+```css
[attr$='ue'] { font-size:smaller; }
```
<p dir='rtl'>یا ارزش(`value`) دقیقاً خود ارزش(`value`) یا بوسیله `-` که یونیکد (U+002D) از حرف بعدی جدا شود</p>
-```CSS
+```css
[otherAttr|='en'] { font-size:smaller; }
```
<p dir='rtl'>و مهمتر از همه اینکه میتوان آنها را ترکیب کرد. نکته مهمی که در اینجا باید مد نظر داشته باشید این است که هنگام ترکیب نباید هیچگونه فاصله ای بین آنها قرار گیرد زیرا در این حالت معنای دستور تغییر میکند</p>
-```CSS
+```css
div.some-class[attr$='ue'] { }
```
<p dir='rtl'>CSS این امکان را به شما میدهد که یک عنصر را بوسیله والدین آن انتخاب کنید</p>
<p dir='rtl'>برای مثال دستور زیر همه عناصری را که نام کلاس آنها <span dir="ltr">`.class-name`</span> و دارای پدر و مادری با این مشخصه <span dir="ltr">`div.some-parent`</span> هستند را انتخاب میکند.</p>
-```CSS
+```css
div.some-parent > .class-name {}
```
<p dir='rtl'>یا دستور زیر که همه عناصری را که نام کلاس آنها <span dir="ltr">`.class-name`</span> و داخل عنصری با مشخصه <span dir="ltr">`div.some-parent`</span> هستند را در هر عمقی که باشند (یعنی فرزندی از فرزندان <span dir="ltr">`div.some-parent`</span><span dir="ltr"> باشند) انتخاب میکند.</p>
-```CSS
+```css
div.some-parent .class-name {}
```
<p dir='rtl'>نکته ای که در اینجا باید به آن توجه کنید این است که این رستور با فاصله ای بین نام دو کلاس همراه است و با مثال زیر که در بالا هم ذکر شد تفاوت دارد.</p>
-```CSS
+```css
div.some-parent.class-name {}
```
<p dir='rtl'>دستور زیر همه عناصری را که نام کلاس آنها <span dir="ltr">`.this-element`</span> و بلافاصله بعد از عنصری با مشخصه <span dir="ltr">`.i-am-before`</span> قرار دارد را انتخاب میکند.</p>
-```CSS
+```css
.i-am-before + .this-element { }
```
<p dir='rtl'>هر خواهر یا برادری که بعد از <span dir="ltr">`.i-am-before`</span> بیاید در اینجا لازم نیست بلافاصله بعد از هم قرار بگیرند ولی باید دارای پدر و مادری یکسان باشند.</p>
-```CSS
+```css
.i-am-any-before ~ .this-element {}
```
<p dir='rtl'>در زیر چند نمونه از شبه کلاسها را معرفی میکنیم که به شما اجازه میدهد عناصر را بر اساس رفتار آنها در صفحه انتخاب کنید.</p>
<p dir='rtl'>برای مثال زمانی که اشاره گر ماوس روی عنصری بر روی صفحه قرار دارد.</p>
-```CSS
+```css
selector:hover {}
```
<p dir='rtl'>یا زمانی از یک لینک بازید کردید.</p>
-```CSS
+```css
selected:visited {}
```
<p dir='rtl'>یا زمانی از لینکی بازید نشده است.</p>
-```CSS
+```css
selected:link {}
```
<p dir='rtl'>یا زمانی که روی یک عنصر ورودی متمرکز شده.</p>
-```CSS
+```css
selected:focus {}
```
<h3 dir='rtl'>واحدها</h3>
-```CSS
+```css
selector {
/* واحدها اندازه */
@@ -247,7 +247,7 @@ selector {
<p dir='rtl'>به مثال زیر توجه کنید:</p>
-```CSS
+```css
/*A*/
p.class1[attr='value']
diff --git a/fr-fr/elixir-fr.html.markdown b/fr-fr/elixir-fr.html.markdown
index 90cdad7c..f8250e16 100644
--- a/fr-fr/elixir-fr.html.markdown
+++ b/fr-fr/elixir-fr.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
diff --git a/fr-fr/git-fr.html.markdown b/fr-fr/git-fr.html.markdown
index 00b6b6e1..a4d0c185 100644
--- a/fr-fr/git-fr.html.markdown
+++ b/fr-fr/git-fr.html.markdown
@@ -171,6 +171,7 @@ $ git init --help
Ne plus suivre certains fichiers et dossiers de Git.
Habituellement fait pour les fichiers privés et temporaires qui seraient,
autrement, partagés dans le dépôt.
+
```bash
$ echo "temp/" >> .gitignore
$ echo "cle_privee" >> .gitignore
@@ -466,6 +467,7 @@ Vous pouvez maintenant pull !
```bash
git pull
```
+
`...changes apply...`
Vérifiez maintenant que tout est OK
diff --git a/fr-fr/markdown-fr.html.markdown b/fr-fr/markdown-fr.html.markdown
index 1fd22883..f5d6aacc 100644
--- a/fr-fr/markdown-fr.html.markdown
+++ b/fr-fr/markdown-fr.html.markdown
@@ -178,7 +178,7 @@ Vous pouvez également utiliser des sous-listes.
1. Item un
2. Item deux
3. Item trois
- * Sub-item
+ * Sub-item
* Sub-item
4. Item quatre
```
@@ -210,7 +210,7 @@ l'intérieur du bloc de code.
```md
my_array.each do |item|
- puts item
+ puts item
end
```
@@ -223,13 +223,15 @@ La fonction `run()` ne vous oblige pas à aller courir!
En Markdown GitHub, vous pouvez utiliser des syntaxes spécifiques.
- ```ruby
- def foobar
- puts "Hello world!"
- end
- ```
+````md
+```ruby
+def foobar
+ puts "Hello world!"
+end
+```
+````
-Pas besoin d'indentation pour le code juste au-dessus, de plus, GitHub
+Pas besoin d'indentation pour le code juste au-dessus, de plus, GitHub
va utiliser une coloration syntaxique pour le langage indiqué après les <code>```</code>.
## Ligne Horizontale
@@ -267,13 +269,13 @@ Markdown supporte aussi les liens relatifs.
Les liens de références sont eux aussi disponibles en Markdown.
-<div class="highlight"><code><pre>
-[<span class="nv">Cliquez ici</span>][<span class="ss">link1</span>] pour plus d'information!
-[<span class="nv">Regardez aussi par ici</span>][<span class="ss">foobar</span>] si vous voulez.
+```md
+[Cliquez ici][link1] pour plus d'information!
+[Regardez aussi par ici][foobar] si vous voulez.
-[<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Cool!"</span>
-[<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Génial!"</span>
-</pre></code></div>
+[link1]: http://test.com/ "Cool!"
+[foobar]: http://foobar.biz/ "Génial!"
+```
Le titre peut aussi être entouré de guillemets simples, ou de parenthèses, ou
absent. Les références peuvent être placées où vous voulez dans le document et
@@ -282,11 +284,11 @@ les identifiants peuvent être n'importe quoi tant qu'ils sont uniques.
Il y a également le nommage implicite qui transforme le texte du lien en
identifiant.
-<div class="highlight"><code><pre>
-[<span class="nv">Ceci</span>][] est un lien.
+```md
+[Ceci][] est un lien.
-[<span class="nv">Ceci</span>]:<span class="sx">http://ceciestunlien.com/</span>
-</pre></code></div>
+[Ceci]:http://ceciestunlien.com/
+```
Mais ce n'est pas beaucoup utilisé.
@@ -301,12 +303,11 @@ d'un point d'exclamation!
Là aussi, on peut utiliser le mode "références".
+```md
+![Ceci est l'attribut ALT de l'image][monimage]
-<div class="highlight"><code><pre>
-![<span class="nv">Ceci est l'attribut ALT de l'image</span>][<span class="ss">monimage</span>]
-
-[<span class="nv">monimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"si vous voulez un titre, c'est ici."</span>
-</pre></code></div>
+[monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici."
+```
## Divers
@@ -334,7 +335,7 @@ Tapez \*ce texte\*.
### Touches de clavier
-Avec le "Github Flavored Markdown", vous pouvez utiliser la balise `<kdb>`
+Avec le "GitHub Flavored Markdown", vous pouvez utiliser la balise `<kdb>`
pour représenter une touche du clavier.
```md
@@ -348,10 +349,10 @@ Les tableaux ne sont disponibles que dans le "GitHub Flavored Markdown" et
ne sont pas tres agréable d'utilisation. Mais si vous en avez besoin :
```md
-| Col1 | Col2 | Col3 |
-| :----------- | :------: | ------------: |
-| Alignement Gauche | Centré | Alignement Droite |
-| bla | bla | bla |
+| Col1 | Col2 | Col3 |
+| :---------------- | :------: | ----------------: |
+| Alignement Gauche | Centré | Alignement Droite |
+| bla | bla | bla |
```
ou bien, pour un résultat équivalent :
diff --git a/fr-fr/pyqt-fr.html.markdown b/fr-fr/pyqt-fr.html.markdown
index 6da9a380..7f0f018b 100644
--- a/fr-fr/pyqt-fr.html.markdown
+++ b/fr-fr/pyqt-fr.html.markdown
@@ -14,14 +14,14 @@ lang: fr-fr
Ceci est une adaptation de l'intro C++ à QT par [Aleksey Kholovchuk](https://github.com/vortexxx192
), certains exemples du code doivent avoir la même fonctionnalité,
-cette version ayant juste été faite en utilisant pyqt!
+cette version ayant juste été faite en utilisant pyqt!
```python
import sys
from PyQt4 import QtGui
-
+
def window():
- # Création de l'objet application
+ # Création de l'objet application
app = QtGui.QApplication(sys.argv)
# Création d'un widget où notre label sera placé
w = QtGui.QWidget()
@@ -47,7 +47,7 @@ if __name__ == '__main__':
Pour obtenir certaines des fonctionnalités les plus avancées de **pyqt** nous devons commencer par chercher à construire des éléments supplémentaires.
Ici nous voyons comment introduire une boîte de dialogue popup, utile pour demander une confirmation à un utilisateur ou fournir des informations.
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
@@ -66,7 +66,7 @@ def window():
w.setWindowTitle("PyQt Dialog")
w.show()
sys.exit(app.exec_())
-
+
# Cette fonction devrait créer une fenêtre de dialogue avec un bouton
# qui attend d'être cliqué puis quitte le programme
def showdialog():
diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown
index 7b446259..10a37994 100644
--- a/fr-fr/wolfram-fr.html.markdown
+++ b/fr-fr/wolfram-fr.html.markdown
@@ -21,7 +21,7 @@ Ce code d'exemple peut être utilisé et modifié dans ces logiciels. Cependant,
copier-coller directement dans Mathematica peut causer des problèmes de
formatage, car il ne contient aucune information de mise en page.
-```
+```mathematica
(* Ceci est un commentaire *)
(* Dans Mathematica, au lieu d'utiliser ces commentaires, vous pouvez créer des
diff --git a/hd-hd/amd.html.markdown b/hd-hd/amd.html.markdown
index 0a6581d6..7e335668 100644
--- a/hd-hd/amd.html.markdown
+++ b/hd-hd/amd.html.markdown
@@ -4,7 +4,7 @@ tool: amd
contributors:
- ["Frederik Ring", "https://github.com/m90"]
filename: learnamd-hd.js
-lang: hd
+lang: hd-hd
---
## एएमडी के साथ प्रारंभ करना
@@ -12,6 +12,7 @@ lang: hd
जावास्क्रिप्ट मॉड्यूल ऐसे मॉड्यूल और इसकी अतुल्यकालिक निर्भरता से भरा हुआ है। यह ब्राउज़र पर्यावरण जहां के लिए विशेष रूप से अच्छी तरह से अनुकूल है, और प्रदर्शन , प्रयोज्य, डीबगिंग, और क्रॉस-डोमेन जैसे मॉड्यूल्स को जल्दी सिंक्रनाइज़ लोडिंग करता hai।
### मूल अवधारणा
+
```javascript
// बुनियादी एएमडी एपीआई दो तरीकों लेकिन कुछ भी नहीं होते : ` define` और` require`
// और सभी मॉड्यूल परिभाषा और खपत के बारे में है :
@@ -79,6 +80,7 @@ function require(deps, callback){
### Require.js के साथ वास्तविक दुनिया के उपयोग
परिचयात्मक उदाहरण के विपरीत, ` require.js` (सबसे लोकप्रिय एएमडी पुस्तकालय ) वास्तव में लागू करता है ** ** Amd ** में *A * **, आप XHR के माध्यम से मॉड्यूल और उनकी निर्भरता लोड करने के लिए सक्षम करने के लिए :
+
```javascript
/* file: app/main.js */
require(['modules/someClass'], function(SomeClass){
@@ -113,6 +115,7 @@ define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){
return SomeClass;
});
```
+
अपने ` main.js` में डिफ़ॉल्ट पथ मानचित्रण व्यवहार का उपयोग ` requirejs.config ( configObj ) ` में परिवर्तन करने के लिए:
```javascript
@@ -131,6 +134,7 @@ require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolL
coolLib.doFancyStuffWith(helpers.transform($('#foo')));
});
```
+
` require.js` आधारित क्षुधा आमतौर पर एक डाटा विशेषता के रूप में ` require.js` स्क्रिप्ट टैग को पारित कर दिया है कि एक एकल प्रवेश बिंदु (` main.js` ) होगा। यह स्वचालित रूप से भरी हुई है और pageload पर क्रियान्वित किया जाएगा :
```html
@@ -151,16 +155,19 @@ require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolL
(राइनो भी समर्थन किया है, तो आप शायद Node.js में चलेगा ) ` require.js` ( अपनी परियोजना की निर्भरता ग्राफ का विश्लेषण , और अपने सभी मॉड्यूल युक्त एक एकल फाइल निर्माण कर सकते हैं कि ` r.js` नामक एक स्क्रिप्ट के साथ आता है ठीक से minified और उपभोग के लिए तैयार है, ) नाम दिया है।
Install it using `npm`:
+
```shell
$ npm install requirejs -g
```
अब आप एक विन्यास फाइल के साथ फ़ीड कर सकते हैं:
+
```shell
$ r.js -o app.build.js
```
हमारे ऊपर के उदाहरण के लिए विन्यास की तरह लग सकता है:
+
```javascript
/* file : app.build.js */
({
@@ -177,6 +184,7 @@ $ r.js -o app.build.js
```
उत्पादन में बनाया फ़ाइल का उपयोग करने के लिए, बस ` Data-main` स्वैप:
+
```html
<script src="require.js" data-main="app/main-built"></script>
```
diff --git a/hd-hd/d.html.markdown b/hd-hd/d.html.markdown
index 96274e2b..a08feb2e 100644
--- a/hd-hd/d.html.markdown
+++ b/hd-hd/d.html.markdown
@@ -3,7 +3,7 @@ language: D
filename: learnd-hd.d
contributors:
- ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"]
-lang: hd
+lang: hd-hd
---
```c
@@ -126,7 +126,6 @@ class Matrix(uint m, uint n, T = int) {
}
auto mat = new Matrix!(3, 3);
-
```
Classes की बात हो रही है , एक दूसरे के लिए गुणों के बारे में बात करते हैं। एक संपत्ति
@@ -176,8 +175,8 @@ class MyClass(T, U) {
void main() {
auto mc = new MyClass!(int, string)(7, "seven");
- करने के लिए लिखने के लिए मानक पुस्तकालय से
- // आयात ' stdio ' मॉड्यूल
+ // करने के लिए लिखने के लिए मानक पुस्तकालय से
+ // आयात ' stdio ' मॉड्यूल
// सांत्वना (आयात एक गुंजाइश के लिए स्थानीय हो सकता है) ।
import std.stdio;
@@ -235,22 +234,21 @@ UFCS के साथ, हम एक विधि के रूप में ए
एक विधि के रूप में ग्रुप ए की किसी भी अभिव्यक्ति पर कुछ प्रकार एक की है ।
मैं समानता चाहते । समानता की तरह कोई और? ज़रूर तुम करना। चलो कुछ करते हैं!
+
```c
import std.stdio;
import std.parallelism : parallel;
import std.math : sqrt;
void main() {
- // हम हमारे सरणी में वर्गमूल हर नंबर ले जाना चाहता हूँ ,
- // हम उपलब्ध है के रूप में और के रूप में कई कोर का लाभ ले।
+ // हम हमारे सरणी में वर्गमूल हर नंबर ले जाना चाहता हूँ ,
+ // हम उपलब्ध है के रूप में और के रूप में कई कोर का लाभ ले।
auto arr = new double[1_000_000];
- // संदर्भ के द्वारा एक सूचकांक , और एक सरणी तत्व का प्रयोग
+ // संदर्भ के द्वारा एक सूचकांक , और एक सरणी तत्व का प्रयोग
// और सिर्फ सरणी पर समानांतर फोन!
foreach(i, ref elem; parallel(arr)) {
ref = sqrt(i + 1.0);
}
}
-
-
```
diff --git a/hjson.html.markdown b/hjson.html.markdown
index 6b3cc3ed..e778dabb 100644
--- a/hjson.html.markdown
+++ b/hjson.html.markdown
@@ -3,7 +3,7 @@ language: Hjson
filename: learnhjson.hjson
contributors:
- ["MrTeferi", "https://github.com/MrTeferi"]
-lang: en
+lang: en-us
---
Hjson is an attempt to make [JSON](https://learnxinyminutes.com/docs/json/) more human readable.
diff --git a/httpie.html.markdown b/httpie.html.markdown
index 390e7b35..40481dff 100644
--- a/httpie.html.markdown
+++ b/httpie.html.markdown
@@ -117,4 +117,4 @@ http --follow GET https://example.com # Follow Redirects
## Further Reading
- [Official Documentation](https://httpie.io/docs/cli).
-- [Github](https://github.com/httpie).
+- [GitHub](https://github.com/httpie).
diff --git a/hu-hu/pythonlegacy-hu.html.markdown b/hu-hu/pythonlegacy-hu.html.markdown
index b5922766..483784ba 100644
--- a/hu-hu/pythonlegacy-hu.html.markdown
+++ b/hu-hu/pythonlegacy-hu.html.markdown
@@ -20,7 +20,7 @@ bele. Tulajdonképpen futtatható pszeudokód.
Szívesen fogadok visszajelzéseket! Elérsz itt: [@louiedinh](http://twitter.com/louiedinh)
vagy pedig a louiedinh [kukac] [google email szolgáltatása] címen.
-Figyelem: ez a leírás a Python 2.7 verziójára vonatkozok, illetve
+Figyelem: ez a leírás a Python 2.7 verziójára vonatkozik, illetve
általánosságban a 2.x verziókra. A Python 2.7 azonban már csak 2020-ig lesz
támogatva, ezért kezdőknek ajánlott, hogy a Python 3-mal kezdjék az
ismerkedést. A Python 3.x verzióihoz a [Python 3 bemutató](http://learnxinyminutes.com/docs/python/)
diff --git a/id-id/coffeescript-id.html.markdown b/id-id/coffeescript-id.html.markdown
index 7fa40bb6..fc876184 100644
--- a/id-id/coffeescript-id.html.markdown
+++ b/id-id/coffeescript-id.html.markdown
@@ -16,7 +16,7 @@ dan kompatibel dengan semua *runtime* JavaScript.
Lihat juga [website CoffeeScript](http://coffeescript.org/) yang memiliki tutorial lengkap tentang CoffeeScript.
-```CoffeeScript
+```coffeescript
# CoffeeScript adalah bahasa hipster.
# Mengikuti tren bahasa modern lainnya.
# Sehingga, seperti Ruby dan Python, untuk komentar digunakan tanda pagar.
diff --git a/id-id/markdown.html.markdown b/id-id/markdown.html.markdown
index 1ff1963b..22fcb17f 100644
--- a/id-id/markdown.html.markdown
+++ b/id-id/markdown.html.markdown
@@ -54,8 +54,8 @@ __Dan juga teks ini.__
**_Dan juga ini!_**
*__Dan ini!__*
-<!-- Di markdown ala Github, yang digunakan untuk me-render berkas markdown pada
-Github, kita juga punya coretan: -->
+<!-- Di markdown ala GitHub, yang digunakan untuk me-render berkas markdown pada
+GitHub, kita juga punya coretan: -->
~~Teks ini dirender dengan coretan.~~
@@ -155,7 +155,7 @@ di dalam kode Anda -->
John bahkan tidak tahu apa fungsi dari `go_to()` !
-<!-- Di Markdown ala Github, Anda dapat menggunakan syntax spesial untuk kode -->
+<!-- Di Markdown ala GitHub, Anda dapat menggunakan syntax spesial untuk kode -->
\`\`\`ruby <!-- kecuali hapus backlash tersebut ketika melakukannya, hanya ```ruby ! -->
def foobar
@@ -163,7 +163,7 @@ def foobar
end
\`\`\` <!-- Disini juga, tidak ada backslashes, hanya ``` -->
-<!-- Teks di atas tidak membutuhkan indentasi, plus Github akan menggunakan syntax
+<!-- Teks di atas tidak membutuhkan indentasi, plus GitHub akan menggunakan syntax
highlighting dari bahasa yang digunakan setelah ``` -->
<!-- Horizontal rule (<hr />) -->
@@ -236,14 +236,14 @@ Saya ingin mengetik *teks ini dikelilingi tanda bintang* tapi saya tidak mau tek
miring, jadi saya melakukan: \*teks ini dikelilingi tanda bintang\*.
<!-- Tombol keyboard -->
-<!-- Pada Markdown ala Github, Anda dapat menggunakan tag <kbd> untuk merepresentasikan tombol
+<!-- Pada Markdown ala GitHub, Anda dapat menggunakan tag <kbd> untuk merepresentasikan tombol
keyboard -->
Komputer Anda hang? Coba kirim sebuah
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
<!-- Tabel -->
-<!-- Tabel hanya tersedia pada Markdown ala Github dan sedikit merepotkan, namun jika Anda
+<!-- Tabel hanya tersedia pada Markdown ala GitHub dan sedikit merepotkan, namun jika Anda
sangat menginginkannya: -->
| Kol1 | Kol2 | Kol3 |
diff --git a/id-id/pyqt-id.html.markdown b/id-id/pyqt-id.html.markdown
index c4833d06..a9163326 100644
--- a/id-id/pyqt-id.html.markdown
+++ b/id-id/pyqt-id.html.markdown
@@ -15,10 +15,10 @@ lang: id-id
Tulisan ini diadaptasi dari **Intro Qt untuk C++** oleh [Aleksey Kholovchuk](https://github.com/vortexxx192). Kode-kode yang tertulis di sini akan menghasilkan fungsionalitas yang sama. Bedanya, versi ini dibangun menggunakan **PyQt**!
-```Python
+```python
import sys
from PyQt4 import QtGui
-
+
def window():
# Buat objek aplikasi
app = QtGui.QApplication(sys.argv)
@@ -45,7 +45,7 @@ if __name__ == '__main__':
Untuk menunjukkan beberapa fitur yang lebih canggih di **PyQt**, kita akan membangun elemen tambahan.
Di sini, kita akan membuat Kotak Popup Dialog, yang berguna untuk meminta pengguna untuk mengkonfirmasi keputusan atau untuk menampilkan informasi.
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
diff --git a/id-id/rst-id.html.markdown b/id-id/rst-id.html.markdown
index 06d80089..a5070d64 100644
--- a/id-id/rst-id.html.markdown
+++ b/id-id/rst-id.html.markdown
@@ -88,14 +88,14 @@ ini :)
Ada berbagai macam cara untuk membuat tautan:
-- Dengan menambahkan garis bawah setelah sebuah huruf : Github_ dan dengan
+- Dengan menambahkan garis bawah setelah sebuah huruf : GitHub_ dan dengan
menambahkan URL target setelah teks (cara ini mempunyai kelebihan dengan tidak
memasukkan URL yang tidak penting ke dalam teks yang bisa dibaca).
- Dengan mengetik URL lengkap yang dapat dipahami : https://github.com (akan
otomatis diubah menjadi sebuah link)
-- Dengan membuat link seperti di Markdown: `Github <https://github.com/>`_ .
+- Dengan membuat link seperti di Markdown: `GitHub <https://github.com/>`_ .
-.. _Github https://github.com/
+.. _GitHub https://github.com/
```
diff --git a/it-it/elixir-it.html.markdown b/it-it/elixir-it.html.markdown
index 48afe0c8..ce3e4535 100644
--- a/it-it/elixir-it.html.markdown
+++ b/it-it/elixir-it.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Luca 'Kino' Maroni", "https://github.com/kino90"]
- ["Joao Marques", "http://github.com/mrshankly"]
@@ -21,11 +21,11 @@ e molte altre funzionalità.
# Non esistono commenti multilinea,
# ma puoi concatenare più commenti.
-# Per usare la shell di elixir usa il comando `iex`.
+# Per usare la shell di Elixir usa il comando `iex`.
# Compila i tuoi moduli con il comando `elixirc`.
# Entrambi i comandi dovrebbero già essere nel tuo PATH se hai installato
-# elixir correttamente.
+# Elixir correttamente.
## ---------------------------
## -- Tipi di base
@@ -87,7 +87,7 @@ multi-linea.
<<?a, ?b, ?c>> #=> "abc"
[?a, ?b, ?c] #=> 'abc'
-# `?a` in elixir restituisce il valore ASCII della lettera `a`
+# `?a` in Elixir restituisce il valore ASCII della lettera `a`
?a #=> 97
# Per concatenare liste si usa `++`, per binari si usa `<>`
@@ -112,7 +112,7 @@ minore..maggiore = 1..10 # Puoi fare pattern matching anche sugli intervalli
5 * 2 #=> 10
10 / 2 #=> 5.0
-# In elixir l'operatore `/` restituisce sempre un decimale.
+# In Elixir l'operatore `/` restituisce sempre un decimale.
# Per fare una divisione intera si usa `div`
div(10, 2) #=> 5
@@ -173,7 +173,7 @@ else
end
# Ti ricordi il pattern matching?
-# Moltre strutture di controllo di flusso in elixir si basano su di esso.
+# Moltre strutture di controllo di flusso in Elixir si basano su di esso.
# `case` ci permette di confrontare un valore a diversi pattern:
case {:uno, :due} do
@@ -307,7 +307,7 @@ Geometria.area({:cerchio, 3}) #=> 28.25999999999999801048
# Geometria.area({:cerchio, "non_un_numero"})
#=> ** (FunctionClauseError) no function clause matching in Geometria.area/1
-# A causa dell'immutabilità dei dati, la ricorsione è molto frequente in elixir
+# A causa dell'immutabilità dei dati, la ricorsione è molto frequente in Elixir
defmodule Ricorsione do
def somma_lista([testa | coda], accumulatore) do
somma_lista(coda, accumulatore + testa)
@@ -382,7 +382,7 @@ end
## ---------------------------
# Elixir si basa sul modello degli attori per la concorrenza.
-# Tutto ciò di cui abbiamo bisogno per scrivere programmi concorrenti in elixir
+# Tutto ciò di cui abbiamo bisogno per scrivere programmi concorrenti in Elixir
# sono tre primitive: creare processi, inviare messaggi e ricevere messaggi.
# Per creare un nuovo processo si usa la funzione `spawn`, che riceve una
@@ -434,7 +434,7 @@ self() #=> #PID<0.27.0>
## Referenze
-* [Getting started guide](http://elixir-lang.org/getting_started/1.html) dalla [pagina web ufficiale di elixir](http://elixir-lang.org)
+* [Getting started guide](http://elixir-lang.org/getting_started/1.html) dalla [pagina web ufficiale di Elixir](http://elixir-lang.org)
* [Documentazione Elixir](https://elixir-lang.org/docs.html)
* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) di Dave Thomas
* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf)
diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown
index c14bc175..609d3bb7 100644
--- a/it-it/markdown.html.markdown
+++ b/it-it/markdown.html.markdown
@@ -72,7 +72,7 @@ __Come pure questo.__
*__E questo!__*
```
-In Github Flavored Markdown, che è utilizzato per renderizzare i file markdown su Github, è presente anche lo stile barrato:
+In GitHub Flavored Markdown, che è utilizzato per renderizzare i file markdown su GitHub, è presente anche lo stile barrato:
```md
~~Questo testo è barrato.~~
@@ -183,7 +183,7 @@ Potete inoltre inserire un altro tab (o altri quattro spazi) per indentare il vo
```md
my_array.each do |item|
- puts item
+ puts item
end
```
@@ -193,14 +193,17 @@ Codice inline può essere inserito usando il carattere backtick `
Giovanni non sapeva neppure a cosa servisse la funzione `go_to()`!
```
-In Github Flavored Markdown, potete inoltre usare una sintassi speciale per il codice
-<pre>
-<code class="highlight">&#x60;&#x60;&#x60;ruby
+In GitHub Flavored Markdown, potete inoltre usare una sintassi speciale per il codice
+
+````md
+```ruby
def foobar
- puts "Hello world!"
+ puts "Hello world!"
end
-&#x60;&#x60;&#x60;</code></pre>
-Se usate questa sintassi, il testo non richiederà di essere indentato, inoltre Github userà l'evidenziazione della sintassi del linguaggio specificato dopo i \`\`\` iniziali
+```
+````
+
+Se usate questa sintassi, il testo non richiederà di essere indentato, inoltre GitHub userà l'evidenziazione della sintassi del linguaggio specificato dopo i \`\`\` iniziali
## Linea orizzontale
Le linee orizzontali (`<hr/>`) sono inserite facilmente usanto tre o più asterischi o trattini, con o senza spazi.
@@ -282,7 +285,7 @@ Voglio inserire *questo testo circondato da asterischi* ma non voglio che venga
```
### Combinazioni di tasti
-In Github Flavored Markdown, potete utilizzare il tag `<kbd>` per raffigurare i tasti della tastiera.
+In GitHub Flavored Markdown, potete utilizzare il tag `<kbd>` per raffigurare i tasti della tastiera.
```md
Il tuo computer è crashato? Prova a premere
@@ -290,7 +293,7 @@ Il tuo computer è crashato? Prova a premere
```
### Tabelle
-Le tabelle sono disponibili solo in Github Flavored Markdown e sono leggeremente complesse, ma se proprio volete inserirle fate come segue:
+Le tabelle sono disponibili solo in GitHub Flavored Markdown e sono leggeremente complesse, ma se proprio volete inserirle fate come segue:
```md
| Col1 | Col2 | Col3 |
diff --git a/it-it/pyqt-it.html.markdown b/it-it/pyqt-it.html.markdown
index 7238dd7b..7b5a98c2 100644
--- a/it-it/pyqt-it.html.markdown
+++ b/it-it/pyqt-it.html.markdown
@@ -14,12 +14,12 @@ lang: it-it
Questo è un adattamento sull'introduzione di C ++ a QT di [Aleksey Kholovchuk] (https://github.com/vortexxx192
), alcuni degli esempi di codice dovrebbero avere la stessa funzionalità
-che avrebbero se fossero fatte usando pyqt!
+che avrebbero se fossero fatte usando pyqt!
```python
import sys
from PyQt4 import QtGui
-
+
def window():
# Crea un oggetto applicazione
app = QtGui.QApplication(sys.argv)
@@ -47,7 +47,7 @@ if __name__ == '__main__':
Per ottenere alcune delle funzionalità più avanzate in **pyqt**, dobbiamo iniziare a cercare di creare elementi aggiuntivi.
Qui mostriamo come creare una finestra popup di dialogo, utile per chiedere all'utente di confermare una decisione o fornire informazioni
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
@@ -66,7 +66,7 @@ def window():
w.setWindowTitle("PyQt Dialog")
w.show()
sys.exit(app.exec_())
-
+
# Questa funzione dovrebbe creare una finestra di dialogo con un pulsante
# che aspetta di essere cliccato e quindi esce dal programma
def showdialog():
diff --git a/it-it/rst-it.html.markdown b/it-it/rst-it.html.markdown
index a834e899..3885cbd8 100644
--- a/it-it/rst-it.html.markdown
+++ b/it-it/rst-it.html.markdown
@@ -81,11 +81,11 @@ Anche le tabelle più complesse possono essere inserite facilmente (colonne e/o
Esistono diversi modi per creare collegamenti:
-- Aggiungendo un underscore dopo una parola: Github_ e aggiungendo l'URL di destinazione dopo il testo (questo metodo ha il vantaggio di non inserire URL non necessari all'interno del testo leggibile).
+- Aggiungendo un underscore dopo una parola: GitHub_ e aggiungendo l'URL di destinazione dopo il testo (questo metodo ha il vantaggio di non inserire URL non necessari all'interno del testo leggibile).
- Digitando un URL completo: https://github.com/ (verrà automaticamente convertito in un collegamento)
-- Utilizzando una sintassi simile a Markdown: `Github <https://github.com/>`_ .
+- Utilizzando una sintassi simile a Markdown: `GitHub <https://github.com/>`_ .
-.. _Github https://github.com/
+.. _GitHub https://github.com/
```
diff --git a/it-it/toml-it.html.markdown b/it-it/toml-it.html.markdown
index 99082048..beb63096 100644
--- a/it-it/toml-it.html.markdown
+++ b/it-it/toml-it.html.markdown
@@ -1,276 +1,276 @@
----
-language: toml
-filename: learntoml-it.toml
-contributors:
- - ["Alois de Gouvello", "https://github.com/aloisdg"]
-translators:
- - ["Christian Grasso", "https://grasso.io"]
-lang: it-it
----
-
-TOML è l'acronimo di _Tom's Obvious, Minimal Language_. È un linguaggio per la
-serializzazione di dati, progettato per i file di configurazione.
-
-È un'alternativa a linguaggi come YAML e JSON, che punta ad essere più leggibile
-per le persone. Allo stesso tempo, TOML può essere utilizzato in modo abbastanza
-semplice nella maggior parte dei linguaggi di programmazione, in quanto è
-progettato per essere tradotto senza ambiguità in una hash table.
-
-Tieni presente che TOML è ancora in fase di sviluppo, e la sua specifica non è
-ancora stabile. Questo documento utilizza TOML 0.4.0.
-
-```toml
-# I commenti in TOML sono fatti così.
-
-################
-# TIPI SCALARI #
-################
-
-# Il nostro oggetto root (corrispondente all'intero documento) sarà una mappa,
-# anche chiamata dizionario, hash o oggetto in altri linguaggi.
-
-# La key, il simbolo di uguale e il valore devono trovarsi sulla stessa riga,
-# eccetto per alcuni tipi di valori.
-key = "value"
-stringa = "ciao"
-numero = 42
-float = 3.14
-boolean = true
-data = 1979-05-27T07:32:00-08:00
-notazScientifica = 1e+12
-"puoi utilizzare le virgolette per la key" = true # Puoi usare " oppure '
-"la key può contenere" = "lettere, numeri, underscore e trattini"
-
-############
-# Stringhe #
-############
-
-# Le stringhe possono contenere solo caratteri UTF-8 validi.
-# Possiamo effettuare l'escape dei caratteri, e alcuni hanno delle sequenze
-# di escape compatte. Ad esempio, \t corrisponde al TAB.
-stringaSemplice = "Racchiusa tra virgolette. \"Usa il backslash per l'escape\"."
-
-stringaMultiriga = """
-Racchiusa da tre virgolette doppie all'inizio e
-alla fine - consente di andare a capo."""
-
-stringaLiteral = 'Virgolette singole. Non consente di effettuare escape.'
-
-stringaMultirigaLiteral = '''
-Racchiusa da tre virgolette singole all'inizio e
-alla fine - consente di andare a capo.
-Anche in questo caso non si può fare escape.
-Il primo ritorno a capo viene eliminato.
- Tutti gli altri spazi aggiuntivi
- vengono mantenuti.
-'''
-
-# Per i dati binari è consigliabile utilizzare Base64 e
-# gestirli manualmente dall'applicazione.
-
-##########
-# Interi #
-##########
-
-## Gli interi possono avere o meno un segno (+, -).
-## Non si possono inserire zero superflui all'inizio.
-## Non è possibile inoltre utilizzare valori numerici
-## non rappresentabili con una sequenza di cifre.
-int1 = +42
-int2 = 0
-int3 = -21
-
-## Puoi utilizzare gli underscore per migliorare la leggibilità.
-## Fai attenzione a non inserirne due di seguito.
-int4 = 5_349_221
-int5 = 1_2_3_4_5 # VALIDO, ma da evitare
-
-#########
-# Float #
-#########
-
-# I float permettono di rappresentare numeri decimali.
-flt1 = 3.1415
-flt2 = -5e6
-flt3 = 6.626E-34
-
-###########
-# Boolean #
-###########
-
-# I valori boolean (true/false) devono essere scritti in minuscolo.
-bool1 = true
-bool2 = false
-
-############
-# Data/ora #
-############
-
-data1 = 1979-05-27T07:32:00Z # Specifica RFC 3339/ISO 8601 (UTC)
-data2 = 1979-05-26T15:32:00+08:00 # RFC 3339/ISO 8601 con offset
-
-######################
-# TIPI DI COLLECTION #
-######################
-
-#########
-# Array #
-#########
-
-array1 = [ 1, 2, 3 ]
-array2 = [ "Le", "virgole", "sono", "delimitatori" ]
-array3 = [ "Non", "unire", "tipi", "diversi" ]
-array4 = [ "tutte", 'le stringhe', """hanno lo stesso""", '''tipo''' ]
-array5 = [
- "Gli spazi vuoti", "sono", "ignorati"
-]
-
-###########
-# Tabelle #
-###########
-
-# Le tabelle (o hash table o dizionari) sono collection di coppie key/value.
-# Iniziano con un nome tra parentesi quadre su una linea separata.
-# Le tabelle vuote (senza alcun valore) sono valide.
-[tabella]
-
-# Tutti i valori che si trovano sotto il nome della tabella
-# appartengono alla tabella stessa (finchè non ne viene creata un'altra).
-# L'ordine di questi valori non è garantito.
-[tabella-1]
-key1 = "una stringa"
-key2 = 123
-
-[tabella-2]
-key1 = "un'altra stringa"
-key2 = 456
-
-# Utilizzando i punti è possibile creare delle sottotabelle.
-# Ogni parte suddivisa dai punti segue le regole delle key per il nome.
-[tabella-3."sotto.tabella"]
-key1 = "prova"
-
-# Ecco l'equivalente JSON della tabella precedente:
-# { "tabella-3": { "sotto.tabella": { "key1": "prova" } } }
-
-# Gli spazi non vengono considerati, ma è consigliabile
-# evitare di usare spazi superflui.
-[a.b.c] # consigliato
-[ d.e.f ] # identico a [d.e.f]
-
-# Non c'è bisogno di creare le tabelle superiori per creare una sottotabella.
-# [x] queste
-# [x.y] non
-# [x.y.z] servono
-[x.y.z.w] # per creare questa tabella
-
-# Se non è stata già creata prima, puoi anche creare
-# una tabella superiore più avanti.
-[a.b]
-c = 1
-
-[a]
-d = 2
-
-# Non puoi definire una key o una tabella più di una volta.
-
-# ERRORE
-[a]
-b = 1
-
-[a]
-c = 2
-
-# ERRORE
-[a]
-b = 1
-
-[a.b]
-c = 2
-
-# I nomi delle tabelle non possono essere vuoti.
-[] # NON VALIDO
-[a.] # NON VALIDO
-[a..b] # NON VALIDO
-[.b] # NON VALIDO
-[.] # NON VALIDO
-
-##################
-# Tabelle inline #
-##################
-
-tabelleInline = { racchiuseData = "{ e }", rigaSingola = true }
-punto = { x = 1, y = 2 }
-
-####################
-# Array di tabelle #
-####################
-
-# Un array di tabelle può essere creato utilizzando due parentesi quadre.
-# Tutte le tabelle con questo nome saranno elementi dell'array.
-# Gli elementi vengono inseriti nell'ordine in cui si trovano.
-
-[[prodotti]]
-nome = "array di tabelle"
-sku = 738594937
-tabelleVuoteValide = true
-
-[[prodotti]]
-
-[[prodotti]]
-nome = "un altro item"
-sku = 284758393
-colore = "grigio"
-
-# Puoi anche creare array di tabelle nested. Le sottotabelle con doppie
-# parentesi quadre apparterranno alla tabella più vicina sopra di esse.
-
-[[frutta]]
- nome = "mela"
-
- [frutto.geometria]
- forma = "sferica"
- nota = "Sono una proprietà del frutto"
-
- [[frutto.colore]]
- nome = "rosso"
- nota = "Sono un oggetto di un array dentro mela"
-
- [[frutto.colore]]
- nome = "verde"
- nota = "Sono nello stesso array di rosso"
-
-[[frutta]]
- nome = "banana"
-
- [[frutto.colore]]
- nome = "giallo"
- nota = "Anche io sono un oggetto di un array, ma dentro banana"
-```
-
-Ecco l'equivalente JSON dell'ultima tabella:
-
-```json
-{
- "frutta": [
- {
- "nome": "mela",
- "geometria": { "forma": "sferica", "nota": "..."},
- "colore": [
- { "nome": "rosso", "nota": "..." },
- { "nome": "verde", "nota": "..." }
- ]
- },
- {
- "nome": "banana",
- "colore": [
- { "nome": "giallo", "nota": "..." }
- ]
- }
- ]
-}
-```
-
-### Altre risorse
-
-+ [Repository ufficiale di TOML](https://github.com/toml-lang/toml)
+---
+language: toml
+filename: learntoml-it.toml
+contributors:
+ - ["Alois de Gouvello", "https://github.com/aloisdg"]
+translators:
+ - ["Christian Grasso", "https://grasso.io"]
+lang: it-it
+---
+
+TOML è l'acronimo di _Tom's Obvious, Minimal Language_. È un linguaggio per la
+serializzazione di dati, progettato per i file di configurazione.
+
+È un'alternativa a linguaggi come YAML e JSON, che punta ad essere più leggibile
+per le persone. Allo stesso tempo, TOML può essere utilizzato in modo abbastanza
+semplice nella maggior parte dei linguaggi di programmazione, in quanto è
+progettato per essere tradotto senza ambiguità in una hash table.
+
+Tieni presente che TOML è ancora in fase di sviluppo, e la sua specifica non è
+ancora stabile. Questo documento utilizza TOML 0.4.0.
+
+```toml
+# I commenti in TOML sono fatti così.
+
+################
+# TIPI SCALARI #
+################
+
+# Il nostro oggetto root (corrispondente all'intero documento) sarà una mappa,
+# anche chiamata dizionario, hash o oggetto in altri linguaggi.
+
+# La key, il simbolo di uguale e il valore devono trovarsi sulla stessa riga,
+# eccetto per alcuni tipi di valori.
+key = "value"
+stringa = "ciao"
+numero = 42
+float = 3.14
+boolean = true
+data = 1979-05-27T07:32:00-08:00
+notazScientifica = 1e+12
+"puoi utilizzare le virgolette per la key" = true # Puoi usare " oppure '
+"la key può contenere" = "lettere, numeri, underscore e trattini"
+
+############
+# Stringhe #
+############
+
+# Le stringhe possono contenere solo caratteri UTF-8 validi.
+# Possiamo effettuare l'escape dei caratteri, e alcuni hanno delle sequenze
+# di escape compatte. Ad esempio, \t corrisponde al TAB.
+stringaSemplice = "Racchiusa tra virgolette. \"Usa il backslash per l'escape\"."
+
+stringaMultiriga = """
+Racchiusa da tre virgolette doppie all'inizio e
+alla fine - consente di andare a capo."""
+
+stringaLiteral = 'Virgolette singole. Non consente di effettuare escape.'
+
+stringaMultirigaLiteral = '''
+Racchiusa da tre virgolette singole all'inizio e
+alla fine - consente di andare a capo.
+Anche in questo caso non si può fare escape.
+Il primo ritorno a capo viene eliminato.
+ Tutti gli altri spazi aggiuntivi
+ vengono mantenuti.
+'''
+
+# Per i dati binari è consigliabile utilizzare Base64 e
+# gestirli manualmente dall'applicazione.
+
+##########
+# Interi #
+##########
+
+## Gli interi possono avere o meno un segno (+, -).
+## Non si possono inserire zero superflui all'inizio.
+## Non è possibile inoltre utilizzare valori numerici
+## non rappresentabili con una sequenza di cifre.
+int1 = +42
+int2 = 0
+int3 = -21
+
+## Puoi utilizzare gli underscore per migliorare la leggibilità.
+## Fai attenzione a non inserirne due di seguito.
+int4 = 5_349_221
+int5 = 1_2_3_4_5 # VALIDO, ma da evitare
+
+#########
+# Float #
+#########
+
+# I float permettono di rappresentare numeri decimali.
+flt1 = 3.1415
+flt2 = -5e6
+flt3 = 6.626E-34
+
+###########
+# Boolean #
+###########
+
+# I valori boolean (true/false) devono essere scritti in minuscolo.
+bool1 = true
+bool2 = false
+
+############
+# Data/ora #
+############
+
+data1 = 1979-05-27T07:32:00Z # Specifica RFC 3339/ISO 8601 (UTC)
+data2 = 1979-05-26T15:32:00+08:00 # RFC 3339/ISO 8601 con offset
+
+######################
+# TIPI DI COLLECTION #
+######################
+
+#########
+# Array #
+#########
+
+array1 = [ 1, 2, 3 ]
+array2 = [ "Le", "virgole", "sono", "delimitatori" ]
+array3 = [ "Non", "unire", "tipi", "diversi" ]
+array4 = [ "tutte", 'le stringhe', """hanno lo stesso""", '''tipo''' ]
+array5 = [
+ "Gli spazi vuoti", "sono", "ignorati"
+]
+
+###########
+# Tabelle #
+###########
+
+# Le tabelle (o hash table o dizionari) sono collection di coppie key/value.
+# Iniziano con un nome tra parentesi quadre su una linea separata.
+# Le tabelle vuote (senza alcun valore) sono valide.
+[tabella]
+
+# Tutti i valori che si trovano sotto il nome della tabella
+# appartengono alla tabella stessa (finchè non ne viene creata un'altra).
+# L'ordine di questi valori non è garantito.
+[tabella-1]
+key1 = "una stringa"
+key2 = 123
+
+[tabella-2]
+key1 = "un'altra stringa"
+key2 = 456
+
+# Utilizzando i punti è possibile creare delle sottotabelle.
+# Ogni parte suddivisa dai punti segue le regole delle key per il nome.
+[tabella-3."sotto.tabella"]
+key1 = "prova"
+
+# Ecco l'equivalente JSON della tabella precedente:
+# { "tabella-3": { "sotto.tabella": { "key1": "prova" } } }
+
+# Gli spazi non vengono considerati, ma è consigliabile
+# evitare di usare spazi superflui.
+[a.b.c] # consigliato
+[ d.e.f ] # identico a [d.e.f]
+
+# Non c'è bisogno di creare le tabelle superiori per creare una sottotabella.
+# [x] queste
+# [x.y] non
+# [x.y.z] servono
+[x.y.z.w] # per creare questa tabella
+
+# Se non è stata già creata prima, puoi anche creare
+# una tabella superiore più avanti.
+[a.b]
+c = 1
+
+[a]
+d = 2
+
+# Non puoi definire una key o una tabella più di una volta.
+
+# ERRORE
+[a]
+b = 1
+
+[a]
+c = 2
+
+# ERRORE
+[a]
+b = 1
+
+[a.b]
+c = 2
+
+# I nomi delle tabelle non possono essere vuoti.
+[] # NON VALIDO
+[a.] # NON VALIDO
+[a..b] # NON VALIDO
+[.b] # NON VALIDO
+[.] # NON VALIDO
+
+##################
+# Tabelle inline #
+##################
+
+tabelleInline = { racchiuseData = "{ e }", rigaSingola = true }
+punto = { x = 1, y = 2 }
+
+####################
+# Array di tabelle #
+####################
+
+# Un array di tabelle può essere creato utilizzando due parentesi quadre.
+# Tutte le tabelle con questo nome saranno elementi dell'array.
+# Gli elementi vengono inseriti nell'ordine in cui si trovano.
+
+[[prodotti]]
+nome = "array di tabelle"
+sku = 738594937
+tabelleVuoteValide = true
+
+[[prodotti]]
+
+[[prodotti]]
+nome = "un altro item"
+sku = 284758393
+colore = "grigio"
+
+# Puoi anche creare array di tabelle nested. Le sottotabelle con doppie
+# parentesi quadre apparterranno alla tabella più vicina sopra di esse.
+
+[[frutta]]
+ nome = "mela"
+
+ [frutto.geometria]
+ forma = "sferica"
+ nota = "Sono una proprietà del frutto"
+
+ [[frutto.colore]]
+ nome = "rosso"
+ nota = "Sono un oggetto di un array dentro mela"
+
+ [[frutto.colore]]
+ nome = "verde"
+ nota = "Sono nello stesso array di rosso"
+
+[[frutta]]
+ nome = "banana"
+
+ [[frutto.colore]]
+ nome = "giallo"
+ nota = "Anche io sono un oggetto di un array, ma dentro banana"
+```
+
+Ecco l'equivalente JSON dell'ultima tabella:
+
+```json
+{
+ "frutta": [
+ {
+ "nome": "mela",
+ "geometria": { "forma": "sferica", "nota": "..."},
+ "colore": [
+ { "nome": "rosso", "nota": "..." },
+ { "nome": "verde", "nota": "..." }
+ ]
+ },
+ {
+ "nome": "banana",
+ "colore": [
+ { "nome": "giallo", "nota": "..." }
+ ]
+ }
+ ]
+}
+```
+
+### Altre risorse
+
++ [Repository ufficiale di TOML](https://github.com/toml-lang/toml)
diff --git a/ja-jp/python-jp.html.markdown b/ja-jp/python-jp.html.markdown
index 18e7d1b8..363d00a0 100644
--- a/ja-jp/python-jp.html.markdown
+++ b/ja-jp/python-jp.html.markdown
@@ -11,6 +11,7 @@ contributors:
translators:
- ["kakakaya", "https://github.com/kakakaya"]
- ["Ryota Kayanuma", "https://github.com/PicoSushi"]
+ - ["Kenryu Shibata", "https://github.com/kenryuS"]
filename: learnpython-jp.py
lang: ja-jp
---
@@ -180,7 +181,7 @@ bool({}) # => False
bool(()) # => False
####################################################
-# 2. Variables and Collections
+# 2. 変数と集合
####################################################
# Python にはprint関数があります。
@@ -400,7 +401,7 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6}
####################################################
-# 3. 制御の流れとiterable
+# 3. 制御の流れと反復可能オブジェクト
####################################################
# まずは変数を作りましょう。
@@ -429,7 +430,7 @@ for animal in ["dog", "cat", "mouse"]:
print("{} is a mammal".format(animal))
"""
-"range(数値)" は、ゼロから与えられた数値までのiterableを返します。
+"range(数値)" は、ゼロから与えられた数値までのiterable(反復可能オブジェクト)を返します。
出力:
0
1
@@ -649,7 +650,7 @@ print(ceil(3.7)) # => 4.0
print(floor(3.7)) # => 3.0
# 全部の関数をモジュールからインポートすることができます。
-# Warning: この方法は推奨されません。
+# 注意: この方法は推奨されません。
from math import *
# 短い名前でモジュールをインポートすることができます。
@@ -990,9 +991,9 @@ print(say()) # Can you buy me a beer?
print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
```
-## Ready For More?
+## さらなる学習の準備ができましたか?
-### Free Online
+### 無料のオンラインコンテンツ
* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
* [Ideas for Python Projects](http://pythonpracticeprojects.com)
diff --git a/ja-jp/rust-jp.html.markdown b/ja-jp/rust-jp.html.markdown
new file mode 100644
index 00000000..3eb381ab
--- /dev/null
+++ b/ja-jp/rust-jp.html.markdown
@@ -0,0 +1,351 @@
+---
+language: Rust
+contributors:
+ - ["P1start", "http://p1start.github.io/"]
+filename: learnrust-jp.rs
+translators:
+ - ["Takashi Takeda", "https://github.com/Takashicc"]
+lang: ja-jp
+---
+
+RustはMozilla Researchによって開発されたプログラミング言語です。
+Rustは低レベルの性能制御と高レベルの利便性と、安全性の保証を兼ね備えています。
+
+ガベージコレクションやランタイムを必要としないことから上記の目標が達成出来ます。
+それによってRustライブラリをC言語の「完全互換品」として使用することが可能です。
+
+Rustの最初のリリースである0.1は、2012年1月にリリースされ、
+その後3年間の開発は非常に速く進み、最近までは安定板リリースの利用は推奨されていませんでした。
+代わりにナイトリービルドを使用することが一般的なアドバイスでした。
+
+2015年5月15日、後方互換性を完全に保障したRust 1.0がリリースされました。
+コンパイル時間などの改善は、現在ナイトリービルドで提供されています。
+Rustはトレインリリースモデルを採用しており、6週間ごとにリリースしています。
+Rust 1.1 ベータ版は、Rust 1.0がリリースされたのと同時にリリースされました。
+
+Rustは比較的低レベルの言語ですが、一般的に高水準言語に見られるようないくつかの概念を持っています。
+これによりRustはただ速いだけではなく、コーディングが簡単で効率的に書くことが出来ます。
+
+```rust
+// これはコメントです。 行コメントはこのように書けます...
+// そしてこのように複数行に分けて書くこともできます。
+
+/// ドキュメントコメントはこのように書けて、マークダウン記法をサポートしています。
+/// # Examples
+///
+/// ```
+/// let five = 5
+/// ```
+
+////////////
+// 1. 基本 //
+////////////
+
+#[allow(dead_code)]
+// 関数
+// `i32` は32ビットの符号付き整数の型です
+fn add2(x: i32, y: i32) -> i32 {
+ // 暗黙の戻り値 (セミコロンなし)
+ x + y
+}
+
+#[allow(unused_variables)]
+#[allow(unused_assignments)]
+#[allow(dead_code)]
+// Main関数
+fn main() {
+ // 数値 //
+
+ // 不変な変数
+ let x: i32 = 1;
+
+ // 整数/浮動小数点の型を数値の末尾に
+ let y: i32 = 13i32;
+ let f: f64 = 1.3f64;
+
+ // 型推論
+ // ほとんどの場合、Rustコンパイラは変数の型を推測することができるため、
+ // 明示的に型アノテーションを書く必要はありません。
+ // このチュートリアルでは、多くの場所で明示的に型がアノテーションされていますが、
+ // あくまで説明目的です。型推論はほとんどの場合処理することができます。
+ let implicit_x = 1;
+ let implicit_f = 1.3;
+
+ // 算術
+ let sum = x + y + 13;
+
+ // 可変な変数
+ let mut mutable = 1;
+ mutable = 4;
+ mutable += 2;
+
+ // 文字列 //
+
+ // 文字列リテラル
+ let x: &str = "hello world!";
+
+ // プリント
+ println!("{} {}", f, x); // 1.3 hello world
+
+ // `String`はヒープに割り当てられた文字列です。
+ // `Vec<u8>`としてヒープに格納され、
+ // 常に有効なUTF-8シーケンス(ヌル文字で終了していない)を保持します。
+ let s: String = "hello world".to_string();
+
+ // 文字列スライスは不変なビューを別の文字列に変換します。
+ // これは基本的に文字列への不変のポインタのペアを保持しており、
+ // 文字そのものは保持していません。
+ // 文字列バッファの先頭と末尾へのポイントだけを保持しています。
+ // 静的割り当てられるか、別のオブジェクトに含まれます。(この場合は`s`)
+ // 文字列スライスは`&[u8]`を`Vec<T>`に変換するようなものです。
+ let s_slice: &str = &s;
+
+ println!("{} {}", s, s_slice); // hello world hello world
+
+ // ベクター/配列 //
+
+ // 固定サイズの配列
+ let four_ints: [i32; 4] = [1, 2, 3, 4];
+
+ // 動的配列(ベクター)
+ let mut vector: Vec<i32> = vec![1, 2, 3, 4];
+ vector.push(5);
+
+ // スライスは不変なビューをベクターまたは配列に変換します。
+ // これは文字列スライスによく似ていますが、ベクターに対してのものです。
+ let slice: &[i32] = &vector;
+
+ // デバッグ形式で何かを表示する際は、`{:?}`を使用できます。
+ println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
+
+ // タプル //
+
+ // タプルは固定サイズの値の集合でできており、値それぞれが異なる型でもよい
+ let x: (i32, &str, f64) = (1, "hello", 3.4);
+
+ // `let`をデストラクト
+ let (a, b, c) = x;
+ println!("{} {} {}", a, b, c); // 1 hello 3.4
+
+ // インデックス
+ println!("{}", x.1); // hello
+
+ ///////////
+ // 2. 型 //
+ ///////////
+
+ // 構造体
+ struct Point {
+ x: i32,
+ y: i32,
+ }
+
+ let origin: Point = Point { x: 0, y: 0 };
+
+ // 名前のないフィールドで構成された構造体は、タプル構造体と言われる。
+ struct Point2(i32, i32);
+
+ let origin2 = Point2(0, 0);
+
+ // C言語風列挙型
+ enum Direction {
+ Left,
+ Right,
+ Up,
+ Down,
+ }
+
+ let up = Direction::Up;
+
+ // フィールドがある列挙型
+ enum OptionalI32 {
+ AnI32(i32),
+ Nothing,
+ }
+
+ let two: OptionalI32 = OptionalI32::AnI32(2);
+ let nothing = OptionalI32::Nothing;
+
+ // ジェネリクス //
+
+ struct Foo<T> { bar: T }
+
+ // 以下は標準ライブラリで定義されている`Option`です。
+ enum Optional<T> {
+ SomeVal(T),
+ NoVal,
+ }
+
+ // メソッド //
+
+ impl<T> Foo<T> {
+ // メソッドは明示的に`self`パラメータを受け取ります。
+ fn bar(&self) -> &T { // `self`は借用されています。
+ &self.bar
+ }
+ fn bar_mut(&mut self) -> &mut T { // `self`は可変に借用されています。
+ &mut self.bar
+ }
+ fn into_bar(self) -> T { // `self`は消費されています。
+ self.bar
+ }
+ }
+
+ let a_foo = Foo { bar: 1 };
+ println!("{}", a_foo.bar()); // 1
+
+ // トレイト (他の言語ではインターフェースや型クラスとして知られています) //
+
+ trait Frobnicate<T> {
+ fn frobnicate(self) -> Option<T>;
+ }
+
+ impl<T> Frobnicate<T> for Foo<T> {
+ fn frobnicate(self) -> Option<T> {
+ Some(self.bar)
+ }
+ }
+
+ let another_foo = Foo { bar: 1 };
+ println!("{:?}", another_foo.frobnicate()); // Some(1)
+
+ // 関数ポインタの種類 //
+
+ fn fibonacci(n: u32) -> u32 {
+ match n {
+ 0 => 1,
+ 1 => 1,
+ _ => fibonacci(n - 1) + fibonacci(n - 2),
+ }
+ }
+
+ type FunctionPointer = fn(u32) -> u32;
+
+ let fib : FunctionPointer = fibonacci;
+ println!("Fib: {}", fib(4));
+
+ /////////////////////////
+ // 3. パターンマッチング //
+ /////////////////////////
+
+ let foo = OptionalI32::AnI32(1);
+ match foo {
+ OptionalI32::AnI32(n) => println!("it’s an i32: {}", n),
+ OptionalI32::Nothing => println!("it’s nothing!"),
+ }
+
+ // 応用的なパターンマッチング
+ struct FooBar { x: i32, y: OptionalI32 }
+ let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) };
+
+ match bar {
+ FooBar { x: 0, y: OptionalI32::AnI32(0) } =>
+ println!("The numbers are zero!"),
+ FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m =>
+ println!("The numbers are the same"),
+ FooBar { x: n, y: OptionalI32::AnI32(m) } =>
+ println!("Different numbers: {} {}", n, m),
+ FooBar { x: _, y: OptionalI32::Nothing } =>
+ println!("The second number is Nothing!"),
+ }
+
+ //////////////////
+ // 4. 制御フロー //
+ //////////////////
+
+ // `for`ループ/イテレーション
+ let array = [1, 2, 3];
+ for i in array {
+ println!("{}", i);
+ }
+
+ // 範囲
+ for i in 0u32..10 {
+ print!("{} ", i);
+ }
+ println!("");
+ // 右記にある文をプリントします `0 1 2 3 4 5 6 7 8 9 `
+
+ // `if`
+ if 1 == 1 {
+ println!("Maths is working!");
+ } else {
+ println!("Oh no...");
+ }
+
+ // 式として使う`if`
+ let value = if true {
+ "good"
+ } else {
+ "bad"
+ };
+
+ // `while` loop
+ while 1 == 1 {
+ println!("The universe is operating normally.");
+ // break文でwhileループから抜け出せます。
+ // 無駄な繰り返しを避けることができます。
+ break
+ }
+
+ // 無限ループ
+ loop {
+ println!("Hello!");
+ // break文でループから抜け出せます。
+ break
+ }
+
+ ///////////////////////////
+ // 5. メモリ安全とポインタ //
+ ///////////////////////////
+
+ // 所有ポインタはポインタを「所有」できるのは、一度に1つだけです。
+ // つまり、`Box`がそのスコープから離れると、自動的に安全に解放されます。
+ let mut mine: Box<i32> = Box::new(3);
+ *mine = 5; // デリファレンス
+ // ここで`now_its_mine`が`mine`の所有権を取得します。言い換えると`mine`がムーブしました。
+ let mut now_its_mine = mine;
+ *now_its_mine += 2;
+
+ println!("{}", now_its_mine); // 7
+ // println!("{}", mine); // これは`now_its_mine`がポインタを所有しているため、コンパイルができません。
+
+ // 参照は他のデータを参照する不変なポインタです。
+ // 値を参照する場合、値を「借用」したと言います。
+ // 値が不変に借用されている間は、値を変更したり、ムーブすることはできない。
+ // 借用は借用されている変数が使用されている最後まで有効です。
+ let mut var = 4;
+ var = 3;
+ let ref_var: &i32 = &var;
+
+ println!("{}", var); // `mine`と違って、`var`はまだ使用できます。
+ println!("{}", *ref_var);
+ // var = 5; // `var`が借用されているため、コンパイルができません。
+ // *ref_var = 6; // `ref_var`が不変な参照であるため、コンパイルできません。
+ ref_var; // 操作は行っていませんが、使用されているとみなされ、借用が有効になります。
+ var = 2; // `ref_var`上記行以降使用されていないため、借用は終了しています。
+
+ // 可変な参照
+ // 値が可変な借用である間は、一切アクセスできません。
+ let mut var2 = 4;
+ let ref_var2: &mut i32 = &mut var2;
+ *ref_var2 += 2; // '*'は可変な参照をされた`var2`を指すために使用されます。
+
+ println!("{}", *ref_var2); // 6 , // `var2`はコンパイルされません。
+ // `ref_var2`は型が&mut i32であるため、i32への可変な参照が格納されています。値は入っていません。
+ // var2 = 2; // `var2`が借用されているため、コンパイルできません。
+ ref_var2; // 操作は行っていませんが、使用されているとみなされ、借用が有効になります。
+}
+```
+
+## 補足資料
+
+Rustにはまだまだ多くの魅力がありますが、ここではRustの基本的な知識をお伝えします。
+Rustについてもっと知りたい場合は、[The Rust Programming
+Language](http://doc.rust-lang.org/book/index.html)
+を読んで、[/r/rust](http://reddit.com/r/rust)をチェックしてみてください。
+irc.mozilla.orgの#rustチャンネルにいる人たちも、新参者にも熱心に助けてくれます。
+
+また、Rustの機能を公式のオンラインコンパイラで試すこともできます。
+[Rust playpen](http://play.rust-lang.org) またはメインの
+[Rust website](http://rust-lang.org).
diff --git a/ko-kr/markdown-kr.html.markdown b/ko-kr/markdown-kr.html.markdown
index 397e9f30..0167f0ff 100644
--- a/ko-kr/markdown-kr.html.markdown
+++ b/ko-kr/markdown-kr.html.markdown
@@ -25,15 +25,18 @@ lang: ko-kr
## HTML 요소
HTML은 마크다운의 수퍼셋입니다. 모든 HTML 파일은 유효한 마크다운이라는 것입니다.
+
```md
<!--따라서 주석과 같은 HTML 요소들을 마크다운에 사용할 수 있으며, 마크다운 파서에 영향을
받지 않을 것입니다. 하지만 마크다운 파일에서 HTML 요소를 만든다면 그 요소의 안에서는
마크다운 문법을 사용할 수 없습니다.-->
```
+
## 제목
텍스트 앞에 붙이는 우물 정 기호(#)의 갯수에 따라 `<h1>`부터 `<h6>`까지의 HTML 요소를
손쉽게 작성할 수 있습니다.
+
```md
# <h1>입니다.
## <h2>입니다.
@@ -42,7 +45,9 @@ HTML은 마크다운의 수퍼셋입니다. 모든 HTML 파일은 유효한 마
##### <h5>입니다.
###### <h6>입니다.
```
+
또한 h1과 h2를 나타내는 다른 방법이 있습니다.
+
```md
h1입니다.
=============
@@ -50,9 +55,11 @@ h1입니다.
h2입니다.
-------------
```
+
## 간단한 텍스트 꾸미기
마크다운으로 쉽게 텍스트를 기울이거나 굵게 할 수 있습니다.
+
```md
*기울인 텍스트입니다.*
_이 텍스트도 같습니다._
@@ -64,10 +71,13 @@ __이 텍스트도 같습니다.__
**_이 텍스트도 같습니다._**
*__이것도 같습니다.__*
```
+
깃헙 전용 마크다운에는 취소선도 있습니다.
+
```md
~~이 텍스트에는 취소선이 그려집니다.~~
```
+
## 문단
문단은 하나 이상의 빈 줄로 구분되는, 한 줄 이상의 인접한 텍스트입니다.
@@ -103,6 +113,7 @@ HTML `<br />` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어
## 목록
순서가 없는 목록은 별표, 더하기, 하이픈을 이용해 만들 수 있습니다.
+
```md
* 이거
* 저거
@@ -140,6 +151,7 @@ HTML `<br />` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어
1. 둘
1. 셋
```
+
(위의 예시와 똑같이 나타납니다.)
목록 안에 목록이 올 수도 있습니다.
@@ -176,7 +188,7 @@ x가 없는 박스들은 체크되지 않은 HTML 체크박스입니다.
```md
my_array.each do |item|
- puts item
+ puts item
end
```
@@ -188,12 +200,13 @@ x가 없는 박스들은 체크되지 않은 HTML 체크박스입니다.
깃헙 전용 마크다운에서는 코드를 나타내기 위해 특별한 문법을 쓸 수 있습니다.
-<pre>
-<code class="highlight">&#x60;&#x60;&#x60;ruby
+````md
+```ruby
def foobar
- puts "Hello world!"
+ puts "Hello world!"
end
-&#x60;&#x60;&#x60;</code></pre>
+```
+````
위의 경우에 들여쓰기가 필요없을 뿐 아니라 \`\`\` 뒤에 특정해 준 언어의 문법에 따라
색을 입혀줄 것입니다.
@@ -202,12 +215,14 @@ end
수평선(`<hr/>`)은 셋 이상의 별표나 하이픈을 이용해 쉽게 나타낼 수 있습니다.
띄어쓰기가 포함될 수 있습니다.
+
```md
***
---
- - -
****************
```
+
## 링크
마크다운의 장점 중 하나는 링크를 만들기 쉽다는 것입니다. 대괄호 안에 나타낼 텍스트를 쓰고
@@ -231,20 +246,24 @@ end
참조하는 식으로 링크를 걸 수도 있습니다.
-<pre><code class="highlight">&#x5b;<span class="nv">이 </span>][<span class="ss">링크</span>]에서 더 알아보세요!
-&#x5b;<span class="nv">원하신다면 </span>][<span class="ss">foobar</span>]도 참고하세요.
+```md
+[이 ][링크]에서 더 알아보세요!
+[원하신다면 ][foobar]도 참고하세요.
-&#x5b;<span class="nv">링크</span>]: <span class="sx">http://test.com/</span> <span class="nn">"좋아!"</span>
-&#x5b;<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"됐다!"</span></code></pre>
+[링크]: http://test.com/ "좋아!"
+[foobar]: http://foobar.biz/ "됐다!"
+```
제목은 작은 따옴표나 괄호에 들어갈 수도 있고, 완전히 생략할 수도 있습니다. 참조는 문서의
어느 곳에든 올 수 있고 참조 ID는 유일하다면 무엇이든 될 수 있습니다.
링크 텍스트를 ID로 사용하는 "묵시적 이름"도 있습니다.
-<pre><code class="highlight">&#x5b;<span class="nv">이것</span>][]은 링크입니다.
+```md
+[이것][]은 링크입니다.
-&#x5b;<span class="nv">이것</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
+[이것]: http://thisisalink.com/
+```
하지만 보통 그렇게 추천하지는 않습니다.
@@ -257,9 +276,11 @@ end
참조 방식도 가능합니다.
-<pre><code class="highlight">!&#x5b;<span class="nv">alt 속성</span>][<span class="ss">이미지</span>]
+```md
+![alt 속성][이미지]
-&#x5b;<span class="nv">이미지</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"제목이 필요하다면 여기에"</span></code></pre>
+[이미지]: relative/urls/cool/image.jpg "제목이 필요하다면 여기에"
+```
## 기타
### 자동 링크
@@ -270,9 +291,11 @@ end
```
### 이메일 자동 링크
+
```md
<foo@bar.com>
```
+
### 탈출 문자
```md
@@ -292,17 +315,21 @@ end
### 표
표는 깃헙 전용 마크다운에서만 쓸 수 있고 다소 복잡하지만, 정말 쓰고 싶으시다면
+
```md
| 1열 | 2열 | 3열 |
| :--------| :-------: | --------: |
| 왼쪽 정렬 | 가운데 정렬 | 오른쪽 정렬 |
| 머시기 | 머시기 | 머시기 |
```
+
혹은
+
```md
1열 | 2열 | 3열
:-- | :-: | --:
으악 너무 못생겼어 | 그만 | 둬
```
+
---
추가 정보를 위해, 존 그루버의 공식 문법 [(영어) 문서](http://daringfireball.net/projects/markdown/syntax)와 애덤 프릿차드의 훌륭한 [(영어) 치트싯](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)을 확인하세요.
diff --git a/lsf/lambda-calculus-lsf.html.markdown b/lsf/lambda-calculus-lsf.html.markdown
deleted file mode 100644
index 88bb638f..00000000
--- a/lsf/lambda-calculus-lsf.html.markdown
+++ /dev/null
@@ -1,91 +0,0 @@
----
-category: Algorithms & Data Structures
-name: Lambda Calculus
-contributors:
- - ["Max Sun", "http://github.com/maxsun"]
-translators:
- - ["Victore Leve", "https://github.com/AcProIL"]
-lang: lsf
----
-
-# Calculo λ
-
-Calculo lambda, creato principto per Alonzo Church, es lingua de programmatura
-computatro maximo parvo. Quamquam non habe numero, serie de charactere vel ullo
-typo de data non functionale, id pote repraesenta omne machina de Turing.
-
-Tres elemento compone calculo lambda: **quantitate variabile** (q.v.),
-**functione** et **applicatione**.
-
-| Elemento | Syntaxe | Exemplo |
-|----------------------|-----------------------------------|-----------|
-| Quantitate variabile | `<nomine>` | `x` |
-| Functione | `λ<parametro>.<corpore>` | `λx.x` |
-| Applicatione | `<functione><q.v. aut functione>` | `(λx.x)a` |
-
-Functione fundamentale es identitate: `λx.x` cum argumento primo `x` et cum
-corpore secundo `x`. In mathematica, nos scribe `id: x↦x`.
-
-## Quantitate variabile libero et ligato
-
-* In functione praecedente, `x` es q.v. ligato nam id es et in copore et
- argumento.
-* In `λx.y`, `y` es q.v. libero nam non es declarato ante.
-
-## Valutatione
-
-Valutatione es facto per reductione beta (reductione β) que es essentialiter
-substitutione lexicale.
-
-Dum valutatione de formula `(λx.x)a`, nos substitue omne evento de `x` in
-corpore de functione pro `a`.
-
-* `(λx.x)a` vale `a`
-* `(λx.y)a` vale `y`
-
-Pote etiam crea functione de ordine supero: `(λx.(λy.x))a` vale `λy.a`.
-
-Etsi calculo lambda solo tracta functione de uno parametro, nos pote crea
-functione cum plure argumento utente methodo de Curry: `λx.(λy.(λz.xyz))`
-es scriptura informatica de formula mathematico `f: x, y, z ↦ x(y(z)))`.
-
-Ergo, interdum, nos ute `λxy.<corpore>` pro `λx.λy.<corpore>`.
-
-## Arithmetica
-
-### Logica de Boole
-
-Es nec numero nec booleano in calculo lambda.
-
-* «vero» es `v = λx.λy.x`
-* «falso» es `f = λx.λy.y`
-
-Primo, nos pote defini functione «si t tunc a alio b» per `si = λtab.tab`.
-Si `t` es vero, valutatione da `(λxy.x) a b` id es `a`. Similiter si `t` es
-falso, nos obtine `b`.
-
-Secundo, nos pote defini operatore de logica:
-
-* «a et b» es `et = λa.λb.si a b f`
-* «a vel b» es `vel = λa.λb.si a t b`
-* «non a» es `non = λa.si a f t`
-
-### Numeros
-
-Nos pone:
-
-* `0 = λf.λx.x` (`0: f↦id`)
-* `1 = λf.λx.f x` (`1: f↦f`)
-* `2 = λf.λx.f(f x)` (`2: f↦f⚬f`)
-
-Cum mente generale, successore de numero `n` es `S n = λf.λx.f((n f) x)`
-(`n+1: f↦f⚬fⁿ`). Id es **`n` est functione que da `fⁿ` ex functione `f`**.
-
-Postremo additione es `λab.(a S)b`
-
-## Ut progrede
-
-### In lingua anglo
-
-1. [A Tutorial Introduction to the Lambda Calculus](http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf) per Raúl Roja
-2. [The Lambda Calculus](http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html), CS 312 Recitation 26
diff --git a/lsf/latex-lsf.html.markdown b/lsf/latex-lsf.html.markdown
deleted file mode 100644
index 18c2e62b..00000000
--- a/lsf/latex-lsf.html.markdown
+++ /dev/null
@@ -1,146 +0,0 @@
----
-language: latex
-lang: lsf
-contributors:
- - ["Chaitanya Krishna Ande", "http://icymist.github.io"]
- - ["Colton Kohnke", "http://github.com/voltnor"]
- - ["Sricharan Chiruvolu", "http://sricharan.xyz"]
-translators:
- - ["Victore Leve", "https://github.com/AcProIL"]
-filename: learn-latex-lsf.tex
----
-
-```tex
-% Solo existe commentario monolinea, illo incipe cum charactere %
-
-% LaTeX non es sicut MS Word aut OpenOffice: que scribe non es que obtine.
-% Primo, scribe imperio (que semper incipe cum \) et secundo programma crea
-% lima.
-
-% Nos defini typo de document (id es articulo aut libro aut libello etc.).
-% Optione muta quomodo programma age, per exemplo altore de littera.
-\documentclass[12pt]{article}
-
-% Deinde nos lista paccettos que nos vol ute. Es classe de imperio que alio
-% utatore e scribe. Pote muta funda, geometria de pagina, etc. vel adde
-% functionnalitate.
-\usepackage{euler}
-\usepackage{graphicx}
-
-% Ultimo statione ante scribe documento es metadata id es titulo, auctore et
-% tempore. Charactere ~ es spatio que non pote es secato.
-\title{Disce LaTeX in~Y Minutos!}
-\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu}
-\date{\today}
-
-% Principio de documento
-\begin{document}
- \maketitle % Nos vol adfige metadata.
-
- % Saepe nos adde breviario us describe texto.
- \begin{abstract}
- Hic es exmplo de documento sibre cum lingua de LaTeX.
- \end{abstract}
-
- % \section crea sectione cum titulo dato sicut sperato
- \section{Introductione}
-
- Traductione de hic cursu es importante.
-
- \subsection{Methodo}
- Iste parte non es utile.
-
- \subsubsection{Methodo peculiare}
- % \label da nomine ad parte ut post ute imperio de referentia \ref.
- \label{subsec:metpec}
-
- % Cum asteritco nos indice que nos non vol numero ante titulo de sectione.
- \section*{Me non aestima numero…}
-
- …sed de Peano aut de Church.
-
- \section{Listas}
-
- Que me debe scribe:
-
- \begin{enumerate} % `enumerate` designa lista cum numeros contra `itemize`.
- \item articulo,
- \item libro,
- \item cursu.
- \end{enumerate}
-
- \section{Mathematica}
-
- Methematicas ute multo programma LaTeX ut communica suo decooperito.
- Illo necessita symbolo multo instar de logica vel sagitta vel littera cum
- accento.
-
- % Fornula es in linea si nos scribe inter \( et \) (aut duo $) sed magno si
- % nos ute \[ et \].
- \(\forall n\in N_0\) % pro omne n in classe N₀
- \[^{3}/_{4} = \frac{3}{4} < 1\] % ¾ < 1
-
- Alphabeta graeco contine littera $\alpha$.
-
- % Ut scribe equatione cum numero et nomine, existe circumiecto `equation`.
- \begin{equation}
- c^2 = a^2 + b^2
- \label{eq:pythagoras}
- \end{equation}
-
- \begin{equation}
- % Summa ab 1 ad n de numeros dimidio de n(n+1)
- \sum_{i=1}^n i = \frac{n(n+1)}{2}
- \end{equation}
-
- \section{Figura}
-
- % Nos adde imagine `right-triangle.png` cum latitudo de quinque centimetro,
- % horizontaliter in centro et cum capite «Triangulo recto».
- \begin{figure}
- \centering
- \includegraphics[width=5cm]{right-triangle.png}
- \caption{Triangulo recto}
- \label{fig:right-triangle}
- \end{figure}
-
- \subsection{Tabula}
-
- \begin{table}
- \caption{Título para la tabla.}
- % Argumento de `tabular` es lineamente de columna.
- % c: centro, l: sinistra, r: destra, | linea verticale
- \begin{tabular}{c|cc}
- Numero & B & C \\
- \hline % linea horizontale
- 1 & et & aut \\
- 2 & atque & vel
- \end{tabular}
- \end{table}
-
- \section{Stylo}
-
- Texto pote es \textbf{crasso} et \textit{italico}!
-
- \section{Texto puro}
-
- % Circumiecto `verbatim` ignora imperio, nos saepe ute id pro monstra
- % programma.
- \begin{verbatim}
-from math import tau, e
-print(e ** tau)
- \end{verbatim}
-
- \section{Et plus!}
- LaTeX habe facultate crea bibliographia, paritura, scaccarip… cum paccetto
- dedicato.
-\end{document}
-```
-
-Imperio ut conge documento es `pdflatex documento` in terminale.
-
-## Ut progrede
-
-### In lingua anglo
-
-* [LaTeX tutorial](http://www.latex-tutorial.com/) per Claudio Vellage
diff --git a/make.html.markdown b/make.html.markdown
index eecc96bf..f5352f9e 100644
--- a/make.html.markdown
+++ b/make.html.markdown
@@ -1,246 +1,246 @@
----
-category: tool
-tool: make
-contributors:
- - ["Robert Steed", "https://github.com/robochat"]
- - ["Stephan Fuhrmann", "https://github.com/sfuhrm"]
-filename: Makefile
----
-
-A Makefile defines a graph of rules for creating a target (or targets).
-Its purpose is to do the minimum amount of work needed to update a
-target to the most recent version of the source. Famously written over a
-weekend by Stuart Feldman in 1976, it is still widely used (particularly
-on Unix and Linux) despite many competitors and criticisms.
-
-There are many varieties of make in existence, however this article
-assumes that we are using GNU make which is the standard on Linux.
-
-```make
-
-# Comments can be written like this.
-
-# File should be named Makefile and then can be run as `make <target>`.
-# Otherwise we use `make -f "filename" <target>`.
-
-# Warning - only use TABS to indent in Makefiles, never spaces!
-
-#-----------------------------------------------------------------------
-# Basics
-#-----------------------------------------------------------------------
-
-# Rules are of the format
-# target: <prerequisite>
-# where prerequisites are optional.
-
-# A rule - this rule will only run if file0.txt doesn't exist.
-file0.txt:
- echo "foo" > file0.txt
- # Even comments in these 'recipe' sections get passed to the shell.
- # Try `make file0.txt` or simply `make` - first rule is the default.
-
-# This rule will only run if file0.txt is newer than file1.txt.
-file1.txt: file0.txt
- cat file0.txt > file1.txt
- # use the same quoting rules as in the shell.
- @cat file0.txt >> file1.txt
- # @ stops the command from being echoed to stdout.
- -@echo 'hello'
- # - means that make will keep going in the case of an error.
- # Try `make file1.txt` on the commandline.
-
-# A rule can have multiple targets and multiple prerequisites
-file2.txt file3.txt: file0.txt file1.txt
- touch file2.txt
- touch file3.txt
-
-# Make will complain about multiple recipes for the same rule. Empty
-# recipes don't count though and can be used to add new dependencies.
-
-#-----------------------------------------------------------------------
-# Phony Targets
-#-----------------------------------------------------------------------
-
-# A phony target. Any target that isn't a file.
-# It will never be up to date so make will always try to run it.
-all: maker process
-
-# We can declare things out of order.
-maker:
- touch ex0.txt ex1.txt
-
-# Can avoid phony rules breaking when a real file has the same name by
-.PHONY: all maker process
-# This is a special target. There are several others.
-
-# A rule with a dependency on a phony target will always run
-ex0.txt ex1.txt: maker
-
-# Common phony targets are: all make clean install ...
-
-#-----------------------------------------------------------------------
-# Automatic Variables & Wildcards
-#-----------------------------------------------------------------------
-
-process: file*.txt #using a wildcard to match filenames
- @echo $^ # $^ is a variable containing the list of prerequisites
- @echo $@ # prints the target name
- #(for multiple target rules, $@ is whichever caused the rule to run)
- @echo $< # the first prerequisite listed
- @echo $? # only the dependencies that are out of date
- @echo $+ # all dependencies including duplicates (unlike normal)
- #@echo $| # all of the 'order only' prerequisites
-
-# Even if we split up the rule dependency definitions, $^ will find them
-process: ex1.txt file0.txt
-# ex1.txt will be found but file0.txt will be deduplicated.
-
-#-----------------------------------------------------------------------
-# Patterns
-#-----------------------------------------------------------------------
-
-# Can teach make how to convert certain files into other files.
-
-%.png: %.svg
- inkscape --export-png $^
-
-# Pattern rules will only do anything if make decides to create the
-# target.
-
-# Directory paths are normally ignored when matching pattern rules. But
-# make will try to use the most appropriate rule available.
-small/%.png: %.svg
- inkscape --export-png --export-dpi 30 $^
-
-# make will use the last version for a pattern rule that it finds.
-%.png: %.svg
- @echo this rule is chosen
-
-# However make will use the first pattern rule that can make the target
-%.png: %.ps
- @echo this rule is not chosen if *.svg and *.ps are both present
-
-# make already has some pattern rules built-in. For instance, it knows
-# how to turn *.c files into *.o files.
-
-# Older makefiles might use suffix rules instead of pattern rules
-.png.ps:
- @echo this rule is similar to a pattern rule.
-
-# Tell make about the suffix rule
-.SUFFIXES: .png
-
-#-----------------------------------------------------------------------
-# Variables
-#-----------------------------------------------------------------------
-# aka. macros
-
-# Variables are basically all string types
-
-name = Ted
-name2="Sarah"
-
-echo:
- @echo $(name)
- @echo ${name2}
- @echo $name # This won't work, treated as $(n)ame.
- @echo $(name3) # Unknown variables are treated as empty strings.
-
-# There are 4 places to set variables.
-# In order of priority from highest to lowest:
-# 1: commandline arguments
-# 2: Makefile
-# 3: shell environment variables - make imports these automatically.
-# 4: make has some predefined variables
-
-name4 ?= Jean
-# Only set the variable if environment variable is not already defined.
-
-override name5 = David
-# Stops commandline arguments from changing this variable.
-
-name4 +=grey
-# Append values to variable (includes a space).
-
-# Pattern-specific variable values (GNU extension).
-echo: name2 = Sara # True within the matching rule
- # and also within its remade recursive dependencies
- # (except it can break when your graph gets too complicated!)
-
-# Some variables defined automatically by make.
-echo_inbuilt:
- echo $(CC)
- echo ${CXX}
- echo $(FC)
- echo ${CFLAGS}
- echo $(CPPFLAGS)
- echo ${CXXFLAGS}
- echo $(LDFLAGS)
- echo ${LDLIBS}
-
-#-----------------------------------------------------------------------
-# Variables 2
-#-----------------------------------------------------------------------
-
-# The first type of variables are evaluated each time they are used.
-# This can be expensive, so a second type of variable exists which is
-# only evaluated once. (This is a GNU make extension)
-
-var := hello
-var2 ::= $(var) hello
-#:= and ::= are equivalent.
-
-# These variables are evaluated procedurally (in the order that they
-# appear), thus breaking with the rest of the language !
-
-# This doesn't work
-var3 ::= $(var4) and good luck
-var4 ::= good night
-
-#-----------------------------------------------------------------------
-# Functions
-#-----------------------------------------------------------------------
-
-# make has lots of functions available.
-
-sourcefiles = $(wildcard *.c */*.c)
-objectfiles = $(patsubst %.c,%.o,$(sourcefiles))
-
-# Format is $(func arg0,arg1,arg2...)
-
-# Some examples
-ls: * src/*
- @echo $(filter %.txt, $^)
- @echo $(notdir $^)
- @echo $(join $(dir $^),$(notdir $^))
-
-#-----------------------------------------------------------------------
-# Directives
-#-----------------------------------------------------------------------
-
-# Include other makefiles, useful for platform specific code
-include foo.mk
-
-sport = tennis
-# Conditional compilation
-report:
-ifeq ($(sport),tennis)
- @echo 'game, set, match'
-else
- @echo "They think it's all over; it is now"
-endif
-
-# There are also ifneq, ifdef, ifndef
-
-foo = true
-
-ifdef $(foo)
-bar = 'hello'
-endif
-```
-
-### More Resources
-
-+ [gnu make documentation](https://www.gnu.org/software/make/manual/)
-+ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/)
-+ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)
+---
+category: tool
+tool: make
+contributors:
+ - ["Robert Steed", "https://github.com/robochat"]
+ - ["Stephan Fuhrmann", "https://github.com/sfuhrm"]
+filename: Makefile
+---
+
+A Makefile defines a graph of rules for creating a target (or targets).
+Its purpose is to do the minimum amount of work needed to update a
+target to the most recent version of the source. Famously written over a
+weekend by Stuart Feldman in 1976, it is still widely used (particularly
+on Unix and Linux) despite many competitors and criticisms.
+
+There are many varieties of make in existence, however this article
+assumes that we are using GNU make which is the standard on Linux.
+
+```make
+
+# Comments can be written like this.
+
+# File should be named Makefile and then can be run as `make <target>`.
+# Otherwise we use `make -f "filename" <target>`.
+
+# Warning - only use TABS to indent in Makefiles, never spaces!
+
+#-----------------------------------------------------------------------
+# Basics
+#-----------------------------------------------------------------------
+
+# Rules are of the format
+# target: <prerequisite>
+# where prerequisites are optional.
+
+# A rule - this rule will only run if file0.txt doesn't exist.
+file0.txt:
+ echo "foo" > file0.txt
+ # Even comments in these 'recipe' sections get passed to the shell.
+ # Try `make file0.txt` or simply `make` - first rule is the default.
+
+# This rule will only run if file0.txt is newer than file1.txt.
+file1.txt: file0.txt
+ cat file0.txt > file1.txt
+ # use the same quoting rules as in the shell.
+ @cat file0.txt >> file1.txt
+ # @ stops the command from being echoed to stdout.
+ -@echo 'hello'
+ # - means that make will keep going in the case of an error.
+ # Try `make file1.txt` on the commandline.
+
+# A rule can have multiple targets and multiple prerequisites
+file2.txt file3.txt: file0.txt file1.txt
+ touch file2.txt
+ touch file3.txt
+
+# Make will complain about multiple recipes for the same rule. Empty
+# recipes don't count though and can be used to add new dependencies.
+
+#-----------------------------------------------------------------------
+# Phony Targets
+#-----------------------------------------------------------------------
+
+# A phony target. Any target that isn't a file.
+# It will never be up to date so make will always try to run it.
+all: maker process
+
+# We can declare things out of order.
+maker:
+ touch ex0.txt ex1.txt
+
+# Can avoid phony rules breaking when a real file has the same name by
+.PHONY: all maker process
+# This is a special target. There are several others.
+
+# A rule with a dependency on a phony target will always run
+ex0.txt ex1.txt: maker
+
+# Common phony targets are: all make clean install ...
+
+#-----------------------------------------------------------------------
+# Automatic Variables & Wildcards
+#-----------------------------------------------------------------------
+
+process: file*.txt #using a wildcard to match filenames
+ @echo $^ # $^ is a variable containing the list of prerequisites
+ @echo $@ # prints the target name
+ #(for multiple target rules, $@ is whichever caused the rule to run)
+ @echo $< # the first prerequisite listed
+ @echo $? # only the dependencies that are out of date
+ @echo $+ # all dependencies including duplicates (unlike normal)
+ #@echo $| # all of the 'order only' prerequisites
+
+# Even if we split up the rule dependency definitions, $^ will find them
+process: ex1.txt file0.txt
+# ex1.txt will be found but file0.txt will be deduplicated.
+
+#-----------------------------------------------------------------------
+# Patterns
+#-----------------------------------------------------------------------
+
+# Can teach make how to convert certain files into other files.
+
+%.png: %.svg
+ inkscape --export-png $^
+
+# Pattern rules will only do anything if make decides to create the
+# target.
+
+# Directory paths are normally ignored when matching pattern rules. But
+# make will try to use the most appropriate rule available.
+small/%.png: %.svg
+ inkscape --export-png --export-dpi 30 $^
+
+# make will use the last version for a pattern rule that it finds.
+%.png: %.svg
+ @echo this rule is chosen
+
+# However make will use the first pattern rule that can make the target
+%.png: %.ps
+ @echo this rule is not chosen if *.svg and *.ps are both present
+
+# make already has some pattern rules built-in. For instance, it knows
+# how to turn *.c files into *.o files.
+
+# Older makefiles might use suffix rules instead of pattern rules
+.png.ps:
+ @echo this rule is similar to a pattern rule.
+
+# Tell make about the suffix rule
+.SUFFIXES: .png
+
+#-----------------------------------------------------------------------
+# Variables
+#-----------------------------------------------------------------------
+# aka. macros
+
+# Variables are basically all string types
+
+name = Ted
+name2="Sarah"
+
+echo:
+ @echo $(name)
+ @echo ${name2}
+ @echo $name # This won't work, treated as $(n)ame.
+ @echo $(name3) # Unknown variables are treated as empty strings.
+
+# There are 4 places to set variables.
+# In order of priority from highest to lowest:
+# 1: commandline arguments
+# 2: Makefile
+# 3: shell environment variables - make imports these automatically.
+# 4: make has some predefined variables
+
+name4 ?= Jean
+# Only set the variable if environment variable is not already defined.
+
+override name5 = David
+# Stops commandline arguments from changing this variable.
+
+name4 +=grey
+# Append values to variable (includes a space).
+
+# Pattern-specific variable values (GNU extension).
+echo: name2 = Sara # True within the matching rule
+ # and also within its remade recursive dependencies
+ # (except it can break when your graph gets too complicated!)
+
+# Some variables defined automatically by make.
+echo_inbuilt:
+ echo $(CC)
+ echo ${CXX}
+ echo $(FC)
+ echo ${CFLAGS}
+ echo $(CPPFLAGS)
+ echo ${CXXFLAGS}
+ echo $(LDFLAGS)
+ echo ${LDLIBS}
+
+#-----------------------------------------------------------------------
+# Variables 2
+#-----------------------------------------------------------------------
+
+# The first type of variables are evaluated each time they are used.
+# This can be expensive, so a second type of variable exists which is
+# only evaluated once. (This is a GNU make extension)
+
+var := hello
+var2 ::= $(var) hello
+#:= and ::= are equivalent.
+
+# These variables are evaluated procedurally (in the order that they
+# appear), thus breaking with the rest of the language !
+
+# This doesn't work
+var3 ::= $(var4) and good luck
+var4 ::= good night
+
+#-----------------------------------------------------------------------
+# Functions
+#-----------------------------------------------------------------------
+
+# make has lots of functions available.
+
+sourcefiles = $(wildcard *.c */*.c)
+objectfiles = $(patsubst %.c,%.o,$(sourcefiles))
+
+# Format is $(func arg0,arg1,arg2...)
+
+# Some examples
+ls: * src/*
+ @echo $(filter %.txt, $^)
+ @echo $(notdir $^)
+ @echo $(join $(dir $^),$(notdir $^))
+
+#-----------------------------------------------------------------------
+# Directives
+#-----------------------------------------------------------------------
+
+# Include other makefiles, useful for platform specific code
+include foo.mk
+
+sport = tennis
+# Conditional compilation
+report:
+ifeq ($(sport),tennis)
+ @echo 'game, set, match'
+else
+ @echo "They think it's all over; it is now"
+endif
+
+# There are also ifneq, ifdef, ifndef
+
+foo = true
+
+ifdef $(foo)
+bar = 'hello'
+endif
+```
+
+### More Resources
+
++ [gnu make documentation](https://www.gnu.org/software/make/manual/)
++ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/)
++ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)
diff --git a/markdown.html.markdown b/markdown.html.markdown
index fefb60f6..ee213083 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -207,7 +207,7 @@ inside your code.
```md
my_array.each do |item|
- puts item
+ puts item
end
```
@@ -219,12 +219,13 @@ John didn't even know what the `go_to()` function did!
In GitHub Flavored Markdown, you can use a special syntax for code.
-<pre>
-<code class="highlight">&#x60;&#x60;&#x60;ruby
+````md
+```ruby
def foobar
- puts "Hello world!"
+ puts "Hello world!"
end
-&#x60;&#x60;&#x60;</code></pre>
+```
+````
The above text doesn't require indenting, plus GitHub will use syntax
highlighting of the language you specify after the opening <code>```</code>.
@@ -264,11 +265,13 @@ Relative paths work too.
Markdown also supports reference style links.
-<pre><code class="highlight">&#x5b;<span class="nv">Click this link</span>][<span class="ss">link1</span>] for more info about it!
-&#x5b;<span class="nv">Also check out this link</span>][<span class="ss">foobar</span>] if you want to.
+```md
+[Click this link][link1] for more info about it!
+[Also check out this link][foobar] if you want to.
-&#x5b;<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Cool!"</span>
-&#x5b;<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Alright!"</span></code></pre>
+[link1]: http://test.com/ "Cool!"
+[foobar]: http://foobar.biz/ "Alright!"
+```
The title can also be in single quotes or in parentheses, or omitted
entirely. The references can be anywhere in your document and the reference IDs
@@ -276,9 +279,11 @@ can be anything so long as they are unique.
There is also "implicit naming" which lets you use the link text as the id.
-<pre><code class="highlight">&#x5b;<span class="nv">This</span>][] is a link.
+```md
+[This][] is a link.
-&#x5b;<span class="nv">This</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
+[This]: http://thisisalink.com/
+```
But it's not that commonly used.
@@ -311,9 +316,11 @@ Images are done the same way as links but with an exclamation point in front!
And reference style works as expected.
-<pre><code class="highlight">!&#x5b;<span class="nv">This is the alt-attribute.</span>][<span class="ss">myimage</span>]
+```md
+![This is the alt-attribute.][myimage]
-&#x5b;<span class="nv">myimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"if you need a title, it's here"</span></code></pre>
+[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here"
+```
## Miscellany
diff --git a/mercury.html.markdown b/mercury.html.markdown
index f749bac4..6d278ce0 100644
--- a/mercury.html.markdown
+++ b/mercury.html.markdown
@@ -254,7 +254,7 @@ received(crypto(Type, _Wallet, Amount)) = S :- % _Wallet is named throwaway
* [Mercury Tutorial](https://mercurylang.org/documentation/papers/book.pdf) (pdf link) - a more traditional tutorial with a more relaxed pace
* [Mercury Crash Course](https://mercury-in.space/crash.html) - a dense example-driven tutorial with Q&A format
-* [Github Wiki Tutorial](https://github.com/Mercury-Language/mercury/wiki/Tutorial)
+* [GitHub Wiki Tutorial](https://github.com/Mercury-Language/mercury/wiki/Tutorial)
* [Getting Started with Mercury](https://bluishcoder.co.nz/2019/06/23/getting-started-with-mercury.html) - installation and your first steps
### Documentation
diff --git a/montilang.html.markdown b/montilang.html.markdown
index 483dc5a5..14b45d31 100644
--- a/montilang.html.markdown
+++ b/montilang.html.markdown
@@ -230,4 +230,4 @@ DEL 1 PRINT . /# [1, 3] #/
## Extra information
- [MontiLang.ml](http://montilang.ml/)
-- [Github Page](https://github.com/lduck11007/MontiLang)
+- [GitHub Page](https://github.com/lduck11007/MontiLang)
diff --git a/neat.html.markdown b/neat.html.markdown
deleted file mode 100644
index f02461ee..00000000
--- a/neat.html.markdown
+++ /dev/null
@@ -1,297 +0,0 @@
----
-language: neat
-contributors:
- - ["Feep", "https://github.com/FeepingCreature"]
-filename: LearnNeat.nt
----
-
-Neat is basically a smaller version of D1 with some experimental syntax and a focus on terseness without losing the basic C-like syntax.
-
-[Read more here.](https://github.com/FeepingCreature/fcc/wiki)
-
-```c
-// single line comments start with //
-/*
- multiline comments look like this
-*/
-/+
- or this
- /+ these can be nested too, same as D +/
-+/
-
-// Module name. This has to match the filename/directory.
-module LearnNeat;
-
-// Make names from another module visible in this one.
-import std.file;
-// You can import multiple things at once.
-import std.math, std.util;
-// You can even group up imports!
-import std.(process, socket);
-
-// Global functions!
-void foo() { }
-
-// Main function, same as in C.
-// string[] == "array of strings".
-// "string" is just an alias for char[],
-void main(string[] args) {
- // Call functions with "function expression".
- writeln "Hello World";
- // You can do it like in C too... if you really want.
- writeln ("Hello World");
- // Declare a variable with "type identifier"
- string arg = ("Hello World");
- writeln arg;
- // (expression, expression) forms a tuple.
- // There are no one-value tuples though.
- // So you can always use () in the mathematical sense.
- // (string) arg; <- is an error
-
- /*
- byte: 8 bit signed integer
- char: 8 bit UTF-8 byte component.
- short: 16 bit signed integer
- int: 32 bit signed integer
- long: 64 bit signed integer
-
- float: 32 bit floating point
- double: 64 bit floating point
- real: biggest native size floating point (80 bit on x86).
-
- bool: true or false
- */
- int a = 5;
- bool b = true;
- // as in C, && and || are short-circuit evaluating.
- b = b && false;
- assert(b == false);
- // "" are "format strings". So $variable will be substituted at runtime
- // with a formatted version of the variable.
- writeln "$a";
- // This will just print $a.
- writeln `$a`;
- // you can format expressions with $()
- writeln "$(2+2)";
- // Note: there is no special syntax for characters.
- char c = "a";
- // Cast values by using type: expression.
- // There are three kinds of casts:
- // casts that just specify conversions that would be happening automatically
- // (implicit casts)
- float f = float:5;
- float f2 = 5; // would also work
- // casts that require throwing away information or complicated computation -
- // those must always be done explicitly
- // (conversion casts)
- int i = int:f;
- // int i = f; // would not work!
- // and, as a last attempt, casts that just reinterpret the raw data.
- // Those only work if the types have the same size.
- string s = "Hello World";
- // Arrays are (length, pointer) pairs.
- // This is a tuple type. Tuple types are (type, type, type).
- // The type of a tuple expression is a tuple type. (duh)
- (int, char*) array = (int, char*): s;
- // You can index arrays and tuples using the expression[index] syntax.
- writeln "pointer is $(array[1]) and length is $(array[0])";
- // You can slice them using the expression[from .. to] syntax.
- // Slicing an array makes another array.
- writeln "$(s[0..5]) World";
- // Alias name = expression gives the expression a name.
- // As opposed to a variable, aliases do not have an address
- // and can not be assigned to. (Unless the expression is assignable)
- alias range = 0 .. 5;
- writeln "$(s[range]) World";
- // You can iterate over ranges.
- for int i <- range {
- write "$(s[i])";
- }
- writeln " World";
- // Note that if "range" had been a variable, it would be 'empty' now!
- // Range variables can only be iterated once.
- // The syntax for iteration is "expression <- iterable".
- // Lots of things are iterable.
- for char c <- "Hello" { write "$c"; }
- writeln " World";
- // For loops are "for test statement";
- alias test = char d <- "Hello";
- for test write "$d";
- writeln " World\t\x05"; // note: escapes work
- // Pointers: function the same as in C, btw. The usual.
- // Do note: the pointer star sticks with the TYPE, not the VARIABLE!
- string* p;
- assert(p == null); // default initializer
- p = &s;
- writeln "$(*p)";
- // Math operators are (almost) standard.
- int x = 2 + 3 * 4 << 5;
- // Note: XOR is "xor". ^ is reserved for exponentiation (once I implement that).
- int y = 3 xor 5;
- int z = 5;
- assert(z++ == 5);
- assert(++z == 7);
- writeln "x $x y $y z $z";
- // As in D, ~ concatenates.
- string hewo = "Hello " ~ "World";
- // == tests for equality, "is" tests for identity.
- assert (hewo == s);
- assert !(hewo is s);
- // same as
- assert (hewo !is s);
-
- // Allocate arrays using "new array length"
- int[] integers = new int[] 10;
- assert(integers.length == 10);
- assert(integers[0] == 0); // zero is default initializer
- integers = integers ~ 5; // This allocates a new array!
- assert(integers.length == 11);
-
- // This is an appender array.
- // Instead of (length, pointer), it tracks (capacity, length, pointer).
- // When you append to it, it will use the free capacity if it can.
- // If it runs out of space, it reallocates - but it will free the old array automatically.
- // This makes it convenient for building arrays.
- int[auto~] appender;
- appender ~= 2;
- appender ~= 3;
- appender.free(); // same as {mem.free(appender.ptr); appender = null;}
-
- // Scope variables are automatically freed at the end of the current scope.
- scope int[auto~] someOtherAppender;
- // This is the same as:
- int[auto~] someOtherAppender2;
- onExit { someOtherAppender2.free; }
-
- // You can do a C for loop too
- // - but why would you want to?
- for (int i = 0; i < 5; ++i) { }
- // Otherwise, for and while are the same.
- while int i <- 0..4 {
- assert(i == 0);
- break; // continue works too
- } then assert(false); // if we hadn't break'd, this would run at the end
- // This is the height of loopdom - the produce-test-consume loop.
- do {
- int i = 5;
- } while (i == 5) {
- assert(i == 5);
- break; // otherwise we'd go back up to do {
- }
-
- // This is a nested function.
- // Nested functions can access the surrounding function.
- string returnS() { return s; }
- writeln returnS();
-
- // Take the address of a function using &
- // The type of a global function is ReturnType function(ParameterTypeTuple).
- void function() foop = &foo;
-
- // Similarly, the type of a nested function is ReturnType delegate(ParameterTypeTuple).
- string delegate() returnSp = &returnS;
- writeln returnSp();
- // Class member functions and struct member functions also fit into delegate variables.
- // In general, delegates are functions that carry an additional context pointer.
- // ("fat pointers" in C)
-
- // Allocate a "snapshot" with "new delegate".
- // Snapshots are not closures! I used to call them closures too,
- // but then my Haskell-using friends yelled at me so I had to stop.
- // The difference is that snapshots "capture" their surrounding context
- // when "new" is used.
- // This allows things like this
- int delegate(int) add(int a) {
- int add_a(int b) { return a + b; }
- // This does not work - the context of add_a becomes invalid
- // when add returns.
- // return &add_a;
- // Instead:
- return new &add_a;
- }
- int delegate(int) dg = add 2;
- assert (dg(3) == 5);
- // or
- assert (((add 2) 3) == 5);
- // or
- assert (add 2 3 == 5);
- // add can also be written as
- int delegate(int) add2(int a) {
- // this is an implicit, nameless nested function.
- return new λ(int b) { return a + b; }
- }
- // or even
- auto add3(int a) { return new λ(int b) -> a + b; }
- // hahahaaa
- auto add4 = λ(int a) -> new λ(int b) -> a + b;
- assert(add4 2 3 == 5);
- // If your keyboard doesn't have a λ (you poor sod)
- // you can use \ too.
- auto add5 = \(int a) -> new \(int b) -> a + b;
- // Note!
- auto nestfun = λ() { } // There is NO semicolon needed here!
- // "}" can always substitute for "};".
- // This provides syntactic consistency with built-in statements.
-
-
- // This is a class.
- // Note: almost all elements of Neat can be used on the module level
- // or just as well inside a function.
- class C {
- int a;
- void writeA() { writeln "$a"; }
- // It's a nested class - it exists in the context of main().
- // so if you leave main(), any instances of C become invalid.
- void writeS() { writeln "$s"; }
- }
- C cc = new C;
- // cc is a *reference* to C. Classes are always references.
- cc.a = 5; // Always used for property access.
- auto ccp = &cc;
- (*ccp).a = 6;
- // or just
- ccp.a = 7;
- cc.writeA();
- cc.writeS(); // to prove I'm not making things up
- // Interfaces work same as in D, basically. Or Java.
- interface E { void doE(); }
- // Inheritance works same as in D, basically. Or Java.
- class D : C, E {
- override void writeA() { writeln "hahahahaha no"; }
- override void doE() { writeln "eeeee"; }
- // all classes inherit from Object. (toString is defined in Object)
- override string toString() { return "I am a D"; }
- }
- C cd = new D;
- // all methods are always virtual.
- cd.writeA();
- E e = E:cd; // dynamic class cast!
- e.doE();
- writeln "$e"; // all interfaces convert to Object implicitly.
-
- // Templates!
- // Templates are parameterized namespaces, taking a type as a parameter.
- template Templ(T) {
- alias hi = 5, hii = 8;
- // Templates always have to include something with the same name as the template
- // - this will become the template's _value_.
- // Static ifs are evaluated statically, at compile-time.
- // Because of this, the test has to be a constant expression,
- // or something that can be optimized to a constant.
- static if (types-equal (T, int)) {
- alias Templ = hi;
- } else {
- alias Templ = hii;
- }
- }
- assert(Templ!int == 5);
- assert(Templ!float == 8);
-}
-```
-
-## Topics Not Covered
-
- * Extended iterator types and expressions
- * Standard library
- * Conditions (error handling)
- * Macros
diff --git a/nix.html.markdown b/nix.html.markdown
index c2a2c074..677aaf54 100644
--- a/nix.html.markdown
+++ b/nix.html.markdown
@@ -378,6 +378,9 @@ with builtins; [
* [Susan Potter - Nix Cookbook - Nix By Example]
(https://ops.functionalalgebra.com/nix-by-example/)
-
+
+* [Zero to Nix - Nix Tutorial]
+ (https://zero-to-nix.com/)
+
* [Rommel Martinez - A Gentle Introduction to the Nix Family]
(https://web.archive.org/web/20210121042658/https://ebzzry.io/en/nix/#nix)
diff --git a/nl-nl/markdown-nl.html.markdown b/nl-nl/markdown-nl.html.markdown
index b5b4681c..0af78d88 100644
--- a/nl-nl/markdown-nl.html.markdown
+++ b/nl-nl/markdown-nl.html.markdown
@@ -52,7 +52,7 @@ __En deze tekst ook!__
*__En zelfs deze!__*
<!-- In de github versie van markdown, die gebruikt wordt om markdown te renderen
-op Github, is er ook doorstrepen -->
+op GitHub, is er ook doorstrepen -->
~~Deze tekst wordt doorstreept.~~
@@ -142,7 +142,7 @@ Dit item zal aangevinkt zijn in de gerenderde html.
John wist zelfs niet dat de `go_to()` functie bestond!
-<!-- In Github Markdown kan je een speciale syntax gebruiken die aangeeft welke
+<!-- In GitHub Markdown kan je een speciale syntax gebruiken die aangeeft welke
taal gebruikt wordt in het code blok. -->
\`\`\`ruby <!-- Wis de backslashes om dit te doen, juist ```ruby ! -->
@@ -151,7 +151,7 @@ def foobar
end
\`\`\` <!-- Hier ook, geen backslashes, juist ``` -->
-<!-- Voor bovenstaande tekst moet geen tab gebruikt worden. Plus, Github zal syntax
+<!-- Voor bovenstaande tekst moet geen tab gebruikt worden. Plus, GitHub zal syntax
highlighting gebruiken voor deze specifieke taal. Hier, Ruby.
<!-- Horizontale lijn (<hr />) -->
@@ -215,13 +215,13 @@ worden.
Dit kan je oplossen met backslashes: \*dit\* staat tussen sterretjes
<!-- Toetsenbord toetsen -->
-<!-- In Github Markdown, kan je <kbd> gebruiken om toetsenbord toetsen weer te geven -->
+<!-- In GitHub Markdown, kan je <kbd> gebruiken om toetsenbord toetsen weer te geven -->
Loopt je computer vast? Probeer volgende toetsen combinatie:
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
<!-- Tabellen -->
-<!-- Tabellen zijn momenteel enkel beschikbaar in Github Markdown en zijn redelijk omslachtig.
+<!-- Tabellen zijn momenteel enkel beschikbaar in GitHub Markdown en zijn redelijk omslachtig.
Maar als je er echt wilt toevoegen: -->
| Col1 | Col2 | Col3 |
diff --git a/opengl.html.markdown b/opengl.html.markdown
index 993402f7..f6a9085f 100644
--- a/opengl.html.markdown
+++ b/opengl.html.markdown
@@ -1,765 +1,765 @@
----
-category: tool
-tool: OpenGL
-filename: learnopengl.cpp
-contributors:
- - ["Simon Deitermann", "s.f.deitermann@t-online.de"]
----
-
-**Open Graphics Library** (**OpenGL**) is a cross-language cross-platform application programming interface
-(API) for rendering 2D computer graphics and 3D vector graphics.<sup>[1]</sup> In this tutorial we will be
-focusing on modern OpenGL from 3.3 and above, ignoring "immediate-mode", Displaylists and
-VBO's without use of Shaders.
-I will be using C++ with SFML for window, image and context creation aswell as GLEW
-for modern OpenGL extensions, though there are many other librarys available.
-
-```cpp
-// Creating an SFML window and OpenGL basic setup.
-#include <GL/glew.h>
-#include <GL/gl.h>
-#include <SFML/Graphics.h>
-#include <iostream>
-
-int main() {
- // First we tell SFML how to setup our OpenGL context.
- sf::ContextSettings context{ 24, // depth buffer bits
- 8, // stencil buffer bits
- 4, // MSAA samples
- 3, // major opengl version
- 3 }; // minor opengl version
- // Now we create the window, enable VSync
- // and set the window active for OpenGL.
- sf::Window window{ sf::VideoMode{ 1024, 768 },
- "opengl window",
- sf::Style::Default,
- context };
- window.setVerticalSyncEnabled(true);
- window.setActive(true);
- // After that we initialise GLEW and check if an error occurred.
- GLenum error;
- glewExperimental = GL_TRUE;
- if ((err = glewInit()) != GLEW_OK)
- std::cout << glewGetErrorString(err) << std::endl;
- // Here we set the color glClear will clear the buffers with.
- glClearColor(0.0f, // red
- 0.0f, // green
- 0.0f, // blue
- 1.0f); // alpha
- // Now we can start the event loop, poll for events and draw objects.
- sf::Event event{ };
- while (window.isOpen()) {
- while (window.pollEvent(event)) {
- if (event.type == sf::Event::Closed)
- window.close;
- }
- // Tell OpenGL to clear the color buffer
- // and the depth buffer, this will clear our window.
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
- // Flip front- and backbuffer.
- window.display();
- }
- return 0;
-}
-```
-
-## Loading Shaders
-
-After creating a window and our event loop we should create a function,
-that sets up our shader program.
-
-```cpp
-GLuint createShaderProgram(const std::string& vertexShaderPath,
- const std::string& fragmentShaderPath) {
- // Load the vertex shader source.
- std::stringstream ss{ };
- std::string vertexShaderSource{ };
- std::string fragmentShaderSource{ };
- std::ifstream file{ vertexShaderPath };
- if (file.is_open()) {
- ss << file.rdbuf();
- vertexShaderSource = ss.str();
- file.close();
- }
- // Clear the stringstream and load the fragment shader source.
- ss.str(std::string{ });
- file.open(fragmentShaderPath);
- if (file.is_open()) {
- ss << file.rdbuf();
- fragmentShaderSource = ss.str();
- file.close();
- }
- // Create the program.
- GLuint program = glCreateProgram();
- // Create the shaders.
- GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
- GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
- // Now we can load the shader source into the shader objects and compile them.
- // Because glShaderSource() wants a const char* const*,
- // we must first create a const char* and then pass the reference.
- const char* cVertexSource = vertexShaderSource.c_str();
- glShaderSource(vertexShader, // shader
- 1, // number of strings
- &cVertexSource, // strings
- nullptr); // length of strings (nullptr for 1)
- glCompileShader(vertexShader);
- // Now we have to do the same for the fragment shader.
- const char* cFragmentSource = fragmentShaderSource.c_str();
- glShaderSource(fragmentShader, 1, &cFragmentSource, nullptr);
- glCompileShader(fragmentShader);
- // After attaching the source and compiling the shaders,
- // we attach them to the program;
- glAttachShader(program, vertexShader);
- glAttachShader(program, fragmentShader);
- glLinkProgram(program);
- // After linking the shaders we should detach and delete
- // them to prevent memory leak.
- glDetachShader(program, vertexShader);
- glDetachShader(program, fragmentShader);
- glDeleteShader(vertexShader);
- glDeleteShader(fragmentShader);
- // With everything done we can return the completed program.
- return program;
-}
-```
-
-If you want to check the compilation log you can add the following between <code>glCompileShader()</code> and <code>glAttachShader()</code>.
-
-```cpp
-GLint logSize = 0;
-std::vector<GLchar> logText{ };
-glGetShaderiv(vertexShader, // shader
- GL_INFO_LOG_LENGTH, // requested parameter
- &logSize); // return object
-if (logSize > 0) {
- logText.resize(logSize);
- glGetShaderInfoLog(vertexShader, // shader
- logSize, // buffer length
- &logSize, // returned length
- logText.data()); // buffer
- std::cout << logText.data() << std::endl;
-}
-```
-
-The same is possible after <code>glLinkProgram()</code>, just replace <code>glGetShaderiv()</code> with <code>glGetProgramiv()</code>
-and <code>glGetShaderInfoLog()</code> with <code>glGetProgramInfoLog()</code>.
-
-```cpp
-// Now we can create a shader program with a vertex and a fragment shader.
-// ...
-glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
-
-GLuint program = createShaderProgram("vertex.glsl", "fragment.glsl");
-
-sf::Event event{ };
-// ...
-// We also have to delete the program at the end of the application.
-// ...
- }
- glDeleteProgram(program);
- return 0;
-}
-// ...
-```
-
-Ofcourse we have to create the vertex and fragment shader before we can load them,
-so lets create two basic shaders.
-
-**Vertex Shader**
-
-```glsl
-// Declare which version of GLSL we use.
-// Here we declare, that we want to use the OpenGL 3.3 version of GLSL.
-#version 330 core
-// At attribute location 0 we want an input variable of type vec3,
-// that contains the position of the vertex.
-// Setting the location is optional, if you don't set it you can ask for the
-// location with glGetAttribLocation().
-layout(location = 0) in vec3 position;
-// Every shader starts in it's main function.
-void main() {
- // gl_Position is a predefined variable that holds
- // the final vertex position.
- // It consists of a x, y, z and w coordinate.
- gl_Position = vec4(position, 1.0);
-}
-```
-
-**Fragment Shader**
-
-```glsl
-#version 330 core
-// The fragment shader does not have a predefined variable for
-// the vertex color, so we have to define a output vec4,
-// that holds the final vertex color.
-out vec4 outColor;
-
-void main() {
- // We simply set the output color to red.
- // The parameters are red, green, blue and alpha.
- outColor = vec4(1.0, 0.0, 0.0, 1.0);
-}
-```
-
-## VAO and VBO
-Now we need to define some vertex position we can pass to our shaders. Lets define a simple 2D quad.
-
-```cpp
-// The vertex data is defined in a counter-clockwise way,
-// as this is the default front face.
-std::vector<float> vertexData {
- -0.5f, 0.5f, 0.0f,
- -0.5f, -0.5f, 0.0f,
- 0.5f, -0.5f, 0.0f,
- 0.5f, 0.5f, 0.0f
-};
-// If you want to use a clockwise definition, you can simply call
-glFrontFace(GL_CW);
-// Next we need to define a Vertex Array Object (VAO).
-// The VAO stores the current state while its active.
-GLuint vao = 0;
-glGenVertexArrays(1, &vao);
-glBindVertexArray(vao);
-// With the VAO active we can now create a Vertex Buffer Object (VBO).
-// The VBO stores our vertex data.
-GLuint vbo = 0;
-glGenBuffers(1, &vbo);
-glBindBuffer(GL_ARRAY_BUFFER, vbo);
-// For reading and copying there are also GL_*_READ and GL_*_COPY,
-// if your data changes more often use GL_DYNAMIC_* or GL_STREAM_*.
-glBufferData(GL_ARRAY_BUFFER, // target buffer
- sizeof(vertexData[0]) * vertexData.size(), // size
- vertexData.data(), // data
- GL_STATIC_DRAW); // usage
-// After filling the VBO link it to the location 0 in our vertex shader,
-// which holds the vertex position.
-// ...
-// To ask for the attribute location, if you haven't set it:
-GLint posLocation = glGetAttribLocation(program, "position");
-// ..
-glEnableVertexAttribArray(0);
-glVertexAttribPointer(0, 3, // location and size
- GL_FLOAT, // type of data
- GL_FALSE, // normalized (always false for floats)
- 0, // stride (interleaved arrays)
- nullptr); // offset (interleaved arrays)
-// Everything should now be saved in our VAO and we can unbind it and the VBO.
-glBindVertexArray(0);
-glBindBuffer(GL_ARRAY_BUFFER, 0);
-// Now we can draw the vertex data in our render loop.
-// ...
-glClear(GL_COLOR_BUFFER_BIT);
-// Tell OpenGL we want to use our shader program.
-glUseProgram(program);
-// Binding the VAO loads the data we need.
-glBindVertexArray(vao);
-// We want to draw a quad starting at index 0 of the VBO using 4 indices.
-glDrawArrays(GL_QUADS, 0, 4);
-glBindVertexArray(0);
-window.display();
-// ...
-// Ofcource we have to delete the allocated memory for the VAO and VBO at
-// the end of our application.
-// ...
-glDeleteBuffers(1, &vbo);
-glDeleteVertexArrays(1, &vao);
-glDeleteProgram(program);
-return 0;
-// ...
-```
-
-You can find the current code here: [OpenGL - 1](https://pastebin.com/W8jdmVHD).
-
-## More VBO's and Color
-Let's create another VBO for some colors.
-
-```cpp
-std::vector<float> colorData {
- 1.0f, 0.0f, 0.0f,
- 0.0f, 1.0f, 0.0f,
- 0.0f, 0.0f, 1.0f,
- 1.0f, 1.0f, 0.0f
-};
-```
-
-Next we can simply change some previous parameters to create a second VBO for our colors.
-
-```cpp
-// ...
-GLuint vbo[2];
-glGenBuffers(2, vbo);
-glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
-// ...
-glDeleteBuffers(2, vbo);
-/ ...
-// With these changes made we now have to load our color data into the new VBO
-// ...
-glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
-
-glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
-glBufferData(GL_ARRAY_BUFFER, sizeof(colorData[0]) * colorData.size(),
- colorData.data(), GL_STATIC_DRAW);
-glEnableVertexAttribArray(1);
-glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
-
-glBindVertexArray(0);
-// ...
-```
-
-Next we have to change our vertex shader to pass the color data to the fragment shader.<br>
-**Vertex Shader**
-
-```glsl
-#version 330 core
-
-layout(location = 0) in vec3 position;
-// The new location has to differ from any other input variable.
-// It is the same index we need to pass to
-// glEnableVertexAttribArray() and glVertexAttribPointer().
-layout(location = 1) in vec3 color;
-
-out vec3 fColor;
-
-void main() {
- fColor = color;
- gl_Position = vec4(position, 1.0);
-}
-```
-
-**Fragment Shader**
-
-```glsl
-#version 330 core
-
-in vec3 fColor;
-
-out vec4 outColor;
-
-void main() {
- outColor = vec4(fColor, 1.0);
-}
-```
-
-We define a new input variable ```color``` which represents our color data, this data
-is passed on to ```fColor```, which is an output variable of our vertex shader and
-becomes an input variable for our fragment shader.
-It is imporatant that variables passed between shaders have the exact same name
-and type.
-
-## Handling VBO's
-
-```cpp
-// If you want to completely clear and refill a VBO use glBufferData(),
-// just like we did before.
-// ...
-// There are two mains ways to update a subset of a VBO's data.
-// To update a VBO with existing data
-std::vector<float> newSubData {
- -0.25f, 0.5f, 0.0f
-};
-glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
-glBufferSubData(GL_ARRAY_BUFFER, // target buffer
- 0, // offset
- sizeof(newSubData[0]) * newSubData.size(), // size
- newSubData.data()); // data
-// This would update the first three values in our vbo[0] buffer.
-// If you want to update starting at a specific location just set the second
-// parameter to that value and multiply by the types size.
-// ...
-// If you are streaming data, for example from a file,
-// it is faster to directly pass the data to the buffer.
-// Other access values are GL_READ_ONLY and GL_READ_WRITE.
-glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
-// You can static_cast<float*>() the void* to be more safe.
-void* Ptr = glMapBuffer(GL_ARRAY_BUFFER, // buffer to map
- GL_WRITE_ONLY); // access to buffer
-memcpy(Ptr, newSubData.data(), sizeof(newSubData[0]) * newSubData.size());
-// To copy to a specific location add a destination offset to memcpy().
-glUnmapBuffer(GL_ARRAY_BUFFER);
-// ...
-// There is also a way to copy data from one buffer to another,
-// If we have two VBO's vbo[0] and vbo[1], we can copy like so
-// You can also read from GL_ARRAY_BUFFER.
-glBindBuffer(GL_COPY_READ_BUFFER, vbo[0]);
-// GL_COPY_READ_BUFFER and GL_COPY_WRITE_BUFFER are specifically for
-// copying buffer data.
-glBindBuffer(GL_COPY_WRITE_BUFFER, vbo[1]);
-glCopyBufferSubData(GL_COPY_READ_BUFFER, // read buffer
- GL_COPY_WRITE_BUFFER, // write buffer
- 0, 0, // read and write offset
- sizeof(vbo[0]) * 3); // copy size
-// This will copy the first three elements from vbo[0] to vbo[1].
-```
-
-## Uniforms
-
-**Fragment Shader**
-
-```glsl
-// Uniforms are variables like in and out, however,
-// we can change them easily by passing new values with glUniform().
-// Lets define a time variable in our fragment shader.
-#version 330 core
-// Unlike a in/out variable we can use a uniform in every shader,
-// without the need to pass it to the next one, they are global.
-// Don't use locations already used for attributes!
-// Uniform layout locations require OpenGL 4.3!
-layout(location = 10) uniform float time;
-
-in vec3 fColor;
-
-out vec4 outColor;
-
-void main() {
- // Create a sine wave from 0 to 1 based on the time passed to the shader.
- float factor = (sin(time * 2) + 1) / 2;
- outColor = vec4(fColor.r * factor, fColor.g * factor, fColor.b * factor, 1.0);
-}
-```
-
-Back to our source code.
-
-```cpp
-// If we haven't set the layout location, we can ask for it.
-GLint timeLocation = glGetUniformLocation(program, "time");
-// ...
-// Also we should define a Timer counting the current time.
-sf::Clock clock{ };
-// In out render loop we can now update the uniform every frame.
- // ...
- window.display();
- glUniform1f(10, // location
- clock.getElapsedTime().asSeconds()); // data
-}
-// ...
-```
-
-With the time getting updated every frame the quad should now be changing from
-fully colored to pitch black.
-There are different types of glUniform() you can find simple documentation here:
-[glUniform - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glUniform.xhtml)
-
-## Indexing and IBO's
-
-Element Array Buffers or more commonly Index Buffer Objects (IBO) allow us to use the
-same vertex data again which makes drawing a lot easier and faster. here's an example:
-
-```cpp
-// Lets create a quad from two rectangles.
-// We can simply use the old vertex data from before.
-// First, we have to create the IBO.
-// The index is referring to the first declaration in the VBO.
-std::vector<unsigned int> iboData {
- 0, 1, 2,
- 0, 2, 3
-};
-// That's it, as you can see we could reuse 0 - the top left
-// and 2 - the bottom right.
-// Now that we have our data, we have to fill it into a buffer.
-// Note that this has to happen between the two glBindVertexArray() calls,
-// so it gets saved into the VAO.
-GLuint ibo = 0;
-glGenBufferrs(1, &ibo);
-glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
-glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(iboData[0]) * iboData.size(),
- iboData.data(), GL_STATIC_DRAW);
-// Next in our render loop, we replace glDrawArrays() with:
-glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSIGNED_INT, nullptr);
-// Remember to delete the allocated memory for the IBO.
-```
-
-You can find the current code here: [OpenGL - 2](https://pastebin.com/R3Z9ACDE).
-
-## Textures
-
-To load out texture we first need a library that loads the data, for simplicity I will be
-using SFML, however there are a lot of librarys for loading image data.
-
-```cpp
-// Lets save we have a texture called "my_tex.tga", we can load it with:
-sf::Image image;
-image.loadFromFile("my_tex.tga");
-// We have to flip the texture around the y-Axis, because OpenGL's texture
-// origin is the bottom left corner, not the top left.
-image.flipVertically();
-// After loading it we have to create a OpenGL texture.
-GLuint texture = 0;
-glGenTextures(1, &texture);
-glBindTexture(GL_TEXTURE_2D, texture);
-// Specify what happens when the coordinates are out of range.
-glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
-glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
-// Specify the filtering if the object is very large.
-glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-// Load the image data to the texture.
-glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.getSize().x, image.getSize().y,
- 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr());
-// Unbind the texture to prevent modifications.
-glBindTexture(GL_TEXTURE_2D, 0);
-// Delete the texture at the end of the application.
-// ...
-glDeleteTextures(1, &texture);
-```
-
-Ofcourse there are more texture formats than only 2D textures,
-You can find further information on parameters here:
-[glBindTexture - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBindTexture.xhtml)<br>
-[glTexImage2D - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexImage2D.xhtml)<br>
-[glTexParameter - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexParameter.xhtml)<br>
-
-```cpp
-// With the texture created, we now have to specify the UV,
-// or in OpenGL terms ST coordinates.
-std::vector<float> texCoords {
- // The texture coordinates have to match the triangles/quad
- // definition.
- 0.0f, 1.0f, // start at top-left
- 0.0f, 0.0f, // go round counter-clockwise
- 1.0f, 0.0f,
- 1.0f, 1.0f // end at top-right
-};
-// Now we increase the VBO's size again just like we did for the colors.
-// ...
-GLuint vbo[3];
-glGenBuffers(3, vbo);
-// ...
-glDeleteBuffers(3, vbo);
-// ...
-// Load the texture coordinates into the new buffer.
-glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
-glBufferData(GL_ARRAY_BUFFER, sizeof(texCoords[0]) * texCoords.size(),
- texCoords.data(), GL_STATIC_DRAW);
-glEnableVertexAttribArray(2);
-glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
-// Because the VAO does not store the texture we have to bind it before drawing.
-// ...
-glBindVertexArray(vao);
-glBindTexture(GL_TEXTURE_2D, texture);
-glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSIGNED_INT, nullptr);
-// ...
-```
-
-Change the shaders to pass the data to the fragment shader.<br>
-
-**Vertex Shader**
-
-```glsl
-#version 330 core
-
-layout(location = 0) in vec3 position;
-layout(location = 1) in vec3 color;
-layout(location = 2) in vec2 texCoords;
-
-out vec3 fColor;
-out vec2 fTexCoords;
-
-void main() {
- fColor = color;
- fTexCoords = texCoords;
- gl_Position = vec4(position, 1.0);
-}
-```
-
-**Fragment Shader**
-
-```glsl
-#version 330 core
-// sampler2D represents our 2D texture.
-uniform sampler2D tex;
-uniform float time;
-
-in vec3 fColor;
-in vec2 fTexCoords;
-
-out vec4 outColor;
-
-void main() {
- // texture() loads the current texure data at the specified texture coords,
- // then we can simply multiply them by our color.
- outColor = texture(tex, fTexCoords) * vec4(fColor, 1.0);
-}
-```
-
-You can find the current code here: [OpenGL - 3](https://pastebin.com/u3bcwM6q)
-
-## Matrix Transformation
-
-**Vertex Shader**
-
-```glsl
-#version 330 core
-
-layout(location = 0) in vec3 position;
-layout(location = 1) in vec3 color;
-layout(location = 2) in vec2 texCoords;
-// Create 2 4x4 matricies, 1 for the projection matrix
-// and 1 for the model matrix.
-// Because we draw in a static scene, we don't need a view matrix.
-uniform mat4 projection;
-uniform mat4 model;
-
-out vec3 fColor;
-out vec2 fTexCoords;
-
-void main() {
- fColor = color;
- fTexCoords = texCoords;
- // Multiplay the position by the model matrix and then by the
- // projection matrix.
- // Beware order of multiplication for matricies!
- gl_Position = projection * model * vec4(position, 1.0);
-}
-```
-
-In our source we now need to change the vertex data, create a model- and a projection matrix.
-
-```cpp
-// The new vertex data, counter-clockwise declaration.
-std::vector<float> vertexData {
- 0.0f, 1.0f, 0.0f, // top left
- 0.0f, 0.0f, 0.0f, // bottom left
- 1.0f, 0.0f, 0.0f, // bottom right
- 1.0f, 1.0f, 0.0f // top right
-};
-// Request the location of our matricies.
-GLint projectionLocation = glGetUniformLocation(program, "projection");
-GLint modelLocation = glGetUniformLocation(program, "model");
-// Declaring the matricies.
-// Orthogonal matrix for a 1024x768 window.
-std::vector<float> projection {
- 0.001953f, 0.0f, 0.0f, 0.0f,
- 0.0f, -0.002604f, 0.0f, 0.0f,
- 0.0f, 0.0f, -1.0f, 0.0f,
- -1.0f, 1.0f, 0.0f, 1.0f
-};
-// Model matrix translating to x 50, y 50
-// and scaling to x 200, y 200.
-std::vector<float> model {
- 200.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 200.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 1.0f, 0.0f,
- 50.0f, 50.0f, 0.0f, 1.0f
-};
-// Now we can send our calculated matricies to the program.
-glUseProgram(program);
-glUniformMatrix4fv(projectionLocation, // location
- 1, // count
- GL_FALSE, // transpose the matrix
- projection.data()); // data
-glUniformMatrix4fv(modelLocation, 1, GL_FALSE, model.data());
-glUseProgram(0);
-// The glUniform*() calls have to be done, while the program is bound.
-```
-
-The application should now display the texture at the defined position and size.<br>
-You can find the current code here: [OpenGL - 4](https://pastebin.com/9ahpFLkY)
-
-```cpp
-// There are many math librarys for OpenGL, which create
-// matricies and vectors, the most used in C++ is glm (OpenGL Mathematics).
-// Its a header only library.
-// The same code using glm would look like:
-glm::mat4 projection{ glm::ortho(0.0f, 1024.0f, 768.0f, 0.0f) };
-glUniformMatrix4fv(projectionLocation, 1, GL_FALSE,
- glm::value_ptr(projection));
-// Initialise the model matrix to the identity matrix, otherwise every
-// multiplication would be 0.
-glm::mat4 model{ 1.0f };
-model = glm::translate(model, glm::vec3{ 50.0f, 50.0f, 0.0f });
-model = glm::scale(model, glm::vec3{ 200.0f, 200.0f, 0.0f });
-glUniformMatrix4fv(modelLocation, 1, GL_FALSE,
- glm::value_ptr(model));
-```
-
-## Geometry Shader
-
-Geometry shaders were introduced in OpenGL 3.2, they can produce vertices
-that are send to the rasterizer. They can also change the primitive type e.g.
-they can take a point as an input and output other primitives.
-Geometry shaders are inbetween the vertex and the fragment shader.
-
-**Vertex Shader**
-
-```glsl
-#version 330 core
-
-layout(location = 0) in vec3 position;
-layout(location = 1) in vec3 color;
-// Create an output interface block passed to the next shadaer stage.
-// Interface blocks can be used to structure data passed between shaders.
-out VS_OUT {
- vec3 color;
-} vs_out;
-
-void main() {
- vs_out.color = color
- gl_Position = vec4(position, 1.0);
-}
-```
-
-**Geometry Shader**
-
-```glsl
-#version 330 core
-// The geometry shader takes in points.
-layout(points) in;
-// It outputs a triangle every 3 vertices emitted.
-layout(triangle_strip, max_vertices = 3) out;
-// VS_OUT becomes an input variable in the geometry shader.
-// Every input to the geometry shader in treated as an array.
-in VS_OUT {
- vec3 color;
-} gs_in[];
-// Output color for the fragment shader.
-// You can also simply define color as 'out vec3 color',
-// If you don't want to use interface blocks.
-out GS_OUT {
- vec3 color;
-} gs_out;
-
-void main() {
- // Each emit calls the fragment shader, so we set a color for each vertex.
- gs_out.color = mix(gs_in[0].color, vec3(1.0, 0.0, 0.0), 0.5);
- // Move 0.5 units to the left and emit the new vertex.
- // gl_in[] is the current vertex from the vertex shader, here we only
- // use 0, because we are receiving points.
- gl_Position = gl_in[0].gl_Position + vec4(-0.5, 0.0, 0.0, 0.0);
- EmitVertex();
- gs_out.color = mix(gs_in[0].color, vec3(0.0, 1.0, 0.0), 0.5);
- // Move 0.5 units to the right and emit the new vertex.
- gl_Position = gl_in[0].gl_Position + vec4(0.5, 0.0, 0.0, 0.0);
- EmitVertex();
- gs_out.color = mix(gs_in[0].color, vec3(0.0, 0.0, 1.0), 0.5);
- // Move 0.5 units up and emit the new vertex.
- gl_Position = gl_in[0].gl_Position + vec4(0.0, 0.75, 0.0, 0.0);
- EmitVertex();
- EndPrimitive();
-}
-```
-
-**Fragment Shader**
-
-```glsl
-in GS_OUT {
- vec3 color;
-} fs_in;
-
-out vec4 outColor;
-
-void main() {
- outColor = vec4(fs_in.color, 1.0);
-}
-```
-
-If you now store a single point with a single color in a VBO and draw them,
-you should see a triangle, with your color mixed half way between
-red, green and blue on each vertex.
-
-
-## Quotes
-<sup>[1]</sup>[OpenGL - Wikipedia](https://en.wikipedia.org/wiki/OpenGL)
-
-## Books
-
-- OpenGL Superbible - Fifth Edition (covering OpenGL 3.3)
-- OpenGL Programming Guide - Eighth Edition (covering OpenGL 4.3)
+---
+category: tool
+tool: OpenGL
+filename: learnopengl.cpp
+contributors:
+ - ["Simon Deitermann", "s.f.deitermann@t-online.de"]
+---
+
+**Open Graphics Library** (**OpenGL**) is a cross-language cross-platform application programming interface
+(API) for rendering 2D computer graphics and 3D vector graphics.<sup>[1]</sup> In this tutorial we will be
+focusing on modern OpenGL from 3.3 and above, ignoring "immediate-mode", Displaylists and
+VBO's without use of Shaders.
+I will be using C++ with SFML for window, image and context creation aswell as GLEW
+for modern OpenGL extensions, though there are many other librarys available.
+
+```cpp
+// Creating an SFML window and OpenGL basic setup.
+#include <GL/glew.h>
+#include <GL/gl.h>
+#include <SFML/Graphics.h>
+#include <iostream>
+
+int main() {
+ // First we tell SFML how to setup our OpenGL context.
+ sf::ContextSettings context{ 24, // depth buffer bits
+ 8, // stencil buffer bits
+ 4, // MSAA samples
+ 3, // major opengl version
+ 3 }; // minor opengl version
+ // Now we create the window, enable VSync
+ // and set the window active for OpenGL.
+ sf::Window window{ sf::VideoMode{ 1024, 768 },
+ "opengl window",
+ sf::Style::Default,
+ context };
+ window.setVerticalSyncEnabled(true);
+ window.setActive(true);
+ // After that we initialise GLEW and check if an error occurred.
+ GLenum error;
+ glewExperimental = GL_TRUE;
+ if ((err = glewInit()) != GLEW_OK)
+ std::cout << glewGetErrorString(err) << std::endl;
+ // Here we set the color glClear will clear the buffers with.
+ glClearColor(0.0f, // red
+ 0.0f, // green
+ 0.0f, // blue
+ 1.0f); // alpha
+ // Now we can start the event loop, poll for events and draw objects.
+ sf::Event event{ };
+ while (window.isOpen()) {
+ while (window.pollEvent(event)) {
+ if (event.type == sf::Event::Closed)
+ window.close;
+ }
+ // Tell OpenGL to clear the color buffer
+ // and the depth buffer, this will clear our window.
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+ // Flip front- and backbuffer.
+ window.display();
+ }
+ return 0;
+}
+```
+
+## Loading Shaders
+
+After creating a window and our event loop we should create a function,
+that sets up our shader program.
+
+```cpp
+GLuint createShaderProgram(const std::string& vertexShaderPath,
+ const std::string& fragmentShaderPath) {
+ // Load the vertex shader source.
+ std::stringstream ss{ };
+ std::string vertexShaderSource{ };
+ std::string fragmentShaderSource{ };
+ std::ifstream file{ vertexShaderPath };
+ if (file.is_open()) {
+ ss << file.rdbuf();
+ vertexShaderSource = ss.str();
+ file.close();
+ }
+ // Clear the stringstream and load the fragment shader source.
+ ss.str(std::string{ });
+ file.open(fragmentShaderPath);
+ if (file.is_open()) {
+ ss << file.rdbuf();
+ fragmentShaderSource = ss.str();
+ file.close();
+ }
+ // Create the program.
+ GLuint program = glCreateProgram();
+ // Create the shaders.
+ GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
+ GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
+ // Now we can load the shader source into the shader objects and compile them.
+ // Because glShaderSource() wants a const char* const*,
+ // we must first create a const char* and then pass the reference.
+ const char* cVertexSource = vertexShaderSource.c_str();
+ glShaderSource(vertexShader, // shader
+ 1, // number of strings
+ &cVertexSource, // strings
+ nullptr); // length of strings (nullptr for 1)
+ glCompileShader(vertexShader);
+ // Now we have to do the same for the fragment shader.
+ const char* cFragmentSource = fragmentShaderSource.c_str();
+ glShaderSource(fragmentShader, 1, &cFragmentSource, nullptr);
+ glCompileShader(fragmentShader);
+ // After attaching the source and compiling the shaders,
+ // we attach them to the program;
+ glAttachShader(program, vertexShader);
+ glAttachShader(program, fragmentShader);
+ glLinkProgram(program);
+ // After linking the shaders we should detach and delete
+ // them to prevent memory leak.
+ glDetachShader(program, vertexShader);
+ glDetachShader(program, fragmentShader);
+ glDeleteShader(vertexShader);
+ glDeleteShader(fragmentShader);
+ // With everything done we can return the completed program.
+ return program;
+}
+```
+
+If you want to check the compilation log you can add the following between <code>glCompileShader()</code> and <code>glAttachShader()</code>.
+
+```cpp
+GLint logSize = 0;
+std::vector<GLchar> logText{ };
+glGetShaderiv(vertexShader, // shader
+ GL_INFO_LOG_LENGTH, // requested parameter
+ &logSize); // return object
+if (logSize > 0) {
+ logText.resize(logSize);
+ glGetShaderInfoLog(vertexShader, // shader
+ logSize, // buffer length
+ &logSize, // returned length
+ logText.data()); // buffer
+ std::cout << logText.data() << std::endl;
+}
+```
+
+The same is possible after <code>glLinkProgram()</code>, just replace <code>glGetShaderiv()</code> with <code>glGetProgramiv()</code>
+and <code>glGetShaderInfoLog()</code> with <code>glGetProgramInfoLog()</code>.
+
+```cpp
+// Now we can create a shader program with a vertex and a fragment shader.
+// ...
+glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
+
+GLuint program = createShaderProgram("vertex.glsl", "fragment.glsl");
+
+sf::Event event{ };
+// ...
+// We also have to delete the program at the end of the application.
+// ...
+ }
+ glDeleteProgram(program);
+ return 0;
+}
+// ...
+```
+
+Ofcourse we have to create the vertex and fragment shader before we can load them,
+so lets create two basic shaders.
+
+**Vertex Shader**
+
+```glsl
+// Declare which version of GLSL we use.
+// Here we declare, that we want to use the OpenGL 3.3 version of GLSL.
+#version 330 core
+// At attribute location 0 we want an input variable of type vec3,
+// that contains the position of the vertex.
+// Setting the location is optional, if you don't set it you can ask for the
+// location with glGetAttribLocation().
+layout(location = 0) in vec3 position;
+// Every shader starts in it's main function.
+void main() {
+ // gl_Position is a predefined variable that holds
+ // the final vertex position.
+ // It consists of a x, y, z and w coordinate.
+ gl_Position = vec4(position, 1.0);
+}
+```
+
+**Fragment Shader**
+
+```glsl
+#version 330 core
+// The fragment shader does not have a predefined variable for
+// the vertex color, so we have to define a output vec4,
+// that holds the final vertex color.
+out vec4 outColor;
+
+void main() {
+ // We simply set the output color to red.
+ // The parameters are red, green, blue and alpha.
+ outColor = vec4(1.0, 0.0, 0.0, 1.0);
+}
+```
+
+## VAO and VBO
+Now we need to define some vertex position we can pass to our shaders. Lets define a simple 2D quad.
+
+```cpp
+// The vertex data is defined in a counter-clockwise way,
+// as this is the default front face.
+std::vector<float> vertexData {
+ -0.5f, 0.5f, 0.0f,
+ -0.5f, -0.5f, 0.0f,
+ 0.5f, -0.5f, 0.0f,
+ 0.5f, 0.5f, 0.0f
+};
+// If you want to use a clockwise definition, you can simply call
+glFrontFace(GL_CW);
+// Next we need to define a Vertex Array Object (VAO).
+// The VAO stores the current state while its active.
+GLuint vao = 0;
+glGenVertexArrays(1, &vao);
+glBindVertexArray(vao);
+// With the VAO active we can now create a Vertex Buffer Object (VBO).
+// The VBO stores our vertex data.
+GLuint vbo = 0;
+glGenBuffers(1, &vbo);
+glBindBuffer(GL_ARRAY_BUFFER, vbo);
+// For reading and copying there are also GL_*_READ and GL_*_COPY,
+// if your data changes more often use GL_DYNAMIC_* or GL_STREAM_*.
+glBufferData(GL_ARRAY_BUFFER, // target buffer
+ sizeof(vertexData[0]) * vertexData.size(), // size
+ vertexData.data(), // data
+ GL_STATIC_DRAW); // usage
+// After filling the VBO link it to the location 0 in our vertex shader,
+// which holds the vertex position.
+// ...
+// To ask for the attribute location, if you haven't set it:
+GLint posLocation = glGetAttribLocation(program, "position");
+// ..
+glEnableVertexAttribArray(0);
+glVertexAttribPointer(0, 3, // location and size
+ GL_FLOAT, // type of data
+ GL_FALSE, // normalized (always false for floats)
+ 0, // stride (interleaved arrays)
+ nullptr); // offset (interleaved arrays)
+// Everything should now be saved in our VAO and we can unbind it and the VBO.
+glBindVertexArray(0);
+glBindBuffer(GL_ARRAY_BUFFER, 0);
+// Now we can draw the vertex data in our render loop.
+// ...
+glClear(GL_COLOR_BUFFER_BIT);
+// Tell OpenGL we want to use our shader program.
+glUseProgram(program);
+// Binding the VAO loads the data we need.
+glBindVertexArray(vao);
+// We want to draw a quad starting at index 0 of the VBO using 4 indices.
+glDrawArrays(GL_QUADS, 0, 4);
+glBindVertexArray(0);
+window.display();
+// ...
+// Ofcource we have to delete the allocated memory for the VAO and VBO at
+// the end of our application.
+// ...
+glDeleteBuffers(1, &vbo);
+glDeleteVertexArrays(1, &vao);
+glDeleteProgram(program);
+return 0;
+// ...
+```
+
+You can find the current code here: [OpenGL - 1](https://pastebin.com/W8jdmVHD).
+
+## More VBO's and Color
+Let's create another VBO for some colors.
+
+```cpp
+std::vector<float> colorData {
+ 1.0f, 0.0f, 0.0f,
+ 0.0f, 1.0f, 0.0f,
+ 0.0f, 0.0f, 1.0f,
+ 1.0f, 1.0f, 0.0f
+};
+```
+
+Next we can simply change some previous parameters to create a second VBO for our colors.
+
+```cpp
+// ...
+GLuint vbo[2];
+glGenBuffers(2, vbo);
+glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
+// ...
+glDeleteBuffers(2, vbo);
+/ ...
+// With these changes made we now have to load our color data into the new VBO
+// ...
+glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
+
+glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
+glBufferData(GL_ARRAY_BUFFER, sizeof(colorData[0]) * colorData.size(),
+ colorData.data(), GL_STATIC_DRAW);
+glEnableVertexAttribArray(1);
+glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
+
+glBindVertexArray(0);
+// ...
+```
+
+Next we have to change our vertex shader to pass the color data to the fragment shader.<br>
+**Vertex Shader**
+
+```glsl
+#version 330 core
+
+layout(location = 0) in vec3 position;
+// The new location has to differ from any other input variable.
+// It is the same index we need to pass to
+// glEnableVertexAttribArray() and glVertexAttribPointer().
+layout(location = 1) in vec3 color;
+
+out vec3 fColor;
+
+void main() {
+ fColor = color;
+ gl_Position = vec4(position, 1.0);
+}
+```
+
+**Fragment Shader**
+
+```glsl
+#version 330 core
+
+in vec3 fColor;
+
+out vec4 outColor;
+
+void main() {
+ outColor = vec4(fColor, 1.0);
+}
+```
+
+We define a new input variable ```color``` which represents our color data, this data
+is passed on to ```fColor```, which is an output variable of our vertex shader and
+becomes an input variable for our fragment shader.
+It is imporatant that variables passed between shaders have the exact same name
+and type.
+
+## Handling VBO's
+
+```cpp
+// If you want to completely clear and refill a VBO use glBufferData(),
+// just like we did before.
+// ...
+// There are two mains ways to update a subset of a VBO's data.
+// To update a VBO with existing data
+std::vector<float> newSubData {
+ -0.25f, 0.5f, 0.0f
+};
+glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
+glBufferSubData(GL_ARRAY_BUFFER, // target buffer
+ 0, // offset
+ sizeof(newSubData[0]) * newSubData.size(), // size
+ newSubData.data()); // data
+// This would update the first three values in our vbo[0] buffer.
+// If you want to update starting at a specific location just set the second
+// parameter to that value and multiply by the types size.
+// ...
+// If you are streaming data, for example from a file,
+// it is faster to directly pass the data to the buffer.
+// Other access values are GL_READ_ONLY and GL_READ_WRITE.
+glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
+// You can static_cast<float*>() the void* to be more safe.
+void* Ptr = glMapBuffer(GL_ARRAY_BUFFER, // buffer to map
+ GL_WRITE_ONLY); // access to buffer
+memcpy(Ptr, newSubData.data(), sizeof(newSubData[0]) * newSubData.size());
+// To copy to a specific location add a destination offset to memcpy().
+glUnmapBuffer(GL_ARRAY_BUFFER);
+// ...
+// There is also a way to copy data from one buffer to another,
+// If we have two VBO's vbo[0] and vbo[1], we can copy like so
+// You can also read from GL_ARRAY_BUFFER.
+glBindBuffer(GL_COPY_READ_BUFFER, vbo[0]);
+// GL_COPY_READ_BUFFER and GL_COPY_WRITE_BUFFER are specifically for
+// copying buffer data.
+glBindBuffer(GL_COPY_WRITE_BUFFER, vbo[1]);
+glCopyBufferSubData(GL_COPY_READ_BUFFER, // read buffer
+ GL_COPY_WRITE_BUFFER, // write buffer
+ 0, 0, // read and write offset
+ sizeof(vbo[0]) * 3); // copy size
+// This will copy the first three elements from vbo[0] to vbo[1].
+```
+
+## Uniforms
+
+**Fragment Shader**
+
+```glsl
+// Uniforms are variables like in and out, however,
+// we can change them easily by passing new values with glUniform().
+// Lets define a time variable in our fragment shader.
+#version 330 core
+// Unlike a in/out variable we can use a uniform in every shader,
+// without the need to pass it to the next one, they are global.
+// Don't use locations already used for attributes!
+// Uniform layout locations require OpenGL 4.3!
+layout(location = 10) uniform float time;
+
+in vec3 fColor;
+
+out vec4 outColor;
+
+void main() {
+ // Create a sine wave from 0 to 1 based on the time passed to the shader.
+ float factor = (sin(time * 2) + 1) / 2;
+ outColor = vec4(fColor.r * factor, fColor.g * factor, fColor.b * factor, 1.0);
+}
+```
+
+Back to our source code.
+
+```cpp
+// If we haven't set the layout location, we can ask for it.
+GLint timeLocation = glGetUniformLocation(program, "time");
+// ...
+// Also we should define a Timer counting the current time.
+sf::Clock clock{ };
+// In out render loop we can now update the uniform every frame.
+ // ...
+ window.display();
+ glUniform1f(10, // location
+ clock.getElapsedTime().asSeconds()); // data
+}
+// ...
+```
+
+With the time getting updated every frame the quad should now be changing from
+fully colored to pitch black.
+There are different types of glUniform() you can find simple documentation here:
+[glUniform - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glUniform.xhtml)
+
+## Indexing and IBO's
+
+Element Array Buffers or more commonly Index Buffer Objects (IBO) allow us to use the
+same vertex data again which makes drawing a lot easier and faster. here's an example:
+
+```cpp
+// Lets create a quad from two rectangles.
+// We can simply use the old vertex data from before.
+// First, we have to create the IBO.
+// The index is referring to the first declaration in the VBO.
+std::vector<unsigned int> iboData {
+ 0, 1, 2,
+ 0, 2, 3
+};
+// That's it, as you can see we could reuse 0 - the top left
+// and 2 - the bottom right.
+// Now that we have our data, we have to fill it into a buffer.
+// Note that this has to happen between the two glBindVertexArray() calls,
+// so it gets saved into the VAO.
+GLuint ibo = 0;
+glGenBufferrs(1, &ibo);
+glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
+glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(iboData[0]) * iboData.size(),
+ iboData.data(), GL_STATIC_DRAW);
+// Next in our render loop, we replace glDrawArrays() with:
+glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSIGNED_INT, nullptr);
+// Remember to delete the allocated memory for the IBO.
+```
+
+You can find the current code here: [OpenGL - 2](https://pastebin.com/R3Z9ACDE).
+
+## Textures
+
+To load out texture we first need a library that loads the data, for simplicity I will be
+using SFML, however there are a lot of librarys for loading image data.
+
+```cpp
+// Lets save we have a texture called "my_tex.tga", we can load it with:
+sf::Image image;
+image.loadFromFile("my_tex.tga");
+// We have to flip the texture around the y-Axis, because OpenGL's texture
+// origin is the bottom left corner, not the top left.
+image.flipVertically();
+// After loading it we have to create a OpenGL texture.
+GLuint texture = 0;
+glGenTextures(1, &texture);
+glBindTexture(GL_TEXTURE_2D, texture);
+// Specify what happens when the coordinates are out of range.
+glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+// Specify the filtering if the object is very large.
+glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+// Load the image data to the texture.
+glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.getSize().x, image.getSize().y,
+ 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr());
+// Unbind the texture to prevent modifications.
+glBindTexture(GL_TEXTURE_2D, 0);
+// Delete the texture at the end of the application.
+// ...
+glDeleteTextures(1, &texture);
+```
+
+Ofcourse there are more texture formats than only 2D textures,
+You can find further information on parameters here:
+[glBindTexture - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBindTexture.xhtml)<br>
+[glTexImage2D - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexImage2D.xhtml)<br>
+[glTexParameter - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexParameter.xhtml)<br>
+
+```cpp
+// With the texture created, we now have to specify the UV,
+// or in OpenGL terms ST coordinates.
+std::vector<float> texCoords {
+ // The texture coordinates have to match the triangles/quad
+ // definition.
+ 0.0f, 1.0f, // start at top-left
+ 0.0f, 0.0f, // go round counter-clockwise
+ 1.0f, 0.0f,
+ 1.0f, 1.0f // end at top-right
+};
+// Now we increase the VBO's size again just like we did for the colors.
+// ...
+GLuint vbo[3];
+glGenBuffers(3, vbo);
+// ...
+glDeleteBuffers(3, vbo);
+// ...
+// Load the texture coordinates into the new buffer.
+glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
+glBufferData(GL_ARRAY_BUFFER, sizeof(texCoords[0]) * texCoords.size(),
+ texCoords.data(), GL_STATIC_DRAW);
+glEnableVertexAttribArray(2);
+glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
+// Because the VAO does not store the texture we have to bind it before drawing.
+// ...
+glBindVertexArray(vao);
+glBindTexture(GL_TEXTURE_2D, texture);
+glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSIGNED_INT, nullptr);
+// ...
+```
+
+Change the shaders to pass the data to the fragment shader.<br>
+
+**Vertex Shader**
+
+```glsl
+#version 330 core
+
+layout(location = 0) in vec3 position;
+layout(location = 1) in vec3 color;
+layout(location = 2) in vec2 texCoords;
+
+out vec3 fColor;
+out vec2 fTexCoords;
+
+void main() {
+ fColor = color;
+ fTexCoords = texCoords;
+ gl_Position = vec4(position, 1.0);
+}
+```
+
+**Fragment Shader**
+
+```glsl
+#version 330 core
+// sampler2D represents our 2D texture.
+uniform sampler2D tex;
+uniform float time;
+
+in vec3 fColor;
+in vec2 fTexCoords;
+
+out vec4 outColor;
+
+void main() {
+ // texture() loads the current texure data at the specified texture coords,
+ // then we can simply multiply them by our color.
+ outColor = texture(tex, fTexCoords) * vec4(fColor, 1.0);
+}
+```
+
+You can find the current code here: [OpenGL - 3](https://pastebin.com/u3bcwM6q)
+
+## Matrix Transformation
+
+**Vertex Shader**
+
+```glsl
+#version 330 core
+
+layout(location = 0) in vec3 position;
+layout(location = 1) in vec3 color;
+layout(location = 2) in vec2 texCoords;
+// Create 2 4x4 matricies, 1 for the projection matrix
+// and 1 for the model matrix.
+// Because we draw in a static scene, we don't need a view matrix.
+uniform mat4 projection;
+uniform mat4 model;
+
+out vec3 fColor;
+out vec2 fTexCoords;
+
+void main() {
+ fColor = color;
+ fTexCoords = texCoords;
+ // Multiplay the position by the model matrix and then by the
+ // projection matrix.
+ // Beware order of multiplication for matricies!
+ gl_Position = projection * model * vec4(position, 1.0);
+}
+```
+
+In our source we now need to change the vertex data, create a model- and a projection matrix.
+
+```cpp
+// The new vertex data, counter-clockwise declaration.
+std::vector<float> vertexData {
+ 0.0f, 1.0f, 0.0f, // top left
+ 0.0f, 0.0f, 0.0f, // bottom left
+ 1.0f, 0.0f, 0.0f, // bottom right
+ 1.0f, 1.0f, 0.0f // top right
+};
+// Request the location of our matricies.
+GLint projectionLocation = glGetUniformLocation(program, "projection");
+GLint modelLocation = glGetUniformLocation(program, "model");
+// Declaring the matricies.
+// Orthogonal matrix for a 1024x768 window.
+std::vector<float> projection {
+ 0.001953f, 0.0f, 0.0f, 0.0f,
+ 0.0f, -0.002604f, 0.0f, 0.0f,
+ 0.0f, 0.0f, -1.0f, 0.0f,
+ -1.0f, 1.0f, 0.0f, 1.0f
+};
+// Model matrix translating to x 50, y 50
+// and scaling to x 200, y 200.
+std::vector<float> model {
+ 200.0f, 0.0f, 0.0f, 0.0f,
+ 0.0f, 200.0f, 0.0f, 0.0f,
+ 0.0f, 0.0f, 1.0f, 0.0f,
+ 50.0f, 50.0f, 0.0f, 1.0f
+};
+// Now we can send our calculated matricies to the program.
+glUseProgram(program);
+glUniformMatrix4fv(projectionLocation, // location
+ 1, // count
+ GL_FALSE, // transpose the matrix
+ projection.data()); // data
+glUniformMatrix4fv(modelLocation, 1, GL_FALSE, model.data());
+glUseProgram(0);
+// The glUniform*() calls have to be done, while the program is bound.
+```
+
+The application should now display the texture at the defined position and size.<br>
+You can find the current code here: [OpenGL - 4](https://pastebin.com/9ahpFLkY)
+
+```cpp
+// There are many math librarys for OpenGL, which create
+// matricies and vectors, the most used in C++ is glm (OpenGL Mathematics).
+// Its a header only library.
+// The same code using glm would look like:
+glm::mat4 projection{ glm::ortho(0.0f, 1024.0f, 768.0f, 0.0f) };
+glUniformMatrix4fv(projectionLocation, 1, GL_FALSE,
+ glm::value_ptr(projection));
+// Initialise the model matrix to the identity matrix, otherwise every
+// multiplication would be 0.
+glm::mat4 model{ 1.0f };
+model = glm::translate(model, glm::vec3{ 50.0f, 50.0f, 0.0f });
+model = glm::scale(model, glm::vec3{ 200.0f, 200.0f, 0.0f });
+glUniformMatrix4fv(modelLocation, 1, GL_FALSE,
+ glm::value_ptr(model));
+```
+
+## Geometry Shader
+
+Geometry shaders were introduced in OpenGL 3.2, they can produce vertices
+that are send to the rasterizer. They can also change the primitive type e.g.
+they can take a point as an input and output other primitives.
+Geometry shaders are inbetween the vertex and the fragment shader.
+
+**Vertex Shader**
+
+```glsl
+#version 330 core
+
+layout(location = 0) in vec3 position;
+layout(location = 1) in vec3 color;
+// Create an output interface block passed to the next shadaer stage.
+// Interface blocks can be used to structure data passed between shaders.
+out VS_OUT {
+ vec3 color;
+} vs_out;
+
+void main() {
+ vs_out.color = color
+ gl_Position = vec4(position, 1.0);
+}
+```
+
+**Geometry Shader**
+
+```glsl
+#version 330 core
+// The geometry shader takes in points.
+layout(points) in;
+// It outputs a triangle every 3 vertices emitted.
+layout(triangle_strip, max_vertices = 3) out;
+// VS_OUT becomes an input variable in the geometry shader.
+// Every input to the geometry shader in treated as an array.
+in VS_OUT {
+ vec3 color;
+} gs_in[];
+// Output color for the fragment shader.
+// You can also simply define color as 'out vec3 color',
+// If you don't want to use interface blocks.
+out GS_OUT {
+ vec3 color;
+} gs_out;
+
+void main() {
+ // Each emit calls the fragment shader, so we set a color for each vertex.
+ gs_out.color = mix(gs_in[0].color, vec3(1.0, 0.0, 0.0), 0.5);
+ // Move 0.5 units to the left and emit the new vertex.
+ // gl_in[] is the current vertex from the vertex shader, here we only
+ // use 0, because we are receiving points.
+ gl_Position = gl_in[0].gl_Position + vec4(-0.5, 0.0, 0.0, 0.0);
+ EmitVertex();
+ gs_out.color = mix(gs_in[0].color, vec3(0.0, 1.0, 0.0), 0.5);
+ // Move 0.5 units to the right and emit the new vertex.
+ gl_Position = gl_in[0].gl_Position + vec4(0.5, 0.0, 0.0, 0.0);
+ EmitVertex();
+ gs_out.color = mix(gs_in[0].color, vec3(0.0, 0.0, 1.0), 0.5);
+ // Move 0.5 units up and emit the new vertex.
+ gl_Position = gl_in[0].gl_Position + vec4(0.0, 0.75, 0.0, 0.0);
+ EmitVertex();
+ EndPrimitive();
+}
+```
+
+**Fragment Shader**
+
+```glsl
+in GS_OUT {
+ vec3 color;
+} fs_in;
+
+out vec4 outColor;
+
+void main() {
+ outColor = vec4(fs_in.color, 1.0);
+}
+```
+
+If you now store a single point with a single color in a VBO and draw them,
+you should see a triangle, with your color mixed half way between
+red, green and blue on each vertex.
+
+
+## Quotes
+<sup>[1]</sup>[OpenGL - Wikipedia](https://en.wikipedia.org/wiki/OpenGL)
+
+## Books
+
+- OpenGL Superbible - Fifth Edition (covering OpenGL 3.3)
+- OpenGL Programming Guide - Eighth Edition (covering OpenGL 4.3)
diff --git a/osl.html.markdown b/osl.html.markdown
index af5f83bc..1fe010ec 100644
--- a/osl.html.markdown
+++ b/osl.html.markdown
@@ -747,5 +747,5 @@ for (int i = 0; i < 5; i += 1) {
* [Blender Docs for OSL](https://docs.blender.org/manual/en/latest/render/shader_nodes/osl.html)
* [C4D Docs for OSL](https://docs.otoy.com/cinema4d//OpenShadingLanguageOSL.html)
-* Open Shading Language on [Github](https://github.com/AcademySoftwareFoundation/OpenShadingLanguage)
+* Open Shading Language on [GitHub](https://github.com/AcademySoftwareFoundation/OpenShadingLanguage)
* [Official OSL Documentation](https://open-shading-language.readthedocs.io/en/main/) \ No newline at end of file
diff --git a/powershell.html.markdown b/powershell.html.markdown
index 2e7539a5..4488d94c 100644
--- a/powershell.html.markdown
+++ b/powershell.html.markdown
@@ -229,7 +229,7 @@ $defaultArray.Add("thing4") # => Exception "Collection was of a fixed size."
# ArrayLists store sequences
[System.Collections.ArrayList]$array = @()
# You can start with a prefilled ArrayList
-[System.Collections.ArrayList]$otherArray = @(4, 5, 6)
+[System.Collections.ArrayList]$otherArray = @(5, 6, 7, 8)
# Add to the end of a list with 'Add' (Note: produces output, append to $null)
$array.Add(1) > $null # $array is now [1]
@@ -245,25 +245,14 @@ $array.Add(3) > $null # array is now [1, 2, 4, 3] again.
$array[0] # => 1
# Look at the last element
$array[-1] # => 3
-
# Looking out of bounds returns nothing
$array[4] # blank line returned
-# You can look at ranges with slice syntax.
-# The start index is included, the end index is not
-# (It's a closed/open range for you mathy types.)
-$array[1..3] # Return array from index 1 to 3 => [2, 4]
-$array[2..-1] # Return array starting from index 2 => [4, 3]
-$array[0..3] # Return array from beginning until index 3 => [1, 2, 4]
-$array[0..2] # Return array selecting every second entry => [1, 4]
-$array.Reverse() # mutates array to reverse order => [3, 4, 2, 1]
-# Use any combination of these to make advanced slices
-
-# Remove arbitrary elements from a array with "del"
-$array.Remove($array[2]) # $array is now [1, 2, 3]
+# Remove elements from a array
+$array.Remove($array[3]) # $array is now [1, 2, 4]
-# Insert an element at a specific index
-$array.Insert(1, 2) # $array is now [1, 2, 3] again
+# Insert at index an element
+$array.Insert(2, 3) # $array is now [1, 2, 3, 4]
# Get the index of the first item found matching the argument
$array.IndexOf(2) # => 1
@@ -271,16 +260,24 @@ $array.IndexOf(6) # Returns -1 as "outside array"
# You can add arrays
# Note: values for $array and for $otherArray are not modified.
-$array + $otherArray # => [1, 2, 3, 4, 5, 6]
+$array + $otherArray # => [1, 2, 3, 4, 5, 6, 7, 8]
# Concatenate arrays with "AddRange()"
-$array.AddRange($otherArray) # Now $array is [1, 2, 3, 4, 5, 6]
+$array.AddRange($otherArray) # Now $array is [1, 2, 3, 4, 5, 6, 7, 8]
# Check for existence in a array with "in"
1 -in $array # => True
# Examine length with "Count" (Note: "Length" on arrayList = each items length)
-$array.Count # => 6
+$array.Count # => 8
+
+# You can look at ranges with slice syntax.
+$array[1,3,5] # Return selected index => [2, 4, 6]
+$array[1..3] # Return from index 1 to 3 => [2, 3, 4]
+$array[-3..-1] # Return from last 3 to last 1 => [6, 7, 8]
+$array[-1..-3] # Return from last 1 to last 3 => [8, 7, 6]
+$array[2..-1] # Return from index 2 to last (NOT as most expect) => [3, 2, 1, 8]
+$array[0,2+4..6] # Return multiple ranges with the + => [1, 3, 5, 6, 7]
# -eq doesn't compare array but extract the matching elements
$array = 1,2,3,1,1
@@ -296,13 +293,14 @@ $tuple.Item(0) = 3 # Raises a TypeError
# You can do some of the array methods on tuples, but they are limited.
$tuple.Length # => 3
$tuple + (4, 5, 6) # => Exception
-$tuple[0..2] # => $null
+$tuple[0..2] # => $null (in powershell 5) => [1, 2, 3] (in powershell 7)
2 -in $tuple # => False
-# Hashtables store mappings from keys to values, similar to Dictionaries.
+# Hashtables store mappings from keys to values, similar to (but distinct from) Dictionaries.
+# Hashtables do not hold entry order as arrays do.
$emptyHash = @{}
-# Here is a prefilled dictionary
+# Here is a prefilled hashtable
$filledHash = @{"one"= 1
"two"= 2
"three"= 3}
@@ -311,7 +309,6 @@ $filledHash = @{"one"= 1
$filledHash["one"] # => 1
# Get all keys as an iterable with ".Keys".
-# items maintain the order at which they are inserted into the dictionary.
$filledHash.Keys # => ["one", "two", "three"]
# Get all values as an iterable with ".Values".
@@ -319,18 +316,18 @@ $filledHash.Values # => [1, 2, 3]
# Check for existence of keys or values in a hash with "-in"
"one" -in $filledHash.Keys # => True
-1 -in $filledHash.Values # => False
+1 -in $filledHash.Values # => False (in powershell 5) => True (in powershell 7)
# Looking up a non-existing key returns $null
$filledHash["four"] # $null
-# Adding to a dictionary
+# Adding to a hashtable
$filledHash.Add("five",5) # $filledHash["five"] is set to 5
$filledHash.Add("five",6) # exception "Item with key "five" has already been added"
-$filledHash["four"] = 4 # $filledHash["four"] is set to 4, running again does nothing
+$filledHash["four"] = 4 # $filledHash["four"] is set to 4, running again does nothing
-# Remove keys from a dictionary with del
-$filledHash.Remove("one") # Removes the key "one" from filled dict
+# Remove keys from a hashtable
+$filledHash.Remove("one") # Removes the key "one" from filled hashtable
####################################################
@@ -677,7 +674,7 @@ Powershell as a Tool:
Getting Help:
-```Powershell
+```powershell
# Find commands
Get-Command about_* # alias: gcm
Get-Command -Verb Add
@@ -694,7 +691,7 @@ Update-Help # Run as admin
If you are uncertain about your environment:
-```Powershell
+```powershell
Get-ExecutionPolicy -List
Set-ExecutionPolicy AllSigned
# Execution policies include:
@@ -708,7 +705,7 @@ help about_Execution_Policies # for more info
$PSVersionTable
```
-```Powershell
+```powershell
# Calling external commands, executables,
# and functions with the call operator.
# Exe paths with arguments passed or containing spaces can create issues.
diff --git a/pt-br/amd-pt.html.markdown b/pt-br/amd-pt.html.markdown
index 40c7cd09..886cb253 100644
--- a/pt-br/amd-pt.html.markdown
+++ b/pt-br/amd-pt.html.markdown
@@ -19,6 +19,7 @@ módulos de forma síncrona fica sujeito a problemas de performance, usabilidade
debugging e problemas de acesso em requisições cross-domain.
### Conceito básico
+
```javascript
// O básico da API de AMD consiste de nada mais que dois métodos: `define` e `require`
// e isso é tudo sobre a definição de módulo e consumo:
@@ -122,6 +123,7 @@ define(['daos/coisas', 'modules/algunsHelpers'], function(coisasDao, helpers){
return AlgumaClasse;
});
```
+
Para alterar o comportamento padrão de mapeamento de caminho de pastas utilize
`requirejs.config(configObj)` em seu `main.js`:
@@ -141,6 +143,7 @@ require(['jquery', 'coolLibFromBower', 'modules/algunsHelpers'], function($, coo
coolLib.facaAlgoDoidoCom(helpers.transform($('#foo')));
});
```
+
Apps baseados em `require.js` geralmente terão um único ponto de acesso (`main.js`) que é passado à tag script do `require.js` como um data-attribute. Ele vai ser automaticamente carregado e executado com o carregamento da página:
```html
@@ -162,16 +165,19 @@ Muitas pessoas preferem usar AMD para sanar a organização do código durante o
`require.js` vem com um script chamado `r.js` (que você vai provavelmente rodar em node.js, embora Rhino suporte também) que você pode analisar o gráfico de dependências de seu projeto, e fazer em um único arquivo contendo todos os seus módulos (corretamente nomeados), minificados e prontos para serem consumidos.
Instale-o utilizando `npm`:
+
```shell
$ npm install requirejs -g
```
Agora você pode alimentá-lo com um arquivo de configuração:
+
```shell
$ r.js -o app.build.js
```
Para o nosso exemplo acima a configuração pode ser essa:
+
```javascript
/* file : app.build.js */
({
@@ -188,6 +194,7 @@ Para o nosso exemplo acima a configuração pode ser essa:
```
Para usar o arquivo gerado, em produção, simplesmente troque o `data-main`:
+
```html
<script src="require.js" data-main="app/main-built"></script>
```
diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown
index 87e5b3a4..d464a639 100644
--- a/pt-br/csharp-pt.html.markdown
+++ b/pt-br/csharp-pt.html.markdown
@@ -252,7 +252,7 @@ on a new line! ""Wow!"", the masses cried";
{
// Inicia a interação 100 vezes, fooDoWhile 0->99
if (false)
- continue; // pule a intereção atual para apróxima
+ continue; // pule a intereção atual para a próxima
fooDoWhile++;
@@ -269,7 +269,7 @@ on a new line! ""Wow!"", the masses cried";
// For Each Loop
// Estrutura do foreach => foreach(<Tipo Iterador> <Nome do Iterador> in <enumerable>)
- // O laço foreach percorre sobre qualquer objeto que implementa IEnumerable ou IEnumerable<T>
+ // O laço foreach percorre sobre qualquer objeto que implementa IEnumerable ou IEnumerable<T>
// Toda a coleção de tipos (Array, List, Dictionary...) no .Net framework
// implementa uma ou mais destas interfaces.
// (O ToCharArray() pode ser removido, por que uma string também implementa IEnumerable)
diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown
index e4f55276..4c52942a 100644
--- a/pt-br/css-pt.html.markdown
+++ b/pt-br/css-pt.html.markdown
@@ -8,33 +8,36 @@ contributors:
- ["Connor Shea", "https://github.com/connorshea"]
- ["Deepanshu Utkarsh", "https://github.com/duci9y"]
translators:
+ - ["Adaías Magdiel", "https://adaiasmagdiel.com/"]
- ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"]
- ["Gabriele Luz", "https://github.com/gabrieleluz"]
-
lang: pt-br
---
-No início da web não havia elementos visuais, apenas texto puro. Mas com maior desenvolvimento de navegadores da web, páginas web totalmente visuais também se tornaram comuns.
-
-CSS ajuda a manter a separação entre o conteúdo (HTML) e o visual de uma página web.
+Páginas web são feitas utilizando HTML para demarcar o conteúdo.
+O CSS (Cascading Style Sheets) é uma linguagem separada que é responsável
+especificamente pela **aparência** da página.
-CSS permite atingir diferentes elementos em uma página HTML e atribuir diferentes propriedades visuais para eles.
+Códigos CSS são construídos utilizando várias regras estáticas. Cada regra aceita um ou mais *seletores*
+e aplica *valores* específicos de propriedades visuais. Essas propriedades são aplicadas
+nos elementos da página indicados pelos seletores.
-Este guia foi escrito para CSS2, embora CSS3 esteja rapidamente se tornando popular.
+Este guia foi escrito com o CSS 2 em mente, complementado pelas novas
+funcionalidades do CSS 3.
-**NOTA:** Porque CSS produz resultados visuais, a fim de aprender, você precisa treinar em um playground CSS como [dabblet](http://dabblet.com/).
-O foco principal deste artigo é sobre a sintaxe e algumas dicas gerais.
+**NOTA:** Devido ao fato do CSS produzir resultados visuais, a fim de aprender, você precisa treinar em um playground CSS como [dabblet](http://dabblet.com/).
+O foco principal deste artigo é a sintaxe e algumas dicas gerais.
```css
-/* Comentários aparecem dentro do slash-asterisk, tal como esta linha!
- Não há "comentários de uma linha"; este é o único estilo de comentário * /
+/* Comentários aparecem dentro de blocos com / e *, tal como esta linha!
+ Não há "comentários de uma linha"; este é o único estilo de comentário. * /
/* ####################
## SELETORES
#################### */
-/* O seletor é usado para direcionar um elemento em uma página.
- seletor { propriedade: valor; / * Mais propriedades ... * / }
+/* O seletor é usado para selecionar um elemento em uma página. */
+seletor { propriedade: valor; /* Mais propriedades... */ }
/*
Abaixo um elemento de exemplo:
@@ -42,63 +45,62 @@ Abaixo um elemento de exemplo:
<div class='class1 class2' id='anID' attr='value' otherAttr='pt-br foo bar' />
*/
-/* Você pode direcioná-lo usando uma das suas classes CSS */
+/* Você pode seleciona-lo usando uma das suas classes CSS */
.class1 { }
-/* ou ambas as classes! */
+/* Ou ambas as classes! */
.class1.class2 { }
-/* ou o seu nome */
+/* Ou o seu nome */
div { }
-/* ou o seu id */
+/* Ou o seu id */
#anID { }
-/* ou utilizando o fator de que tem um atributo!*/
-[attr] { font-size:smaller; }
+/* Ou através de um dos seus atributos! */
+[attr] { font-size: smaller; }
-/* ou que o atributo tem um valor específico */
-[attr='value'] { font-size:smaller; }
+/* Ou utilizando um atributo com um valor específico */
+[attr='value'] { font-size: smaller; }
-/* começa com um valor (CSS 3) */
+/* Um atributo que começa com um valor (CSS 3) */
[attr^='val'] { font-size:smaller; }
-/* ou terminando com um valor (CSS 3) */
-[attr$='ue'] { font-size:smaller; }
-
+/* Ou termina com um valor (CSS 3) */
+[attr$='ue'] { font-size: smaller; }
/* Ou contém um valor em uma lista separada por espaços */
-[otherAttr ~ = 'foo'] {}
-[otherAttr ~ = 'bar'] {}
+[otherAttr~='foo'] {}
+[otherAttr~='bar'] {}
/* Ou contém um valor em uma lista separada por hífen, ou seja, "-" (U + 002D) */
-[otherAttr | = 'en'] {font-size: smaller; }
+[otherAttr|='pt'] {font-size: smaller; }
-/* Você pode concatenar diferentes seletores para criar um seletor mais estreito. Não
-   colocar espaços entre eles. */
-classe div.some [attr $ = 'ue'] {}
+/* Você pode combinar diferentes seletores para criar um seletor mais específica. Lembre-se
+ de não colocar espaço entre eles */
+div.some-class[attr$='ue'] {}
-/* Você pode selecionar um elemento que é filho de outro elemento */
-div.some-parent> .class-name {}
+/* Você pode selecionar um elemento que está diretamento dentro de outro elemento */
+div.some-parent > .class-name {}
-/* Ou um descendente de um outro elemento. Os filhos são os descendentes diretos de
-   seu elemento pai, apenas um nível abaixo da árvore. Pode ser quaisquer descendentes
-   nivelados por baixo da árvore. */
-div.some-parent class-name {}
+/* Ou um descendente desse elemento. Os filhos são os descendentes diretos de
+ um elemento pai, apenas um nível abaixo. Da seguinte forma, você pode seleciona qualquer
+ elemento que esteja dentro do elemento principal. */
+div.some-parent .class-name {}
/* Atenção: o mesmo seletor sem espaço tem um outro significado.
-   Você consegue adivinhar o que? */
+ Dessa forma você estará selecionando um elemento que contenha as duas classes. */
div.some-parent.class-name {}
-/* Você também pode selecionar um elemento com base em seu irmão adjacente */
-.i am just-antes + .Este elemento {}
+/* Você também pode selecionar um elemento com base em seu irmão mais próximo */
+.i-am-just-before + .this-element {}
/* Ou qualquer irmão que o precede */
-.i am-qualquer-elemento antes ~ .Este elemento {}
+.i-am-any-element-before ~ .this-element { }
-/* Existem alguns seletores chamados pseudo classes que podem ser usados para selecionar um
-   elemento quando ele está em um determinado estado */
+/* Existem alguns seletores, chamados pseudo classes, que podem ser usados para selecionar um
+ elemento quando ele está em um determinado estado */
/* Por exemplo, quando o cursor passa sobre um elemento */
seletor:hover {}
@@ -112,10 +114,10 @@ seletor:link {}
/* Ou um elemento em foco */
seletor:focus {}
-/* Qualquer elemento que é o primeiro filho de seu pai */
+/* Qualquer elemento que é o primeiro filho */
seletor:first-child {}
-/* Qualquer elemento que é o último filho de seu pai */
+/* Qualquer elemento que é o último filho */
seletor:last-child {}
/* Assim como pseudo classes, pseudo elementos permitem que você estilize certas partes de um documento */
@@ -126,88 +128,91 @@ seletor::before {}
/* Corresponde a um último filho virtual do elemento selecionado */
seletor::after {}
-/* Nos locais apropriados, um asterisco pode ser utilizado como um curinga para selecionar todos
-   os elementos */
-* {} /* */ Todos os elementos
-.parent * {} /* */ todos os descendentes
-.parent> * {} /* */ todos os filhos
+/* Nos locais apropriados, um asterisco pode ser utilizado como um curinga para selecionar
+ todos os elementos */
+
+* {} /* Todos os elementos */
+.parent * {} /* todos os descendentes */
+.parent > * {} /* todos os filhos */
/* ####################
-   ## PROPRIEDADES
-   #################### */
+ ## PROPRIEDADES
+ #################### */
seletor {
-
-    /* Unidades de comprimento pode ser absoluta ou relativa. */
-
-    /* Unidades relativas */
-    width: 50%; /* Percentagem de largura do elemento pai */
-    font-size: 2em; /* Múltiplos de font-size original de elemento */
-    font-size: 2rem; /* Ou do elemento raiz font-size */
-    font-size: 2vw; /* Múltiplos de 1% da largura da janela de exibição (CSS 3) */
-    font-size: 2vh; /* Ou a sua altura */
-    font-size: 2vmin; /* Qualquer um de VH ou um VW é menor */
-    font-size: 2vmax; /* Ou superior */
-
-    /* Unidades absolutas */
-    width: 200px; /* píxeis */
-    font-size: 20pt; /* Pontos */
-    width: 5cm; /* Centímetros */
-    min-width: 50mm; /* Milímetros */
-    max-width: 5 polegadas; /* Polegadas */
-
-    /* Cores */
-    color: # F6E; /* Formato hexadecimal curto */
-    color: # FF66EE; /* Formato hexadecimal longo */
-    color: tomato; /* Uma cor nomeada */
-    color: rgb (255, 255, 255); /* Como valores rgb */
-    color: RGB (10%, 20%, 50%); /* Como porcentagens rgb */
-    color: rgba (255, 0, 0, 0,3); /* Como valores RGBA (CSS 3) NOTA: 0 <a <1 */
-    color: transparent; /* Equivale a definir o alfa a 0 */
-    color: HSL (0, 100%, 50%); /* Como porcentagens HSL (CSS 3) */
-    color: HSLA (0, 100%, 50%, 0,3); /* Como porcentagens HSLA com alfa */
-
-    /* Imagens como fundos de elementos */
-    background-image: url (/img-path/img.jpg); /* Citações dentro url () opcional */
-
-    /* Fontes */
-    font-family: Arial;
-    /* Se o nome da família de fonte tem um espaço, deve ser citado */
-    font-family: "Courier New";
-    /* Se o primeiro não for encontrada, o navegador usa o próximo, e assim por diante */
-    font-family: "Courier New", Trebuchet, Arial, sans-serif;
+ /* Unidades de comprimento pode ser absoluta ou relativa. */
+
+ /* Unidades relativas */
+ width: 50%; /* Percentagem de largura do elemento pai */
+ font-size: 2em; /* Múltiplos de font-size original de elemento */
+ font-size: 2rem; /* Ou do elemento raiz font-size */
+ font-size: 2vw; /* Múltiplos de 1% da largura da janela de exibição (CSS 3) */
+ font-size: 2vh; /* Ou a sua altura */
+ font-size: 2vmin; /* Qualquer um de VH ou um VW é menor */
+ font-size: 2vmax; /* Ou superior */
+
+ /* Unidades absolutas */
+ width: 200px; /* Píxeis */
+ font-size: 20pt; /* Pontos */
+ width: 5cm; /* Centímetros */
+ min-width: 50mm; /* Milímetros */
+ max-width: 5 polegadas; /* Polegadas */
+
+ /* Cores */
+ color: #F6E; /* Formato hexadecimal curto */
+ color: #FF66EE; /* Formato hexadecimal longo */
+ color: tomato; /* Uma cor nomeada */
+ color: rgb(255, 255, 255); /* Como valores rgb */
+ color: RGB(10%, 20%, 50%); /* Como porcentagens rgb */
+ color: rgba(255, 0, 0, 0,3); /* Como valores RGBA (CSS 3) NOTA: 0 <a <1 */
+ color: transparent; /* Equivale a definir o alfa a 0 */
+ color: HSL(0, 100%, 50%); /* Como porcentagens HSL (CSS 3) */
+ color: HSLA(0, 100%, 50%, 0,3); /* Como porcentagens HSLA com alfa */
+
+ /* Imagens como fundos de elementos */
+ background-image: url(/img-path/img.jpg); /* O uso das aspas dentro de url() é opcional */
+
+ /* Fontes */
+ font-family: Arial;
+ /* Se o nome da família de fonte tem um espaço, deve estar entre aspas */
+ font-family: "Courier New";
+ /* Se o primeiro não for encontrada, o navegador usa a próxima, e assim por diante */
+ font-family: "Courier New", Trebuchet, Arial, sans-serif;
}
```
## Uso
-Salvar uma folha de estilo CSS com a extensão `.css`.
+Salve o arquivo de estilos CSS com a extensão `.css`.
-```xml
-<!-- Você precisa incluir o arquivo css no da sua página <head>. Isto é o
-     método recomendado. Consulte http://stackoverflow.com/questions/8284365 -->
-<link rel='stylesheet' type='text/css' href='path/to/style.css' />
+```html
+<!-- Você precisa incluir o arquivo css dentro da tag <head>. Esse é o
+ método recomendado. Consulte http://stackoverflow.com/questions/8284365 -->
+<link rel="stylesheet" type="text/css" href="path/to/style.css" />
-<!-- Você também pode incluir alguns CSS inline na sua marcação. -->
+<!-- Você também pode incluir alguns CSS inline no seu HTML. -->
<style>
-   a { color: purple; }
+ a { color: purple; }
</style>
-<!-- Ou diretamente definir propriedades CSS no elemento. -->
+<!-- Ou definir propriedades CSS diretamente no elemento. -->
<div style="border: 1px solid red;">
</div>
```
## Precedência ou Cascata
-Um elemento pode ser alvo de vários seletores e pode ter um conjunto de propriedades em que mais de uma vez. Nestes casos, uma das regras tem precedência sobre as outras. Geralmente, uma regra em um seletor mais específico têm precedência sobre um menos específico, e uma regra que ocorre mais tarde na folha de estilo substitui uma anterior.
+Um elemento pode ser alvo de vários seletores e pode ter um conjunto de propriedades que
+são adicionados mais de uma vez. Nestes casos, uma das regras tem precedência sobre as
+outras. Geralmente, uma regra em um seletor mais específico têm precedência sobre um
+menos específico, e uma regra que ocorre mais tarde na folha de estilo substitui uma anterior.
-Este processo é chamado de cascata, portanto, as Fichas de nome de estilo em cascata.
+Este processo é chamado de cascata, daí vem o nome: Cascading Style Sheets (Folhas de Estilo em Cascata).
Dado o seguinte CSS:
```css
-/* UMA */
+/* A */
p.class1[attr="value"]
/* B */
@@ -225,20 +230,22 @@ p { property: value !important; }
e a seguinte marcação:
-```xml
+```html
<p style='/*F*/ property:value;' class='class1 class2' attr='value' />
```
-A precedência de estilo é a seguinte. Lembre-se, a precedência é para cada **propriedade**, não para todo o bloco.
+A precedência de estilo é a seguinte: Lembre-se, a precedência se aplica a
+cada **propriedade**, não ao bloco como um todo.
-* `E` tem a precedência mais alta por causa de uma palavra-chave`!important`. É recomendável que você evitar seu uso.
-* `F` é a próxima, porque é um estilo interno.
-* `A` é a próxima, porque é mais" específico "do que qualquer outra coisa. Tem 3 especificadores: O nome do elemento `p`, o seu `class1` classe, um atributo `attr='value'`.
-* `C` está próximo, mesmo que ele tenha a mesma especificidade que `B`. Isso é porque ele aparece depois de `B`.
-* `B` é o próximo.
-* `D` é a última.
+* `E` tem a precedência mais alta por causa de uma palavra-chave`!important`. É recomendado evitar seu uso.
+* `F` é o seguinte, porque é um estilo interno.
+* `A` é o seguinte, porque é "mais específico" do que os outros. Tem 3 especificadores: O nome do elemento `p`, a sua classe `class1` e um atributo `attr="value"`.
+* `C` é o seguinte, mesmo que ele tenha a mesma especificidade que `B`. Isso acontece porque ele aparece logo após o `B`.
+* `B` é o seguinte.
+* `D` é o último.
## Media Queries
+
Media queries são recursos do CSS3 que permitem especificar quando determinadas regras de CSS devem ser aplicadas; é possível aplicar regras diferentes quando a página é impressa, quando a tela possui determinadas dimensões ou densidade de pixels e quando é lida por um leitor de tela. Media queries não adicionam especificidade ao seletor.
```css
@@ -265,7 +272,8 @@ h1 {
}
}
```
-Media queries podem incluir os seguintes atributos: `width`, `height`, `device-width`, `device-height`, `orientation`, `aspect-ratio`, `device-aspect-ratio`, `color`, `color-index`, `monochrome`, `resolution`, `scan`, `grid`. A maioria desses atributos pode ser prefixada com `min-` ou `max-`.
+
+Media queries podem incluir os seguintes atributos: `width`, `height`, `device-width`, `device-height`, `orientation`, `aspect-ratio`, `device-aspect-ratio`, `color`, `color-index`, `monochrome`, `resolution`, `scan` e `grid`. A maioria desses atributos pode ser prefixada com `min-` ou `max-`.
O atributo `resolution` não é suportado em dispositivos mais antigos. Em vez disso, use `device-pixel-ratio`.
@@ -279,20 +287,22 @@ Muitos smartphones e tablets tentarão renderizar a página como se estivesse nu
## Compatibilidade
-A maior parte dos recursos do CSS 2 (e muitos em CSS 3) estão disponíveis em todos os navegadores e dispositivos. Mas é sempre boa prática verificar antes de usar um novo recurso.
+A maioria dos recursos do CSS 2 (e muitos do CSS 3) está disponível em todos os navegadores
+e dispositivos.
-## Recursos
+## Recursos Adicionais
* Para executar uma verificação de compatibilidade rápida, [CanIUse](http://caniuse.com).
* CSS Playground [Dabblet](http://dabblet.com/).
-* [Documentação CSS Mozilla Developer Rede](https://developer.mozilla.org/en-US/docs/Web/CSS)
-* [Codrops 'Referência CSS](http://tympanus.net/codrops/css_reference/)
+* [Documentação CSS Mozilla Developer](https://developer.mozilla.org/en-US/docs/Web/CSS)
+* [Codrops Referência CSS](http://tympanus.net/codrops/css_reference/)
+* [DevTips CSS Basics](https://www.youtube.com/playlist?list=PLqGj3iMvMa4IOmy04kDxh_hqODMqoeeCy) (Tutorials)
## Leitura adicional
* [Entendendo Estilo Precedência em CSS: Especificidade, Herança, e o Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
* [Selecionando elementos usando atributos](https://css-tricks.com/almanac/selectors/a/attribute/)
* [QuirksMode CSS](http://www.quirksmode.org/css/)
-* [Z-Index - O empilhamento context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
-* [SASS](http://sass-lang.com/) e [Less](http://lesscss.org/) para CSS pré-processamento
+* [Z-Index - O contexto de empilhamento](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
+* [SASS](http://sass-lang.com/) e [Less](http://lesscss.org/) para pré-processamento do CSS
* [CSS-Tricks](https://css-tricks.com)
diff --git a/pt-br/elixir-pt.html.markdown b/pt-br/elixir-pt.html.markdown
index aa1bd060..18441ff7 100644
--- a/pt-br/elixir-pt.html.markdown
+++ b/pt-br/elixir-pt.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
@@ -20,7 +20,7 @@ e muitos outros recursos.
# Não há comentários de múltiplas linhas,
# mas você pode empilhar os comentários.
-# Para usar o shell do elixir use o comando `iex`.
+# Para usar o shell do Elixir use o comando `iex`.
# Compile seus módulos com o comando `elixirc`.
# Ambos devem estar em seu path se você instalou o Elixir corretamente.
@@ -51,7 +51,7 @@ elem({1, 2, 3}, 0) #=> 1
head #=> 1
tail #=> [2,3]
-# Em elixir, bem como em Erlang, o sinal `=` denota pattern match,
+# Em Elixir, bem como em Erlang, o sinal `=` denota pattern match,
# e não uma atribuição.
#
# Isto significa que o que estiver à esquerda (pattern) é comparado com o que
@@ -85,7 +85,7 @@ linhas.
<<?a, ?b, ?c>> #=> "abc"
[?a, ?b, ?c] #=> 'abc'
-# `?a` em elixir retorna o valor ASCII para a letra `a`
+# `?a` em Elixir retorna o valor ASCII para a letra `a`
?a #=> 97
# Para concatenar listas use `++`, para binários use `<>`
@@ -110,7 +110,7 @@ menor..maior = 1..10 # Pattern matching pode ser usada em ranges também
5 * 2 #=> 10
10 / 2 #=> 5.0
-# Em elixir o operador `/` sempre retorna um float.
+# Em Elixir o operador `/` sempre retorna um float.
# Para divisão de inteiros use `div`
div(10, 2) #=> 5
@@ -167,7 +167,7 @@ else
"Isso será"
end
-# Lembra do pattern matching? Muitas estruturas de fluxo de controle em elixir contam com ela.
+# Lembra do pattern matching? Muitas estruturas de fluxo de controle em Elixir contam com ela.
# `case` nos permite comparar um valor com muitos patterns:
case {:um, :dois} do
@@ -296,7 +296,7 @@ Geometry.area({:circle, 3}) #=> 28.25999999999999801048
# Geometry.area({:circle, "not_a_number"})
#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
-# Devido à imutabilidade, recursão é uma grande parte do elixir
+# Devido à imutabilidade, recursão é uma grande parte do Elixir
defmodule Recursion do
def sum_list([head | tail], acc) do
sum_list(tail, acc + head)
@@ -309,7 +309,7 @@ end
Recursion.sum_list([1,2,3], 0) #=> 6
-# Módulos do elixir suportam atributos, hpa atributos embutidos e você
+# Módulos do Elixir suportam atributos, hpa atributos embutidos e você
# pode também adicionar os seus próprios.
defmodule MyMod do
@moduledoc """
@@ -361,7 +361,7 @@ end
## ---------------------------
# Elixir conta com o modelo de ator para concorrência. Tudo o que precisamos para
-# escrever programas concorrentes em elixir são três primitivos: spawning processes,
+# escrever programas concorrentes em Elixir são três primitivos: spawning processes,
# sending messages e receiving messages.
# Para iniciar um novo processo usamos a função `spawn`, a qual leva uma função
diff --git a/pt-br/httpie-pt.html.markdown b/pt-br/httpie-pt.html.markdown
new file mode 100644
index 00000000..f81919fe
--- /dev/null
+++ b/pt-br/httpie-pt.html.markdown
@@ -0,0 +1,122 @@
+---
+category: tool
+tool: httpie
+filename: learn-httpie-pt.sh
+contributors:
+ - ["Adaías Magdiel", "https://github.com/AdaiasMagdiel"]
+translators:
+ - ["Adaías Magdiel", "https://adaiasmagdiel.com/"]
+lang: pt-br
+---
+
+HTTPie é um poderoso cliente HTTP para linha de comando, projetado para uma
+integração suave com servidores HTTP. Oferece uma interface simples e intuitiva,
+tornando-se uma excelente ferramenta para desenvolvedores, testadores e administradores de sistemas.
+
+## Uso Básico
+
+HTTPie possui uma sintaxe simples: http [flags] [MÉTODO] URL [itens].
+
+```bash
+http GET https://api.example.com/posts
+```
+
+Você pode exibir a requisição sem executá-la, de fato, usando a flag `--offline`.
+
+```bash
+http --offline https://api.example.com/posts
+```
+
+### Encurtando URLs `localhost`
+
+HTTPie fornece suporte a atalhos para o localhost, similares aos do `curl`. Por exemplo, ":3000"
+expande para "http://localhost:3000". Se a porta for omitida, o padrão será a porta 80.
+
+```bash
+http :/users # http://localhost/users
+http :5000/rss # http://localhost:5000/rss
+```
+
+### Métodos Opcionais GET e POST
+
+Se você não especificar o método, o HTTPie usará o seguinte:
+
+- GET para requisições sem corpo
+- POST para requisições com corpo
+
+```bash
+http https://api.example.com/tags # GET - Seleciona as tags
+http https://api.example.com/tags title="Tutorial" slug="tutorial" # POST - Cria uma nova tag
+```
+
+## Parâmetros Querystring
+
+Se você adiciona querystrings manualmente no terminal, tente a seguinte sintaxe:
+`param==value`. Isso evita que o shell tente reconhecer o operador & como comando
+e automaticamente escape caracteres especiais nos parâmetros.
+Isso difere dos parâmetros na URL completa, que o HTTPie não modifica.
+
+```bash
+http https://api.example.com/search q==httpie per_page==20
+```
+
+## Enviando Dados
+
+Você pode enviar dados nos mais diversos formatos, como JSON, formulários ou arquivos.
+
+### Enviando JSON
+
+```bash
+http POST https://api.example.com/posts title="Olá" body="Mundo"
+```
+
+### Enviando Formulário
+
+```bash
+http -f POST https://api.example.com/submit name=John email=john@example.com
+```
+
+### Enviando Arquivos
+
+```bash
+http --form POST https://api.example.com/upload file@/caminho/do/arquivo.txt
+```
+
+## Headers e Autenticação
+
+HTTPie permite que você adicione headers e lide com autenticação de uma forma fácil.
+
+### Headers
+
+```bash
+http GET https://api.example.com/posts Authorization:"Bearer Token" User-Agent:"HTTPie"
+```
+
+### Autenticação Básica
+
+```bash
+http -a usuario:senha GET https://api.example.com/protected
+```
+
+### Autenticação Bearer
+
+```bash
+https -A bearer -a token https://api.example.com/admin
+```
+
+## Lidando com Respostas
+
+HTTPie fornece várias opções para lidar com respostas.
+
+```bash
+http GET https://api.example.com/data Accept:application/json # Exibe o JSON de uma forma legível
+
+http GET https://api.example.com/image --output image.png # Grava a resposta em um arquivo
+
+http --follow GET https://example.com # Segue redirecionamentos
+```
+
+## Leitura Adicional
+
+- [Documentação Oficial](https://httpie.io/docs/cli).
+- [GitHub](https://github.com/httpie).
diff --git a/pt-br/make-pt.html.markdown b/pt-br/make-pt.html.markdown
index 40ac733a..d908435a 100644
--- a/pt-br/make-pt.html.markdown
+++ b/pt-br/make-pt.html.markdown
@@ -1,245 +1,245 @@
----
-category: tool
-tool: make
-contributors:
- - ["Robert Steed", "https://github.com/robochat"]
- - ["Stephan Fuhrmann", "https://github.com/sfuhrm"]
-translators:
- - ["Rogério Gomes Rio", "https://github.com/rogerlista"]
-filename: Makefile-pt
-
-lang: pt-br
----
-
-Um Makefile define um gráfico de regras para criar um alvo (ou alvos). Sua finalidade é fazer o mínimo de trabalho necessário para atualizar um alvo para a versão mais recente da fonte. Famosamente escrito ao longo de um fim de semana por Stuart Feldman em 1976, ainda é amplamente usada (particularmente no Unix e no Linux) apesar de muitos concorrentes e críticas.
-
-Existem muitas variedades de make na existência, no entanto, este artigo pressupõe que estamos usando o GNU make, que é o padrão no Linux.
-
-```make
-
-# Comentários podem ser escritos assim.
-
-# O arquivo deve ser nomeado Makefile e então pode ser executado como `make <alvo>`.
-# Caso contrário, nós usamos `make -f "nome-do-arquivo" <alvo>`.
-
-# Aviso - use somente TABS para identar em Makefiles, nunca espaços!
-
-#-----------------------------------------------------------------------
-# Noções básicas
-#-----------------------------------------------------------------------
-
-# Regras são do formato
-# alvo: <pré-requisito>
-# onde os pré-requisitos são opcionais.
-
-# Uma regra - esta regra só será executada se o arquivo0.txt não existir.
-arquivo0.txt:
- echo "foo" > arquivo0.txt
- # Mesmo os comentários nestas seções da 'receita' são passados ​​para o shell.
- # Experimentar `make arquivo0.txt` or simplyou simplesmente `make` - primeira regra é o padrão.
-
-# Esta regra só será executada se arquivo0.txt for mais recente que arquivo1.txt.
-arquivo1.txt: arquivo0.txt
- cat arquivo0.txt > arquivo1.txt
- # se as mesmas regras de citação do shell.
- @cat arquivo0.txt >> arquivo1.txt
- # @ pára o comando de ser ecoado para stdout.
- -@echo 'hello'
- # - significa que make continuará em caso de erro.
- # Experimentar `make arquivo1.txt` na linha de comando.
-
-# Uma regra pode ter vários alvos e vários pré-requisitos
-arquivo2.txt arquivo3.txt: arquivo0.txt arquivo1.txt
- touch arquivo2.txt
- touch arquivo3.txt
-
-# Make vai reclamar sobre várias receitas para a mesma regra. Esvaziar
-# receitas não contam e podem ser usadas para adicionar novas dependências.
-
-#-----------------------------------------------------------------------
-# Alvos falsos
-#-----------------------------------------------------------------------
-
-# Um alvo falso. Qualquer alvo que não seja um arquivo.
-# Ele nunca será atualizado, portanto, o make sempre tentará executá-lo.
-all: maker process
-
-# Podemos declarar as coisas fora de ordem.
-maker:
- touch ex0.txt ex1.txt
-
-# Pode evitar quebrar regras falsas quando um arquivo real tem o mesmo nome
-.PHONY: all maker process
-# Este é um alvo especial. Existem vários outros.
-
-# Uma regra com dependência de um alvo falso sempre será executada
-ex0.txt ex1.txt: maker
-
-# Alvos falsos comuns são: todos fazem instalação limpa ...
-
-#-----------------------------------------------------------------------
-# Variáveis ​​Automáticas e Curingas
-#-----------------------------------------------------------------------
-
-process: Arquivo*.txt # Usando um curinga para corresponder nomes de arquivos
- @echo $^ # $^ é uma variável que contém a lista de pré-requisitos
- @echo $@ # imprime o nome do alvo
- #(fpara várias regras alvo, $@ é o que causou a execução da regra)
- @echo $< # o primeiro pré-requisito listado
- @echo $? # somente as dependências que estão desatualizadas
- @echo $+ # todas as dependências, incluindo duplicadas (ao contrário do normal)
- #@echo $| # todos os pré-requisitos 'somente pedidos'
-
-# Mesmo se dividirmos as definições de dependência de regra, $^ vai encontrá-los
-process: ex1.txt arquivo0.txt
-# ex1.txt será encontrado, mas arquivo0.txt será desduplicado.
-
-#-----------------------------------------------------------------------
-# Padrões
-#-----------------------------------------------------------------------
-
-# Pode ensinar make a converter certos arquivos em outros arquivos.
-
-%.png: %.svg
- inkscape --export-png $^
-
-# As regras padrões só farão qualquer coisa se decidirem criar o alvo.
-
-# Os caminhos de diretório são normalmente ignorados quando as regras de
-# padrões são correspondentes. Mas make tentará usar a regra mais
-# apropriada disponível.
-small/%.png: %.svg
- inkscape --export-png --export-dpi 30 $^
-
-# make utilizará a última versão para uma regra de padrão que encontrar.
-%.png: %.svg
- @echo esta regra é escolhida
-
-# No entanto, o make usará a primeira regra padrão que pode se tornar o alvo
-%.png: %.ps
- @echo esta regra não é escolhida se *.svg and *.ps estão ambos presentes
-
-# make já tem algumas regras padrões embutidas. Por exemplo, ele sabe
-# como transformar arquivos *.c em arquivos *.o.
-
-# Makefiles antigos podem usar regras de sufixo em vez de regras padrões
-.png.ps:
- @echo essa regra é semelhante a uma regra de padrão.
-
-# make sobre a regra de sufixo
-.SUFFIXES: .png
-
-#-----------------------------------------------------------------------
-# Variáveis
-#-----------------------------------------------------------------------
-# aka. macros
-
-# As variáveis ​​são basicamente todos os tipos de string
-
-name = Ted
-name2="Sarah"
-
-echo:
- @echo $(name)
- @echo ${name2}
- @echo $name # Isso não funcionará, tratado como $ (n)ame.
- @echo $(name3) # Variáveis ​​desconhecidas são tratadas como strings vazias.
-
-# Existem 4 lugares para definir variáveis.
-# Em ordem de prioridade, do maior para o menor:
-# 1: argumentos de linha de comando
-# 2: Makefile
-# 3: variáveis ​​de ambiente do shell - faça importações automaticamente.
-# 4: make tem algumas variáveis ​​predefinidas
-
-name4 ?= Jean
-# Somente defina a variável se a variável de ambiente ainda não estiver definida.
-
-override name5 = David
-# Pára os argumentos da linha de comando de alterar essa variável.
-
-name4 +=grey
-# Anexar valores à variável (inclui um espaço).
-
-# Valores variáveis ​​específicos de padrões (extensão GNU).
-echo: name2 = Sara # Verdadeiro dentro da regra de correspondência
- # e também dentro de suas recursivas dependências
- # (exceto que ele pode quebrar quando seu gráfico ficar muito complicado!)
-
-# Algumas variáveis ​​definidas automaticamente pelo make
-echo_inbuilt:
- echo $(CC)
- echo ${CXX}
- echo $(FC)
- echo ${CFLAGS}
- echo $(CPPFLAGS)
- echo ${CXXFLAGS}
- echo $(LDFLAGS)
- echo ${LDLIBS}
-
-#-----------------------------------------------------------------------
-# Variáveis 2
-#-----------------------------------------------------------------------
-
-# O primeiro tipo de variáveis ​​é avaliado a cada vez que elas são usadas.
-# TIsso pode ser caro, então existe um segundo tipo de variável que é
-# avaliado apenas uma vez. (Esta é uma extensão do GNU make)
-
-var := hello
-var2 ::= $(var) hello
-#:= e ::= são equivalentes.
-
-# Essas variáveis ​​são avaliadas procedimentalmente (na ordem em que
-# aparecem), quebrando assim o resto da línguagem!
-
-# Isso não funciona
-var3 ::= $(var4) and good luck
-var4 ::= good night
-
-#-----------------------------------------------------------------------
-# Funções
-#-----------------------------------------------------------------------
-
-# make tem muitas funções disponíveis.
-
-sourcefiles = $(wildcard *.c */*.c)
-objectfiles = $(patsubst %.c,%.o,$(sourcefiles))
-
-# O formato é $(func arg0,arg1,arg2...)
-
-# Alguns exemplos
-ls: * src/*
- @echo $(filter %.txt, $^)
- @echo $(notdir $^)
- @echo $(join $(dir $^),$(notdir $^))
-
-#-----------------------------------------------------------------------
-# Diretivas
-#-----------------------------------------------------------------------
-
-# Inclua outros makefiles, úteis para código específico da plataforma
-include foo.mk
-
-sport = tennis
-# Compilação condicional
-report:
-ifeq ($(sport),tennis)
- @echo 'game, set, match'
-else
- @echo "They think it's all over; it is now"
-endif
-
-# Há também ifneq, ifdef, ifndef
-
-foo = true
-
-ifdef $(foo)
-bar = 'hello'
-endif
-```
-
-### More Resources
-
-+ [documentação gnu make](https://www.gnu.org/software/make/manual/)
-+ [tutorial de carpintaria de software](http://swcarpentry.github.io/make-novice/)
-+ aprenda C da maneira mais difícil [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)
+---
+category: tool
+tool: make
+contributors:
+ - ["Robert Steed", "https://github.com/robochat"]
+ - ["Stephan Fuhrmann", "https://github.com/sfuhrm"]
+translators:
+ - ["Rogério Gomes Rio", "https://github.com/rogerlista"]
+filename: Makefile-pt
+
+lang: pt-br
+---
+
+Um Makefile define um gráfico de regras para criar um alvo (ou alvos). Sua finalidade é fazer o mínimo de trabalho necessário para atualizar um alvo para a versão mais recente da fonte. Famosamente escrito ao longo de um fim de semana por Stuart Feldman em 1976, ainda é amplamente usada (particularmente no Unix e no Linux) apesar de muitos concorrentes e críticas.
+
+Existem muitas variedades de make na existência, no entanto, este artigo pressupõe que estamos usando o GNU make, que é o padrão no Linux.
+
+```make
+
+# Comentários podem ser escritos assim.
+
+# O arquivo deve ser nomeado Makefile e então pode ser executado como `make <alvo>`.
+# Caso contrário, nós usamos `make -f "nome-do-arquivo" <alvo>`.
+
+# Aviso - use somente TABS para identar em Makefiles, nunca espaços!
+
+#-----------------------------------------------------------------------
+# Noções básicas
+#-----------------------------------------------------------------------
+
+# Regras são do formato
+# alvo: <pré-requisito>
+# onde os pré-requisitos são opcionais.
+
+# Uma regra - esta regra só será executada se o arquivo0.txt não existir.
+arquivo0.txt:
+ echo "foo" > arquivo0.txt
+ # Mesmo os comentários nestas seções da 'receita' são passados ​​para o shell.
+ # Experimentar `make arquivo0.txt` or simplyou simplesmente `make` - primeira regra é o padrão.
+
+# Esta regra só será executada se arquivo0.txt for mais recente que arquivo1.txt.
+arquivo1.txt: arquivo0.txt
+ cat arquivo0.txt > arquivo1.txt
+ # se as mesmas regras de citação do shell.
+ @cat arquivo0.txt >> arquivo1.txt
+ # @ pára o comando de ser ecoado para stdout.
+ -@echo 'hello'
+ # - significa que make continuará em caso de erro.
+ # Experimentar `make arquivo1.txt` na linha de comando.
+
+# Uma regra pode ter vários alvos e vários pré-requisitos
+arquivo2.txt arquivo3.txt: arquivo0.txt arquivo1.txt
+ touch arquivo2.txt
+ touch arquivo3.txt
+
+# Make vai reclamar sobre várias receitas para a mesma regra. Esvaziar
+# receitas não contam e podem ser usadas para adicionar novas dependências.
+
+#-----------------------------------------------------------------------
+# Alvos falsos
+#-----------------------------------------------------------------------
+
+# Um alvo falso. Qualquer alvo que não seja um arquivo.
+# Ele nunca será atualizado, portanto, o make sempre tentará executá-lo.
+all: maker process
+
+# Podemos declarar as coisas fora de ordem.
+maker:
+ touch ex0.txt ex1.txt
+
+# Pode evitar quebrar regras falsas quando um arquivo real tem o mesmo nome
+.PHONY: all maker process
+# Este é um alvo especial. Existem vários outros.
+
+# Uma regra com dependência de um alvo falso sempre será executada
+ex0.txt ex1.txt: maker
+
+# Alvos falsos comuns são: todos fazem instalação limpa ...
+
+#-----------------------------------------------------------------------
+# Variáveis ​​Automáticas e Curingas
+#-----------------------------------------------------------------------
+
+process: Arquivo*.txt # Usando um curinga para corresponder nomes de arquivos
+ @echo $^ # $^ é uma variável que contém a lista de pré-requisitos
+ @echo $@ # imprime o nome do alvo
+ #(fpara várias regras alvo, $@ é o que causou a execução da regra)
+ @echo $< # o primeiro pré-requisito listado
+ @echo $? # somente as dependências que estão desatualizadas
+ @echo $+ # todas as dependências, incluindo duplicadas (ao contrário do normal)
+ #@echo $| # todos os pré-requisitos 'somente pedidos'
+
+# Mesmo se dividirmos as definições de dependência de regra, $^ vai encontrá-los
+process: ex1.txt arquivo0.txt
+# ex1.txt será encontrado, mas arquivo0.txt será desduplicado.
+
+#-----------------------------------------------------------------------
+# Padrões
+#-----------------------------------------------------------------------
+
+# Pode ensinar make a converter certos arquivos em outros arquivos.
+
+%.png: %.svg
+ inkscape --export-png $^
+
+# As regras padrões só farão qualquer coisa se decidirem criar o alvo.
+
+# Os caminhos de diretório são normalmente ignorados quando as regras de
+# padrões são correspondentes. Mas make tentará usar a regra mais
+# apropriada disponível.
+small/%.png: %.svg
+ inkscape --export-png --export-dpi 30 $^
+
+# make utilizará a última versão para uma regra de padrão que encontrar.
+%.png: %.svg
+ @echo esta regra é escolhida
+
+# No entanto, o make usará a primeira regra padrão que pode se tornar o alvo
+%.png: %.ps
+ @echo esta regra não é escolhida se *.svg and *.ps estão ambos presentes
+
+# make já tem algumas regras padrões embutidas. Por exemplo, ele sabe
+# como transformar arquivos *.c em arquivos *.o.
+
+# Makefiles antigos podem usar regras de sufixo em vez de regras padrões
+.png.ps:
+ @echo essa regra é semelhante a uma regra de padrão.
+
+# make sobre a regra de sufixo
+.SUFFIXES: .png
+
+#-----------------------------------------------------------------------
+# Variáveis
+#-----------------------------------------------------------------------
+# aka. macros
+
+# As variáveis ​​são basicamente todos os tipos de string
+
+name = Ted
+name2="Sarah"
+
+echo:
+ @echo $(name)
+ @echo ${name2}
+ @echo $name # Isso não funcionará, tratado como $ (n)ame.
+ @echo $(name3) # Variáveis ​​desconhecidas são tratadas como strings vazias.
+
+# Existem 4 lugares para definir variáveis.
+# Em ordem de prioridade, do maior para o menor:
+# 1: argumentos de linha de comando
+# 2: Makefile
+# 3: variáveis ​​de ambiente do shell - faça importações automaticamente.
+# 4: make tem algumas variáveis ​​predefinidas
+
+name4 ?= Jean
+# Somente defina a variável se a variável de ambiente ainda não estiver definida.
+
+override name5 = David
+# Pára os argumentos da linha de comando de alterar essa variável.
+
+name4 +=grey
+# Anexar valores à variável (inclui um espaço).
+
+# Valores variáveis ​​específicos de padrões (extensão GNU).
+echo: name2 = Sara # Verdadeiro dentro da regra de correspondência
+ # e também dentro de suas recursivas dependências
+ # (exceto que ele pode quebrar quando seu gráfico ficar muito complicado!)
+
+# Algumas variáveis ​​definidas automaticamente pelo make
+echo_inbuilt:
+ echo $(CC)
+ echo ${CXX}
+ echo $(FC)
+ echo ${CFLAGS}
+ echo $(CPPFLAGS)
+ echo ${CXXFLAGS}
+ echo $(LDFLAGS)
+ echo ${LDLIBS}
+
+#-----------------------------------------------------------------------
+# Variáveis 2
+#-----------------------------------------------------------------------
+
+# O primeiro tipo de variáveis ​​é avaliado a cada vez que elas são usadas.
+# TIsso pode ser caro, então existe um segundo tipo de variável que é
+# avaliado apenas uma vez. (Esta é uma extensão do GNU make)
+
+var := hello
+var2 ::= $(var) hello
+#:= e ::= são equivalentes.
+
+# Essas variáveis ​​são avaliadas procedimentalmente (na ordem em que
+# aparecem), quebrando assim o resto da línguagem!
+
+# Isso não funciona
+var3 ::= $(var4) and good luck
+var4 ::= good night
+
+#-----------------------------------------------------------------------
+# Funções
+#-----------------------------------------------------------------------
+
+# make tem muitas funções disponíveis.
+
+sourcefiles = $(wildcard *.c */*.c)
+objectfiles = $(patsubst %.c,%.o,$(sourcefiles))
+
+# O formato é $(func arg0,arg1,arg2...)
+
+# Alguns exemplos
+ls: * src/*
+ @echo $(filter %.txt, $^)
+ @echo $(notdir $^)
+ @echo $(join $(dir $^),$(notdir $^))
+
+#-----------------------------------------------------------------------
+# Diretivas
+#-----------------------------------------------------------------------
+
+# Inclua outros makefiles, úteis para código específico da plataforma
+include foo.mk
+
+sport = tennis
+# Compilação condicional
+report:
+ifeq ($(sport),tennis)
+ @echo 'game, set, match'
+else
+ @echo "They think it's all over; it is now"
+endif
+
+# Há também ifneq, ifdef, ifndef
+
+foo = true
+
+ifdef $(foo)
+bar = 'hello'
+endif
+```
+
+### More Resources
+
++ [documentação gnu make](https://www.gnu.org/software/make/manual/)
++ [tutorial de carpintaria de software](http://swcarpentry.github.io/make-novice/)
++ aprenda C da maneira mais difícil [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)
diff --git a/pt-br/markdown-pt.html.markdown b/pt-br/markdown-pt.html.markdown
index 7960a59a..fca864bb 100644
--- a/pt-br/markdown-pt.html.markdown
+++ b/pt-br/markdown-pt.html.markdown
@@ -8,7 +8,7 @@ translators:
- ["Monique Baptista", "https://github.com/bfmonique"]
- ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"]
-lang: pt-br
+lang: pt-br
filename: learnmarkdown-pt.md
---
@@ -213,8 +213,8 @@ adicionais) para indentação no seu código.
```md
my_array.each do |item|
- puts item
- end
+ puts item
+ end
```
Código embutido pode ser criado usando o caractere de crase `` ` ``.
@@ -225,13 +225,13 @@ John não sabia nem o que a função `go_to()` fazia!
No GitHub Flavored Markdown, você pode usar uma sintaxe especial para código.
-<pre>
-<code class="highlight">&#x60;&#x60;&#x60;ruby
+````md
+```ruby
def foobar
- puts "Olá mundo!"
+ puts "Olá mundo!"
end
-&#x60;&#x60;&#x60;</code></pre>
-
+```
+````
O texto acima não requer indentação, além disso o GitHub vai usar o destaque
de sintaxe da linguagem qeu você especificar após a tag <code>```</code>.
@@ -272,11 +272,13 @@ Caminhos relativos funcionam também.
O Markdown também suporta links para referências no texto.
-<pre><code class="highlight">&#x5b;<span class="nv">Clique nesse link</span>][<span class="ss">link1</span>] para mais informações!
-&#x5b;<span class="nv">Também cheque esse link</span>][<span class="ss">foobar</span>] se você quiser.
+```md
+[Clique nesse link][link1] para mais informações!
+[Também cheque esse link][foobar] se você quiser.
-&#x5b;<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Legal!"</span>
-&#x5b;<span class="nv">link2r</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Certo!"</span></code></pre>
+[link1]: http://test.com/ "Legal!"
+[link2r]: http://foobar.biz/ "Certo!"
+```
O título também pode estar entre aspas simples ou entre parênteses, ou omitido
inteiramente. As referências podem estar em qualquer lugar no documento e os
@@ -285,10 +287,11 @@ IDs de referência podem ser qualquer um, desde que eles sejam únicos.
Existe também a "nomeação implícita", que permite que você use o texto do link
como o id:
-<pre><code class="highlight">&#x5b;<span class="nv">Isso</span>][] é um link.
-
-&#x5b;<span class="nv">Isso</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
+```md
+[Isso][] é um link.
+[Isso]: http://thisisalink.com/
+```
Mas geralmente não são usados.
@@ -322,9 +325,11 @@ exclamação na frente!
E estilo de referência funciona como esperado
-<pre><code class="highlight">!&#x5b;<span class="nv">Esse é o alt-attribute.</span>][<span class="ss">myimage</span>]
+```md
+![Esse é o alt-attribute.][myimage]
-&#x5b;<span class="nv">Minha imagem</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"se precisar de um título, está aqui"</span></code></pre>
+[Minha imagem]: relative/urls/cool/image.jpg "se precisar de um título, está aqui"
+```
## Miscelânea
diff --git a/pt-br/pug-pt.html.markdown b/pt-br/pug-pt.html.markdown
index a74666fb..52eda86a 100644
--- a/pt-br/pug-pt.html.markdown
+++ b/pt-br/pug-pt.html.markdown
@@ -208,4 +208,4 @@ mixin comment(nome, comentario)
### Saiba Mais
- [Site Oficial](https://pugjs.org/)
- [Documentação](https://pugjs.org/api/getting-started.html)
-- [Repositório no Github](https://github.com/pugjs/pug)
+- [Repositório no GitHub](https://github.com/pugjs/pug)
diff --git a/pt-br/pyqt-pt.html.markdown b/pt-br/pyqt-pt.html.markdown
index 40fe82d5..42f744e2 100644
--- a/pt-br/pyqt-pt.html.markdown
+++ b/pt-br/pyqt-pt.html.markdown
@@ -24,7 +24,7 @@ o pyqt!
```python
import sys
from PyQt4 import QtGui
-
+
def window():
# Cria um objeto para a aplicação
app = QtGui.QApplication(sys.argv)
@@ -54,7 +54,7 @@ outros elementos.
Aqui mostraremos como criar uma janela popup, muito útil para perguntar ao
usuário qual decisão tomar ou exibir alguma informação.
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
@@ -73,7 +73,7 @@ def window():
w.setWindowTitle("PyQt Dialog")
w.show()
sys.exit(app.exec_())
-
+
# Essa função deve criar uma janela de diálogo com um botão,
# aguarda ser clicado e encerra o programa
def showdialog():
diff --git a/pt-br/self-pt.html.markdown b/pt-br/self-pt.html.markdown
index eb821474..0fadf58d 100644
--- a/pt-br/self-pt.html.markdown
+++ b/pt-br/self-pt.html.markdown
@@ -117,6 +117,7 @@ Múltiplas expressões são separadas por ponto final. ^ retorna imediatamente.
```
Blocos são realizados (completados) ao enviá-los a mensagem 'value' e herdando (imcumbir a) seus contextos:
+
```
"retorna 0"
[|x|
diff --git a/pt-br/stylus-pt.html.markdown b/pt-br/stylus-pt.html.markdown
index 40c3c02c..40c3c02c 100755..100644
--- a/pt-br/stylus-pt.html.markdown
+++ b/pt-br/stylus-pt.html.markdown
diff --git a/pt-br/visualbasic-pt.html.markdown b/pt-br/visualbasic-pt.html.markdown
index 81292798..dcc72c04 100644
--- a/pt-br/visualbasic-pt.html.markdown
+++ b/pt-br/visualbasic-pt.html.markdown
@@ -8,7 +8,7 @@ lang: pt-br
filename: learnvisualbasic-pt.vb
---
-```
+```visualbasic
Module Module1
module Module1
diff --git a/pt-pt/swift-pt.html.markdown b/pt-pt/swift-pt.html.markdown
index a8d3e1ab..aba1994a 100644
--- a/pt-pt/swift-pt.html.markdown
+++ b/pt-pt/swift-pt.html.markdown
@@ -16,7 +16,7 @@ Swift é uma linguagem de programação criada pela Apple para o desenvolvimento
Desenhada de forma a coexistir com Objective-C e ser mais resiliente contra código errôneo, a linguagem Swift foi introduzida em 2014 na conferência para desenvolvedores WWDC da Apple.
Swift usa o compilador LLVM incluido no XCode 6+.
-O livro oficial [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) da Apple está agora disponivel via iBooks.
+O livro oficial [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) da Apple está agora disponivel via Apple Books.
Consulta também o [guia de iniciação](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/) da Apple, que contêm um tutorial completo em Swift.
diff --git a/pug.html.markdown b/pug.html.markdown
index 9badee92..21d8db9f 100644
--- a/pug.html.markdown
+++ b/pug.html.markdown
@@ -205,4 +205,4 @@ mixin comment(name, comment)
### Additional Resources
- [The Site](https://pugjs.org/)
- [The Docs](https://pugjs.org/api/getting-started.html)
-- [Github Repo](https://github.com/pugjs/pug)
+- [GitHub Repo](https://github.com/pugjs/pug)
diff --git a/pyqt.html.markdown b/pyqt.html.markdown
index 6bdb6488..2b331874 100644
--- a/pyqt.html.markdown
+++ b/pyqt.html.markdown
@@ -11,25 +11,25 @@ contributors:
This is an adaption on the C++ intro to QT by [Aleksey Kholovchuk](https://github.com/vortexxx192
), some of the code examples should result in the same functionality
-this version just having been done using pyqt!
+this version just having been done using pyqt!
```python
import sys
from PyQt4 import QtGui
-
+
def window():
- # Create an application object
+ # Create an application object
app = QtGui.QApplication(sys.argv)
# Create a widget where our label will be placed in
w = QtGui.QWidget()
- # Add a label to the widget
+ # Add a label to the widget
b = QtGui.QLabel(w)
- # Set some text for the label
+ # Set some text for the label
b.setText("Hello World!")
- # Give some size and placement information
+ # Give some size and placement information
w.setGeometry(100, 100, 200, 50)
b.move(50, 20)
- # Give our window a nice title
+ # Give our window a nice title
w.setWindowTitle("PyQt")
# Have everything display
w.show()
@@ -41,10 +41,10 @@ if __name__ == '__main__':
```
-In order to get some of the more advanced features in **pyqt** we need to start looking at building additional elements.
+In order to get some of the more advanced features in **pyqt** we need to start looking at building additional elements.
Here we show how to introduce a dialog popup box, useful for asking the user to confirm a decision or to provide information.
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
@@ -63,7 +63,7 @@ def window():
w.setWindowTitle("PyQt Dialog")
w.show()
sys.exit(app.exec_())
-
+
# This function should create a dialog window with a button
# that waits to be clicked and then exits the program
def showdialog():
diff --git a/python.html.markdown b/python.html.markdown
index d863bcc3..9d97e64d 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -501,20 +501,20 @@ with open("myfile.txt") as f:
# Writing to a file
contents = {"aa": 12, "bb": 21}
-with open("myfile1.txt", "w+") as file:
+with open("myfile1.txt", "w") as file:
file.write(str(contents)) # writes a string to a file
import json
-with open("myfile2.txt", "w+") as file:
+with open("myfile2.txt", "w") as file:
file.write(json.dumps(contents)) # writes an object to a file
# Reading from a file
-with open('myfile1.txt', "r+") as file:
+with open('myfile1.txt', "r") as file:
contents = file.read() # reads a string from a file
print(contents)
# print: {"aa": 12, "bb": 21}
-with open('myfile2.txt', "r+") as file:
+with open('myfile2.txt', "r") as file:
contents = json.load(file) # reads a json object from a file
print(contents)
# print: {"aa": 12, "bb": 21}
diff --git a/qsharp.html.markdown b/qsharp.html.markdown
index 10015d7f..04e697a4 100644
--- a/qsharp.html.markdown
+++ b/qsharp.html.markdown
@@ -9,7 +9,7 @@ filename: LearnQSharp.qs
Q# is a high-level domain-specific language which enables developers to write quantum algorithms. Q# programs can be executed on a quantum simulator running on a classical computer and (in future) on quantum computers.
-```C#
+```c#
// Single-line comments start with //
diff --git a/ro-ro/elixir-ro.html.markdown b/ro-ro/elixir-ro.html.markdown
index 10fec3c5..60500d64 100644
--- a/ro-ro/elixir-ro.html.markdown
+++ b/ro-ro/elixir-ro.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
@@ -22,7 +22,7 @@ posibilități.
# Pentru comentarii pe mai multe linii nu există sintaxă separată,
# de aceea folosiți mai multe linii cu comentarii.
-# Pentru a folosi shell-ul elixir utilizați comanda `iex`.
+# Pentru a folosi shell-ul Elixir utilizați comanda `iex`.
# Compilați modulele cu comanda `elixirc`.
# Ambele comenzi vor lucra în terminal, dacă ați instalat Elixir corect.
diff --git a/rst.html.markdown b/rst.html.markdown
index 8a730c7a..c68c1d54 100644
--- a/rst.html.markdown
+++ b/rst.html.markdown
@@ -84,11 +84,11 @@ More complex tables can be done easily (merged columns and/or rows) but I sugges
There are multiple ways to make links:
-- By adding an underscore after a word : Github_ and by adding the target URL after the text (this way has the advantage of not inserting unnecessary URLs in the visible text).
+- By adding an underscore after a word : GitHub_ and by adding the target URL after the text (this way has the advantage of not inserting unnecessary URLs in the visible text).
- By typing a full comprehensible URL : https://github.com/ (will be automatically converted to a link).
-- By making a more Markdown-like link: `Github <https://github.com/>`_ .
+- By making a more Markdown-like link: `GitHub <https://github.com/>`_ .
-.. _Github: https://github.com/
+.. _GitHub: https://github.com/
```
diff --git a/ru-ru/asymptotic-notation-ru.html.markdown b/ru-ru/asymptotic-notation-ru.html.markdown
index 7fd02c47..02ebd205 100644
--- a/ru-ru/asymptotic-notation-ru.html.markdown
+++ b/ru-ru/asymptotic-notation-ru.html.markdown
@@ -1,225 +1,225 @@
----
-category: Algorithms & Data Structures
-name: Asymptotic Notation
-contributors:
- - ["Jake Prather", "http://github.com/JakeHP"]
- - ["Divay Prakash", "http://github.com/divayprakash"]
-translators:
- - ["pru-mike", "http://github.com/pru-mike"]
-lang: ru-ru
----
-
-# О-символика
-
-## Что это такое?
-
-О-символика, или асимптотическая запись, — это система символов, позволяющая
-оценить время выполнения алгоритма, устанавливая зависимость времени выполнения
-от увеличения объёма входных данных. Она также известна как оценка
-сложности алгоритмов. Станет ли алгоритм невероятно медленным, когда
-объём входных данных увеличится? Будет ли алгоритм выполняться достаточно быстро,
-если объём входных данных возрастёт? О-символика позволяет ответить на эти
-вопросы.
-
-## Можно ли по-другому найти ответы на эти вопросы?
-
-Один способ — это подсчитать число элементарных операций в зависимости от
-различных объёмов входных данных. Хотя это и приемлемое решение, тот объём
-работы, которого оно потребует, даже для простых алгоритмов делает его
-использование неоправданным.
-
-Другой способ — это измерить, какое время алгоритм потребует для завершения на
-различных объёмах входных данных. В то же время, точность и относительность
-этого метода (полученное время будет относиться только к той машине, на которой
-оно вычислено) зависит от среды выполнения: компьютерного аппаратного
-обеспечения, мощности процессора и т.д.
-
-## Виды О-символики
-
-В первом разделе этого документа мы определили, что О-символика
-позволяет оценивать алгоритмы в зависимости от изменения размера входных
-данных. Представим, что алгоритм — это функция f, n — размер входных данных и
-f(n) — время выполнения. Тогда для данного алгоритма f с размером входных
-данных n получим какое-то результирующее время выполнения f(n).
-Из этого можно построить график, где ось y — время выполнения, ось x — размер входных
-данных, а точки на графике — это время выполнения для заданного размера входных
-данных.
-
-С помощью О-символики можно оценить функцию или алгоритм
-несколькими различными способами. Например, можно оценить алгоритм исходя
-из нижней оценки, верхней оценки, тождественной оценки. Чаще всего встречается
-анализ на основе верхней оценки. Как правило не используется нижняя оценка,
-потому что она не подходит под планируемые условия. Отличный пример — алгоритмы
-сортировки, особенно добавление элементов в древовидную структуру. Нижняя оценка
-большинства таких алгоритмов может быть дана как одна операция. В то время как в
-большинстве случаев добавляемые элементы должны быть отсортированы
-соответствующим образом при помощи дерева, что может потребовать обхода целой
-ветви. Это и есть худший случай, для которого планируется верхняя оценка.
-
-### Виды функций, пределы и упрощения
-
-```
-Логарифмическая функция — log n
-Линейная функция — an + b
-Квадратичная функция — an^2 + bn +c
-Степенная функция — an^z + . . . + an^2 + a*n^1 + a*n^0, где z — константа
-Показательная функция — a^n, где a — константа
-```
-
-Приведены несколько базовых функций, используемых при определении сложности в
-различных оценках. Список начинается с самой медленно возрастающей функции
-(логарифм, наиболее быстрое время выполнения) и следует до самой быстро
-возрастающей функции (экспонента, самое медленное время выполнения). Отметим,
-что в то время, как «n», или размер входных данных, возрастает в каждой из этих функций,
-результат намного быстрее возрастает в квадратичной, степенной
-и показательной по сравнению с логарифмической и линейной.
-
-Крайне важно понимать, что при использовании описанной далее нотации необходимо
-использовать упрощённые выражения.
-Это означает, что необходимо отбрасывать константы и слагаемые младших порядков,
-потому что если размер входных данных (n в функции f(n) нашего примера)
-увеличивается до бесконечности (в пределе), тогда слагаемые младших порядков
-и константы становятся пренебрежительно малыми. Таким образом, если есть
-константа, например, размера 2^9001 или любого другого невообразимого размера,
-надо понимать, что её упрощение внесёт значительные искажения в точность
-оценки.
-
-Т.к. нам нужны упрощённые выражения, немного скорректируем нашу таблицу...
-
-```
-Логарифм — log n
-Линейная функция — n
-Квадратичная функция — n^2
-Степенная функция — n^z, где z — константа
-Показательная функция — a^n, где a — константа
-```
-
-### О Большое
-О Большое, записывается как **О**, — это асимптотическая запись для оценки худшего
-случая, или для ограничения заданной функции сверху. Это позволяет сделать
-_**асимптотическую оценку верхней границы**_ скорости роста времени выполнения
-алгоритма. Пусть `f(n)` — время выполнения алгоритма, а `g(n)` — заданная временная
-сложность, которая проверяется для алгоритма. Тогда `f(n)` — это O(g(n)), если
-существуют действительные константы c (c > 0) и n<sub>0</sub>, такие,
-что `f(n)` <= `c g(n)` выполняется для всех n, начиная с некоторого n<sub>0</sub> (n > n<sub>0</sub>).
-
-*Пример 1*
-
-```
-f(n) = 3log n + 100
-g(n) = log n
-```
-
-Является ли `f(n)` O(g(n))?
-Является ли `3 log n + 100` O(log n)?
-Посмотрим на определение О Большого:
-
-```
-3log n + 100 <= c * log n
-```
-
-Существуют ли константы c и n<sub>0</sub>, такие, что выражение верно для всех n > n<sub>0</sub>?
-
-```
-3log n + 100 <= 150 * log n, n > 2 (не определенно для n = 1)
-```
-
-Да! По определению О Большого `f(n)` является O(g(n)).
-
-*Пример 2*
-
-```
-f(n) = 3 * n^2
-g(n) = n
-```
-
-Является ли `f(n)` O(g(n))?
-Является ли `3 * n^2` O(n)?
-Посмотрим на определение О Большого:
-
-```
-3 * n^2 <= c * n
-```
-
-Существуют ли константы c и n<sub>0</sub>, такие, что выражение верно для всех n > n<sub>0</sub>?
-Нет, не существуют. `f(n)` НЕ ЯВЛЯЕТСЯ O(g(n)).
-
-### Омега Большое
-Омега Большое, записывается как **Ω**, — это асимптотическая запись для оценки
-лучшего случая, или для ограничения заданной функции снизу. Это позволяет сделать
-_**асимптотическую оценку нижней границы**_ скорости роста времени выполнения
-алгоритма.
-
-`f(n)` является Ω(g(n)), если существуют действительные константы
-c (c > 0) и n<sub>0</sub> (n<sub>0</sub> > 0), такие, что `f(n)` >= `c g(n)` для всех n > n<sub>0</sub>.
-
-### Примечание
-
-Асимптотические оценки, сделаные при помощи О Большого и Омега Большого, могут
-как являться, так и не являться точными. Для того, чтобы обозначить, что границы не
-являются асимптотически точными, используются записи О Малое и Омега Малое.
-
-### О Малое
-O Малое, записывается как **о**, — это асимптотическая запись для оценки верхней
-границы времени выполнения алгоритма при условии, что граница не является
-асимптотически точной.
-
-`f(n)` является o(g(n)), если можно подобрать такие действительные константы,
-что для всех c (c > 0) найдётся n<sub>0</sub> (n<sub>0</sub> > 0), так
-что `f(n)` < `c g(n)` выполняется для всех n (n > n<sub>0</sub>).
-
-Определения О-символики для О Большого и О Малого похожи. Главное отличие в том,
-что если f(n) = O(g(n)), тогда условие f(n) <= c g(n) выполняется, если _**существует**_
-константа c > 0, но если f(n) = o(g(n)), тогда условие f(n) < c g(n) выполняется
-для _**всех**_ констант c > 0.
-
-### Омега Малое
-Омега Малое, записывается как **ω**, — это асимптотическая запись для оценки
-верхней границы времени выполнения алгоритма при условии, что граница не является
-асимптотически точной.
-
-`f(n)` является ω(g(n)), если можно подобрать такие действительные константы,
-что для всех c (c > 0) найдётся n<sub>0</sub> (n<sub>0</sub> > 0), так
-что `f(n)` > `c g(n)` выполняется для всех n (n > n<sub>0</sub>).
-
-Определения Ω-символики и ω-символики похожи. Главное отличие в том, что
-если f(n) = Ω(g(n)), тогда условие f(n) >= c g(n) выполняется, если _**существует**_
-константа c > 0, но если f(n) = ω(g(n)), тогда условие f(n) > c g(n)
-выполняется для _**всех**_ констант c > 0.
-
-### Тета
-Тета, записывается как **Θ**, — это асимптотическая запись для оценки
-_***асимптотически точной границы***_ времени выполнения алгоритма.
-
-`f(n)` является Θ(g(n)), если для некоторых действительных
-констант c1, c2 и n<sub>0</sub> (c1 > 0, c2 > 0, n<sub>0</sub> > 0)
-`c1 g(n)` < `f(n)` < `c2 g(n)` для всех n (n > n<sub>0</sub>).
-
-∴ `f(n)` является Θ(g(n)) означает, что `f(n)` является O(g(n))
-и `f(n)` является Ω(g(n)).
-
-О Большое — основной инструмент для анализа сложности алгоритмов.
-Также см. примеры по ссылкам.
-
-### Заключение
-Такую тему сложно изложить кратко, поэтому обязательно стоит пройти по ссылкам и
-посмотреть дополнительную литературу. В ней даётся более глубокое описание с
-определениями и примерами.
-
-
-## Дополнительная литература
-
-* [Алгоритмы на Java](https://www.ozon.ru/context/detail/id/18319699/)
-* [Алгоритмы. Построение и анализ](https://www.ozon.ru/context/detail/id/33769775/)
-
-## Ссылки
-
-* [Оценки времени исполнения. Символ O()](http://algolist.manual.ru/misc/o_n.php)
-* [Асимптотический анализ и теория вероятностей](https://www.lektorium.tv/course/22903)
-
-## Ссылки (англ.)
-
-* [Algorithms, Part I](https://www.coursera.org/learn/algorithms-part1)
-* [Cheatsheet 1](http://web.mit.edu/broder/Public/asymptotics-cheatsheet.pdf)
-* [Cheatsheet 2](http://bigocheatsheet.com/)
-
+---
+category: Algorithms & Data Structures
+name: Asymptotic Notation
+contributors:
+ - ["Jake Prather", "http://github.com/JakeHP"]
+ - ["Divay Prakash", "http://github.com/divayprakash"]
+translators:
+ - ["pru-mike", "http://github.com/pru-mike"]
+lang: ru-ru
+---
+
+# О-символика
+
+## Что это такое?
+
+О-символика, или асимптотическая запись, — это система символов, позволяющая
+оценить время выполнения алгоритма, устанавливая зависимость времени выполнения
+от увеличения объёма входных данных. Она также известна как оценка
+сложности алгоритмов. Станет ли алгоритм невероятно медленным, когда
+объём входных данных увеличится? Будет ли алгоритм выполняться достаточно быстро,
+если объём входных данных возрастёт? О-символика позволяет ответить на эти
+вопросы.
+
+## Можно ли по-другому найти ответы на эти вопросы?
+
+Один способ — это подсчитать число элементарных операций в зависимости от
+различных объёмов входных данных. Хотя это и приемлемое решение, тот объём
+работы, которого оно потребует, даже для простых алгоритмов делает его
+использование неоправданным.
+
+Другой способ — это измерить, какое время алгоритм потребует для завершения на
+различных объёмах входных данных. В то же время, точность и относительность
+этого метода (полученное время будет относиться только к той машине, на которой
+оно вычислено) зависит от среды выполнения: компьютерного аппаратного
+обеспечения, мощности процессора и т.д.
+
+## Виды О-символики
+
+В первом разделе этого документа мы определили, что О-символика
+позволяет оценивать алгоритмы в зависимости от изменения размера входных
+данных. Представим, что алгоритм — это функция f, n — размер входных данных и
+f(n) — время выполнения. Тогда для данного алгоритма f с размером входных
+данных n получим какое-то результирующее время выполнения f(n).
+Из этого можно построить график, где ось y — время выполнения, ось x — размер входных
+данных, а точки на графике — это время выполнения для заданного размера входных
+данных.
+
+С помощью О-символики можно оценить функцию или алгоритм
+несколькими различными способами. Например, можно оценить алгоритм исходя
+из нижней оценки, верхней оценки, тождественной оценки. Чаще всего встречается
+анализ на основе верхней оценки. Как правило, не используется нижняя оценка,
+потому что она не подходит под планируемые условия. Отличный пример — алгоритмы
+сортировки, особенно добавление элементов в древовидную структуру. Нижняя оценка
+большинства таких алгоритмов может быть дана как одна операция. В то время как в
+большинстве случаев добавляемые элементы должны быть отсортированы
+соответствующим образом при помощи дерева, что может потребовать обхода целой
+ветви. Это и есть худший случай, для которого планируется верхняя оценка.
+
+### Виды функций, пределы и упрощения
+
+```
+Логарифмическая функция — log n
+Линейная функция — an + b
+Квадратичная функция — an^2 + bn +c
+Степенная функция — an^z + . . . + an^2 + a*n^1 + a*n^0, где z — константа
+Показательная функция — a^n, где a — константа
+```
+
+Приведены несколько базовых функций, используемых при определении сложности в
+различных оценках. Список начинается с самой медленно возрастающей функции
+(логарифм, наиболее быстрое время выполнения) и следует до самой быстро
+возрастающей функции (экспонента, самое медленное время выполнения). Отметим,
+что в то время, как «n», или размер входных данных, возрастает в каждой из этих функций,
+результат намного быстрее возрастает в квадратичной, степенной
+и показательной по сравнению с логарифмической и линейной.
+
+Крайне важно понимать, что при использовании описанной далее нотации необходимо
+использовать упрощённые выражения.
+Это означает, что необходимо отбрасывать константы и слагаемые младших порядков,
+потому что если размер входных данных (n в функции f(n) нашего примера)
+увеличивается до бесконечности (в пределе), тогда слагаемые младших порядков
+и константы становятся пренебрежительно малыми. Таким образом, если есть
+константа, например, размера 2^9001 или любого другого невообразимого размера,
+надо понимать, что её упрощение внесёт значительные искажения в точность
+оценки.
+
+Т.к. нам нужны упрощённые выражения, немного скорректируем нашу таблицу...
+
+```
+Логарифм — log n
+Линейная функция — n
+Квадратичная функция — n^2
+Степенная функция — n^z, где z — константа
+Показательная функция — a^n, где a — константа
+```
+
+### О Большое
+О Большое, записывается как **О**, — это асимптотическая запись для оценки худшего
+случая, или для ограничения заданной функции сверху. Это позволяет сделать
+_**асимптотическую оценку верхней границы**_ скорости роста времени выполнения
+алгоритма. Пусть `f(n)` — время выполнения алгоритма, а `g(n)` — заданная временная
+сложность, которая проверяется для алгоритма. Тогда `f(n)` — это O(g(n)), если
+существуют действительные константы c (c > 0) и n<sub>0</sub>, такие,
+что `f(n)` <= `c g(n)` выполняется для всех n, начиная с некоторого n<sub>0</sub> (n > n<sub>0</sub>).
+
+*Пример 1*
+
+```
+f(n) = 3log n + 100
+g(n) = log n
+```
+
+Является ли `f(n)` O(g(n))?
+Является ли `3 log n + 100` O(log n)?
+Посмотрим на определение О Большого:
+
+```
+3log n + 100 <= c * log n
+```
+
+Существуют ли константы c и n<sub>0</sub>, такие, что выражение верно для всех n > n<sub>0</sub>?
+
+```
+3log n + 100 <= 150 * log n, n > 2 (не определенно для n = 1)
+```
+
+Да! По определению О Большого `f(n)` является O(g(n)).
+
+*Пример 2*
+
+```
+f(n) = 3 * n^2
+g(n) = n
+```
+
+Является ли `f(n)` O(g(n))?
+Является ли `3 * n^2` O(n)?
+Посмотрим на определение О Большого:
+
+```
+3 * n^2 <= c * n
+```
+
+Существуют ли константы c и n<sub>0</sub>, такие, что выражение верно для всех n > n<sub>0</sub>?
+Нет, не существуют. `f(n)` НЕ ЯВЛЯЕТСЯ O(g(n)).
+
+### Омега Большое
+Омега Большое, записывается как **Ω**, — это асимптотическая запись для оценки
+лучшего случая, или для ограничения заданной функции снизу. Это позволяет сделать
+_**асимптотическую оценку нижней границы**_ скорости роста времени выполнения
+алгоритма.
+
+`f(n)` является Ω(g(n)), если существуют действительные константы
+c (c > 0) и n<sub>0</sub> (n<sub>0</sub> > 0), такие, что `f(n)` >= `c g(n)` для всех n > n<sub>0</sub>.
+
+### Примечание
+
+Асимптотические оценки, сделанные при помощи О Большого и Омега Большого, могут
+как являться, так и не являться точными. Для того чтобы обозначить, что границы не
+являются асимптотически точными, используются записи О Малое и Омега Малое.
+
+### О Малое
+O Малое, записывается как **о**, — это асимптотическая запись для оценки верхней
+границы времени выполнения алгоритма при условии, что граница не является
+асимптотически точной.
+
+`f(n)` является o(g(n)), если можно подобрать такие действительные константы,
+что для всех c (c > 0) найдётся n<sub>0</sub> (n<sub>0</sub> > 0), так
+что `f(n)` < `c g(n)` выполняется для всех n (n > n<sub>0</sub>).
+
+Определения О-символики для О Большого и О Малого похожи. Главное отличие в том,
+что если f(n) = O(g(n)), тогда условие f(n) <= c g(n) выполняется, если _**существует**_
+константа c > 0, но если f(n) = o(g(n)), тогда условие f(n) < c g(n) выполняется
+для _**всех**_ констант c > 0.
+
+### Омега Малое
+Омега Малое, записывается как **ω**, — это асимптотическая запись для оценки
+верхней границы времени выполнения алгоритма при условии, что граница не является
+асимптотически точной.
+
+`f(n)` является ω(g(n)), если можно подобрать такие действительные константы,
+что для всех c (c > 0) найдётся n<sub>0</sub> (n<sub>0</sub> > 0), так
+что `f(n)` > `c g(n)` выполняется для всех n (n > n<sub>0</sub>).
+
+Определения Ω-символики и ω-символики похожи. Главное отличие в том, что
+если f(n) = Ω(g(n)), тогда условие f(n) >= c g(n) выполняется, если _**существует**_
+константа c > 0, но если f(n) = ω(g(n)), тогда условие f(n) > c g(n)
+выполняется для _**всех**_ констант c > 0.
+
+### Тета
+Тета, записывается как **Θ**, — это асимптотическая запись для оценки
+_***асимптотически точной границы***_ времени выполнения алгоритма.
+
+`f(n)` является Θ(g(n)), если для некоторых действительных
+констант c1, c2 и n<sub>0</sub> (c1 > 0, c2 > 0, n<sub>0</sub> > 0)
+`c1 g(n)` < `f(n)` < `c2 g(n)` для всех n (n > n<sub>0</sub>).
+
+∴ `f(n)` является Θ(g(n)) означает, что `f(n)` является O(g(n))
+и `f(n)` является Ω(g(n)).
+
+О Большое — основной инструмент для анализа сложности алгоритмов.
+Также см. примеры по ссылкам.
+
+### Заключение
+Такую тему сложно изложить кратко, поэтому обязательно стоит пройти по ссылкам и
+посмотреть дополнительную литературу. В ней даётся более глубокое описание с
+определениями и примерами.
+
+
+## Дополнительная литература
+
+* [Алгоритмы на Java](https://www.ozon.ru/context/detail/id/18319699/)
+* [Алгоритмы. Построение и анализ](https://www.ozon.ru/context/detail/id/33769775/)
+
+## Ссылки
+
+* [Оценки времени исполнения. Символ O()](http://algolist.manual.ru/misc/o_n.php)
+* [Асимптотический анализ и теория вероятностей](https://www.lektorium.tv/course/22903)
+
+## Ссылки (англ.)
+
+* [Algorithms, Part I](https://www.coursera.org/learn/algorithms-part1)
+* [Cheatsheet 1](http://web.mit.edu/broder/Public/asymptotics-cheatsheet.pdf)
+* [Cheatsheet 2](http://bigocheatsheet.com/)
+
diff --git a/ru-ru/binary-search-ru.html.markdown b/ru-ru/binary-search-ru.html.markdown
index 9ed62cb8..ab1a1585 100644
--- a/ru-ru/binary-search-ru.html.markdown
+++ b/ru-ru/binary-search-ru.html.markdown
@@ -55,7 +55,7 @@ def search(arr, x):
### На заметку
-Существует и другая форма двоичного поиска, которая можеть быть полезна.
+Существует и другая форма двоичного поиска, которая может быть полезна.
## На почитать
diff --git a/ru-ru/c++-ru.html.markdown b/ru-ru/c++-ru.html.markdown
index fad1b434..43e9e6a3 100644
--- a/ru-ru/c++-ru.html.markdown
+++ b/ru-ru/c++-ru.html.markdown
@@ -17,7 +17,7 @@ C++ - компилируемый, статически типизированн
- "лучшая замена C"
- язык с поддержкой абстракции данных
-- язык с поддержкой объектно-ориентированого программирования
+- язык с поддержкой объектно-ориентированного программирования
- язык с поддержкой обобщенного программирования
Хотя его синтаксис может показаться более трудным или сложным для понимания, чем в более современных языках,
diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown
index eb5de011..a146a76b 100644
--- a/ru-ru/c-ru.html.markdown
+++ b/ru-ru/c-ru.html.markdown
@@ -476,7 +476,7 @@ void str_reverse_through_pointer(char *str_in) {
Если у вас появился вопрос, почитайте [compl.lang.c Frequently Asked Questions](http://c-faq.com).
Очень важно использовать правильные отступы и ставить пробелы в нужных местах.
-Читаемый код лучше чем красивый или быстрый код.
+Читаемый код лучше, чем красивый или быстрый код.
Чтобы научиться писать хороший код, почитайте [Linux kernel coding style](https://www.kernel.org/doc/Documentation/CodingStyle).
Также не забывайте, что [Google](http://google.com) и [Яндекс](http://yandex.ru) – ваши хорошие друзья.
diff --git a/ru-ru/css-ru.html.markdown b/ru-ru/css-ru.html.markdown
index e0e5e30b..b543bfeb 100644
--- a/ru-ru/css-ru.html.markdown
+++ b/ru-ru/css-ru.html.markdown
@@ -20,12 +20,12 @@ HTML элементы и определять их внешний вид.
**ВАЖНО:** Так как результатом применения CSS является изменение внешнего вида
элементов, постарайтесь использовать CSS-песочницы при изучении языка.
-Например [dabblet](http://dabblet.com/).
+Например, [dabblet](http://dabblet.com/).
В данной статье рассматриваются в первую очередь синтаксис и общие рекомендации.
```css
-/* Для комментариев используется слеш-астериск, как на этой строчке.
+/* Для комментариев используется слэш-астериск, как на этой строчке.
В CSS нет однострочных комментариев; все комментарии записываются таким способом */
/* ####################
@@ -104,7 +104,7 @@ div.some-parent.class-name {}
.i-am-any-before ~ .this-element {}
-/* Существуют псевдо-классы, позволяющие изменять внешний вид элемента
+/* Существуют псевдоклассы, позволяющие изменять внешний вид элемента
в зависимости от событий, произошедших с элементом */
/* например, когда курсор наведен на элемент */
diff --git a/ru-ru/elixir-ru.html.markdown b/ru-ru/elixir-ru.html.markdown
index c8c2c060..8dd48ba7 100644
--- a/ru-ru/elixir-ru.html.markdown
+++ b/ru-ru/elixir-ru.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
diff --git a/ru-ru/forth-ru.html.markdown b/ru-ru/forth-ru.html.markdown
index 2fc4ad7c..96fa0941 100644
--- a/ru-ru/forth-ru.html.markdown
+++ b/ru-ru/forth-ru.html.markdown
@@ -10,10 +10,10 @@ lang: ru-ru
Форт создан Чарлзом Муром в 70-е годы. Это императивный, стековый язык программирования и среда исполнения программ. Использовался в таких проектах как Open Firmware. Продолжает применятся в проектах. Применяется в НАСА.
-Внимание: эта материал использует реализацию Форта - Gforth, но большая часть написанного будет работать в других средах.
+Внимание: этот материал использует реализацию Форта - Gforth, но большая часть написанного будет работать в других средах.
-```
+```forth
\ Это комментарий
( Это тоже комментарий, но используется для предоределённых слов )
diff --git a/ru-ru/haml-ru.html.markdown b/ru-ru/haml-ru.html.markdown
index c2f8852e..ed823496 100644
--- a/ru-ru/haml-ru.html.markdown
+++ b/ru-ru/haml-ru.html.markdown
@@ -39,7 +39,7 @@ $ haml input_file.haml output_file.html
/ Комментарии
/ -------------------------------------------
-/ Комментари начинается с символа косой черты.
+/ Комментарии начинается с символа косой черты.
/
Для написания многострочного комментария расположите ваш комментарий
@@ -94,7 +94,7 @@ $ haml input_file.haml output_file.html
/ выведет 'Да &amp; да'
/
- Чтобы выполнять Ruby-код без экранрования, можно использовать
+ Чтобы выполнять Ruby-код без экранирования, можно использовать
"восклицательный знак" и "равно" (!=)
%p
@@ -196,13 +196,13 @@ $ haml input_file.haml output_file.html
/ -------------------------------------------
/
- Фильтры передают связанный блок текста в соотвествующую
+ Фильтры передают связанный блок текста в соответствующую
фильтрующую программу и возвращают результат в Haml
Фильтр обозначается двоеточием и названием фильтра:
/ Markdown filter
:markdown
- # Заголовк
+ # Заголовок
Текст **внутри** *блока*
@@ -221,7 +221,7 @@ $ haml input_file.haml output_file.html
</script>
/
- Существует множество типов фильров (:markdown, :javascript, :coffee,
+ Существует множество типов фильтров (:markdown, :javascript, :coffee,
:css, :ruby и так далее). Вы можете определить собственный фильтр c
помощью Haml::Filters.
diff --git a/ru-ru/haskell-ru.html.markdown b/ru-ru/haskell-ru.html.markdown
index f04c45e2..aada30c1 100644
--- a/ru-ru/haskell-ru.html.markdown
+++ b/ru-ru/haskell-ru.html.markdown
@@ -8,7 +8,7 @@ translators:
lang: ru-ru
---
-Haskell разрабатывался, как чистый функциональный язык программирования, применимый на практике. Язык известен благодаря своей системе типов, и "знаменит" благодаря монадам. [Меня][autor] же Haskell заставляет возвращаться к себе снова и снова именно своей элегантностью и [я][autor] получаю истинное удовольствие, программируя на Haskell.
+Haskell разрабатывался, как чистый функциональный язык программирования, применимый на практике. Язык известен благодаря своей системе типов, и "знаменит" благодаря монадам. [Меня][author] же Haskell заставляет возвращаться к себе снова и снова именно своей элегантностью и [я][author] получаю истинное удовольствие, программируя на Haskell.
```haskell
-- Однострочные комментарии начинаются с двух дефисов
@@ -544,4 +544,4 @@ Haskell прост в установке, забирайте [здесь](http:/
[Learn you a Haskell](http://learnyouahaskell.com/) и
[Real World Haskell](http://book.realworldhaskell.org/).
-[autor]: http://adit.io имеется в виду автор оригинального текста Adit Bhargava *(примечание переводчика)*
+[author]: http://adit.io имеется в виду автор оригинального текста Adit Bhargava *(примечание переводчика)*
diff --git a/ru-ru/html-ru.html.markdown b/ru-ru/html-ru.html.markdown
index 120981b9..e18fb8a0 100644
--- a/ru-ru/html-ru.html.markdown
+++ b/ru-ru/html-ru.html.markdown
@@ -8,28 +8,28 @@ translators:
lang: ru-ru
---
-HTML расшифровывается как Hypertext Markup Language(гипертекстовый язык разметки).
-Это язык используют для написания страниц для World Wide Web(всемирной паутины).
-Это язык разметки позволяет писать веб-страниц с помощью кода, чтобы определять,
-как должны быть отображены текст и данные.
+HTML расшифровывается как Hypertext Markup Language (гипертекстовый язык разметки).
+Этот язык используют для написания страниц для World Wide Web (всемирной паутины).
+Этот язык разметки позволяет описать веб-страницу с помощью кода, чтобы определить,
+как на ней должны быть отображены текст и данные.
На самом деле, HTML файлы представляют собой простые текстовые файлы.
-Что такое разметка? Это способ организации данных страницы,
-путем открытия и закрытия тегов(помещая данные внутрь этих тегов).
-Эта разметка служит, чтобы придать значение тексту, который он окружает.
+Что такое разметка? Это способ организации данных страницы
+путем открытия и закрытия тегов и помещения данных внутрь этих тегов.
+Эта разметка служит, чтобы придать значение тексту, который она окружает.
Как и в других языках программирования, HTML имеет много версий. Здесь мы будем говорить о HTML5.
**Примечание:** Вы можете тестировать различные теги и элементы по мере продвижения
-через учебник на сайте, как [codepen](http://codepen.io/pen/) для того, чтобы увидеть
+через учебник на сайте [codepen](http://codepen.io/pen/) для того, чтобы увидеть
их влияние, понять, как они работают и ознакомиться с языком.
-В данной статье рассматривается в основном HTML синтаксис и некоторые полезные советы.
+В данной статье рассматривается в основном HTML-синтаксис и некоторые полезные советы.
```html
-<!-- Комментарии заключаются как эта лини\! -->
+<!-- Это комментарий. -->
<!-- #################### Теги #################### -->
-<!-- Ниже приведен пример HTML-файл, который мы будем анализировать. -->
+<!-- Ниже приведен пример HTML-файла, который мы будем анализировать. -->
<!doctype html>
<html>
@@ -39,7 +39,7 @@ HTML расшифровывается как Hypertext Markup Language(гипе
<body>
<h1>Привет, мир!</h1>
<a href = "http://codepen.io/anon/pen/xwjLbZ">
- Переходите сюда, чтоб посмотреть как это выглядит.
+ Переходите сюда, чтобы посмотреть, как это выглядит.
</a>
<p>Это параграф.</p>
<p>Это другой параграф.</p>
@@ -51,41 +51,41 @@ HTML расшифровывается как Hypertext Markup Language(гипе
</body>
</html>
-<!-- HTML-файл всегда начинается с указанием браузеру, что страница это HTML. -->
+<!-- HTML-файл всегда начинается с указания браузеру, что страница — это HTML. -->
<!doctype html>
-<!-- После этого, страница начинается с <html> тега. -->
+<!-- После этого страница начинается с <html> тега. -->
<html>
-<!-- страница будет закрыта в конце с помощью тега </html>. -->
+<!-- Страница будет закрыта в конце с помощью тега </html>. -->
</html>
<!-- Ничто не должно появиться после этого заключительного тега. -->
-<!-- Внутри (между открывающим и закрывающим тегами <html> </ html>), мы находим: -->
+<!-- Внутри (между открывающим и закрывающим тегами <html> </ html>) мы находим: -->
-<!-- Заголовок определяется <head> (it он должен быть закрыт </head>). -->
+<!-- Заголовок определяется <head> (и он должен быть закрыт </head>). -->
<!-- Заголовок содержит описание и дополнительную информацию, которая не отображается; это метаданные. -->
<head>
- <title>Мой сайт</title><!-- Тег <title> указывает браузеру заголовок, чтобы показать в строке заголовка названия и вкладки браузера окна. -->
+ <title>Мой сайт</title><!-- Тег <title> указывает браузеру заголовок, который следует показать в строке заголовка названия и вкладки браузера окна. -->
</head>
-<!-- После секция <head>, находится секция - <body> -->
-<!-- До этого момента, ничего описаное не будет отображаться в окне браузера. -->
-<!-- Мы должны наполнить <body> содержанием, которое будет отображаться. -->
+<!-- После секции <head>, находится секция - <body> -->
+<!-- До этого момента, ничего из описанного не будет отображаться в окне браузера. -->
+<!-- Мы должны наполнить <body> содержанием, которое будет отображаться. -->
<body>
<h1>Hello, world!</h1> <!-- Тег h1 создает заголовок. -->
- <!-- Так же существуют другие заголовки от имеющего большее значение <h1> по убыванию к <h6>. -->
- <a href = "http://codepen.io/anon/pen/xwjLbZ">Переходите сюда, чтоб посмотреть как это выглядит.</a>
- <!--гиперссылка на URL, заданнf атрибутом href="" -->
- <p>Это параграф.</p> <!-- Тег <p> позволяет нам добавдять текст на странице HTML. -->
+ <!-- Также существуют другие заголовки от имеющего большее значение <h1> до меньшего <h6>. -->
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Переходите сюда, чтобы посмотреть, как это выглядит.</a>
+ <!--гиперссылка на URL, заданная атрибутом href="" -->
+ <p>Это параграф.</p> <!-- Тег <p> позволяет нам добавлять текст на странице HTML. -->
<p>Это другой параграф.</p>
<ul> <!-- Тег <ul> создает маркированный список. -->
- <!-- Для того, чтобы иметь пронумерованный список лучше использовать <ol>
- тогда первый элемент будет иметь значение 1. для второго элемента, 2. и так далее. -->
- <li>Это элемент в не нумерованном списке (маркированный список)</li>
+ <!-- Для того, чтобы иметь пронумерованный список, лучше использовать <ol>
+ тогда первый элемент будет иметь значение 1., для второго элемента 2. и так далее. -->
+ <li>Это элемент в ненумерованном списке (маркированный список)</li>
<li>Это еще один элемент</li>
<li>И это последний пункт в списке</li>
</ul>
@@ -124,6 +124,6 @@ HTML файлы имеют окончание(расширение) `.html`.
## Узнать больше
-* [википедиа](https://ru.wikipedia.org/wiki/HTML)
+* [википедия](https://ru.wikipedia.org/wiki/HTML)
* [HTML учебник](https://developer.mozilla.org/ru/docs/Web/HTML)
* [htmlbook](http://htmlbook.ru/)
diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown
index 4556b425..4c4fa503 100644
--- a/ru-ru/javascript-ru.html.markdown
+++ b/ru-ru/javascript-ru.html.markdown
@@ -504,7 +504,7 @@ if (Object.create === undefined) { // не перезаписываем мето
[Mozilla Developer Network](https://developer.mozilla.org/ru/docs/Web/JavaScript) —
предоставляет отличную документацию для JavaScript, как он используется в браузерах.
-Кроме того, это вики, поэтому, если вы знаете больше, вы можете помочь другим,
+Кроме того, это вики. Поэтому, если вы знаете больше, вы можете помочь другим,
делясь своими знаниями.
[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/ru/) — это
diff --git a/ru-ru/learnvisualbasic-ru.html.markdown b/ru-ru/learnvisualbasic-ru.html.markdown
index 72e1358c..6242fc42 100644
--- a/ru-ru/learnvisualbasic-ru.html.markdown
+++ b/ru-ru/learnvisualbasic-ru.html.markdown
@@ -8,7 +8,7 @@ filename: learnvisualbasic-ru.vb
lang: ru-ru
---
-```vbnet
+```visualbasic
Module Module1
Sub Main()
diff --git a/ru-ru/linker-ru.html.markdown b/ru-ru/linker-ru.html.markdown
index 7df29c23..14cfd229 100644
--- a/ru-ru/linker-ru.html.markdown
+++ b/ru-ru/linker-ru.html.markdown
@@ -34,11 +34,11 @@ lang: ru-ru
# Определяем точку входа в программу
ENTRY(Reset_Handler)
-# Определяем перемнную которая содержит адрес вершины стека
+# Определяем переменную которая содержит адрес вершины стека
_estack = 0x20020000;
-# Определяем перемнную которая содержит значение размера кучи
+# Определяем переменную которая содержит значение размера кучи
_Min_Heap_Size = 0x200;
-# Определяем перемнную которая содержит значение размера стека
+# Определяем переменную которая содержит значение размера стека
_Min_Stack_Size = 0x400;
# Описание карты памяти доступной для данного процессора
@@ -50,7 +50,7 @@ _Min_Stack_Size = 0x400;
# RAM - начинается с адреса 0x20000000 и занимает 128 Кбайт;
# CCMRAM - начинается с адреса 0x10000000и занимает 64 Кбайт;
# FLASH - начинается с адреса 0x8000000 занимает 1024 Кбайт;
-# Причем RAM память доступка для чтения, записи и исполнения.
+# Причем RAM память доступна для чтения, записи и исполнения.
# CCMRAM память доступна только на чтение и запись.
# FLASH память доступна на чтение и исполнение.
MEMORY
@@ -70,7 +70,7 @@ SECTIONS
. = ALIGN(4);
# Существует опция --gc-sections, которая позволяет собирать мусор из неиспользуемых
- # входных разделов. И если есть разделы, которые сборщик муссора не должен трогать,
+ # входных разделов. И если есть разделы, которые сборщик мусора не должен трогать,
# то их необходимо указать в качестве аргумента функции KEEP() (аналог ключевого слова
# volatile).
# Запись (*(.isr_vector)) означает разделы .isr_vector во всех объектных файлах. Т.к.
@@ -80,8 +80,8 @@ SECTIONS
# Выравниваем текущую позицию на границу 4-х байт.
. = ALIGN(4);
- # Выражение ">ОБЛАСТЬ_ПАМЯТИ" указывает в какую именно область памяти будет помещенна
- # данная секция. В нашем слущае секция .isr_vector будет размещена во FLASH памяти.
+ # Выражение ">ОБЛАСТЬ_ПАМЯТИ" указывает в какую именно область памяти будет помещена
+ # данная секция. В нашем случае секция .isr_vector будет размещена во FLASH памяти.
} >FLASH
# ИТОГО: Секция .isr_vector, которая содержит таблицу векторов прерываний выравнивается
@@ -125,7 +125,7 @@ SECTIONS
# Выравниваем текущую позицию на границу 4-х байт.
. = ALIGN(4);
- # Указываем, что в данной секции будут хранится области .rodataвсех
+ # Указываем, что в данной секции будут хранится области .rodata всех
# объектных файлов
*(.rodata)
*(.rodata*)
@@ -158,13 +158,13 @@ SECTIONS
_edata = .;
# Функция AT указывает на то, что данный сектор хранится в одной области памяти
- # (в нашем случае FLASH), а исполняться будет из другой обасти памяти (в нашем случае RAM).
- # Есть два типа адрессов:
- # * VMA (Virtual memory address) - это run-time адрес по которому уомпилятор ожидает
+ # (в нашем случае FLASH), а исполняться будет из другой области памяти (в нашем случае RAM).
+ # Есть два типа адресов:
+ # * VMA (Virtual memory address) - это run-time адрес по которому компилятор ожидает
# видеть данные.
# * LMA (Load memory address) - это адрес по которому линкер хранит данные.
- #Startup должен код скопировать секцию .data из адрессов LMA в адресса VMA.
+ #Startup должен код скопировать секцию .data из адресов LMA в адреса VMA.
} >RAM AT> FLASH
diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown
index 579a9a20..fc8614c4 100644
--- a/ru-ru/markdown-ru.html.markdown
+++ b/ru-ru/markdown-ru.html.markdown
@@ -45,7 +45,7 @@ Markdown является надмножеством HTML, поэтому люб
HTML-элементов -->
```
-## Заголовки
+## Заголовки
HTML-элементы от <h1> до <h6> размечаются очень просто:
текст, который должен стать заголовком, предваряется
@@ -85,7 +85,7 @@ __И этот тоже.__
*__И даже здесь!__*
```
-В Github Flavored Markdown, стандарте, который используется в Github,
+В GitHub Flavored Markdown, стандарте, который используется в GitHub,
текст также можно сделать зачёркнутым:
```md
@@ -110,7 +110,7 @@ __И этот тоже.__
Для вставки принудительных переносов можно завершить абзац двумя дополнительными пробелами:
```md
-Эта строка завершается двумя пробелами (выделите, чтобы увидеть!).
+Эта строка завершается двумя пробелами (выделите, чтобы увидеть!).
Над этой строкой есть <br />!
```
@@ -208,7 +208,7 @@ __И этот тоже.__
```md
my_array.each do |item|
- puts item
+ puts item
end
```
@@ -220,18 +220,17 @@ __И этот тоже.__
Ваня даже не знал, что делает функция `go_to()`!
```
-В Github Flavored Markdown для блоков кода можно использовать
+В GitHub Flavored Markdown для блоков кода можно использовать
специальный синтаксис:
-<pre>
-<code class="highlight">&#x60;&#x60;&#x60;ruby
+```ruby
def foobar
- puts "Привет, мир!"
+ puts "Привет, мир!"
end
-&#x60;&#x60;&#x60;</code></pre>
+```
Во фрагменте, приведённом выше, отступ не требуется.
-Кроме того, Github подсветит синтаксис языка, указанного после \`\`\`
+Кроме того, GitHub подсветит синтаксис языка, указанного после \`\`\`
## Горизонтальный разделитель
@@ -255,6 +254,7 @@ end
```md
[Ссылка!](http://test.com/)
```
+
Также для ссылки можно указать всплывающую подсказку (`title`), используя
кавычки внутри круглых скобок:
@@ -269,11 +269,13 @@ end
Markdown также позволяет размечать ссылку в виде сноски:
-<pre><code class="highlight">&#x5b;<span class="nv">Щёлкните эту ссылку</span>][<span class="ss">link1</span>] для подробной информации!
-&#x5b;<span class="nv">Также посмотрите эту ссылку,</span>][<span class="ss">foobar</span>] если хотите.
+```md
+[Щёлкните эту ссылку][link1] для подробной информации!
+[Также посмотрите эту ссылку,][foobar] если хотите.
-&#x5b;<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Круто!"</span>
-&#x5b;<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Нормально!"</span></code></pre>
+[link1]: http://test.com/ "Круто!"
+[foobar]: http://foobar.biz/ "Нормально!"
+```
`Title` также может быть в одинарных кавычках или круглых скобках, а также
отсутствовать вовсе. Ссылки на сноски могут быть в любом месте документа,
@@ -281,9 +283,11 @@ Markdown также позволяет размечать ссылку в вид
Существует также неявное именование, когда ссылка является идентификатором.
-<pre><code class="highlight">&#x5b;<span class="nv">Это</span>][] ссылка.
+```md
+[Это][] ссылка.
-&#x5b;<span class="nv">это</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
+[это]: http://thisisalink.com/
+```
Правда, эта возможность не очень распространена.
@@ -294,11 +298,15 @@ Markdown также позволяет размечать ссылку в вид
```md
![Альтернативный текст для изображения](http://imgur.com/myimage.jpg "Подсказка")
```
-Изображения тоже могут быть оформлены, как сноски.
-<pre><code class="highlight">!&#x5b;<span class="nv">Это альтернативный текст.</span>][<span class="ss">myimage</span>]
+Изображения тоже могут быть оформлены как сноски.
+
+```md
+![Это альтернативный текст.][myimage]
+
+[myimage]: relative/urls/cool/image.jpg "Если нужна подсказка, её можно добавить"
+```
-&#x5b;<span class="nv">myimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"Если нужна подсказка, её можно добавить"</span></code></pre>
## Разное
### Автоссылки
@@ -322,7 +330,7 @@ Markdown также позволяет размечать ссылку в вид
```
### Клавиши на клавиатуре
-В Github Flavored Markdown для представления клавиш на клавиатуре
+В GitHub Flavored Markdown для представления клавиш на клавиатуре
вы можете использовать тег `<kbd>`.
```md
@@ -341,6 +349,7 @@ Markdown также позволяет размечать ссылку в вид
| Выравнивание | Выравнивание | Выравнивание |
| влево | по центру | вправо |
```
+
Или более компактно
```md
diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown
index af77a9ca..4a508cfc 100644
--- a/ru-ru/php-ru.html.markdown
+++ b/ru-ru/php-ru.html.markdown
@@ -125,7 +125,7 @@ echo 'Multiple', 'Parameters', 'Valid'; // печатает 'MultipleParametersV
// и никогда не может быть изменена во время выполнения программы!
// Правильное имя константы начинается с буквы или символа подчеркивания
-// и содержит любое колличество букв, цифр или символов подчеркивания.
+// и содержит любое количество букв, цифр или символов подчеркивания.
define("FOO", "something");
// Доступ к константе возможен через прямое указание её имени без знака $
@@ -224,7 +224,7 @@ assert($c > $b); // больше
assert($a <= $b); // меньше или равно
assert($c >= $d); // больше или равно
-// Следующие утверждения истинны, если переменные имеют одинаковые тип.
+// Следующие утверждения истинны, если переменные имеют одинаковый тип.
assert($c === $d);
assert($a !== $d);
assert(1 == '1');
@@ -251,7 +251,7 @@ echo $string + $string; // => 2 (строка превращается в чис
$string = 'one';
echo $string + $string; // => 0
-// Приведение типов (type casting) может быть использовано для преобразование
+// Приведение типов (type casting) может быть использовано для преобразования
// переменной в другой тип
$boolean = (boolean) 1; // => true
@@ -458,7 +458,7 @@ include_once 'my-file.php';
require 'my-file.php';
require_once 'my-file.php';
-// Действует также как и include(), но если файл не удалось подключить,
+// Действует так же как и include(), но если файл не удалось подключить,
// функция выдает фатальную ошибку
// Содержимое файла my-include.php:
@@ -497,7 +497,7 @@ class MyClass
// Конструктор описывается с помощью __construct
public function __construct($instanceProp) {
- // Доступ к эземпляру класса с помощью $this
+ // Доступ к экземпляру класса с помощью $this
$this->instanceProp = $instanceProp;
}
@@ -661,7 +661,7 @@ $cls->myTraitMethod(); // Напечатает "I have MyTrait"
<?php
// По умолчанию, классы существуют в глобальном пространстве имен и могут быть
-// вызваны с обратным слешем.
+// вызваны с обратным слэшем.
$cls = new \MyClass();
@@ -762,7 +762,7 @@ echo "Current method is " . __METHOD__;
echo "Current namespace is " . __NAMESPACE__;
// Возвращает имя текущего трейта.
-// Возвращает только если испольщуется внутри трейта.
+// Возвращает только если используется внутри трейта.
echo "Current namespace is " . __TRAIT__;
@@ -771,7 +771,7 @@ echo "Current namespace is " . __TRAIT__;
*
*/
-// Простую обработку ошибок можно произвести спомощью try catch блока.
+// Простую обработку ошибок можно произвести с помощью try catch блока.
try {
// Выполняем что-то
@@ -779,7 +779,7 @@ try {
// Обработка исключения
}
-// При использовании try catch блока в области вилимости, стоит использовать
+// При использовании try catch блока в области видимости, стоит использовать
// следующий подход:
try {
@@ -788,7 +788,7 @@ try {
// Обработка исключения
}
-// Специальное(кастомное) исключение - exceptions
+// Специальное (кастомное) исключение - exceptions
class MyException extends Exception {}
@@ -797,7 +797,7 @@ try {
$condition = true;
if ($condition) {
- throw new MyException('Something just happend');
+ throw new MyException('Something just happened');
}
} catch (MyException $e) {
diff --git a/ru-ru/pyqt-ru.html.markdown b/ru-ru/pyqt-ru.html.markdown
index 24afc03d..a7e14c02 100644
--- a/ru-ru/pyqt-ru.html.markdown
+++ b/ru-ru/pyqt-ru.html.markdown
@@ -11,7 +11,7 @@ translators:
**Qt** - широко известный кросс-платформенный фреймворк для разработки программного обеспечения,
который может быть использован на различных софтварных и хардварных платформах без какого-либо
-изменения в коде. Данный фреймворк при этом обладает мощью и скоростью нативных приложений.
+изменения в коде. Данный фреймворк при этом обладает мощью и скоростью нативных приложений.
Qt и был изначально написан на *C++*.
Данный текст является адаптацией введения в Qt на C++ под авторством Алексея Ковальчука для pyqt.
@@ -20,7 +20,7 @@ Qt и был изначально написан на *C++*.
```python
def window():
- # Создайте объект приложения
+ # Создайте объект приложения
app = QtGui.QApplication(sys.argv)
# Создайте виджет, где будет находиться наш лейбл
w = QtGui.QWidget()
@@ -28,10 +28,10 @@ def window():
b = QtGui.QLabel(w)
# Задайте текст для лейбла
b.setText("Hello World!")
- # Задайте информация о размере и расположении
+ # Задайте информация о размере и расположении
w.setGeometry(100, 100, 200, 50)
b.move(50, 20)
- # Задайте заголовок окна
+ # Задайте заголовок окна
w.setWindowTitle("PyQt")
# Все ранее написанное выводится на экран
w.show()
@@ -43,11 +43,11 @@ if __name__ == '__main__':
```
-Для того, чтобы получить более продвинутые функции приложения в pyqt, нам необходимо
-обратить внимание на создание дополнительных элементов. Ниже представлено создание всплывающего диалогового окна, которое просит пользователя подтвердить его решение или предоставить какую-либо
+Для того чтобы получить более продвинутые функции приложения в pyqt, нам необходимо
+обратить внимание на создание дополнительных элементов. Ниже представлено создание всплывающего диалогового окна, которое просит пользователя подтвердить его решение или предоставить какую-либо
информацию.
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
@@ -67,7 +67,7 @@ def window():
w.show()
sys.exit(app.exec_())
-Данная функция должна создавать диалоговое окно с кнопкой, которая ждет клика по себе
+Данная функция должна создавать диалоговое окно с кнопкой, которая ждет клика по себе
и затем завершает программу.
def showdialog():
diff --git a/ru-ru/qt-ru.html.markdown b/ru-ru/qt-ru.html.markdown
index 5fbcc3b4..15e2c775 100644
--- a/ru-ru/qt-ru.html.markdown
+++ b/ru-ru/qt-ru.html.markdown
@@ -80,7 +80,7 @@ int main(int argc, char *argv[]) {
```
Обратите внимание на метод *QObject::connect*. Этот метод соединяет *СИГНАЛЫ* одного объекта со *СЛОТАМИ* другого.
-**Сигналы** отправляются когда с объектами происходят отпределённые события, например, сигнал *нажатие* отправляется когда пользователь нажимает на объект типа QPushButton.
+**Сигналы** отправляются когда с объектами происходят определённые события, например, сигнал *нажатие* отправляется, когда пользователь нажимает на объект типа QPushButton.
**Слоты** это *действия*, которые могут быть выполнены в ответ на полученные сигналы.
diff --git a/ru-ru/sql-ru.html.markdown b/ru-ru/sql-ru.html.markdown
index 7353a175..702a8102 100644
--- a/ru-ru/sql-ru.html.markdown
+++ b/ru-ru/sql-ru.html.markdown
@@ -22,9 +22,9 @@ lang: ru-ru
поддерживают ключевые слова QUIT, EXIT или оба).
Некоторые команды ниже предполагают использование
-[демонстрационного образца базы данных сотрудников от MySQL](https://dev.mysql.com/doc/employee/en/), доступного на [Github](https://github.com/datacharmer/test_db).
+[демонстрационного образца базы данных сотрудников от MySQL](https://dev.mysql.com/doc/employee/en/), доступного на [GitHub](https://github.com/datacharmer/test_db).
Следовательно, для повторения команд в локальном окружении он должен быть загружен.
-Файлы на github — это скрипты с командами, которые схожи с командами ниже,
+Файлы на github — это скрипты с командами, схожие с командами ниже,
которые создают и манипулируют таблицами и данными о сотрудниках вымышленной
компании. Синтаксис для запуска этих скриптов будет зависеть от используемой
вами реализации SQL. Обычно используется утилита, запускаемая из командной
@@ -50,7 +50,7 @@ SHOW DATABASES;
USE employees;
-- Выбрать все строки и колонки из таблицы «departments» (отделы) текущей базы.
--- В интерактивном режиме обыч но результат будет выведен на экран.
+-- В интерактивном режиме обычно результат будет выведен на экран.
SELECT * FROM departments;
-- Тот же запрос, что и выше, но выбор только колонок «dept_no» и «dept_name».
diff --git a/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown
index bd2d23a0..56471961 100644
--- a/ru-ru/swift-ru.html.markdown
+++ b/ru-ru/swift-ru.html.markdown
@@ -18,7 +18,7 @@ Swift - это язык программирования, созданный к
конференции разработчиков Apple, WWDC. Приложения на Swift собираются
с помощью LLVM-компилятора, включенного в Xcode 6+.
-Официальная книга по [языку программирования Swift](https://itunes.apple.com/us/book/swift-programming-language/id881256329) от Apple доступна в iBooks.
+Официальная книга по [языку программирования Swift](https://itunes.apple.com/us/book/swift-programming-language/id881256329) от Apple доступна в Apple Books.
Смотрите еще [начальное руководство](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html) Apple, которое содержит полное учебное пособие по Swift.
diff --git a/ru-ru/tcl-ru.html.markdown b/ru-ru/tcl-ru.html.markdown
new file mode 100644
index 00000000..380d7b05
--- /dev/null
+++ b/ru-ru/tcl-ru.html.markdown
@@ -0,0 +1,584 @@
+---
+language: Tcl
+lang: ru-ru
+contributors:
+ - ["Poor Yorick", "https://pooryorick.com/"]
+translators:
+ - ["Viktor Sokhranov", "https://github.com/weirdvic"]
+filename: learntcl-ru.tcl
+---
+
+Tcl был создан [Джоном Оустерхаутом](https://ru.wikipedia.org/wiki/Оустерхаут,_Джон)
+в качестве скриптового языка в своих инструментах проектирования электрических цепей.
+В 1997 году за разработку языка Tcl автор получил [ACM](https://ru.wikipedia.org/wiki/ACM)
+ Software System Award. Tcl может использоваться и как встраиваемый скриптовый язык,
+и как язык программирования общего назначения. Кроме того, он может быть использован как
+библиотека в программах на C, даже в случаях когда не требуется написание скриптов,
+поскольку Tcl может предоставить программе на C различные типы данных, такие как
+динамические строки, списки и хэш-таблицы. Также с помощью этой библиотеки возможно
+использовать форматирование строк, операции с файловой системой, работу с кодировками и
+динамически загружаемые библиотеки. К другим особенностям Tcl относятся:
+
+* Удобный кроссплатформенный API для работы с сетью
+
+* Поддержка виртуальной файловой системы (VFS)
+
+* Стекируемые каналы ввода-вывода
+
+* Асинхронность в ядре языка
+
+* Поддержка корутин
+
+* Простая и надёжная модель потоков выполнения
+
+Tcl имеет много общего с Lisp, но в отличие от списков, в Tcl "валютой" языка
+являются строки. Все значения являются строками. Список в Tcl это просто строка в
+определённом формате, а тело процедуры (скрипт) это ещё одна строка, а не блок.
+С целью увеличения производительности, интерпретатор Tcl использует кэшированные
+внутренние представления различных типов данных. Например, рутины (routines), работающие
+со списками, фактически используют внутреннее представление списков, а интерпретатор
+Tcl обновляет строковое представление в том случае если оно используется в скрипте.
+В Tcl используется подход copy-on-write, позволяющий оперировать большими объёмами
+данных без дополнительного оверхеда. Процедуры в Tcl автоматически компилируются
+в байткод, кроме случаев когда в процедуре используются динамические рутины, такие
+как `uplevel`, `upvar` и `trace`.
+
+Программировать на Tcl приятно. Его находят привлекательным хакеры, которым интересны
+Lisp, Forth или Smalltalk, а также инженеры и учёные, которым просто необходим
+гибкий инструмент для выполнения их задач. В Tcl языковые конструкции, включая
+циклы и математические операторы, представлены в виде изменяемых рутин, в отличие
+от других языков программирования, где они закреплены в синтаксисе, что позволяет
+синтаксису Tcl не мешать работать с предметной областью проекта. Синтаксис Tcl в этом
+смысле даже более минималистичен чем у Lisp.
+
+```tcl
+#! /bin/env tclsh
+
+###############################################################################
+## 1. Рекомендации
+###############################################################################
+
+# Tcl это не shell или C! Этот момент требует уточнения, поскольку привычки
+# написания shell-скриптов почти работают в Tcl и часто люди начинают
+# изучать Tcl со знанием синтаксиса других языков. Поначалу это работает, но
+# когда скрипты становятся сложнее, наступает фрустрация.
+
+# Фигурные скобки {} в Tcl используются не для построения блоков кода или
+# списков, а как механизм экранирования (quoting) для кода. Фактически в Tcl
+# нет ни списков, ни блоков кода. Фигурные скобки использутся для
+# экранирования специальных символов и потому подходят для представления
+# тела процедур и строк, которые должны интерпретироваться как списки.
+
+
+###############################################################################
+## 2. Синтаксис
+###############################################################################
+
+# Скрипт состоит из команд, разделённых символами перевода строки или символами
+# точки с запятой. Каждая команда представляет собой вызов рутины. Первое слово
+# это имя вызываемой рутины, а последующие слова это аргументы. Слова разделены
+# пробелами. Так как каждый аргумент это слово в команде, он является строкой и
+# может быть неэкранирован:
+set part1 Sal
+set part2 ut; set part3 ations
+
+
+# символ доллара используется для подставления значения переменных:
+set greeting $part1$part2$part3
+
+
+# Когда "set" получает только имя переменной, возвращается значение переменной:
+set part3 ;# Возвращает значение переменной
+
+
+# Содержимое квадратных скобок заменяется на результат выполнения:
+set greeting $part1$part2[set part3]
+
+
+# Встроенный таким образов скрипт может состоять из нескольких команд, но
+# результат подстановки определяется последней командой:
+set greeting $greeting[
+ incr i
+ incr i
+ incr i
+]
+puts $greeting ;# Выведет "Salutations3"
+
+# Каждое слово в команде является строкой, включая имя рутины, поэтому
+# подстановки могут быть использованы и таким образом:
+set action pu
+
+# следующие команды эквивалентны:
+puts $greeting
+${action}ts $greeting
+[set action]ts $greeting
+
+
+# Обратный слэш экранирует специальные символы:
+set amount \$16.42
+
+
+# и он же используется для ввода специальных символов:
+puts lots\nof\n\n\n\n\n\nnewlines
+
+
+# Слово в фигурных скобках никак не интерпретируется и в нём не работают
+# никакие подстановки, за исключением экранирования закрывающей скобки:
+set somevar {
+ Это литерал знака $, а это \} экранированная закрывающая скобка
+}
+
+
+# В слове внутри двойных кавычек, пробельные символы теряют своё
+# специальное значение:
+set name Neo
+set greeting "Hello, $name"
+
+
+# Имя переменной может быть любой строкой:
+set {first name} New
+
+
+# Фигурные скобки используются для доступа к переменным с составными именами:
+set greeting "Hello, ${first name}"
+
+
+# "set" всегда можно использовать вместо подстановки переменной:
+set greeting "Hello, [set {first name}]"
+
+
+# Чтобы "распаковать" список в команду используется оператор расширения "{*}"
+# Эти две команды эквивалентны:
+set name Neo
+set {*}{name Neo}
+
+
+# Массив это особая переменная, являющаяся контейнером для других переменных.
+set person(name) Neo
+set person(destiny) {The One}
+set greeting "Hello, $person(name)"
+
+
+# "variable" может быть использована для объявления или установки переменных.
+# В отличие от "set", которая использует глобальное и локальное пространство
+# имён, "variable" работает только с локальным пространством:
+variable name New
+
+
+# "namespace eval" создаёт новое пространство имён, если его не существует.
+# Пространство имён может содержать рутины и переменные:
+namespace eval people {
+ namespace eval person1 {
+ variable name Neo
+ }
+}
+
+
+# Двумя или более двоеточиями в именах переменных отделяется название
+# пространства имён:
+namespace eval people {
+ set greeting "Hello $person1::name"
+}
+
+# Два или более двоеточия также отделяют название пространства имён
+# в имени рутины:
+proc people::person1::speak {} {
+ puts {I am The One.}
+}
+
+# Полные(fully-qualified) имена начинаются с двух двоеточий:
+set greeting "Hello $::people::person1::name"
+
+
+
+###############################################################################
+## 3. Больше никакого синтаксиса
+###############################################################################
+
+# Все остальные функции реализованы посредством рутин. С этого момента и далее
+# больше нет нового синтаксиса. Всё остальное что можно изучить о Tcl это
+# поведение отдельных рутин и какие значения они присваивают своим аргументам.
+
+
+
+###############################################################################
+## 4. Переменные и пространства имён
+###############################################################################
+
+# Каждая переменная и рутина связана с пространством имён.
+
+# Чтобы получить интерпретатор, который не может сделать ничего, достаточно
+# удалить глобальное пространство имён. Особой пользы в этом нет, но это хорошо
+# иллюстрирует природу Tcl. Фактически имя глобального пространства имён это
+# пустая строка, но единственный способ представить её -- в виде полного имени:
+proc delete_global_namespace {} {
+ namespace delete ::
+}
+
+# Поскольку "set" всегда учитывает и глобальное, и текущее пространства имён,
+# более безопасно использовать "variable" чтобы объявить новую переменную или
+# задать значение переменной. Если переменная с именем "name" уже существует
+# в глобальном пространстве имён, использование "set" задаст значение
+# глобальной переменной, тогда как "variable" работает только с текущим
+# пространством имён.
+
+namespace eval people {
+ namespace eval person1 {
+ variable name Neo
+ }
+}
+
+# После объявления переменной в пространстве имён, [set] видит её, а не
+# одноимённую переменную в глобальном пространстве имён:
+
+namespace eval people {
+ namespace eval person1 {
+ variable name
+ set name Neo
+ }
+}
+
+# Но если "set" приходится создать новую переменную, он всегда делает это
+# с учётом текущего пространства имён:
+unset name
+namespace eval people {
+ namespace eval person1 {
+ set name neo
+ }
+
+}
+set people::person1::name
+
+
+# Абсолютное имя всегда начинается с имени глобального пространства имён, то
+# есть с пустой строки, за которой следует два двоеточия:
+set ::people::person1::name Neo
+
+
+# В пределах процедуры "variable" связывает перменную в текущем пространстве
+# имён с локальной областью видимости:
+namespace eval people::person1 {
+ proc fly {} {
+ variable name
+ puts "$name is flying!"
+ }
+}
+
+
+
+
+###############################################################################
+## 5. Встроенные рутины
+###############################################################################
+
+# Математические операции можно выполнять при помощи "expr":
+set a 3
+set b 4
+set c [expr {$a + $b}]
+
+# Поскольку "expr" самостоятельно занимается подстановкой значений переменных,
+# математическое выражение нужно оборачивать в фигурные скобки чтобы отключить
+# подстановку значений переменных интерпретатором Tcl.
+# Подробнее об этом можно прочесть здесь:
+# "https://wiki.tcl-lang.org/page/Brace+your+expr-essions"
+
+
+# "expr" выполняет подстановку переменных и результатов команд:
+set c [expr {$a + [set b]}]
+
+
+# "expr" предоставляет разные математические функции:
+set c [expr {pow($a,$b)}]
+
+
+# Математические операторы сами по себе доступны в виде рутин в
+# пространстве имён ::tcl::mathop
+::tcl::mathop::+ 5 3
+
+# Рутины могут быть импортированы из других пространств имён:
+namespace import ::tcl::mathop::+
+set result [+ 5 3]
+
+
+# Не числовые значения должны быть квотированы. Такие операторы как "eq"
+# Могут быть использованы чтобы провести строковое сравнение:
+set name Neo
+expr {{Bob} eq $name}
+
+# Общие операторы сравнения тоже работают со строками если числовое значение
+# операнда недоступно:
+expr {{Bob} == $name}
+
+
+# "proc" создаёт новые рутины:
+proc greet name {
+ return "Hello, $name!"
+}
+
+# можно указать несколько параметров:
+proc greet {greeting name} {
+ return "$greeting, $name!"
+}
+
+
+# Как было отмечено ранее, фигурные скобки не обозначают блок кода.
+# Любое значение, даже третий аргумент "proc", является строкой.
+# Предыдущая команда может быть переписана без использования фигурных скобок:
+proc greet greeting\ name return\ \"\$greeting,\ \$name!\"
+
+
+
+# Если последний параметр называется "args", все дополнительные аргументы,
+# переданные рутине, собираются в список и передаются как "args":
+proc fold {cmd first args} {
+ foreach arg $args {
+ set first [$cmd $first $arg]
+ }
+ return $first
+}
+fold ::tcl::mathop::* 5 3 3 ;# -> 45
+
+
+# Условное выполнение тоже реализовано как рутина:
+if {3 > 4} {
+ puts {This will never happen}
+} elseif {4 > 4} {
+ puts {This will also never happen}
+} else {
+ puts {This will always happen}
+}
+
+
+# Циклы реализованы как рутины. Первый и третий аргумент для "for"
+# обрабатываются как скрипты, а второй аргумент как выражение:
+set res 0
+for {set i 0} {$i < 10} {incr i} {
+ set res [expr {$res + $i}]
+}
+unset res
+
+
+# Первый аргумент для "while" тоже обрабатывается как выражение:
+set i 0
+while {$i < 10} {
+ incr i 2
+}
+
+
+# Список это строка, а элементы списка разделены пробелами:
+set amounts 10\ 33\ 18
+set amount [lindex $amounts 1]
+
+# Если элемент списка содержит пробел, его надо экранировать:
+set inventory {"item 1" item\ 2 {item 3}}
+
+
+# Хорошая практика использовать списковые рутины для обработки списков:
+lappend inventory {item 1} {item 2} {item 3}
+
+
+# Фигурные скобки и бэкслеш могут быть использованы чтобы хранить более
+# комплексные структуры внутри списков. Список выглядит как скрипт, за
+# исключением того, что перевод строки и точка с запятой теряют своё
+# специальное значение, а также не производится подстановка значений.
+# Эта особенность Tcl называется гомоиконичность
+# https://ru.wikipedia.org/wiki/Гомоиконичность
+# В приведённом списке есть три элемента:
+set values {
+
+ one\ two
+
+ {three four}
+
+ five\{six
+
+}
+
+
+# Поскольку как и все значения, список является строкой, строковые
+# операции могут выполняться и над списком, с риском повреждения:
+set values {one two three four}
+set values [string map {two \{} $values] ;# $values больше не \
+ правильно отформатированный список
+
+
+# Безопасный способ работать со списками — использовать "list" рутины:
+set values [list one \{ three four]
+lappend values { } ;# добавить символ пробела как элемент в список
+
+
+# Использование "eval" для вычисления значения скрипта:
+eval {
+ set name Neo
+ set greeting "Hello, $name"
+}
+
+
+# Список всегда можно передать в "eval" как скрипт, содержащий одну команду:
+eval {set name Neo}
+eval [list set greeting "Hello, $name"]
+
+
+# Следовательно, когда используется "eval", используйте "list" чтобы собрать
+# необходимую команду:
+set command {set name}
+lappend command {Archibald Sorbisol}
+eval $command
+
+
+# Частая ошибка: не использовать списковые функции для построения команды:
+set command {set name}
+append command { Archibald Sorbisol}
+try {
+ eval $command ;# Здесь будет ошибка, превышено количество аргументов \
+ к "set" в {set name Archibald Sorbisol}
+} on error {result eoptions} {
+ puts [list {received an error} $result]
+}
+
+# Эта ошибка запросто может произойти с "subst":
+
+set replacement {Archibald Sorbisol}
+set command {set name $replacement}
+set command [subst $command]
+try {
+ eval $command ;# Та же ошибка, лишние аргументы к \
+ {set name Archibald Sorbisol}
+} trap {TCL WRONGARGS} {result options} {
+ puts [list {received another error} $result]
+}
+
+
+# "list" корректно форматирует значение для подстановки:
+set replacement [list {Archibald Sorbisol}]
+set command {set name $replacement}
+set command [subst $command]
+eval $command
+
+
+# "list" обычно используется для форматирования значений для подстановки в
+# скрипты, вот несколько примеров:
+
+
+# "apply" вычисляет список из двух элементов как рутину:
+set cmd {{greeting name} {
+ return "$greeting, $name!"
+}}
+apply $cmd Whaddup Neo
+
+# Третий элемент может быть использован для указания пространства имён рутины:
+set cmd [list {greeting name} {
+ return "$greeting, $name!"
+} [namespace current]]
+apply $cmd Whaddup Neo
+
+
+# "uplevel" вычисляет скрипт на уровень выше в списке вызовов:
+proc greet {} {
+ uplevel {puts "$greeting, $name"}
+}
+
+proc set_double {varname value} {
+ if {[string is double $value]} {
+ uplevel [list variable $varname $value]
+ } else {
+ error [list {not a double} $value]
+ }
+}
+
+
+# "upvar" связывает переменную на текущем уровне вызовов с переменной на
+# более высоком уровне:
+proc set_double {varname value} {
+ if {[string is double $value]} {
+ upvar 1 $varname var
+ set var $value
+ } else {
+ error [list {not a double} $value]
+ }
+}
+
+
+# Избавляемся от встроенной рутины "while" и используем "proc" чтобы написать
+# свою версию:
+rename ::while {}
+# обработка оставлена как упражнение:
+proc while {condition script} {
+ if {[uplevel 1 [list expr $condition]]} {
+ uplevel 1 $script
+ tailcall [namespace which while] $condition $script
+ }
+}
+
+
+# "coroutine" создаёт новый стек вызовов, новую рутину для входа в этот стек
+# и вызывает эту рутину. "yield" приостанавливает вычисления в этом стеке и
+# возвращает управление вызывавшему стеку:
+proc countdown count {
+ # отправить что-нибудь обратно создателю корутины, фактически
+ # останавливая стек вызовов на время.
+ yield [info coroutine]
+
+ while {$count > 1} {
+ yield [incr count -1]
+ }
+ return 0
+}
+coroutine countdown1 countdown 3
+coroutine countdown2 countdown 5
+puts [countdown1] ;# -> 2
+puts [countdown2] ;# -> 4
+puts [countdown1] ;# -> 1
+puts [countdown1] ;# -> 0
+catch {
+ puts [coundown1] ;# -> invalid command name "countdown1"
+} cres copts
+puts $cres
+puts [countdown2] ;# -> 3
+
+
+# Стеки корутин могут передавать контроль друг другу:
+
+proc pass {whom args} {
+ return [yieldto $whom {*}$args]
+}
+
+coroutine a apply {{} {
+ yield
+ set result [pass b {please pass the salt}]
+ puts [list got the $result]
+ set result [pass b {please pass the pepper}]
+ puts [list got the $result]
+}}
+
+coroutine b apply {{} {
+ set request [yield]
+ while 1 {
+ set response [pass c $request]
+ puts [list [info coroutine] is now yielding]
+ set request [pass a $response]
+ }
+}}
+
+coroutine c apply {{} {
+ set request [yield]
+ while 1 {
+ if {[string match *salt* $request]} {
+ set request [pass b salt]
+ } else {
+ set request [pass b huh?]
+ }
+ }
+}}
+
+
+
+```
+
+## Ссылки
+
+[Официальная документация Tcl](https://www.tcl-lang.org)
+
+[Tcl Wiki](https://wiki.tcl-lang.org)
+
+[Tcl на Reddit](http://www.reddit.com/r/Tcl)
diff --git a/ru-ru/tmux-ru.html.markdown b/ru-ru/tmux-ru.html.markdown
index aa7545cc..643c48b0 100644
--- a/ru-ru/tmux-ru.html.markdown
+++ b/ru-ru/tmux-ru.html.markdown
@@ -249,4 +249,4 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] |
[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux)
-[Отображение CPU/MEM % в статусбаре](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux)
+[Отображение CPU/MEM % в статус баре](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux)
diff --git a/ru-ru/typescript-ru.html.markdown b/ru-ru/typescript-ru.html.markdown
index 09bbb2d1..ad931599 100644
--- a/ru-ru/typescript-ru.html.markdown
+++ b/ru-ru/typescript-ru.html.markdown
@@ -9,8 +9,8 @@ translators:
filename: learntypescript-ru.ts
---
-TypeScript — это язык программирования, целью которого является лёгкая разработка широкомасштабируемых JavaScript-приложений.
-TypeScript добавляет в Javascript общие концепции, такие, как классы, модули, интерфейсы, обобщённое программирование и (опционально) статическую типизацию.
+TypeScript — это язык программирования, целью которого является лёгкая разработка широко масштабируемых JavaScript-приложений.
+TypeScript добавляет в Javascript общие концепции, такие как классы, модули, интерфейсы, обобщённое программирование и (опционально) статическую типизацию.
Это надмножество языка JavaScript: весь JavaScript-код является валидным TypeScript-кодом, следовательно, может быть добавлен бесшовно в любой проект.
Компилятор TypeScript генерирует JavaScript-код.
diff --git a/ru-ru/vim-ru.html.markdown b/ru-ru/vim-ru.html.markdown
index f43f99eb..60b381e7 100644
--- a/ru-ru/vim-ru.html.markdown
+++ b/ru-ru/vim-ru.html.markdown
@@ -10,7 +10,7 @@ lang: ru-ru
---
[Vim](http://www.vim.org)
-(Vi IMproved) это клон полулярного текстового редактора для Unix. Он разработан
+(Vi IMproved) это клон популярного текстового редактора для Unix. Он разработан
с целью повышения скорости и продуктивности и повсеместно используется в
большинство Юникс-подобных систем. В нем имеется множество клавиатурных
сочетаний для быстрой навигации к определенным точкам в файле и быстрого
@@ -167,8 +167,8 @@ Vim можно рассматривать как набор команд в фо
## Макросы
Макросы это просто записываемые действия.
-Во время записи макросы запоминают **все** действия и команды до тех пор пока
-запись не будет остановлена.При вызове макрос применяет ту же самую последовательность
+Во время записи макросы запоминают **все** действия и команды до тех пор, пока
+запись не будет остановлена. При вызове макрос применяет ту же самую последовательность
действий и команд на выделенном тексте.
```
diff --git a/ru-ru/xml-ru.html.markdown b/ru-ru/xml-ru.html.markdown
index bf3f22b0..34e17b9b 100644
--- a/ru-ru/xml-ru.html.markdown
+++ b/ru-ru/xml-ru.html.markdown
@@ -15,7 +15,7 @@ XML - это язык разметки, предназначенный для х
* XML-Синтаксис
```xml
-<!-- Комментарии в XML выглядят вот так -->
+<!-- Это комментарий. -->
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
diff --git a/ru-ru/yaml-ru.html.markdown b/ru-ru/yaml-ru.html.markdown
index ddaed2b6..693848fc 100644
--- a/ru-ru/yaml-ru.html.markdown
+++ b/ru-ru/yaml-ru.html.markdown
@@ -12,7 +12,7 @@ lang: ru-ru
YAML как язык сериализации данных предназначен прежде всего для использования людьми.
Это строгое надмножество JSON с добавлением синтаксически значимых переносов строк и
-отступов как в Python. Тем не менее, в отличие от Python, YAML запрещает
+отступов как в Python. Тем не менее в отличие от Python, YAML запрещает
использование табов для отступов.
```yaml
@@ -53,7 +53,7 @@ literal_block: |
Любые строки с большим отступом сохраняют остатки своего отступа -
эта строка будет содержать дополнительно 4 пробела.
folded_style: >
- Весь блок этого тектса будет значением 'folded_style', но в данном случае
+ Весь блок этого текста будет значением 'folded_style', но в данном случае
все символы новой строки будут заменены пробелами.
Пустые строки будут преобразованы в перенос строки.
@@ -76,7 +76,7 @@ a_nested_map:
0.25: a float key
# Ключи также могут быть сложными, например многострочными.
-# Мы используем ? с последующим пробелом чтобы обозначить начало сложного ключа.
+# Мы используем ? с последующим пробелом, чтобы обозначить начало сложного ключа.
? |
Этот ключ
который содержит несколько строк
@@ -124,7 +124,7 @@ base: &base
name: Каждый будет иметь одинаковое имя
# Регулярное выражение << называется ключом объединения независимо от типа языка.
-# Он используется чтобы показать что все ключи одного или более словарей должны быть
+# Он используется, чтобы показать что все ключи одного или более словарей должны быть
# добавлены в текущий словарь.
foo: &foo
@@ -185,5 +185,5 @@ set2:
### Больше информации
-+ [YAML оффициальный вебсайт](http://yaml.org/)
++ [YAML официальный вебсайт](http://yaml.org/)
+ [YAML онлайн валидатор](http://www.yamllint.com/)
diff --git a/sk-sk/elixir-sk.html.markdown b/sk-sk/elixir-sk.html.markdown
index 2401f92e..c9522b49 100644
--- a/sk-sk/elixir-sk.html.markdown
+++ b/sk-sk/elixir-sk.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
@@ -14,7 +14,7 @@ Elixir je moderný funkcionálny jazyk vytvorený nad Erlang VM (virtuálnym
strojom). Je plne kompatibilný s Erlangom, ale ponúka viac štandardnú syntax
a množstvo funkcií.
-```Elixir
+```elixir
# Jednoriadkový komentár začína symbolom #
@@ -24,7 +24,7 @@ a množstvo funkcií.
# Pre spustenie Elixir shellu zadajte príkaz `iex`
# Kompiláciu zdrojových kódov vykonáte príkazom `elixirc`
-# Obe príkazy by sa už mali nachádzať v path pokiaľ ste nainštalovali elixir
+# Obe príkazy by sa už mali nachádzať v path pokiaľ ste nainštalovali Elixir
# správne.
## ---------------------------
@@ -86,7 +86,7 @@ reťazec.
<<?a, ?b, ?c>> #=> "abc"
[?a, ?b, ?c] #=> 'abc'
-# `?a` v elixire vráti ASCII číselnú reprezentáciu pre znak `a`
+# `?a` v Elixir vráti ASCII číselnú reprezentáciu pre znak `a`
?a #=> 97
# Pre spájanie zoznamov sa používa `++`, pre binárne typy `<>`
@@ -119,7 +119,7 @@ pohlavia.gillian #=> "žena"
5 * 2 #=> 10
10 / 2 #=> 5.0
-# V elixire operátor `/` vždy vráti float (reálne číslo).
+# V Elixir operátor `/` vždy vráti float (reálne číslo).
# Pre celočíselné delenie sa používa `div`
div(10, 2) #=> 5
@@ -182,7 +182,7 @@ else
end
# Pamätáte sa na pattern matching? Mnoho štruktúr pre riadenie toku v
-# elixire sa spoliehajú práve na pattern matching.
+# Elixir sa spoliehajú práve na pattern matching.
# `case` dovolí nám porovnať hodnotu oproti mnohým vzorom:
case {:one, :two} do
@@ -314,7 +314,7 @@ Geometria.oblast({:kruh, 3}) #=> 28.25999999999999801048
# Geometria.oblast({:kruh, "nie_je_cislo"})
#=> ** (FunctionClauseError) no function clause matching in Geometria.oblast/1
-# Vďaka nemeniteľnosti (immutability) je rekurzia významnou časťou elixiru
+# Vďaka nemeniteľnosti (immutability) je rekurzia významnou časťou Elixir
defmodule Rekurzia do
def sumuj_zoznam([hlavicka | schvost], acc) do
sumuj_zoznam(chvost, acc + hlavicka)
@@ -389,7 +389,7 @@ end
## ---------------------------
# Elixir sa pri konkurencii spolieha na Actor model. Všetko čo je
-# potrebné na písanie konkuretných programov v elixire sú tri primitívy:
+# potrebné na písanie konkuretných programov v Elixir sú tri primitívy:
# spawning procesy, posielanie a prijímanie správ.
# Na spustnenie nového procesu použijeme `spawn` funkciu, ktorá má ako
diff --git a/sk-sk/git-sk.html.markdown b/sk-sk/git-sk.html.markdown
index ddcd9658..1187abc5 100644
--- a/sk-sk/git-sk.html.markdown
+++ b/sk-sk/git-sk.html.markdown
@@ -139,6 +139,7 @@ $ git init --help
### ignoruj súbory
Zámerne prestaneš sledovať súbor(y) a zložky. Typicky sa používa pre súkromné a dočasné súbory, ktoré by boli inak zdieľané v repozitári.
+
```bash
$ echo "temp/" >> .gitignore
$ echo "private_key" >> .gitignore
@@ -172,6 +173,7 @@ $ git add /cesta/k/súboru/HelloWorld.c
# Môžeš použiť regulárne výrazy!
$ git add ./*.java
```
+
Tento príkaz len pridáva súbory do staging indexu, necommituje ich do repozitára.
### branch
@@ -476,6 +478,7 @@ $ git reset 31f2bb1
# a zosúladí ju s pracovným adresárom (vymaže nekomitnuté zmeny).
$ git reset --hard 31f2bb1
```
+
### revert
Vezme naspäť ("od-urobí") commit. Nezamieňaj s resetom, ktorý obnoví stav
diff --git a/sv-se/nix-sv.html.markdown b/sv-se/nix-sv.html.markdown
index 647575fe..9069c286 100644
--- a/sv-se/nix-sv.html.markdown
+++ b/sv-se/nix-sv.html.markdown
@@ -366,6 +366,9 @@ with builtins; [
* [Susan Potter - Nix Cookbook - Nix By Example]
(https://ops.functionalalgebra.com/nix-by-example/)
-
+
+* [Zero to Nix - Nix Tutorial]
+ (https://zero-to-nix.com/)
+
* [Rommel Martinez - A Gentle Introduction to the Nix Family]
(https://web.archive.org/web/20210121042658/https://ebzzry.io/en/nix/#nix)
diff --git a/swift.html.markdown b/swift.html.markdown
index 36124e11..52015344 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -14,7 +14,7 @@ filename: learnswift.swift
Swift is a programming language for iOS and macOS development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6+.
-The official _[Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329)_ book from Apple is now available via iBooks. It goes into much more detail than this guide, and if you have the time and patience to read it, it's recommended. Some of these examples are from that book.
+The official _[Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329)_ book from Apple is now available via Apple Books. It goes into much more detail than this guide, and if you have the time and patience to read it, it's recommended. Some of these examples are from that book.
Another great reference is _About Swift_ on Swift's [website](https://docs.swift.org/swift-book/).
diff --git a/toml.html.markdown b/toml.html.markdown
index 69dfd754..69dfd754 100755..100644
--- a/toml.html.markdown
+++ b/toml.html.markdown
diff --git a/tr-tr/git-tr.html.markdown b/tr-tr/git-tr.html.markdown
index c6979468..ad2f2e95 100644
--- a/tr-tr/git-tr.html.markdown
+++ b/tr-tr/git-tr.html.markdown
@@ -591,4 +591,4 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [Pro Git](http://www.git-scm.com/book/en/v2)
-* [Yeni başlayanlar için Git ve Github](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners)
+* [Yeni başlayanlar için Git ve GitHub](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners)
diff --git a/tr-tr/sql-tr.html.markdown b/tr-tr/sql-tr.html.markdown
index 54007d32..2e91e9f8 100644
--- a/tr-tr/sql-tr.html.markdown
+++ b/tr-tr/sql-tr.html.markdown
@@ -1,125 +1,125 @@
----
-language: SQL
-contributors:
- - ["Metin Yalçınkaya", "https://github.com/mtnylnky"]
-lang: tr-tr
-filename: learnsql-tr.sql
----
-
-
-```sql
--- Yorumlar iki tire ile başlar
-
--- KISITLAR
-Not null -- Bir kolon asla boş olamaz
-default -- Boş olan yerlere varsayılan bir değer atar
-unique -- Bir kolondaki tüm değerlerin farklı olması kısıtlaması
-primary key -- Bir tablodaki her veri için kimlik bilgisi niteliğindedir
-check -- Bir kolondaki değerlerin belli bir kısıtlamayı sağlamasını sağlar
-
--- Tablo oluşturulur
-CREATE TABLE tablo1 ();
-
--- Tabloyu içerisinde kolonlar ile oluşturma
-CREATE TABLE tablo1(id INTEGER PRIMARY KEY NOT NULL UNIQUE, ad TEXT, soyad TEXT, yas INTEGER);
-
--- TABLO varlığını kontrol eder
-.table
-
--- Veri tabanında olan bütün tabloları görüntüler.
-.schema
-
--- Satır ekle
-INSERT INTO tablo1 ( ad, soyad) VALUES ("Deger1","Deger2");
-
--- Veritabanında tablo üzerindeki verileri görüntüle
--- Sadece 'ad' gibi sınırlı bir veri için
-SELECT ad FROM tablo1;
--- Bütün veriler için
-SELECT * FROM tablo1;
-
--- Veri güncelleme
-UPDATE tablo1 SET ad = "deger1-2"; WHERE name = "Deger1";
-
--- Satır sil
-DELETE FROM tablo1 WHERE id = 1;
-DELETE FROM tablo1 WHERE ad = "Deger1" OR ad = "Deger2";
-
--- Tabloya sonradan kolon ekleme
-ALTER TABLE tablo1 ADD COLUMN email TEXT;
-
--- Tablodaki kolon adı değiştirme
-EXEC sp_rename ' tablo1.[ad]', Ad, 'COLUMN';
-
--- Tablo adı değiştirme
-ALTER TABLE table1 RENAME TO Table1;
-
--- Tabloyu silme
-DROP TABLE Table1;
-
--- BİR TABLOYU BAŞKA TABLO KULLANARAK DOLDURMAK
-INSERT INTO Tablo2 SELECT id,ad, soyad, email from Tablo1;
-
--- LIKE KOMUTU
--- Belirli bir kritere göre arama yaparken kullanılır
--- Adı 'A' ile başlayan veriler
-SELECT * FROM tablo1 WHERE adi LIKE "A%";
--- İçinde 'A' olan veriler
-SELECT * FROM tablo1 WHERE adi LIKE "%A%";
-
--- LIMIT KOMUTU
--- Gösterilen satır sayısını sınırlamak için
-SELECT * FROM Tablo1 LIMIT 6;
--- Gösterilen satırları belirli bir noktadan başlamak üzere sınırlamak için
-SELECT * FROM Tablo1 LIMIT 6 OFFSET 3;
-
--- ORDER BY KOMUTU
--- Herhangi bir kolona göre gösterilen değerleri azalan veya artan şekilde sıralamak için
-SELECT kolon FROM tablo1 WHERE yas ORDER BY column1, column2, .. columnN] [ASC | DESC];
-SELECT * FROM Tablo1 ORDER BY yas ASC
-SELECT * FROM Tablo1 ORDER BY yas DESC
-
--- DISTINCT ANAHTAR SÖZCÜĞÜ
--- Bu anahtar sözcükle sadece farklı değerler gösterilir.
-SELECT DISTINCT yas FROM tablo1;
-
--- JOIN KOMUTU
--- CROSS JOIN
--- Cross join bir tablodaki her satırı ikinci tablodaki bir satır ile eşleştirmek için kulanılır.
--- Eğer birinci tabloda x satır ikinci tabloda y satır varsa sonuçta x*y satır olur.
-SELECT ... FROM table1 CROSS JOIN table2 …
-SELECT ad, yas FROM Tablo1 CROSS JOIN Tablo2;
-
--- INNER JOIN
--- Inner join iki tablodaki ortak kolon değerlerini kullanarak bir sonuç üretir.
-SELECT ... FROM table1 [INNER] JOIN table2 ON conditional_expression …
-SELECT ad, yas FROM Tablo1 INNER JOIN Tablo2 ON Tablo1.ad = Tablo2.soyad;
-
--- OUTER JOIN
--- Outer join iki tablodaki ortak kolon değerlerinin dışında kalanları kullanarak bir sonuç üretir.
-SELECT isci_num, isim, dept FROM Tablo1 LEFT OUTER JOIN Tablo2 ON Tablo1.id = Tablo2.isci_num;
-
--- ÇEKİRDEK FONKSİYONLAR
-COUNT -- Sayma
-AVG -- Ortalama
-ABS -- Mutlak değer
-SUM -- Toplam
-RANDOM -- Rastgele
-ROUND -- Yuvarlama
-MAX -- Maksimim
-MIN -- Minimum
-UPPER -- Büyük Harf
-LOWER -- Küçük Harf
-LENGTH -- Uzunluk
-CURRENT_TIMESTAMP -- Zaman
-
-SELECT max(yas) FROM Table1;
-SELECT min(yas) FROM Table1;
-SELECT avg(yas) FROM Table1;
-SELECT * From Table1 WHERE yas ==18;
-SELECT sum(yas) FROM Table1;
-SELECT random() AS Random;
-SELECT upper(ad) FROM Table1;
-SELECT lower(ad) FROM Table1;
-SELECT ad, length(ad) FROM Table1;
+---
+language: SQL
+contributors:
+ - ["Metin Yalçınkaya", "https://github.com/mtnylnky"]
+lang: tr-tr
+filename: learnsql-tr.sql
+---
+
+
+```sql
+-- Yorumlar iki tire ile başlar
+
+-- KISITLAR
+Not null -- Bir kolon asla boş olamaz
+default -- Boş olan yerlere varsayılan bir değer atar
+unique -- Bir kolondaki tüm değerlerin farklı olması kısıtlaması
+primary key -- Bir tablodaki her veri için kimlik bilgisi niteliğindedir
+check -- Bir kolondaki değerlerin belli bir kısıtlamayı sağlamasını sağlar
+
+-- Tablo oluşturulur
+CREATE TABLE tablo1 ();
+
+-- Tabloyu içerisinde kolonlar ile oluşturma
+CREATE TABLE tablo1(id INTEGER PRIMARY KEY NOT NULL UNIQUE, ad TEXT, soyad TEXT, yas INTEGER);
+
+-- TABLO varlığını kontrol eder
+.table
+
+-- Veri tabanında olan bütün tabloları görüntüler.
+.schema
+
+-- Satır ekle
+INSERT INTO tablo1 ( ad, soyad) VALUES ("Deger1","Deger2");
+
+-- Veritabanında tablo üzerindeki verileri görüntüle
+-- Sadece 'ad' gibi sınırlı bir veri için
+SELECT ad FROM tablo1;
+-- Bütün veriler için
+SELECT * FROM tablo1;
+
+-- Veri güncelleme
+UPDATE tablo1 SET ad = "deger1-2"; WHERE name = "Deger1";
+
+-- Satır sil
+DELETE FROM tablo1 WHERE id = 1;
+DELETE FROM tablo1 WHERE ad = "Deger1" OR ad = "Deger2";
+
+-- Tabloya sonradan kolon ekleme
+ALTER TABLE tablo1 ADD COLUMN email TEXT;
+
+-- Tablodaki kolon adı değiştirme
+EXEC sp_rename ' tablo1.[ad]', Ad, 'COLUMN';
+
+-- Tablo adı değiştirme
+ALTER TABLE table1 RENAME TO Table1;
+
+-- Tabloyu silme
+DROP TABLE Table1;
+
+-- BİR TABLOYU BAŞKA TABLO KULLANARAK DOLDURMAK
+INSERT INTO Tablo2 SELECT id,ad, soyad, email from Tablo1;
+
+-- LIKE KOMUTU
+-- Belirli bir kritere göre arama yaparken kullanılır
+-- Adı 'A' ile başlayan veriler
+SELECT * FROM tablo1 WHERE adi LIKE "A%";
+-- İçinde 'A' olan veriler
+SELECT * FROM tablo1 WHERE adi LIKE "%A%";
+
+-- LIMIT KOMUTU
+-- Gösterilen satır sayısını sınırlamak için
+SELECT * FROM Tablo1 LIMIT 6;
+-- Gösterilen satırları belirli bir noktadan başlamak üzere sınırlamak için
+SELECT * FROM Tablo1 LIMIT 6 OFFSET 3;
+
+-- ORDER BY KOMUTU
+-- Herhangi bir kolona göre gösterilen değerleri azalan veya artan şekilde sıralamak için
+SELECT kolon FROM tablo1 WHERE yas ORDER BY column1, column2, .. columnN] [ASC | DESC];
+SELECT * FROM Tablo1 ORDER BY yas ASC
+SELECT * FROM Tablo1 ORDER BY yas DESC
+
+-- DISTINCT ANAHTAR SÖZCÜĞÜ
+-- Bu anahtar sözcükle sadece farklı değerler gösterilir.
+SELECT DISTINCT yas FROM tablo1;
+
+-- JOIN KOMUTU
+-- CROSS JOIN
+-- Cross join bir tablodaki her satırı ikinci tablodaki bir satır ile eşleştirmek için kulanılır.
+-- Eğer birinci tabloda x satır ikinci tabloda y satır varsa sonuçta x*y satır olur.
+SELECT ... FROM table1 CROSS JOIN table2 …
+SELECT ad, yas FROM Tablo1 CROSS JOIN Tablo2;
+
+-- INNER JOIN
+-- Inner join iki tablodaki ortak kolon değerlerini kullanarak bir sonuç üretir.
+SELECT ... FROM table1 [INNER] JOIN table2 ON conditional_expression …
+SELECT ad, yas FROM Tablo1 INNER JOIN Tablo2 ON Tablo1.ad = Tablo2.soyad;
+
+-- OUTER JOIN
+-- Outer join iki tablodaki ortak kolon değerlerinin dışında kalanları kullanarak bir sonuç üretir.
+SELECT isci_num, isim, dept FROM Tablo1 LEFT OUTER JOIN Tablo2 ON Tablo1.id = Tablo2.isci_num;
+
+-- ÇEKİRDEK FONKSİYONLAR
+COUNT -- Sayma
+AVG -- Ortalama
+ABS -- Mutlak değer
+SUM -- Toplam
+RANDOM -- Rastgele
+ROUND -- Yuvarlama
+MAX -- Maksimim
+MIN -- Minimum
+UPPER -- Büyük Harf
+LOWER -- Küçük Harf
+LENGTH -- Uzunluk
+CURRENT_TIMESTAMP -- Zaman
+
+SELECT max(yas) FROM Table1;
+SELECT min(yas) FROM Table1;
+SELECT avg(yas) FROM Table1;
+SELECT * From Table1 WHERE yas ==18;
+SELECT sum(yas) FROM Table1;
+SELECT random() AS Random;
+SELECT upper(ad) FROM Table1;
+SELECT lower(ad) FROM Table1;
+SELECT ad, length(ad) FROM Table1;
``` \ No newline at end of file
diff --git a/tr-tr/swift-tr.html.markdown b/tr-tr/swift-tr.html.markdown
index 4c2cf59b..29df93ef 100644
--- a/tr-tr/swift-tr.html.markdown
+++ b/tr-tr/swift-tr.html.markdown
@@ -9,7 +9,7 @@ lang: tr-tr
Swift iOS ve OSX platformlarında geliştirme yapmak için Apple tarafından oluşturulan yeni bir programlama dilidir. Objective - C ile beraber kullanılabilecek ve de hatalı kodlara karşı daha esnek bir yapı sunacak bir şekilde tasarlanmıştır. Swift 2014 yılında Apple'ın geliştirici konferansı WWDC de tanıtıldı. Xcode 6+'a dahil edilen LLVM derleyici ile geliştirildi.
-Apple'ın resmi [Swift Programlama Dili](https://itunes.apple.com/us/book/swift-programming-language/id881256329) kitabı iBooks'ta yerini aldı.
+Apple'ın resmi [Swift Programlama Dili](https://itunes.apple.com/us/book/swift-programming-language/id881256329) kitabı Apple Books'ta yerini aldı.
Ayrıca Swift ile gelen tüm özellikleri görmek için Apple'ın [başlangıç kılavuzu](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html)na bakmanızda yarar var.
diff --git a/uk-ua/bash-ua.html.markdown b/uk-ua/bash-ua.html.markdown
index c6e9ebb1..9375d5f3 100644
--- a/uk-ua/bash-ua.html.markdown
+++ b/uk-ua/bash-ua.html.markdown
@@ -19,7 +19,7 @@ lang: uk-ua
Bash - командна оболонка unix (unix shell), що також розповсюджувалась як оболонка для
операційної системи GNU і зараз використовується як командна оболонка за замовчуванням
-для Linux i Max OS X.
+для Linux i Mac OS X.
Майже всі приклади, що наведені нижче можуть бути частиною shell-скриптів або
виконані в оболонці
@@ -52,9 +52,9 @@ VARIABLE= 'Просто рядок'
# виконання команди 'Просто рядок')
# Використання змінних:
-echo $VARIABLE
-echo "$VARIABLE"
-echo '$VARIABLE'
+echo $VARIABLE # Просто рядок
+echo "$VARIABLE" # Просто рядок
+echo '$VARIABLE' # $VARIABLE
# Коли ви використовуєте змінну - присвоюєте значення, експортуєте і т.д. -
# пишіть її імя без $. А для отримання значення змінної використовуйте $.
# Одинарні лапки ' не розкривають значення змінних
@@ -96,12 +96,12 @@ else
echo "Ім’я збігаєтьяс з іменем користувача"
fi
-# Зауважте! якщо $Name пуста, bash інтерпретує код вище як:
+# Зауважте! якщо $NAME пуста, bash інтерпретує код вище як:
if [ -ne $USER ]
# що є неправильним синтаксисом
# тому безпечний спосіб використання потенційно пустих змінних має вигляд:
-if [ "$Name" -ne $USER ] ...
-# коли $Name пуста, інтерпретується наступним чином:
+if [ "$NAME" -ne $USER ] ...
+# коли $NAME пуста, інтерпретується наступним чином:
if [ "" -ne $USER ] ...
# що працює як і очікувалося
@@ -205,7 +205,7 @@ do
echo $a
done
-# Цикл for можно використати, щоб виконувати дії над файлами.
+# Цикл for можна використати, щоб виконувати дії над файлами.
# Цей код запустить команду 'cat' для файлів file1 и file2
for VARIABLE in file1 file2
do
@@ -259,12 +259,12 @@ uniq -d file.txt
cut -d ',' -f 1 file.txt
# замінити кожне 'okay' на 'great' у файлі file.txt (підтримується regex)
sed -i 's/okay/great/g' file.txt
-# вивести в stdout всі рядки з file.txt, що задовольняють шаблону regex;
+# вивести в stdout всі рядки з file.txt, що відповідають шаблону regex;
# цей приклад виводить рядки, що починаються на foo і закінчуються на bar:
grep "^foo.*bar$" file.txt
# використайте опцію -c, щоб вивести кількість входжень
grep -c "^foo.*bar$" file.txt
-# щоб здійснити пошук по рядку, а не по шаблону regex, використовуйте fgrea (або grep -F)
+# щоб здійснити пошук по рядку, а не по шаблону regex, використовуйте fgrep (або grep -F)
fgrep "^foo.*bar$" file.txt
# Читайте вбудовану документацію Bash командою 'help':
diff --git a/vala.html.markdown b/vala.html.markdown
index 739e0fda..739e0fda 100755..100644
--- a/vala.html.markdown
+++ b/vala.html.markdown
diff --git a/vi-vn/git-vi.html.markdown b/vi-vn/git-vi.html.markdown
index f5454ebf..47485bd9 100644
--- a/vi-vn/git-vi.html.markdown
+++ b/vi-vn/git-vi.html.markdown
@@ -1,328 +1,328 @@
----
-category: tool
-tool: git
-contributors:
+---
+category: tool
+tool: git
+contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
- - ["Vinh Nguyen", "https://twitter.com/vinhnx"]
-filename: LearnGit-vi.txt
-lang: vi-vn
----
-
-Git là một hệ quản lý mã nguồn và phiên bản phân tán (distributed version control and source code management system).
-
-Nó làm được điều này là do một loạt các snapshot từ đề án của bạn, và nó hoạt động
-với các snapshot đó để cung cấp cho bạn với chức năng đến phiên bản và
-quản lý mã nguồn của bạn.
-
-## Khái Niệm Versioning
-
-### Version Control là gì?
-
-Version Control là một hệ thống ghi lại những thay đổi ở một tập tin, hay một nhóm các tập tin, theo thời gian.
-
-### So sánh giữa Centralized Versioning và Distributed Versioning
-
-* Quản lý phiên bản tập trung (Centralized Versioning) tập trung vào việc đồng bộ hóa, theo dõi, và lưu trữ tập tin.
-* Quản lý phiên bản phân tán (Distributed Versioning) tập trung vào việc chia sẻ các thay đổi. Mỗi sự thay đổi có một mã định dạng (id) duy nhất.
-* Các hệ phân tán không có cấu trúc định sẵn. Bạn có thể thay đổi một kiểu SVN, hệ phân tán, với git.
-
-[Thông tin thêm](http://git-scm.com/book/en/Getting-Started-About-Version-Control)
-
-### Tại Sao Dùng Git?
-
-* Có thể hoạt động offline.
-* Cộng tác với nhau rất dễ dàng!
-* Phân nhánh dễ dàng!
-* Trộn (Merging)
-* Git nhanh.
-* Git linh hoạt.
-
-## Kiến Trúc Git
-
-
-### Repository
-
-Một nhóm các tập tin, thư mục, các ghi chép trong quá khứ, commit, và heads. Tưởng tượng nó như là một cấu trúc dữ liệu mã nguồn,
-với thuộc tính mà một "nhân tố" mã nguồn cho bạn quyền truy cập đến lịch sử sửa đổi, và một số thứ khác.
-
-Một git repository bao gồm thư mục .git & tree đang làm việc.
-
-### Thư mục .git (thành phần của một repository)
-
-Thư mục .git chứa tất cả các cấu hình, log, nhánh, HEAD, và hơn nữa.
-[Danh Sách Chi Tiết.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html)
-
-### Tree Đang Làm (thành phần của một repository)
-
-Đây cơ bản là các thư mục và tập tin trong repository của bạn. Nó thường được tham chiếu
-thư mục đang làm việc của bạn
-
-### Chỉ mục (thành phần của một thư mục .git)
-
-Chỉ mục của là một staging area trong git. Nó đơn giản là một lớp riêng biệt với tree đang làm việc của bạn
-từ Git repository. Điều này cho nhà phát triền nhiều lựa chọn hơn trong việc xem xét những gì được gửi đến Git
-repository.
-
-### Commit
-
-Một git commit là một snapshot của một nhóm các thay đổi, hoặc các thao tác Working Tree của bạn.
-Ví dụ, nếu bạn thêm 5 tập tin, và xóa 2 tập tin khác, những thay đổi này sẽ được chứa trong
-một commit (hoặc snapshot). Commit này có thể được đẩy đến các repo khác, hoặc không!
-
-### Nhánh
-
-Nhánh thực chất là một con trỏ đến commit mới nhất mà bạn vừa thực hiện. Khi bạn commit,
-con trỏ này sẽ cập nhật tự động và trỏ đến commit mới nhất.
-
-### HEAD và head (thành phần của thư mục .git)
-
-HEAD là một con trỏ đến branch hiện tại. Một repo chỉ có một HEAD *đang hoạt động*.
-head là một con trỏ đến bất kỳ commit nào. Một repo có thể có nhiều head.
-
-### Các Tài Nguyên Mang Tính Khái Niệm
-
-* [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/)
-* [Git For Designers](http://hoth.entp.com/output/git_for_designers.html)
-
-
-## Các Lệnh
-
-
-### init
-
-Tạo một repo Git rỗng. Các cài đặt, thông tin lưu trữ... của Git
-được lưu ở một thư mục tên là ".git".
-
-```bash
-$ git init
-```
-
-### config
-
-Để chỉnh tùy chọn. Bất kể là cho repo, hay cho hệ thống, hay điều chỉnh
-toàn cục (global)
-
-
-
-```bash
-# In Ra & Và Gán Một Số Biến Tùy Chỉnh Cơ Bản (Toàn cục - Global)
-$ git config --global user.email
-$ git config --global user.name
-
-$ git config --global user.email "MyEmail@Zoho.com"
-$ git config --global user.name "My Name"
-```
-
-[Tìm hiểu thêm về git config.](http://git-scm.com/docs/git-config)
-
-### help
-
-Để cho bạn lối truy cập nhanh đến một chỉ dẫn cực kỳ chi tiết của từng lệnh. Hoặc chỉ để
-nhắc bạn một số cú pháp.
-
-```bash
-# Xem nhanh các lệnh có sẵn
-$ git help
-
-# Xem tất các các lệnh
-$ git help -a
-
-# Lệnh help riêng biệt - tài liệu người dùng
-# git help <command_here>
-$ git help add
-$ git help commit
-$ git help init
-```
-
-### status
-
-Để hiển thị sự khác nhau giữa tập tin index (cơ bản là repo đang làm việc) và HEAD commit
-hiện tại.
-
-
-```bash
-# Sẽ hiển thị nhánh, các tập tin chưa track (chưa commit), các thay đổi và những khác biệt khác
-$ git status
-
-# Để xem các "tid bits" về git status
-$ git help status
-```
-
-### add
-
-Để thêm các tập vào tree/thư mục/repo hiện tại. Nếu bạn không `git add` các tập tin mới đến
-tree/thư mục hiện tại, chúng sẽ không được kèm theo trong các commit!
-
-```bash
-# thêm một file vào thư mục hiện tại
-$ git add HelloWorld.java
-
-# thêm một file vào một thư mục khác
-$ git add /path/to/file/HelloWorld.c
-
-# Hỗ trợ Regular Expression!
-$ git add ./*.java
-```
-
-### branch
-
-Quản lý nhánh (branch). Bạn có thể xem, sửa, tạo, xóa các nhánh bằng cách dùng lệnh này.
-
-```bash
-# liệt kê các branch đang có và ở remote
-$ git branch -a
-
-# tạo branch mới
-$ git branch myNewBranch
-
-# xóa một branch
-$ git branch -d myBranch
-
-# đặt tên lại một branch
-# git branch -m <oldname> <newname>
-$ git branch -m myBranchName myNewBranchName
-
-# chỉnh sửa diễn giải của một branch
-$ git branch myBranchName --edit-description
-```
-
-### checkout
-
-Cập nhật tất cả các file trong tree hiện tại để cho trùng khớp với phiên bản của index, hoặc tree cụ thể.
-
-```bash
-# Checkout (chuyển) một repo - mặc định là nhánh master
-$ git checkout
-# Checkout một nhánh cụ thể
-$ git checkout branchName
-# Tạo một nhánh mới và chuyển đến nó, tương tự: "git branch <name>; git checkout <name>"
-$ git checkout -b newBranch
-```
-
-### clone
-
-Nhân bản, hoặc sao chép, một repo hiện có thành một thư mục mới. Nó cũng thêm
-các branch có remote-tracking cho mỗi branch trong một repo được nhân bản, mà
-cho phép bạn push đến một remote branch.
-
-```bash
-# Nhân bản learnxinyminutes-docs
-$ git clone https://github.com/adambard/learnxinyminutes-docs.git
-```
-
-### commit
-
-Lưu trữ nội dung hiện tại của index trong một "commit" mới. Điều này cho phép tạo ra thay đổi và một ghi chú tạo ra bởi người dùng.
-
-```bash
-# commit với một ghi chú
-$ git commit -m "Added multiplyNumbers() function to HelloWorld.c"
-```
-
-### diff
-
-Hiển thị sự khác biệt giữa một file trong thư mục hiện tại, index và commits.
-
-```bash
-# Hiển thị sự khác biệt giữa thư mục hiện tại và index
-$ git diff
-
-# Hiển thị khác biệt giữa index và commit mới nhất.
-$ git diff --cached
-
-# Hiển thị khác biệt giữa thư mục đang làm việc và commit mới nhất
-$ git diff HEAD
-```
-
-### grep
-
-Cho phép bạn tìm kiếm nhanh một repo.
-
-Các tinh chỉnh tùy chọn:
-
-```bash
-# Cảm ơn Travis Jeffery vì những lệnh này
-# Đặt số của dòng được hiển thị trong kết quả tìm kiếm grep
-$ git config --global grep.lineNumber true
-
-# Làm cho kết quả tìm kiếm dễ đọc hơn, bao gồm cả gom nhóm
-$ git config --global alias.g "grep --break --heading --line-number"
-```
-
-```bash
-# Tìm "variableName" trong tất cả các file Java
-$ git grep 'variableName' -- '*.java'
-
-# Tìm một dòng mà có chứa "arrayListName" và, "add" hoặc "remove"
-$ git grep -e 'arrayListName' --and \( -e add -e remove \)
-```
-
-Google để xem thêm các ví dụ
-[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja)
-
-### log
-
-Hiển thị các commit đến repo.
-
-```bash
-# Hiện tất cả các commit
-$ git log
-
-# Hiện X commit
-$ git log -n 10
-
-# Chỉ hiện các commit đã merge merge commits
-$ git log --merges
-```
-
-### merge
-
-"Trộn" các thay đổi từ commit bên ngoài vào trong nhánh hiện tại.
-
-```bash
-# Merge branch cụ thể vào branch hiện tại.
-$ git merge branchName
-
-# Luôn khởi tạo một merge commit khi trộn (merge)
-$ git merge --no-ff branchName
-```
-
-### mv
-
-Đặt lại tên hoặc di chuyển một file
-
-```bash
-# Đặt lại tên một file
-$ git mv HelloWorld.c HelloNewWorld.c
-
-# Di chuyển một file
-$ git mv HelloWorld.c ./new/path/HelloWorld.c
-
-# Buộc đặt lại tên hoặc di chuyển
-# "existingFile" đã tồn tại trong thự mục, sẽ bị ghi đè
-$ git mv -f myFile existingFile
-```
-
-### pull
-
-Pull về từ một repo và merge nó vào branch khác.
-
-```bash
-# Cập nhật repo local của bạn, bằng cách merge các thay đổi mới
-# từ remote "origin" và nhánh "master".
-# git pull <remote> <branch>
-# git pull => hoàn toàn mặc định như => git pull origin master
-$ git pull origin master
-
-# Merge các thay đổi từ remote branch và rebase
-# các commit trong branch lên trên local repo, như sau: "git pull <remote> <branch>, git rebase <branch>"
-$ git pull origin master --rebase
-```
-
-### push
-
-push và merge các thay đổi từ một branch đến một remote & branch.
-
+ - ["Vinh Nguyen", "https://twitter.com/vinhnx"]
+filename: LearnGit-vi.txt
+lang: vi-vn
+---
+
+Git là một hệ quản lý mã nguồn và phiên bản phân tán (distributed version control and source code management system).
+
+Nó làm được điều này là do một loạt các snapshot từ đề án của bạn, và nó hoạt động
+với các snapshot đó để cung cấp cho bạn với chức năng đến phiên bản và
+quản lý mã nguồn của bạn.
+
+## Khái Niệm Versioning
+
+### Version Control là gì?
+
+Version Control là một hệ thống ghi lại những thay đổi ở một tập tin, hay một nhóm các tập tin, theo thời gian.
+
+### So sánh giữa Centralized Versioning và Distributed Versioning
+
+* Quản lý phiên bản tập trung (Centralized Versioning) tập trung vào việc đồng bộ hóa, theo dõi, và lưu trữ tập tin.
+* Quản lý phiên bản phân tán (Distributed Versioning) tập trung vào việc chia sẻ các thay đổi. Mỗi sự thay đổi có một mã định dạng (id) duy nhất.
+* Các hệ phân tán không có cấu trúc định sẵn. Bạn có thể thay đổi một kiểu SVN, hệ phân tán, với git.
+
+[Thông tin thêm](http://git-scm.com/book/en/Getting-Started-About-Version-Control)
+
+### Tại Sao Dùng Git?
+
+* Có thể hoạt động offline.
+* Cộng tác với nhau rất dễ dàng!
+* Phân nhánh dễ dàng!
+* Trộn (Merging)
+* Git nhanh.
+* Git linh hoạt.
+
+## Kiến Trúc Git
+
+
+### Repository
+
+Một nhóm các tập tin, thư mục, các ghi chép trong quá khứ, commit, và heads. Tưởng tượng nó như là một cấu trúc dữ liệu mã nguồn,
+với thuộc tính mà một "nhân tố" mã nguồn cho bạn quyền truy cập đến lịch sử sửa đổi, và một số thứ khác.
+
+Một git repository bao gồm thư mục .git & tree đang làm việc.
+
+### Thư mục .git (thành phần của một repository)
+
+Thư mục .git chứa tất cả các cấu hình, log, nhánh, HEAD, và hơn nữa.
+[Danh Sách Chi Tiết.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html)
+
+### Tree Đang Làm (thành phần của một repository)
+
+Đây cơ bản là các thư mục và tập tin trong repository của bạn. Nó thường được tham chiếu
+thư mục đang làm việc của bạn
+
+### Chỉ mục (thành phần của một thư mục .git)
+
+Chỉ mục của là một staging area trong git. Nó đơn giản là một lớp riêng biệt với tree đang làm việc của bạn
+từ Git repository. Điều này cho nhà phát triền nhiều lựa chọn hơn trong việc xem xét những gì được gửi đến Git
+repository.
+
+### Commit
+
+Một git commit là một snapshot của một nhóm các thay đổi, hoặc các thao tác Working Tree của bạn.
+Ví dụ, nếu bạn thêm 5 tập tin, và xóa 2 tập tin khác, những thay đổi này sẽ được chứa trong
+một commit (hoặc snapshot). Commit này có thể được đẩy đến các repo khác, hoặc không!
+
+### Nhánh
+
+Nhánh thực chất là một con trỏ đến commit mới nhất mà bạn vừa thực hiện. Khi bạn commit,
+con trỏ này sẽ cập nhật tự động và trỏ đến commit mới nhất.
+
+### HEAD và head (thành phần của thư mục .git)
+
+HEAD là một con trỏ đến branch hiện tại. Một repo chỉ có một HEAD *đang hoạt động*.
+head là một con trỏ đến bất kỳ commit nào. Một repo có thể có nhiều head.
+
+### Các Tài Nguyên Mang Tính Khái Niệm
+
+* [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/)
+* [Git For Designers](http://hoth.entp.com/output/git_for_designers.html)
+
+
+## Các Lệnh
+
+
+### init
+
+Tạo một repo Git rỗng. Các cài đặt, thông tin lưu trữ... của Git
+được lưu ở một thư mục tên là ".git".
+
+```bash
+$ git init
+```
+
+### config
+
+Để chỉnh tùy chọn. Bất kể là cho repo, hay cho hệ thống, hay điều chỉnh
+toàn cục (global)
+
+
+
+```bash
+# In Ra & Và Gán Một Số Biến Tùy Chỉnh Cơ Bản (Toàn cục - Global)
+$ git config --global user.email
+$ git config --global user.name
+
+$ git config --global user.email "MyEmail@Zoho.com"
+$ git config --global user.name "My Name"
+```
+
+[Tìm hiểu thêm về git config.](http://git-scm.com/docs/git-config)
+
+### help
+
+Để cho bạn lối truy cập nhanh đến một chỉ dẫn cực kỳ chi tiết của từng lệnh. Hoặc chỉ để
+nhắc bạn một số cú pháp.
+
+```bash
+# Xem nhanh các lệnh có sẵn
+$ git help
+
+# Xem tất các các lệnh
+$ git help -a
+
+# Lệnh help riêng biệt - tài liệu người dùng
+# git help <command_here>
+$ git help add
+$ git help commit
+$ git help init
+```
+
+### status
+
+Để hiển thị sự khác nhau giữa tập tin index (cơ bản là repo đang làm việc) và HEAD commit
+hiện tại.
+
+
+```bash
+# Sẽ hiển thị nhánh, các tập tin chưa track (chưa commit), các thay đổi và những khác biệt khác
+$ git status
+
+# Để xem các "tid bits" về git status
+$ git help status
+```
+
+### add
+
+Để thêm các tập vào tree/thư mục/repo hiện tại. Nếu bạn không `git add` các tập tin mới đến
+tree/thư mục hiện tại, chúng sẽ không được kèm theo trong các commit!
+
+```bash
+# thêm một file vào thư mục hiện tại
+$ git add HelloWorld.java
+
+# thêm một file vào một thư mục khác
+$ git add /path/to/file/HelloWorld.c
+
+# Hỗ trợ Regular Expression!
+$ git add ./*.java
+```
+
+### branch
+
+Quản lý nhánh (branch). Bạn có thể xem, sửa, tạo, xóa các nhánh bằng cách dùng lệnh này.
+
+```bash
+# liệt kê các branch đang có và ở remote
+$ git branch -a
+
+# tạo branch mới
+$ git branch myNewBranch
+
+# xóa một branch
+$ git branch -d myBranch
+
+# đặt tên lại một branch
+# git branch -m <oldname> <newname>
+$ git branch -m myBranchName myNewBranchName
+
+# chỉnh sửa diễn giải của một branch
+$ git branch myBranchName --edit-description
+```
+
+### checkout
+
+Cập nhật tất cả các file trong tree hiện tại để cho trùng khớp với phiên bản của index, hoặc tree cụ thể.
+
+```bash
+# Checkout (chuyển) một repo - mặc định là nhánh master
+$ git checkout
+# Checkout một nhánh cụ thể
+$ git checkout branchName
+# Tạo một nhánh mới và chuyển đến nó, tương tự: "git branch <name>; git checkout <name>"
+$ git checkout -b newBranch
+```
+
+### clone
+
+Nhân bản, hoặc sao chép, một repo hiện có thành một thư mục mới. Nó cũng thêm
+các branch có remote-tracking cho mỗi branch trong một repo được nhân bản, mà
+cho phép bạn push đến một remote branch.
+
+```bash
+# Nhân bản learnxinyminutes-docs
+$ git clone https://github.com/adambard/learnxinyminutes-docs.git
+```
+
+### commit
+
+Lưu trữ nội dung hiện tại của index trong một "commit" mới. Điều này cho phép tạo ra thay đổi và một ghi chú tạo ra bởi người dùng.
+
+```bash
+# commit với một ghi chú
+$ git commit -m "Added multiplyNumbers() function to HelloWorld.c"
+```
+
+### diff
+
+Hiển thị sự khác biệt giữa một file trong thư mục hiện tại, index và commits.
+
+```bash
+# Hiển thị sự khác biệt giữa thư mục hiện tại và index
+$ git diff
+
+# Hiển thị khác biệt giữa index và commit mới nhất.
+$ git diff --cached
+
+# Hiển thị khác biệt giữa thư mục đang làm việc và commit mới nhất
+$ git diff HEAD
+```
+
+### grep
+
+Cho phép bạn tìm kiếm nhanh một repo.
+
+Các tinh chỉnh tùy chọn:
+
+```bash
+# Cảm ơn Travis Jeffery vì những lệnh này
+# Đặt số của dòng được hiển thị trong kết quả tìm kiếm grep
+$ git config --global grep.lineNumber true
+
+# Làm cho kết quả tìm kiếm dễ đọc hơn, bao gồm cả gom nhóm
+$ git config --global alias.g "grep --break --heading --line-number"
+```
+
+```bash
+# Tìm "variableName" trong tất cả các file Java
+$ git grep 'variableName' -- '*.java'
+
+# Tìm một dòng mà có chứa "arrayListName" và, "add" hoặc "remove"
+$ git grep -e 'arrayListName' --and \( -e add -e remove \)
+```
+
+Google để xem thêm các ví dụ
+[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja)
+
+### log
+
+Hiển thị các commit đến repo.
+
+```bash
+# Hiện tất cả các commit
+$ git log
+
+# Hiện X commit
+$ git log -n 10
+
+# Chỉ hiện các commit đã merge merge commits
+$ git log --merges
+```
+
+### merge
+
+"Trộn" các thay đổi từ commit bên ngoài vào trong nhánh hiện tại.
+
+```bash
+# Merge branch cụ thể vào branch hiện tại.
+$ git merge branchName
+
+# Luôn khởi tạo một merge commit khi trộn (merge)
+$ git merge --no-ff branchName
+```
+
+### mv
+
+Đặt lại tên hoặc di chuyển một file
+
+```bash
+# Đặt lại tên một file
+$ git mv HelloWorld.c HelloNewWorld.c
+
+# Di chuyển một file
+$ git mv HelloWorld.c ./new/path/HelloWorld.c
+
+# Buộc đặt lại tên hoặc di chuyển
+# "existingFile" đã tồn tại trong thự mục, sẽ bị ghi đè
+$ git mv -f myFile existingFile
+```
+
+### pull
+
+Pull về từ một repo và merge nó vào branch khác.
+
+```bash
+# Cập nhật repo local của bạn, bằng cách merge các thay đổi mới
+# từ remote "origin" và nhánh "master".
+# git pull <remote> <branch>
+# git pull => hoàn toàn mặc định như => git pull origin master
+$ git pull origin master
+
+# Merge các thay đổi từ remote branch và rebase
+# các commit trong branch lên trên local repo, như sau: "git pull <remote> <branch>, git rebase <branch>"
+$ git pull origin master --rebase
+```
+
+### push
+
+push và merge các thay đổi từ một branch đến một remote & branch.
+
```bash
# Push và merge các thay đổi từ một repo local đến một
# remote có tên là "origin" và nhánh "master".
@@ -334,68 +334,68 @@ $ git push origin master
$ git push -u origin master
# Từ lúc này, bất cứ khi nào bạn muốn push từ cùng một nhánh local đó, sử dụng lối tắt:
$ git push
-```
-
-### rebase (thận trọng)
-
-Lấy tất cả các thay đổi mà đã được commit trên một nhánh, và replay (?) chúng trên một nhánh khác.
-*Không rebase các commit mà bạn đã push đến một repo công khai*.
-
-```bash
-# Rebase experimentBranch lên master
-# git rebase <basebranch> <topicbranch>
-$ git rebase master experimentBranch
-```
-
-[Đọc Thêm.](http://git-scm.com/book/en/Git-Branching-Rebasing)
-
-### reset (thận trọng)
-
-Thiết lập lạo HEAD hiện tại đến một trạng thái cụ thể. Điều này cho phép bạn làm lại các merges,
-pulls, commits, thêm, and hơn nữa. Nó là một lệnh hay nhưng cũng nguy hiểm nếu bạn không
-biết mình đang làm gì.
-
-```bash
-# Thiết lập lại staging area, để trùng với commit mới nhất (để thư mục không thay đổi)
-$ git reset
-
-# Thiết lập lại staging area, để trùng với commit mới nhất, và ghi đè lên thư mục hiện tại
-$ git reset --hard
-
-# Di chuyển nhánh hiện tại đến một commit cụ thể (để thư mục không thay đổi)
-# tất cả thay đổi vẫn duy trì trong thư mục.
-$ git reset 31f2bb1
-
-# Di chuyển nhánh hiện tại lùi về một commit cụ thể
-# và làm cho thư mục hiện tại trùng (xóa các thay đổi chưa được commit và tất cả các commit
-# sau một commit cụ thể).
-$ git reset --hard 31f2bb1
-```
-
-### rm
-
-Ngược lại với git add, git rm xóa file từ tree đang làm việc.
-
-```bash
-# xóa HelloWorld.c
-$ git rm HelloWorld.c
-
-# Xóa file từ thư mục khác
-$ git rm /pather/to/the/file/HelloWorld.c
-```
-
-## Thông tin thêm
-
-* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1)
-
-* [git-scm - Video Tutorials](http://git-scm.com/videos)
-
-* [git-scm - Documentation](http://git-scm.com/docs)
-
-* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/)
-
-* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-
+```
+
+### rebase (thận trọng)
+
+Lấy tất cả các thay đổi mà đã được commit trên một nhánh, và replay (?) chúng trên một nhánh khác.
+*Không rebase các commit mà bạn đã push đến một repo công khai*.
+
+```bash
+# Rebase experimentBranch lên master
+# git rebase <basebranch> <topicbranch>
+$ git rebase master experimentBranch
+```
+
+[Đọc Thêm.](http://git-scm.com/book/en/Git-Branching-Rebasing)
+
+### reset (thận trọng)
+
+Thiết lập lạo HEAD hiện tại đến một trạng thái cụ thể. Điều này cho phép bạn làm lại các merges,
+pulls, commits, thêm, and hơn nữa. Nó là một lệnh hay nhưng cũng nguy hiểm nếu bạn không
+biết mình đang làm gì.
+
+```bash
+# Thiết lập lại staging area, để trùng với commit mới nhất (để thư mục không thay đổi)
+$ git reset
+
+# Thiết lập lại staging area, để trùng với commit mới nhất, và ghi đè lên thư mục hiện tại
+$ git reset --hard
+
+# Di chuyển nhánh hiện tại đến một commit cụ thể (để thư mục không thay đổi)
+# tất cả thay đổi vẫn duy trì trong thư mục.
+$ git reset 31f2bb1
+
+# Di chuyển nhánh hiện tại lùi về một commit cụ thể
+# và làm cho thư mục hiện tại trùng (xóa các thay đổi chưa được commit và tất cả các commit
+# sau một commit cụ thể).
+$ git reset --hard 31f2bb1
+```
+
+### rm
+
+Ngược lại với git add, git rm xóa file từ tree đang làm việc.
+
+```bash
+# xóa HelloWorld.c
+$ git rm HelloWorld.c
+
+# Xóa file từ thư mục khác
+$ git rm /pather/to/the/file/HelloWorld.c
+```
+
+## Thông tin thêm
+
+* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1)
+
+* [git-scm - Video Tutorials](http://git-scm.com/videos)
+
+* [git-scm - Documentation](http://git-scm.com/docs)
+
+* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/)
+
+* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
+
* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html)
-
+
diff --git a/vi-vn/markdown-vi.html.markdown b/vi-vn/markdown-vi.html.markdown
index 89b59253..696fe465 100644
--- a/vi-vn/markdown-vi.html.markdown
+++ b/vi-vn/markdown-vi.html.markdown
@@ -48,6 +48,7 @@ bằng cách thêm số lượng dấu thăng (#) đằng trước chuỗi cần
##### Đây là đầu mục <h5>
###### Đây là đầu mục <h6>
```
+
Markdown còn cung cấp cách khác để tạo đầu mục hạng nhất h1 và hạng nhì h2.
```md
@@ -79,6 +80,7 @@ Trong cài đặt Markdown để hiển thị file của GitHub,ta còn có gạ
```md
~~Đoạn văn bản này được gạch ngang.~~
```
+
## Đoạn văn
Đoạn văn bao gồm một hay nhiều dòng văn bản liên tiếp nhau được phân cách
@@ -153,6 +155,7 @@ Ta không nhất thiết phải điền số thứ thự cho chỉ mục đúng
1. Mục thứ hai
1. Mục thứ ba
```
+
(Sẽ hiển thị như ví dụ trước đó)
Ta còn có thể sử dụng danh sách con
@@ -189,7 +192,7 @@ Ta còn có thể thêm dấu nhảy (hoặc thêm vào bốn dấu cách nữa)
```md
my_array.each do |item|
- puts item
+ puts item
end
```
@@ -201,12 +204,13 @@ John didn't even know what the `go_to()` function did!
Trong Markdown của GitHub, ta còn có thêm cách để hiển thị code:
-<pre>
-<code class="highlight">&#x60;&#x60;&#x60;ruby
+````md
+```ruby
def foobar
- puts "Hello world!"
+ puts "Hello world!"
end
-&#x60;&#x60;&#x60;</code></pre>
+```
+````
The above text doesn't require indenting, plus GitHub will use syntax
highlighting of the language you specify after the \`\`\`
@@ -231,11 +235,13 @@ Một trong những thứ tốt nhất khi làm việc với Markdown là khả
```md
[Click me!](http://test.com/)
```
+
Ta còn có thể tạo tiêu đề cho liên kết sử dụng cặp ngoặc nháy bên trong cặp ngoặc tròn
```md
[Click me!](http://test.com/ "Link to Test.com")
```
+
Đường dẫn tương đối cũng hoạt động.
```md
@@ -244,19 +250,23 @@ Ta còn có thể tạo tiêu đề cho liên kết sử dụng cặp ngoặc nh
Markdown còn hỗ trợ liên kết kiểu tham chiếu.
-<pre><code class="highlight">&#x5b;<span class="nv">Nhấn vào đây</span>][<span class="ss">link1</span>] để xem thêm!
-&#x5b;<span class="nv">Ngoài ra nhấn vào đây</span>][<span class="ss">foobar</span>] nếu bạn muốn xem qua.
+```md
+[Nhấn vào đây][link1] để xem thêm!
+[Ngoài ra nhấn vào đây][foobar] nếu bạn muốn xem qua.
-&#x5b;<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Tuyệt!"</span>
-&#x5b;<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Tốt!"</span></code></pre>
+[link1]: http://test.com/ "Tuyệt!"
+[foobar]: http://foobar.biz/ "Tốt!"
+```
Tiêu đề có thể được đóng trong dấu nháy hay ngoặc đơn, hoặc có thể được bỏ qua. Tham chiếu có thể được đặt bất kì đâu trong văn bản và ID của tham chiếu có thể là bất kì gì miễn là nó độc nhất.
Ngoài ra còn có kiểu đặt tên ngầm cho phép ta sử dụng đường dẫn làm ID.
-<pre><code class="highlight">&#x5b;<span class="nv">This</span>][] is a link.
+```md
+[This][] is a link.
-&#x5b;<span class="nv">this</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
+[this]: http://thisisalink.com/
+```
Nhưng nó không được sử dụng rộng rãi.
@@ -270,9 +280,11 @@ Hiển thị ảnh tương tự như liên kết nhưng có thêm dấu chấm t
Và kiểu tham chiếu cũng hoạt động như vậy.
-<pre><code class="highlight">!&#x5b;<span class="nv">Đây là thuộc tính alt.</span>][<span class="ss">myimage</span>]
+```md
+![Đây là thuộc tính alt.][myimage]
-&#x5b;<span class="nv">myimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"Đây là tiêu đề"</span></code></pre>
+[myimage]: relative/urls/cool/image.jpg "Đây là tiêu đề"
+```
## Khác
@@ -297,12 +309,13 @@ Khi ta muốn viết *đoạn văn bản này có dấu sao bao quanh* nhưng ta
### Phím bàn phím
-Trong Markdown của Github, ta có thể sử dụng thẻ `<kbd>` để thay cho phím trên bàn phím.
+Trong Markdown của GitHub, ta có thể sử dụng thẻ `<kbd>` để thay cho phím trên bàn phím.
```md
Máy treo? Thử bấm tổ hợp
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
```
+
### Bảng biểu
Bảng biểu được hỗ trợ trên Markdown của GitHub, Jira, Trello, v.v và khá khó viết:
@@ -313,6 +326,7 @@ Bảng biểu được hỗ trợ trên Markdown của GitHub, Jira, Trello, v.v
| Căn trái | Căn giữa | Căn phải |
| blah | blah | blah |
```
+
Hoặc có thể sử dụng kết quả dưới đây
```md
diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown
index 4656cf38..b01ce806 100644
--- a/vi-vn/objective-c-vi.html.markdown
+++ b/vi-vn/objective-c-vi.html.markdown
@@ -1,316 +1,316 @@
----
-language: Objective-C
-contributors:
- - ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
- - ["Yannick Loriot", "https://github.com/YannickL"]
-lang: vi-vn
-filename: LearnObjectiveC-vi.m
----
-
-Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành macOS, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch.
-Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C.
-
-```objective-c
-// Chú thích dòng đơn bắt đầu với //
-
-/*
-Chú thích đa dòng trông như thế này.
-*/
-
-// Nhập các headers của framework Foundation với cú pháp #import
-#import <Foundation/Foundation.h>
-#import "MyClass.h"
-
-// Đầu vào chương trình của bạn là một hàm gọi là
-// main với một kiểu trả về kiểu integer.
-int main (int argc, const char * argv[])
-{
- // Tạo một autorelease pool để quản lý bộ nhớ vào chương trình
- NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
-
- // Sử dụng hàm NSLog() để in ra các dòng lệnh vào console
- NSLog(@"Hello World!"); // Print the string "Hello World!"
-
- ///////////////////////////////////////
- // Kiểu & Biến (Types & Variables)
- ///////////////////////////////////////
-
- // Khai báo số nguyên
- int myPrimitive1 = 1;
- long myPrimitive2 = 234554664565;
-
- // Khai báo đối tượng
- // Đặt dấu nháy * vào trước tên biến cho khai báo đối tượng strong
- MyClass *myObject1 = nil; // Strong
- id myObject2 = nil; // Weak
- // %@ là một đối tượng
- // 'miêu tả' ('desciption') là thông lệ để trình bày giá trị của các Đối tượng
- NSLog(@"%@ và %@", myObject1, [myObject2 description]); // In ra "(null) và (null)"
-
- // Chuỗi
- NSString *worldString = @"World";
- NSLog(@"Hello %@!", worldString); // In ra "Hello World!"
-
- // Ký tự literals
- NSNumber *theLetterZNumber = @'Z';
- char theLetterZ = [theLetterZNumber charValue];
- NSLog(@"%c", theLetterZ);
-
- // Số nguyên literals
- NSNumber *fortyTwoNumber = @42;
- int fortyTwo = [fortyTwoNumber intValue];
- NSLog(@"%i", fortyTwo);
-
- NSNumber *fortyTwoUnsignedNumber = @42U;
- unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue];
- NSLog(@"%u", fortyTwoUnsigned);
-
- NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42];
- short fortyTwoShort = [fortyTwoShortNumber shortValue];
- NSLog(@"%hi", fortyTwoShort);
-
- NSNumber *fortyTwoLongNumber = @42L;
- long fortyTwoLong = [fortyTwoLongNumber longValue];
- NSLog(@"%li", fortyTwoLong);
-
- // Dấu phẩy động (floating point) literals
- NSNumber *piFloatNumber = @3.141592654F;
- float piFloat = [piFloatNumber floatValue];
- NSLog(@"%f", piFloat);
-
- NSNumber *piDoubleNumber = @3.1415926535;
- double piDouble = [piDoubleNumber doubleValue];
- NSLog(@"%f", piDouble);
-
- // BOOL literals
- NSNumber *yesNumber = @YES;
- NSNumber *noNumber = @NO;
-
- // Đối tượng Mảng
- NSArray *anArray = @[@1, @2, @3, @4];
- NSNumber *thirdNumber = anArray[2];
- NSLog(@"Third number = %@", thirdNumber); // In ra "Third number = 3"
-
- // Đối tượng Từ điển
- NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" };
- NSObject *valueObject = aDictionary[@"A Key"];
- NSLog(@"Đối tượng = %@", valueObject); // In ra "Object = (null)"
-
- ///////////////////////////////////////
- // Toán Tử (Operators)
- ///////////////////////////////////////
-
- // Các toán tử cũng hoạt động giống như ngôn ngữ C
- // Ví dụ:
- 2 + 5; // => 7
- 4.2f + 5.1f; // => 9.3f
- 3 == 2; // => 0 (NO)
- 3 != 2; // => 1 (YES)
- 1 && 1; // => 1 (Logical and)
- 0 || 1; // => 1 (Logical or)
- ~0x0F; // => 0xF0 (bitwise negation)
- 0x0F & 0xF0; // => 0x00 (bitwise AND)
- 0x01 << 1; // => 0x02 (bitwise dịch trái (bởi 1))
-
- /////////////////////////////////////////////
- // Cấu Trúc Điều Khiển (Controls Structures)
- /////////////////////////////////////////////
-
- // Câu lệnh If-Else
- if (NO)
- {
- NSLog(@"I am never run");
- } else if (0)
- {
- NSLog(@"I am also never run");
- } else
- {
- NSLog(@"I print");
- }
-
- // Câu lệnh Switch
- switch (2)
- {
- case 0:
- {
- NSLog(@"I am never run");
- } break;
- case 1:
- {
- NSLog(@"I am also never run");
- } break;
- default:
- {
- NSLog(@"I print");
- } break;
- }
-
- // Câu lệnh vòng lặp While
- int ii = 0;
- while (ii < 4)
- {
- NSLog(@"%d,", ii++); // ii++ tăng dần, sau khi sử dụng giá trị của nó.
- } // => in ra "0,"
- // "1,"
- // "2,"
- // "3,"
-
- // Câu lệnh vòng lặp For
- int jj;
- for (jj=0; jj < 4; jj++)
- {
- NSLog(@"%d,", jj);
- } // => in ra "0,"
- // "1,"
- // "2,"
- // "3,"
-
- // Câu lệnh Foreach
- NSArray *values = @[@0, @1, @2, @3];
- for (NSNumber *value in values)
- {
- NSLog(@"%@,", value);
- } // => in ra "0,"
- // "1,"
- // "2,"
- // "3,"
-
- // Câu lệnh Try-Catch-Finally
- @try
- {
- // Your statements here
- @throw [NSException exceptionWithName:@"FileNotFoundException"
- reason:@"Không Tìm Thấy Tập Tin trên Hệ Thống" userInfo:nil];
- } @catch (NSException * e)
- {
- NSLog(@"Exception: %@", e);
- } @finally
- {
- NSLog(@"Finally");
- } // => in ra "Exception: Không Tìm Thấy Tập Tin trên Hệ Thống"
- // "Finally"
-
- ///////////////////////////////////////
- // Đối Tượng (Objects)
- ///////////////////////////////////////
-
- // Tạo một thực thể đối tượng bằng cách phân vùng nhớ và khởi tạo đối tượng đó.
- // Một đối tượng sẽ không thật sự hoạt động cho đến khi cả 2 bước alloc] init] được hoàn thành
- MyClass *myObject = [[MyClass alloc] init];
-
- // Mô hình lập trình hướng đối tượng của Objective-C dựa trên việc truyền thông điệp (message)
- // và các thực thể đối tượng với nhau.
- // Trong Objective-C một đối tượng không đơn thuần gọi phương thức; nó truyền thông điệp.
- [myObject instanceMethodWithParameter:@"Steve Jobs"];
-
- // Dọn dẹp vùng nhớ mà bạn đã dùng ở chương trình
- [pool drain];
-
- // Kết thúc chương trình
- return 0;
-}
-
-///////////////////////////////////////
-// Lớp và Hàm (Classes & Functions)
-///////////////////////////////////////
-
-// Khai báo lớp của bạn ở một tập tin header (MyClass.h):
-// Cú pháp Khai Báo Lớp:
-// @interface ClassName : ParentClassName <ImplementedProtocols>
-// {
-// Khai báo biến thành viên;
-// }
-// -/+ (type) Khai báo method;
-// @end
-@interface MyClass : NSObject <MyProtocol>
-{
- int count;
- id data;
- NSString *name;
-}
-// Ký hiệu (notation) tiện ích để tự động khởi tạo public getter và setter
-@property int count;
-@property (copy) NSString *name; // Sao chép đối tượng trong quá trình gán.
-@property (readonly) id data; // Chỉ khai báo phương thức getter.
-
-// Phương thức
-+/- (return type)methodSignature:(Parameter Type *)parameterName;
-
-// dấu '+' cho phương thức lớp
-+ (NSString *)classMethod;
-
-// dấu '-' cho phương thức thực thể
-- (NSString *)instanceMethodWithParameter:(NSString *)string;
-- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number;
-
-@end
-
-// Thực thi các phương thức trong một tập tin thực thi (MyClass.m):
-
-@implementation MyClass
-
-// Gọi khi đối tượng được release
-- (void)dealloc
-{
-}
-
-// Phương thức khởi tạo (Constructors) là một cách để tạo các lớp
-// Đây là phương thức khởi tạo mặc định được gọi khi đối tượng được khởi tạo
-- (id)init
-{
- if ((self = [super init]))
- {
- self.count = 1;
- }
- return self;
-}
-
-+ (NSString *)classMethod
-{
- return [[self alloc] init];
-}
-
-- (NSString *)instanceMethodWithParameter:(NSString *)string
-{
- return @"New string";
-}
-
-- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number
-{
- return @42;
-}
-
-// Các phương thức được khai báo vào MyProtocol
-- (void)myProtocolMethod
-{
- // câu lệnh
-}
-
-@end
-
-/*
- * Một protocol khai báo các phương thức mà có thể thực thi bởi bất kỳ lớp nào.
- * Các protocol chính chúng không phải là các lớp. Chúng chỉ đơn giản là định ra giao diện (interface)
- * mà các đối tượng khác có trách nhiệm sẽ thực thi.
- */
-@protocol MyProtocol
- - (void)myProtocolMethod;
-@end
-
-
-
-```
-## Xem Thêm
-
-+ [Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C)
-
-+ Apple Docs':
- + [Learning Objective-C](http://developer.apple.com/library/ios/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/)
-
- + [Programming With Objective-C](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html)
-
- + [Object-Oriented Programming with Objective-C](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/OOP_ObjC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40005149)
-
- + [Coding Guidelines for Cocoa](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html)
-
-+ [iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started)
+---
+language: Objective-C
+contributors:
+ - ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
+ - ["Yannick Loriot", "https://github.com/YannickL"]
+lang: vi-vn
+filename: LearnObjectiveC-vi.m
+---
+
+Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành macOS, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch.
+Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C.
+
+```objective-c
+// Chú thích dòng đơn bắt đầu với //
+
+/*
+Chú thích đa dòng trông như thế này.
+*/
+
+// Nhập các headers của framework Foundation với cú pháp #import
+#import <Foundation/Foundation.h>
+#import "MyClass.h"
+
+// Đầu vào chương trình của bạn là một hàm gọi là
+// main với một kiểu trả về kiểu integer.
+int main (int argc, const char * argv[])
+{
+ // Tạo một autorelease pool để quản lý bộ nhớ vào chương trình
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+ // Sử dụng hàm NSLog() để in ra các dòng lệnh vào console
+ NSLog(@"Hello World!"); // Print the string "Hello World!"
+
+ ///////////////////////////////////////
+ // Kiểu & Biến (Types & Variables)
+ ///////////////////////////////////////
+
+ // Khai báo số nguyên
+ int myPrimitive1 = 1;
+ long myPrimitive2 = 234554664565;
+
+ // Khai báo đối tượng
+ // Đặt dấu nháy * vào trước tên biến cho khai báo đối tượng strong
+ MyClass *myObject1 = nil; // Strong
+ id myObject2 = nil; // Weak
+ // %@ là một đối tượng
+ // 'miêu tả' ('desciption') là thông lệ để trình bày giá trị của các Đối tượng
+ NSLog(@"%@ và %@", myObject1, [myObject2 description]); // In ra "(null) và (null)"
+
+ // Chuỗi
+ NSString *worldString = @"World";
+ NSLog(@"Hello %@!", worldString); // In ra "Hello World!"
+
+ // Ký tự literals
+ NSNumber *theLetterZNumber = @'Z';
+ char theLetterZ = [theLetterZNumber charValue];
+ NSLog(@"%c", theLetterZ);
+
+ // Số nguyên literals
+ NSNumber *fortyTwoNumber = @42;
+ int fortyTwo = [fortyTwoNumber intValue];
+ NSLog(@"%i", fortyTwo);
+
+ NSNumber *fortyTwoUnsignedNumber = @42U;
+ unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue];
+ NSLog(@"%u", fortyTwoUnsigned);
+
+ NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42];
+ short fortyTwoShort = [fortyTwoShortNumber shortValue];
+ NSLog(@"%hi", fortyTwoShort);
+
+ NSNumber *fortyTwoLongNumber = @42L;
+ long fortyTwoLong = [fortyTwoLongNumber longValue];
+ NSLog(@"%li", fortyTwoLong);
+
+ // Dấu phẩy động (floating point) literals
+ NSNumber *piFloatNumber = @3.141592654F;
+ float piFloat = [piFloatNumber floatValue];
+ NSLog(@"%f", piFloat);
+
+ NSNumber *piDoubleNumber = @3.1415926535;
+ double piDouble = [piDoubleNumber doubleValue];
+ NSLog(@"%f", piDouble);
+
+ // BOOL literals
+ NSNumber *yesNumber = @YES;
+ NSNumber *noNumber = @NO;
+
+ // Đối tượng Mảng
+ NSArray *anArray = @[@1, @2, @3, @4];
+ NSNumber *thirdNumber = anArray[2];
+ NSLog(@"Third number = %@", thirdNumber); // In ra "Third number = 3"
+
+ // Đối tượng Từ điển
+ NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" };
+ NSObject *valueObject = aDictionary[@"A Key"];
+ NSLog(@"Đối tượng = %@", valueObject); // In ra "Object = (null)"
+
+ ///////////////////////////////////////
+ // Toán Tử (Operators)
+ ///////////////////////////////////////
+
+ // Các toán tử cũng hoạt động giống như ngôn ngữ C
+ // Ví dụ:
+ 2 + 5; // => 7
+ 4.2f + 5.1f; // => 9.3f
+ 3 == 2; // => 0 (NO)
+ 3 != 2; // => 1 (YES)
+ 1 && 1; // => 1 (Logical and)
+ 0 || 1; // => 1 (Logical or)
+ ~0x0F; // => 0xF0 (bitwise negation)
+ 0x0F & 0xF0; // => 0x00 (bitwise AND)
+ 0x01 << 1; // => 0x02 (bitwise dịch trái (bởi 1))
+
+ /////////////////////////////////////////////
+ // Cấu Trúc Điều Khiển (Controls Structures)
+ /////////////////////////////////////////////
+
+ // Câu lệnh If-Else
+ if (NO)
+ {
+ NSLog(@"I am never run");
+ } else if (0)
+ {
+ NSLog(@"I am also never run");
+ } else
+ {
+ NSLog(@"I print");
+ }
+
+ // Câu lệnh Switch
+ switch (2)
+ {
+ case 0:
+ {
+ NSLog(@"I am never run");
+ } break;
+ case 1:
+ {
+ NSLog(@"I am also never run");
+ } break;
+ default:
+ {
+ NSLog(@"I print");
+ } break;
+ }
+
+ // Câu lệnh vòng lặp While
+ int ii = 0;
+ while (ii < 4)
+ {
+ NSLog(@"%d,", ii++); // ii++ tăng dần, sau khi sử dụng giá trị của nó.
+ } // => in ra "0,"
+ // "1,"
+ // "2,"
+ // "3,"
+
+ // Câu lệnh vòng lặp For
+ int jj;
+ for (jj=0; jj < 4; jj++)
+ {
+ NSLog(@"%d,", jj);
+ } // => in ra "0,"
+ // "1,"
+ // "2,"
+ // "3,"
+
+ // Câu lệnh Foreach
+ NSArray *values = @[@0, @1, @2, @3];
+ for (NSNumber *value in values)
+ {
+ NSLog(@"%@,", value);
+ } // => in ra "0,"
+ // "1,"
+ // "2,"
+ // "3,"
+
+ // Câu lệnh Try-Catch-Finally
+ @try
+ {
+ // Your statements here
+ @throw [NSException exceptionWithName:@"FileNotFoundException"
+ reason:@"Không Tìm Thấy Tập Tin trên Hệ Thống" userInfo:nil];
+ } @catch (NSException * e)
+ {
+ NSLog(@"Exception: %@", e);
+ } @finally
+ {
+ NSLog(@"Finally");
+ } // => in ra "Exception: Không Tìm Thấy Tập Tin trên Hệ Thống"
+ // "Finally"
+
+ ///////////////////////////////////////
+ // Đối Tượng (Objects)
+ ///////////////////////////////////////
+
+ // Tạo một thực thể đối tượng bằng cách phân vùng nhớ và khởi tạo đối tượng đó.
+ // Một đối tượng sẽ không thật sự hoạt động cho đến khi cả 2 bước alloc] init] được hoàn thành
+ MyClass *myObject = [[MyClass alloc] init];
+
+ // Mô hình lập trình hướng đối tượng của Objective-C dựa trên việc truyền thông điệp (message)
+ // và các thực thể đối tượng với nhau.
+ // Trong Objective-C một đối tượng không đơn thuần gọi phương thức; nó truyền thông điệp.
+ [myObject instanceMethodWithParameter:@"Steve Jobs"];
+
+ // Dọn dẹp vùng nhớ mà bạn đã dùng ở chương trình
+ [pool drain];
+
+ // Kết thúc chương trình
+ return 0;
+}
+
+///////////////////////////////////////
+// Lớp và Hàm (Classes & Functions)
+///////////////////////////////////////
+
+// Khai báo lớp của bạn ở một tập tin header (MyClass.h):
+// Cú pháp Khai Báo Lớp:
+// @interface ClassName : ParentClassName <ImplementedProtocols>
+// {
+// Khai báo biến thành viên;
+// }
+// -/+ (type) Khai báo method;
+// @end
+@interface MyClass : NSObject <MyProtocol>
+{
+ int count;
+ id data;
+ NSString *name;
+}
+// Ký hiệu (notation) tiện ích để tự động khởi tạo public getter và setter
+@property int count;
+@property (copy) NSString *name; // Sao chép đối tượng trong quá trình gán.
+@property (readonly) id data; // Chỉ khai báo phương thức getter.
+
+// Phương thức
++/- (return type)methodSignature:(Parameter Type *)parameterName;
+
+// dấu '+' cho phương thức lớp
++ (NSString *)classMethod;
+
+// dấu '-' cho phương thức thực thể
+- (NSString *)instanceMethodWithParameter:(NSString *)string;
+- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number;
+
+@end
+
+// Thực thi các phương thức trong một tập tin thực thi (MyClass.m):
+
+@implementation MyClass
+
+// Gọi khi đối tượng được release
+- (void)dealloc
+{
+}
+
+// Phương thức khởi tạo (Constructors) là một cách để tạo các lớp
+// Đây là phương thức khởi tạo mặc định được gọi khi đối tượng được khởi tạo
+- (id)init
+{
+ if ((self = [super init]))
+ {
+ self.count = 1;
+ }
+ return self;
+}
+
++ (NSString *)classMethod
+{
+ return [[self alloc] init];
+}
+
+- (NSString *)instanceMethodWithParameter:(NSString *)string
+{
+ return @"New string";
+}
+
+- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number
+{
+ return @42;
+}
+
+// Các phương thức được khai báo vào MyProtocol
+- (void)myProtocolMethod
+{
+ // câu lệnh
+}
+
+@end
+
+/*
+ * Một protocol khai báo các phương thức mà có thể thực thi bởi bất kỳ lớp nào.
+ * Các protocol chính chúng không phải là các lớp. Chúng chỉ đơn giản là định ra giao diện (interface)
+ * mà các đối tượng khác có trách nhiệm sẽ thực thi.
+ */
+@protocol MyProtocol
+ - (void)myProtocolMethod;
+@end
+
+
+
+```
+## Xem Thêm
+
++ [Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C)
+
++ Apple Docs':
+ + [Learning Objective-C](http://developer.apple.com/library/ios/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/)
+
+ + [Programming With Objective-C](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html)
+
+ + [Object-Oriented Programming with Objective-C](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/OOP_ObjC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40005149)
+
+ + [Coding Guidelines for Cocoa](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html)
+
++ [iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started)
diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown
index a253af48..b79017dc 100644
--- a/visualbasic.html.markdown
+++ b/visualbasic.html.markdown
@@ -5,7 +5,7 @@ contributors:
filename: learnvisualbasic.vb
---
-```
+```visualbasic
Module Module1
Sub Main()
diff --git a/wolfram.html.markdown b/wolfram.html.markdown
index 5fddbc82..fa8ee078 100644
--- a/wolfram.html.markdown
+++ b/wolfram.html.markdown
@@ -14,7 +14,7 @@ Wolfram Language has several interfaces:
The code in this example can be typed in to any interface and edited with Wolfram Workbench. Loading directly into Mathematica may be awkward because the file contains no cell formatting information (which would make the file a huge mess to read as text) - it can be viewed/edited but may require some setting up.
-```
+```mathematica
(* This is a comment *)
(* In Mathematica instead of using these comments you can create a text cell
diff --git a/yaml.html.markdown b/yaml.html.markdown
index 2bb35d42..6901695c 100644
--- a/yaml.html.markdown
+++ b/yaml.html.markdown
@@ -165,7 +165,7 @@ other_anchor: *anchor_name
base: &base
name: Everyone has same name
-# The regexp << is called 'Merge Key Language-Independent Type'. It is used to
+# The expression << is called 'Merge Key Language-Independent Type'. It is used to
# indicate that all the keys of one or more specified maps should be inserted
# into the current map.
# NOTE: If key already exists alias will not be merged
diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown
index a6a61949..db36ebc4 100644
--- a/zh-cn/c++-cn.html.markdown
+++ b/zh-cn/c++-cn.html.markdown
@@ -1,572 +1,572 @@
----
-language: C++
-filename: learncpp-cn.cpp
-contributors:
- - ["Steven Basart", "http://github.com/xksteven"]
- - ["Matt Kline", "https://github.com/mrkline"]
-translators:
- - ["Arnie97", "https://github.com/Arnie97"]
-lang: zh-cn
----
-
-C++是一种系统编程语言。用它的发明者,
-[Bjarne Stroustrup的话](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote)来说,C++的设计目标是:
-
-- 成为“更好的C语言”
-- 支持数据的抽象与封装
-- 支持面向对象编程
-- 支持泛型编程
-
-C++提供了对硬件的紧密控制(正如C语言一样),
-能够编译为机器语言,由处理器直接执行。
-与此同时,它也提供了泛型、异常和类等高层功能。
-虽然C++的语法可能比某些出现较晚的语言更复杂,它仍然得到了人们的青睞——
-功能与速度的平衡使C++成为了目前应用最广泛的系统编程语言之一。
-
-```c++
-////////////////
-// 与C语言的比较
-////////////////
-
-// C++_几乎_是C语言的一个超集,它与C语言的基本语法有许多相同之处,
-// 例如变量和函数的声明,原生数据类型等等。
-
-// 和C语言一样,在C++中,你的程序会从main()开始执行,
-// 该函数的返回值应当为int型,这个返回值会作为程序的退出状态值。
-// 不过,大多数的编译器(gcc,clang等)也接受 void main() 的函数原型。
-// (参见 http://en.wikipedia.org/wiki/Exit_status 来获取更多信息)
-int main(int argc, char** argv)
-{
- // 和C语言一样,命令行参数通过argc和argv传递。
- // argc代表命令行参数的数量,
- // 而argv是一个包含“C语言风格字符串”(char *)的数组,
- // 其中每个字符串代表一个命令行参数的内容,
- // 首个命令行参数是调用该程序时所使用的名称。
- // 如果你不关心命令行参数的值,argc和argv可以被忽略。
- // 此时,你可以用int main()作为函数原型。
-
- // 退出状态值为0时,表示程序执行成功
- return 0;
-}
-
-// 然而,C++和C语言也有一些区别:
-
-// 在C++中,字符字面量的大小是一个字节。
-sizeof('c') == 1
-
-// 在C语言中,字符字面量的大小与int相同。
-sizeof('c') == sizeof(10)
-
-
-// C++的函数原型与函数定义是严格匹配的
-void func(); // 这个函数不能接受任何参数
-
-// 而在C语言中
-void func(); // 这个函数能接受任意数量的参数
-
-// 在C++中,用nullptr代替C语言中的NULL
-int* ip = nullptr;
-
-// C++也可以使用C语言的标准头文件,
-// 但是需要加上前缀“c”并去掉末尾的“.h”。
-#include <cstdio>
-
-int main()
-{
- printf("Hello, world!\n");
- return 0;
-}
-
-///////////
-// 函数重载
-///////////
-
-// C++支持函数重载,你可以定义一组名称相同而参数不同的函数。
-
-void print(char const* myString)
-{
- printf("String %s\n", myString);
-}
-
-void print(int myInt)
-{
- printf("My int is %d", myInt);
-}
-
-int main()
-{
- print("Hello"); // 解析为 void print(const char*)
- print(15); // 解析为 void print(int)
-}
-
-///////////////////
-// 函数参数的默认值
-///////////////////
-
-// 你可以为函数的参数指定默认值,
-// 它们将会在调用者没有提供相应参数时被使用。
-
-void doSomethingWithInts(int a = 1, int b = 4)
-{
- // 对两个参数进行一些操作
-}
-
-int main()
-{
- doSomethingWithInts(); // a = 1, b = 4
- doSomethingWithInts(20); // a = 20, b = 4
- doSomethingWithInts(20, 5); // a = 20, b = 5
-}
-
-// 默认参数必须放在所有的常规参数之后。
-
-void invalidDeclaration(int a = 1, int b) // 这是错误的!
-{
-}
-
-
-///////////
-// 命名空间
-///////////
-
-// 命名空间为变量、函数和其他声明提供了分离的的作用域。
-// 命名空间可以嵌套使用。
-
-namespace First {
- namespace Nested {
- void foo()
- {
- printf("This is First::Nested::foo\n");
- }
- } // 结束嵌套的命名空间Nested
-} // 结束命名空间First
-
-namespace Second {
- void foo()
- {
- printf("This is Second::foo\n")
- }
-}
-
-void foo()
-{
- printf("This is global foo\n");
-}
-
-int main()
-{
- // 如果没有特别指定,就从“Second”中取得所需的内容。
- using namespace Second;
-
- foo(); // 显示“This is Second::foo”
- First::Nested::foo(); // 显示“This is First::Nested::foo”
- ::foo(); // 显示“This is global foo”
-}
-
-////////////
-// 输入/输出
-////////////
-
-// C++使用“流”来输入输出。<<是流的插入运算符,>>是流提取运算符。
-// cin、cout、和cerr分别代表
-// stdin(标准输入)、stdout(标准输出)和stderr(标准错误)。
-
-#include <iostream> // 引入包含输入/输出流的头文件
-
-using namespace std; // 输入输出流在std命名空间(也就是标准库)中。
-
-int main()
-{
- int myInt;
-
- // 在标准输出(终端/显示器)中显示
- cout << "Enter your favorite number:\n";
- // 从标准输入(键盘)获得一个值
- cin >> myInt;
-
- // cout也提供了格式化功能
- cout << "Your favorite number is " << myInt << "\n";
- // 显示“Your favorite number is <myInt>”
-
- cerr << "Used for error messages";
-}
-
-/////////
-// 字符串
-/////////
-
-// C++中的字符串是对象,它们有很多成员函数
-#include <string>
-
-using namespace std; // 字符串也在std命名空间(标准库)中。
-
-string myString = "Hello";
-string myOtherString = " World";
-
-// + 可以用于连接字符串。
-cout << myString + myOtherString; // "Hello World"
-
-cout << myString + " You"; // "Hello You"
-
-// C++中的字符串是可变的,具有“值语义”。
-myString.append(" Dog");
-cout << myString; // "Hello Dog"
-
-
-/////////////
-// 引用
-/////////////
-
-// 除了支持C语言中的指针类型以外,C++还提供了_引用_。
-// 引用是一种特殊的指针类型,一旦被定义就不能重新赋值,并且不能被设置为空值。
-// 使用引用时的语法与原变量相同:
-// 也就是说,对引用类型进行解引用时,不需要使用*;
-// 赋值时也不需要用&来取地址。
-
-using namespace std;
-
-string foo = "I am foo";
-string bar = "I am bar";
-
-
-string& fooRef = foo; // 建立了一个对foo的引用。
-fooRef += ". Hi!"; // 通过引用来修改foo的值
-cout << fooRef; // "I am foo. Hi!"
-
-// 这句话的并不会改变fooRef的指向,其效果与“foo = bar”相同。
-// 也就是说,在执行这条语句之后,foo == "I am bar"。
-fooRef = bar;
-
-const string& barRef = bar; // 建立指向bar的常量引用。
-// 和C语言中一样,(指针和引用)声明为常量时,对应的值不能被修改。
-barRef += ". Hi!"; // 这是错误的,不能修改一个常量引用的值。
-
-///////////////////
-// 类与面向对象编程
-///////////////////
-
-// 有关类的第一个示例
-#include <iostream>
-
-// 声明一个类。
-// 类通常在头文件(.h或.hpp)中声明。
-class Dog {
- // 成员变量和成员函数默认情况下是私有(private)的。
- std::string name;
- int weight;
-
-// 在这个标签之后,所有声明都是公有(public)的,
-// 直到重新指定“private:”(私有继承)或“protected:”(保护继承)为止
-public:
-
- // 默认的构造器
- Dog();
-
- // 这里是成员函数声明的一个例子。
- // 可以注意到,我们在此处使用了std::string,而不是using namespace std
- // 语句using namespace绝不应当出现在头文件当中。
- void setName(const std::string& dogsName);
-
- void setWeight(int dogsWeight);
-
- // 如果一个函数不对对象的状态进行修改,
- // 应当在声明中加上const。
- // 这样,你就可以对一个以常量方式引用的对象执行该操作。
- // 同时可以注意到,当父类的成员函数需要被子类重写时,
- // 父类中的函数必须被显式声明为_虚函数(virtual)_。
- // 考虑到性能方面的因素,函数默认情况下不会被声明为虚函数。
- virtual void print() const;
-
- // 函数也可以在class body内部定义。
- // 这样定义的函数会自动成为内联函数。
- void bark() const { std::cout << name << " barks!\n" }
-
- // 除了构造器以外,C++还提供了析构器。
- // 当一个对象被删除或者脱离其定义域时,它的析构函数会被调用。
- // 这使得RAII这样的强大范式(参见下文)成为可能。
- // 为了衍生出子类来,基类的析构函数必须定义为虚函数。
- virtual ~Dog();
-
-}; // 在类的定义之后,要加一个分号
-
-// 类的成员函数通常在.cpp文件中实现。
-void Dog::Dog()
-{
- std::cout << "A dog has been constructed\n";
-}
-
-// 对象(例如字符串)应当以引用的形式传递,
-// 对于不需要修改的对象,最好使用常量引用。
-void Dog::setName(const std::string& dogsName)
-{
- name = dogsName;
-}
-
-void Dog::setWeight(int dogsWeight)
-{
- weight = dogsWeight;
-}
-
-// 虚函数的virtual关键字只需要在声明时使用,不需要在定义时重复
-void Dog::print() const
-{
- std::cout << "Dog is " << name << " and weighs " << weight << "kg\n";
-}
-
-void Dog::~Dog()
-{
- std::cout << "Goodbye " << name << "\n";
-}
-
-int main() {
- Dog myDog; // 此时显示“A dog has been constructed”
- myDog.setName("Barkley");
- myDog.setWeight(10);
- myDog.print(); // 显示“Dog is Barkley and weighs 10 kg”
- return 0;
-} // 显示“Goodbye Barkley”
-
-// 继承:
-
-// 这个类继承了Dog类中的公有(public)和保护(protected)对象
-class OwnedDog : public Dog {
-
- void setOwner(const std::string& dogsOwner)
-
- // 重写OwnedDogs类的print方法。
- // 如果你不熟悉子类多态的话,可以参考这个页面中的概述:
- // http://zh.wikipedia.org/wiki/%E5%AD%90%E7%B1%BB%E5%9E%8B
-
- // override关键字是可选的,它确保你所重写的是基类中的方法。
- void print() const override;
-
-private:
- std::string owner;
-};
-
-// 与此同时,在对应的.cpp文件里:
-
-void OwnedDog::setOwner(const std::string& dogsOwner)
-{
- owner = dogsOwner;
-}
-
-void OwnedDog::print() const
-{
- Dog::print(); // 调用基类Dog中的print方法
- // "Dog is <name> and weights <weight>"
-
- std::cout << "Dog is owned by " << owner << "\n";
- // "Dog is owned by <owner>"
-}
-
-/////////////////////
-// 初始化与运算符重载
-/////////////////////
-
-// 在C++中,通过定义一些特殊名称的函数,
-// 你可以重载+、-、*、/等运算符的行为。
-// 当运算符被使用时,这些特殊函数会被调用,从而实现运算符重载。
-
-#include <iostream>
-using namespace std;
-
-class Point {
-public:
- // 可以以这样的方式为成员变量设置默认值。
- double x = 0;
- double y = 0;
-
- // 定义一个默认的构造器。
- // 除了将Point初始化为(0, 0)以外,这个函数什么都不做。
- Point() { };
-
- // 下面使用的语法称为初始化列表,
- // 这是初始化类中成员变量的正确方式。
- Point (double a, double b) :
- x(a),
- y(b)
- { /* 除了初始化成员变量外,什么都不做 */ }
-
- // 重载 + 运算符
- Point operator+(const Point& rhs) const;
-
- // 重载 += 运算符
- Point& operator+=(const Point& rhs);
-
- // 增加 - 和 -= 运算符也是有意义的,但这里不再赘述。
-};
-
-Point Point::operator+(const Point& rhs) const
-{
- // 创建一个新的点,
- // 其横纵坐标分别为这个点与另一点在对应方向上的坐标之和。
- return Point(x + rhs.x, y + rhs.y);
-}
-
-Point& Point::operator+=(const Point& rhs)
-{
- x += rhs.x;
- y += rhs.y;
- return *this;
-}
-
-int main () {
- Point up (0,1);
- Point right (1,0);
- // 这里使用了Point类型的运算符“+”
- // 调用up(Point类型)的“+”方法,并以right作为函数的参数
- Point result = up + right;
- // 显示“Result is upright (1,1)”
- cout << "Result is upright (" << result.x << ',' << result.y << ")\n";
- return 0;
-}
-
-///////////
-// 异常处理
-///////////
-
-// 标准库中提供了一些基本的异常类型
-// (参见http://en.cppreference.com/w/cpp/error/exception)
-// 但是,其他任何类型也可以作为一个异常被拋出
-#include <exception>
-
-// 在_try_代码块中拋出的异常可以被随后的_catch_捕获。
-try {
- // 不要用 _new_关键字在堆上为异常分配空间。
- throw std::exception("A problem occurred");
-}
-// 如果拋出的异常是一个对象,可以用常量引用来捕获它
-catch (const std::exception& ex)
-{
- std::cout << ex.what();
-// 捕获尚未被_catch_处理的所有错误
-} catch (...)
-{
- std::cout << "Unknown exception caught";
- throw; // 重新拋出异常
-}
-
-///////
-// RAII
-///////
-
-// RAII指的是“资源获取就是初始化”(Resource Allocation Is Initialization),
-// 它被视作C++中最强大的编程范式之一。
-// 简单说来,它指的是,用构造函数来获取一个对象的资源,
-// 相应的,借助析构函数来释放对象的资源。
-
-// 为了理解这一范式的用处,让我们考虑某个函数使用文件句柄时的情况:
-void doSomethingWithAFile(const char* filename)
-{
- // 首先,让我们假设一切都会顺利进行。
-
- FILE* fh = fopen(filename, "r"); // 以只读模式打开文件
-
- doSomethingWithTheFile(fh);
- doSomethingElseWithIt(fh);
-
- fclose(fh); // 关闭文件句柄
-}
-
-// 不幸的是,随着错误处理机制的引入,事情会变得复杂。
-// 假设fopen函数有可能执行失败,
-// 而doSomethingWithTheFile和doSomethingElseWithIt会在失败时返回错误代码。
-// (虽然异常是C++中处理错误的推荐方式,
-// 但是某些程序员,尤其是有C语言背景的,并不认可异常捕获机制的作用)。
-// 现在,我们必须检查每个函数调用是否成功执行,并在问题发生的时候关闭文件句柄。
-bool doSomethingWithAFile(const char* filename)
-{
- FILE* fh = fopen(filename, "r"); // 以只读模式打开文件
- if (fh == nullptr) // 当执行失败是,返回的指针是nullptr
- return false; // 向调用者汇报错误
-
- // 假设每个函数会在执行失败时返回false
- if (!doSomethingWithTheFile(fh)) {
- fclose(fh); // 关闭文件句柄,避免造成内存泄漏。
- return false; // 反馈错误
- }
- if (!doSomethingElseWithIt(fh)) {
- fclose(fh); // 关闭文件句柄
- return false; // 反馈错误
- }
-
- fclose(fh); // 关闭文件句柄
- return true; // 指示函数已成功执行
-}
-
-// C语言的程序员通常会借助goto语句简化上面的代码:
-bool doSomethingWithAFile(const char* filename)
-{
- FILE* fh = fopen(filename, "r");
- if (fh == nullptr)
- return false;
-
- if (!doSomethingWithTheFile(fh))
- goto failure;
-
- if (!doSomethingElseWithIt(fh))
- goto failure;
-
- fclose(fh); // 关闭文件
- return true; // 执行成功
-
-failure:
- fclose(fh);
- return false; // 反馈错误
-}
-
-// 如果用异常捕获机制来指示错误的话,
-// 代码会变得清晰一些,但是仍然有优化的余地。
-void doSomethingWithAFile(const char* filename)
-{
- FILE* fh = fopen(filename, "r"); // 以只读模式打开文件
- if (fh == nullptr)
- throw std::exception("Could not open the file.");
-
- try {
- doSomethingWithTheFile(fh);
- doSomethingElseWithIt(fh);
- }
- catch (...) {
- fclose(fh); // 保证出错的时候文件被正确关闭
- throw; // 之后,重新抛出这个异常
- }
-
- fclose(fh); // 关闭文件
- // 所有工作顺利完成
-}
-
-// 相比之下,使用C++中的文件流类(fstream)时,
-// fstream会利用自己的析构器来关闭文件句柄。
-// 只要离开了某一对象的定义域,它的析构函数就会被自动调用。
-void doSomethingWithAFile(const std::string& filename)
-{
- // ifstream是输入文件流(input file stream)的简称
- std::ifstream fh(filename); // 打开一个文件
-
- // 对文件进行一些操作
- doSomethingWithTheFile(fh);
- doSomethingElseWithIt(fh);
-
-} // 文件已经被析构器自动关闭
-
-// 与上面几种方式相比,这种方式有着_明显_的优势:
-// 1. 无论发生了什么情况,资源(此例当中是文件句柄)都会被正确关闭。
-// 只要你正确使用了析构器,就_不会_因为忘记关闭句柄,造成资源的泄漏。
-// 2. 可以注意到,通过这种方式写出来的代码十分简洁。
-// 析构器会在后台关闭文件句柄,不再需要你来操心这些琐事。
-// 3. 这种方式的代码具有异常安全性。
-// 无论在函数中的何处拋出异常,都不会阻碍对文件资源的释放。
-
-// 地道的C++代码应当把RAII的使用扩展到各种类型的资源上,包括:
-// - 用unique_ptr和shared_ptr管理的内存
-// - 各种数据容器,例如标准库中的链表、向量(容量自动扩展的数组)、散列表等;
-// 当它们脱离作用域时,析构器会自动释放其中储存的内容。
-// - 用lock_guard和unique_lock实现的互斥
-```
-扩展阅读:
-
-* [CPP Reference](http://cppreference.com/w/cpp) 提供了最新的语法参考。
-* 可以在 [CPlusPlus](http://cplusplus.com) 找到一些补充资料。
-* 可以在 [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb)上找到涵盖语言基础和设置编码环境的教程。
+---
+language: C++
+filename: learncpp-cn.cpp
+contributors:
+ - ["Steven Basart", "http://github.com/xksteven"]
+ - ["Matt Kline", "https://github.com/mrkline"]
+translators:
+ - ["Arnie97", "https://github.com/Arnie97"]
+lang: zh-cn
+---
+
+C++是一种系统编程语言。用它的发明者,
+[Bjarne Stroustrup的话](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote)来说,C++的设计目标是:
+
+- 成为“更好的C语言”
+- 支持数据的抽象与封装
+- 支持面向对象编程
+- 支持泛型编程
+
+C++提供了对硬件的紧密控制(正如C语言一样),
+能够编译为机器语言,由处理器直接执行。
+与此同时,它也提供了泛型、异常和类等高层功能。
+虽然C++的语法可能比某些出现较晚的语言更复杂,它仍然得到了人们的青睞——
+功能与速度的平衡使C++成为了目前应用最广泛的系统编程语言之一。
+
+```c++
+////////////////
+// 与C语言的比较
+////////////////
+
+// C++_几乎_是C语言的一个超集,它与C语言的基本语法有许多相同之处,
+// 例如变量和函数的声明,原生数据类型等等。
+
+// 和C语言一样,在C++中,你的程序会从main()开始执行,
+// 该函数的返回值应当为int型,这个返回值会作为程序的退出状态值。
+// 不过,大多数的编译器(gcc,clang等)也接受 void main() 的函数原型。
+// (参见 http://en.wikipedia.org/wiki/Exit_status 来获取更多信息)
+int main(int argc, char** argv)
+{
+ // 和C语言一样,命令行参数通过argc和argv传递。
+ // argc代表命令行参数的数量,
+ // 而argv是一个包含“C语言风格字符串”(char *)的数组,
+ // 其中每个字符串代表一个命令行参数的内容,
+ // 首个命令行参数是调用该程序时所使用的名称。
+ // 如果你不关心命令行参数的值,argc和argv可以被忽略。
+ // 此时,你可以用int main()作为函数原型。
+
+ // 退出状态值为0时,表示程序执行成功
+ return 0;
+}
+
+// 然而,C++和C语言也有一些区别:
+
+// 在C++中,字符字面量的大小是一个字节。
+sizeof('c') == 1
+
+// 在C语言中,字符字面量的大小与int相同。
+sizeof('c') == sizeof(10)
+
+
+// C++的函数原型与函数定义是严格匹配的
+void func(); // 这个函数不能接受任何参数
+
+// 而在C语言中
+void func(); // 这个函数能接受任意数量的参数
+
+// 在C++中,用nullptr代替C语言中的NULL
+int* ip = nullptr;
+
+// C++也可以使用C语言的标准头文件,
+// 但是需要加上前缀“c”并去掉末尾的“.h”。
+#include <cstdio>
+
+int main()
+{
+ printf("Hello, world!\n");
+ return 0;
+}
+
+///////////
+// 函数重载
+///////////
+
+// C++支持函数重载,你可以定义一组名称相同而参数不同的函数。
+
+void print(char const* myString)
+{
+ printf("String %s\n", myString);
+}
+
+void print(int myInt)
+{
+ printf("My int is %d", myInt);
+}
+
+int main()
+{
+ print("Hello"); // 解析为 void print(const char*)
+ print(15); // 解析为 void print(int)
+}
+
+///////////////////
+// 函数参数的默认值
+///////////////////
+
+// 你可以为函数的参数指定默认值,
+// 它们将会在调用者没有提供相应参数时被使用。
+
+void doSomethingWithInts(int a = 1, int b = 4)
+{
+ // 对两个参数进行一些操作
+}
+
+int main()
+{
+ doSomethingWithInts(); // a = 1, b = 4
+ doSomethingWithInts(20); // a = 20, b = 4
+ doSomethingWithInts(20, 5); // a = 20, b = 5
+}
+
+// 默认参数必须放在所有的常规参数之后。
+
+void invalidDeclaration(int a = 1, int b) // 这是错误的!
+{
+}
+
+
+///////////
+// 命名空间
+///////////
+
+// 命名空间为变量、函数和其他声明提供了分离的的作用域。
+// 命名空间可以嵌套使用。
+
+namespace First {
+ namespace Nested {
+ void foo()
+ {
+ printf("This is First::Nested::foo\n");
+ }
+ } // 结束嵌套的命名空间Nested
+} // 结束命名空间First
+
+namespace Second {
+ void foo()
+ {
+ printf("This is Second::foo\n")
+ }
+}
+
+void foo()
+{
+ printf("This is global foo\n");
+}
+
+int main()
+{
+ // 如果没有特别指定,就从“Second”中取得所需的内容。
+ using namespace Second;
+
+ foo(); // 显示“This is Second::foo”
+ First::Nested::foo(); // 显示“This is First::Nested::foo”
+ ::foo(); // 显示“This is global foo”
+}
+
+////////////
+// 输入/输出
+////////////
+
+// C++使用“流”来输入输出。<<是流的插入运算符,>>是流提取运算符。
+// cin、cout、和cerr分别代表
+// stdin(标准输入)、stdout(标准输出)和stderr(标准错误)。
+
+#include <iostream> // 引入包含输入/输出流的头文件
+
+using namespace std; // 输入输出流在std命名空间(也就是标准库)中。
+
+int main()
+{
+ int myInt;
+
+ // 在标准输出(终端/显示器)中显示
+ cout << "Enter your favorite number:\n";
+ // 从标准输入(键盘)获得一个值
+ cin >> myInt;
+
+ // cout也提供了格式化功能
+ cout << "Your favorite number is " << myInt << "\n";
+ // 显示“Your favorite number is <myInt>”
+
+ cerr << "Used for error messages";
+}
+
+/////////
+// 字符串
+/////////
+
+// C++中的字符串是对象,它们有很多成员函数
+#include <string>
+
+using namespace std; // 字符串也在std命名空间(标准库)中。
+
+string myString = "Hello";
+string myOtherString = " World";
+
+// + 可以用于连接字符串。
+cout << myString + myOtherString; // "Hello World"
+
+cout << myString + " You"; // "Hello You"
+
+// C++中的字符串是可变的,具有“值语义”。
+myString.append(" Dog");
+cout << myString; // "Hello Dog"
+
+
+/////////////
+// 引用
+/////////////
+
+// 除了支持C语言中的指针类型以外,C++还提供了_引用_。
+// 引用是一种特殊的指针类型,一旦被定义就不能重新赋值,并且不能被设置为空值。
+// 使用引用时的语法与原变量相同:
+// 也就是说,对引用类型进行解引用时,不需要使用*;
+// 赋值时也不需要用&来取地址。
+
+using namespace std;
+
+string foo = "I am foo";
+string bar = "I am bar";
+
+
+string& fooRef = foo; // 建立了一个对foo的引用。
+fooRef += ". Hi!"; // 通过引用来修改foo的值
+cout << fooRef; // "I am foo. Hi!"
+
+// 这句话的并不会改变fooRef的指向,其效果与“foo = bar”相同。
+// 也就是说,在执行这条语句之后,foo == "I am bar"。
+fooRef = bar;
+
+const string& barRef = bar; // 建立指向bar的常量引用。
+// 和C语言中一样,(指针和引用)声明为常量时,对应的值不能被修改。
+barRef += ". Hi!"; // 这是错误的,不能修改一个常量引用的值。
+
+///////////////////
+// 类与面向对象编程
+///////////////////
+
+// 有关类的第一个示例
+#include <iostream>
+
+// 声明一个类。
+// 类通常在头文件(.h或.hpp)中声明。
+class Dog {
+ // 成员变量和成员函数默认情况下是私有(private)的。
+ std::string name;
+ int weight;
+
+// 在这个标签之后,所有声明都是公有(public)的,
+// 直到重新指定“private:”(私有继承)或“protected:”(保护继承)为止
+public:
+
+ // 默认的构造器
+ Dog();
+
+ // 这里是成员函数声明的一个例子。
+ // 可以注意到,我们在此处使用了std::string,而不是using namespace std
+ // 语句using namespace绝不应当出现在头文件当中。
+ void setName(const std::string& dogsName);
+
+ void setWeight(int dogsWeight);
+
+ // 如果一个函数不对对象的状态进行修改,
+ // 应当在声明中加上const。
+ // 这样,你就可以对一个以常量方式引用的对象执行该操作。
+ // 同时可以注意到,当父类的成员函数需要被子类重写时,
+ // 父类中的函数必须被显式声明为_虚函数(virtual)_。
+ // 考虑到性能方面的因素,函数默认情况下不会被声明为虚函数。
+ virtual void print() const;
+
+ // 函数也可以在class body内部定义。
+ // 这样定义的函数会自动成为内联函数。
+ void bark() const { std::cout << name << " barks!\n" }
+
+ // 除了构造器以外,C++还提供了析构器。
+ // 当一个对象被删除或者脱离其定义域时,它的析构函数会被调用。
+ // 这使得RAII这样的强大范式(参见下文)成为可能。
+ // 为了衍生出子类来,基类的析构函数必须定义为虚函数。
+ virtual ~Dog();
+
+}; // 在类的定义之后,要加一个分号
+
+// 类的成员函数通常在.cpp文件中实现。
+void Dog::Dog()
+{
+ std::cout << "A dog has been constructed\n";
+}
+
+// 对象(例如字符串)应当以引用的形式传递,
+// 对于不需要修改的对象,最好使用常量引用。
+void Dog::setName(const std::string& dogsName)
+{
+ name = dogsName;
+}
+
+void Dog::setWeight(int dogsWeight)
+{
+ weight = dogsWeight;
+}
+
+// 虚函数的virtual关键字只需要在声明时使用,不需要在定义时重复
+void Dog::print() const
+{
+ std::cout << "Dog is " << name << " and weighs " << weight << "kg\n";
+}
+
+void Dog::~Dog()
+{
+ std::cout << "Goodbye " << name << "\n";
+}
+
+int main() {
+ Dog myDog; // 此时显示“A dog has been constructed”
+ myDog.setName("Barkley");
+ myDog.setWeight(10);
+ myDog.print(); // 显示“Dog is Barkley and weighs 10 kg”
+ return 0;
+} // 显示“Goodbye Barkley”
+
+// 继承:
+
+// 这个类继承了Dog类中的公有(public)和保护(protected)对象
+class OwnedDog : public Dog {
+
+ void setOwner(const std::string& dogsOwner)
+
+ // 重写OwnedDogs类的print方法。
+ // 如果你不熟悉子类多态的话,可以参考这个页面中的概述:
+ // http://zh.wikipedia.org/wiki/%E5%AD%90%E7%B1%BB%E5%9E%8B
+
+ // override关键字是可选的,它确保你所重写的是基类中的方法。
+ void print() const override;
+
+private:
+ std::string owner;
+};
+
+// 与此同时,在对应的.cpp文件里:
+
+void OwnedDog::setOwner(const std::string& dogsOwner)
+{
+ owner = dogsOwner;
+}
+
+void OwnedDog::print() const
+{
+ Dog::print(); // 调用基类Dog中的print方法
+ // "Dog is <name> and weights <weight>"
+
+ std::cout << "Dog is owned by " << owner << "\n";
+ // "Dog is owned by <owner>"
+}
+
+/////////////////////
+// 初始化与运算符重载
+/////////////////////
+
+// 在C++中,通过定义一些特殊名称的函数,
+// 你可以重载+、-、*、/等运算符的行为。
+// 当运算符被使用时,这些特殊函数会被调用,从而实现运算符重载。
+
+#include <iostream>
+using namespace std;
+
+class Point {
+public:
+ // 可以以这样的方式为成员变量设置默认值。
+ double x = 0;
+ double y = 0;
+
+ // 定义一个默认的构造器。
+ // 除了将Point初始化为(0, 0)以外,这个函数什么都不做。
+ Point() { };
+
+ // 下面使用的语法称为初始化列表,
+ // 这是初始化类中成员变量的正确方式。
+ Point (double a, double b) :
+ x(a),
+ y(b)
+ { /* 除了初始化成员变量外,什么都不做 */ }
+
+ // 重载 + 运算符
+ Point operator+(const Point& rhs) const;
+
+ // 重载 += 运算符
+ Point& operator+=(const Point& rhs);
+
+ // 增加 - 和 -= 运算符也是有意义的,但这里不再赘述。
+};
+
+Point Point::operator+(const Point& rhs) const
+{
+ // 创建一个新的点,
+ // 其横纵坐标分别为这个点与另一点在对应方向上的坐标之和。
+ return Point(x + rhs.x, y + rhs.y);
+}
+
+Point& Point::operator+=(const Point& rhs)
+{
+ x += rhs.x;
+ y += rhs.y;
+ return *this;
+}
+
+int main () {
+ Point up (0,1);
+ Point right (1,0);
+ // 这里使用了Point类型的运算符“+”
+ // 调用up(Point类型)的“+”方法,并以right作为函数的参数
+ Point result = up + right;
+ // 显示“Result is upright (1,1)”
+ cout << "Result is upright (" << result.x << ',' << result.y << ")\n";
+ return 0;
+}
+
+///////////
+// 异常处理
+///////////
+
+// 标准库中提供了一些基本的异常类型
+// (参见http://en.cppreference.com/w/cpp/error/exception)
+// 但是,其他任何类型也可以作为一个异常被拋出
+#include <exception>
+
+// 在_try_代码块中拋出的异常可以被随后的_catch_捕获。
+try {
+ // 不要用 _new_关键字在堆上为异常分配空间。
+ throw std::exception("A problem occurred");
+}
+// 如果拋出的异常是一个对象,可以用常量引用来捕获它
+catch (const std::exception& ex)
+{
+ std::cout << ex.what();
+// 捕获尚未被_catch_处理的所有错误
+} catch (...)
+{
+ std::cout << "Unknown exception caught";
+ throw; // 重新拋出异常
+}
+
+///////
+// RAII
+///////
+
+// RAII指的是“资源获取就是初始化”(Resource Allocation Is Initialization),
+// 它被视作C++中最强大的编程范式之一。
+// 简单说来,它指的是,用构造函数来获取一个对象的资源,
+// 相应的,借助析构函数来释放对象的资源。
+
+// 为了理解这一范式的用处,让我们考虑某个函数使用文件句柄时的情况:
+void doSomethingWithAFile(const char* filename)
+{
+ // 首先,让我们假设一切都会顺利进行。
+
+ FILE* fh = fopen(filename, "r"); // 以只读模式打开文件
+
+ doSomethingWithTheFile(fh);
+ doSomethingElseWithIt(fh);
+
+ fclose(fh); // 关闭文件句柄
+}
+
+// 不幸的是,随着错误处理机制的引入,事情会变得复杂。
+// 假设fopen函数有可能执行失败,
+// 而doSomethingWithTheFile和doSomethingElseWithIt会在失败时返回错误代码。
+// (虽然异常是C++中处理错误的推荐方式,
+// 但是某些程序员,尤其是有C语言背景的,并不认可异常捕获机制的作用)。
+// 现在,我们必须检查每个函数调用是否成功执行,并在问题发生的时候关闭文件句柄。
+bool doSomethingWithAFile(const char* filename)
+{
+ FILE* fh = fopen(filename, "r"); // 以只读模式打开文件
+ if (fh == nullptr) // 当执行失败是,返回的指针是nullptr
+ return false; // 向调用者汇报错误
+
+ // 假设每个函数会在执行失败时返回false
+ if (!doSomethingWithTheFile(fh)) {
+ fclose(fh); // 关闭文件句柄,避免造成内存泄漏。
+ return false; // 反馈错误
+ }
+ if (!doSomethingElseWithIt(fh)) {
+ fclose(fh); // 关闭文件句柄
+ return false; // 反馈错误
+ }
+
+ fclose(fh); // 关闭文件句柄
+ return true; // 指示函数已成功执行
+}
+
+// C语言的程序员通常会借助goto语句简化上面的代码:
+bool doSomethingWithAFile(const char* filename)
+{
+ FILE* fh = fopen(filename, "r");
+ if (fh == nullptr)
+ return false;
+
+ if (!doSomethingWithTheFile(fh))
+ goto failure;
+
+ if (!doSomethingElseWithIt(fh))
+ goto failure;
+
+ fclose(fh); // 关闭文件
+ return true; // 执行成功
+
+failure:
+ fclose(fh);
+ return false; // 反馈错误
+}
+
+// 如果用异常捕获机制来指示错误的话,
+// 代码会变得清晰一些,但是仍然有优化的余地。
+void doSomethingWithAFile(const char* filename)
+{
+ FILE* fh = fopen(filename, "r"); // 以只读模式打开文件
+ if (fh == nullptr)
+ throw std::exception("Could not open the file.");
+
+ try {
+ doSomethingWithTheFile(fh);
+ doSomethingElseWithIt(fh);
+ }
+ catch (...) {
+ fclose(fh); // 保证出错的时候文件被正确关闭
+ throw; // 之后,重新抛出这个异常
+ }
+
+ fclose(fh); // 关闭文件
+ // 所有工作顺利完成
+}
+
+// 相比之下,使用C++中的文件流类(fstream)时,
+// fstream会利用自己的析构器来关闭文件句柄。
+// 只要离开了某一对象的定义域,它的析构函数就会被自动调用。
+void doSomethingWithAFile(const std::string& filename)
+{
+ // ifstream是输入文件流(input file stream)的简称
+ std::ifstream fh(filename); // 打开一个文件
+
+ // 对文件进行一些操作
+ doSomethingWithTheFile(fh);
+ doSomethingElseWithIt(fh);
+
+} // 文件已经被析构器自动关闭
+
+// 与上面几种方式相比,这种方式有着_明显_的优势:
+// 1. 无论发生了什么情况,资源(此例当中是文件句柄)都会被正确关闭。
+// 只要你正确使用了析构器,就_不会_因为忘记关闭句柄,造成资源的泄漏。
+// 2. 可以注意到,通过这种方式写出来的代码十分简洁。
+// 析构器会在后台关闭文件句柄,不再需要你来操心这些琐事。
+// 3. 这种方式的代码具有异常安全性。
+// 无论在函数中的何处拋出异常,都不会阻碍对文件资源的释放。
+
+// 地道的C++代码应当把RAII的使用扩展到各种类型的资源上,包括:
+// - 用unique_ptr和shared_ptr管理的内存
+// - 各种数据容器,例如标准库中的链表、向量(容量自动扩展的数组)、散列表等;
+// 当它们脱离作用域时,析构器会自动释放其中储存的内容。
+// - 用lock_guard和unique_lock实现的互斥
+```
+扩展阅读:
+
+* [CPP Reference](http://cppreference.com/w/cpp) 提供了最新的语法参考。
+* 可以在 [CPlusPlus](http://cplusplus.com) 找到一些补充资料。
+* 可以在 [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb)上找到涵盖语言基础和设置编码环境的教程。
diff --git a/zh-cn/crystal-cn.html.markdown b/zh-cn/crystal-cn.html.markdown
index 14805114..b69ce688 100644
--- a/zh-cn/crystal-cn.html.markdown
+++ b/zh-cn/crystal-cn.html.markdown
@@ -564,4 +564,4 @@ ex #=> "ex2"
- [官方网站](https://crystal-lang.org/)
- [官方文档](https://crystal-lang.org/docs/overview/)
- [在线运行代码](https://play.crystal-lang.org/#/cr)
-- [Github仓库](https://github.com/crystal-lang/crystal)
+- [GitHub仓库](https://github.com/crystal-lang/crystal)
diff --git a/zh-cn/elisp-cn.html.markdown b/zh-cn/elisp-cn.html.markdown
index 3f6ccbcf..a429fcbc 100644
--- a/zh-cn/elisp-cn.html.markdown
+++ b/zh-cn/elisp-cn.html.markdown
@@ -1,345 +1,345 @@
----
-language: elisp
-contributors:
- - ["Bastien Guerry", "http://bzg.fr"]
-translators:
- - ["Chenbo Li", "http://binarythink.net"]
-filename: learn-emacs-lisp-zh.el
-lang: zh-cn
----
-
-```scheme
-;; 15分钟学会Emacs Lisp (v0.2a)
-;;(作者:bzg,https://github.com/bzg
-;; 译者:lichenbo,http://douban.com/people/lichenbo)
-;;
-;; 请先阅读Peter Norvig的一篇好文:
-;; http://norvig.com/21-days.html
-;; (译者注:中文版请见http://blog.youxu.info/21-days/)
-;;
-;; 之后安装GNU Emacs 24.3:
-;;
-;; Debian: apt-get install emacs (视具体发行版而定)
-;; MacOSX: http://emacsformacosx.com/emacs-builds/Emacs-24.3-universal-10.6.8.dmg
-;; Windows: http://ftp.gnu.org/gnu/windows/emacs/emacs-24.3-bin-i386.zip
-;;
-;; 更多信息可以在这里找到:
-;; http://www.gnu.org/software/emacs/#Obtaining
-
-;; 很重要的警告:
-;;
-;; 按照这个教程来学习并不会对你的电脑有任何损坏
-;; 除非你自己在学习的过程中愤怒地把它砸了
-;; 如果出现了这种情况,我不会承担任何责任
-;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;
-;; 打开emacs
-;;
-;; 按'q'消除欢迎界面
-;;
-;; 现在请注意窗口底部的那一个灰色长条
-;;
-;; "*scratch*" 是你现在编辑界面的名字。
-;; 这个编辑界面叫做一个"buffer"。
-;;
-;; 每当你打开Emacs时,都会默认打开这个scratch buffer
-;; 此时你并没有在编辑任何文件,而是在编辑一个buffer
-;; 之后你可以将这个buffer保存到一个文件中。
-;;
-;; 之后的"Lisp interaction" 则是表明我们可以用的某组命令
-;;
-;; Emacs在每个buffer中都有一组内置的命令
-;; 而当你激活某种特定的模式时,就可以使用相应的命令
-;; 这里我们使用`lisp-interaction-mode',
-;; 这样我们就可以使用内置的Emacs Lisp(以下简称Elisp)命令了。
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;
-;; 分号是注释开始的标志
-;;
-;; Elisp 是由符号表达式构成的 (即"s-表达式"或"s式"):
-(+ 2 2)
-
-;; 这个s式的意思是 "对2进行加2操作".
-
-;; s式周围有括号,而且也可以嵌套:
-(+ 2 (+ 1 1))
-
-;; 一个s式可以包含原子符号或者其他s式
-;; 在上面的例子中,1和2是原子符号
-;; (+ 2 (+ 1 1)) 和 (+ 1 1) 是s式.
-
-;; 在 `lisp-interaction-mode' 中你可以计算s式.
-;; 把光标移到闭括号后,之后按下ctrl+j(以后简写为'C-j')
-
-(+ 3 (+ 1 2))
-;; ^ 光标放到这里
-;; 按下`C-j' 就会输出 6
-
-;; `C-j' 会在buffer中插入当前运算的结果
-
-;; 而`C-xC-e' 则会在emacs最底部显示结果,也就是被称作"minibuffer"的区域
-;; 为了避免把我们的buffer填满无用的结果,我们以后会一直用`C-xC-e'
-
-;; `setq' 可以将一个值赋给一个变量
-(setq my-name "Bastien")
-;; `C-xC-e' 输出 "Bastien" (在 mini-buffer 中显示)
-
-;; `insert' 会在光标处插入字符串:
-(insert "Hello!")
-;; `C-xC-e' 输出 "Hello!"
-
-;; 在这里我们只传给了insert一个参数"Hello!", 但是
-;; 我们也可以传给它更多的参数,比如2个:
-
-(insert "Hello" " world!")
-;; `C-xC-e' 输出 "Hello world!"
-
-;; 你也可以用变量名来代替字符串
-(insert "Hello, I am " my-name)
-;; `C-xC-e' 输出 "Hello, I am Bastien"
-
-;; 你可以把s式嵌入函数中
-(defun hello () (insert "Hello, I am " my-name))
-;; `C-xC-e' 输出 hello
-
-;; 现在执行这个函数
-(hello)
-;; `C-xC-e' 输出 Hello, I am Bastien
-
-;; 函数中空括号的意思是我们不需要接受任何参数
-;; 但是我们不能一直总是用my-name这个变量
-;; 所以我们现在使我们的函数接受一个叫做"name"的参数
-
-(defun hello (name) (insert "Hello " name))
-;; `C-xC-e' 输出 hello
-
-;; 现在我们调用这个函数,并且将"you"作为参数传递
-
-(hello "you")
-;; `C-xC-e' 输出 "Hello you"
-
-;; 成功!
-
-;; 现在我们可以休息一下
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;
-;; 下面我们在新的窗口中新建一个名为 "*test*" 的buffer:
-
-(switch-to-buffer-other-window "*test*")
-;; `C-xC-e' 这时屏幕上会显示两个窗口,而光标此时位于*test* buffer内
-
-;; 用鼠标单击上面的buffer就会使光标移回。
-;; 或者你可以使用 `C-xo' 使得光标跳到另一个窗口中
-
-;; 你可以用 `progn'命令将s式结合起来:
-(progn
- (switch-to-buffer-other-window "*test*")
- (hello "you"))
-;; `C-xC-e' 此时屏幕分为两个窗口,并且在*test* buffer中显示"Hello you"
-
-;; 现在为了简洁,我们需要在每个s式后面都使用`C-xC-e'来执行,后面就不再说明了
-
-;; 记得可以用过鼠标或者`C-xo'回到*scratch*这个buffer。
-
-;; 清除当前buffer也是常用操作之一:
-(progn
- (switch-to-buffer-other-window "*test*")
- (erase-buffer)
- (hello "there"))
-
-;; 也可以回到其他的窗口中
-(progn
- (switch-to-buffer-other-window "*test*")
- (erase-buffer)
- (hello "you")
- (other-window 1))
-
-;; 你可以用 `let' 将一个值和一个局部变量绑定:
-(let ((local-name "you"))
- (switch-to-buffer-other-window "*test*")
- (erase-buffer)
- (hello local-name)
- (other-window 1))
-
-;; 这里我们就不需要使用 `progn' 了, 因为 `let' 也可以将很多s式组合起来。
-
-;; 格式化字符串的方法:
-(format "Hello %s!\n" "visitor")
-
-;; %s 是字符串占位符,这里被"visitor"替代.
-;; \n 是换行符。
-
-;; 现在我们用格式化的方法再重写一下我们的函数:
-(defun hello (name)
- (insert (format "Hello %s!\n" name)))
-
-(hello "you")
-
-;; 我们再用`let'新建另一个函数:
-(defun greeting (name)
- (let ((your-name "Bastien"))
- (insert (format "Hello %s!\n\nI am %s."
- name ; the argument of the function
- your-name ; the let-bound variable "Bastien"
- ))))
-
-;; 之后执行:
-(greeting "you")
-
-;; 有些函数可以和用户交互:
-(read-from-minibuffer "Enter your name: ")
-
-;; 这个函数会返回在执行时用户输入的信息
-
-;; 现在我们让`greeting'函数显示你的名字:
-(defun greeting (from-name)
- (let ((your-name (read-from-minibuffer "Enter your name: ")))
- (insert (format "Hello!\n\nI am %s and you are %s."
- from-name ; the argument of the function
- your-name ; the let-bound var, entered at prompt
- ))))
-
-(greeting "Bastien")
-
-;; 我们让结果在另一个窗口中显示:
-(defun greeting (from-name)
- (let ((your-name (read-from-minibuffer "Enter your name: ")))
- (switch-to-buffer-other-window "*test*")
- (erase-buffer)
- (insert (format "Hello %s!\n\nI am %s." your-name from-name))
- (other-window 1)))
-
-;; 测试一下:
-(greeting "Bastien")
-
-;; 第二节结束,休息一下吧。
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;
-;; 我们将一些名字存到列表中:
-(setq list-of-names '("Sarah" "Chloe" "Mathilde"))
-
-;; 用 `car'来取得第一个名字:
-(car list-of-names)
-
-;; 用 `cdr'取得剩下的名字:
-(cdr list-of-names)
-
-;; 用 `push'把名字添加到列表的开头:
-(push "Stephanie" list-of-names)
-
-;; 注意: `car' 和 `cdr' 并不修改列表本身, 但是 `push' 却会对列表本身进行操作.
-;; 这个区别是很重要的: 有些函数没有任何副作用(比如`car')
-;; 但还有一些却是有的 (比如 `push').
-
-;; 我们来对`list-of-names'列表中的每一个元素都使用hello函数:
-(mapcar 'hello list-of-names)
-
-;; 将 `greeting' 改进,使的我们能够对`list-of-names'中的所有名字执行:
-(defun greeting ()
- (switch-to-buffer-other-window "*test*")
- (erase-buffer)
- (mapcar 'hello list-of-names)
- (other-window 1))
-
-(greeting)
-
-;; 记得我们之前定义的 `hello' 函数吗? 这个函数接受一个参数,名字。
-;; `mapcar' 调用 `hello', 并将`list-of-names'作为参数先后传给`hello'
-
-;; 现在我们对显示的buffer中的内容进行一些更改:
-
-(defun replace-hello-by-bonjour ()
- (switch-to-buffer-other-window "*test*")
- (goto-char (point-min))
- (while (search-forward "Hello")
- (replace-match "Bonjour"))
- (other-window 1))
-
-;; (goto-char (point-min)) 将光标移到buffer的开始
-;; (search-forward "Hello") 查找字符串"Hello"
-;; (while x y) 当x返回某个值时执行y这个s式
-;; 当x返回`nil' (空), 退出循环
-
-(replace-hello-by-bonjour)
-
-;; 你会看到所有在*test* buffer中出现的"Hello"字样都被换成了"Bonjour"
-
-;; 你也会得到以下错误提示: "Search failed: Hello".
-;;
-;; 如果要避免这个错误, 你需要告诉 `search-forward' 这个命令是否在
-;; buffer的某个地方停止查找, 并且在什么都没找到时是否应该不给出错误提示
-
-;; (search-forward "Hello" nil t) 可以达到这个要求:
-
-;; `nil' 参数的意思是 : 查找并不限于某个范围内
-;; `t' 参数的意思是: 当什么都没找到时,不给出错误提示
-
-;; 在下面的函数中,我们用到了s式,并且不给出任何错误提示:
-
-(defun hello-to-bonjour ()
- (switch-to-buffer-other-window "*test*")
- (erase-buffer)
- ;; 为`list-of-names'中的每个名字调用hello
- (mapcar 'hello list-of-names)
- (goto-char (point-min))
- ;; 将"Hello" 替换为"Bonjour"
- (while (search-forward "Hello" nil t)
- (replace-match "Bonjour"))
- (other-window 1))
-
-(hello-to-bonjour)
-
-;; 给这些名字加粗:
-
-(defun boldify-names ()
- (switch-to-buffer-other-window "*test*")
- (goto-char (point-min))
- (while (re-search-forward "Bonjour \\(.+\\)!" nil t)
- (add-text-properties (match-beginning 1)
- (match-end 1)
- (list 'face 'bold)))
- (other-window 1))
-
-;; 这个函数使用了 `re-search-forward':
-;; 和查找一个字符串不同,你用这个命令可以查找一个模式,即正则表达式
-
-;; 正则表达式 "Bonjour \\(.+\\)!" 的意思是:
-;; 字符串 "Bonjour ", 之后跟着
-;; 一组 | \\( ... \\) 结构
-;; 任意字符 | . 的含义
-;; 有可能重复的 | + 的含义
-;; 之后跟着 "!" 这个字符串
-
-;; 准备好了?试试看。
-
-(boldify-names)
-
-;; `add-text-properties' 可以添加文字属性, 比如文字样式
-
-;; 好的,我们成功了!
-
-;; 如果你想对一个变量或者函数有更多的了解:
-;;
-;; C-h v 变量 回车
-;; C-h f 函数 回车
-;;
-;; 阅读Emacs Lisp官方文档:
-;;
-;; C-h i m elisp 回车
-;;
-;; 在线阅读Emacs Lisp文档:
-;; https://www.gnu.org/software/emacs/manual/html_node/eintr/index.html
-
-;; 感谢以下同学的建议和反馈:
-;; - Wes Hardaker
-;; - notbob
-;; - Kevin Montuori
-;; - Arne Babenhauserheide
-;; - Alan Schmitt
-;; - spacegoing
-```
-
+---
+language: elisp
+contributors:
+ - ["Bastien Guerry", "http://bzg.fr"]
+translators:
+ - ["Chenbo Li", "http://binarythink.net"]
+filename: learn-emacs-lisp-zh.el
+lang: zh-cn
+---
+
+```scheme
+;; 15分钟学会Emacs Lisp (v0.2a)
+;;(作者:bzg,https://github.com/bzg
+;; 译者:lichenbo,http://douban.com/people/lichenbo)
+;;
+;; 请先阅读Peter Norvig的一篇好文:
+;; http://norvig.com/21-days.html
+;; (译者注:中文版请见http://blog.youxu.info/21-days/)
+;;
+;; 之后安装GNU Emacs 24.3:
+;;
+;; Debian: apt-get install emacs (视具体发行版而定)
+;; MacOSX: http://emacsformacosx.com/emacs-builds/Emacs-24.3-universal-10.6.8.dmg
+;; Windows: http://ftp.gnu.org/gnu/windows/emacs/emacs-24.3-bin-i386.zip
+;;
+;; 更多信息可以在这里找到:
+;; http://www.gnu.org/software/emacs/#Obtaining
+
+;; 很重要的警告:
+;;
+;; 按照这个教程来学习并不会对你的电脑有任何损坏
+;; 除非你自己在学习的过程中愤怒地把它砸了
+;; 如果出现了这种情况,我不会承担任何责任
+;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;; 打开emacs
+;;
+;; 按'q'消除欢迎界面
+;;
+;; 现在请注意窗口底部的那一个灰色长条
+;;
+;; "*scratch*" 是你现在编辑界面的名字。
+;; 这个编辑界面叫做一个"buffer"。
+;;
+;; 每当你打开Emacs时,都会默认打开这个scratch buffer
+;; 此时你并没有在编辑任何文件,而是在编辑一个buffer
+;; 之后你可以将这个buffer保存到一个文件中。
+;;
+;; 之后的"Lisp interaction" 则是表明我们可以用的某组命令
+;;
+;; Emacs在每个buffer中都有一组内置的命令
+;; 而当你激活某种特定的模式时,就可以使用相应的命令
+;; 这里我们使用`lisp-interaction-mode',
+;; 这样我们就可以使用内置的Emacs Lisp(以下简称Elisp)命令了。
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;; 分号是注释开始的标志
+;;
+;; Elisp 是由符号表达式构成的 (即"s-表达式"或"s式"):
+(+ 2 2)
+
+;; 这个s式的意思是 "对2进行加2操作".
+
+;; s式周围有括号,而且也可以嵌套:
+(+ 2 (+ 1 1))
+
+;; 一个s式可以包含原子符号或者其他s式
+;; 在上面的例子中,1和2是原子符号
+;; (+ 2 (+ 1 1)) 和 (+ 1 1) 是s式.
+
+;; 在 `lisp-interaction-mode' 中你可以计算s式.
+;; 把光标移到闭括号后,之后按下ctrl+j(以后简写为'C-j')
+
+(+ 3 (+ 1 2))
+;; ^ 光标放到这里
+;; 按下`C-j' 就会输出 6
+
+;; `C-j' 会在buffer中插入当前运算的结果
+
+;; 而`C-xC-e' 则会在emacs最底部显示结果,也就是被称作"minibuffer"的区域
+;; 为了避免把我们的buffer填满无用的结果,我们以后会一直用`C-xC-e'
+
+;; `setq' 可以将一个值赋给一个变量
+(setq my-name "Bastien")
+;; `C-xC-e' 输出 "Bastien" (在 mini-buffer 中显示)
+
+;; `insert' 会在光标处插入字符串:
+(insert "Hello!")
+;; `C-xC-e' 输出 "Hello!"
+
+;; 在这里我们只传给了insert一个参数"Hello!", 但是
+;; 我们也可以传给它更多的参数,比如2个:
+
+(insert "Hello" " world!")
+;; `C-xC-e' 输出 "Hello world!"
+
+;; 你也可以用变量名来代替字符串
+(insert "Hello, I am " my-name)
+;; `C-xC-e' 输出 "Hello, I am Bastien"
+
+;; 你可以把s式嵌入函数中
+(defun hello () (insert "Hello, I am " my-name))
+;; `C-xC-e' 输出 hello
+
+;; 现在执行这个函数
+(hello)
+;; `C-xC-e' 输出 Hello, I am Bastien
+
+;; 函数中空括号的意思是我们不需要接受任何参数
+;; 但是我们不能一直总是用my-name这个变量
+;; 所以我们现在使我们的函数接受一个叫做"name"的参数
+
+(defun hello (name) (insert "Hello " name))
+;; `C-xC-e' 输出 hello
+
+;; 现在我们调用这个函数,并且将"you"作为参数传递
+
+(hello "you")
+;; `C-xC-e' 输出 "Hello you"
+
+;; 成功!
+
+;; 现在我们可以休息一下
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;; 下面我们在新的窗口中新建一个名为 "*test*" 的buffer:
+
+(switch-to-buffer-other-window "*test*")
+;; `C-xC-e' 这时屏幕上会显示两个窗口,而光标此时位于*test* buffer内
+
+;; 用鼠标单击上面的buffer就会使光标移回。
+;; 或者你可以使用 `C-xo' 使得光标跳到另一个窗口中
+
+;; 你可以用 `progn'命令将s式结合起来:
+(progn
+ (switch-to-buffer-other-window "*test*")
+ (hello "you"))
+;; `C-xC-e' 此时屏幕分为两个窗口,并且在*test* buffer中显示"Hello you"
+
+;; 现在为了简洁,我们需要在每个s式后面都使用`C-xC-e'来执行,后面就不再说明了
+
+;; 记得可以用过鼠标或者`C-xo'回到*scratch*这个buffer。
+
+;; 清除当前buffer也是常用操作之一:
+(progn
+ (switch-to-buffer-other-window "*test*")
+ (erase-buffer)
+ (hello "there"))
+
+;; 也可以回到其他的窗口中
+(progn
+ (switch-to-buffer-other-window "*test*")
+ (erase-buffer)
+ (hello "you")
+ (other-window 1))
+
+;; 你可以用 `let' 将一个值和一个局部变量绑定:
+(let ((local-name "you"))
+ (switch-to-buffer-other-window "*test*")
+ (erase-buffer)
+ (hello local-name)
+ (other-window 1))
+
+;; 这里我们就不需要使用 `progn' 了, 因为 `let' 也可以将很多s式组合起来。
+
+;; 格式化字符串的方法:
+(format "Hello %s!\n" "visitor")
+
+;; %s 是字符串占位符,这里被"visitor"替代.
+;; \n 是换行符。
+
+;; 现在我们用格式化的方法再重写一下我们的函数:
+(defun hello (name)
+ (insert (format "Hello %s!\n" name)))
+
+(hello "you")
+
+;; 我们再用`let'新建另一个函数:
+(defun greeting (name)
+ (let ((your-name "Bastien"))
+ (insert (format "Hello %s!\n\nI am %s."
+ name ; the argument of the function
+ your-name ; the let-bound variable "Bastien"
+ ))))
+
+;; 之后执行:
+(greeting "you")
+
+;; 有些函数可以和用户交互:
+(read-from-minibuffer "Enter your name: ")
+
+;; 这个函数会返回在执行时用户输入的信息
+
+;; 现在我们让`greeting'函数显示你的名字:
+(defun greeting (from-name)
+ (let ((your-name (read-from-minibuffer "Enter your name: ")))
+ (insert (format "Hello!\n\nI am %s and you are %s."
+ from-name ; the argument of the function
+ your-name ; the let-bound var, entered at prompt
+ ))))
+
+(greeting "Bastien")
+
+;; 我们让结果在另一个窗口中显示:
+(defun greeting (from-name)
+ (let ((your-name (read-from-minibuffer "Enter your name: ")))
+ (switch-to-buffer-other-window "*test*")
+ (erase-buffer)
+ (insert (format "Hello %s!\n\nI am %s." your-name from-name))
+ (other-window 1)))
+
+;; 测试一下:
+(greeting "Bastien")
+
+;; 第二节结束,休息一下吧。
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;; 我们将一些名字存到列表中:
+(setq list-of-names '("Sarah" "Chloe" "Mathilde"))
+
+;; 用 `car'来取得第一个名字:
+(car list-of-names)
+
+;; 用 `cdr'取得剩下的名字:
+(cdr list-of-names)
+
+;; 用 `push'把名字添加到列表的开头:
+(push "Stephanie" list-of-names)
+
+;; 注意: `car' 和 `cdr' 并不修改列表本身, 但是 `push' 却会对列表本身进行操作.
+;; 这个区别是很重要的: 有些函数没有任何副作用(比如`car')
+;; 但还有一些却是有的 (比如 `push').
+
+;; 我们来对`list-of-names'列表中的每一个元素都使用hello函数:
+(mapcar 'hello list-of-names)
+
+;; 将 `greeting' 改进,使的我们能够对`list-of-names'中的所有名字执行:
+(defun greeting ()
+ (switch-to-buffer-other-window "*test*")
+ (erase-buffer)
+ (mapcar 'hello list-of-names)
+ (other-window 1))
+
+(greeting)
+
+;; 记得我们之前定义的 `hello' 函数吗? 这个函数接受一个参数,名字。
+;; `mapcar' 调用 `hello', 并将`list-of-names'作为参数先后传给`hello'
+
+;; 现在我们对显示的buffer中的内容进行一些更改:
+
+(defun replace-hello-by-bonjour ()
+ (switch-to-buffer-other-window "*test*")
+ (goto-char (point-min))
+ (while (search-forward "Hello")
+ (replace-match "Bonjour"))
+ (other-window 1))
+
+;; (goto-char (point-min)) 将光标移到buffer的开始
+;; (search-forward "Hello") 查找字符串"Hello"
+;; (while x y) 当x返回某个值时执行y这个s式
+;; 当x返回`nil' (空), 退出循环
+
+(replace-hello-by-bonjour)
+
+;; 你会看到所有在*test* buffer中出现的"Hello"字样都被换成了"Bonjour"
+
+;; 你也会得到以下错误提示: "Search failed: Hello".
+;;
+;; 如果要避免这个错误, 你需要告诉 `search-forward' 这个命令是否在
+;; buffer的某个地方停止查找, 并且在什么都没找到时是否应该不给出错误提示
+
+;; (search-forward "Hello" nil t) 可以达到这个要求:
+
+;; `nil' 参数的意思是 : 查找并不限于某个范围内
+;; `t' 参数的意思是: 当什么都没找到时,不给出错误提示
+
+;; 在下面的函数中,我们用到了s式,并且不给出任何错误提示:
+
+(defun hello-to-bonjour ()
+ (switch-to-buffer-other-window "*test*")
+ (erase-buffer)
+ ;; 为`list-of-names'中的每个名字调用hello
+ (mapcar 'hello list-of-names)
+ (goto-char (point-min))
+ ;; 将"Hello" 替换为"Bonjour"
+ (while (search-forward "Hello" nil t)
+ (replace-match "Bonjour"))
+ (other-window 1))
+
+(hello-to-bonjour)
+
+;; 给这些名字加粗:
+
+(defun boldify-names ()
+ (switch-to-buffer-other-window "*test*")
+ (goto-char (point-min))
+ (while (re-search-forward "Bonjour \\(.+\\)!" nil t)
+ (add-text-properties (match-beginning 1)
+ (match-end 1)
+ (list 'face 'bold)))
+ (other-window 1))
+
+;; 这个函数使用了 `re-search-forward':
+;; 和查找一个字符串不同,你用这个命令可以查找一个模式,即正则表达式
+
+;; 正则表达式 "Bonjour \\(.+\\)!" 的意思是:
+;; 字符串 "Bonjour ", 之后跟着
+;; 一组 | \\( ... \\) 结构
+;; 任意字符 | . 的含义
+;; 有可能重复的 | + 的含义
+;; 之后跟着 "!" 这个字符串
+
+;; 准备好了?试试看。
+
+(boldify-names)
+
+;; `add-text-properties' 可以添加文字属性, 比如文字样式
+
+;; 好的,我们成功了!
+
+;; 如果你想对一个变量或者函数有更多的了解:
+;;
+;; C-h v 变量 回车
+;; C-h f 函数 回车
+;;
+;; 阅读Emacs Lisp官方文档:
+;;
+;; C-h i m elisp 回车
+;;
+;; 在线阅读Emacs Lisp文档:
+;; https://www.gnu.org/software/emacs/manual/html_node/eintr/index.html
+
+;; 感谢以下同学的建议和反馈:
+;; - Wes Hardaker
+;; - notbob
+;; - Kevin Montuori
+;; - Arne Babenhauserheide
+;; - Alan Schmitt
+;; - spacegoing
+```
+
diff --git a/zh-cn/elixir-cn.html.markdown b/zh-cn/elixir-cn.html.markdown
index daee8d3c..0ed1d823 100644
--- a/zh-cn/elixir-cn.html.markdown
+++ b/zh-cn/elixir-cn.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
translators:
diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown
index 707d6927..23f27dda 100644
--- a/zh-cn/markdown-cn.html.markdown
+++ b/zh-cn/markdown-cn.html.markdown
@@ -147,7 +147,6 @@ GitHub 也支持 Markdown,在 GitHub 的 Markdown 解析器中,我们可以
- 项目
- 项目
- 最后一个项目
-
```
有序序列可由数字加上点 `.` 来实现
@@ -188,6 +187,7 @@ GitHub 也支持 Markdown,在 GitHub 的 Markdown 解析器中,我们可以
下面这个选择框将会是选中状态
- [x] 这个任务已经完成
```
+
- [ ] 你看完了这个任务(注:此选择框是无法直接更改的,即禁用状态。)
## 代码块
@@ -204,7 +204,7 @@ GitHub 也支持 Markdown,在 GitHub 的 Markdown 解析器中,我们可以
```md
my_array.each do |item|
- puts item
+ puts item
end
```
@@ -216,12 +216,13 @@ John 甚至不知道 `go_to()` 函数是干嘛的!
在GitHub的 Markdown(GitHub Flavored Markdown)解析器中,你可以使用特殊的语法表示代码块
-<pre>
-<code class="highlight">&#x60;&#x60;&#x60;ruby
+````md
+```ruby
def foobar
- puts "Hello world!"
+ puts "Hello world!"
end
-&#x60;&#x60;&#x60;</code></pre>
+```
+````
以上代码不需要缩进,而且 GitHub 会根据\`\`\`后指定的语言来进行语法高亮显示
@@ -246,7 +247,6 @@ Markdown 最棒的地方就是便捷的书写链接。把链接文字放在中
```md
[点我点我!](http://test.com/)
-
```
你也可以在小括号内使用引号,为链接加上一个标题(title)
@@ -345,6 +345,7 @@ Markdown同样支持引用形式的链接
| 我是左对齐 | 居个中 | 右对齐 |
| 注意 | 冒 | 号 |
```
+
好吧,强行对齐字符是很难的。但是,至少比下面这种写法好一点——
```md
@@ -352,6 +353,7 @@ Markdown同样支持引用形式的链接
:-- | :-: | --:
这真的太丑了 | 药不能 | 停!!!!
```
+
真的是*看着令人头晕*
diff --git a/zh-cn/matlab-cn.html.markdown b/zh-cn/matlab-cn.html.markdown
index ca08b36b..bb1ab79a 100644
--- a/zh-cn/matlab-cn.html.markdown
+++ b/zh-cn/matlab-cn.html.markdown
@@ -1,504 +1,504 @@
----
-language: MATLAB
-filename: matlab-cn.m
-contributors:
- - ["mendozao", "http://github.com/mendozao"]
- - ["jamesscottbrown", "http://jamesscottbrown.com"]
-translators:
- - ["sunxb10", "https://github.com/sunxb10"]
-lang: zh-cn
-
----
-
-MATLAB 是 MATrix LABoratory(矩阵实验室)的缩写。
-它是一种功能强大的数值计算语言,在工程和数学领域中应用广泛。
-
-如果您有任何需要反馈或交流的内容,请联系本教程作者:
-[@the_ozzinator](https://twitter.com/the_ozzinator)
-或 [osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com)。
-
-```matlab
-% 以百分号作为注释符
-
-%{
-多行注释
-可以
-这样
-表示
-%}
-
-% 指令可以随意跨行,但需要在跨行处用 '...' 标明:
- a = 1 + 2 + ...
- + 4
-
-% 可以在MATLAB中直接向操作系统发出指令
-!ping google.com
-
-who % 显示内存中的所有变量
-whos % 显示内存中的所有变量以及它们的类型
-clear % 清除内存中的所有变量
-clear('A') % 清除指定的变量
-openvar('A') % 在变量编辑器中编辑指定变量
-
-clc % 清除命令窗口中显示的所有指令
-diary % 将命令窗口中的内容写入本地文件
-ctrl-c % 终止当前计算
-
-edit('myfunction.m') % 在编辑器中打开指定函数或脚本
-type('myfunction.m') % 在命令窗口中打印指定函数或脚本的源码
-
-profile on % 打开 profile 代码分析工具
-profile off % 关闭 profile 代码分析工具
-profile viewer % 查看 profile 代码分析工具的分析结果
-
-help command % 在命令窗口中显示指定命令的帮助文档
-doc command % 在帮助窗口中显示指定命令的帮助文档
-lookfor command % 在所有 MATLAB 内置函数的头部注释块的第一行中搜索指定命令
-lookfor command -all % 在所有 MATLAB 内置函数的整个头部注释块中搜索指定命令
-
-
-% 输出格式
-format short % 浮点数保留 4 位小数
-format long % 浮点数保留 15 位小数
-format bank % 金融格式,浮点数只保留 2 位小数
-fprintf('text') % 在命令窗口中显示 "text"
-disp('text') % 在命令窗口中显示 "text"
-
-
-% 变量与表达式
-myVariable = 4 % 命令窗口中将新创建的变量
-myVariable = 4; % 加上分号可使命令窗口中不显示当前语句执行结果
-4 + 6 % ans = 10
-8 * myVariable % ans = 32
-2 ^ 3 % ans = 8
-a = 2; b = 3;
-c = exp(a)*sin(pi/2) % c = 7.3891
-
-
-% 调用函数有两种方式:
-% 标准函数语法:
-load('myFile.mat', 'y') % 参数放在括号内,以英文逗号分隔
-% 指令语法:
-load myFile.mat y % 不加括号,以空格分隔参数
-% 注意在指令语法中参数不需要加引号:在这种语法下,所有输入参数都只能是文本文字,
-% 不能是变量的具体值,同样也不能是输出变量
-[V,D] = eig(A); % 这条函数调用无法转换成等价的指令语法
-[~,D] = eig(A); % 如果结果中只需要 D 而不需要 V 则可以这样写
-
-
-
-% 逻辑运算
-1 > 5 % 假,ans = 0
-10 >= 10 % 真,ans = 1
-3 ~= 4 % 不等于 -> ans = 1
-3 == 3 % 等于 -> ans = 1
-3 > 1 && 4 > 1 % 与 -> ans = 1
-3 > 1 || 4 > 1 % 或 -> ans = 1
-~1 % 非 -> ans = 0
-
-% 逻辑运算可直接应用于矩阵,运算结果也是矩阵
-A > 5
-% 对矩阵中每个元素做逻辑运算,若为真,则在运算结果的矩阵中对应位置的元素就是 1
-A( A > 5 )
-% 如此返回的向量,其元素就是 A 矩阵中所有逻辑运算为真的元素
-
-% 字符串
-a = 'MyString'
-length(a) % ans = 8
-a(2) % ans = y
-[a,a] % ans = MyStringMyString
-b = '字符串' % MATLAB目前已经可以支持包括中文在内的多种文字
-length(b) % ans = 3
-b(2) % ans = 符
-[b,b] % ans = 字符串字符串
-
-
-% 元组(cell 数组)
-a = {'one', 'two', 'three'}
-a(1) % ans = 'one' - 返回一个元组
-a{1} % ans = one - 返回一个字符串
-
-
-% 结构体
-A.b = {'one','two'};
-A.c = [1 2];
-A.d.e = false;
-
-
-% 向量
-x = [4 32 53 7 1]
-x(2) % ans = 32,MATLAB中向量的下标索引从1开始,不是0
-x(2:3) % ans = 32 53
-x(2:end) % ans = 32 53 7 1
-
-x = [4; 32; 53; 7; 1] % 列向量
-
-x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
-
-
-% 矩阵
-A = [1 2 3; 4 5 6; 7 8 9]
-% 以分号分隔不同的行,以空格或逗号分隔同一行中的不同元素
-% A =
-
-% 1 2 3
-% 4 5 6
-% 7 8 9
-
-A(2,3) % ans = 6,A(row, column)
-A(6) % ans = 8
-% (隐式地将 A 的三列首尾相接组成一个列向量,然后取其下标为 6 的元素)
-
-
-A(2,3) = 42 % 将第 2 行第 3 列的元素设为 42
-% A =
-
-% 1 2 3
-% 4 5 42
-% 7 8 9
-
-A(2:3,2:3) % 取原矩阵中的一块作为新矩阵
-%ans =
-
-% 5 42
-% 8 9
-
-A(:,1) % 第 1 列的所有元素
-%ans =
-
-% 1
-% 4
-% 7
-
-A(1,:) % 第 1 行的所有元素
-%ans =
-
-% 1 2 3
-
-[A ; A] % 将两个矩阵上下相接构成新矩阵
-%ans =
-
-% 1 2 3
-% 4 5 42
-% 7 8 9
-% 1 2 3
-% 4 5 42
-% 7 8 9
-
-% 等价于
-vertcat(A, A);
-
-
-[A , A] % 将两个矩阵左右相接构成新矩阵
-
-%ans =
-
-% 1 2 3 1 2 3
-% 4 5 42 4 5 42
-% 7 8 9 7 8 9
-
-% 等价于
-horzcat(A, A);
-
-
-A(:, [3 1 2]) % 重新排布原矩阵的各列
-%ans =
-
-% 3 1 2
-% 42 4 5
-% 9 7 8
-
-size(A) % 返回矩阵的行数和列数,ans = 3 3
-
-A(1, :) =[] % 删除矩阵的第 1 行
-A(:, 1) =[] % 删除矩阵的第 1 列
-
-transpose(A) % 矩阵(非共轭)转置,等价于 A.' (注意!有个点)
-ctranspose(A) % 矩阵的共轭转置(对矩阵中的每个元素取共轭复数),等价于 A'
-
-
-% 元素运算 vs. 矩阵运算
-% 单独运算符就是对矩阵整体进行矩阵运算
-% 在运算符加上英文句点就是对矩阵中的元素进行元素计算
-% 示例如下:
-A * B % 矩阵乘法,要求 A 的列数等于 B 的行数
-A .* B % 元素乘法,要求 A 和 B 形状一致,即两矩阵行列数完全一致
- % 元素乘法的结果是与 A 和 B 形状一致的矩阵
- % 其每个元素等于 A 对应位置的元素乘 B 对应位置的元素
-
-% 以下函数中,函数名以 m 结尾的执行矩阵运算,其余执行元素运算:
-exp(A) % 对矩阵中每个元素做指数运算
-expm(A) % 对矩阵整体做指数运算
-sqrt(A) % 对矩阵中每个元素做开方运算
-sqrtm(A) % 对矩阵整体做开方运算(即试图求出一个矩阵,该矩阵与自身的乘积等于 A 矩阵)
-
-
-% 绘图
-x = 0:0.1:2*pi; % 生成一向量,其元素从 0 开始,以 0.1 的间隔一直递增到 2*pi
- % 其中 pi 为圆周率
-y = sin(x);
-plot(x,y)
-xlabel('x axis')
-ylabel('y axis')
-title('Plot of y = sin(x)')
-axis([0 2*pi -1 1]) % x 轴范围是从 0 到 2*pi,y 轴范围是从 -1 到 1
-
-plot(x,y1,'-',x,y2,'--',x,y3,':') % 在同一张图中绘制多条曲线
-legend('Line 1 label', 'Line 2 label') % 为图片加注图例
-% 图例数量应当小于或等于实际绘制的曲线数目,从 plot 绘制的第一条曲线开始对应
-
-% 在同一张图上绘制多条曲线的另一种方法:
-% 使用 hold on,令系统保留前次绘图结果并在其上直接叠加新的曲线,
-% 如果没有 hold on,则每个 plot 都会首先清除之前的绘图结果再进行绘制。
-% 在 hold on 和 hold off 中可以放置任意多的 plot 指令,
-% 它们和 hold on 前最后一个 plot 指令的结果都将显示在同一张图中。
-plot(x, y1)
-hold on
-plot(x, y2)
-plot(x, y3)
-plot(x, y4)
-hold off
-
-loglog(x, y) % 对数—对数绘图
-semilogx(x, y) % 半对数(x 轴对数)绘图
-semilogy(x, y) % 半对数(y 轴对数)绘图
-
-fplot (@(x) x^2, [2,5]) % 绘制函数 x^2 在 [2, 5] 区间的曲线
-
-grid on % 在绘制的图中显示网格,使用 grid off 可取消网格显示
-axis square % 将当前坐标系设定为正方形(保证在图形显示上各轴等长)
-axis equal % 将当前坐标系设定为相等(保证在实际数值上各轴等长)
-
-scatter(x, y); % 散点图
-hist(x); % 直方图
-
-z = sin(x);
-plot3(x,y,z); % 绘制三维曲线
-
-pcolor(A) % 伪彩色图(热图)
-contour(A) % 等高线图
-mesh(A) % 网格曲面图
-
-h = figure % 创建新的图片对象并返回其句柄 h
-figure(h) % 将句柄 h 对应的图片作为当前图片
-close(h) % 关闭句柄 h 对应的图片
-close all % 关闭 MATLAB 中所用打开的图片
-close % 关闭当前图片
-
-shg % 显示图形窗口
-clf clear % 清除图形窗口中的图像,并重置图像属性
-
-% 图像属性可以通过图像句柄进行设定
-% 在创建图像时可以保存图像句柄以便于设置
-% 也可以用 gcf 函数返回当前图像的句柄
-h = plot(x, y); % 在创建图像时显式地保存图像句柄
-set(h, 'Color', 'r')
-% 颜色代码:
-% 'y' 黄色,'m' 洋红,'c' 青色
-% 'r' 红色,'g' 绿色,'b' 蓝色
-% 'w' 白色,'k' 黑色
-set(h, 'Color', [0.5, 0.5, 0.4])
-% 也可以使用 RGB 值指定颜色
-set(h, 'LineStyle', '--')
-% 线型代码:'--' 实线,'---' 虚线,':' 点线,'-.' 点划线,'none' 不划线
-get(h, 'LineStyle')
-% 获取当前句柄的线型
-
-
-% 用 gca 函数返回当前图像的坐标轴句柄
-set(gca, 'XDir', 'reverse'); % 令 x 轴反向
-
-% 用 subplot 指令创建平铺排列的多张子图
-subplot(2,3,1); % 选择 2 x 3 排列的子图中的第 1 张图
-plot(x1); title('First Plot') % 在选中的图中绘图
-subplot(2,3,2); % 选择 2 x 3 排列的子图中的第 2 张图
-plot(x2); title('Second Plot') % 在选中的图中绘图
-
-
-% 要调用函数或脚本,必须保证它们在你的当前工作目录中
-path % 显示当前工作目录
-addpath /path/to/dir % 将指定路径加入到当前工作目录中
-rmpath /path/to/dir % 将指定路径从当前工作目录中删除
-cd /path/to/move/into % 以制定路径作为当前工作目录
-
-
-% 变量可保存到 .mat 格式的本地文件
-save('myFileName.mat') % 保存当前工作空间中的所有变量
-load('myFileName.mat') % 将指定文件中的变量载入到当前工作空间
-
-
-% .m 脚本文件
-% 脚本文件是一个包含多条 MATLAB 指令的外部文件,以 .m 为后缀名
-% 使用脚本文件可以避免在命令窗口中重复输入冗长的指令
-
-
-% .m 函数文件
-% 与脚本文件类似,同样以 .m 作为后缀名
-% 但函数文件可以接受用户输入的参数并返回运算结果
-% 并且函数拥有自己的工作空间(变量域),不必担心变量名称冲突
-% 函数文件的名称应当与其所定义的函数的名称一致
-% 比如下面例子中函数文件就应命名为 double_input.m
-% 使用 'help double_input.m' 可返回函数定义中第一行注释信息
-function output = double_input(x)
- % double_input(x) 返回 x 的 2 倍
- output = 2*x;
-end
-double_input(6) % ans = 12
-
-
-% 同样还可以定义子函数和内嵌函数
-% 子函数与主函数放在同一个函数文件中,且只能被这个主函数调用
-% 内嵌函数放在另一个函数体内,可以直接访问被嵌套函数的各个变量
-
-
-% 使用匿名函数可以不必创建 .m 函数文件
-% 匿名函数适用于快速定义某函数以便传递给另一指令或函数(如绘图、积分、求根、求极值等)
-% 下面示例的匿名函数返回输入参数的平方根,可以使用句柄 sqr 进行调用:
-sqr = @(x) x.^2;
-sqr(10) % ans = 100
-doc function_handle % find out more
-
-
-% 接受用户输入
-a = input('Enter the value: ')
-
-
-% 从文件中读取数据
-fopen(filename)
-% 类似函数还有 xlsread(excel 文件)、importdata(CSV 文件)、imread(图像文件)
-
-
-% 输出
-disp(a) % 在命令窗口中打印变量 a 的值
-disp('Hello World') % 在命令窗口中打印字符串
-fprintf % 按照指定格式在命令窗口中打印内容
-
-% 条件语句(if 和 elseif 语句中的括号并非必需,但推荐加括号避免混淆)
-if (a > 15)
- disp('Greater than 15')
-elseif (a == 23)
- disp('a is 23')
-else
- disp('neither condition met')
-end
-
-% 循环语句
-% 注意:对向量或矩阵使用循环语句进行元素遍历的效率很低!!
-% 注意:只要有可能,就尽量使用向量或矩阵的整体运算取代逐元素循环遍历!!
-% MATLAB 在开发时对向量和矩阵运算做了专门优化,做向量和矩阵整体运算的效率高于循环语句
-for k = 1:5
- disp(k)
-end
-
-k = 0;
-while (k < 5)
- k = k + 1;
-end
-
-
-% 程序运行计时:'tic' 是计时开始,'toc' 是计时结束并打印结果
-tic
-A = rand(1000);
-A*A*A*A*A*A*A;
-toc
-
-
-% 链接 MySQL 数据库
-dbname = 'database_name';
-username = 'root';
-password = 'root';
-driver = 'com.mysql.jdbc.Driver';
-dburl = ['jdbc:mysql://localhost:8889/' dbname];
-javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); % 此处 xx 代表具体版本号
-% 这里的 mysql-connector-java-5.1.xx-bin.jar 可从 http://dev.mysql.com/downloads/connector/j/ 下载
-conn = database(dbname, username, password, driver, dburl);
-sql = ['SELECT * from table_name where id = 22'] % SQL 语句
-a = fetch(conn, sql) % a 即包含所需数据
-
-
-% 常用数学函数
-sin(x)
-cos(x)
-tan(x)
-asin(x)
-acos(x)
-atan(x)
-exp(x)
-sqrt(x)
-log(x)
-log10(x)
-abs(x)
-min(x)
-max(x)
-ceil(x)
-floor(x)
-round(x)
-rem(x)
-rand % 均匀分布的伪随机浮点数
-randi % 均匀分布的伪随机整数
-randn % 正态分布的伪随机浮点数
-
-% 常用常数
-pi
-NaN
-inf
-
-% 求解矩阵方程(如果方程无解,则返回最小二乘近似解)
-% \ 操作符等价于 mldivide 函数,/ 操作符等价于 mrdivide 函数
-x=A\b % 求解 Ax=b,比先求逆再左乘 inv(A)*b 更加高效、准确
-x=b/A % 求解 xA=b
-
-inv(A) % 逆矩阵
-pinv(A) % 伪逆矩阵
-
-
-% 常用矩阵函数
-zeros(m, n) % m x n 阶矩阵,元素全为 0
-ones(m, n) % m x n 阶矩阵,元素全为 1
-diag(A) % 返回矩阵 A 的对角线元素
-diag(x) % 构造一个对角阵,对角线元素就是向量 x 的各元素
-eye(m, n) % m x n 阶单位矩阵
-linspace(x1, x2, n) % 返回介于 x1 和 x2 之间的 n 个等距节点
-inv(A) % 矩阵 A 的逆矩阵
-det(A) % 矩阵 A 的行列式
-eig(A) % 矩阵 A 的特征值和特征向量
-trace(A) % 矩阵 A 的迹(即对角线元素之和),等价于 sum(diag(A))
-isempty(A) % 测试 A 是否为空
-all(A) % 测试 A 中所有元素是否都非 0 或都为真(逻辑值)
-any(A) % 测试 A 中是否有元素非 0 或为真(逻辑值)
-isequal(A, B) % 测试 A 和 B是否相等
-numel(A) % 矩阵 A 的元素个数
-triu(x) % 返回 x 的上三角这部分
-tril(x) % 返回 x 的下三角这部分
-cross(A, B) % 返回 A 和 B 的叉积(矢量积、外积)
-dot(A, B) % 返回 A 和 B 的点积(数量积、内积),要求 A 和 B 必须等长
-transpose(A) % 矩阵(非共轭)转置,等价于 A.' (注意!有个点)
-fliplr(A) % 将一个矩阵左右翻转
-flipud(A) % 将一个矩阵上下翻转
-
-% 矩阵分解
-[L, U, P] = lu(A) % LU 分解:PA = LU,L 是下三角阵,U 是上三角阵,P 是置换阵
-[P, D] = eig(A) % 特征值分解:AP = PD
- % D 是由特征值构成的对角阵,P 的各列就是对应的特征向量
-[U, S, V] = svd(X) % 奇异值分解:XV = US
- % U 和 V 是酉矩阵,S 是由奇异值构成的半正定实数对角阵
-
-% 常用向量函数
-max % 最大值
-min % 最小值
-length % 元素个数
-sort % 按升序排列
-sum % 各元素之和
-prod % 各元素之积
-mode % 众数
-median % 中位数
-mean % 平均值
-std % 标准差
-perms(x) % x 元素的全排列
-
-```
-
-## 相关资料
-
-* 官方网页:[MATLAB - 技术计算语言 - MATLAB & Simulink](https://ww2.mathworks.cn/products/matlab.html)
-* 官方论坛:[MATLAB Answers - MATLAB Central](https://ww2.mathworks.cn/matlabcentral/answers/)
+---
+language: MATLAB
+filename: matlab-cn.m
+contributors:
+ - ["mendozao", "http://github.com/mendozao"]
+ - ["jamesscottbrown", "http://jamesscottbrown.com"]
+translators:
+ - ["sunxb10", "https://github.com/sunxb10"]
+lang: zh-cn
+
+---
+
+MATLAB 是 MATrix LABoratory(矩阵实验室)的缩写。
+它是一种功能强大的数值计算语言,在工程和数学领域中应用广泛。
+
+如果您有任何需要反馈或交流的内容,请联系本教程作者:
+[@the_ozzinator](https://twitter.com/the_ozzinator)
+或 [osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com)。
+
+```matlab
+% 以百分号作为注释符
+
+%{
+多行注释
+可以
+这样
+表示
+%}
+
+% 指令可以随意跨行,但需要在跨行处用 '...' 标明:
+ a = 1 + 2 + ...
+ + 4
+
+% 可以在MATLAB中直接向操作系统发出指令
+!ping google.com
+
+who % 显示内存中的所有变量
+whos % 显示内存中的所有变量以及它们的类型
+clear % 清除内存中的所有变量
+clear('A') % 清除指定的变量
+openvar('A') % 在变量编辑器中编辑指定变量
+
+clc % 清除命令窗口中显示的所有指令
+diary % 将命令窗口中的内容写入本地文件
+ctrl-c % 终止当前计算
+
+edit('myfunction.m') % 在编辑器中打开指定函数或脚本
+type('myfunction.m') % 在命令窗口中打印指定函数或脚本的源码
+
+profile on % 打开 profile 代码分析工具
+profile off % 关闭 profile 代码分析工具
+profile viewer % 查看 profile 代码分析工具的分析结果
+
+help command % 在命令窗口中显示指定命令的帮助文档
+doc command % 在帮助窗口中显示指定命令的帮助文档
+lookfor command % 在所有 MATLAB 内置函数的头部注释块的第一行中搜索指定命令
+lookfor command -all % 在所有 MATLAB 内置函数的整个头部注释块中搜索指定命令
+
+
+% 输出格式
+format short % 浮点数保留 4 位小数
+format long % 浮点数保留 15 位小数
+format bank % 金融格式,浮点数只保留 2 位小数
+fprintf('text') % 在命令窗口中显示 "text"
+disp('text') % 在命令窗口中显示 "text"
+
+
+% 变量与表达式
+myVariable = 4 % 命令窗口中将新创建的变量
+myVariable = 4; % 加上分号可使命令窗口中不显示当前语句执行结果
+4 + 6 % ans = 10
+8 * myVariable % ans = 32
+2 ^ 3 % ans = 8
+a = 2; b = 3;
+c = exp(a)*sin(pi/2) % c = 7.3891
+
+
+% 调用函数有两种方式:
+% 标准函数语法:
+load('myFile.mat', 'y') % 参数放在括号内,以英文逗号分隔
+% 指令语法:
+load myFile.mat y % 不加括号,以空格分隔参数
+% 注意在指令语法中参数不需要加引号:在这种语法下,所有输入参数都只能是文本文字,
+% 不能是变量的具体值,同样也不能是输出变量
+[V,D] = eig(A); % 这条函数调用无法转换成等价的指令语法
+[~,D] = eig(A); % 如果结果中只需要 D 而不需要 V 则可以这样写
+
+
+
+% 逻辑运算
+1 > 5 % 假,ans = 0
+10 >= 10 % 真,ans = 1
+3 ~= 4 % 不等于 -> ans = 1
+3 == 3 % 等于 -> ans = 1
+3 > 1 && 4 > 1 % 与 -> ans = 1
+3 > 1 || 4 > 1 % 或 -> ans = 1
+~1 % 非 -> ans = 0
+
+% 逻辑运算可直接应用于矩阵,运算结果也是矩阵
+A > 5
+% 对矩阵中每个元素做逻辑运算,若为真,则在运算结果的矩阵中对应位置的元素就是 1
+A( A > 5 )
+% 如此返回的向量,其元素就是 A 矩阵中所有逻辑运算为真的元素
+
+% 字符串
+a = 'MyString'
+length(a) % ans = 8
+a(2) % ans = y
+[a,a] % ans = MyStringMyString
+b = '字符串' % MATLAB目前已经可以支持包括中文在内的多种文字
+length(b) % ans = 3
+b(2) % ans = 符
+[b,b] % ans = 字符串字符串
+
+
+% 元组(cell 数组)
+a = {'one', 'two', 'three'}
+a(1) % ans = 'one' - 返回一个元组
+a{1} % ans = one - 返回一个字符串
+
+
+% 结构体
+A.b = {'one','two'};
+A.c = [1 2];
+A.d.e = false;
+
+
+% 向量
+x = [4 32 53 7 1]
+x(2) % ans = 32,MATLAB中向量的下标索引从1开始,不是0
+x(2:3) % ans = 32 53
+x(2:end) % ans = 32 53 7 1
+
+x = [4; 32; 53; 7; 1] % 列向量
+
+x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
+
+
+% 矩阵
+A = [1 2 3; 4 5 6; 7 8 9]
+% 以分号分隔不同的行,以空格或逗号分隔同一行中的不同元素
+% A =
+
+% 1 2 3
+% 4 5 6
+% 7 8 9
+
+A(2,3) % ans = 6,A(row, column)
+A(6) % ans = 8
+% (隐式地将 A 的三列首尾相接组成一个列向量,然后取其下标为 6 的元素)
+
+
+A(2,3) = 42 % 将第 2 行第 3 列的元素设为 42
+% A =
+
+% 1 2 3
+% 4 5 42
+% 7 8 9
+
+A(2:3,2:3) % 取原矩阵中的一块作为新矩阵
+%ans =
+
+% 5 42
+% 8 9
+
+A(:,1) % 第 1 列的所有元素
+%ans =
+
+% 1
+% 4
+% 7
+
+A(1,:) % 第 1 行的所有元素
+%ans =
+
+% 1 2 3
+
+[A ; A] % 将两个矩阵上下相接构成新矩阵
+%ans =
+
+% 1 2 3
+% 4 5 42
+% 7 8 9
+% 1 2 3
+% 4 5 42
+% 7 8 9
+
+% 等价于
+vertcat(A, A);
+
+
+[A , A] % 将两个矩阵左右相接构成新矩阵
+
+%ans =
+
+% 1 2 3 1 2 3
+% 4 5 42 4 5 42
+% 7 8 9 7 8 9
+
+% 等价于
+horzcat(A, A);
+
+
+A(:, [3 1 2]) % 重新排布原矩阵的各列
+%ans =
+
+% 3 1 2
+% 42 4 5
+% 9 7 8
+
+size(A) % 返回矩阵的行数和列数,ans = 3 3
+
+A(1, :) =[] % 删除矩阵的第 1 行
+A(:, 1) =[] % 删除矩阵的第 1 列
+
+transpose(A) % 矩阵(非共轭)转置,等价于 A.' (注意!有个点)
+ctranspose(A) % 矩阵的共轭转置(对矩阵中的每个元素取共轭复数),等价于 A'
+
+
+% 元素运算 vs. 矩阵运算
+% 单独运算符就是对矩阵整体进行矩阵运算
+% 在运算符加上英文句点就是对矩阵中的元素进行元素计算
+% 示例如下:
+A * B % 矩阵乘法,要求 A 的列数等于 B 的行数
+A .* B % 元素乘法,要求 A 和 B 形状一致,即两矩阵行列数完全一致
+ % 元素乘法的结果是与 A 和 B 形状一致的矩阵
+ % 其每个元素等于 A 对应位置的元素乘 B 对应位置的元素
+
+% 以下函数中,函数名以 m 结尾的执行矩阵运算,其余执行元素运算:
+exp(A) % 对矩阵中每个元素做指数运算
+expm(A) % 对矩阵整体做指数运算
+sqrt(A) % 对矩阵中每个元素做开方运算
+sqrtm(A) % 对矩阵整体做开方运算(即试图求出一个矩阵,该矩阵与自身的乘积等于 A 矩阵)
+
+
+% 绘图
+x = 0:0.1:2*pi; % 生成一向量,其元素从 0 开始,以 0.1 的间隔一直递增到 2*pi
+ % 其中 pi 为圆周率
+y = sin(x);
+plot(x,y)
+xlabel('x axis')
+ylabel('y axis')
+title('Plot of y = sin(x)')
+axis([0 2*pi -1 1]) % x 轴范围是从 0 到 2*pi,y 轴范围是从 -1 到 1
+
+plot(x,y1,'-',x,y2,'--',x,y3,':') % 在同一张图中绘制多条曲线
+legend('Line 1 label', 'Line 2 label') % 为图片加注图例
+% 图例数量应当小于或等于实际绘制的曲线数目,从 plot 绘制的第一条曲线开始对应
+
+% 在同一张图上绘制多条曲线的另一种方法:
+% 使用 hold on,令系统保留前次绘图结果并在其上直接叠加新的曲线,
+% 如果没有 hold on,则每个 plot 都会首先清除之前的绘图结果再进行绘制。
+% 在 hold on 和 hold off 中可以放置任意多的 plot 指令,
+% 它们和 hold on 前最后一个 plot 指令的结果都将显示在同一张图中。
+plot(x, y1)
+hold on
+plot(x, y2)
+plot(x, y3)
+plot(x, y4)
+hold off
+
+loglog(x, y) % 对数—对数绘图
+semilogx(x, y) % 半对数(x 轴对数)绘图
+semilogy(x, y) % 半对数(y 轴对数)绘图
+
+fplot (@(x) x^2, [2,5]) % 绘制函数 x^2 在 [2, 5] 区间的曲线
+
+grid on % 在绘制的图中显示网格,使用 grid off 可取消网格显示
+axis square % 将当前坐标系设定为正方形(保证在图形显示上各轴等长)
+axis equal % 将当前坐标系设定为相等(保证在实际数值上各轴等长)
+
+scatter(x, y); % 散点图
+hist(x); % 直方图
+
+z = sin(x);
+plot3(x,y,z); % 绘制三维曲线
+
+pcolor(A) % 伪彩色图(热图)
+contour(A) % 等高线图
+mesh(A) % 网格曲面图
+
+h = figure % 创建新的图片对象并返回其句柄 h
+figure(h) % 将句柄 h 对应的图片作为当前图片
+close(h) % 关闭句柄 h 对应的图片
+close all % 关闭 MATLAB 中所用打开的图片
+close % 关闭当前图片
+
+shg % 显示图形窗口
+clf clear % 清除图形窗口中的图像,并重置图像属性
+
+% 图像属性可以通过图像句柄进行设定
+% 在创建图像时可以保存图像句柄以便于设置
+% 也可以用 gcf 函数返回当前图像的句柄
+h = plot(x, y); % 在创建图像时显式地保存图像句柄
+set(h, 'Color', 'r')
+% 颜色代码:
+% 'y' 黄色,'m' 洋红,'c' 青色
+% 'r' 红色,'g' 绿色,'b' 蓝色
+% 'w' 白色,'k' 黑色
+set(h, 'Color', [0.5, 0.5, 0.4])
+% 也可以使用 RGB 值指定颜色
+set(h, 'LineStyle', '--')
+% 线型代码:'--' 实线,'---' 虚线,':' 点线,'-.' 点划线,'none' 不划线
+get(h, 'LineStyle')
+% 获取当前句柄的线型
+
+
+% 用 gca 函数返回当前图像的坐标轴句柄
+set(gca, 'XDir', 'reverse'); % 令 x 轴反向
+
+% 用 subplot 指令创建平铺排列的多张子图
+subplot(2,3,1); % 选择 2 x 3 排列的子图中的第 1 张图
+plot(x1); title('First Plot') % 在选中的图中绘图
+subplot(2,3,2); % 选择 2 x 3 排列的子图中的第 2 张图
+plot(x2); title('Second Plot') % 在选中的图中绘图
+
+
+% 要调用函数或脚本,必须保证它们在你的当前工作目录中
+path % 显示当前工作目录
+addpath /path/to/dir % 将指定路径加入到当前工作目录中
+rmpath /path/to/dir % 将指定路径从当前工作目录中删除
+cd /path/to/move/into % 以制定路径作为当前工作目录
+
+
+% 变量可保存到 .mat 格式的本地文件
+save('myFileName.mat') % 保存当前工作空间中的所有变量
+load('myFileName.mat') % 将指定文件中的变量载入到当前工作空间
+
+
+% .m 脚本文件
+% 脚本文件是一个包含多条 MATLAB 指令的外部文件,以 .m 为后缀名
+% 使用脚本文件可以避免在命令窗口中重复输入冗长的指令
+
+
+% .m 函数文件
+% 与脚本文件类似,同样以 .m 作为后缀名
+% 但函数文件可以接受用户输入的参数并返回运算结果
+% 并且函数拥有自己的工作空间(变量域),不必担心变量名称冲突
+% 函数文件的名称应当与其所定义的函数的名称一致
+% 比如下面例子中函数文件就应命名为 double_input.m
+% 使用 'help double_input.m' 可返回函数定义中第一行注释信息
+function output = double_input(x)
+ % double_input(x) 返回 x 的 2 倍
+ output = 2*x;
+end
+double_input(6) % ans = 12
+
+
+% 同样还可以定义子函数和内嵌函数
+% 子函数与主函数放在同一个函数文件中,且只能被这个主函数调用
+% 内嵌函数放在另一个函数体内,可以直接访问被嵌套函数的各个变量
+
+
+% 使用匿名函数可以不必创建 .m 函数文件
+% 匿名函数适用于快速定义某函数以便传递给另一指令或函数(如绘图、积分、求根、求极值等)
+% 下面示例的匿名函数返回输入参数的平方根,可以使用句柄 sqr 进行调用:
+sqr = @(x) x.^2;
+sqr(10) % ans = 100
+doc function_handle % find out more
+
+
+% 接受用户输入
+a = input('Enter the value: ')
+
+
+% 从文件中读取数据
+fopen(filename)
+% 类似函数还有 xlsread(excel 文件)、importdata(CSV 文件)、imread(图像文件)
+
+
+% 输出
+disp(a) % 在命令窗口中打印变量 a 的值
+disp('Hello World') % 在命令窗口中打印字符串
+fprintf % 按照指定格式在命令窗口中打印内容
+
+% 条件语句(if 和 elseif 语句中的括号并非必需,但推荐加括号避免混淆)
+if (a > 15)
+ disp('Greater than 15')
+elseif (a == 23)
+ disp('a is 23')
+else
+ disp('neither condition met')
+end
+
+% 循环语句
+% 注意:对向量或矩阵使用循环语句进行元素遍历的效率很低!!
+% 注意:只要有可能,就尽量使用向量或矩阵的整体运算取代逐元素循环遍历!!
+% MATLAB 在开发时对向量和矩阵运算做了专门优化,做向量和矩阵整体运算的效率高于循环语句
+for k = 1:5
+ disp(k)
+end
+
+k = 0;
+while (k < 5)
+ k = k + 1;
+end
+
+
+% 程序运行计时:'tic' 是计时开始,'toc' 是计时结束并打印结果
+tic
+A = rand(1000);
+A*A*A*A*A*A*A;
+toc
+
+
+% 链接 MySQL 数据库
+dbname = 'database_name';
+username = 'root';
+password = 'root';
+driver = 'com.mysql.jdbc.Driver';
+dburl = ['jdbc:mysql://localhost:8889/' dbname];
+javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); % 此处 xx 代表具体版本号
+% 这里的 mysql-connector-java-5.1.xx-bin.jar 可从 http://dev.mysql.com/downloads/connector/j/ 下载
+conn = database(dbname, username, password, driver, dburl);
+sql = ['SELECT * from table_name where id = 22'] % SQL 语句
+a = fetch(conn, sql) % a 即包含所需数据
+
+
+% 常用数学函数
+sin(x)
+cos(x)
+tan(x)
+asin(x)
+acos(x)
+atan(x)
+exp(x)
+sqrt(x)
+log(x)
+log10(x)
+abs(x)
+min(x)
+max(x)
+ceil(x)
+floor(x)
+round(x)
+rem(x)
+rand % 均匀分布的伪随机浮点数
+randi % 均匀分布的伪随机整数
+randn % 正态分布的伪随机浮点数
+
+% 常用常数
+pi
+NaN
+inf
+
+% 求解矩阵方程(如果方程无解,则返回最小二乘近似解)
+% \ 操作符等价于 mldivide 函数,/ 操作符等价于 mrdivide 函数
+x=A\b % 求解 Ax=b,比先求逆再左乘 inv(A)*b 更加高效、准确
+x=b/A % 求解 xA=b
+
+inv(A) % 逆矩阵
+pinv(A) % 伪逆矩阵
+
+
+% 常用矩阵函数
+zeros(m, n) % m x n 阶矩阵,元素全为 0
+ones(m, n) % m x n 阶矩阵,元素全为 1
+diag(A) % 返回矩阵 A 的对角线元素
+diag(x) % 构造一个对角阵,对角线元素就是向量 x 的各元素
+eye(m, n) % m x n 阶单位矩阵
+linspace(x1, x2, n) % 返回介于 x1 和 x2 之间的 n 个等距节点
+inv(A) % 矩阵 A 的逆矩阵
+det(A) % 矩阵 A 的行列式
+eig(A) % 矩阵 A 的特征值和特征向量
+trace(A) % 矩阵 A 的迹(即对角线元素之和),等价于 sum(diag(A))
+isempty(A) % 测试 A 是否为空
+all(A) % 测试 A 中所有元素是否都非 0 或都为真(逻辑值)
+any(A) % 测试 A 中是否有元素非 0 或为真(逻辑值)
+isequal(A, B) % 测试 A 和 B是否相等
+numel(A) % 矩阵 A 的元素个数
+triu(x) % 返回 x 的上三角这部分
+tril(x) % 返回 x 的下三角这部分
+cross(A, B) % 返回 A 和 B 的叉积(矢量积、外积)
+dot(A, B) % 返回 A 和 B 的点积(数量积、内积),要求 A 和 B 必须等长
+transpose(A) % 矩阵(非共轭)转置,等价于 A.' (注意!有个点)
+fliplr(A) % 将一个矩阵左右翻转
+flipud(A) % 将一个矩阵上下翻转
+
+% 矩阵分解
+[L, U, P] = lu(A) % LU 分解:PA = LU,L 是下三角阵,U 是上三角阵,P 是置换阵
+[P, D] = eig(A) % 特征值分解:AP = PD
+ % D 是由特征值构成的对角阵,P 的各列就是对应的特征向量
+[U, S, V] = svd(X) % 奇异值分解:XV = US
+ % U 和 V 是酉矩阵,S 是由奇异值构成的半正定实数对角阵
+
+% 常用向量函数
+max % 最大值
+min % 最小值
+length % 元素个数
+sort % 按升序排列
+sum % 各元素之和
+prod % 各元素之积
+mode % 众数
+median % 中位数
+mean % 平均值
+std % 标准差
+perms(x) % x 元素的全排列
+
+```
+
+## 相关资料
+
+* 官方网页:[MATLAB - 技术计算语言 - MATLAB & Simulink](https://ww2.mathworks.cn/products/matlab.html)
+* 官方论坛:[MATLAB Answers - MATLAB Central](https://ww2.mathworks.cn/matlabcentral/answers/)
diff --git a/zh-cn/pyqt-cn.html.markdown b/zh-cn/pyqt-cn.html.markdown
index 55e5bbe3..04041c83 100644
--- a/zh-cn/pyqt-cn.html.markdown
+++ b/zh-cn/pyqt-cn.html.markdown
@@ -19,7 +19,7 @@ lang: zh-cn
```python
import sys
from PyQt4 import QtGui
-
+
def window():
# 创建应用对象
app = QtGui.QApplication(sys.argv)
@@ -44,7 +44,7 @@ if __name__ == '__main__':
为了运用 pyqt 中一些更高级的功能,我们需要开始学习使用其他控件。下文演示了如何弹出对话框,该对话框在用户确认操作或输入信息等情况下经常用到。
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
@@ -62,7 +62,7 @@ def window():
w.setWindowTitle("PyQt Dialog")
w.show()
sys.exit(app.exec_())
-
+
# 对话框窗口创建函数
# 当窗口中的按钮被点击时退出本程序
def showdialog():
diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown
index c56a0d33..7955cc2b 100644
--- a/zh-cn/swift-cn.html.markdown
+++ b/zh-cn/swift-cn.html.markdown
@@ -12,7 +12,7 @@ lang: zh-cn
Swift 是 Apple 开发的用于 iOS 和 macOS 开发的编程语言。Swift 于2014年 Apple WWDC (全球开发者大会)中被引入,用以与 Objective-C 共存,同时对错误代码更具弹性。Swift 由 Xcode 6 beta 中包含的 LLVM 编译器编译。
-Swift 的官方语言教程 [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) 可以从 iBooks 免费下载.
+Swift 的官方语言教程 [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) 可以从 Apple Books 免费下载.
亦可参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/) ——一个完整的Swift 教程
diff --git a/zh-cn/visualbasic-cn.html.markdown b/zh-cn/visualbasic-cn.html.markdown
index e30041b3..cda7b864 100644
--- a/zh-cn/visualbasic-cn.html.markdown
+++ b/zh-cn/visualbasic-cn.html.markdown
@@ -8,7 +8,7 @@ lang: zh-cn
filename: learnvisualbasic-cn.vb
---
-```
+```visualbasic
Module Module1
Sub Main()
diff --git a/zh-cn/wolfram-cn.html.markdown b/zh-cn/wolfram-cn.html.markdown
index 9d6ef54f..64990234 100644
--- a/zh-cn/wolfram-cn.html.markdown
+++ b/zh-cn/wolfram-cn.html.markdown
@@ -18,7 +18,7 @@ Wolfram 语言有几个界面。
本例中的代码可以在任何界面中输入,并使用 Wolfram Workbench 进行编辑。直接加载到 Mathematica 中可能会很不方便,因为该文件不包含单元格格式化信息(这将使该文件作为文本阅读时变得一团糟)--它可以被查看/编辑,但可能需要一些设置。
-```mma
+```mathematica
(* 这是一个注释 *)
(* 在Mathematica中,您可以创建一个文本单元格,用排版好的文本和图像来注释您的代码,而不是使用这些注释 *)
diff --git a/zh-cn/zfs-cn.html.markdown b/zh-cn/zfs-cn.html.markdown
index fdf5277e..80688fbe 100644
--- a/zh-cn/zfs-cn.html.markdown
+++ b/zh-cn/zfs-cn.html.markdown
@@ -288,6 +288,7 @@ tank/home/sarlalian@now 0 - 259M -
tank/home/alice@now 0 - 156M -
tank/home/bob@now 0 - 156M -
...
+```
Destroy snapshots (删除快照)
@@ -297,7 +298,6 @@ $ zfs destroy tank/home/sarlalian@now
# 删除某一数据集及其子集的快照
$ zfs destroy -r tank/home/sarlalian@now
-
```
Renaming Snapshots (重命名)
diff --git a/zh-tw/elixir-tw.html.markdown b/zh-tw/elixir-tw.html.markdown
index c15f90c1..3dba95b3 100644
--- a/zh-tw/elixir-tw.html.markdown
+++ b/zh-tw/elixir-tw.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
@@ -19,10 +19,10 @@ Elixir 是一門建構在 Erlang 虛擬機上的現代函數式語言。它完
# 沒有多行註解的功能
# 但你可以連續使用多個單行
-# 用 `iex` 來進入 elixir shell
+# 用 `iex` 來進入 Elixir shell
# 用 `elixirc` 來編譯你的模組
-# 如果你已成功安裝 elixir 的話,這兩個命令應已在你的 path 下。
+# 如果你已成功安裝 Elixir 的話,這兩個命令應已在你的 path 下。
## ---------------------------
## -- 基本型別
@@ -50,7 +50,7 @@ elem({1, 2, 3}, 0) #=> 1
head #=> 1
tail #=> [2,3]
-# 在 elixir 中,就如同 Erlang 裡一樣,`=` 代表的是模式比對,而非指派。
+# 在 Elixir 中,就如同 Erlang 裡一樣,`=` 代表的是模式比對,而非指派。
#
# 這代表將使用左手邊的模式 (pattern) 去與右手邊的值進行比對。
#
@@ -80,7 +80,7 @@ string.
<<?a, ?b, ?c>> #=> "abc"
[?a, ?b, ?c] #=> 'abc'
-# `?a` 在 elixir 中會回傳字母 `a` 的 ASCII 整數
+# `?a` 在 Elixir 中會回傳字母 `a` 的 ASCII 整數
?a #=> 97
# 用 `++` 來合併串列,而合併二進位則要用 `<>`
@@ -105,7 +105,7 @@ lower..upper = 1..10 # 可以對 range 進行模式比對
5 * 2 #=> 10
10 / 2 #=> 5.0
-# 在 elixir 中, `/` 運算元永遠回傳浮點數。
+# 在 Elixir 中, `/` 運算元永遠回傳浮點數。
# 若需要回傳整數的除法,用 `div`
div(10, 2) #=> 5
@@ -290,7 +290,7 @@ Geometry.area({:circle, 3}) #=> 28.25999999999999801048
# Geometry.area({:circle, "not_a_number"})
#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
-# 由於不可變特性 (immutability),遞迴在 elixir 中扮演重要的角色。
+# 由於不可變特性 (immutability),遞迴在 Elixir 中扮演重要的角色。
defmodule Recursion do
def sum_list([head | tail], acc) do
sum_list(tail, acc + head)
@@ -356,7 +356,7 @@ end
## -- 平行處理
## ---------------------------
-# Elixir 依靠 actor 模式來進行平行處理。在 elixir 中要寫出平行處理程式,
+# Elixir 依靠 actor 模式來進行平行處理。在 Elixir 中要寫出平行處理程式,
# 只需要三個基本要素:建立行程,發送訊息及接收訊息。
# 我們用 `spawn` 函式來建立行程,它接收一個函式當參數。
diff --git a/zig.html.markdown b/zig.html.markdown
index f8c866e5..65fd1e6b 100644
--- a/zig.html.markdown
+++ b/zig.html.markdown
@@ -5,24 +5,19 @@ contributors:
- ["Philippe Pittoli", "https://karchnu.fr/"]
---
-
[Zig][ziglang] aims to be a replacement for the C programming language.
**WARNING**: this document expects you to understand a few basic concepts in computer science, such as pointers, stack and heap memory, etc.
**WARNING**: Zig isn't considered as ready for production. Bugs are expected.
-DO NOT TRY ZIG AS YOUR FIRST PROGRAMMING EXPERIENCE.
-The compiler, even the language and its libraries aren't ready, yet.
-You've been warned.
Prior knowledge of C is recommended.
-
## Quick overview: Zig compared to C
- Syntax is mostly the same, with some improvements (less ambiguity).
- Zig introduces namespaces.
-- Try and catch mechanism, which is both convenient, efficient and optional.
+- `try` and `catch` mechanism, which is both convenient, efficient and optional.
- Most of the C undefined behaviors (UBs) are fixed.
- Compared to C, raw pointers are safer to use and less likely to be needed.
* The type system distinguishes between a pointer to a single value, or multiple values, etc.
@@ -38,8 +33,7 @@ Prior knowledge of C is recommended.
## Zig language
-
-```
+```zig
//! Top-level documentation.
/// Documentation comment.
@@ -47,9 +41,9 @@ Prior knowledge of C is recommended.
// Simple comment.
```
-
### Hello world.
-```
+
+```zig
// Import standard library, reachable through the "std" constant.
const std = @import("std");
@@ -67,7 +61,8 @@ pub fn main() void {
```
### Booleans, integers and float.
-```
+
+```zig
// Booleans.
// Keywords are preferred to operators for boolean operations.
print("{}\n{}\n{}\n", .{
@@ -109,7 +104,8 @@ i <<| 8 == 255 // u8: won't go higher than 255
```
### Arrays.
-```
+
+```zig
// An array is a well-defined structure with a length attribute (len).
// 5-byte array with undefined content (stack garbage).
@@ -156,8 +152,8 @@ try some_integers[i]; // Runtime error 'index out of bounds'.
```
### Multidimensional arrays.
-```
+```zig
const mat4x4 = [4][4]f32{
[_]f32{ 1.0, 0.0, 0.0, 0.0 },
[_]f32{ 0.0, 1.0, 0.0, 1.0 },
@@ -177,8 +173,8 @@ for (mat4x4) |row, row_index| {
```
### Strings.
-```
+```zig
// Simple string constant.
const greetings = "hello";
// ... which is equivalent to:
@@ -195,8 +191,8 @@ print("string: {s}\n", .{greetings});
```
### Slices.
-```
+```zig
// A slice is a pointer and a size, an array without compile-time known size.
// Slices have runtime out-of-band verifications.
@@ -206,8 +202,8 @@ const slice = array[0..array.len]; // "slice" represents the whole array.
```
### Pointers.
-```
+```zig
// Pointer on a value can be created with "&".
const x: i32 = 1;
const pointer: *i32 = &x; // "pointer" is a pointer on the i32 var "x".
@@ -223,7 +219,8 @@ const foo = pointer.?; // Get the pointed value, otherwise crash.
```
### Optional values (?<type>).
-```
+
+```zig
// An optional is a value than can be of any type or null.
// Example: "optional_value" can either be "null" or an unsigned 32-bit integer.
@@ -239,7 +236,8 @@ if (x) |value| {
```
### Errors.
-```
+
+```zig
// Zig provides an unified way to express errors.
// Errors are defined in error enumerations, example:
@@ -299,7 +297,7 @@ var value = try some_function();
### Control flow.
-```
+```zig
// Conditional branching.
if (condition) {
@@ -384,8 +382,8 @@ const result = for (items) |value| {
```
### Labels.
-```
+```zig
// Labels are a way to name an instruction, a location in the code.
// Labels can be used to "continue" or "break" in a nested loop.
outer: for ([_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 }) |_| {
@@ -434,8 +432,8 @@ const result = for (items) |value| { // First: loop.
```
### Switch.
-```
+```zig
// As a switch in C, but slightly more advanced.
// Syntax:
// switch (value) {
@@ -454,15 +452,15 @@ var x = switch(value) {
// A slightly more advanced switch, accepting a range of values:
const foo: i32 = 0;
const bar = switch (foo) {
- 0 => "zero",
- 1...std.math.maxInt(i32) => "positive",
- else => "negative",
+ 0 => "zero",
+ 1...std.math.maxInt(i32) => "positive",
+ else => "negative",
};
```
### Structures.
-```
+```zig
// Structure containing a single value.
const Full = struct {
number: u16,
@@ -564,7 +562,8 @@ print("p.y: {}\n", .{p.y}); // 30
```
### Tuples.
-```
+
+```zig
// A tuple is a list of elements, possibly of different types.
const foo = .{ "hello", true, 42 };
@@ -572,33 +571,33 @@ const foo = .{ "hello", true, 42 };
```
### Enumerations.
-```
+```zig
const Type = enum { ok, not_ok };
const CardinalDirections = enum { North, South, East, West };
const direction: CardinalDirections = .North;
const x = switch (direction) {
- // shorthand for CardinalDirections.North
- .North => true,
- else => false
+ // shorthand for CardinalDirections.North
+ .North => true,
+ else => false
};
// Switch statements need exhaustiveness.
// WARNING: won't compile. East and West are missing.
const x = switch (direction) {
- .North => true,
- .South => true,
+ .North => true,
+ .South => true,
};
// Switch statements need exhaustiveness.
// Won't compile: East and West are missing.
const x = switch (direction) {
- .North => true,
- .South => true,
- .East, // Its value is the same as the following pattern: false.
- .West => false,
+ .North => true,
+ .South => true,
+ .East, // Its value is the same as the following pattern: false.
+ .West => false,
};
@@ -606,12 +605,12 @@ const x = switch (direction) {
```
### Unions.
-```
+```zig
const Bar = union {
- boolean: bool,
- int: i16,
- float: f32,
+ boolean: bool,
+ int: i16,
+ float: f32,
};
// Both syntaxes are equivalent.
@@ -622,8 +621,8 @@ const foo: Bar = .{ .int = 42 };
```
### Tagged unions.
-```
+```zig
// Unions can be declared with an enum tag type, allowing them to be used in
// switch expressions.
@@ -653,8 +652,8 @@ switch (nay) {
```
### Defer and errdefer.
-```
+```zig
// Make sure that an action (single instruction or block of code) is executed
// before the end of the scope (function, block of code).
// Even on error, that action will be executed.
@@ -695,24 +694,25 @@ Thus, the standard library lets developers handle memory as they need, through s
**NOTE**: the choice of the allocator isn't in the scope of this document.
A whole book could be written about it.
However, here are some examples, to get an idea of what you can expect:
-- page_allocator.
+- `page_allocator`.
Allocate a whole page of memory each time we ask for some memory.
Very simple, very dumb, very wasteful.
-- GeneralPurposeAllocator.
+- `GeneralPurposeAllocator`.
Get some memory first and manage some buckets of memory in order to
reduce the number of allocations.
A bit complex. Can be combined with other allocators.
Can detect leaks and provide useful information to find them.
-- FixedBufferAllocator.
+- `FixedBufferAllocator`.
Use a fixed buffer to get its memory, don't ask memory to the kernel.
Very simple, limited and wasteful (can't deallocate), but very fast.
-- ArenaAllocator.
+- `ArenaAllocator`.
Allow to free all allocated memory at once.
To use in combinations with another allocator.
Very simple way of avoiding leaks.
A first example.
-```
+
+```zig
// "!void" means the function doesn't return any value except for errors.
// In this case we try to allocate memory, and this may fail.
fn foo() !void {
@@ -735,8 +735,8 @@ fn foo() !void {
```
### Memory allocation combined with error management and defer.
-```
+```zig
fn some_memory_allocation_example() !void {
// Memory allocation may fail, so we "try" to allocate the memory and
// in case there is an error, the current function returns it.
@@ -759,8 +759,8 @@ fn some_memory_allocation_example() !void {
```
### Memory allocators: a taste of the standard library.
-```
+```zig
// Allocators: 4 main functions to know
// single_value = create (type)
// destroy (single_value)
@@ -846,8 +846,8 @@ fn gpa_arena_allocator_fn() !void {
```
### Comptime.
-```
+```zig
// Comptime is a way to avoid the pre-processor.
// The idea is simple: run code at compilation.
@@ -883,7 +883,8 @@ list.items[0] = 10;
```
### Conditional compilation.
-```
+
+```zig
const available_os = enum { OpenBSD, Linux };
const myos = available_os.OpenBSD;
@@ -905,7 +906,8 @@ const myprint = switch(myos) {
```
### Testing our functions.
-```
+
+```zig
const std = @import("std");
const expect = std.testing.expect;
@@ -936,45 +938,44 @@ There are more than a hundred built-ins, allowing very low-level stuff:
- etc.
Example: enums aren't integers, they have to be converted with a built-in.
-```
+
+```zig
const Value = enum { zero, stuff, blah };
if (@enumToInt(Value.zero) == 0) { ... }
if (@enumToInt(Value.stuff) == 1) { ... }
if (@enumToInt(Value.blah) == 2) { ... }
```
-
### A few "not yourself in the foot" measures in the Zig language.
-- Namespaces: names conflicts are easily avoided.
- In practice, that means an unified API between different structures (data types).
+- Namespaces: name conflicts are easily avoided.
+ In practice, that means a unified API between different structures (data types).
- Enumerations aren't integers. Comparing an enumeration to an integer requires a conversion.
- Explicit casts, coercion exists but is limited.
Types are slightly more enforced than in C, just a taste:
Pointers aren't integers, explicit conversion is necessary.
- You won't lose precision by accident, implicit coercions are only authorized in case no precision can be lost.
- Unions cannot be reinterpreted (in an union with an integer and a float, one cannot take a value for another by accident).
+ You won't lose precision by accident, implicit coercions are only authorized in cases where no precision can be lost.
+ Unions cannot be reinterpreted (in a union with an integer and a float, one cannot take a value for another by accident).
Etc.
- Removing most of the C undefined behaviors (UBs), and when the compiler encounters one, it stops.
- Slice and Array structures are preferred to pointers.
Types enforced by the compiler are less prone to errors than pointer manipulations.
- Numerical overflows produce an error, unless explicitly accepted using wrapping operators.
-- Try and catch mechanism.
+- `try` and `catch` mechanism.
It's both handy, trivially implemented (simple error enumeration), and it takes almost no space nor computation time.
-- Unused variables are considered as errors by the compiler.
-- Many pointer types exist in order to represent what is pointed.
+- Unused variables are considered to be errors by the compiler.
+- Many pointer types exist in order to represent what is pointed to.
Example: is this a single value or an array, is the length known, etc.
-- Structures need a value for their attributes, and it still is possible to give an undefined value (stack garbage), but at least it is explicitly undefined.
+- Structures need a value for their attributes, and it is still possible to give an undefined value (stack garbage), but at least it is explicitly undefined.
## Further Reading
-For a start, some concepts are presented on the [Zig learn website][ziglearn].
-
-The [official website][zigdoc] provides a reference documentation to the language.
+For a start, some concepts are presented on [zig.guide][zigguide].
-For now, documentation for standard library is WIP.
+The [official website][zigdoc] provides the reference documentation of the language. The standard library [has its own documentation][zigstd].
[ziglang]: https://ziglang.org
-[ziglearn]: https://ziglearn.org/
+[zigguide]: https://zig.guide/
[zigdoc]: https://ziglang.org/documentation/
+[zigstd]: https://ziglang.org/documentation/master/std/