diff options
147 files changed, 9810 insertions, 7995 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/ada.html.markdown b/ada.html.markdown index a06792b3..7191c5dc 100644 --- a/ada.html.markdown +++ b/ada.html.markdown @@ -2,10 +2,10 @@ language: Ada filename: learn.ada contributors: - ["Luke A. Guest", "https://github.com/Lucretia"] - ["Fernando Oleo Blanco", "https://github.com/Irvise"] - ["Fabien Chouteau", "https://github.com/Fabien-Chouteau"] - ["Manuel", "https://github.com/mgrojo"] + - ["Luke A. Guest", "https://github.com/Lucretia"] + - ["Fernando Oleo Blanco", "https://github.com/Irvise"] + - ["Fabien Chouteau", "https://github.com/Fabien-Chouteau"] + - ["Manuel", "https://github.com/mgrojo"] --- Ada is a strong statically typed imperative, [object-oriented](https://ada-lang.io/docs/arm/AA-3/AA-3.9), [real-time](https://ada-lang.io/docs/arm/AA-D), [parallel](https://ada-lang.io/docs/arm/AA-9) and [distributed](https://ada-lang.io/docs/arm/AA-9) programming language from the Pascal/Algol family of languages, but nowadays, it only has a passing resemblance to Pascal, with the only remnants left being the ```begin/end``` keyword pair, the ```:=``` assignment symbol, records and ```if/case``` control statement structures. 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/ca-es/go-ca.html.markdown b/ca-es/go-ca.html.markdown index 591ce837..7bec4ba4 100644 --- a/ca-es/go-ca.html.markdown +++ b/ca-es/go-ca.html.markdown @@ -433,25 +433,25 @@ func requestServer() { ## Més informació L'arrel de tot en Go és la web oficial [official Go web site] -(http://golang.org/). Allà es pot seguir el tutorial, jugar interactivament +(https://go.dev/). Allà es pot seguir el tutorial, jugar interactivament i llegir molt més del que hem vist aquí.En el "tour", -[the docs](https://golang.org/doc/) conté informació sobre com escriure codi +[the docs](https://go.dev/doc/) conté informació sobre com escriure codi net i efectiu en Go, comandes per empaquetar i generar documentació, i història de les versions. És altament recomanable llegir La definició del llenguatge. És fàcil de llegir i sorprenentment curta (com la definició del llenguatge en aquests dies). -Es pot jugar amb codi a [Go playground](https://play.golang.org/p/tnWMjr16Mm). +Es pot jugar amb codi a [Go playground](https://go.dev/play/p/tnWMjr16Mm). Prova de fer canvis en el codi i executar-lo des del navegador! Es pot fer -servir [https://play.golang.org](https://play.golang.org) com a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) per provar coses i codi +servir [https://go.dev/play/](https://go.dev/play/) com a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) per provar coses i codi en el navegador sense haver d'instal·lar Go. En la llista de lectures pels estudiants de Go hi ha -[el codi font de la llibreria estàndard](http://golang.org/src/pkg/). +[el codi font de la llibreria estàndard](https://go.dev/src/). Ampliament comentada, que demostra el fàcil que és de llegir i entendre els programes en Go, l'estil de programació, i les formes de treballar-hi. O es -pot clicar en un nom de funció en [la documentació](http://golang.org/pkg/) +pot clicar en un nom de funció en [la documentació](https://go.dev/pkg/) i veure'n el codi! Un altre gran recurs per aprendre Go és 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/go.html.markdown b/cs-cz/go.html.markdown index 4f8569bf..18880a3b 100644 --- a/cs-cz/go.html.markdown +++ b/cs-cz/go.html.markdown @@ -408,20 +408,20 @@ func requestServer() { ## Kam dále -Vše hlavní o Go se nachází na [oficiálních stránkách go](http://golang.org/). +Vše hlavní o Go se nachází na [oficiálních stránkách go](https://go.dev/). Tam najdete tutoriály, interaktivní konzolu a mnoho materiálu ke čtení. -Kromě úvodu, [dokumenty](https://golang.org/doc/) tam obsahují jak psát čistý kód v Go +Kromě úvodu, [dokumenty](https://go.dev/doc/) tam obsahují jak psát čistý kód v Go popis balíčků (package), dokumentaci příkazové řádky a historii releasů. Také doporučujeme přečíst si definici jazyka. Je čtivá a překvapivě krátká. Tedy alespoň proti jiným současným jazyků. -Pokud si chcete pohrát s Go, tak navštivte [hřiště Go](https://play.golang.org/p/r46YvCu-XX). -Můžete tam spouštět programy s prohlížeče. Také můžete [https://play.golang.org](https://play.golang.org) použít jako +Pokud si chcete pohrát s Go, tak navštivte [hřiště Go](https://go.dev/play/p/r46YvCu-XX). +Můžete tam spouštět programy s prohlížeče. Také můžete [https://go.dev/play/](https://go.dev/play/) použít jako [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop), kde si v rychlosti vyzkoušíte věci, bez instalace Go. -Na vašem knižním seznamu, by neměly chybět [zdrojáky stadardní knihovny](http://golang.org/src/pkg/). -Důkladně popisuje a dokumentuje Go, styl zápisu Go a Go idiomy. Pokud kliknete na [dokumentaci](http://golang.org/pkg/) +Na vašem knižním seznamu, by neměly chybět [zdrojáky stadardní knihovny](https://go.dev/src/). +Důkladně popisuje a dokumentuje Go, styl zápisu Go a Go idiomy. Pokud kliknete na [dokumentaci](https://go.dev/pkg/) tak se podíváte na dokumentaci. Dalším dobrým zdrojem informací je [Go v ukázkách](https://gobyexample.com/). 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">```ruby +````md +```ruby def neco - puts "Ahoj světe!" + puts "Ahoj světe!" end -```</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/go-de.html.markdown b/de-de/go-de.html.markdown index 30a660fa..1b09a1e1 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -308,13 +308,13 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { ``` ## Weitere Resourcen -Informationen zu Go findet man auf der [offiziellen Go Webseite](http://golang.org/). +Informationen zu Go findet man auf der [offiziellen Go Webseite](https://go.dev/). Dort gibt es unter anderem ein Tutorial und interaktive Quelltext-Beispiele, vor allem aber Dokumentation zur Sprache und den Paketen. Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr kurz und gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen -ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/) +ist außerdem der Quelltext der [Go standard Bibliothek](https://go.dev/src/) einzusehen. Dieser kann als Referenz für leicht zu verstehendes und im idiomatischen Stil verfasstes Go dienen. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen -in der [offiziellen Dokumentation von Go](http://golang.org/pkg/). +in der [offiziellen Dokumentation von Go](https://go.dev/pkg/). 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 c86494ce..ce31c648 100644 --- a/de-de/pug-de.html.markdown +++ b/de-de/pug-de.html.markdown @@ -162,13 +162,13 @@ case bestellungsStatus //- <p class="warn">Deine Bestellung steht noch aus</p> //- --INCLUDE-- -//- File path -> "includes/nav.png" +//- File path -> "includes/nav.pug" h1 Firmenname nav a(href="index.html") Home a(href="about.html") Über uns -//- Dateipfad -> "index.png" +//- Dateipfad -> "index.pug" html body include includes/nav.pug @@ -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/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/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/css-es.html b/es-es/css-es.html.markdown index 506a9467..506a9467 100644 --- a/es-es/css-es.html +++ b/es-es/css-es.html.markdown 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/go-es.html.markdown b/es-es/go-es.html.markdown index 2d1dbce7..17bf4a22 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -425,7 +425,7 @@ func consultaAlServidor() { ## Más información La raíz de todas las cosas sobre Go es el -[sitio web oficial de Go](http://golang.org/). +[sitio web oficial de Go](https://go.dev/). Allí puedes seguir el tutorial, jugar interactivamente y leer mucho más. La definición del lenguaje es altamente recomendada. Es fácil de leer y @@ -433,17 +433,17 @@ sorprendentemente corta (como la definición del lenguaje Go en estos días). Puedes jugar con el código en el -[parque de diversiones Go](https://play.golang.org/p/ncRC2Zevag). ¡Trata +[parque de diversiones Go](https://go.dev/play/p/ncRC2Zevag). ¡Trata de cambiarlo y ejecutarlo desde tu navegador! Ten en cuenta que puedes -utilizar [https://play.golang.org]( https://play.golang.org) como un +utilizar [https://go.dev/play/]( https://go.dev/play/) como un [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) para probar cosas y el código en el navegador, sin ni siquiera instalar Go. En la lista de lecturas para estudiantes de Go está el -[código fuente de la biblioteca estándar](http://golang.org/src/pkg/). +[código fuente de la biblioteca estándar](https://go.dev/src/). Ampliamente documentado, que demuestra lo mejor del legible y comprensible Go, con su característico estilo y modismos. ¡O puedes hacer clic en un -nombre de función en [la documentación](http://golang.org/pkg/) y +nombre de función en [la documentación](https://go.dev/pkg/) y aparecerá el código fuente! Otro gran recurso para aprender Go está en 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/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/fi-fi/go-fi.html.markdown b/fi-fi/go-fi.html.markdown index a7337250..ef88a96e 100644 --- a/fi-fi/go-fi.html.markdown +++ b/fi-fi/go-fi.html.markdown @@ -418,21 +418,21 @@ func requestServer() { ## Lisää luettavaa -Go-tietämyksen alku ja juuri on sen [virallinen verkkosivu]()(http://golang.org/). +Go-tietämyksen alku ja juuri on sen [virallinen verkkosivu]()(https://go.dev/). Siellä voit seurata oppitunteja, askarrella vuorovaikutteisesti sekä lukea paljon. -Kierroksen lisäksi [dokumentaatio](https://golang.org/doc/) pitää sisällään tietoa +Kierroksen lisäksi [dokumentaatio](https://go.dev/doc/) pitää sisällään tietoa siistin Go-koodin kirjoittamisesta, pakettien ja komentojen käytöstä sekä julkaisuhistoriasta. Kielen määritelmä itsessään on suuresti suositeltavissa. Se on helppolukuinen ja yllättävän lyhyt (niissä määrin kuin kielimääritelmät nykypäivänä ovat.) -Voit askarrella parissa kanssa [Go playgroundissa](https://play.golang.org/p/tnWMjr16Mm). -Muuttele sitä ja aja se selaimestasi! Huomaa, että voit käyttää [https://play.golang.org](https://play.golang.org) +Voit askarrella parissa kanssa [Go playgroundissa](https://go.dev/play/p/tnWMjr16Mm). +Muuttele sitä ja aja se selaimestasi! Huomaa, että voit käyttää [https://go.dev/play/](https://go.dev/play/) [REPL:na](https://en.wikipedia.org/wiki/Read-eval-print_loop) testataksesi ja koodataksesi selaimessasi, ilman Go:n asentamista. -Go:n opiskelijoiden lukulistalla on [oletuskirjaston lähdekoodi](http://golang.org/src/pkg/). +Go:n opiskelijoiden lukulistalla on [oletuskirjaston lähdekoodi](https://go.dev/src/). Kattavasti dokumentoituna se antaa parhaan kuvan helppolukuisesta ja ymmärrettävästä Go-koodista, --tyylistä ja -tavoista. Voit klikata funktion nimeä [doukumentaatiossa](http://golang.org/pkg/) ja +-tyylistä ja -tavoista. Voit klikata funktion nimeä [doukumentaatiossa](https://go.dev/pkg/) ja lähdekoodi tulee esille! Toinen loistava paikka oppia on [Go by example](https://gobyexample.com/). 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/go-fr.html.markdown b/fr-fr/go-fr.html.markdown index a002acfc..5468096a 100644 --- a/fr-fr/go-fr.html.markdown +++ b/fr-fr/go-fr.html.markdown @@ -422,18 +422,18 @@ func requestServer() { ## En savoir plus -La référence Go se trouve sur [le site officiel de Go](http://golang.org/). +La référence Go se trouve sur [le site officiel de Go](https://go.dev/). Vous pourrez y suivre le tutoriel interactif et en apprendre beaucoup plus. Une lecture de la documentation du langage est grandement conseillée. C'est facile à lire et très court (comparé aux autres langages). -Vous pouvez exécuter et modifier le code sur [Go playground](https://play.golang.org/p/tnWMjr16Mm). Essayez de le modifier et de l'exécuter à partir de votre navigateur! Prennez en note que vous pouvez utiliser [https://play.golang.org](https://play.golang.org) comme un [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) pour tester et coder dans votre navigateur, sans même avoir à installer Go. +Vous pouvez exécuter et modifier le code sur [Go playground](https://go.dev/play/p/tnWMjr16Mm). Essayez de le modifier et de l'exécuter à partir de votre navigateur! Prennez en note que vous pouvez utiliser [https://go.dev/play/](https://go.dev/play/) comme un [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) pour tester et coder dans votre navigateur, sans même avoir à installer Go. Sur la liste de lecteur des étudiants de Go se trouve le [code source de la -librairie standard](http://golang.org/src/pkg/). Bien documentée, elle démontre +librairie standard](https://go.dev/src/). Bien documentée, elle démontre le meilleur de la clarté de Go, le style ainsi que ses expressions. Sinon, vous pouvez cliquer sur le nom d'une fonction dans [la -documentation](http://golang.org/pkg/) et le code source apparaît! +documentation](https://go.dev/pkg/) et le code source apparaît! Une autre excellente ressource pour apprendre est [Go par l'exemple](https://gobyexample.com/). 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/go.html.markdown b/go.html.markdown index 0631ffab..59ba2e4f 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -456,21 +456,21 @@ func requestServer() { ## Further Reading -The root of all things Go is the [official Go web site](http://golang.org/). +The root of all things Go is the [official Go web site](https://go.dev/). There you can follow the tutorial, play interactively, and read lots. -Aside from a tour, [the docs](https://golang.org/doc/) contain information on +Aside from a tour, [the docs](https://go.dev/doc/) contain information on how to write clean and effective Go code, package and command docs, and release history. -The [Go language specification](https://golang.org/ref/spec) itself is highly recommended. It's easy to read +The [Go language specification](https://go.dev/ref/spec) itself is highly recommended. It's easy to read and amazingly short (as language definitions go these days.) -You can play around with the code on [Go playground](https://play.golang.org/p/tnWMjr16Mm). Try to change it and run it from your browser! Note that you can use [https://play.golang.org](https://play.golang.org) as a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) to test things and code in your browser, without even installing Go. +You can play around with the code on [Go playground](https://go.dev/play/p/tnWMjr16Mm). Try to change it and run it from your browser! Note that you can use [https://go.dev/play/](https://go.dev/play/) as a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) to test things and code in your browser, without even installing Go. On the reading list for students of Go is the [source code to the standard -library](http://golang.org/src/pkg/). Comprehensively documented, it +library](https://go.dev/src/). Comprehensively documented, it demonstrates the best of readable and understandable Go, Go style, and Go idioms. Or you can click on a function name in [the -documentation](http://golang.org/pkg/) and the source code comes up! +documentation](https://go.dev/pkg/) and the source code comes up! Another great resource to learn Go is [Go by example](https://gobyexample.com/). diff --git a/hd-hd/amd.html.markdown b/hd-hd/amd.html.markdown index 0a6581d6..b85567c2 100644 --- a/hd-hd/amd.html.markdown +++ b/hd-hd/amd.html.markdown @@ -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..f5e0858a 100644 --- a/hd-hd/d.html.markdown +++ b/hd-hd/d.html.markdown @@ -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/httpie.html.markdown b/httpie.html.markdown new file mode 100644 index 00000000..40481dff --- /dev/null +++ b/httpie.html.markdown @@ -0,0 +1,120 @@ +--- +category: tool +tool: httpie +contributors: + - ["Adaías Magdiel", "https://github.com/AdaiasMagdiel"] +filename: learn-httpie.sh +--- + +HTTPie is a powerful command-line HTTP client designed for easy interaction +with HTTP servers. It provides a simple and intuitive interface, making it an +excellent tool for developers, testers, and system administrators. + +## Basic Usage + +HTTPie follows a simple syntax: http [flags] [METHOD] URL [items]. + +```bash +http GET https://api.example.com/posts +``` + +You can print the request without sending it by using the `--offline` flag. + +```bash +http --offline https://api.example.com/posts +``` + +### URL shortcuts for `localhost` + +HTTPie supports a curl-like shorthand for localhost. For instance, ":3000" +expands to "http://localhost:3000". If the port is omitted, it assumes port 80. + +```bash +http :/users # http://localhost/users +http :5000/rss # http://localhost:5000/rss +``` + +### Optional GET and POST + +If you don't specify the METHOD, the HTTPie will use: + +- GET for requests without body +- POST for requests with body + +```bash +http https://api.example.com/tags # GET tags +http https://api.example.com/tags title="Tutorial" slug="tutorial" # POST a new tag +``` + +## Querystring Parameters + + +If you're manually adding query string parameters in the terminal, try the +`param==value` syntax. It avoids shell escaping for & separators and +automatically URL-escapes special characters in parameter names and values. +This differs from parameters in the full URL, which HTTPie doesn't modify. + +```bash +http https://api.example.com/search q==httpie per_page==20 +``` + +## Sending Data + +You can send data in various formats such as JSON, form data, or files. + +### JSON Data + +```bash +http POST https://api.example.com/posts title="Hello" body="World" +``` + +### Form Data + +```bash +http -f POST https://api.example.com/submit name=John email=john@example.com +``` + +### Files + +```bash +http --form POST https://api.example.com/upload file@/path/to/file.txt +``` + +## Headers and Authentication + +HTTPie allows you to set headers and handle authentication easily. + +### Headers + +```bash +http GET https://api.example.com/posts Authorization:"Bearer Token" User-Agent:"HTTPie" +``` + +### Basic Authentication + +```bash +http -a username:password GET https://api.example.com/protected +``` + +### Bearer Authentication + +```bash +https -A bearer -a token https://api.example.com/admin +``` + +## Response Handling + +HTTPie provides various options for handling responses. + +```bash +http GET https://api.example.com/data Accept:application/json # Pretty Print JSON + +http GET https://api.example.com/image --output image.png # Save Response to File + +http --follow GET https://example.com # Follow Redirects +``` + +## Further Reading + +- [Official Documentation](https://httpie.io/docs/cli). +- [GitHub](https://github.com/httpie). diff --git a/hu-hu/go-hu.html.markdown b/hu-hu/go-hu.html.markdown index 1a96b8c3..451f9147 100644 --- a/hu-hu/go-hu.html.markdown +++ b/hu-hu/go-hu.html.markdown @@ -325,7 +325,7 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { ## További olvasmányok -Minden Go-val kapcsolatos megtaláható a [hivatalos Go weboldalon](http://golang.org/). +Minden Go-val kapcsolatos megtaláható a [hivatalos Go weboldalon](https://go.dev/). Ott követhetsz egy tutorialt, játszhatsz a nyelvvel az interneten, és sok érdekességet olvashatsz. A nyelv specifikációját kifejezetten érdemes olvasni, viszonylag rövid és sokat tanul belőle az ember. 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/hy.html.markdown b/hy.html.markdown index f6bdead0..5eddbf55 100644 --- a/hy.html.markdown +++ b/hy.html.markdown @@ -174,10 +174,10 @@ True ; => True ; create lexical bindings with `let', all variables defined thusly ; have local scope -(let [[nemesis {"superman" "lex luther" +(let [nemesis {"superman" "lex luther" "sherlock" "moriarty" - "seinfeld" "newman"}]] - (for [(, h v) (.items nemesis)] + "seinfeld" "newman"}] + (for [[h v] (.items nemesis)] (print (.format "{0}'s nemesis was {1}" h v)))) ;; classes 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/go-it.html.markdown b/it-it/go-it.html.markdown index d88e8741..6f974c91 100644 --- a/it-it/go-it.html.markdown +++ b/it-it/go-it.html.markdown @@ -422,9 +422,9 @@ func richiediServer() { ## Letture consigliate -La risorsa più importante per imparare il Go è il [sito ufficiale di Go](http://golang.org/). +La risorsa più importante per imparare il Go è il [sito ufficiale di Go](https://go.dev/). Qui puoi seguire i tutorial, scrivere codice in modo interattivo, e leggere tutti i dettagli. -Oltre al tour, [la documentazione](https://golang.org/doc/) contiene informazioni su +Oltre al tour, [la documentazione](https://go.dev/doc/) contiene informazioni su come scrivere ottimo codice in Go, documentazione sui package e sui comandi, e la cronologia delle release. @@ -432,17 +432,17 @@ Anche il documento che definisce il linguaggio è un'ottima lettura. E' semplice da leggere e incredibilmente corto (rispetto ad altri documenti riguardanti la creazione di linguaggi). -Puoi giocare con il codice visto finora nel [Go playground](https://play.golang.org/p/Am120Xe7qf). +Puoi giocare con il codice visto finora nel [Go playground](https://go.dev/play/p/Am120Xe7qf). Prova a cambiarlo e ad eseguirlo dal browser! -Osserva che puoi usare [https://play.golang.org](https://play.golang.org) come +Osserva che puoi usare [https://go.dev/play/](https://go.dev/play/) come una [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) per scrivere codice all'interno del browser, senza neanche installare Go! Una lettura importante per capire Go in modo più profondo è il [codice -sorgente della libreria standard](http://golang.org/src/pkg/). Infatti è +sorgente della libreria standard](https://go.dev/src/). Infatti è molto ben documentato e costituisce quanto più chiaro e conciso ci sia riguardo gli idiomi e le buone pratiche del Go. Inoltre, clickando sul nome di una -funzione [nella documentazione](http://golang.org/pkg/) compare il relativo +funzione [nella documentazione](https://go.dev/pkg/) compare il relativo codice sorgente! Un'altra ottima risorsa per imparare è [Go by example](https://gobyexample.com/). 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">```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 -```</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/javascript.html.markdown b/javascript.html.markdown index 08f1d8fb..4e7c5c09 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -405,7 +405,7 @@ myObj = { }; myObj.myFunc(); // = "Hello world!" -// What this is set to has to do with how the function is called, not where +// What `this` is set to has to do with how the function is called, not where // it's defined. So, our function doesn't work if it isn't called in the // context of the object. var myFunc = myObj.myFunc; diff --git a/jinja.html.markdown b/jinja.html.markdown new file mode 100644 index 00000000..7e5b8e96 --- /dev/null +++ b/jinja.html.markdown @@ -0,0 +1,270 @@ +--- +language: Jinja +contributors: + - ["Adaías Magdiel", "https://github.com/AdaiasMagdiel"] +filename: learn-jinja.j2 +--- + +## Getting Started with Jinja + +Jinja is a fast, expressive, and extensible templating engine for Python +applications. + +Jinja includes a lot of functionalities, such as: +- Template inheritance and inclusion; +- Defining and importing macros within templates; +- Security mechanisms to prevent XSS attacks; +- A sandboxed environment that can safely render untrusted templates; +- Extensible filters, tests, functions, and even syntax. + +A Jinja template is simply a text file. Jinja doesn't require a specific +extension, but it's common to use `.j2` or `.jinja` to make it easier for +some IDEs. + +There are a few kinds of delimiters. The default Jinja delimiters are configured +as follows: + +- `{% ... %}` for Statements +- `{{ ... }}` for Expressions to print to the template output +- `{# ... #}` for Comments not included in the template output + +```jinja +{# This is an example of a comment. #} + +{# + You can use this syntax + to write multiline comments + as well. +#} +``` + + +## VARIABLES + +```jinja +{# You have the option to access variables from the context passed to the template #} + +{{ foo }} + +{# + Additionally, you can use a dot (.) to access attributes of a variable or + use Python syntax, using [] +#} + +{{ foo.bar }} +{{ foo['bar'] }} + +{# Within the template, you can define variables as well #} + +{% set name = "Magdiel" %} +{{ name }} +``` + +## Loops + +```html +<h1>Members</h1> +<ul> +{% for user in users %} + <li>{{ user.username }}</li> +{% endfor %} +</ul> + + +<div> +{% for key, value in my_dict.items() %} + <p>{{ key }}</p> - <p>{{ value }}</p> +{% endfor %} +</div> + + +<div> +{% for idx, url in enumerate(urls) %} + <a href="{{ url }}">Go to url {{ idx + 1 }}</a> +{% endfor %} +</div> +``` + +## Conditionals + +The if statement in Jinja is similar to the if statement in Python. It is +commonly used to check if a variable is defined, not empty, and not false in +its most basic form. + +```html +{% if users %} +<ul> +{% for user in users %} + <li>{{ user.username }}</li> +{% endfor %} +</ul> +{% endif %} + + +{# For multiple branches, elif and else can be used like in Python. #} + + +{% if message.status == "error" %} + <p class="text-red-400">{{ message.content }}</p> +{% elif message.status == "success" %} + <p class="text-green-400">{{ message.content }}</p> +{% else %} + <p class="text-blue-400">{{ message.content }}</p> +{% endif %} +``` + +## Template Inheritance + +One of the most powerful features of Jinja is template inheritance. You can +create a base layout with predefined blocks that you can extend in another file +and override with your own content. + +```html +{# file: base.html.j2 #} + +<!DOCTYPE html> +<html lang="en"> +<head> + {% block head %} + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>{% block title %}{% endblock title %} - Learning Jinja</title> + {% endblock head %} +</head> +<body> + <main> + {% block content %}{% endblock %} + {# the endblock tag doesn't need the name of the block #} + </main> +</body> +</html> + + + +{# file: child.html.j2 #} + +{% extends "base.html.j2" %} + +{% block head %} + {{ super() }} + <script> + console.log("There's a console.log here") + </script> +{% endblock %} + +{% block title %}Home{% endblock %} + +{% block content %} + <h1>Index</h1> + <p>Welcome to my home homepage.</p> +{% endblock %} + + + +{# RESULT #} + +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>Home - Learning Jinja</title> + <script> + console.log("There's a console.log here") + </script> +</head> +<body> + <main> + <h1>Index</h1> + <p>Welcome to my home homepage.</p> + </main> +</body> +</html> + +``` + +### Including Content + +You can include content from another template on your current template using +the `{% include "template/path" %}` tag. + +```html + +{# file: footer.html.j2 #} + +<footer> + <p>© 2024 - John Doe</p> +</footer> + + + +{# file: index.html.j2 #} +... +<body> + <main> + <h1>Hi! I'm John Doe!</h1> + </main> + {% include "footer.html.j2" %} +</body> +... + + + +{# RESULT #} + +... +<body> + <main> + <h1>Hi! I'm John Doe!</h1> + </main> + <footer> + <p>© 2024 - John Doe</p> + </footer> +</body> +... +``` + +Variables passed to the main template can also be used in the include, as the +included template has access to the context of the main template. + +```html +{# file: greetings.html.j2 #} + +<p>I'm the {{ name }} and i like to {{ hobby }}.</p> + + + +{# file: index.html.j2 #} + +{% set name = "Captain Nemo" %} +{% set hobby = "navigate through the depths of the ocean" %} + +<div> + {% include "greetings.html.j2" %} +</div> + + + +{# RESULT #} + +<div> + <p>I'm the Captain Nemo and i like to navigate through the depths of the ocean.</p> +</div> +``` + +## Macros + +Macros are basically like functions in another languages. You can define macros with or without arguments and reuse them in various parts of your template. + +```html +{% macro input(value="", type="text", placeholder="") -%} + <input type="{{ type }}" value="{{ value }}" placeholder="{{ placeholder }}"> +{%- endmacro %} + +<p>{{ input(placeholder="Your username") }}</p> +<p>{{ input(type="password") }}</p> +``` + +## Official Documentation + +To learn more, access the [official documentation](https://jinja.palletsprojects.com/en/). diff --git a/ko-kr/go-kr.html.markdown b/ko-kr/go-kr.html.markdown index 42360294..aed0918e 100644 --- a/ko-kr/go-kr.html.markdown +++ b/ko-kr/go-kr.html.markdown @@ -332,15 +332,15 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { ## 더 읽어볼 것들 -Go에 대한 모든 것들은 [Go 공식 웹 사이트](http://golang.org/)를 참고하자. +Go에 대한 모든 것들은 [Go 공식 웹 사이트](https://go.dev/)를 참고하자. 여기에는 따라해볼 튜토리얼, 웹 기반의 인터랙티브 실행환경과 많은 읽을거리들이 있다. Go 언어 자체에 대한 스펙도 읽어보기를 적극 추천한다. 읽기 쉽게 되어있고 그리 길지는 않다. -Go 소스코드에 대해 좀더 알아보고 싶다면 [Go 표준 라이브러리](http://golang.org/src/pkg/)를 +Go 소스코드에 대해 좀더 알아보고 싶다면 [Go 표준 라이브러리](https://go.dev/src/)를 분석해보기 바란다. 이해하기 쉽게 문서화되어 있고, Go 스타일 그리고 Go에서의 -관례 배우기에 가장 좋은 방법일 것이다. 또는 [문서](http://golang.org/pkg/) 안에서 +관례 배우기에 가장 좋은 방법일 것이다. 또는 [문서](https://go.dev/pkg/) 안에서 함수 이름 하나를 클릭해보면 소스코드를 브라우저에서 살펴볼 수도 있다. Go를 배울수 있는 또하나의 좋은 방법은 [Go by example](https://gobyexample.com/). 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">```ruby +````md +```ruby def foobar - puts "Hello world!" + puts "Hello world!" end -```</code></pre> +``` +```` 위의 경우에 들여쓰기가 필요없을 뿐 아니라 \`\`\` 뒤에 특정해 준 언어의 문법에 따라 색을 입혀줄 것입니다. @@ -202,12 +215,14 @@ end 수평선(`<hr/>`)은 셋 이상의 별표나 하이픈을 이용해 쉽게 나타낼 수 있습니다. 띄어쓰기가 포함될 수 있습니다. + ```md *** --- - - - **************** ``` + ## 링크 마크다운의 장점 중 하나는 링크를 만들기 쉽다는 것입니다. 대괄호 안에 나타낼 텍스트를 쓰고 @@ -231,20 +246,24 @@ end 참조하는 식으로 링크를 걸 수도 있습니다. -<pre><code class="highlight">[<span class="nv">이 </span>][<span class="ss">링크</span>]에서 더 알아보세요! -[<span class="nv">원하신다면 </span>][<span class="ss">foobar</span>]도 참고하세요. +```md +[이 ][링크]에서 더 알아보세요! +[원하신다면 ][foobar]도 참고하세요. -[<span class="nv">링크</span>]: <span class="sx">http://test.com/</span> <span class="nn">"좋아!"</span> -[<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">[<span class="nv">이것</span>][]은 링크입니다. +```md +[이것][]은 링크입니다. -[<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">![<span class="nv">alt 속성</span>][<span class="ss">이미지</span>] +```md +![alt 속성][이미지] -[<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/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">```ruby +````md +```ruby def foobar - puts "Hello world!" + puts "Hello world!" end -```</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">[<span class="nv">Click this link</span>][<span class="ss">link1</span>] for more info about it! -[<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. -[<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">"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">[<span class="nv">This</span>][] is a link. +```md +[This][] is a link. -[<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">![<span class="nv">This is the alt-attribute.</span>][<span class="ss">myimage</span>] +```md +![This is the alt-attribute.][myimage] -[<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 new file mode 100644 index 00000000..1fe010ec --- /dev/null +++ b/osl.html.markdown @@ -0,0 +1,751 @@ +--- +language: osl +filename: learnosl.osl +contributors: + - ["Preetham Pemmasani", "https://github.com/Preetham-ai"] +--- + +OSL (Open Shading Language) is a programming language designed by Sony for Arnold Renderer used for creating shaders. + +[Read more here.](https://raw.githubusercontent.com/imageworks/OpenShadingLanguage/master/src/doc/osl-languagespec.pdf) + +```c + + +// Single-line comments start with // + +/* Multi line comments are preserved. */ + +// Statements can be terminated by ; +divide(1,2); + +/////////////// +// 1. Basics // +/////////////// + +// Declating variables +color Blue; // Initializing a variable +int _num = 3; +float Num = 3.00; +float c[3] = {0.1, 0.2, 3.14}; // Array + +// Math works as you would expect +3 + 1; // 4 +74 - 3; // 71 +20 * 2; // 40 +75/3; // 25.0 + +// And modulo division only works with integers +10 % 2; // 0 +31 % 4; // 1 + +// Bitwise operations only works with integers +- 0 // 1 (Unary Negation) +~ 00100011 // 11011100 (bitwise Compliment) +1 << 2; // 4 (shift Left) +12 >> 1; // 3 (shift Right) +1 & 0; // 0 (bitwise AND) +1 | 0; // 1 (bitwise OR) +1 ^ 1; // 0 (bitwise XOR) + +// We also have booleans +true; +false; + +// Booleans can't be compared to integers +true == 1 // Error +false == 0 // Error + +// Negation uses the ! symbol +!0; // 1 +!1; // 0 +!2; // 0 +//... and so on + +// Relation Operators are defined like: +0 == 0 // true (equal to) +0 != 1 // true (not equal to) +5 < 3 // false (less then) +3 <= 3 // true (less than or equal to) +69 > 69 // false (greater than) +99 >= 52 // true (greater than or equal) + + +// Functions are same as C and C++ +float sum(float a, float b){ + return a+b; +} + +int subtract(int a, int b){ + return a-b; +} + +sum(2,3); // 5 + +//////////////// +// 2. Shaders // +//////////////// + +// Shaders explain the custom behavior of materials and light +// Shader's syntax is similar to the main function in C +// The inputs and the outputs should be initialized to default types +shader multiply(float a = 0.0, + float b = 0.0, + output float c = 0.0){ + c = a*b; +} + +// Double brackets[[ ]] is used to classify metadata of a shader +surface plastic + [[ string help = "Realistic wood shader" ]] +( + color Plastic = color (0.7, 0.5, 0.3) [[ string help = "Base color" ]], + float Reflectivity = 0.5 [[ float min = 0, float max = 1 ]], +){...} + +/////////////////////////////////////// +// Metadata Types +/////////////////////////////////////// + +[[ string label = "IOR" ]] // Display-name in UI of the parameter +[[ string help = "Change Refractive Index" ]] // Info about the parameter +[[ string help = "widget" // Gives widgets to input the parameter + string widget = "number" ]] // input float or int + string widget = "string" ]] // String input + string widget = "boolean" ]] // yes/no (or) 1/0 + string widget = "popup", options = "smooth|rough" ]] // Drop-down list + // enum Drop-down list can also be made + string widget = "mapper", options = "smooth:0|rough:1" ]] + string widget = "filename" ]] // Input files externally + string widget = "null" ]] // null input + +[[ float min = 0.0 ]] // Minimum value of parameter +[[ float max = 0.5 ]] // Maximum value of parameter +[[ int slider = 3.0 // Adds a slider as an input + int slidermin = -1]] // minimum value of the slider + int slidermax = 3]] // maximum value of the slider + int slidercenter = 2]] // origin value of the slider + +[[ float sensitivity = 0.5 ]] // step size for incrementing the parameter +[[ string URL = www.example.com/ ]] // URL of shader's documentation + + + +// There are different types of shaders + +/* Surface shaders determine the basic material properties of a surface and +how it reacts to light */ +// Light shaders are a type of SURFACE shaders used for emissive objects. +// Displacement shaders alter the geometry using position and normals. +// Volume shaders adds a medium like air/smoke/dust into the scene. + +volume multiply(float a = 0.0, float b = 0.0, output float c = 0.0){ + c = 2*a+b; +} + +//////////////////////////////////////// +// 3. Data Types and Global Variables // +//////////////////////////////////////// + +// Data Types + +// 1. The void type indicates a function that doesn't return any value + +// 2. int (Integer) + int x = -12; // Minimum size of 32-bits + int new2 = 0x01cf; // Hexadecimal can also be specified + + /////////////////////////////////////// + // Order of Evaluation + /////////////////////////////////////// + + // From top to bottom, top has higher precedence + //--------------------------// + // Operators // + //--------------------------// + // int++, int-- // + // ++ int --int - ~ ! // + // * / % // + // + - // + // << >> // + // < <= > >= // + // == != // + // & // + // ^ // + // | // + // && // + // || // + // ?: // + // = += -= *= /= // + //--------------------------// + +// 3. float (Floating-point number) + float A = 2.3; // minimum IEEE 32-bit float + float Z = -4.1e2; // Z = -4.1 * 10^2 + + // Order of evaluation is similar to int. + // Operations like ( ~ ! % << >> ^ | & && || ) aren't available in float + +// 4. string + // The syntax is similar to C + string new = "Hello World"; + // some Special characters: + /* + '\"'; // double quote + '\n'; // newline character + '\t'; // tab character (left justifies text) + '\v'; // vertical tab + '\\'; // back slash + '\r'; // carriage return + '\b'; // backspace character + */ + + // Strings are concatenated with whitespace + "Hello " "world!"; // "Hello world!" + // concat function can also be used + string concat ("Hello ","World!"); // "Hello world!" + + // printf function is same as C + int i = 18; + printf("I am %d years old",i); // I am 18 years old + + // String functions can alse be used + int strlen (string s); // gives the length of the string + int len = strlen("Hello, World!"); // len = 13 + + // startswith returns 1 if string starts with prefix, else returns 0 + int starts = startswith("The quick brown fox", "The"); // starts = 1 + + // endswith returns 1 if string starts with suffix, else returns 0 + int ends = endswith("The quick brown fox", "fox"); // ends will be 1 + +// 5. color (Red, Green, Blue) + color p = color(0,1,2); // black + color q = color(1); // white ( same as color(1,1,1) ) + color r = color("rgb", 0.23, 0.1, 0.8); // explicitly specify in RGB + color s = color("hsv", 0.23, 0.1, 0.8); // specify in HSV + // HSV stands for (Hue, Saturation, Luminance) + // HSL stands for (Hue, Saturation, Lightness) + // YIQ, XYZ and xyY formats can also be used + // We can also access the indivudual values of (R,G,B) + float Red = p[0]; // 0 (access the red component) + float Green = p[1]; // 1 (access the green component) + float Blue = p[2]; // 2 (access the blue component) + + // They can also be accessed like this + float Red = p.r; // 0 (access the red component) + float Green = p.g; // 1 (access the green component) + float Blue = p.b; // 2 (access the blue component) + + // Math operators work like this with decreasing precedence + color C = (3,2,3) * (1,0,0); // (3, 0, 0) + color D = (1,1,1) * 255; // (255, 255, 255) + color E = (25,5,125) / 5; // (5, 1, 25) + color F = (30,40,50) / (3,4,5); // (10, 10, 10) + color A = (1,2,3) + (1,0,0); // (2, 2, 3) + color B = (1,2,3) - (1,0,0); // (0, 2, 3) + // Operators like ( - == != ) are also used + + // Color Functions + color blackbody (1500) // Gives color based on temperature (in Kelvin) + float luminance (0.5, 0.3, 0.8) // 0.37 gives luminance cd/m^2 + // Luminance is calculated by 0.2126R+0.7152G+0.0722B + color wavelength color (700) // (1, 0, 0) Gives color based on wavelength + color transformc ("hsl", "rgb") // converts one system to another + +// 6. point (x,y,z) is position of a point in the 3D space +// 7. vector (x,y,z) has length and direction but no position +// 8. normal (x,y,z) is a special vector perpendicular to a surface + // These Operators are the same as color and have the same precedence + L = point(0.5, 0.6, 0.7); + M = vector(30, 100, 70); + N = normal(0, 0, 1); + + // These 3 types can be assigned to a coordinate system + L = point("object", 0.5, 0.6, 0.7); // relative to local space + M = vector("common", 30, 100, 70); // relative to world space + // There's also ("shader", "world", "camera", "screen", "raster", "NDC") + + float x = L[0]; // 0.5 (access the x-component) + float y = L[1]; // 0.6 (access the y-component) + float z = L[2]; // 0.7 (access the z-component) + + // They can also be accessed like this + float x = M.x; // 30 (access the x-component) + float y = M.y; // 100 (access the y-component) + float z = M.z; // 70 (access the z-component) + + float a = dot ((1,2,3), (1,2,3)); // 14 (Dot Product) + vector b = cross ((1,2,3), (1,2,3)); // (0,0,0) (Cross Product) + float l = length(L); // 1.085 (length of vector) + vector normalize (vector L); // (0.460, 0.552, 0.644) Normalizes the vector + + point p0 = point(1, 2, 3); + point p1 = point(4, 5, 6); + point Q = point(0, 0, 0); + + // Finding distance between two points + float len = distance(point(1, 2, 3), point(4, 5, 6)); // 5.196 + // Perpendicular distance from Q to line joining P0 and P1 + float distance (point P0, point P1, point Q); // 2.45 + + +// 9. matrix + // Used for transforming vectors between different coordinate systems. + // They are usually 4x4 (or) 16 floats + matrix zero = 0; // makes a 4x4 zero matrix + /* 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0 */ + + matrix ident = 1; // makes a 4x4 identity matrix + /* 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 */ + + matrix m = 7; // Maked a 4x4 scalar matrix with scaling factor of 7 + /* 7.0, 0.0, 0.0, 0.0, + 0.0, 7.0, 0.0, 0.0, + 0.0, 0.0, 7.0, 0.0, + 0.0, 0.0, 0.0, 7.0 */ + + float x = m[1][1]; // 7 + + // matrices can be constructed using floats in row-major order + // matrices are usually 4x4 with 16 elements + matrix myMatrix = matrix(1.0, 0.0, 0.0, 0.0, // Row 1 + 0.0, 2.0, 0.0, 0.0, // Row 2 + 0.0, 0.0, 3.0, 0.0, // Row 3 + 0.0, 0.0, 0.0, 4.0); // Row 4 + + // matrix transformations are easy to implement + matrix a = matrix ("shader", 1); // converted shader to common + matrix m = matrix ("object", "world"); // converted object to world + + // Operations that can be used with decreasing precedence are: + // ( - * / == !=) + + float determinant (matrix M) // 24 (returns the determinant of the matrix) + float transpose (matrix M) // returns the transpose of the matrix + /* 1.0, 0.0, 0.0, 0.0, + 0.0, 2.0, 0.0, 0.0, + 0.0, 0.0, 3.0, 0.0, + 0.0, 0.0, 0.0, 4.0 */ + +// 10. array + // Arrays in OSL are similar to C + float a[5]; // initialize array a with size 5 + int b[3] = {90,80,70}; // declare array with size 3 + int len = arraylength(b); // 3 + int f = b[1]; // 80 + float anotherarray[3] = b; // arrays can be copied if same type + +// 11. struct (Structures) + // Structures in OSL are similar to C and C++. + struct RGBA { // Defining a structure + color rgb; + float alpha; + }; + + + RGBA col; // Declaring a structure + RGBA b = { color(0.1, 0.2, 0.3), 1 }; // Can also be declared like this + + r.rgb = color (1, 0, 0); // Assign to one field + color c = r.rgb; // Read from a structure field + +// 12. closure + // Closure is used to store data that aren't considered when it executes. + // It cannot be manipulated or read. + // A null closure can always be assigned. + // OSL currently only supports color as their closure. + + // A few examples of closures are: + + // Diffuse BSDF closures: + closure color oren_nayar_diffuse_bsdf(normal N, color alb, float roughness) + closure color burley_diffuse_bsdf(normal N, color alb, float roughness); + + // Dielectric BSDF closure: + closure color dielectric_bsdf(normal N, vector U, color reflection_tint, + color transmission_tint, float roughness_x, float roughness_y, + float ior, string distribution); + + // Conductor BSDF closure: + closure color conductor_bsdf(normal N, vector U, float roughness_x, + float roughness_y, color ior, color extinction, string distribution); + + // Generalized Schlick BSDF closure: + closure color generalized_schlick_bsdf(normal N, vector U, + color reflection_tint, color transmission_tint, + float roughness_x, float roughness_y, color f0, color f90, + float exponent, string distribution); + + // Translucent BSDF closure: + closure color translucent_bsdf(normal N, color albedo); + + // Transparent BSDF closure: + closure color transparent_bsdf(); + + // Subsurface BSSRDF closure: + closure color subsurface_bssrdf(); + + // Sheen BSDF closure: + closure color sheen_bsdf(normal N, color albedo, float roughness); + + // Anisotropic VDF closure: (Volumetric) + closure color anisotropic_vdf(color albedo, color extinction, + float anisotropy); + + // Medium VDF closure: (Volumetric) + closure color medium_vdf(color albedo, float transmission_depth, + color transmission_color, float anisotropy, float ior, int priority); + + closure color uniform edf(color emittance); // Emission closure + closure color holdout(); // Holdout Hides objects beneath it + + // BSDFs can be layered using this closure + closure color layer (closure color top, closure color base); + + + +// Global Variables +// Contains info that the renderer knows +// These variables need not be declared + +point P // Position of the point you are shading +vector I // Incident ray direction from viewing position to shading position +normal N // Normal of the surface at P +normal Ng // Normal of the surface at P irrespective of bump mapping +float u // UV 2D x - parametric coordinate of geometry +float v // UV 2D y - parametric coordinate of geometry +vector dPdu // change of P with respect to u tangent to the surface +vector dPdv // change of P with respect to v tangent to the surface +float time // Current time +float dtime // Time covered +vector dPdtime // change of P with respect to time + +///////////////////// +// 4. Control flow // +///////////////////// + +// Conditionals in OSL are just like in C or C++. + +// If/Else +if (5>2){ + int x = s; + int l = x; +} +else{ + int x = s + l; +} + +// 'while' loop +int i = 0; +while (i < 5) { + i += 1; + printf("Current value of i: %d\n", i); +} + +// 'do-while' loop is where test happens after the body of the loop +int i = 0; +do { + printf("Current value of i: %d\n", i); + i += 1; +} while (i < 5); + +// 'for' loop +for (int i = 0; i < 5; i += 1) { + printf("Current value of i: %d\n", i); +} + +///////////////////// +// 5. Functions // +///////////////////// + +// Math Constants + M_PI // π + M_PI_35 // π/35 + m_E // e + M_LN2 // ln 2 + M_SQRT2 // √2 + M_SQRT1_2 // √(1/2) + +// Geometry Functions + vector N = vector(0.1, 1, 0.2); // Normal vector + vector I = vector(-0.5, 0.2, 0.8); // Incident vector + + // Faceforward tells the direction of vector + vector facing_dir = faceforward(N, I); // facing_dir = (-0.5, 0.2, 0.8) + + // faceforward with three arguments + vector ref = vector(0.3, -0.7, 0.6); // Reference normal + facing_dir = faceforward(N, I, ref); // facing_dir = (0.5, -0.2, -0.8) + + // reflect gives the reflected vector along normal + vector refl = reflect(I, N); // refl = (-0.7, -0.4, 1.4)\ + + // refract gives the refracted vector along normal + float ior = 1.5; // Index of refraction + vector refr = refract(I, N, ior); // refr = (-0.25861, 0.32814, 0.96143) + + /* Fresnel computes the Reflection (R) and Transmission (T) vectors, along + with the scaling factors for reflected (Kr) and transmitted (Kt) light. */ + float Kr, Kt; + vector R, T; + fresnel(I, N, ior, Kr, Kt, R, T); +/* Kr = 0.03958, Kt = 0.96042 + R = (-0.19278, -0.07711, 0.33854) + T = (-0.25861, 0.32814, 0.96143) */ + + // Rotating a point along a given axis + point Q = point(1, 0, 0); + float angle = radians(90); // 90 degrees + vector axis = vector(0, 0, 1); + point rotated_point = rotate(Q, angle, axis); + // rotated_point = point(0, 1, 0) + + // Rotating a point along a line made by 2 points + point P0 = point(0, 0, 0); + point P1 = point(1, 1, 0); + angle = radians(45); // 45 degrees + Q = point(1, 0, 0); + rotated_point = rotate(Q, angle, P0, P1); + // rotated_point = point(0.707107, 0.707107, 0) + + // Calculating normal of surface at point p + point p1 = point(1, 0, 0); // Point on the sphere of radius 1 + vector normal1 = calculatenormal(p1); + // normal1 = vector(1, 0, 0) + + // Transforming units is easy + float transformu ("cm", float x) // converts to cm + float transformu ("cm", "m", float y) // converts cm to m + +// Displacement Functions + void displace (float 5); // Displace by 5 amp units + void bump (float 10); // Bump by 10 amp units + + +// Noise Generation + + type noise (type noise (string noisetype, float u, float v, ...)); // noise + type noise (string noisetype, point p,...); // point instead of coordinates + /* some noises are ("perlin", "snoise", "uperlin", "noise", "cell", "hash" + "simplex", "usimplex", "gabor", etc) */ + + // Noise Names + + // 1. Perlin Noise (perlin, snoise): + // Creates smooth, swirling noise often used for textures. + // Range: [-1, 1] (signed) + color cloud_texture = noise("perlin", P); + + // 2. Simplex Noise (simplex, usimplex): + // Similar to Perlin noise but faster. + // Range: [-1, 1] (signed) for simplex, [0, 1] (unsigned) for usimplex + float bump_amount = 0.2 * noise("simplex", P * 5.0); + + // 3. UPerlin Noise (uperlin, noise): + // Similar to peril + // Range: [0, 1] (unsigned) + color new_texture = noise("uperlin", P); + + // 4. Cell Noise (cell): + // Creates a blocky, cellular and constant values within each unit block + // Range: [0, 1] (unsigned) + color new_texture = noise("cell", P); + + // 5. Hash Noise (hash): + // Generates random, uncorrelated values at each point. + // Range: [0, 1] (unsigned) + color new_texture = noise("hash", P); + + // Gabor Noise (gabor) + // Gabor Noise is advanced version of Perin noies and gives more control + // Range: [-1, 1] (signed) + // Gabor Noise Parameters + + // Anisotropic (default: 0) + // Controls anisotropy: + // 0: Isotropic (equal frequency in all directions) + // 1: Anisotropic with user-defined direction vector (defaults to (1,0,0)) + /* 2: Hybrid mode,anisotropic along direction vector but radially isotropic + perpendicularly. */ + + // Direction (default: (1,0,0)) + // Specifies the direction of anisotropy (used only if anisotropic is 1). + + // bandwidth (default: 1.0) + // Controls the frequency range of the noise. + + // impulses (default: 16) + // Controls the number of impulses used per cell, affecting detail level. + + // do_filter (default: 1) + // Enables/disables antialiasing (filtering). + + result = noise( + "gabor", + P, + "anisotropic", anisotropic, + "direction", direction, + "bandwidth", bandwidth, + "impulses", impulses, + "do_filter", do_filter + ); + + // Specific noises can also be used instead of passing them as types + // pnoise is periodic noise + float n1 = pnoise("perlin", 0.5, 1.0); + // 2D periodic noise with Gabor type + float n2 = pnoise("gabor", 0.2, 0.3, 2.0, 3.0); + // 2D non-periodic simplex noise + float n3 = snoise(0.1, 0.7); + // 2D periodic simplex noise + type psnoise (float u, float v, float uperiod, float vperiod); + float n4 = psnoise(0.4, 0.6, 0.5, 0.25); + // 2D cellular noise + float n5 = cellnoise(0.2, 0.8); + // 2D hash noise + int n6 = hash(0.7, 0.3); + +// Step Function + // Step Functions are used to compare input and threshold + + // The type may be of float, color, point, vector, or normal. + type step (type edge, type x); // Returns 1 if x ≥ edge, else 0 + color checker = step(0.5, P); // P is a point on the surface + /* Pixels with P values below 0.5 will be black, those above or equal will + be white */ + float visibility = step(10, distance(P, light_position)); + // Light is fully visible within 10 units, completely invisible beyond + + type linearstep (type edge0, type edge1, type x); /* Linearstep Returns 0 + if x ≤ edge0, and 1 if x ≥ edge1, with linear interpolation */ + color gradient = linearstep(0, 1, P); + // P is a point on the surface between 0 and 1 + // Color will graduate smoothly from black to white as P moves from 0 to 1 + float fade = linearstep(0.85, 1, N.z); // N.z is the z-component + // Object edges with normals close to vertical (N.z near 1) will fade out + + type smoothstep (type edge0, type edge1, type x); /* smoothstep Returns 0 + if x ≤ edge0, and 1 if x ≥ edge1, with Hermite interpolation */ + float soft_mask = smoothstep(0.2, 0.8, noise(P)); /* noise(P) is a noisy + value between 0 and 1. soft_mask will vary smoothly between 0 and 1 based + on noise(P), with a smoother curve than linearstep */ + +// Splines + // Splines are smooth curves based on a set of control points + + /* The type of interpolation ranges from "catmull-rom", "bezier", + "bspline", "hermite", "linear", or "constant" */ + + // Spline with knot vector + float[] knots = {0, 0, 0, 0.25, 0.5, 0.75, 1, 1, 1}; + point[] controls = {point(0),point(1, 2, 1),point(2, 1, 2),point(3, 3, 1)}; + spline curve1 = spline("bezier", 0.5, len(knots), controls); + // curve1 is a Bezier spline evaluated at u = 0.5 + + // Spline with control points + spline curve2 = spline("catmull-rom", 0.25, point(0, 0, 0), point(1, 2, 1), + point(2, 1, 2), point(3, 3, 1)); + // curve2 is a Catmull-Rom spline evaluated at u = 0.25 + + // Constant spline with a single float value + float value = 10; + u = 0.1; + spline curve5 = spline("constant", u, value); + // curve5 is a constant spline with value 10 evaluated at u = 0.1 + + // Hermite spline with point and vector controls + point q0 = point(0, 0, 0), q1 = point(3, 3, 3); + vector t0 = vector(1, 0, 0), t1 = vector(-1, 1, 1); + u = 0.75; + spline curve3 = spline("hermite", u, q0, t0, q1, t1); + // curve3 is a Hermite spline evaluated at u = 0.75 + + // Linear spline with float controls + float f0 = 0, f1 = 1, f2 = 2, f3 = 3; + u = 0.4; + spline curve4 = spline("linear", u, f0, f1, f2, f3); + // curve4 is a linear spline evaluated at u = 0.4 + + // InverseSplines also exist + + // Inverse spline with control values + float y0 = 0, y1 = 1, y2 = 2, y3 = 3; + float v = 1.5; + float u1 = splineinverse("linear", v, y0, y1, y2, y3); + // u1 = 0.5 (linear interpolation between y1 and y2) + + // Inverse spline with knot vector + float[] knots = {0, 0, 0, 0.25, 0.5, 0.75, 1, 1, 1}; + float[] values = {0, 1, 4, 9}; + v = 6; + float u2 = splineinverse("bezier", v, len(knots), values); + // u2 = 0.75 (Bezier spline inverse evaluated at v = 6) + + // Inverse spline with constant value + v = 10; + float u3 = splineinverse("constant", v, 10); + // u3 = 0 (since the constant spline always returns 10) + + // Inverse spline with periodic values + float y4 = 0, y5 = 1, y6 = 0; + v = 0.5; + float u4 = splineinverse("periodic", v, y4, y5, y6); + // u4 = 0.75 (periodic spline inverse evaluated at v = 0.5) + + + +// Calculus Operators + // Partial derivative of f with respect to x, y and z using Dx, Dy, Dz + float a = 3.14; + float dx = Dx(a); // partial derivative of a with respect to x + + point p = point(1.0, 2.0, 3.0); + vector dp_dx = Dx(p); // partial derivative of p with respect to x + + vector dv_dy = Dy(N); // partial derivative of normal with respect to y + + color c = color(0.5, 0.2, 0.8); + color dc_dz = Dz(c); // partial derivative of c with respect to z + + + float area (point p) // gives the surface area at the position p + + float filterwidth (float x) // gives the changes of x in adjacent samples + +// Texture Functions + // lookup for a texture at coordinates (x,y) + color col1 = texture("texture.png", 0.5, 0.2); + // Lookup color at (0.5, 0.2) in texture.png + + // 3D lookup for a texture at coordinates (x,y) + color col3 = texture3d("texture3d.vdb", point(0.25, 0.5, 0.75)); + + // parameters are ("blur","width","wrap","fill","alpha","interp", ...) + color col2 = texture("texture.png",1.0,0.75,"blur",0.1,"wrap", "periodic"); + // Lookup color at (1.0, 0.75) with blur 0.1 and periodic wrap mode + +// Light Functions + + float surfacearea (); // Returns the surface area of area light covers + int backfacing (); // Outputs 1 if the normals are backfaced, else 0 + int raytype (string name); // returns 1 if the ray is a particular raytype + + // Tracing a ray from a position in a direction + point pos = point(0, 0, 0); // Starting position of the ray + vector dir = vector(0, 0, 1); // Direction of the ray + int hit = trace(pos, dir); // returns 1 if it hits, else 0 + +``` +### Further reading + +* [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) +* [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..50e1e27e 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -677,7 +677,7 @@ Powershell as a Tool: Getting Help: -```Powershell +```powershell # Find commands Get-Command about_* # alias: gcm Get-Command -Verb Add @@ -694,7 +694,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 +708,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/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/go-pt.html.markdown b/pt-br/go-pt.html.markdown index 60b3a472..ce10e079 100644 --- a/pt-br/go-pt.html.markdown +++ b/pt-br/go-pt.html.markdown @@ -295,17 +295,17 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { ## Leitura Recomendada -A principal fonte de informação é o [web site oficial Go](http://golang.org/). +A principal fonte de informação é o [web site oficial Go](https://go.dev/). Lá é possível seguir o tutorial, experimentar de forma iterativa, e ler muito. A própria especificação da linguagem é altamente recomendada. É fácil de ler e incrivelmente curta (em relação ao que é habitual hoje em dia). Na lista de leitura para os aprendizes de Go deve constar o [código fonte da -biblioteca padrão](http://golang.org/src/pkg/). Exaustivamente documentado, é +biblioteca padrão](https://go.dev/src/). Exaustivamente documentado, é a melhor demonstração de código fácil de ler e de perceber, do estilo Go, e da sua escrita idiomática. Ou então clique no nome de uma função na [documentação] -(http://golang.org/pkg/) e veja o código fonte aparecer! +(https://go.dev/pkg/) e veja o código fonte aparecer! Outra ótima fonte para aprender Go é o [Go by example](https://gobyexample.com/). Apesar de ser em inglês, é possível recodificar os exemplos para aprender sobre 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">```ruby +````md +```ruby def foobar - puts "Olá mundo!" + puts "Olá mundo!" end -```</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">[<span class="nv">Clique nesse link</span>][<span class="ss">link1</span>] para mais informações! -[<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. -[<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Legal!"</span> -[<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">[<span class="nv">Isso</span>][] é um link. - -[<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">![<span class="nv">Esse é o alt-attribute.</span>][<span class="ss">myimage</span>] +```md +![Esse é o alt-attribute.][myimage] -[<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/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/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index 40b32816..22249a6e 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -334,12 +334,12 @@ func requestServer() { ## Что дальше -Основа всех основ в Go это [официальный веб сайт](http://golang.org/). +Основа всех основ в Go это [официальный веб сайт](https://go.dev/). Там можно пройти туториал, поиграться с интерактивной средой Go и почитать объёмную документацию. Для живого ознакомления рекомендуется почитать исходные коды [стандартной -библиотеки Go](http://golang.org/src/pkg/). Отлично задокументированная, она +библиотеки Go](https://go.dev/src/). Отлично задокументированная, она является лучшим источником для чтения и понимания Go, его стиля и идиом. Либо -можно, кликнув на имени функции в [документации](http://golang.org/pkg/), +можно, кликнув на имени функции в [документации](https://go.dev/pkg/), перейти к ее исходным кодам. 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 / выведет 'Да & да' / - Чтобы выполнять 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 b1b8eb79..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 -- Однострочные комментарии начинаются с двух дефисов @@ -172,7 +172,7 @@ fib x первое определение, к образцу которого "подойдет" набор аргументов -} fib 1 = 1 -fib 2 = 2 +fib 2 = 1 fib x = fib (x - 1) + fib (x - 2) -- Pattern matching для кортежей выглядит так @@ -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">```ruby +```ruby def foobar - puts "Привет, мир!" + puts "Привет, мир!" end -```</code></pre> +``` Во фрагменте, приведённом выше, отступ не требуется. -Кроме того, Github подсветит синтаксис языка, указанного после \`\`\` +Кроме того, GitHub подсветит синтаксис языка, указанного после \`\`\` ## Горизонтальный разделитель @@ -255,6 +254,7 @@ end ```md [Ссылка!](http://test.com/) ``` + Также для ссылки можно указать всплывающую подсказку (`title`), используя кавычки внутри круглых скобок: @@ -269,11 +269,13 @@ end Markdown также позволяет размечать ссылку в виде сноски: -<pre><code class="highlight">[<span class="nv">Щёлкните эту ссылку</span>][<span class="ss">link1</span>] для подробной информации! -[<span class="nv">Также посмотрите эту ссылку,</span>][<span class="ss">foobar</span>] если хотите. +```md +[Щёлкните эту ссылку][link1] для подробной информации! +[Также посмотрите эту ссылку,][foobar] если хотите. -[<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Круто!"</span> -[<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">[<span class="nv">Это</span>][] ссылка. +```md +[Это][] ссылка. -[<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">![<span class="nv">Это альтернативный текст.</span>][<span class="ss">myimage</span>] +Изображения тоже могут быть оформлены как сноски. + +```md +![Это альтернативный текст.][myimage] + +[myimage]: relative/urls/cool/image.jpg "Если нужна подсказка, её можно добавить" +``` -[<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/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/ru-ru/zfs-ru.html.markdown b/ru-ru/zfs-ru.html.markdown new file mode 100644 index 00000000..46a3fbb5 --- /dev/null +++ b/ru-ru/zfs-ru.html.markdown @@ -0,0 +1,406 @@ +--- +category: tool +tool: zfs +contributors: + - ["sarlalian", "http://github.com/sarlalian"] + - ["A1EF", "https://github.com/A1EF"] +filename: LearnZfs-ru.txt +translators: + - ["A1EF", "https://github.com/A1EF"] +lang: ru-ru +--- + + +[ZFS](http://open-zfs.org/wiki/Main_Page) +представляет собой переосмысление системы хранения данных, комбинирующее в едином инструменте +традиционные файловые системы и системы управления томами. ZFS обладает некоторой специфичной +терминологией, которая отличает её от более традиционных систем хранения данных, однако имеет +отличный набор возможностей, акцентированных на удобстве использования системными администраторами. + + +## Концепции ZFS + +### Виртуальные устройства + +Виртуальное устройство (VDEV) подобно устройству RAID, представляемого RAID-контроллером. +Есть несколько типов виртуальных устройств (VDEV), которые предлагают различные преимущества, +включая отказоустойчивость и скорость доступа. В основном виртуальные устройства (VDEV) +предоставляют лучшую отказоустойчивость и безопасность, нежели RAID-контроллеры. Не рекомендуется +использовать установку RAID с ZFS, поскольку ZFS рассчитывает непосредственно управлять дисками. + +Типы виртуальных устройств (VDEV) + +* mirror (поддерживается n-кратное зеркалирование) +* raidz + * raidz1 (1-диск четности, аналог RAID 5) + * raidz2 (2-диска четности, аналог RAID 6) + * raidz3 (3-диска четности, нет имеет аналогичного RAID-массива) +* disk +* file (не рекомендовано для промышленного применения из-за добавления нежелательного промежуточного слоя иной файловой системы) + +Ваши данные распределяются среди всех виртуальных устройств (VDEV), представленных в пуле хранения, +так что увеличив число виртуальных устройств (VDEV), вы увеличите количество IOPS. + +### Пулы хранения + +ZFS использует пулы хранения как абстракцию над нижним уровнем провайдера хранения (VDEV), позволяя вам отделить видимые пользователю +файловые системы от физического их размещения. + +### ZFS датасеты + +ZFS датасеты подобны традиционным файловым системам, но имеют гораздо больше возможностей, обеспечивающих обилие преимуществ ZFS. +Датасеты поддерживают [Copy on Write](https://ru.wikipedia.org/wiki/%D0%9A%D0%BE%D0%BF%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5_%D0%BF%D1%80%D0%B8_%D0%B7%D0%B0%D0%BF%D0%B8%D1%81%D0%B8), снапшоты, квоты, сжатие и дедубликацию. + + +### Ограничения + +Один каталог может содержать до 2^48 файлов, каждый до 16 эксабайт. Один пул хранения может содержать до 256 зеттабайт (2^78) данных +и может быть распределён по 2^64 устройствам. А один хост может иметь 2^64 пула хранения. Лимиты огромны. + + +## Команды + +### Пулы хранения + +Действия: + +* Просмотр +* Статус +* Удаление +* Получение/установка свойств + +Просмотр пулов + +```bash +# Создание пула типа raidz +$ zpool create zroot raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 + +# Просмотр пулов +$ zpool list +NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT +zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - + +# Просмотр детализованной информации о конкретном пуле +$ zpool list -v zroot +NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT +zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 141G 106G 35.2G - 43% 75% +``` + +Статус пулов + +```bash +# Получение информации о статусе пулов +$ zpool status + pool: zroot + state: ONLINE + scan: scrub repaired 0 in 2h51m with 0 errors on Thu Oct 1 07:08:31 2015 +config: + + NAME STATE READ WRITE CKSUM + zroot ONLINE 0 0 0 + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0 + +errors: No known data errors + +# Скрабинг пула для исправления любых ошибок +$ zpool scrub zroot +$ zpool status -v zroot + pool: zroot + state: ONLINE + scan: scrub in progress since Thu Oct 15 16:59:14 2015 + 39.1M scanned out of 106G at 1.45M/s, 20h47m to go + 0 repaired, 0.04% done +config: + + NAME STATE READ WRITE CKSUM + zroot ONLINE 0 0 0 + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0 + +errors: No known data errors +``` + +Свойства пулов + +```bash + +# Получение свойств пула, свойства могут быть заданы пользователем или системой. +$ zpool get all zroot +NAME PROPERTY VALUE SOURCE +zroot size 141G - +zroot capacity 75% - +zroot altroot - default +zroot health ONLINE - +... + +# Установка значения свойства пула +$ zpool set comment="Storage of mah stuff" zroot +$ zpool get comment +NAME PROPERTY VALUE SOURCE +tank comment - default +zroot comment Storage of mah stuff local +``` + +Удаление пула + +```bash +$ zpool destroy test +``` + + +### Датасеты + +Действия: + +* Создание +* Просмотр +* Переименование +* Удаление +* Получение/установка свойств + +Создание датасетов + +```bash +# Создание датасета +$ zfs create zroot/root/data +$ mount | grep data +zroot/root/data on /data (zfs, local, nfsv4acls) + +# Создание дочернего датасета +$ zfs create zroot/root/data/stuff +$ mount | grep data +zroot/root/data on /data (zfs, local, nfsv4acls) +zroot/root/data/stuff on /data/stuff (zfs, local, nfsv4acls) + + +# Создание тома +$ zfs create -V zroot/win_vm +$ zfs list zroot/win_vm +NAME USED AVAIL REFER MOUNTPOINT +zroot/win_vm 4.13G 17.9G 64K - +``` + +Просмотр датасетов + +```bash +# Просмотр всех датасетов +$ zfs list +NAME USED AVAIL REFER MOUNTPOINT +zroot 106G 30.8G 144K none +zroot/ROOT 18.5G 30.8G 144K none +zroot/ROOT/10.1 8K 30.8G 9.63G / +zroot/ROOT/default 18.5G 30.8G 11.2G / +zroot/backup 5.23G 30.8G 144K none +zroot/home 288K 30.8G 144K none +... + +# Просмотр конкретного датасета +$ zfs list zroot/home +NAME USED AVAIL REFER MOUNTPOINT +zroot/home 288K 30.8G 144K none + +# Просмотр снапшотов +$ zfs list -t snapshot +zroot@daily-2015-10-15 0 - 144K - +zroot/ROOT@daily-2015-10-15 0 - 144K - +zroot/ROOT/default@daily-2015-10-15 0 - 24.2G - +zroot/tmp@daily-2015-10-15 124K - 708M - +zroot/usr@daily-2015-10-15 0 - 144K - +zroot/home@daily-2015-10-15 0 - 11.9G - +zroot/var@daily-2015-10-15 704K - 1.42G - +zroot/var/log@daily-2015-10-15 192K - 828K - +zroot/var/tmp@daily-2015-10-15 0 - 152K - +``` + +Переименование датасетов + +```bash +$ zfs rename zroot/root/home zroot/root/old_home +$ zfs rename zroot/root/new_home zroot/root/home +``` + +Удаление датасета + +```bash +# Датасеты не могут быть удалены, если у них имеются какие-то снапшоты +$ zfs destroy zroot/root/home +``` + +Получение / установка свойств датасета + +```bash +# Получение всех свойств +$ zfs get all zroot/usr/home +NAME PROPERTY VALUE SOURCE +zroot/home type filesystem - +zroot/home creation Mon Oct 20 14:44 2014 - +zroot/home used 11.9G - +zroot/home available 94.1G - +zroot/home referenced 11.9G - +zroot/home mounted yes - +... + +# Получения свойства для датасета +$ zfs get compression zroot/usr/home +NAME PROPERTY VALUE SOURCE +zroot/home compression off default + +# Установка значения свойства на датасете +$ zfs set compression=lz4 zroot/lamb + +# Получение значений выбранных свойств всех датасетов +$ zfs list -o name,quota,reservation +NAME QUOTA RESERV +zroot none none +zroot/ROOT none none +zroot/ROOT/default none none +zroot/tmp none none +zroot/usr none none +zroot/home none none +zroot/var none none +... +``` + + +### Снапшоты + +ZFS снапшоты -- одна из очень важных особенностей zfs + +* Место, которое они занимают, равно разнице данных между файловой системой и её снапшотом +* Время создания занимает считанные секунды +* Восстановление настолько быстро, насколько позволяет вам запись данных +* Они очень просты в автоматизации + +Действия: + +* Создание +* Удаление +* Переименование +* Получение доступа к снапшотам +* Отправка / Получение +* Клонирование + + +Создание снапшотов + +```bash +# Создание снапшота единственного датасета +zfs snapshot zroot/home/sarlalian@now + +# Создание снапшота для родительского и дочерних датасетов +$ zfs snapshot -r zroot/home@now +$ zfs list -t snapshot +NAME USED AVAIL REFER MOUNTPOINT +zroot/home@now 0 - 26K - +zroot/home/sarlalian@now 0 - 259M - +zroot/home/alice@now 0 - 156M - +zroot/home/bob@now 0 - 156M - +... +``` + +Удаление снапшотов + +```bash +# Как удалить снапшот +$ zfs destroy zroot/home/sarlalian@now + +# Удаление снапшота в родительском и дочерних датасетах +$ zfs destroy -r zroot/home/sarlalian@now + +``` + +Переименование снапшотов + +```bash +# Переименование снапшота +$ zfs rename zroot/home/sarlalian@now zroot/home/sarlalian@today +$ zfs rename zroot/home/sarlalian@now today + +$ zfs rename -r zroot/home@now @yesterday +``` + +Получение доступа к спапшотам + +```bash +# CD в каталог снапшота +$ cd /home/.zfs/snapshot/ +``` + +Отправка и получение + +```bash +# Сохранение снапшота в файл +$ zfs send zroot/home/sarlalian@now | gzip > backup_file.gz + +# Отправка снапшота в другой датасет +$ zfs send zroot/home/sarlalian@now | zfs recv backups/home/sarlalian + +# Отправка снапшота на удаленный хост +$ zfs send zroot/home/sarlalian@now | ssh root@backup_server 'zfs recv zroot/home/sarlalian' + +# Отправка полного датасета со снапшотами на новый хост +$ zfs send -v -R zroot/home@now | ssh root@backup_server 'zfs recv zroot/home' +``` + +Клонирование снапшотов + +```bash +# Клонирование снапшота +$ zfs clone zroot/home/sarlalian@now zroot/home/sarlalian_new + +# Повышение клона, чтобы он больше не зависел от снапшота +$ zfs promote zroot/home/sarlalian_new +``` + +### Собираем всё вместе + +Нижеследующий скрипт использует FreeBSD, jails и ZFS для автоматизации +подготовки чистой копии стейджинговой базы mysql с живой реплики слейв-ноды. + +```bash +#!/bin/sh + +echo "==== Остановка стейджингового сервера баз данных ====" +jail -r staging + +echo "==== Очистка существующих стейджингового сервера и снапшота ====" +zfs destroy -r zroot/jails/staging +zfs destroy zroot/jails/slave@staging + +echo "==== Фиксация базы на слейве ====" +echo "FLUSH TABLES WITH READ LOCK;" | /usr/local/bin/mysql -u root -pmyrootpassword -h slave + +echo "==== Сохранение снапшота файлов базы слейва как zroot/jails/slave@staging ====" +zfs snapshot zroot/jails/slave@staging + +echo "==== Запуск слейв-ноды сервера баз данных ====" +jail -c slave + +echo "==== Клонирование снапшота слейва на стейджинговый сервер ====" +zfs clone zroot/jails/slave@staging zroot/jails/staging + +echo "==== Установка конфига стейджингово mysql ====" +mv /jails/staging/usr/local/etc/my.cnf /jails/staging/usr/local/etc/my.cnf.slave +cp /jails/staging/usr/local/etc/my.cnf.staging /jails/staging/usr/local/etc/my.cnf + +echo "==== Настройка стейджингового файла rc.conf ====" +mv /jails/staging/etc/rc.conf.local /jails/staging/etc/rc.conf.slave +mv /jails/staging/etc/rc.conf.staging /jails/staging/etc/rc.conf.local + +echo "==== Запуск стейджингово сервера баз данных ====" +jail -c staging + +echo "==== Отключение синхронизации стейджинговой базы с мастером ====" +echo "STOP SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging +echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging +``` + + +### Почитать дополнительно + +* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) +* [FreeBSD Handbook on ZFS](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/zfs.html) +* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) +* [Oracle's Tuning Guide](http://www.oracle.com/technetwork/articles/servers-storage-admin/sto-recommended-zfs-settings-1951715.html) +* [OpenZFS Tuning Guide](http://open-zfs.org/wiki/Performance_tuning) +* [FreeBSD ZFS Tuning Guide](https://wiki.freebsd.org/ZFSTuningGuide) 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/sk-sk/latex-sk.html.markdown.tex b/sk-sk/latex-sk.html.markdown index 5e2f9c7f..5e2f9c7f 100644 --- a/sk-sk/latex-sk.html.markdown.tex +++ b/sk-sk/latex-sk.html.markdown diff --git a/sk-sk/learn-latex-sk.tex b/sk-sk/learn-latex-sk.tex deleted file mode 100644 index 5cc7b11f..00000000 --- a/sk-sk/learn-latex-sk.tex +++ /dev/null @@ -1,209 +0,0 @@ -% Všetky komentáre začínajú s % -% Viac-riadkové komentáre sa nedajú urobiť - -% LaTeX NIE JE WYSIWY ("What You See Is What You Get") software ako MS Word, alebo OpenOffice Writer - -% Každý LaTeX príkaz začína s opačným lomítkom (\) - -% LaTeX dokumenty začínajú s definíciou typu kompilovaného dokumentu -% Ostatné typy sú napríklad kniha (book), správa (report), prezentácia (presentation), atď. -% Možnosti dokumentu sa píšu do [] zátvoriek. V tomto prípade tam upresňujeme veľkosť (12pt) fontu. -\documentclass[12pt]{article} - -% Ďalej definujeme balíčky, ktoré dokuemnt používa. -% Ak chceš zahrnúť grafiku, farebný text, či zdrojový kód iného jazyka, musíš rozšíriť možnosti LaTeXu dodatočnými balíčkami. -% Zahŕňam float a caption. Na podporu slovenčiny treba zahrnúť aj utf8 balíček. -\usepackage{caption} -\usepackage{float} -\usepackage[utf8]{inputenc} -% Tu môžme definovať ostatné vlastnosti dokumentu! -% Autori tohto dokumentu, "\\*" znamená "choď na nový riadok" -\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu, \\*Preklad: Terka Slanináková} -% Vygeneruje dnešný dátum -\date{\today} -\title{Nauč sa LaTeX za Y Minút!} -% Teraz môžme začať pracovať na samotnom dokumente. -% Všetko do tohto riadku sa nazýva "Preambula" ("The Preamble") -\begin{document} -% ak zadáme položky author, date a title, LaTeX vytvorí titulnú stranu. -\maketitle - -% Väčšina odborných článkov má abstrakt, na jeho vytvorenie môžeš použiť preddefinované príkazy. -% Ten by sa mal zobraziť v logickom poradí, teda po hlavičke, -% no pred hlavnými sekciami tela.. -% Tento príkaz je tiež dostupný v triedach article a report. -% Tzv. makro "abstract" je fixnou súčasťou LaTeXu, ak chceme použiť abstract -% a napísať ho po slovensky, musíme ho redefinovať nasledujúcim príkazom -\renewcommand\abstractname{Abstrakt} - -\begin{abstract} -LaTeX dokumentácia v LaTeXe! Aké netradičné riešenie cudzieho nápadu! -\end{abstract} - -% Príkazy pre sekciu sú intuitívne -% Všetky nadpisy sekcií sú pridané automaticky do obsahu. -\section{Úvod} -Čaute, volám sa Colton a spoločne sa pustíme do skúmania LaTeXu (toho druhého)! - -\section{Ďalšia sekcia} -Toto je text ďalšej sekcie. Myslím, že potrebuje podsekciu. - -\subsection{Toto je podsekcia} % Podsekcie sú tiež intuitívne. -Zdá sa mi, že treba ďalšiu. - -\subsubsection{Pytagoras} -To je ono! -\label{subsec:pytagoras} - -% Použitím '*' môžeme potlačiť zabudované číslovanie LaTeXu. -% Toto funguje aj na iné príkazy. -\section*{Toto je nečíslovaná sekcia} -Všetky číslované byť nemusia! - -\section{Nejaké poznámočky} -Zarovnávať veci tam, kde ich chceš mať, je všeobecne ľahké. Ak -potrebuješ \\ nový \\ riadok \\ pridaj \textbackslash\textbackslash do -zdrojového kódu. \\ - -\section{Zoznamy} -Zoznamy sú jednou z najjednoduchších vecí vôbec! Treba mi zajtra nakúpiť, urobím si zoznam. -\begin{enumerate} % "enumerate" spustí číslovanie prvkov. - % \item povie LaTeXu, ako že treba pripočítať 1 - \item Vlašský šalát. - \item 5 rožkov. - \item 3 Horalky. - % číslovanie môžeme pozmeniť použitím [] - \item[koľko?] Stredne veľkých guličkoviek. - - Ja už nie som položka zoznamu, no stále som časť "enumerate". - -\end{enumerate} % Všetky prostredia končia s "end". - -\section{Matika} - -Jedným z primárnych použití LaTeXu je písanie akademických, či technických prác. Zvyčajne za použitia matematiky a vedy. Podpora špeciálnych symbolov preto nemôže chýbať!\\ - -Matematika má veľa symbolov, omnoho viac, než by klávesnica mohla reprezentovať; -Množinové a relačné symboly, šípky, operátory a Grécke písmená sú len malou ukážkou.\\ - -Množiny a relácie hrajú hlavnú rolu v mnohých matematických článkoch. -Takto napíšeš, že niečo platí pre všetky x patriace do X, $\forall$ x $\in$ X. \\ -% Všimni si, že som pridal $ pred a po symboloch. Je to -% preto, lebo pri písaní sme v textovom móde, -% no matematické symboly existujú len v matematickom. -% Vstúpime doňho z textového práve '$' znamienkami. -% Platí to aj opačne. Premenná môže byť zobrazená v matematickom móde takisto. -% Do matematického módu sa dá dostať aj s \[\] - -\[a^2 + b^2 = c^2 \] - -Moje obľúbené Grécke písmeno je $\xi$. Tiež sa mi pozdávajú $\beta$, $\gamma$ a $\sigma$. -Ešte som neprišiel na Grécke písmeno, ktoré by LaTeX nepoznal! - -Operátory sú dôležitou súčasťou matematických dokumentov: -goniometrické funkcie ($\sin$, $\cos$, $\tan$), -logaritmy and exponenciálne výrazy ($\log$, $\exp$), -limity ($\lim$), atď. -majú pred-definované LaTeXové príkazy. -Napíšme si rovnicu, nech vidíme, ako to funguje: \\ - -$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ - -Zlomky(Čitateľ-menovateľ) sa píšu v týchto formách: - -% 10 / 7 -$^{10}/_{7}$ - -% Relatívne komplexné zlomky sa píšu ako -% \frac{čitateľ}{menovateľ} -$\frac{n!}{k!(n - k)!}$ \\ - -Rovnice tiež môžeme zadať v "rovnicovom prostredí". - -% Takto funguje rovnicové prostredie -\begin{equation} % vstúpi do matematického módu - c^2 = a^2 + b^2. - \label{eq:pythagoras} % na odkazovanie -\end{equation} % všetky \begin príkazy musia mať konečný príkaz. - -Teraz môžeme odkázať na novovytvorenú rovnicu! -Rovn.~\ref{eq:pythagoras} je tiež známa ako Pytagorova Veta, ktorá je tiež predmetom Sekc.~\ref{subsec:pytagoras}. Odkazovať môžme na veľa vecí, napr na: čísla, rovnice, či sekcie. - -Sumácie a Integrály sa píšu príkazmi sum a int: - -% Niektoré prekladače LaTeXu sa môžu sťažovať na prázdne riadky (ak tam sú) -% v rovnicovom prostredí. -\begin{equation} - \sum_{i=0}^{5} f_{i} -\end{equation} -\begin{equation} - \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x -\end{equation} - -\section{Obrázky} - -Vloženie obrázku môže byť zložitejšie. Ja si vždy možnosti vloženia pozerám pre každý obrázok. -\renewcommand\figurename{Obrázok} -\begin{figure}[H] % H značí možnosť zarovnania. - \centering % nacentruje obrázok na stránku - % Vloží obrázok na 80% šírky stránky. - %\includegraphics[width=0.8\linewidth]{right-triangle.png} - % Zakomentované kvôli kompilácií, použi svoju predstavivosť :). - \caption{Pravouhlý trojuholník so stranami $a$, $b$, $c$} - \label{fig:right-triangle} -\end{figure} -% Opäť, fixné makro "table" nahradíme slovenskou tabuľkou. Pokiaľ preferuješ table, nasledujúci riadok nepridávaj -\renewcommand\tablename{Tabuľka} - -\subsection{Tabuľky} -Tabuľky sa vkládajú podobne ako obrázky. - -\begin{table}[H] - \caption{Nadpis tabuľky.} - % zátvorky: {} hovoria ako sa vykreslí každý riadok. - % Toto si nikdy nepamätám a vždy to musím hľadať. Všetko. Každý. Jeden. Raz! - \begin{tabular}{c|cc} - Číslo & Priezvisko & Krstné meno \\ % Stĺpce sú rozdelené $ - \hline % horizontálna čiara - 1 & Ladislav & Meliško \\ - 2 & Eva & Máziková - \end{tabular} -\end{table} - -% \section{Hyperlinks} % Už čoskoro :) - -\section{Prikáž LaTeXu nekompilovať (napr. Zdrojový Kód)} -Povedzme, že chceme do dokumentu vložiť zdrojový kód, budeme musieť LaTeXu povedať, nech sa ho nesnaží skompilovať, ale nech s ním pracuje ako s textom. -Toto sa robí vo verbatim prostredí. - -% Tiež sú na to špeciálne balíčky, (napr. minty, lstlisting, atď.) -% ale verbatim je to najzákladnejšie, čo môžeš použiť. -\begin{verbatim} - print("Hello World!") - a%b; pozri! Vo verbatime môžme použiť % znamienka. - random = 4; #priradené randomným hodom kockou -\end{verbatim} - -\section{Kompilácia} - -Už by bolo načase túto nádheru skompilovať a zhliadnuť jej úžasnú úžasnosť v podobe LaTeX pdfka, čo povieš? -(áno, tento dokument sa musí kompilovať). \\ -Cesta k finálnemu dokumentu pomocou LaTeXu pozostáva z nasledujúcich krokov: - \begin{enumerate} - \item Napíš dokument v čistom texte (v "zdrojáku"). - \item Skompiluj zdroják na získanie pdfka. - Kompilácia by mala vyzerať nasledovne (v Linuxe): \\ - \begin{verbatim} - $pdflatex learn-latex.tex learn-latex.pdf - \end{verbatim} - \end{enumerate} - -Mnoho LaTeX editorov kombinuje Krok 1 a Krok 2 v jednom prostredí. Krok 1 teda uvidíš, krok 2 už nie. -Ten sa deje za oponou. Kompilácia v 2. kroku sa postará o produkciu dokumentu v tebou zadanom formáte. - -\section{Koniec} - -To je zatiaľ všetko! - -% koniec dokumentu -\end{document} 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/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/uk-ua/go-ua.html.markdown b/uk-ua/go-ua.html.markdown index f980f7b1..6f294b1f 100644 --- a/uk-ua/go-ua.html.markdown +++ b/uk-ua/go-ua.html.markdown @@ -434,15 +434,15 @@ func requestServer() { ## Подальше вивчення -Основним джерелом всієї інформації про Go залишається [офіційна веб-сторінка](http://golang.org/). Там можна знайти уроки, інтерактивно пограти та багато про що почитати. -Окрім туру, у [документації](https://golang.org/doc/) міститься інформація як писати чистий та ефективний код на Go, документація пакетів та окремих команд, а також історія релізів. +Основним джерелом всієї інформації про Go залишається [офіційна веб-сторінка](https://go.dev/). Там можна знайти уроки, інтерактивно пограти та багато про що почитати. +Окрім туру, у [документації](https://go.dev/doc/) міститься інформація як писати чистий та ефективний код на Go, документація пакетів та окремих команд, а також історія релізів. Надзвичайно рекомендується ознайомитись із визначенням мови. Вона легко читається та на диво коротка (в порівнянні з іншими сучасними мовами). -Можна погратись з кодом вище на [Go playground](https://play.golang.org/p/tnWMjr16Mm). Спробуй змінити його та запустити із свого браузера. Поміть, що можна використовувати [https://play.golang.org](https://play.golang.org) як [REPL](https://uk.wikipedia.org/wiki/REPL) до тестів та коду в твоєму браузері, без встановлення Go. +Можна погратись з кодом вище на [Go playground](https://go.dev/play/p/tnWMjr16Mm). Спробуй змінити його та запустити із свого браузера. Поміть, що можна використовувати [https://go.dev/play/](https://go.dev/play/) як [REPL](https://uk.wikipedia.org/wiki/REPL) до тестів та коду в твоєму браузері, без встановлення Go. -В списку для прочитання новачкам в Go - [вихідний код стандартної бібліотеки](http://golang.org/src/pkg/). Код всеосяжно задокоментований, тому є найкращим прикладом з боку зручного для прочитання та швидкості розуміння коду на цій мові програмування. Приведений стиль та ідіоми Go. -Крім того, можна просто натиснути на назву функції в [документації](http://golang.org/pkg/), щоб перейти до її реалізації. +В списку для прочитання новачкам в Go - [вихідний код стандартної бібліотеки](https://go.dev/src/). Код всеосяжно задокоментований, тому є найкращим прикладом з боку зручного для прочитання та швидкості розуміння коду на цій мові програмування. Приведений стиль та ідіоми Go. +Крім того, можна просто натиснути на назву функції в [документації](https://go.dev/pkg/), щоб перейти до її реалізації. Іншим прекрасним посиланням для вивчення Go є [Go by example](https://gobyexample.com/). 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">```ruby +````md +```ruby def foobar - puts "Hello world!" + puts "Hello world!" end -```</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">[<span class="nv">Nhấn vào đây</span>][<span class="ss">link1</span>] để xem thêm! -[<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. -[<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Tuyệt!"</span> -[<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">[<span class="nv">This</span>][] is a link. +```md +[This][] is a link. -[<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">![<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] -[<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/zfs.html.markdown b/zfs.html.markdown index 6795b1fa..3f5a76b5 100644 --- a/zfs.html.markdown +++ b/zfs.html.markdown @@ -3,6 +3,7 @@ category: tool tool: zfs contributors: - ["sarlalian", "http://github.com/sarlalian"] + - ["A1EF", "https://github.com/A1EF"] filename: LearnZfs.txt --- @@ -25,7 +26,6 @@ RAID setup with ZFS, as ZFS expects to directly manage the underlying disks. Types of VDEV's -* stripe (a single disk, no redundancy) * mirror (n-way mirrors supported) * raidz * raidz1 (1-disk parity, similar to RAID 5) @@ -71,7 +71,7 @@ List zpools ```bash # Create a raidz zpool -$ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 +$ zpool create zroot raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 # List ZPools $ zpool list @@ -160,22 +160,22 @@ Create datasets ```bash # Create dataset -$ zfs create tank/root/data +$ zfs create zroot/root/data $ mount | grep data -tank/root/data on /data (zfs, local, nfsv4acls) +zroot/root/data on /data (zfs, local, nfsv4acls) # Create child dataset -$ zfs create tank/root/data/stuff +$ zfs create zroot/root/data/stuff $ mount | grep data -tank/root/data on /data (zfs, local, nfsv4acls) -tank/root/data/stuff on /data/stuff (zfs, local, nfsv4acls) +zroot/root/data on /data (zfs, local, nfsv4acls) +zroot/root/data/stuff on /data/stuff (zfs, local, nfsv4acls) # Create Volume $ zfs create -V zroot/win_vm $ zfs list zroot/win_vm NAME USED AVAIL REFER MOUNTPOINT -tank/win_vm 4.13G 17.9G 64K - +zroot/win_vm 4.13G 17.9G 64K - ``` List datasets @@ -213,28 +213,28 @@ zroot/var/tmp@daily-2015-10-15 Rename datasets ```bash -$ zfs rename tank/root/home tank/root/old_home -$ zfs rename tank/root/new_home tank/root/home +$ zfs rename zroot/root/home zroot/root/old_home +$ zfs rename zroot/root/new_home zroot/root/home ``` Delete dataset ```bash # Datasets cannot be deleted if they have any snapshots -$ zfs destroy tank/root/home +$ zfs destroy zroot/root/home ``` Get / set properties of a dataset ```bash # Get all properties -$ zfs get all zroot/usr/home │157 # Create Volume -NAME PROPERTY VALUE SOURCE │158 $ zfs create -V zroot/win_vm -zroot/home type filesystem - │159 $ zfs list zroot/win_vm -zroot/home creation Mon Oct 20 14:44 2014 - │160 NAME USED AVAIL REFER MOUNTPOINT -zroot/home used 11.9G - │161 tank/win_vm 4.13G 17.9G 64K - -zroot/home available 94.1G - │162 ``` -zroot/home referenced 11.9G - │163 +$ zfs get all zroot/usr/home +NAME PROPERTY VALUE SOURCE +zroot/home type filesystem - +zroot/home creation Mon Oct 20 14:44 2014 - +zroot/home used 11.9G - +zroot/home available 94.1G - +zroot/home referenced 11.9G - zroot/home mounted yes - ... @@ -244,7 +244,7 @@ NAME PROPERTY VALUE SOURCE zroot/home compression off default # Set property on dataset -$ zfs set compression=gzip-9 mypool/lamb +$ zfs set compression=lz4 zroot/lamb # Get a set of properties from all datasets $ zfs list -o name,quota,reservation @@ -283,16 +283,16 @@ Create snapshots ```bash # Create a snapshot of a single dataset -zfs snapshot tank/home/sarlalian@now +zfs snapshot zroot/home/sarlalian@now # Create a snapshot of a dataset and its children -$ zfs snapshot -r tank/home@now +$ zfs snapshot -r zroot/home@now $ zfs list -t snapshot NAME USED AVAIL REFER MOUNTPOINT -tank/home@now 0 - 26K - -tank/home/sarlalian@now 0 - 259M - -tank/home/alice@now 0 - 156M - -tank/home/bob@now 0 - 156M - +zroot/home@now 0 - 26K - +zroot/home/sarlalian@now 0 - 259M - +zroot/home/alice@now 0 - 156M - +zroot/home/bob@now 0 - 156M - ... ``` @@ -300,10 +300,10 @@ Destroy snapshots ```bash # How to destroy a snapshot -$ zfs destroy tank/home/sarlalian@now +$ zfs destroy zroot/home/sarlalian@now # Delete a snapshot on a parent dataset and its children -$ zfs destroy -r tank/home/sarlalian@now +$ zfs destroy -r zroot/home/sarlalian@now ``` @@ -311,10 +311,10 @@ Renaming Snapshots ```bash # Rename a snapshot -$ zfs rename tank/home/sarlalian@now tank/home/sarlalian@today -$ zfs rename tank/home/sarlalian@now today +$ zfs rename zroot/home/sarlalian@now zroot/home/sarlalian@today +$ zfs rename zroot/home/sarlalian@now today -$ zfs rename -r tank/home@now @yesterday +$ zfs rename -r zroot/home@now @yesterday ``` Accessing snapshots @@ -328,26 +328,26 @@ Sending and Receiving ```bash # Backup a snapshot to a file -$ zfs send tank/home/sarlalian@now | gzip > backup_file.gz +$ zfs send zroot/home/sarlalian@now | gzip > backup_file.gz # Send a snapshot to another dataset -$ zfs send tank/home/sarlalian@now | zfs recv backups/home/sarlalian +$ zfs send zroot/home/sarlalian@now | zfs recv backups/home/sarlalian # Send a snapshot to a remote host -$ zfs send tank/home/sarlalian@now | ssh root@backup_server 'zfs recv tank/home/sarlalian' +$ zfs send zroot/home/sarlalian@now | ssh root@backup_server 'zfs recv zroot/home/sarlalian' # Send full dataset with snapshots to new host -$ zfs send -v -R tank/home@now | ssh root@backup_server 'zfs recv tank/home' +$ zfs send -v -R zroot/home@now | ssh root@backup_server 'zfs recv zroot/home' ``` Cloning Snapshots ```bash # Clone a snapshot -$ zfs clone tank/home/sarlalian@now tank/home/sarlalian_new +$ zfs clone zroot/home/sarlalian@now zroot/home/sarlalian_new # Promoting the clone so it is no longer dependent on the snapshot -$ zfs promote tank/home/sarlalian_new +$ zfs promote zroot/home/sarlalian_new ``` ### Putting it all together 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/csharp-cn.html.markdown b/zh-cn/csharp-cn.html.markdown index 0bad34ce..b6cc70c0 100644 --- a/zh-cn/csharp-cn.html.markdown +++ b/zh-cn/csharp-cn.html.markdown @@ -5,45 +5,64 @@ contributors: - ["Max Yankov", "https://github.com/golergka"] - ["Melvyn Laïly", "http://x2a.yt"] - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] + - ["Wouter Van Schandevijl", "http://github.com/laoujin"] + - ["Jo Pearce", "http://github.com/jdpearce"] + - ["Chris Zimmerman", "https://github.com/chriszimmerman"] + - ["Shawn McGuire", "https://github.com/bigbash"] translators: - ["Jakukyo Friel", "http://weakish.github.io"] + - ["CatfishWen", "http://catfishwen.github.io"] filename: LearnCSharp-cn.cs lang: zh-cn --- +C#是一种优雅且类型安全的面向对象的语言,使开发人员能够构建运行在跨平台的.NET框架上,安全且健壮的应用程序。 -C#是一个优雅的、类型安全的面向对象语言。使用C#,开发者可以在.NET框架下构建安全、健壮的应用程序。 - -[更多关于C#的介绍](http://msdn.microsoft.com/en-us/library/vstudio/z1zx9t92.aspx) +[更多关于C#的介绍](https://learn.microsoft.com/zh-cn/dotnet/csharp/tour-of-csharp/) ```c# // 单行注释以 // 开始 /* 多行注释是这样的 */ + /// <summary> -/// XML文档注释 +/// 这是 XML文档注释 +/// 可用于生成外部文档或在 IDE 中提供上下文帮助 /// </summary> +/// <param name="firstParam">这是 firstParam 参数的文档</param> +/// <returns>这是函数返回值的信息</returns> +public void MethodOrClassOrOtherWithParsableHelp(string firstParam) { } -// 声明应用用到的命名空间 +// 声明这段源码使用到的命名空间 +// 下面的命名空间都是标准 .NET Framework 类库的一部分 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; -// 定义作用域,将代码组织成包 +// 但是这个并不是标准类库: +using System.Data.Entity; +// 为了在下方使用它,你需要添加一个 dll 引用 +// 你可以使用 NuGet 包管理器进行安装 +// `Install-Package EntityFramework` + +// 命名空间 Namespaces 可用于将一定的代码组织为 “包” 或者 “模块” +// 你可以在其他文件中这样引用:using Learning.CSharp; + +// 在 C# 10 以后,你也可以这样定义命名空间。这被称为 file-scoped namespaces(文件范围的命名空间). +// namespace Learning.CSharp; + namespace Learning { // 每个 .cs 文件至少需要包含一个和文件名相同的类 - // 你可以不这么干,但是这样不好。 + // 你可以不这么干,但是这样并不推荐。 public class LearnCSharp { - // 基本语法 - 如果你以前用过 Java 或 C++ 的话,可以直接跳到后文「有趣的特性」 + // 基本语法 - 如果你以前用过 Java 或 C++ 的话,可以直接跳到后文「有趣的特性」 public static void Syntax() { // 使用 Console.WriteLine 打印信息 @@ -53,7 +72,7 @@ namespace Learning " Double: " + 3.14 + " Boolean: " + true); - // 使用 Console.Write 打印,不带换行符号 + // 使用 Console.Write 打印将不会换行 Console.Write("Hello "); Console.Write("World"); @@ -113,7 +132,7 @@ namespace Learning char charFromString = fooString[1]; // => 'e' // 字符串不可修改: fooString[1] = 'X' 是行不通的; - // 根据当前的locale设定比较字符串,大小写不敏感 + // 根据当前的区域格式设置比较字符串,大小写不敏感 string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); // 基于sprintf的字符串格式化 @@ -123,12 +142,13 @@ namespace Learning DateTime fooDate = DateTime.Now; Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); - // 使用 @ 符号可以创建跨行的字符串。使用 "" 来表示 " + // 逐字字符串 + // 使用 @ 符号可以创建跨行的字符串。使用 "" 来表示 " string bazString = @"Here's some stuff on a new line! ""Wow!"", the masses cried"; - // 使用const或read-only定义常量 - // 常量在编译期演算 + // 使用 const 或 read-only 定义常量 + // 常量在编译阶段演算 const int HOURS_I_WORK_PER_WEEK = 9001; /////////////////////////////////////////////////// @@ -136,7 +156,7 @@ on a new line! ""Wow!"", the masses cried"; /////////////////////////////////////////////////// // 数组 - 从0开始计数 - // 声明数组时需要确定数组长度 + // 声明数组时需要指定数组长度 // 声明数组的格式如下: // <datatype>[] <var name> = new <datatype>[<array size>]; int[] intArray = new int[10]; @@ -155,8 +175,8 @@ on a new line! ""Wow!"", the masses cried"; // List<datatype> <var name> = new List<datatype>(); List<int> intList = new List<int>(); List<string> stringList = new List<string>(); - List<int> z = new List<int> { 9000, 1000, 1337 }; // i - // <>用于泛型 - 参考下文 + List<int> z = new List<int> { 9000, 1000, 1337 }; // 初始化 + // <> 用于泛型 - 参考下文 // 列表无默认值 // 访问列表元素时必须首先添加元素 @@ -164,18 +184,18 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine("intList @ 0: " + intList[0]); // 其他数据结构: - // 堆栈/队列 - // 字典 (哈希表的实现) - // 哈希集合 - // 只读集合 - // 元组 (.Net 4+) + // Stack 堆栈 / Queue 队列 + // Dictionary 字典 (哈希表的实现) + // HashSet 哈希集合 + // Read-only Collections 只读集合 + // Tuple 元组 (.Net 4+) /////////////////////////////////////// // 操作符 /////////////////////////////////////// Console.WriteLine("\n->Operators"); - int i1 = 1, i2 = 2; // 多重声明的简写形式 + int i1 = 1, i2 = 2; // 声明多个变量的简写形式 // 算术直截了当 Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 @@ -214,7 +234,7 @@ on a new line! ""Wow!"", the masses cried"; /////////////////////////////////////// Console.WriteLine("\n->Control Structures"); - // 类似C的if语句 + // 类似 C 的 if 语句 int j = 10; if (j == 10) { @@ -239,7 +259,7 @@ on a new line! ""Wow!"", the masses cried"; int fooWhile = 0; while (fooWhile < 100) { - //迭代 100 次, fooWhile 0->99 + // 迭代 100 次, fooWhile 0->99 fooWhile++; } @@ -247,14 +267,21 @@ on a new line! ""Wow!"", the masses cried"; int fooDoWhile = 0; do { - //迭代 100 次, fooDoWhile 0->99 + // 迭代 100 次, fooDoWhile 0->99 + if (false) + continue; // 跳过本次迭代 + fooDoWhile++; + + if (fooDoWhile == 50) + break; // 结束整个循环 + } while (fooDoWhile < 100); - //for 循环结构 => for(<初始条件>; <条件>; <步>) + // for 循环结构 => for(<初始条件>; <条件>; <步>) for (int fooFor = 0; fooFor < 10; fooFor++) { - //迭代10次, fooFor 0->9 + // 迭代10次, fooFor 0->9 } // foreach循环 @@ -269,7 +296,7 @@ on a new line! ""Wow!"", the masses cried"; } // Switch 语句 - // switch 适用于 byte、short、char和int 数据类型。 + // switch 适用于 byte、short、char 和 int 数据类型。 // 同样适用于可枚举的类型 // 包括字符串类, 以及一些封装了原始值的类: // Character、Byte、Short和Integer。 @@ -307,46 +334,63 @@ on a new line! ""Wow!"", the masses cried"; // 转换字符串为整数 // 转换失败会抛出异常 - int.Parse("123");//返回整数类型的"123" + int.Parse("123"); // 返回整数类型的"123" - // TryParse会尝试转换类型,失败时会返回缺省类型 + // TryParse 会尝试转换类型,失败时会返回缺省类型 // 例如 0 int tryInt; if (int.TryParse("123", out tryInt)) // Funciton is boolean Console.WriteLine(tryInt); // 123 // 转换整数为字符串 - // Convert类提供了一系列便利转换的方法 + // Convert 类提供了一系列方便转换类型的方法 + + // 比如 字符串 与 int 之间 + + // 最佳方法 + bool result = int.TryParse(string, out var integer) + int.Parse(string); + + // 不推荐 Convert.ToString(123); - // or + + // Int 到字符串 tryInt.ToString(); + + // 转换 + // 显式转换 decimal 类型的 15 为 int 类型 + // 然后隐式转换为 long 类型 + long x = (int) 15M; } /////////////////////////////////////// - // 类 + // 类 - 请参阅文件末尾的定义 /////////////////////////////////////// public static void Classes() { // 参看文件尾部的对象声明 - // 使用new初始化对象 + // 使用 new 初始化对象 Bicycle trek = new Bicycle(); // 调用对象的方法 - trek.SpeedUp(3); // 你应该一直使用setter和getter方法 + trek.SpeedUp(3); // 你应该一直使用 setter 和 getter 方法 trek.Cadence = 100; // 查看对象的信息. Console.WriteLine("trek info: " + trek.Info()); - // 实例化一个新的Penny Farthing + // 实例化一个新的 Penny Farthing 对象 PennyFarthing funbike = new PennyFarthing(1, 10); Console.WriteLine("funbike info: " + funbike.Info()); Console.Read(); } // 结束main方法 - // 终端程序 终端程序必须有一个main方法作为入口 + // record 在 C# 9 及以后可用, 这基本上是类的语法糖. record 对象是不可变的 immutable*. + public record ARecord(string Csharp); + + // 终端程序入口 终端程序必须有一个 main 方法作为入口 public static void Main(string[] args) { OtherInterestingFeatures(); @@ -359,11 +403,11 @@ on a new line! ""Wow!"", the masses cried"; // 默认方法签名 public // 可见性 - static // 允许直接调用类,无需先创建实例 - int, //返回值 + static // 允许从类直接调用,无需先创建实例 + int // 返回值类型 MethodSignatures( - int maxCount, // 第一个变量,类型为整型 - int count = 0, // 如果没有传入值,则缺省值为0 + int maxCount, // 第一个参数,类型为整型 + int count = 0, // 如果没有传入值,则缺省值为 0 int another = 3, params string[] otherParams // 捕获其他参数 ) @@ -371,17 +415,22 @@ on a new line! ""Wow!"", the masses cried"; return -1; } - // 方法可以重名,只要签名不一样 - public static void MethodSignature(string maxCount) + // 方法可以重名,只要方法签名不一样 + // 一个只有返回值类型不同的方法 + public static void MethodSignatures( + ref int maxCount, // 通过引用传递 + out int count) { + // 通过 'count' 参数传入的值将在该方法外保留值 15 + count = 15; // 必须在离开方法之前为 out 参数赋值 } - //泛型 - // TKey和TValue类由用用户调用函数时指定。 - // 以下函数模拟了Python的SetDefault + // 泛型 + // TKey 和 TValue 由用户调用方法时指定 + // 以下函数模拟了 Python 的 SetDefault public static TValue SetDefault<TKey, TValue>( - IDictionary<TKey, TValue> dictionary, - TKey key, + IDictionary<TKey, TValue> dictionary, + TKey key, TValue defaultItem) { TValue result; @@ -393,55 +442,125 @@ on a new line! ""Wow!"", the masses cried"; // 你可以限定传入值的范围 public static void IterateAndPrint<T>(T toPrint) where T: IEnumerable<int> { - // 我们可以进行迭代,因为T是可枚举的 + // 我们可以进行迭代,因为 T 是可枚举的 foreach (var item in toPrint) - // ittm为整数 + // item 为整数 Console.WriteLine(item.ToString()); } + // YIELD + // 使用 "yield" 关键字表明它出现的方法是一个迭代器 Iterator + // (这意味着你可以在 foreach 循环中使用它) + public static IEnumerable<int> YieldCounter(int limit = 10) + { + for (var i = 0; i < limit; i++) + yield return i; + } + + // 你可以这样调用它 + public static void PrintYieldCounterToConsole() + { + foreach (var counter in YieldCounter()) + Console.WriteLine(counter); + } + + // 你可以在一个方法中使用多个 "yield return" + public static IEnumerable<int> ManyYieldCounter() + { + yield return 0; + yield return 1; + yield return 2; + yield return 3; + } + + // 你也可以使用 "yield break" 停止该迭代器 + // 此方法只会返回从 0 到 limit 的一半值。 + public static IEnumerable<int> YieldCounterWithBreak(int limit = 10) + { + for (var i = 0; i < limit; i++) + { + if (i > limit / 2) yield break; + yield return i; + } + } + public static void OtherInterestingFeatures() { - // 可选参数 + // 可选参数 MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); MethodSignatures(3, another: 3); // 显式指定参数,忽略可选参数 + // 使用 ref 和 out 参数 + int maxCount = 0, count; // ref 参数必须有值 + MethodSignatures(ref maxCount, out count); + // 扩展方法 int i = 3; - i.Print(); // 参见下面的定义 + i.Print(); // 参见下面的定义 - // 可为null的类型 对数据库交互、返回值很有用 + // 可为 null 的类型 对数据库交互、返回值很有用 // 任何值类型 (i.e. 不为类) 添加后缀 ? 后会变为可为null的值 // <类型>? <变量名> = <值> int? nullable = null; // Nullable<int> 的简写形式 Console.WriteLine("Nullable variable: " + nullable); bool hasValue = nullable.HasValue; // 不为null时返回真 + // ?? 是用于指定默认值的语法糖 // 以防变量为null的情况 int notNullable = nullable ?? 0; // 0 + // ?. 是另一个可空类型的操作符 - 简写 null 检查 + nullable?.Print(); // 当可空类型值不为 null 的时候调用 Print() 拓展方法 + // 变量类型推断 - 你可以让编译器推断变量类型: var magic = "编译器确定magic是一个字符串,所以仍然是类型安全的"; - // magic = 9; // 不工作,因为magic是字符串,而不是整数。 + // magic = 9; // 不工作,因为magic是字符串,而不是整数。 // 泛型 // - var phonebook = new Dictionary<string, string>() { + var phonebook = new Dictionary<string, string>() { {"Sarah", "212 555 5555"} // 在电话簿中加入新条目 }; - // 调用上面定义为泛型的SETDEFAULT - Console.WriteLine(SetDefault<string,string>(phonebook, "Shaun", "No Phone")); // 没有电话 - // 你不用指定TKey、TValue,因为它们会被隐式地推导出来 + // 调用上面定义为泛型的 SETDEFAULT + Console.WriteLine(SetDefault<string, string>(phonebook, "Shaun", "No Phone")); // No Phone + // 你不用指定 TKey、TValue 的类型 + // 因为它们会被隐式地推导出来 Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 // lambda表达式 - 允许你用一行代码搞定函数 Func<int, int> square = (x) => x * x; // 最后一项为返回值 Console.WriteLine(square(3)); // 9 - // 可抛弃的资源管理 - 让你很容易地处理未管理的资源 - // 大多数访问未管理资源 (文件操作符、设备上下文, etc.)的对象 - // 都实现了IDisposable接口。 - // using语句会为你清理IDisposable对象。 + // 错误处理 - 应对不确定的世界 + try + { + var funBike = PennyFarthing.CreateWithGears(6); + + // 将不再执行,因为 CreateWithGears 抛出异常 + string some = ""; + if (true) some = null; + some.ToLower(); // 抛出 NullReferenceException + } + catch (NotSupportedException) + { + Console.WriteLine("Not so much fun now!"); + } + catch (Exception ex) // 捕获所有其他异常 + { + throw new ApplicationException("It hit the fan", ex); + // throw; // 重新抛出异常并保留调用堆栈 + } + // catch { } // 捕获所有没有捕获的异常 + finally + { + // 在 try 或 catch 之后执行 + } + + // 可抛弃的资源管理 - 让你很容易地处理未托管的资源 + // 大多数访问未托管资源 (文件句柄、设备上下文, etc.) 的对象 + // 都实现了 IDisposable 接口。 + // using语句会为你清理 IDisposable 对象 using (StreamWriter writer = new StreamWriter("log.txt")) { writer.WriteLine("这里没有什么可疑的东西"); @@ -450,29 +569,23 @@ on a new line! ""Wow!"", the masses cried"; } // 并行框架 - // 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>(); - - // 为每个请求新开一个线程 - // 在运行下一步前合并结果 - Parallel.ForEach(websites, - new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads - website => - { - // Do something that takes a long time on the file - using (var r = WebRequest.Create(new Uri(website)).GetResponse()) + // https://learn.microsoft.com/zh-cn/dotnet/standard/parallel-programming/data-parallelism-task-parallel-library + + var words = new List<string> {"dog", "cat", "horse", "pony"}; + + Parallel.ForEach(words, + new ParallelOptions() { MaxDegreeOfParallelism = 4 }, + word => { - responses[website] = r.ContentType; + Console.WriteLine(word); } - }); + ); - // 直到所有的请求完成后才会运行下面的代码 - foreach (var key in responses.Keys) - Console.WriteLine("{0}:{1}", key, responses[key]); + // 运行它会产生不同的输出 + // 因为每个线程在不同的时间完成 + // 一些可能的输出是: + // cat dog horse pony + // dog horse pony cat // 动态对象(配合其他语言使用很方便) dynamic student = new ExpandoObject(); @@ -486,10 +599,10 @@ on a new line! ""Wow!"", the masses cried"; // IQUERYABLE<T> - 几乎所有的集合都实现了它, // 带给你 Map / Filter / Reduce 风格的方法 var bikes = new List<Bicycle>(); - bikes.Sort(); // Sorts the array + bikes.Sort(); // 排序 array bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // 根据车轮数排序 var result = bikes - .Where(b => b.Wheels > 3) // 筛选 - 可以连锁使用 (返回IQueryable) + .Where(b => b.Wheels > 3) // 筛选 - 可以连锁使用 (返回 IQueryable) .Where(b => b.IsBroken && b.HasTassles) .Select(b => b.ToString()); // Map - 这里我们使用了select,所以结果是IQueryable<string> @@ -502,19 +615,19 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine(bikeSummary.Name); // ASPARALLEL - // 邪恶的特性 —— 组合了linq和并行操作 + // 这就是事情开始棘手的地方 —— 组合了 linq 和并行操作 var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); // 以上代码会并发地运行。会自动新开线程,分别计算结果。 // 适用于多核、大数据量的场景。 - // LINQ - 将IQueryable<T>映射到存储,延缓执行 + // LINQ - 映射一组 IQueryable<T> 对象,并延迟执行 // 例如 LinqToSql 映射数据库, LinqToXml 映射XML文档 var db = new BikeRespository(); - // 执行被延迟了,这对于查询数据库来说很好 + // 执行被延迟了,这对于查询数据库来说非常好 var filter = db.Bikes.Where(b => b.HasTassles); // 不运行查询 if (42 > 6) // 你可以不断地增加筛选,包括有条件的筛选,例如用于“高级搜索”功能 - filter = filter.Where(b => b.IsBroken); // 不运行查询 + filter = filter.Where(b => b.IsBroken); // 不运行查询 var query = filter .OrderBy(b => b.Wheels) @@ -541,15 +654,64 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine(obj.ToString()); } } + + + // 委托 和 事件 + public class DelegateTest + { + public static int count = 0; + public static int Increment() + { + // 增加 count 然后返回它 + return ++count; + } + + // 委托是一个方法的引用. + // 要引用 Increment 方法, + // 首先声明一个具有相同签名的委托, + // i.e. 不带参数并返回 int + public delegate int IncrementDelegate(); + + // 事件也可用于触发委托 + // 使用委托类型创建事件 + public static event IncrementDelegate MyEvent; + + static void Main(string[] args) + { + // 通过实例化委托来引用 Increment 方法 + // 并将方法本身作为参数传递 + IncrementDelegate inc = new IncrementDelegate(Increment); + Console.WriteLine(inc()); // => 1 + + // 委托可以用 + 运算符组合 + IncrementDelegate composedInc = inc; + composedInc += inc; + composedInc += inc; + + // composedInc 将执行 Increment 3 次 + Console.WriteLine(composedInc()); // => 4 + + + // 为事件订阅与委托 + MyEvent += new IncrementDelegate(Increment); + MyEvent += new IncrementDelegate(Increment); + + // 触发事件 + // ie. 运行这个事件所有的委托订阅 + Console.WriteLine(MyEvent()); // => 6 + } + } + + // 声明类的语法: // <public/private/protected/internal> class <类名>{ - // //数据字段, 构造器, 内部函数. - / // 在Java中函数被称为方法。 + // // 数据字段, 构造器, 内部函数 + // // 在Java中函数被称为方法 // } public class Bicycle { - // 自行车的字段、变量 + // 自行车的字段/变量 public int Cadence // Public: 任何地方都可以访问 { get // get - 定义获取属性的方法 @@ -558,30 +720,35 @@ on a new line! ""Wow!"", the masses cried"; } set // set - 定义设置属性的方法 { - _cadence = value; // value是被传递给setter的值 + _cadence = value; // value 是被传递给 setter 的值 } } private int _cadence; - protected virtual int Gear // 类和子类可以访问 + protected virtual int Gear // Protected: 类和子类可以访问 { get; // 创建一个自动属性,无需成员字段 set; } - internal int Wheels // Internal:在同一程序集内可以访问 + internal int Wheels // Internal: 在同一程序集内可以访问 { get; - private set; // 可以给get/set方法添加修饰符 + private set; // 可以给 get/set 方法添加修饰符 } - int _speed; // 默认为private: 只可以在这个类内访问,你也可以使用`private`关键词 + int _speed; // 类中的任何内容默认为 private: 只可以在这个类内访问 + // 你也可以使用 `private` 关键词显式指定 public string Name { get; set; } - // enum类型包含一组常量 + // 当您想要一个仅返回表达式结果的只读属性时, + // 属性还具有特殊的语法 + public string LongName => Name + " " + _speed + " speed"; + + // enum 枚举是一种值类型,由一组命名常量组成 // 它将名称映射到值(除非特别说明,是一个整型) - // enmu元素的类型可以是byte、sbyte、short、ushort、int、uint、long、ulong。 - // enum不能包含相同的值。 + // enmu 元素的类型可以是 byte、sbyte、short、ushort、int、uint、long、ulong + // enum 不能包含相同的值 public enum BikeBrand { AIST, @@ -589,13 +756,32 @@ on a new line! ""Wow!"", the masses cried"; Electra = 42, //你可以显式地赋值 Gitane // 43 } - // 我们在Bicycle类中定义的这个类型,所以它是一个内嵌类型。 - // 这个类以外的代码应当使用`Bicycle.Brand`来引用。 + // 我们在 Bicycle 类中定义的这个类型,所以它是一个内嵌类型 + // 这个类以外的代码应当使用 `Bicycle.Brand` 来引用 + + public BikeBrand Brand; // 声明一个 enum 类型之后,我们可以声明这个类型的字段 + + // 使用 FlagsAttribute 定义枚举,表示有多个值可以被匹配 + // 任何从 Attribute 派生的类都可以用来修饰类型、方法、参数等 + // 位运算符 & 和 | 可用于 和/或 操作 + + [Flags] + public enum BikeAccessories + { + None = 0, + Bell = 1, + MudGuards = 2, // 需要手动设定值! + Racks = 4, + Lights = 8, + FullPackage = Bell | MudGuards | Racks | Lights + } - public BikeBrand Brand; // 声明一个enum类型之后,我们可以声明这个类型的字段 + // 用法: aBike.Accessories.HasFlag(Bicycle.BikeAccessories.Bell) + // 在 .NET 4 之前: (aBike.Accessories & Bicycle.BikeAccessories.Bell) == Bicycle.BikeAccessories.Bell + public BikeAccessories Accessories { get; set; } - // 静态方法的类型为自身,不属于特定的对象。 - // 你无需引用对象就可以访问他们。 + // 静态方法属于类型自身,不属于特定的对象 + // 你无需通过对象就可以访问他们 // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); static public int BicyclesCreated = 0; @@ -607,7 +793,7 @@ on a new line! ""Wow!"", the masses cried"; // 下面是一个默认的构造器 public Bicycle() { - this.Gear = 1; // 你可以使用关键词this访问对象的成员 + this.Gear = 1; // 你可以使用关键词 this 访问对象的成员 Cadence = 50; // 不过你并不总是需要它 _speed = 5; Name = "Bontrager"; @@ -618,7 +804,7 @@ on a new line! ""Wow!"", the masses cried"; // 另一个构造器的例子(包含参数) public Bicycle(int startCadence, int startSpeed, int startGear, string name, bool hasCardsInSpokes, BikeBrand brand) - : base() // 首先调用base + : base() // 显式调用基类的无参构造方法 { Gear = startGear; Cadence = startCadence; @@ -637,8 +823,9 @@ on a new line! ""Wow!"", the masses cried"; // 函数语法 // <public/private/protected> <返回值> <函数名称>(<参数>) - // 类可以为字段实现 getters 和 setters 方法 for their fields - // 或者可以实现属性(C#推荐使用这个) + // 类可以为其字段实现 getters 和 setters 方法 + // 或者可以使用属性封装字段(C#推荐使用这个) + // 方法的参数可以有默认值 // 在有默认值的情况下,调用方法的时候可以省略相应的参数 public void SpeedUp(int increment = 1) @@ -652,8 +839,8 @@ on a new line! ""Wow!"", the masses cried"; } // 属性可以访问和设置值 - // 当只需要访问数据的时候,考虑使用属性。 - // 属性可以定义get和set,或者是同时定义两者 + // 当只需要外部访问数据的时候,考虑使用属性。 + // 属性可以定义 get 和 set,或者是同时定义两者 private bool _hasTassles; // private variable public bool HasTassles // public accessor { @@ -663,7 +850,7 @@ on a new line! ""Wow!"", the masses cried"; // 你可以在一行之内定义自动属性 // 这个语法会自动创建后备字段 - // 你可以给getter或setter设置访问修饰符 + // 你可以给 getter 或 setter 设置访问修饰符 // 以便限制它们的访问 public bool IsBroken { get; private set; } @@ -671,12 +858,29 @@ on a new line! ""Wow!"", the masses cried"; public int FrameSize { get; - // 你可以给get或set指定访问修饰符 - // 以下代码意味着只有Bicycle类可以调用Framesize的set + // 你可以给 get 或 set 指定访问修饰符 + // 以下代码意味着只有 Bicycle 类可以调用 Framesize 的 set private set; } - //显示对象属性的方法 + // 还可以在对象上定义自定义索引器 + // 尽管这在本例中并不完全有用, you + // 你可以使用 bicycle[0] 返回 "chris" 来获得第一项 + // 或者 bicycle[1] = "lisa" 来设定值 + private string[] passengers = { "chris", "phil", "darren", "regina" }; + + public string this[int i] + { + get { + return passengers[i]; + } + + set { + passengers[i] = value; + } + } + + // 显示对象属性的方法 public virtual string Info() { return "Gear: " + Gear + @@ -698,7 +902,7 @@ on a new line! ""Wow!"", the masses cried"; } // Bicycle类结束 - // PennyFarthing是Bicycle的一个子类 + // PennyFarthing 是 Bicycle 的一个子类 class PennyFarthing : Bicycle { // (Penny Farthings是一种前轮很大的自行车。没有齿轮。) @@ -717,10 +921,17 @@ on a new line! ""Wow!"", the masses cried"; } set { - throw new ArgumentException("你不可能在PennyFarthing上切换齿轮"); + throw new ArgumentException("你不可能在 PennyFarthing 上切换齿轮"); } } + public static PennyFarthing CreateWithGears(int gears) + { + var penny = new PennyFarthing(1, 1); + penny.Gear = gears; // 你不能这样做! + return penny; + } + public override string Info() { string result = "PennyFarthing bicycle "; @@ -732,7 +943,7 @@ on a new line! ""Wow!"", the masses cried"; // 接口只包含成员的签名,而没有实现。 interface IJumpable { - void Jump(int meters); // 所有接口成员是隐式地公开的 + void Jump(int meters); // 所有接口成员是隐式地公开的 public } interface IBreakable @@ -741,6 +952,8 @@ on a new line! ""Wow!"", the masses cried"; } // 类只能继承一个类,但是可以实现任意数量的接口 + // 但是基类名称必须是列表中的第一个,所有接口都在后面 + class MountainBike : Bicycle, IJumpable, IBreakable { int damage = 0; @@ -759,41 +972,374 @@ on a new line! ""Wow!"", the masses cried"; } /// <summary> - /// 连接数据库,一个 LinqToSql的示例。 + /// 连接数据库,一个 LinqToSql 的示例。 /// EntityFramework Code First 很棒 (类似 Ruby的 ActiveRecord, 不过是双向的) - /// http://msdn.microsoft.com/en-us/data/jj193542.aspx + /// https://learn.microsoft.com/zh-cn/ef/ef6/modeling/code-first/workflows/new-database /// </summary> - public class BikeRespository : DbSet + public class BikeRepository : DbContext { - public BikeRespository() + public BikeRepository() : base() { } public DbSet<Bicycle> Bikes { get; set; } } + + // 一个类可以通过 partial 关键字分别写在多个 .cs 文件中 + // A1.cs + public partial class A + { + public static void A1() + { + Console.WriteLine("Method A1 in class A"); + } + } + + // A2.cs + public partial class A + { + public static void A2() + { + Console.WriteLine("Method A2 in class A"); + } + } + + // 使用 partial 类 "A" + public class Program + { + static void Main() + { + A.A1(); + A.A2(); + } + } + + // 通过在字符串前加上 $ 前缀来进行字符串插值 + // 并用 { 大括号 } 包裹要插值的表达式 + // 您还可以将插值字符串和逐字字符串与 $@ 组合起来 + public class Rectangle + { + public int Length { get; set; } + public int Width { get; set; } + } + + class Program + { + static void Main(string[] args) + { + Rectangle rect = new Rectangle { Length = 5, Width = 3 }; + Console.WriteLine($"The length is {rect.Length} and the width is {rect.Width}"); + + string username = "User"; + Console.WriteLine($@"C:\Users\{username}\Desktop"); + } + } + + // C# 6 新特性 + class GlassBall : IJumpable, IBreakable + { + // 自动属性设置初始值 + public int Damage { get; private set; } = 0; + + // 为仅有 getter 的自动属性设定初始值 + public string Name { get; } = "Glass ball"; + + // 在构造函数中初始化的仅有 getter 的自动属性 + public string GenieName { get; } + + public GlassBall(string genieName = null) + { + GenieName = genieName; + } + + public void Jump(int meters) + { + if (meters < 0) + // 新的 nameof() 表达式; 编译器将检查标识符是否存在 + // nameof(x) == "x" + // 预防 例如 参数名称已更改但错误消息中未更新 + throw new ArgumentException("Cannot jump negative amount!", nameof(meters)); + + Damage += meters; + } + + // 表达式主体 expression-bodied 属性 ... + public bool Broken + => Damage > 100; + + // ... 刚发 + public override string ToString() + // 插值字符串 + => $"{Name}. Damage taken: {Damage}"; + + public string SummonGenie() + // Null 条件运算符 + // x?.y 如果 x 为 null 将立即返回 null; y 将不会求值 + => GenieName?.ToUpper(); + } + + static class MagicService + { + private static bool LogException(Exception ex) + { + // 记录某处的异常 + return false; + } + + public static bool CastSpell(string spell) + { + try + { + // 假设我们在这里调用 API + throw new MagicServiceException("Spell failed", 42); + + // Spell succeeded + return true; + } + // 仅当 Code 为 42(Spell failed)时才捕获 + catch(MagicServiceException ex) when (ex.Code == 42) + { + // Spell failed + return false; + } + // 其他异常,或 MagicServiceException 的 Code 不是 42 + catch(Exception ex) when (LogException(ex)) + { + // 永远不会执行到这块代码 + // 堆栈未展开 + } + return false; + // 请注意,捕获 MagicServiceException + // 并在 Code 不是 42 或 117 时重新抛出是不同的 + // 因为最终的 catch-all 块将不会捕获重新抛出的异常 + } + } + + public class MagicServiceException : Exception + { + public int Code { get; } + + public MagicServiceException(string message, int code) : base(message) + { + Code = code; + } + } + + public static class PragmaWarning { + // 过时的属性 + [Obsolete("Use NewMethod instead", false)] + public static void ObsoleteMethod() + { + // obsolete code + } + + public static void NewMethod() + { + // new code + } + + public static void Main() + { + ObsoleteMethod(); // CS0618: 'ObsoleteMethod 已过时:使用 NewMethod 代替' +#pragma warning disable CS0618 + ObsoleteMethod(); // no warning +#pragma warning restore CS0618 + ObsoleteMethod(); // CS0618: 'ObsoleteMethod 已过时:使用 NewMethod 代替' + } + } } // 结束 Namespace + +using System; +// C# 6, 静态引用 +using static System.Math; + +namespace Learning.More.CSharp +{ + class StaticUsing + { + static void Main() + { + // 不使用静态引用时.. + Console.WriteLine("The square root of 4 is {}.", Math.Sqrt(4)); + // 使用时 + Console.WriteLine("The square root of 4 is {}.", Sqrt(4)); + } + } +} + +// C# 7 新特性 +// 使用 Nuget 安装 Microsoft.Net.Compilers 最新版 +// 使用 Nuget 安装 System.ValueTuple 最新版 +using System; +namespace Csharp7 +{ + // 元组 TUPLES, 析构 DECONSTRUCTION 和 弃元 DISCARDS + class TuplesTest + { + public (string, string) GetName() + { + // 元组中的字段默认命名为 Item1、Item2... + var names1 = ("Peter", "Parker"); + Console.WriteLine(names1.Item2); // => Parker + + // 字段可以显式命名 + // 第 1 种声明 + (string FirstName, string LastName) names2 = ("Peter", "Parker"); + + // 第 2 种声明 + var names3 = (First:"Peter", Last:"Parker"); + + Console.WriteLine(names2.FirstName); // => Peter + Console.WriteLine(names3.Last); // => Parker + + return names3; + } + + public string GetLastName() { + var fullName = GetName(); + + // 元组可以被析构 + (string firstName, string lastName) = fullName; + + // 析构获得的字段可以使用 弃元 _ 丢弃 + var (_, last) = fullName; + return last; + } + + // 通过指定析构方法, + // 可以以相同的方式解构任何类型 + public int randomNumber = 4; + public int anotherRandomNumber = 10; + + public void Deconstruct(out int randomNumber, out int anotherRandomNumber) + { + randomNumber = this.randomNumber; + anotherRandomNumber = this.anotherRandomNumber; + } + + static void Main(string[] args) + { + var tt = new TuplesTest(); + (int num1, int num2) = tt; + Console.WriteLine($"num1: {num1}, num2: {num2}"); // => num1: 4, num2: 10 + + Console.WriteLine(tt.GetLastName()); + } + } + + // 模式匹配 + class PatternMatchingTest + { + public static (string, int)? CreateLogMessage(object data) + { + switch(data) + { + // 使用 when 进行附加过滤 + case System.Net.Http.HttpRequestException h when h.Message.Contains("404"): + return (h.Message, 404); + case System.Net.Http.HttpRequestException h when h.Message.Contains("400"): + return (h.Message, 400); + case Exception e: + return (e.Message, 500); + case string s: + return (s, s.Contains("Error") ? 500 : 200); + case null: + return null; + default: + return (data.ToString(), 500); + } + } + } + + // Reference 变量 / ref 局部变量 + // 允许返回对象的引用而不仅仅是其值 + class RefLocalsTest + { + // 返回值前标明 ref + public static ref string FindItem(string[] arr, string el) + { + for(int i=0; i<arr.Length; i++) + { + if(arr[i] == el) { + // 返回引用 + return ref arr[i]; + } + } + throw new Exception("Item not found"); + } + + public static void SomeMethod() + { + string[] arr = {"this", "is", "an", "array"}; + + // 要在所有地方使用 ref + ref string item = ref FindItem(arr, "array"); + item = "apple"; + Console.WriteLine(arr[3]); // => apple + } + } + + // 本地函数 LOCAL FUNCTIONS + class LocalFunctionTest + { + private static int _id = 0; + public int id; + public LocalFunctionTest() + { + id = generateId(); + + // 这个本地函数只能在此作用域中被访问 + int generateId() + { + return _id++; + } + } + + public static void AnotherMethod() + { + var lf1 = new LocalFunctionTest(); + var lf2 = new LocalFunctionTest(); + Console.WriteLine($"{lf1.id}, {lf2.id}"); // => 0, 1 + + int id = generateId(); + // error CS0103: 当前上下文中不存在名称“generateId” + } + } +} + ``` ## 没有涉及到的主题 +✨ 新的, 👍 旧的, 🎈 长期支持的, 🔥 跨平台的, 🎁 只支持Windows的 + + * 特性 Attributes + + * 异步编程 + + * Web 开发 + * ASP.NET Core ✨ + + * 桌面应用开发 Development + * Windows Presentation Foundation (WPF) 👍 🎈 🎁 + * Universal Windows Platform (UWP) ✨ 🎁 + * Uno Platform 🔥 ✨ + * WinForms 👍 🎈 🎁 + * Avalonia 🔥 ✨ + * WinUI ✨ 🎁 - * Flags - * Attributes - * 静态属性 - * Exceptions, Abstraction - * ASP.NET (Web Forms/MVC/WebMatrix) - * Winforms - * Windows Presentation Foundation (WPF) + * 跨平台开发 + * Xamarin.Forms 👍 + * MAUI ✨ ## 扩展阅读 + * [C# language reference](https://docs.microsoft.com/dotnet/csharp/language-reference/) + * [Learn .NET](https://dotnet.microsoft.com/learn) + * [C# Coding Conventions](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions) * [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/tutorials) - * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) + * [Programming C# 5.0](http://shop.oreilly.com/product/0636920024064.do) + * [LINQ Pocket Reference](http://shop.oreilly.com/product/9780596519254.do) * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) - * [C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) + * [freeCodeCamp - C# Tutorial for Beginners](https://www.youtube.com/watch?v=GhQdlIFylQ8) 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/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index 8afacf2a..a2b71761 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -392,15 +392,15 @@ func requestServer() { ## 更进一步 -关于Go的一切你都可以在[Go官方网站](http://golang.org/)找到。 +关于Go的一切你都可以在[Go官方网站](https://go.dev/)找到。 在那里你可以获得教程参考,在线试用,和更多的资料。 -在简单的尝试过后,在[官方文档](https://golang.org/doc/)那里你会得到你所需要的所有资料、关于编写代码的规范、库和命令行工具的文档与Go的版本历史。 +在简单的尝试过后,在[官方文档](https://go.dev/doc/)那里你会得到你所需要的所有资料、关于编写代码的规范、库和命令行工具的文档与Go的版本历史。 强烈推荐阅读语言定义部分,很简单而且很简洁!(赶时髦!) -你还可以前往[Go在线体验中心](https://play.golang.org/p/tnWMjr16Mm)进,在浏览器里修改并运行这些代码,一定要试一试哦!你可以将[https://play.golang.org](https://play.golang.org)当作一个[REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop),在那里体验语言特性或运行自己的代码,连环境都不用配! +你还可以前往[Go在线体验中心](https://go.dev/play/p/tnWMjr16Mm)进,在浏览器里修改并运行这些代码,一定要试一试哦!你可以将[https://go.dev/play/](https://go.dev/play/)当作一个[REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop),在那里体验语言特性或运行自己的代码,连环境都不用配! -学习Go还要阅读Go[标准库的源代码](http://golang.org/src/),全部文档化了,可读性非常好,可以学到go,go style和go idioms。在[文档](http://golang.org/pkg/)中点击函数名,源代码就出来了! +学习Go还要阅读Go[标准库的源代码](https://go.dev/src/),全部文档化了,可读性非常好,可以学到go,go style和go idioms。在[文档](https://go.dev/pkg/)中点击函数名,源代码就出来了! [Go by example](https://gobyexample.com/)也是一个学习的好地方。 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">```ruby +````md +```ruby def foobar - puts "Hello world!" + puts "Hello world!" end -```</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/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/ |