From 283bac48db7ba2a12f1d7ee134ddaa9c38ef0939 Mon Sep 17 00:00:00 2001 From: Serban Constantin Date: Wed, 30 Sep 2015 20:02:33 +0300 Subject: add untranslated file to ro-ro folder Add the original untranslated file to the ro-ro folder and rename it to respect the correct naming structure. --- ro-ro/json-ro.html.markdown | 58 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 ro-ro/json-ro.html.markdown diff --git a/ro-ro/json-ro.html.markdown b/ro-ro/json-ro.html.markdown new file mode 100644 index 00000000..f57b82b8 --- /dev/null +++ b/ro-ro/json-ro.html.markdown @@ -0,0 +1,58 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +--- + +As JSON is an extremely simple data-interchange format, this is most likely going +to be the simplest Learn X in Y Minutes ever. + +JSON in its purest form has no actual comments, but most parsers will accept +C-style (`//`, `/* */`) comments. For the purposes of this, however, everything is +going to be 100% valid JSON. Luckily, it kind of speaks for itself. + +```json +{ + "key": "value", + + "keys": "must always be enclosed in double quotes", + "numbers": 0, + "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", + "has bools?": true, + "nothingness": null, + + "big number": 1.2e+100, + + "objects": { + "comment": "Most of your structure will come from objects.", + + "array": [0, 1, 2, 3, "Arrays can have anything in them.", 5], + + "another object": { + "comment": "These things can be nested, very useful." + } + }, + + "silliness": [ + { + "sources of potassium": ["bananas"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternative style": { + "comment": "check this out!" + , "comma position": "doesn't matter - as long as its before the value, then its valid" + , "another comment": "how nice" + }, + + "that was short": "And, you're done. You now know everything JSON has to offer." +} +``` -- cgit v1.2.3 From 52c567f664d3e2b79b094aa8e25a41685e34e57b Mon Sep 17 00:00:00 2001 From: Serban Constantin Date: Wed, 30 Sep 2015 20:06:35 +0300 Subject: update header --- ro-ro/json-ro.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ro-ro/json-ro.html.markdown b/ro-ro/json-ro.html.markdown index f57b82b8..7042dde7 100644 --- a/ro-ro/json-ro.html.markdown +++ b/ro-ro/json-ro.html.markdown @@ -1,9 +1,12 @@ --- language: json -filename: learnjson.json +filename: learnjson-ro.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Serban Constantin", "https://github.com/fuzzmz"] +lang: ro-ro --- As JSON is an extremely simple data-interchange format, this is most likely going -- cgit v1.2.3 From d5f62046c37de1b18bd2d5771314e1cc7b9be06a Mon Sep 17 00:00:00 2001 From: Serban Constantin Date: Wed, 30 Sep 2015 20:19:11 +0300 Subject: translate to romanian --- ro-ro/json-ro.html.markdown | 48 ++++++++++++++++++++++----------------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/ro-ro/json-ro.html.markdown b/ro-ro/json-ro.html.markdown index 7042dde7..e897059c 100644 --- a/ro-ro/json-ro.html.markdown +++ b/ro-ro/json-ro.html.markdown @@ -9,38 +9,38 @@ translators: lang: ro-ro --- -As JSON is an extremely simple data-interchange format, this is most likely going -to be the simplest Learn X in Y Minutes ever. +Deoarece JSON este un fromat foarte simplu de schimb de date acesta va fi +probabil cel mai simplu Invata X in Y minute. -JSON in its purest form has no actual comments, but most parsers will accept -C-style (`//`, `/* */`) comments. For the purposes of this, however, everything is -going to be 100% valid JSON. Luckily, it kind of speaks for itself. +JSON in forma cea mai pura nu contine comentarii insa majoritatea parserelor +vor accepta comentarii in stil C (`//`, `/* */`). Pentru acest caz insa totul +va fi JSON 100% valid. Din fericire codul vorbeste de la sine. ```json { - "key": "value", + "cheie": "valoare", - "keys": "must always be enclosed in double quotes", - "numbers": 0, - "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", - "has bools?": true, - "nothingness": null, + "chei": "trebuie mereu inconjurate de ghilimele", + "numere": 0, + "stringuri": "Bunã. Tot setul unicode este permis, chiar si \"escaping\".", + "are booleane?": true, + "nimic": null, - "big number": 1.2e+100, + "numere mari": 1.2e+100, - "objects": { - "comment": "Most of your structure will come from objects.", + "obiecte": { + "comentariu": "Majoritatea structurii va veni din obiecte.", - "array": [0, 1, 2, 3, "Arrays can have anything in them.", 5], + "vectori": [0, 1, 2, 3, "Vectorii pot avea orice in ei.", 5], - "another object": { - "comment": "These things can be nested, very useful." + "alt obiect": { + "comentariu": "Lucrurile pot fi subordonate. Foarte util." } }, - "silliness": [ + "glumite": [ { - "sources of potassium": ["bananas"] + "surse de potasiu": ["banane"] }, [ [1, 0, 0, 0], @@ -50,12 +50,12 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself. ] ], - "alternative style": { - "comment": "check this out!" - , "comma position": "doesn't matter - as long as its before the value, then its valid" - , "another comment": "how nice" + "stil alternativ": { + "comentariu": "ia uite la asta!" + , "pozitia virgulei": "nu conteaza - daca e inaintea valorii atunci e valida" + , "alt comentariu": "ce dragut" }, - "that was short": "And, you're done. You now know everything JSON has to offer." + "a fost scurt": "Am terminat. Acum stii tot ce are JSON de oferit." } ``` -- cgit v1.2.3 From 556758b3ae16c2441a96edb85e72b3c170b53d7a Mon Sep 17 00:00:00 2001 From: Serban Constantin Date: Wed, 30 Sep 2015 20:24:36 +0300 Subject: add untranslated file to ro-ro folder Add the original untranslated file to the ro-ro folder and rename it to respect the correct naming structure. --- ro-ro/xml-ro.html.markdown | 126 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 ro-ro/xml-ro.html.markdown diff --git a/ro-ro/xml-ro.html.markdown b/ro-ro/xml-ro.html.markdown new file mode 100644 index 00000000..fce1a3a4 --- /dev/null +++ b/ro-ro/xml-ro.html.markdown @@ -0,0 +1,126 @@ +--- +language: xml +filename: learnxml.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +--- + +XML is a markup language designed to store and transport data. + +Unlike HTML, XML does not specify how to display or to format data, just carry it. + +* XML Syntax + +```xml + + + + + + Everyday Italian + Giada De Laurentiis + 2005 + 30.00 + + + Harry Potter + J K. Rowling + 2005 + 29.99 + + + Learning XML + Erik T. Ray + 2003 + 39.95 + + + + + + + + + + +computer.gif + + +``` + +* Well-Formated Document x Validation + +A XML document is well-formated if it is syntactically correct. +However, it is possible to inject more constraints in the document, +using document definitions, such as DTD and XML Schema. + +A XML document which follows a document definition is called valid, +regarding that document. + +With this tool, you can check the XML data outside the application logic. + +```xml + + + + + + + + Everyday Italian + 30.00 + + + + + + + + + + +]> + + + + + + + + + + + + + +]> + + + + Everyday Italian + 30.00 + + +``` -- cgit v1.2.3 From 1b799a72998e36f38086db7facc945ce63f1f66a Mon Sep 17 00:00:00 2001 From: Serban Constantin Date: Wed, 30 Sep 2015 20:26:20 +0300 Subject: update header --- ro-ro/xml-ro.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ro-ro/xml-ro.html.markdown b/ro-ro/xml-ro.html.markdown index fce1a3a4..578b430e 100644 --- a/ro-ro/xml-ro.html.markdown +++ b/ro-ro/xml-ro.html.markdown @@ -1,8 +1,11 @@ --- language: xml -filename: learnxml.xml +filename: learnxml-ro.xml contributors: - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Serban Constantin", "https://github.com/fuzzmz"] +lang: ro-ro --- XML is a markup language designed to store and transport data. -- cgit v1.2.3 From 66f7710f6f6af18431b99ab46c40338b362af58a Mon Sep 17 00:00:00 2001 From: Serban Constantin Date: Wed, 30 Sep 2015 20:53:45 +0300 Subject: add translated file --- ro-ro/xml-ro.html.markdown | 166 +++++++++++++++++++++++---------------------- 1 file changed, 85 insertions(+), 81 deletions(-) diff --git a/ro-ro/xml-ro.html.markdown b/ro-ro/xml-ro.html.markdown index 578b430e..269010c2 100644 --- a/ro-ro/xml-ro.html.markdown +++ b/ro-ro/xml-ro.html.markdown @@ -8,122 +8,126 @@ translators: lang: ro-ro --- -XML is a markup language designed to store and transport data. +XML este un limbaj de markup ce are ca scop stocarea si transportul de date. -Unlike HTML, XML does not specify how to display or to format data, just carry it. +Spre deosebire de HTML, XML nu specifica cum sa fie afisata sau formatata +informatia, ci doar o transporta. -* XML Syntax +* Sintaxa XML ```xml - + - - - Everyday Italian - Giada De Laurentiis - 2005 - 30.00 - - - Harry Potter - J K. Rowling - 2005 - 29.99 - - - Learning XML - Erik T. Ray - 2003 - 39.95 - - - - - - - + XML foloseste o structura arborescenta. Deasupra, nodul de baza este + 'librarie', care are trei noduri copil, toate 'carti'. Acele noduri au la + randul lor noduri copii si asa mai departe... + + Nodurile sunt create folosind taguri deschise/inchise, iar copii sunt doar + noduri intre tagurile de deschis si inchis.--> + + + - + computer.gif ``` -* Well-Formated Document x Validation +* Document bine formatat x Validare -A XML document is well-formated if it is syntactically correct. -However, it is possible to inject more constraints in the document, -using document definitions, such as DTD and XML Schema. +Un document XML este bine formatat daca este corect sintactic. +Cu toate astea este posibil sa injectam mai multe constrangeri in document +folosind definitii precum DTD si XML Schema. -A XML document which follows a document definition is called valid, -regarding that document. +Un document XML ce foloseste o definitie de document este numit valid in +contextul documentului. -With this tool, you can check the XML data outside the application logic. +Cu acest tool poti verifica datele XML in afara codului aplicatiei. ```xml - + - - - - Everyday Italian - 30.00 - - + + + + Everyday Italian + 30.00 + + - + - - - - + + + + + ]> - + - + - - - - + + + + + ]> - - - Everyday Italian - 30.00 - - + + + Everyday Italian + 30.00 + + ``` -- cgit v1.2.3 From 5bed6d5a79834d92984a60699ef9f5792b37377c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20S=C3=BC=C3=9F?= Date: Thu, 1 Oct 2015 22:32:49 +0200 Subject: Added D Translation to German --- de-de/d-de.html.markdown | 248 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 248 insertions(+) create mode 100644 de-de/d-de.html.markdown diff --git a/de-de/d-de.html.markdown b/de-de/d-de.html.markdown new file mode 100644 index 00000000..305c9167 --- /dev/null +++ b/de-de/d-de.html.markdown @@ -0,0 +1,248 @@ +--- +language: D +filename: learnd.d +contributors: + - ["Nick Papanastasiou", "Dominik Süß"] +lang: de +--- + +```c +// Es war klar dass das kommt... +module hello; + +import std.stdio; + +// argumente sind optional +void main(string[] args) { + writeln("Hello, World!"); +} +``` + +Wenn du so wie ich bist und viel zeit im Internet verbringst stehen die Chancen gut +das du schonmal über [D](http://dlang.org/) gehört hast. +Die D-Sprache ist eine moderne, überall einsetzbare programmiersprache die von Low bis +High Level verwendet werden kann und dabei viele stile anbietet. + +D wird aktiv von Walter Bright und Andrei Alexandrescu entwickelt, zwei super schlaue, +richtig coole leute. Da das jetzt alles aus dem weg ist - auf zu den Beispielen! + +```c +import std.stdio; + +void main() { + + // Logische Ausdrücke und Schleifen funktionieren wie erwartet + for(int i = 0; i < 10000; i++) { + writeln(i); + } + + auto n = 1; // auto um den typ vom Compiler bestimmen zu lassen + + // Zahlenliterale können _ verwenden für lesbarkeit + while(n < 10_000) { + n += n; + } + + do { + n -= (n / 2); + } while(n > 0); + + // For und while sind ja schön und gut aber D bevorzugt foreach + // .. erstellt eine spanne von zahlen, exklusive dem Ende + foreach(i; 1..1_000_000) { + if(n % 2 == 0) + writeln(i); + } + + foreach_reverse(i; 1..int.max) { + if(n % 2 == 1) { + writeln(i); + } else { + writeln("No!"); + } + } +} +``` + +Neue Typen können mit `struct`, `class`, `union`, und `enum` definiert werden. Structs und unions +werden as-value (koppiert) an methoden übergeben wogegen Klassen als Referenz übergeben werden. +Templates können verwendet werden um alle typen zu parameterisieren. + +```c +// Hier, T ist ein Type-Parameter, Er funktioniert wie Generics in C#/Java/C++ +struct LinkedList(T) { + T data = null; + LinkedList!(T)* next; // Das ! wird verwendet um T zu übergeben. ( in C#/Java/C++) +} + +class BinTree(T) { + T data = null; + + // Wenn es nur einen T parameter gibt können die Klammern um ihn weggelassen werden + BinTree!T left; + BinTree!T right; +} + +enum Day { + Sunday, + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, +} + +// Aliase können verwendet werden um die Entwicklung zu erleichtern + +alias IntList = LinkedList!int; +alias NumTree = BinTree!double; + +// Funktionen können genau so Templates beinhalten + +T max(T)(T a, T b) { + if(a < b) + return b; + + return a; +} + +// Steht ref vor einem Parameter wird sichergestellt das er als Referenz übergeben wird. +// Selbst bei werten wird es immer eine Referenz sein. +void swap(T)(ref T a, ref T b) { + auto temp = a; + + a = b; + b = temp; +} + +// Templates können ebenso werte parameterisieren. +class Matrix(uint m, uint n, T = int) { + T[m] rows; + T[n] columns; +} + +auto mat = new Matrix!(3, 3); // Standardmäßig ist T vom typ Integer + +``` + +Wo wir schon bei Klassen sind - Wie wäre es mit Properties! Eine Property +ist eine Funktion die wie ein Wert agiert. Das gibt uns viel klarere syntax +im stil von `structure.x = 7` was gleichgültig wäre zu `structure.setX(7)` + +```c +// Diese Klasse ist parameterisiert mit T, U + +class MyClass(T, U) { + T _data; + U _other; + +} + +// Ihre Getter und Setter Methoden sehen so aus +class MyClass(T, U) { + T _data; + U _other; + + // Konstruktoren heißen immer `this` + this(T t, U u) { + data = t; + other = u; + } + + // getters + @property T data() { + return _data; + } + + @property U other() { + return _other; + } + + // setters + // @property kann genauso gut am ende der Methodensignatur stehen + void data(T t) @property { + _data = t; + } + + void other(U u) @property { + _other = u; + } +} +// Und so kann man sie dann verwenden + +void main() { + auto mc = MyClass!(int, string); + + mc.data = 7; + mc.other = "seven"; + + writeln(mc.data); + writeln(mc.other); +} +``` + +Mit properties können wir sehr viel logik hinter unseren gettern +und settern hinter einer schönen syntax verstecken + +Other object-oriented goodies at our disposal +Andere Objektorientierte features sind beispielsweise +`interface`s, `abstract class` und `override`. +Vererbung funktioniert in D wie in Java: +Erben von einer Klasse, so viele interfaces wie man will. + +Jetzt haben wir Objektorientierung in D gesehen aber schauen +wir uns noch was anderes an. +D bietet funktionale programmierung mit _first-class functions_ +puren funktionen und unveränderbare daten. +Zusätzlich können viele funktionale Algorithmen wie z.B +map, filter, reduce und friends im `std.algorithm` Modul gefunden werden! + +```c +import std.algorithm : map, filter, reduce; +import std.range : iota; // builds an end-exclusive range + +void main() { + // Wir wollen die summe aller quadratzahlen zwischen + // 1 und 100 ausgeben. Nichts leichter als das! + + // Einfach eine lambda funktion als template parameter übergeben + // Es ist genau so gut möglich eine normale funktion hier zu übergeben + // Lambdas bieten sich hier aber an. + auto num = iota(1, 101).filter!(x => x % 2 == 0) + .map!(y => y ^^ 2) + .reduce!((a, b) => a + b); + + writeln(num); +} +``` + +Ist dir aufgefallen wie wir eine Haskell-Style pipeline gebaut haben +um num zu berechnen? +Das war möglich durch die Uniform Function Call Syntax. +Mit UFCS können wir auswählen ob wir eine Funktion als Methode oder +als freie Funktion aufrufen. Walters artikel dazu findet ihr +[hier.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) +Kurzgesagt kann man Funktionen deren erster parameter vom typ A ist, als +Methode auf A anwenden. + +Parrallel Computing ist eine Tolle sache, findest du nicht auch? + +```c +import std.stdio; +import std.parallelism : parallel; +import std.math : sqrt; + +void main() { + // Wir wollen die Wurzel von jeder Zahl in unserem Array berechnen + // und dabei alle Kerne verwenden die wir zur verfügung haben + auto arr = new double[1_000_000]; + + // Wir verwenden den index und das element als referenz + // und rufen einfach parallel auf! + foreach(i, ref elem; parallel(arr)) { + ref = sqrt(i + 1.0); + } +} + +``` -- cgit v1.2.3 From bc0431b667a5790679792c01e5a12af753fcdf88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20S=C3=BC=C3=9F?= Date: Thu, 1 Oct 2015 22:35:13 +0200 Subject: Fixed File Header --- de-de/d-de.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/de-de/d-de.html.markdown b/de-de/d-de.html.markdown index 305c9167..a7291518 100644 --- a/de-de/d-de.html.markdown +++ b/de-de/d-de.html.markdown @@ -1,8 +1,9 @@ --- language: D -filename: learnd.d +filename: learnd-de.d contributors: - - ["Nick Papanastasiou", "Dominik Süß"] + - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] + - ["Dominik Süß", "www.thesuess.me"] lang: de --- -- cgit v1.2.3 From e19e1a8f27da89487a97146b0c00eb9ffffd0520 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20S=C3=BC=C3=9F?= Date: Thu, 1 Oct 2015 22:35:48 +0200 Subject: Fixed lang --- de-de/d-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/d-de.html.markdown b/de-de/d-de.html.markdown index a7291518..94519b28 100644 --- a/de-de/d-de.html.markdown +++ b/de-de/d-de.html.markdown @@ -4,7 +4,7 @@ filename: learnd-de.d contributors: - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] - ["Dominik Süß", "www.thesuess.me"] -lang: de +lang: de-de --- ```c -- cgit v1.2.3 From 13807790e46d4b75b90d6da17e6c28f4ed9e5a49 Mon Sep 17 00:00:00 2001 From: DaKnOb Date: Fri, 2 Oct 2015 16:42:57 +0300 Subject: Add note about Python Module Order of Import --- python.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index 352f7349..e306dabd 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -569,6 +569,12 @@ math.sqrt == m.sqrt == sqrt # => True import math dir(math) +# If you have a Python script named math.py in the same +# folder as your current script, the file math.py will +# be loaded instead of the built-in Python module. +# This happens because the local folder has priority +# over Python's built-in libraries. + #################################################### ## 7. Advanced -- cgit v1.2.3 From d1a143aed5c7b48888eccb690bf3bf69ae3667bc Mon Sep 17 00:00:00 2001 From: Mathieu De Coster Date: Sat, 3 Oct 2015 12:26:48 +0200 Subject: Add translation to Dutch for json --- nl-nl/json.html.markdown | 61 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 nl-nl/json.html.markdown diff --git a/nl-nl/json.html.markdown b/nl-nl/json.html.markdown new file mode 100644 index 00000000..f025481a --- /dev/null +++ b/nl-nl/json.html.markdown @@ -0,0 +1,61 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Mathieu De Coster", "https://github.com/m-decoster"] +lang: nl-nl +--- + +Aangezien JSON een extreem eenvoudig data-uitwisselingsformaat is, zal dit waarschijnlijk +de meest eenvoudige Learn X in Y Minutes ooit zijn. + +Puur JSON heeft geen commentaar, maar de meeste parsers zullen commentaar in de stijl +van C (`//`, `/* */`) aanvaarden. In dit voorbeeld zal alles 100% correcte JSON zijn. +Gelukkig spreekt het meeste voor zichzelf. + +```json +{ + "key": "value", + + "keys": "moeten altijd tussen dubbele aanhalingstekens staan", + "getallen": 0, + "strings": "Hellø, world. Alle unicode karakters zijn toegelaten, zo ook \"escaping\".", + "heeft json booleans?": true, + "niets": null, + + "groot getal": 1.2e+100, + + "objecten": { + "commentaar": "De meeste structuur wordt gemaakt met objecten.", + + "array": [0, 1, 2, 3, "Arrays kunnen eender wat bevatten.", 5], + + "nog een object": { + "commentaar": "Hoe handig, we kunnen objecten nesten." + } + }, + + "dwaasheid": [ + { + "bronnen van kalium": ["banenen"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternatieve stijl": { + "commentaar": "kijk hier eens naar!" + , "komma locatie": "maakt niet uit - zo lang het voor de value komt, is alles in orde" + , "nog commentaar": "hoe leuk" + }, + + "dat was kort": "Je bent klaar. Je kent nu alles dat JSON kan aanbieden." +} +``` -- cgit v1.2.3 From c2e9577626d60a04409c8568b3fc8ae3d3ef5e96 Mon Sep 17 00:00:00 2001 From: Mathieu De Coster Date: Sat, 3 Oct 2015 12:33:33 +0200 Subject: Fix typo's in nl-nl/json --- nl-nl/json.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-nl/json.html.markdown b/nl-nl/json.html.markdown index f025481a..a82f13c4 100644 --- a/nl-nl/json.html.markdown +++ b/nl-nl/json.html.markdown @@ -9,7 +9,7 @@ translators: lang: nl-nl --- -Aangezien JSON een extreem eenvoudig data-uitwisselingsformaat is, zal dit waarschijnlijk +Aangezien JSON een extreem eenvoudig datauitwisselingsformaat is, zal dit waarschijnlijk de meest eenvoudige Learn X in Y Minutes ooit zijn. Puur JSON heeft geen commentaar, maar de meeste parsers zullen commentaar in de stijl @@ -22,7 +22,7 @@ Gelukkig spreekt het meeste voor zichzelf. "keys": "moeten altijd tussen dubbele aanhalingstekens staan", "getallen": 0, - "strings": "Hellø, world. Alle unicode karakters zijn toegelaten, zo ook \"escaping\".", + "strings": "Hellø, world. Alle Unicode-karakters zijn toegelaten, zo ook \"escaping\".", "heeft json booleans?": true, "niets": null, @@ -40,7 +40,7 @@ Gelukkig spreekt het meeste voor zichzelf. "dwaasheid": [ { - "bronnen van kalium": ["banenen"] + "bronnen van kalium": ["bananen"] }, [ [1, 0, 0, 0], -- cgit v1.2.3 From aae89cbb3f146a2fa001430921870962f7af3597 Mon Sep 17 00:00:00 2001 From: Lari Kovanen Date: Sat, 3 Oct 2015 15:40:54 +0200 Subject: [json/sv] Translated to swedish Translated the english JSON document to swedish. --- sv-se/json-sv.html.markdown | 62 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 sv-se/json-sv.html.markdown diff --git a/sv-se/json-sv.html.markdown b/sv-se/json-sv.html.markdown new file mode 100644 index 00000000..8b76ebad --- /dev/null +++ b/sv-se/json-sv.html.markdown @@ -0,0 +1,62 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Lari Kovanen", "https://github.com/larkov"] +lang: sv-se +--- + +Eftersom JSON är ett extremt lätt data-utbytes format så kommer detta +förmodligen att vara den lättaste "Learn X in Y Minutes" någonsin. + +JSON i dess renaste form har inga kommentarer, men de flesta tolkarna accepterar +C-stils (`//`, `/* */`) kommentarer. Detta dokument kommer dock att tillämpa +100% giltigt JSON. Lyckligtvis så är resten av dokumentet självförklarande. + + +```json +{ + "nyckel": "värde", + + "nycklar": "måste alltid omslutas med dubbla citationstecken", + "nummer": 0, + "strängar": "Alla unicode-tecken (inklusive \"escaping\") är tillåtna.", + "boolska värden?": true, + "nullvärden": null, + + "stora tal": 1.2e+100, + + "objekt": { + "kommentar": "Det flesta datastukturerna i JSON kommer i form av objekt.", + + "matris": [0, 1, 2, 3, "Matriser kan innehålla vad som helst.", 5], + + "ytterligare objekt": { + "kommentar": "Objekten kan vara nästlade." + } + }, + + "trams": [ + { + "kaliumkällor": ["bananer"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternativ formatering": { + "kommentar": "kolla på detta!" + , "kommats position": "spelar ingen roll - så länge det kommer innan värdet" + , "en kommentar till": "vad fint" + }, + + "det var kort": "Nu är du klar och kan allt vad JSON har att erbjuda." +} +``` -- cgit v1.2.3 From 6dabd9568d2a99e7bbc079d0466588bf68a42283 Mon Sep 17 00:00:00 2001 From: Vojta Svoboda Date: Mon, 5 Oct 2015 10:15:07 +0200 Subject: Brainfuck cs_CZ translation --- cs-cz/brainfuck.html.markdown | 87 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 cs-cz/brainfuck.html.markdown diff --git a/cs-cz/brainfuck.html.markdown b/cs-cz/brainfuck.html.markdown new file mode 100644 index 00000000..92424ecf --- /dev/null +++ b/cs-cz/brainfuck.html.markdown @@ -0,0 +1,87 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Vojta Svoboda", "https://github.com/vojtasvoboda/"] +filename: learnbrainfuck.bf +lang: cs-cz +--- + +Brainfuck (psaný bez kapitálek s vyjímkou začátku věty) je extrémně minimální +Turingovsky kompletní (ekvivalentní) programovací jazyk a má pouze 8 příkazů. + +Můžete si ho vyzkoušet přímo v prohlížeči s [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` +Jakýkoliv znak mimo "><+-.,[]" (bez uvozovek) je ignorován. + +Brainfuck je reprezentován jako pole, které má 30.000 buněk s počátkem v nule +a datovým ukazatelem na aktuální buňce. + +Můžeme využít těchto osm příkazů: ++ : Přičte k aktuální buňce jedničku. +- : Odečte od aktuální buňky jedničku. +> : Posune datový ukazatel na další buňku, která je napravo. +< : Posune datový ukazatel na předchozí buňku, která je nalevo. +. : Vytiskne ASCII hodnotu aktuální buňky (například 65 = 'A'). +, : Načte jeden znak do aktuální buňky. +[ : Pokud je hodnota aktuální buňky nulová, přeskočí na buňku odpovídající ] . + Jinak skočí na další instrukci. +] : Pokud je hodnota aktuální buňky nulova, přeskočí na další instrukci. + Jinak skočí zpět na instrukci odpovídající [ . + +[ a ] tak tvoří 'while' smyčku a tyto symboly musí tak být v páru. + +Pojďme se mrknout na některé brainfuck programy. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Tento program vypíše písmeno 'A' (v ASCII je to číslo 65). Nejdříve navýší +buňku #1 na hodnotu 6. Buňka #1 bude použita pro smyčku. Potom program vstoupí +do smyčky ([) a sníží hodnotu buňky #1 o jedničku. Ve smyčce zvýší hodnotu +buňky #2 desetkrát, vrátí ze zpět na buňku #1 a sníží její hodnotu o jedničku. +Toto se stane šestkrát (je potřeba šestkrát snížit hodnotu buňky #1, aby byla +nulová a program přeskočil na konec cyklu označený znakem ]. + +Na konci smyčky, kdy jsme na buňce #1 (která má hodnotu 0), tak má buňka #2 +hodnotu 60. Přesuneme se na buňku #2 a pětkrát zvýšíme její hodnotu o jedničku +na hodnotu 65. Na konci vypíšeme hodnotu buňky #2 - 65, což je v ASCII znak 'A' +na terminálu. + + +, [ > + < - ] > . + +Tento program přečte znak z uživatelského vstupu a zkopíruje ho do buňky #1. +Poté začne smyčka - přesun na buňku #2, zvýšení hodnoty buňky #2 o jedničku, +přesun zpět na buňku #1 a snížení její hodnoty o jedničku. Takto smyčka pokračuje +do té doby, než je buňka #1 nulová a buňka #2 nabyde původní hodnotu buňky #1. +Protože jsme na buňce #1, přesuneme se na buňku #2 a vytiskneme její hodnotu +v ASCII. + +Je dobré vědět, že mezery jsou v programu uvedené pouze z důvodu čitelnosti. +Program je možné klidně zapsat i takto: + +,[>+<-]>. + + +Nyní se podívejte na tento program a zkuste zjistit co dělá: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Tento program vezme dvě čísla ze vstupu a vynásobí je. + +Program nejdříve načte dvě vstupní hodnoty. Poté začíná smyčka řízená hodnotou +v buňce #1 - přesun na buňku #2 a start druhé vnořené smyčky, která je řízená +hodnotou v buňce #2 a zvyšuje hodnotu v buňce #3. Nicméně je zde problém +kdy na konci vnitřní smyčky je v buňce #2 nula a smyčka by tak znovu +napokračovala. Vyřešíme to tak, že zvyšujeme o jedničku i buňku #4 a její +hodnotu poté překopírujeme do buňky #2. Na konci programu je v buňce #3 +výsledek. +``` + +A to je brainbuck. Zase tak složitý není, co? Zkuste si nyní napsat nějaký +vlastní brainfuck program a nebo interpretr v jiném jazyce, což není zase +tak složité, ale pokud jste opravdový masochista, zkuste si naprogramovat +interpretr jazyka brainfuck v jazyce... brainfuck :) -- cgit v1.2.3 From 4d619e9b0fc4a061fa720b47b22068c8661e9be6 Mon Sep 17 00:00:00 2001 From: Vojta Svoboda Date: Wed, 7 Oct 2015 10:22:08 +0200 Subject: [json/cs] JSON translation to cs_CZ --- cs-cz/json.html.markdown | 63 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 cs-cz/json.html.markdown diff --git a/cs-cz/json.html.markdown b/cs-cz/json.html.markdown new file mode 100644 index 00000000..8a685524 --- /dev/null +++ b/cs-cz/json.html.markdown @@ -0,0 +1,63 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Vojta Svoboda", "https://github.com/vojtasvoboda/"] +filename: learnjson.json +lang: cs-cz +--- + +JSON je exterémně jednoduchý datově nezávislý formát a bude asi jeden z +nejjednodušších 'Learn X in Y Minutes' ze všech. + +JSON nemá ve své nejzákladnější podobě žádné komentáře, ale většina parserů +umí pracovat s komentáři ve stylu jazyka C (`//`, `/* */`). Pro tyto účely +však budeme používat 100% validní JSON bez komentářů. Pojďme se podívat na +syntaxi formátu JSON: + +```json +{ + "klic": "value", + + "hodnoty": "Musí být vždy uvozený v dvojitých uvozovkách", + "cisla": 0, + "retezce": "Hellø, wørld. Všechny unicode znaky jsou povolené, společně s \"escapováním\".", + "pravdivostni_hodnota": true, + "prazdna_hodnota": null, + + "velke_cislo": 1.2e+100, + + "objekt": { + "komentar": "Most of your structure will come from objects.", + + "pole": [0, 1, 2, 3, "Pole nemusí být pouze homogenní.", 5], + + "jiny_objekt": { + "comment": "Je povolené jakkoli hluboké zanoření." + } + }, + + "cokoli": [ + { + "zdroje_drasliku": ["banány"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternativni_styl_zapisu": { + "komentar": "Mrkni se na toto!" + , "pozice_carky": "Na pozici čárky nezáleží - pokud je před hodnotou, ať už je kdekoli, tak je validní." + , "dalsi_komentar": "To je skvělé." + }, + + "to_bylo_rychle": "A tím jsme hotový. Nyní již víte vše, co může formát JSON nabídnout!" +} +``` -- cgit v1.2.3 From 3c1e9a8bc06b654cd812306ed90ca61e9d8bb3eb Mon Sep 17 00:00:00 2001 From: davidsonmizael Date: Thu, 8 Oct 2015 00:33:55 -0300 Subject: Adding bash tutorial in pt-br --- pt-br/bash-pt.html.markdown | 282 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 282 insertions(+) create mode 100644 pt-br/bash-pt.html.markdown diff --git a/pt-br/bash-pt.html.markdown b/pt-br/bash-pt.html.markdown new file mode 100644 index 00000000..a604e7b8 --- /dev/null +++ b/pt-br/bash-pt.html.markdown @@ -0,0 +1,282 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] +translators: + - ["Davidson Mizael", "https://github.com/davidsonmizael"] +filename: LearnBash-pt_br.sh +lang: pt-br +--- + +Tutorial de shell em português + +Bash é o nome do shell do Unix, que também é distribuido como shell do sistema +operacional GNU e como shell padrão para Linux e Mac OS X. Praticamente todos +os exemplos abaixo podem fazer parte de um shell script e pode ser executados +diretamente no shell. + +[Leia mais sobre](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# A primeira linha do script é o shebang, que conta para o sistema como executar +# o script: http://en.wikipedia.org/wiki/Shebang_(Unix) +# Como você já deve ter percebido, comentários começam com #. +# Shebang também é um comentário. + +# Exemplo simples de hello world: +echo Hello World! + +# Cada comando começa com uma nova linha, ou após um ponto virgula: +echo 'Essa é a primeira linha'; echo 'Essa é a segunda linha' + +# A declaração de variáveis é mais ou menos assim +Variavel="Alguma string" + +# Mas não assim: +Variavel = "Alguma string" +# Bash interpretará Variavel como um comando e tentará executar e lhe retornar +# um erro porque o comando não pode ser encontrado. + +# Ou assim: +Variavel= 'Alguma string' +# Bash interpretará 'Alguma string' como um comando e tentará executar e lhe retornar +# um erro porque o comando não pode ser encontrado. (Nesse caso a a parte 'Variavel=' +# é vista com uma declaração de variável valida apenas para o escopo do comando 'Uma string'). + +# Usando a variável: +echo $Variavel +echo "$Variavel" +echo '$Variavel' +# Quando você usa a variável em si — declarando valor, exportando, etc — você escreve +# seu nome sem o $. Se você quer usar o valor da variável você deve usar o $. +# Note que ' (aspas simples) não expandirão as variáveis! + +# Substituição de strings em variáveis +echo ${Variavel/Alguma/Uma} +# Isso substituirá a primeira ocorrência de "Alguma" por "Uma" + +# Substring de uma variável +Tamanho=7 +echo ${Variavel:0:Tamanho} +# Isso retornará apenas os 7 primeiros caractéres da variável + +# Valor padrão de uma variável +echo ${Foo:-"ValorPadraoSeFooNaoExistirOuEstiverVazia"} +# Isso funciona para nulo (Foo=) e (Foo=""); zero (Foo=0) retorna 0. +# Note que isso apenas retornar o valor padrão e não mudar o valor da variável. + +# Variáveis internas +# Tem algumas variáveis internas bem uteis, como +echo "O ultimo retorno do programa: $?" +echo "PID do script: $$" +echo "Numero de argumentos passados para o script $#" +echo "Todos os argumentos passados para o script $@" +echo "Os argumentos do script em variáveis diferentes: $1, $2..." + +# Lendo o valor do input: +echo "Qual o seu nome?" +read Nome # Note que nós não precisamos declarar a variável +echo Ola, $Nome + +# Nós temos a estrutura if normal: +# use 'man test' para mais infomações para as condicionais +if [ $Nome -ne $USER ] +then + echo "Seu nome não é o seu username" +else + echo "Seu nome é seu username" +fi + +# Tem também execução condicional +echo "Sempre executado" || echo "Somente executado se o primeiro falhar" +echo "Sempre executado" && "Só executado se o primeiro NÃO falhar" + +# Para usar && e || com o if, você precisa multiplicar os pares de colchetes +if [ $Nome == "Estevao"] && [ $Idade -eq 15] +then + echo "Isso vai rodar se $Nome é igual Estevao E $Idade é 15." +fi + +fi [ $Nome == "Daniela" ] || [ $Nome = "Jose" ] +then + echo "Isso vai rodar se $Nome é Daniela ou Jose." +fi + +# Expressões são denotadas com o seguinte formato +echo $(( 10 + 5)) + +# Diferentemente das outras linguagens de programação, bash é um shell, então ele +# funciona no diretório atual. Você pode listar os arquivos e diretórios no diretório +# atual com o comando ls: +ls + +#Esse comando tem opções que controlam sua execução +ls -l # Lista todo arquivo e diretorio em linhas separadas + +# Os resultados do comando anterior pode ser passado para outro comando como input. +# O comando grep filtra o input com o padrão passado. É assim que listamos apenas +# os arquivos .txt no diretório atual: +ls -l | grep "\.txt" + +# Você pode redirecionar o comando de input e output (stdin, stdout e stderr). +# Lê o stdin até ^EOF$ e sobrescreve hello.py com as linhas entre "EOF": +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ imprt print_function +import sys +print("#stdout", file=sys.stdout) +print("stderr", file=sys.stderr) +for line in sys.stdin: + print(line, file=sys.stdout) +EOF + +# Rode hello.py com várias instruções stdin, stdout e stderr: +python hello.py < "input.in" +python hello.py > "ouput.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# O erro no output sobrescreverá o arquivo se existir, +# se ao invés disso você quiser complementar, use ">>": +python hello.py >> "output.out" 2>> "error.err" + +# Sobrescreve output.out, complemente para error.err e conta as linhas +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +#Roda um comando e imprime o desencriptador (e.g. /dev/fd/123) +# veja: man fd +echo <(echo "#helloworld") + +# Sobrescreve ouput.out com "#helloworld": +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out > /dev/null + +# Limpa os arquivos temporarios detalhando quais foram deletados (use '-i' para confirmar exlusão) +rm -v output.out error.err output-and-error.log + +# Comando podem ser substituidos por outros comandos usando $( ): +# O comand oa seguir mostra o número de arquivos e diretórios no diretorio atual +echo "Existem $(ls | wc -l) itens aqui." + +# O mesmo pode ser feito usando crase `` mas elas não podem ser aninhadas - dá se +# preferência ao uso do $( ) +echo "Existem `ls | wc -l` itens aqui." + +# Bash usa o comando case que funciona de uma maneira similar ao switch de Java e C++: +case "$Variavel" in + # Lista de parametros para condições que você quer encontrar + 0) echo "Isso é um Zero.";; + 1) echo "Isso é um Um.";; + *) echo "Isso não é null.";; +esac + +# loops for iteragem para quantos argumentos passados: +# O conteudo de $Variavel é exibido três vezes. +for Variavel in {1..3} +do + echo "$Variavel" +done + +# Ou use o loop da "maneira tradicional": +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Eles também podem ser usados em arquivos... +# Isso irá rodar o comando 'cat' em arquivo1 e arquivo2 +for Variavel in arquivo1 arquivo2 +do + cat "$Variavel" +done + +# ...ou o output de um comando +# Isso irá usar cat no output do ls. +for Output in $(ls) +do + cat "$Output" +done + +# loop while: +while [ true ] +do + echo "corpo do loop aqui..." + break +done + +# Você também pode usar funções +# Definição: +function foo() { + echo "Argumentos funcionam bem assim como os dos scripts: $@" + echo "E: $1 $2..." + echo "Isso é uma função" + return 0 +} + +# ou simplesmente +bar () { + echo "Outro jeito de declarar funções!" + return 0 +} + +# Chamando sua função +foo "Meu nome é" $Nome + +# Existe um monte de comandos úteis que você deveria aprender: +# exibe as 10 ultimas linhas de arquivo.txt +tail -n 10 arquivo.txt +# exibe as primeiras 10 linhas de arquivo.txt +head -n 10 arquivo.txt +# ordena as linhas de arquivo.txt +sort arquivo.txt +# reporta ou omite as linhas repetidas, com -d você as reporta +uniq -d arquivo.txt +# exibe apenas a primeira coluna após o caráctere ',' +cut -d ',' -f 1 arquivo.txt +# substitui todas as ocorrencias de 'okay' por 'legal' em arquivo.txt (é compativel com regex) +sed -i 's/okay/legal/g' file.txt +# exibe para o stdout todas as linhas do arquivo.txt que encaixam com o regex +# O exemplo exibe linhas que começam com "foo" e terminam com "bar" +grep "^foo.*bar$" arquivo.txt +# passe a opção "-c" para ao invês de imprimir o numero da linha que bate com o regex +grep -c "^foo.*bar$" arquivo.txt +# se você quer literalmente procurar por uma string, +# e não pelo regex, use fgrep (ou grep -F) +fgrep "^foo.*bar$" arquivo.txt + + +# Leia a documentação interna do shell Bash com o comando interno 'help': +help +help help +help for +help return +help source +help . + +# Leia a página principal da documentação com man +apropos bash +man 1 bash +man bash + +# Leia a documentação de informação com info (? para ajuda) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +#Leia a documentação informativa do Bash: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` -- cgit v1.2.3 From 2813f49b8a00afc50a8cbcb1ac2960d594e5db9e Mon Sep 17 00:00:00 2001 From: Martin Schimandl Date: Fri, 9 Oct 2015 10:50:34 +0200 Subject: First version of a german translation of the Tcl page --- de-de/tcl-de.html.markdown | 474 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 474 insertions(+) create mode 100644 de-de/tcl-de.html.markdown diff --git a/de-de/tcl-de.html.markdown b/de-de/tcl-de.html.markdown new file mode 100644 index 00000000..1e24e379 --- /dev/null +++ b/de-de/tcl-de.html.markdown @@ -0,0 +1,474 @@ +--- +language: Tcl +contributors: + - ["Poor Yorick", "http://pooryorick.com/"] +translators: + - ["Martin Schimandl", "https://github.com/Git-Jiro"] +filename: learntcl-de.tcl +--- + +Tcl wurde kreiert von [John Ousterhout](http://wiki.tcl.tk/John Ousterout) als +eine wiederverwendbare Script-Sprache für Chip-Design Werkzeuge die er kreiert +hat. Im Jahre 1997 wurde er mit dem [ACM Software System +Award](http://en.wikipedia.org/wiki/ACM_Software_System_Award) für Tcl +ausgezeichnet. Tcl kann sowohl als eingebettete Scipt-Sprache als auch als +allgemeine Programmier-Sprache verwendet werden. Tcl kann auch als portable +C-Bibliothek verwendet werden. Sogar in Fällen in denen die Script-Fähigkeiten +nicht nötig sind. Denn Tcl stellt Daten-Strukturen wie dynamische Zeichenketten, +Listen und Hash-Tabellen bereit. Die C-Bilbiothek stellt auch portable +Funktionen zur Verfügung: Laden von dynamischen Bibliotheken, Zeichenketten +formatierung und Code Konversion, Dateisystem Operationen, Netzwerk Operationen +und mehr. + + +Verschiedenste herausragende Fähigkeiten von Tcl: + +* Praktische Cross-Platform Netzwerk-API + +* Vollständig virtualisiertes Dateisystem + +* Stapelbare I/O Kanäle + +* Asynchron bis zum Kern + +* Vollständige Ko-Routinen + +* Robustes und einfach zu verwendendes Thread-Modell + + +Wenn Lisp ein Listen-Prozessor ist, dann ist TCl ein Zeichenketten-Prozessor. +Alle Werte sind Zeichenketten. Eine Liste ist ein Zeichenketten-Format. Eine +Prozedur-Definition ist ein Zeichenketten-Format. Um leistungsfähig zu sein, +werden Tcl-intern diese Zeichenketten in Strukutierter-Form gepuffert. Ein +Beispiel: Der "list" Befehl arbeitet mit diesen internen gepufferten +Repräsentationen. Tcl kümmert sich selbständig darum die String-Repräsentationen +zu aktualisieren, falls dies im Skript benötigt werden sollten. Das Kopieren- +beim-Schreiben-Design von Tcl erlaubt es Skript-Authoren mit großen Daten- +Strukturen zu arbeiten ohne zuätzlichen Speicher-Overhead. Prozeduren werden +automatisch byte-kompiliert außer sie verwenden dynamsiche Befehle wie zum +Beispiel "uplevel", "upvar und "trace". + +Es ist eine freude in Tcl zu programmieren. Hacker-Typen werden gefallen daran +finden, wenn sie Lisp, Forth oder Smalltalk interessant finden. Tcl wird auch +Ingenieuren und Wissenshaftlern gefallen die nur den Job erledigen wollen, +und zwar mit Werkzeugen die sich ihrem Willen anpassen. Bei Tcl ist jegliche +funktionalität in Befehlen ausgeführt, selbst Dinge wie Schleifen und +Mathematische-Funktionen die bei anderen Sprachen normalerweise Teil der Syntax +sind. Das erlaubt Tcl in den Hintergrund von Domänen spezischen Sprachen zu +treten die das jeweilige Projekt gerade benötigt. Die Tcl-Syntax ist sehr +leichtgewichtig. Sie ist selbst leichtgewichtiger als die Syntax von Lisp. +Tcl steht dir einfach nicht im Weg. + + +```tcl +#! /bin/env tclsh + +################################################################################ +## 1. Richtlinien +################################################################################ + +# Tcl ist nicht Bash oder C! Das muss gesagt werden, denn standard Shell-Quoting +# funktioniert fast mit Tcl. Daher glauben viele sie können diese Syntax für +# Tcl übernehmen. Am Beginn funktioniert das meist, führt aber schnell zu +# Frustrationen wenn die Skripte komplexer werden. + +# Eckige-Klammern sind nur Quoting-Mechanismen, keine Code-Block-Konstruktoren +# und auch keine Listen-Konstruktoren. In Tcl gibt es diese beiden Dinge nicht. +# Eckige-Klammern werden verwendet um Spezial-Zeichen in Prozeduren zu escapen +# und in Zeichenketten die als Listen formattiert sind. + +################################################################################ +## 2. Syntax +################################################################################ + +# Jede Zeile ist ein Befehl. Das erste Wort ist der Name des Befehls, jedes +# weitere Wort ist ein Argument des Befehls. Wörter sind begrenzt durch +# Leerzeichen. Da jedes Wort auch ein String ist, sind keine speziellen +# auszeichnungen wie Anführungs-Zeichen, Klammern oder Backslashes nötig. +# Selbst wenn Anführungs-Zeichen verwendet werden, denn sie sind ja keine +# String-Konstruktoren, sondern nur Escape-Zeichen. + +set greeting1 Sal +set greeting2 ut +set greeting3 ations + + +# Strichpunkte begrenzen auch Befehle +set greeting1 Sal; set greeting2 ut; set greeting3 ations + + +# Das Dollar-Zeichen zeigt eine Variablen-Substitution an. +set greeting $greeting1$greeting2$greeting3 + + +# Eckige-Klammern zeigen Befehls-Substitionen an. Das Ergebnis des Befehls wird an +# Stelle des Klammern-Ausdrucks eingefügt. Wenn man dem "set" Befehl nur den +# Namen einer Variablen übergibt, gibt er den Wert der Variablen zurück. +set greeting $greeting1$greeting2[set greeting3] + + +# Befehls-Substitution sollte eigentlich Script-Substitution heißen, denn ein +# komplettes Script, und nicht nur ein Befehl, kann zwischen die Eckigen-Klammern +# geschrieben werden. Der "incr" Befehl erhöht den Wert einer Variable um 1 +# und gibt den neuen Wert der Variable zurück. +set greeting $greeting[ + incr i + incr i + incr i +] + + +# Der Backslash unterdrück die Bedeutung von Sonderzeichen +set amount \$16.42 + + +# Der Backslash macht bestimmte Zeichen zu Sonderzeichen +puts lots\nof\n\n\n\n\n\nnewlines + +# Ein Wort das in geschweiften Klammern eingeschlossen wurde ist von jeglichen +# speziellen Interpretationen ausgeschlossen. Eine Ausnahme bilden Backslashes +# vor geschweiften Klammern, hiermit wird die geschweifte Klammer von der Suche +# nach der schließenden geschweiften Klammer ausgeschlossen. +set somevar { + Das ist ein literales $ Zeichen, diese geschweifte Klammer \} wird nicht + als Ende interpretiert. +} + + +# Bei einem Wort das in doppelten Anführungszeichen steht verlieren Leerzeichen +# ihre spezielle Bedeutung. +set name Neo +set greeting "Hallo, $name" + + +#Variablen-Namen können irgend eine Zeichenkette sein. +set {first name} New + + +# Die Geschweifte-Klammern-Form der Variablen-Substitution kann sehr komplexe +# Variblen-Namen handhaben. +set greeting "Hello, ${first name}" + + +# Der "set" Befehl kann immer anstatt einer Variablen-Substition verwendet +# werden. +set greeting "Hello, [set {first name}]" + + +# Mit dem Expansions-Operator "{*}" werden Wörter innerhalb eines Wortes wieder +# individuell als Teile des aktuellen Befehls behandelt. +set {*}{name Neo} + +# Ist Äquivalent zu +set name Neo + + +# Ein Array ist eine spezielle Varible die also Kontainer für andere Variablen +# dient. +set person(name) Neo +set person(gender) male +set greeting "Hello, $person(name)" + + +# Ein Namensraum enthält Befehle und Variablen +namespace eval people { + namespace eval person1 { + variable name Neo + } +} + + +#Der volle Name einer Variablen beihaltet den/die umschließenden +# Namensraum/Namensräume begrenzt durch zwei Doppelpunkte. +set greeting "Hello $people::person1::name" +``` + +```tcl +################################################################################ +## 3. Einige Notizen +################################################################################ + +# Jede weitere Funktion ist über Befehle implementiert. Von nun an kommt keine +# neue Syntax hinzu. Alles weitere das es über Tcl zu lernen gibt ist das +# Verhalten individueller Befehle und die bedeutung ihrer Argumente. + + +# Um einen Interpreter zu bekommen mit dem man nichts mehr machen kann, lösche +# einfach den globalen Namensraum. Das ist nicht sehr sinnvoll, zeigt aber die +# Natur von Tcl. +namespace delete :: + + +# Wegen des Verhaltens der Namens-Auflösung ist es sicherer den "variable" +# Befehl zu verwenden um in einem Namensraum einen Wert zu deklarieren oder +# zuzuweisen. Wenn eine Variable mit dem namen "name" bereits im globalen +# Namensraum existiert, bewirkt der "set" Befehl das der globalen Variable ein +# Wert zugewiesen wird, anstatt eine Variable im lokalen Namensraum zu erzeugen +namespace eval people { + namespace eval person1 { + variable name Neo + } +} + + +# Es kann immer der vollständige Name einer Variable verwendet werden, falls +# gewünscht. +set people::person1::name Neo + + + +################################################################################ +## 4. Befehle +################################################################################ + +# Berechnungen werde mit dem "expr" Befehl durchgeführt. +set a 3 +set b 4 +set c [expr {$a + $b}] + +# Since "expr" performs variable substitution on its own, brace the expression +# to prevent Tcl from performing variable substitution first. See + +# Da der "expr" Befehl eigene Variablen-Substitutionen durchführt, setze den +# zu berechnenden Ausdruck in Eckige-Klammern. Das hindert Tcl daran Variablen- +# Substitutionen durchzuführen. Für Details siehe: +# "http://wiki.tcl.tk/Brace%20your%20#%20expr-essions" + + +# Der "expr" Befehl versteht Variablen- und Befehls-Substitutionen +set c [expr {$a + [set b]}] + + +# Der "expr" Befehl stellt Mathematische-Funktionen zur Verfügung. +set c [expr {pow($a,$b)}] + + +# Mathematische Operatoren sind als Befehle auch im Namensraum +# ::tcl::mathop verfügbar. +::tcl::mathop::+ 5 3 + +# Befehle können aus anderen Namensräumen importiert werden. +namespace import ::tcl::mathop::+ +set result [+ 5 3] + + +# Neu Befehle werden mit dem "proc" Befehl gebildet. +proc greet name { + return "Hello, $name!" +} + +#Es können mehrere Parameter spezifiziert werden. +proc greet {greeting name} { + return "$greeting, $name!" +} + + +# Wie bereits erwähnt, geschwungene Klammern erzeugen keinen Code-Block. +# Jeder Wert, sogar das dritte Argument für den "proc" Befehl ist eine +# Zeichenkette. Der vorherige Befehl kann daher auch ohne +# geschwungene Klammern geschrieben werden: +proc greet greeting\ name return\ \"Hello,\ \$name! + + + +# Wenn der letzte Parameter der literale Wert "args" ist, sammelt dieser Wert +# alle übrigen Argumente des Befehls ein wenn dieser aufgerufen wird. +proc fold {cmd args} { + set res 0 + foreach arg $args { + set res [$cmd $res $arg] + } +} +fold ::tcl::mathop::* 5 3 3 ;# -> 45 + + +# Bedingte Ausführung ist auch als Befehl implementiert +if {3 > 4} { + puts {This will never happen} +} elseif {4 > 4} { + puts {This will also never happen} +} else { + puts {This will always happen} +} + + +# Auch Schleifen sind Befehle. Das erste, zweite und dritte Argument des "for" +# Befehls wird als mathematischer Ausdruck behandelt. +for {set i 0} {$i < 10} {incr i} { + set res [expr {$res + $i}] +} + + +# Das erste Argument des "while" Befehls wird auch als mathematischer Ausdruck +# behandelt. +set i 0 +while {$i < 10} { + incr i 2 +} + + +# Eine Liste ist eine speziell formatierte Zeichenkette. Im einfachsten Fall +# genügen Leerzeichen als Trennzeichen zwischen den einzelnen Werten. +set amounts 10\ 33\ 18 +set amount [lindex $amounts 1] + + +# Geschwungene Klammern und Backslashes können verwendet werden um komplexe +# Werte in einer Liste zu formatieren. Eine Liste sieht aus wie ein Skript, +# allerdings verlieren verlieren Zeilenumbrüche und Doppelüunkte ihre +# besondere Bedeutung. Diese Funktionalität macht Tcl homoikonisch. Die +# folgende Liste enhtält drei Elemente. +set values { + + one\ two + + {three four} + + five\{six + +} + + +# Da Listen auch Zeichenketten sind, kann man Zeichenketten-Operationen auf +# ihnen anwenden. Allerdings mit dem Risiko die Formatierung der Liste zu +# beschädigen. +set values {one two three four} +set values [string map {two \{} $values] ;# $values is no-longer a \ + properly-formatted listwell-formed list + + +# Der sicherste Weg korrekt formatierte Liste zu erzeugen, ist den "list" +# Befehl zu verwenden. +set values [list one \{ three four] +lappend values { } ;# Ein Leerzeichen als Element der Liste hinzufügen + + +# Mit "eval" können Werte als Skripts evaluiert weden. +eval { + set name Neo + set greeting "Hello, $name" +} + + +# Eine Liste kann immer an "eval" übergeben werden, solange die Liste einen +# einzigen Befehl entält. +eval {set name Neo} +eval [list set greeting "Hello, $name"] + + +# Daher: Wenn "eval" verwendet wird, verwende [list] um den gewünschten Befehl +# aufzubauen. +set command {set name} +lappend command {Archibald Sorbisol} +eval $command + + +# Es ist ein häufiger Fehler die Listen funktionen beim Aufbauen von Listen +# nicht zu verwenden. +set command {set name} +append command { Archibald Sorbisol} +eval $command ;# Hier passiert eine Fehler, denn der "set" Befehl hat nun zu \ + viele Argumente {set name Archibald Sorbisol} + + +# Dieser Fehler kann auch leicht beim "subst" Befehl passieren. +set replacement {Archibald Sorbisol} +set command {set name $replacement} +set command [subst $command] +eval $command ;# The same error as before: too many arguments to "set" in \ + {set name Archibald Sorbisol} + + +# Die korrekte Vorgangsweise ist es den substituierten Wert mit dem "list" +# Befehl zu formatieren. +set replacement [list {Archibald Sorbisol}] +set command {set name $replacement} +set command [subst $command] +eval $command + + +# Der "list" Befehl wird sehr häufig verwendet um Werte zu formatieren die +# in Tcl Skript Vorlagen substituiert werden. Es gibt dazu viele Beispiele, +# siehe unterhalb. + + +# Der "apply" Befehl evaluiert eine Zeichenkette als Befehl. +set cmd {{greeting name} { + return "$greeting, $name!" +}} +apply $cmd Whaddup Neo + + +# Der "uplevel" Befehl evaluiert ein Skript in einem höher liegenden +Gültigkeitsbereich. +proc greet {} { + uplevel {puts "$greeting, $name"} +} + +proc set_double {varname value} { + if {[string is double $value]} { + uplevel [list variable $varname $value] + } else { + error [list {not a double} $value] + } +} + + +# Der "upvar" Befehl verknüpft eine Variable im aktuellen Gültigkeitsbereich +# mit einer Variable in einem höher liegenden Gültigkeitsbereich. +proc set_double {varname value} { + if {[string is double $value]} { + upvar 1 $varname var + set var $value + } else { + error [list {not a double} $value] + } +} + + +# Werde den eingebauten "while" Befehl los. +rename ::while {} + + +# Definieren einen neuen "while" Befehl mit hilfe des "proc" Befehls. +# Ausführlichere Fehler-Behandlung wird dem Leser als Übung überlassen. +proc while {condition script} { + if {[uplevel 1 [list expr $condition]]} { + uplevel 1 $script + tailcall [namespace which while] $condition $script + } +} + + +# Der "coroutine" Befehl erzeugt einen separaten Call-Stack, zusammen mit einem +# Befehl um diesem Call-Stack zu verwenden. Der "yield" Befehl unterbricht +# die Ausführung des aktuellen Call-Stacks. +proc countdown {} { + #send something back to the initial "coroutine" command + yield + + set count 3 + while {$count > 1} { + yield [incr count -1] + } + return 0 +} +coroutine countdown1 countdown +coroutine countdown2 countdown +puts [countdown 1] ;# -> 2 +puts [countdown 2] ;# -> 2 +puts [countdown 1] ;# -> 1 +puts [countdown 1] ;# -> 0 +puts [coundown 1] ;# -> invalid command name "countdown1" +puts [countdown 2] ;# -> 1 + + +``` + +## Referenzen + +[Official Tcl Documentation](http://www.tcl.tk/man/tcl/) + +[Tcl Wiki](http://wiki.tcl.tk) + +[Tcl Subreddit](http://www.reddit.com/r/Tcl) -- cgit v1.2.3 From 879337f9be2ef3c6ea2b01d34d2a21ad325c6cc4 Mon Sep 17 00:00:00 2001 From: DaKnOb Date: Fri, 9 Oct 2015 13:43:57 +0300 Subject: Add Python Order Of Module Import for Python 3 --- python3.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/python3.html.markdown b/python3.html.markdown index b3acb122..f21604e4 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -591,6 +591,11 @@ math.sqrt(16) == m.sqrt(16) # => True import math dir(math) +# If you have a Python script named math.py in the same +# folder as your current script, the file math.py will +# be loaded instead of the built-in Python module. +# This happens because the local folder has priority +# over Python's built-in libraries. #################################################### ## 7. Advanced -- cgit v1.2.3 From debf4073bd264b1da728b04feb2c25fd5d6df845 Mon Sep 17 00:00:00 2001 From: Arashk Date: Fri, 9 Oct 2015 18:50:38 +0330 Subject: [CSS/en] translated to [CSS/fa-ir] --- fa-ir/css.html.markdown | 299 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 299 insertions(+) create mode 100644 fa-ir/css.html.markdown diff --git a/fa-ir/css.html.markdown b/fa-ir/css.html.markdown new file mode 100644 index 00000000..7214bb04 --- /dev/null +++ b/fa-ir/css.html.markdown @@ -0,0 +1,299 @@ +--- +language: CSS +translators: + - ["Arashk", "https://github.com/Arashk-A"] +lang: fa-ir +--- + +

در روزهای آغازین وب هیچگونه عنصر بصری مشاهده نمیشد و محتوا به صورت متن خالی بود.

+

اما با توسعه بیشتر مرورگرها صفحات وب کاملاً تصویری نیز رایج شد

+

CSS زبان استانداردی که موجودیت آن برای حفظ جدایی بین محتوا (HTML) و نگاه و احساس از

+

صفحات وب است.

+ +

به طور خلاصه, کاری که CSS انجام میدهد ارائه نحوه ایست که شما را قادر به هدف قرار دادن

+

عناصر مختلف در یک صفحه HTML کرده و امکان اختصاص خواص متفاوت بصری به آنها را میدهد.

+ + +

مانند هر زبانی, CSS نسخه های زیادی دارد که در اینجا توجه ما روی CSS2.0 است. با وجودی که این نسخه جدیدترین نسخه نمیباشد اما بیشترین پشتیبانی و سازگاری را در میان نسخه های مختلف را دارد

+ +

توجه: برای مشاهده برخی از نتایج جلوه های تصویری CSS به منظور یادگیری بیشتر شما باید چیزهای گوناگونی در محیطی مثل [dabblet](http://dabblet.com/) امتحان کنید. توجه اصلی این مقاله روی دستورات و برخی از نکات عمومی است.

+ + +

در CSS همه توضیحات داخل ستاره-بروم نوشته میشوند زیرا CSS دستوری برای توضیحات تک خطی مثل C ندارد

+ +```CSS +/* comments appear inside slash-asterisk, just like this line! + there are no "one-line comments"; this is the only comment style */ +``` + +

به طور کلی دستورات CSS بسیار ساده هستند که در آن یک انتخابگر (selector) عنصری را در روی صفحه هدف قرار میدهد.

+ +```CSS +selector { property: value; /* more properties...*/ } +``` + +

با استفاده از ستاره می توان برای همه عناصر روی صفحه استایل تعریف کرد

+ +```CSS +* { color:red; } +``` + +

فرض کنید عنصری مثل این بر روی صفحه قرار دارد

+ +```html +
+``` +

شما میتوانید با استفاده از نام کلاس آنرا انتخاب کنید

+ +‍‍```CSS +.some-class { } +``` + +

یا با استفاده از نام دو کلاس

+ +```CSS +.some-class.class2 { } +``` + +

یا با استفاده از نام id

+ +```CSS +#someId { } +``` + +

یا با استفاده از نام خود عنصر

+ +```CSS +div { } +``` + +

یا با استفاده از 'attr'

+ +```CSS +[attr] { font-size:smaller; } +``` + +

یا با استفاده از ارزشی که برای 'attr' مشخص شده

+ +```CSS +[attr='value'] { font-size:smaller; } +``` + +

با استفاده از ارزشی که برای 'attr' مشخص شده و آن ارزش با 'val' شروع میشود در CSS3

+ +```CSS +[attr^='val'] { font-size:smaller; } +``` + +

با استفاده از ارزشی که برای 'attr' مشخص شده و آن ارزش با 'ue' به پایان میرسد در CSS3

+ +```CSS +[attr$='ue'] { font-size:smaller; } +``` + +

یا با انتخاب بوسیله یکی از ارزشهایی که در لیست 'otherAttr' بوسیله فاصله از هم جدا شده اند در CSS3

+ +```CSS +[attr$='ue'] { font-size:smaller; } +``` + +

یا ارزش('value') دقیقاً خود ارزش('value') یا بوسیله '-' که یونیکد (U+002D) از حرف بعدی جدا شود

+ +```CSS +[otherAttr|='en'] { font-size:smaller; } +``` + +

و مهمتر از همه اینکه میتوان آنها را ترکیب کرد. نکته مهمی که در اینجا باید مد نظر داشته باشید این است که هنگام ترکیب نباید هیچگونه فاصله ای بین آنها قرار گیرد زیرا در این حالت معنای دستور تغییر میکند

+ +```CSS +div.some-class[attr$='ue'] { } +``` + +

CSS این امکان را به شما میدهد که یک عنصر را بوسیله والدین آن انتخاب کنید

+

برای مثال دستور زیر همه عناصری را که نام کلاس آنها '.class-name' و دارای پدر و مادری با این مشخصه 'div.some-parent' هستند را انتخاب میکند.

+ +```CSS +div.some-parent > .class-name {} +``` + + +

یا دستور زیر که همه عناصری را که نام کلاس آنها '.class-name' و داخل عنصری با مشخصه 'div.some-parent' هستند را در هر عمقی که باشند (یعنی فرزندی از فرزندان 'div.some-parent' باشند) انتخاب میکند.

+ +```CSS +div.some-parent .class-name {} +``` + +

نکته ای که در اینجا باید به آن توجه کنید این است که این رستور با فاصله ای بین نام دو کلاس همراه است و با مثال زیر که در بالا هم ذکر شد تفاوت دارد.

+ +```CSS +div.some-parent.class-name {} +``` + +

دستور زیر همه عناصری را که نام کلاس آنها '.this-element' و بلافاصله بعد از عنصری با مشخصه '.i-am-before' قرار دارد را انتخاب میکند.

+ +```CSS +.i-am-before + .this-element { } +``` + +

هر خواهر یا برادری که بعد از '.i-am-before' بیاید در اینجا لازم نیست بلافاصله بعد از هم قرار بگیرند ولی باید دارای پدر و مادری یکسان باشند.

+ +```CSS +.i-am-any-before ~ .this-element {} +``` +

در زیر چند نمونه از شبه کلاسها را معرفی میکنیم که به شما اجازه میدهد عناصر را بر اساس رفتار آنها در صفحه انتخاب کنید.

+

برای مثال زمانی که اشاره گر ماوس روی عنصری بر روی صفحه قرار دارد.

+ +```CSS +selector:hover {} +``` + +

یا زمانی از یک لینک بازید کردید.

+ +```CSS +selected:visited {} +``` + +

یا زمانی از لینکی بازید نشده است.

+ +```CSS +selected:link {} +``` + +

یا زمانی که روی یک عنصر ورودی متمرکز شده.

+ +```CSS +selected:focus {} +``` + +

واحدها

+ +```CSS +selector { + + /* واحدها اندازه */ + width: 50%; /* در اساس درصد */ + font-size: 2em; /* بر اساس اندازه font-size یعنی دو برابر اندازه فونت فعلی */ + width: 200px; /* بر اساس پیکسل */ + font-size: 20pt; /* بر اساس points (نکات) */ + width: 5cm; /* بر اساس سانتیمتر */ + min-width: 50mm; /* بر اساس میلیمتر */ + max-width: 5in; /* بر اساس اینچ. max-(width|height) */ + height: 0.2vh; /* بر اساس ارتفاع دید 'vh = نسبت به 1٪ از ارتفاع دید' (CSS3) */ + width: 0.4vw; /* بر اساس عرض دید 'vw = نسبت به 1٪ از عرض دید' (CSS3) */ + min-height: 0.1vmin; /* بر اساس کوچکترین مقدار از ارتفاع یا عرض دید (CSS3) */ + max-width: 0.3vmax; /* مانند مثال بالا برای بیشترین مقدار (CSS3) */ + + /* رنگها */ + background-color: #F6E; /* بر اساس short hex */ + background-color: #F262E2; /* بر اساس long hex format */ + background-color: tomato; /* بر اساس نام رنگ */ + background-color: rgb(255, 255, 255); /* بر اساس rgb */ + background-color: rgb(10%, 20%, 50%); /* بر اساس درصد rgb , (rgb percent) */ + background-color: rgba(255, 0, 0, 0.3); /* بر اساس rgba (نیمه شفاف) , (semi-transparent rgb) (CSS3) */ + background-color: transparent; /* شفاف */ + background-color: hsl(0, 100%, 50%); /* بر اساس hsl format (CSS3). */ + background-color: hsla(0, 100%, 50%, 0.3); /* بر اساس hsla ,مثل RGBAکه میتوان شفافیت را در آخر انتخاب کرد (CSS3) */ + + + /* عکسها */ + background-image: url(/path-to-image/image.jpg); /* گذاشتن نقل قول داخل url() اختیاری است*/ + + /* فونتها */ + font-family: Arial; + font-family: "Courier New"; /* اگر اسم فونت با فاصله همراه باشد باید داخل نقل قول یک یا دو نوشته شود */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; /* اگر فونت اولی پیدا نشد مرورگر به سراغ نام بعدی میرود */ +} +``` + +

نحوه استفاده

+ +

هر دستور CSS را که می خواهید در فایلی با پسوند .css ذخیره کنید

+

حالا با استفاده از کد زیر آنرا در قسمت 'head' داخل فایل html خود تعریف کنید

+ +```html + +``` + +

یا میتوان با استفاده از تگ 'style' درون 'head' دستورات CSS را به صورت درون برنامه ای تعریف کرد اما توسیه میشود تا جای ممکن از این کار اجتناب کنید.

+ +```html + +``` + +

همچنین شما میتوانید دستورات CSS را به عنوان یک مشخصه برای عنصر تعریف کنید ولی تا جای ممکن باید از این کار اجتناب کنید.

+ +```html +
+
+``` + +

حق تقدم یا اولویت

+ +

همانگونه که مشاهده کردید یک مشخصه می تواند به وسیله چندین انتخابگر انتخاب گردد.

+

و همچنین یک ویژگی میتواند چندین بار برای یک عنصر تعریف شود.

+

در این صورت یک دستور میتواند بر دستورات دیگر حق تقدم یا اولویت پیدا کند.

+ +

به مثال زیر توجه کنید:

+ +```CSS +/*A*/ +p.class1[attr='value'] + +/*B*/ +p.class1 {} + +/*C*/ +p.class2 {} + +/*D*/ +p {} + +/*E*/ +p { property: value !important; } +``` + +

و همچنین به کد زیر:

+ +```html +

+

+``` +‍‍ +

حق تقدم یا اولویت برای مثال بالا به این صورت است:

+

توجه داشته باشید که حق تقدم برای هر کدام از ویژگیها است نه برای کل مجموعه.

+ +

E دارای بیشترین الویت برای اینکه از '!important' استفاده کرده.

+

اما توصیه میشود تا جای ممکن از این کار اجتناب کنید مگر اینکه اینکار ضرورت داشته باشد

+

اولویت بعدی با F است زیرا که از روش درون برنامه ای استفاده کرده

+

اولویت بعدی با A است زیرا که بیشتر از بقیه مشخص تر تعریف شپه

+

مشخص تر = مشخص کننده بیشتر. دارای ۳ مشخص کننده: ۱ تگ 'p' + ۱ کلاس با نام 'class1' + ۱ خاصیت 'attr="value"'

+

اولویت بعدی با C است که مشخصه یکسانی با B دارد ولی بعد از آن تعریف شده است.

+

اولویت بعدی با B

+

و در آخر D

+ +

سازگاری

+ +

بسیار از ویژگیهای CSS2 (و به تدریج CSS3) بر روی تمام مرورگرها و دستگاه ها سازگارند.اما همیشه حیاتی است که سازگاری CSS مورد استفاده خود را با مرورگر هدف چک کنید.

+ +

[QuirksMode CSS](http://www.quirksmode.org/css/) یک منبع خوب برای این کار است

+ +

برای یک تست سازگاری سریع, [CanIUse](http://caniuse.com/) منبع بزرگی برای این کار است.

+ +

منابع دیگر

+ +
    +
  • +

    [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)

    +
  • +
  • +

    [QuirksMode CSS](http://www.quirksmode.org/css/)

    +
  • +
  • +

    [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)

    +
  • +
+
+ + -- cgit v1.2.3 From 197104715e61315d7214e081fd049091b68fe9ba Mon Sep 17 00:00:00 2001 From: zlarsen Date: Fri, 9 Oct 2015 15:09:26 -0600 Subject: forth-es Adds the Spanish translation of Forth. --- es-es/forth-es.html.markdown | 226 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 226 insertions(+) create mode 100644 es-es/forth-es.html.markdown diff --git a/es-es/forth-es.html.markdown b/es-es/forth-es.html.markdown new file mode 100644 index 00000000..05dc0cc5 --- /dev/null +++ b/es-es/forth-es.html.markdown @@ -0,0 +1,226 @@ +--- +language: forth +contributors: + - ["Horse M.D.", "http://github.com/HorseMD/"] +translators: + - ["Zach Larsen", "http://zachariahlarsen.com/"] +lang: es-es +filename: learnforth-es.fs +--- + +Forth fue criado por Charles H. Moore en los 70s. Forth es un lenguaje imperativo, basado en pila y entorno de programación, siendo usado en proyectos como Open Firmware. También esta usado por NASA. + +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. + +``` +\ Este es un comentario +( Este es un comentario también pero solo esta usado cuando definiendo palabras. ) + +\ --------------------------------- Precursor ---------------------------------- + +\ Todo programación en Forth se hace manipulando el parámetro pila (mas +\ común se refiere como "el pila"). +5 2 3 56 76 23 65 \ ok + +\ estos números se añadieron al pila desde izquierda a derecho. +.s \ <7> 5 2 3 56 76 23 65 ok + +\ En Forth, todo es o una palabra o un numero. + +\ ------------------------------ Básico Aritmética ------------------------------ + +\ Aritmética (de hecho casi todas palabras que requieren datos) funciona manipulando datos +\ en el pila. +5 4 + \ ok + +\ `.` saca lo alto resulto desde el pila: +. \ 9 ok + +\ Mas ejemplos de aritmética: +6 7 * . \ 42 ok +1360 23 - . \ 1337 ok +12 12 / . \ 1 ok +13 2 mod . \ 1 ok + +99 negate . \ -99 ok +-99 abs . \ 99 ok +52 23 max . \ 52 ok +52 23 min . \ 23 ok + +\ ----------------------------- Pila Manipulación ----------------------------- + +\ Naturalmente, cuando trabajaremos con el pila, querremos algunos metidos útiles: + +3 dup - \ duplicar el primero articulo (1ra ahora igual a 2da): 3 - 3 +2 5 swap / \ intercambiar la primera con la segunda elemento: 5 / 2 +6 4 5 rot .s \ rotar los tres primero elementos: 4 5 6 +4 0 drop 2 / \ sacar el primero articulo (no imprima a la pantalla): 4 / 2 +1 2 3 nip .s \ sacar el segundo articulo (similar a drop): 1 3 + +\ ---------------------- Mas Avanzado Pila Manipulación ---------------------- + +1 2 3 4 tuck \ duplicar el primero articulo en el segundo hueco: 1 2 4 3 4 ok +1 2 3 4 over \ duplicar el segundo articulo a la primera del pila: 1 2 3 4 3 ok +1 2 3 4 2 roll \ *mover* el articulo en este posición a la primera del pila: 1 3 4 2 ok +1 2 3 4 2 pick \ *duplicar* el articulo en este posición a la primera del pila: 1 2 3 4 2 ok + +\ Cuando refiere a pila indices, ellos son basado en cero. + +\ ------------------------------ Creando Palabras -------------------------------- + +\ La `:` palabra hace que Forth entra modo de compilar hasta que se ve la `;` palabra. +: cuadrado ( n -- n ) dup * ; \ ok +5 cuadrado . \ 25 ok + +\ Podemos ver lo que hace una palabra también.: +see cuadrado \ : cuadrado dup * ; ok + +\ -------------------------------- Condicionales -------------------------------- + +\ -1 == cierto, 0 == falso. No obstante, valores que no son cero es usualmente tratado como +\ siendo cierto: +42 42 = \ -1 ok +12 53 = \ 0 ok + +\ `if` es una palabra que solamente compila. `if` `then` . +: ?>64 ( n -- n ) dup 64 > if ." Mas que 64!" then ; \ ok +100 ?>64 \ Mas que 64! ok + +\ Else: +: ?>64 ( n -- n ) dup 64 > if ." Mas que 64!" else ." Menos que 64!" then ; +100 ?>64 \ Mas que 64! ok +20 ?>64 \ Menos que 64! ok + +\ ------------------------------------ Loops ----------------------------------- + +\ `do` también es una palabra que solamente compila. +: miloop ( -- ) 5 0 do cr ." Hola!" loop ; \ ok +miloop +\ Hola! +\ Hola! +\ Hola! +\ Hola! +\ Hola! ok + +\ `do` espera dos números en el pila: el último numero y el primero numero. + +\ Podemos recibir el valor del indice mientras damos vuelta con `i`: +: uno-a-12 ( -- ) 12 0 do i . loop ; \ ok +uno-a-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok + +\ `?do` funciona similarmente, pero salta el loop si el último y primero +\ números son iguales. +: cuadrados ( n -- ) 0 ?do i cuadrado . loop ; \ ok +10 cuadrado \ 0 1 4 9 16 25 36 49 64 81 ok + +\ cambiar el "paso" con `+loop`: +: treces ( n n -- ) ?do i . 3 +loop ; \ ok +15 0 treces \ 0 3 6 9 12 ok + +\ Indefinido loops empiezan `begin` `until`: +: death ( -- ) begin ." Ya hemos llegado?" 0 until ; \ ok + +\ ---------------------------- Variables y Memoria ---------------------------- + +\ Use `variable` declarar `edad` ser un variable. +variable edad \ ok + +\ Ahora escribimos 21 a edad con la palabra `!`. +21 edad ! \ ok + +\ Por fin podemos imprimir nuestro variable usando la "leer" palabra `@`, que agregue el +\ valor a la pila, or usa `?` que lee y imprime todo juntos. +edad @ . \ 21 ok +edad ? \ 21 ok + +\ Constantes son muy similar, pero no nos importa los direcciones de memoria: +100 constant PUNTA-QUE-AQUA-HIERVA \ ok +PUNTA-QUE-AQUA-HIERVA . \ 100 ok + +\ ----------------------------------- Arrays ----------------------------------- + +\ Creando arrays es similar a variables, pero necesitamos alocar mas +\ memoria a ellos. + +\ Puede usar `2 cells allot` para crear un array que es sea 3 cédulas de tamaño: +variable minumeros 2 cells allot \ ok + +\ Inicializar todos los valores a 0 +minumeros 3 cells erase \ ok + +\ Alternativamente podemos usar `fill`: +minumeros 3 cells 0 fill + +\ o podemos saltar todo arriba y inicializar con valores específicos: +create minumeros 64 , 9001 , 1337 , \ ok (el último `,` es importante!) + +\ ...que es equivalente a: + +\ Manualmente escribiendo valores a cada indice: +64 minumeros 0 cells + ! \ ok +9001 minumeros 1 cells + ! \ ok +1337 minumeros 2 cells + ! \ ok + +\ Leyendo valores en particular array indices: +0 cells minumeros + ? \ 64 ok +1 cells minumeros + ? \ 9001 ok + +\ Podemos simplificar un poco cuando hacemos una palabra que ayuda cuando manipulando arrays: +: de-arr ( n n -- n ) cells + ; \ ok +minumeros 2 de-arr ? \ 1337 ok + +\ Que podemos usar cuando escribimos también: +20 minumeros 1 de-arr ! \ ok +minumeros 1 de-arr ? \ 20 ok + +\ ------------------------------ El Pila de Regreso ------------------------------ + +\ El pila de regreso se usa para retener punteros a cosas cuando palabras están +\ ejecutando otras palabras como loops. + +\ Ya hemos visto un uso de esto: `i`, que duplica el primero del pila +\ de regreso. `i` es equivalente a `r@`. +: miloop ( -- ) 5 0 do r@ . loop ; \ ok + +\ También como leyendo, podemos agregar al pila de regreso y sacarlo: +5 6 4 >r swap r> .s \ 6 5 4 ok + +\ NOTA: Porque Forth usa el pila de regreso por punteros de palabras, `>r` debe +\ siempre ser seguido por un `r>`. + +\ ------------------------- Flotante Punto Operaciones -------------------------- + +\ La mayoría Forths evitan el uso de flotante punto operaciones. +8.3e 0.8e f+ f. \ 9.1 ok + +\ Usualmente agregamos al frente palabras con 'f' cuando usando flotantes: +variable miflotantevar \ ok +4.4e miflotantevar f! \ ok +miflotantevar f@ f. \ 4.4 ok + +\ --------------------------------- Notas al Final -------------------------------- + +\ Usando una palabra que no existe vaciara el pila. No obstante, también hay una palabra +\ específicamente por esto: +clearstack + +\ vaciar la pantalla: +page + +\ Cargando Forth archivos: +\ s" archivodeforth.fs" included + +\ Puede listar cada palabra en el diccionario de Forth (pero es una lista gigante!): +\ words + +\ Terminando Gforth: +\ bye + +``` + +##Listo Para Mas? + +* [Starting Forth](http://www.forth.com/starting-forth/) +* [Simple Forth](http://www.murphywong.net/hello/simple.htm) +* [Thinking Forth](http://thinking-forth.sourceforge.net/) -- cgit v1.2.3 From 97ce7f1608f5bf32329e6a908a02193b6289d51c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9sar=20Su=C3=A1rez?= Date: Sat, 10 Oct 2015 12:56:25 +0200 Subject: Translation to Spanish if the article about Hack --- es-es/hack-es.html.markdown | 307 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 307 insertions(+) create mode 100644 es-es/hack-es.html.markdown diff --git a/es-es/hack-es.html.markdown b/es-es/hack-es.html.markdown new file mode 100644 index 00000000..1059117a --- /dev/null +++ b/es-es/hack-es.html.markdown @@ -0,0 +1,307 @@ +--- +language: Hack +contributors: + - ["Stephen Holdaway", "https://github.com/stecman"] + - ["David Lima", "https://github.com/davelima"] +translators: + - ["César Suárez", "https://github.com/csuarez"] +lang: es-es +filename: learnhack-es.hh +--- + +Hack es un superconjunto de PHP que se ejecuta en una máquina virtual llamada HHVM. Hack es casi totalmente compatible con código PHP ya existente y añade varias características típicas de los lenguajes de programación estáticamente tipados. + +En este artículo sólo se cubren las características específicas de Hack. Los detalles sobre la sintaxis de PHP están en el [artículo sobre PHP](http://learnxinyminutes.com/docs/php/) de esta misma web. + +```php +id = $id; + } +} + + +// Funciones anónimas concisas (lambdas) +$multiplier = 5; +array_map($y ==> $y * $multiplier, [1, 2, 3]); + + +// Genéricos +class Box +{ + protected T $data; + + public function __construct(T $data) { + $this->data = $data; + } + + public function getData(): T { + return $this->data; + } +} + +function openBox(Box $box) : int +{ + return $box->getData(); +} + + +// Shapes +// +// Hack añade el concepto de shape para definir estructuras similares a +// vectores, pero con un conjunto de claves garantizado y tipado +type Point2D = shape('x' => int, 'y' => int); + +function distance(Point2D $a, Point2D $b) : float +{ + return sqrt(pow($b['x'] - $a['x'], 2) + pow($b['y'] - $a['y'], 2)); +} + +distance( + shape('x' => -1, 'y' => 5), + shape('x' => 2, 'y' => 50) +); + + +// Alias de tipos +// +// Hack permite crear alias para hacer que los tipos complejos sean más legibles +newtype VectorArray = array>; + +// Una tupla que contiene dos enteros +newtype Point = (int, int); + +function addPoints(Point $p1, Point $p2) : Point +{ + return tuple($p1[0] + $p2[0], $p1[1] + $p2[1]); +} + +addPoints( + tuple(1, 2), + tuple(5, 6) +); + + +// Enumerados de primera clase +enum RoadType : int +{ + Road = 0; + Street = 1; + Avenue = 2; + Boulevard = 3; +} + +function getRoadType() : RoadType +{ + return RoadType::Avenue; +} + + +// Promoción de argumentos en constructores +// +// Para evitar repetir una y otra vez la definición de constructores que +// sólo asignan propiedades, Hack añade una sintaxis concisa para definir +// propiedades junto al constructor. +class ArgumentPromotion +{ + public function __construct(public string $name, + protected int $age, + private bool $isAwesome) {} +} + +class WithoutArgumentPromotion +{ + public string $name; + + protected int $age; + + private bool $isAwesome; + + public function __construct(string $name, int $age, bool $isAwesome) + { + $this->name = $name; + $this->age = $age; + $this->isAwesome = $isAwesome; + } +} + + +// Multitarea cooperativa +// +// "async" y "await" son dos palabras claves nuevas para realizar multi-tarea. +// Esto no implica que se usen hilos, sólo permiten transferir el control de la +// ejecución. +{ + for ($i = $start; $i <= $end; $i++) { + echo "$i "; + + // Da a otras tareas la oportunidad de hacer algo + await RescheduleWaitHandle::create(RescheduleWaitHandle::QUEUE_DEFAULT, 0); + } +} + +// Esto imprime "1 4 7 2 5 8 3 6 9" +AwaitAllWaitHandle::fromArray([ + cooperativePrint(1, 3), + cooperativePrint(4, 6), + cooperativePrint(7, 9) +])->getWaitHandle()->join(); + + +// Atributos +// +// Los atributos son una especie de metadatos para funciones. Hack implementa +// algunos atributos especiales para introducir esta característica. + +// El atributo especial __Memoize hace que el resultado de la función se cacheé. +<<__Memoize>> +function doExpensiveTask() : ?string +{ + return file_get_contents('http://example.com'); +} + +// Esta función se va a ejecutar sólo una vez: +doExpensiveTask(); +doExpensiveTask(); + + +// El atributo __ConsistentConstruct indica al comprobador de tipos de Hack que +// asegure que la signatura de __construct sea la misma para todas las +// subclases. +<<__ConsistentConstruct>> +class ConsistentFoo +{ + public function __construct(int $x, float $y) + { + // ... + } + + public function someMethod() + { + // ... + } +} + +class ConsistentBar extends ConsistentFoo +{ + public function __construct(int $x, float $y) + { + // El comprobador de tipos de Hack fuerza que los constructores de + // los padres sean llamados. + parent::__construct($x, $y); + + // ... + } + + // La anotación __Override es un atributo opcional para que el comprobador + // de tipos fuerce que ese método esté sobrecargando un método de un padre + // o de un trait. Sino, fallará. + <<__Override>> + public function someMethod() + { + // ... + } +} + +class InvalidFooSubclass extends ConsistentFoo +{ + // Este constructor no coincide con el padre y causará el siguiente error: + // + // "This object is of type ConsistentBaz. It is incompatible with this + // object of type ConsistentFoo because some of their methods are + // incompatible" + public function __construct(float $x) + { + // ... + } + + // Usando la anotación __Override en un método que no sobrecarga nada se + // producirá el siguiente error: + // + // "InvalidFooSubclass::otherMethod() is marked as override; no non-private + // parent definition found or overridden parent is defined in non-> + public function otherMethod() + { + // ... + } +} + + +// Los traits pueden implementar interfaces (PHP no soporta esto). +interface KittenInterface +{ + public function play() : void; +} + +trait CatTrait implements KittenInterface +{ + public function play() : void + { + // ... + } +} + +class Samuel +{ + use CatTrait; +} + + +$cat = new Samuel(); +$cat instanceof KittenInterface === true; // True + +``` + +## Más información + +Para obtener una explicación más detallada de las características que añade Hack a PHP visita la página de [referencia de Hack](http://docs.hhvm.com/manual/en/hacklangref.php) o la [página oficial de Hack](http://hacklang.org/) para información de caracter más general. + +Visita la [página oficial de HHVM](http://hhvm.com/) para ver las instrucciones de su instalación. + +También puedes visitar la [sección de características de PHP no soportadas por Hack](http://docs.hhvm.com/manual/en/hack.unsupported.php) para más detalles sobre la retrocompatibilidad entre Hack y PHP. -- cgit v1.2.3 From 2f1d29ce8064fe3f920f9d1429b9e5c9c228f5d4 Mon Sep 17 00:00:00 2001 From: Martin Schimandl Date: Sat, 10 Oct 2015 17:50:55 +0200 Subject: First version of german translation of Lua --- de-de/lua-de.html.markdown | 426 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 426 insertions(+) create mode 100644 de-de/lua-de.html.markdown diff --git a/de-de/lua-de.html.markdown b/de-de/lua-de.html.markdown new file mode 100644 index 00000000..875629ad --- /dev/null +++ b/de-de/lua-de.html.markdown @@ -0,0 +1,426 @@ +--- +language: Lua +contributors: + - ["Tyler Neylon", "http://tylerneylon.com/"] +translators: + - ["Martin Schimandl", "https://github.com/Git-Jiro"] +filename: learnlua-de.lua +--- + +```lua +-- Zwei Gedankenstriche starten ein einzeiliges Kommentar. + +--[[ + Fügt man zwei '[' und ']' hinzu, + erzeugt man ein mehrzeiliges Kommentar. +--]] +-------------------------------------------------------------------------------- +-- 1. Variablen und Fluß-Kontrolle. +-------------------------------------------------------------------------------- + +num = 42 -- All Nummern sind vom Typ: Double. +-- Werd nicht nervös, 64-Bit Double haben 52 Bits zum Speichern von exakten +-- Ganzzahlen; Maschinen-Genauigkeit ist kein Problem für Ganzzahlen kleiner als +-- 52 Bit. + +s = 'walternate' -- Unveränderliche Zeichenkette wie by Python. +t = "Doppelte Anführungszeichen sind auch OK" +u = [[ Doppelte eckige Klammern + beginnen und beenden + mehrzeilige Zeichenketten.]] +t = nil -- Undefineren von t; Lua hat Garbage Collection. + +-- Blöcke werden durch Schlüsselwörter markiert wie do/end: +while num < 50 do + num = num + 1 -- Keine Operatoren wie ++ oder += +end + +-- If Bedingungen: +if num > 40 then + print('over 40') +elseif s ~= 'walternate' then -- ~= ist ungleich + -- Gleichheits-Check == wie bei Python; OK für Zeichenketten. + io.write('not over 40\n') -- Standard ist stdout. +else + -- Variablen sind standardmäßig global. + thisIsGlobal = 5 -- Camel case ist üblich. + + -- So macht man eine Variable lokal: + local line = io.read() -- Lies die nächste Zeile von stdin. + + -- Zeichenketten zusammenführen mit dem .. Operator: + print('Winter is coming, ' .. line) +end + +-- Undefinierte Variablen geben nil zurück. +-- Das ist kein Fehler: +foo = anUnknownVariable -- Nun ist foo = nil. + +aBoolValue = false + +-- Nur nil und false sind unwahr; 0 and '' sind wahr! +if not aBoolValue then print('was false') end + +-- 'or' und 'and' sind "kurz-geschlossen". Das ist so ähnlich wie der a?b:c +-- operator in C/js: +-- in C/js: +ans = aBoolValue and 'yes' or 'no' --> 'no' + +karlSum = 0 +for i = 1, 100 do -- Ein Bereich inkludiert beide Enden. + karlSum = karlSum + i +end + +-- Verwende "100, 1, -1" als Breich für Countdowns: +fredSum = 0 +for j = 100, 1, -1 do fredSum = fredSum + j end + +-- Im Allgemeinen besteht ein Bereich aus: Anfang, Ende, [, Schrittweite]. + +-- Ein anderes Schleifen-Konstrukt: +repeat + print('Der Weg der Zukunft') + num = num - 1 +until num == 0 + +-------------------------------------------------------------------------------- +-- 2. Funktionen. +-------------------------------------------------------------------------------- + +function fib(n) + if n < 2 then return n end + return fib(n - 2) + fib(n - 1) +end + +-- Closures und anonyme Funktionen sind ok: +function adder(x) + -- Die zurückgegbe Funktion wird erzeugt wenn addr aufgerufen wird und merkt + -- sich den Wert von x: + return function (y) return x + y end +end +a1 = adder(9) +a2 = adder(36) +print(a1(16)) --> 25 +print(a2(64)) --> 100 + +-- Rückgabewerte. Funktions-Aufrufe und Zuweisungen funktionieren all mit +-- Listen die nicht immer gleich lang sein müssen. Überzählige Empfanger +-- bekommen nil; überzählige Sende werden entfernt. + +x, y, z = 1, 2, 3, 4 +-- Nun ist x = 1, y = 2, z = 3, und 4 wird entfernt. + +function bar(a, b, c) + print(a, b, c) + return 4, 8, 15, 16, 23, 42 +end + +x, y = bar('zaphod') --> prints "zaphod nil nil" +-- Nun ist x = 4, y = 8, die Werte 15..42 werden entfernt. + +-- Funktionen sind erste Klasse, und können lokal oder global sein. +-- Das ist alles das Gleiche: +function f(x) return x * x end +f = function (x) return x * x end + +-- Und diese auch: +local function g(x) return math.sin(x) end +local g = function(x) return math.sin(x) end +-- Äquivalent zu local function g(x)..., außer das Referenzen auf g im +-- Funktions-Körper nicht wie erwartet funktionieren. +local g; g = function (x) return math.sin(x) end +-- Die 'local g' Deklaration macht G-Selbst-Referenzen OK. + +-- Nebenbei gesagt, Trigonometrie-Funktionen verwenden Radianten. + +-- Funktionsaufrufe mit nur einem Zeichenketten-Parameter brauch keine runden +-- Klammern. +print 'hello' -- Works fine. + +-- Funktionsaufruge mit einem Tabellen-Parameter brauchen auch keine runden +-- Klammern. Mehr zu Tabellen später. +print {} -- Works fine too. + +-------------------------------------------------------------------------------- +-- 3. Tabellen. +-------------------------------------------------------------------------------- + +-- Tabellen sind die einzige zusammengesetzte Struktur in Lua. Sie sind +-- assoziative Arrays. Sie sind so ähnlich wie PHP arrays oder JavaScript +-- Objekte. Sie sind Hash-Lookup-Dictionaries die auch als Listen verwendet +-- werden können. + +-- Verwenden von Tabellen als Dictionaries oder Maps: +-- Using tables as dictionaries / maps: + +-- Dict lieterale haben standardmäßig Zeichenketten-Schlüssel: +t = {key1 = 'value1', key2 = false} + +-- Zeichenketten-Schlüssel verwenden ein JavaScript ähnliche Punkt-Notation. +print(t.key1) -- Ausgabe 'value1'. +t.newKey = {} -- Neues Schlüssel/Wert Paar hinzufügen. +t.key2 = nil -- key2 aus der Tabelle entfernen. + +-- Literale notation für jeden (nicht-nil) Wert als Schlüssel: +u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} +print(u[6.28]) -- ausgabe "tau" + +-- Schlüssel-Vergleiche funktionieren per Wert für Nummern und Zeichenketten, +-- aber über die Identität bei Tabellen. +a = u['@!#'] -- Nun ist a = 'qbert'. +b = u[{}] -- Wir würden 1729 erwarten, aber es ist nil: +-- b = nil weil der Lookup fehlschlägt. Er schlägt Fehl, weil der Schlüssel +-- den wir verwendet haben nicht das gleiche Objekt ist das wir verwendet +-- haben um den original Wert zu speichern. Zahlen und Zeichnkette sind daher +-- die praktischeren Schlüssel. + +-- Eine Funktion mit nur einem Tabellen-Parameter benötigt keine Klammern. +function h(x) print(x.key1) end +h{key1 = 'Sonmi~451'} -- Prints 'Sonmi~451'. + +for key, val in pairs(u) do -- Tabellen-Interation. + print(key, val) +end + +-- _G ist eine spezielle Tabelle die alles Globale enthält. +print(_G['_G'] == _G) -- Ausgabe 'true'. + +-- Verwenden von Tabellen als Listen/Arrays: + +-- Listen-Literale verwenden implizit Ganzzahlen als Schlüssel: +v = {'value1', 'value2', 1.21, 'gigawatts'} +for i = 1, #v do -- #v ist die Größe von v für Listen. + print(v[i]) -- Indices beginnen mit 1 !! SO VERRÜCKT! +end +-- Eine 'Liste' ist kein echter Typ. v ist nur eine Tabelle mit fortlaufenden +-- Ganzzahlen als Schlüssel, behandelt wie eine Liste. + +-------------------------------------------------------------------------------- +-- 3.1 Metatabellen und Metamethoden +-------------------------------------------------------------------------------- + +-- Eine Tabelle kann eine Metatabelle haben die ihr so etwas wie +-- Tabellen-Operator-Überladungs-Verhalten verleiht. Später sehen wir wie +-- Metatabellen js-prototypen artiges Verhalten unterstützen. + +f1 = {a = 1, b = 2} -- Repräsentiert den Bruch a/b. +f2 = {a = 2, b = 3} + +-- Dies würde Fehlschlagen: +-- s = f1 + f2 + +metafraction = {} +function metafraction.__add(f1, f2) + local sum = {} + sum.b = f1.b * f2.b + sum.a = f1.a * f2.b + f2.a * f1.b + return sum +end + +setmetatable(f1, metafraction) +setmetatable(f2, metafraction) + +s = f1 + f2 -- Rufe __add(f1, f2) vom der Metatabelle von f1 auf + +-- f1 und f2 haben keine Schlüssel für ihrer Metatabellen, anders als bei js +-- Prototypen. Daher muss mithilfe von getmetatable(f1) darauf zugegriffen +-- werden. Eine Metatabelle ist wie eine normale Tabelle mit Schlüsseln die +-- Lua bekannt sind, so wie __add. + + +-- Die nächste Zeile schlägt fehl weil s keine Metatabelle hat: +-- t = s + s +-- Mihilfe von Klassen ähnlichen Mustern kann das gelöst werden. +-- Siehe weiter unten. + +-- Ein __index einer Metatabelle überlädt Punkt-Lookups: +defaultFavs = {animal = 'gru', food = 'donuts'} +myFavs = {food = 'pizza'} +setmetatable(myFavs, {__index = defaultFavs}) +eatenBy = myFavs.animal -- Funktioniert dank Metatabelle! + +-------------------------------------------------------------------------------- +-- Direkte Tabellen-Lookups die fehlschlagen werden mithilfe von __index der +-- Metatabelle wiederholt. Das geschieht rekursiv. + +-- __index kann auch eine Funktion mit der Form function(tbl, key) sein. +-- Damit kann man Lookups weiter anpassen. + +-- Werte wie __index,add, .. werden Metamethoden genannt. +-- Vollständige Liste aller Metamethoden. + +-- __add(a, b) für a + b +-- __sub(a, b) für a - b +-- __mul(a, b) für a * b +-- __div(a, b) für a / b +-- __mod(a, b) für a % b +-- __pow(a, b) für a ^ b +-- __unm(a) für -a +-- __concat(a, b) für a .. b +-- __len(a) für #a +-- __eq(a, b) für a == b +-- __lt(a, b) für a < b +-- __le(a, b) für a <= b +-- __index(a, b) für a.b +-- __newindex(a, b, c) für a.b = c +-- __call(a, ...) für a(...) + +-------------------------------------------------------------------------------- +-- 3.2 Klassen-Artihe Tabellen und vererbung. +-------------------------------------------------------------------------------- + +-- Klassen sind in Lua nicht eingebaut; es gibt verschieden Wege sie mithilfe +-- von Tabellen und Metatabellen zu erzeugen. + +-- Die Erklärund des Beispiels erfolgt unterhalb. + +Dog = {} -- 1. + +function Dog:new() -- 2. + local newObj = {sound = 'woof'} -- 3. + self.__index = self -- 4. + return setmetatable(newObj, self) -- 5. +end + +function Dog:makeSound() -- 6. + print('I say ' .. self.sound) +end + +mrDog = Dog:new() -- 7. +mrDog:makeSound() -- 'I say woof' -- 8. + +-- 1. Dog verhält sich wie eine Klasse; Ist aber eine Tabelle. +-- 2. "function tablename:fn(...)" ist das gleiche wie +-- "function tablename.fn(self, ...)", Der : fügt nur ein Argument namens +-- self hinzu. Siehe 7 & 8 um zu sehen wie self seinen Wert bekommt. +-- 3. newObj wird eine Instanz von Dog. +-- 4. "self" ist die zu Instanzierende Klasse. Meisterns ist self = Doh, aber +-- dies kann durch Vererbung geändert werden. newObj bekommt die Funktionen +-- von self wenn wir die Metatabelle von newObj und __index von self auf +-- self setzen. +-- 5. Zur Erinnerung: setmetatable gibt sein erstes Argument zurück. +-- 6. Der Doppelpunkt funktioniert wie bei 2, aber dieses Mal erwarten wir das +-- self eine Instanz ist und keine Klasse. +-- 7. Das Selbe wie Dog.new(Dog), also self = Dog in new(). +-- 8. Das Selbe wie mrDog.makeSound(mrDog); self = mrDog. + +-------------------------------------------------------------------------------- + +-- Vererbungs-Beispiel: + +LoudDog = Dog:new() -- 1. + +function LoudDog:makeSound() + local s = self.sound .. ' ' -- 2. + print(s .. s .. s) +end + +seymour = LoudDog:new() -- 3. +seymour:makeSound() -- 'woof woof woof' -- 4. + +-------------------------------------------------------------------------------- +-- 1. LoudDog bekommt die Methoden und Variablen von Dog. +-- 2. self hat einen 'sound' Schlüssel von new(), siehe 3. +-- 3. Das Gleiche wie "LoudDog.new(LoudDog)", und umgewandelt zu "Dog.new(LoudDog)" +-- denn LoudDog hat keinen 'new' Schlüssel, aber "__index = Dog" steht in der +-- Metatabelle. +-- Ergebnis: Die Metatabelle von seymour ist LoudDog und "LoudDog.__index = Dog". +-- Daher ist seymour.key gleich seymour.key, LoudDog.key, Dog.key, je nacdem +-- welche Tabelle als erstes einen passenden Schlüssel hat. +-- 4. Der 'makeSound' Schlüssel wird in LoudDog gefunden: Das ist das Gleiche +-- wie "LoudDog.makeSound(seymour)". + +-- Wenn nötig, sieht new() eine Sub-Klasse genau so aus wie new() der +-- Basis-Klasse: +function LoudDog:new() + local newObj = {} + -- set up newObj + self.__index = self + return setmetatable(newObj, self) +end + +-------------------------------------------------------------------------------- +-- 4. Module. +-------------------------------------------------------------------------------- + + +--[[ Dieser Abschnitt ist auskommentiert damit der Rest des Skripts lauffähig +-- bleibt. +``` + +```lua +-- Angenommen mod.lua sieht so aus: +local M = {} + +local function sayMyName() + print('Hrunkner') +end + +function M.sayHello() + print('Why hello there') + sayMyName() +end + +return M + +-- Eine andere Datei könnte die Funktionen in mod.lua so verwenden: +local mod = require('mod') -- Führe mod.lua aus. + +-- require ist der Standard-Weg um Module zu inkludieren. +-- require verhält sich wie: (Wenn nicht gecached wird; siehe später) +local mod = (function () + +end)() +-- Es ist als ob mod.lua eine Funktion wäre, sodass lokale Variablen in +-- mod.lua ausserhalb unsichtbar sind. + +-- Das funktioniert weil mod hier ist M in mod.lua: +mod.sayHello() -- Says hello to Hrunkner. + +-- Das ist Falsch: syMyName existiert nur in mod.lua: +mod.sayMyName() -- error + +-- Der Rückgabe-Wert von require wird zwischengespeichert. Sodass module nur +-- einmal abgearbeitet werden, auch wenn sie mit require öfters eingebunden +-- werden. + +-- Nehmen wir an mod2.lua enthält "print('Hi!')". +local a = require('mod2') -- Ausgabe Hi! +local b = require('mod2') -- Keine Ausgabe; a=b. + +-- dofile ist wie require aber ohne Zwischenspeichern. +dofile('mod2') --> Hi! +dofile('mod2') --> Hi! (läuft nochmal, nicht wie require) + +-- loadfile ladet eine lua Datei aber die Datei wird noch nicht abgearbeitet. +f = loadfile('mod2') -- Sobald f() aufgerufen wird läuft mod2.lua. + +-- loadstring ist loadfile für Zeichenketten +g = loadstring('print(343)') -- Gibt eine Funktion zurück.. +g() -- Ausgabe 343; Es kam keine Ausgabe bevor hier. + +--]] + +``` +## Referenzen + +Ich war so begeistert Lua zu lernen, um damit Spiele mit Love 2D game engine zu programmieren. + +Ich habe angefangen mit BlackBulletIV's Lua for programmers. +Danach habe ich das offizielle Lua Buch gelesen: Programming in Lua + +Es kann auch hilfreich sein hier vorbeizuschauen: Lua short +reference + +Wichtige Themen die hier nicht angesprochen wurden, die Standard-Bibliotheken: + +* string library +* table library +* math library +* io library +* os library + +Übrigends, die gesamte Datei ist gültiges Lua. Speichere es als learn.lua und +starte es als "lua learn.lua" ! + +Die Erstfassung ist von tylerneylon.com, und ist auch hier verfügbar: github gist. Viel Spaß mit Lua! -- cgit v1.2.3 From c5b6113677e6d1a596d7e5ca53c642482412cacd Mon Sep 17 00:00:00 2001 From: Martin Schimandl Date: Sun, 11 Oct 2015 08:38:45 +0200 Subject: Improve grammar and correct spelling errors. --- de-de/lua-de.html.markdown | 91 +++++++++++++++++++++++----------------------- 1 file changed, 45 insertions(+), 46 deletions(-) diff --git a/de-de/lua-de.html.markdown b/de-de/lua-de.html.markdown index 875629ad..eccfcf1e 100644 --- a/de-de/lua-de.html.markdown +++ b/de-de/lua-de.html.markdown @@ -12,33 +12,33 @@ filename: learnlua-de.lua --[[ Fügt man zwei '[' und ']' hinzu, - erzeugt man ein mehrzeiliges Kommentar. + erzeugt man einen mehrzeiligen Kommentar. --]] -------------------------------------------------------------------------------- -- 1. Variablen und Fluß-Kontrolle. -------------------------------------------------------------------------------- -num = 42 -- All Nummern sind vom Typ: Double. +num = 42 -- Alle Nummern sind vom Typ: Double. -- Werd nicht nervös, 64-Bit Double haben 52 Bits zum Speichern von exakten -- Ganzzahlen; Maschinen-Genauigkeit ist kein Problem für Ganzzahlen kleiner als -- 52 Bit. -s = 'walternate' -- Unveränderliche Zeichenkette wie by Python. +s = 'walternate' -- Zeichenketten sind unveränderlich, wie bei Python. t = "Doppelte Anführungszeichen sind auch OK" u = [[ Doppelte eckige Klammern beginnen und beenden mehrzeilige Zeichenketten.]] -t = nil -- Undefineren von t; Lua hat Garbage Collection. +t = nil -- Undefineren von t; Lua hat einen Garbage Collection. --- Blöcke werden durch Schlüsselwörter markiert wie do/end: +-- Blöcke werden durch Schlüsselwörter wie do/end markiert: while num < 50 do - num = num + 1 -- Keine Operatoren wie ++ oder += + num = num + 1 -- Es gibt Keine Operatoren wie ++ oder += end -- If Bedingungen: if num > 40 then print('over 40') -elseif s ~= 'walternate' then -- ~= ist ungleich +elseif s ~= 'walternate' then -- ~= bedeutet ungleich -- Gleichheits-Check == wie bei Python; OK für Zeichenketten. io.write('not over 40\n') -- Standard ist stdout. else @@ -94,7 +94,7 @@ end -- Closures und anonyme Funktionen sind ok: function adder(x) - -- Die zurückgegbe Funktion wird erzeugt wenn addr aufgerufen wird und merkt + -- Die zurückgegebene Funktion wird erzeugt wenn addr aufgerufen wird und merkt -- sich den Wert von x: return function (y) return x + y end end @@ -103,12 +103,12 @@ a2 = adder(36) print(a1(16)) --> 25 print(a2(64)) --> 100 --- Rückgabewerte. Funktions-Aufrufe und Zuweisungen funktionieren all mit --- Listen die nicht immer gleich lang sein müssen. Überzählige Empfanger --- bekommen nil; überzählige Sende werden entfernt. +-- Rückgabewerte, Funktions-Aufrufe und Zuweisungen funktionieren alle mit +-- Listen die nicht immer gleich lang sein müssen. Überzählige Empfänger +-- bekommen nil; überzählige Sender werden ignoriert. x, y, z = 1, 2, 3, 4 --- Nun ist x = 1, y = 2, z = 3, und 4 wird entfernt. +-- Nun ist x = 1, y = 2, z = 3, und 4 wird ignoriert. function bar(a, b, c) print(a, b, c) @@ -116,30 +116,30 @@ function bar(a, b, c) end x, y = bar('zaphod') --> prints "zaphod nil nil" --- Nun ist x = 4, y = 8, die Werte 15..42 werden entfernt. +-- Nun ist x = 4, y = 8, die Werte 15..42 werden ignoriert. -- Funktionen sind erste Klasse, und können lokal oder global sein. -- Das ist alles das Gleiche: function f(x) return x * x end f = function (x) return x * x end --- Und diese auch: +-- Das auch: local function g(x) return math.sin(x) end local g = function(x) return math.sin(x) end -- Äquivalent zu local function g(x)..., außer das Referenzen auf g im -- Funktions-Körper nicht wie erwartet funktionieren. local g; g = function (x) return math.sin(x) end --- Die 'local g' Deklaration macht G-Selbst-Referenzen OK. +-- Die Deklaration 'local g' macht Selbst-Referenzen auf g OK. -- Nebenbei gesagt, Trigonometrie-Funktionen verwenden Radianten. -- Funktionsaufrufe mit nur einem Zeichenketten-Parameter brauch keine runden -- Klammern. -print 'hello' -- Works fine. +print 'hello' -- Funktioniert wunderbar. --- Funktionsaufruge mit einem Tabellen-Parameter brauchen auch keine runden --- Klammern. Mehr zu Tabellen später. -print {} -- Works fine too. +-- Funktionsaufrufe mit einem Tabellen-Parameter brauchen auch keine runden +-- Klammern. Mehr zu Tabellen kommt später. +print {} -- Funktioniert auch wunderbar. -------------------------------------------------------------------------------- -- 3. Tabellen. @@ -151,19 +151,18 @@ print {} -- Works fine too. -- werden können. -- Verwenden von Tabellen als Dictionaries oder Maps: --- Using tables as dictionaries / maps: --- Dict lieterale haben standardmäßig Zeichenketten-Schlüssel: +-- Dict-Literale haben standardmäßig Zeichenketten als Schlüssel: t = {key1 = 'value1', key2 = false} --- Zeichenketten-Schlüssel verwenden ein JavaScript ähnliche Punkt-Notation. +-- Zeichenketten-Schlüssel verwenden eine JavaScript ähnliche Punkt-Notation. print(t.key1) -- Ausgabe 'value1'. -t.newKey = {} -- Neues Schlüssel/Wert Paar hinzufügen. +t.newKey = {} -- Neues Schlüssel/Wert-Paar hinzufügen. t.key2 = nil -- key2 aus der Tabelle entfernen. -- Literale notation für jeden (nicht-nil) Wert als Schlüssel: u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} -print(u[6.28]) -- ausgabe "tau" +print(u[6.28]) -- Ausgabe "tau" -- Schlüssel-Vergleiche funktionieren per Wert für Nummern und Zeichenketten, -- aber über die Identität bei Tabellen. @@ -176,9 +175,9 @@ b = u[{}] -- Wir würden 1729 erwarten, aber es ist nil: -- Eine Funktion mit nur einem Tabellen-Parameter benötigt keine Klammern. function h(x) print(x.key1) end -h{key1 = 'Sonmi~451'} -- Prints 'Sonmi~451'. +h{key1 = 'Sonmi~451'} -- Ausgabe 'Sonmi~451'. -for key, val in pairs(u) do -- Tabellen-Interation. +for key, val in pairs(u) do -- Tabellen-Iteration. print(key, val) end @@ -193,14 +192,14 @@ for i = 1, #v do -- #v ist die Größe von v für Listen. print(v[i]) -- Indices beginnen mit 1 !! SO VERRÜCKT! end -- Eine 'Liste' ist kein echter Typ. v ist nur eine Tabelle mit fortlaufenden --- Ganzzahlen als Schlüssel, behandelt wie eine Liste. +-- Ganzzahlen als Schlüssel, die behandelt wird wie eine Liste. -------------------------------------------------------------------------------- -- 3.1 Metatabellen und Metamethoden -------------------------------------------------------------------------------- --- Eine Tabelle kann eine Metatabelle haben die ihr so etwas wie --- Tabellen-Operator-Überladungs-Verhalten verleiht. Später sehen wir wie +-- Eine Tabelle kann eine Metatabelle haben. Diese verleiht ihr so etwas wie +-- Tabellen-Operator-Überladungs-Verhalten. Später sehen wir wie -- Metatabellen js-prototypen artiges Verhalten unterstützen. f1 = {a = 1, b = 2} -- Repräsentiert den Bruch a/b. @@ -220,9 +219,9 @@ end setmetatable(f1, metafraction) setmetatable(f2, metafraction) -s = f1 + f2 -- Rufe __add(f1, f2) vom der Metatabelle von f1 auf +s = f1 + f2 -- Rufe __add(f1, f2) vom der Metatabelle von f1 auf. --- f1 und f2 haben keine Schlüssel für ihrer Metatabellen, anders als bei js +-- f1 und f2 haben keine Schlüssel für ihre Metatabellen, anders als bei js -- Prototypen. Daher muss mithilfe von getmetatable(f1) darauf zugegriffen -- werden. Eine Metatabelle ist wie eine normale Tabelle mit Schlüsseln die -- Lua bekannt sind, so wie __add. @@ -247,7 +246,7 @@ eatenBy = myFavs.animal -- Funktioniert dank Metatabelle! -- Damit kann man Lookups weiter anpassen. -- Werte wie __index,add, .. werden Metamethoden genannt. --- Vollständige Liste aller Metamethoden. +-- HIer eine vollständige Liste aller Metamethoden. -- __add(a, b) für a + b -- __sub(a, b) für a - b @@ -266,10 +265,10 @@ eatenBy = myFavs.animal -- Funktioniert dank Metatabelle! -- __call(a, ...) für a(...) -------------------------------------------------------------------------------- --- 3.2 Klassen-Artihe Tabellen und vererbung. +-- 3.2 Klassen-Artige Tabellen und Vererbung. -------------------------------------------------------------------------------- --- Klassen sind in Lua nicht eingebaut; es gibt verschieden Wege sie mithilfe +-- Klassen sind in Lua nicht eingebaut. Es gibt verschieden Wege sie mithilfe -- von Tabellen und Metatabellen zu erzeugen. -- Die Erklärund des Beispiels erfolgt unterhalb. @@ -294,7 +293,7 @@ mrDog:makeSound() -- 'I say woof' -- 8. -- "function tablename.fn(self, ...)", Der : fügt nur ein Argument namens -- self hinzu. Siehe 7 & 8 um zu sehen wie self seinen Wert bekommt. -- 3. newObj wird eine Instanz von Dog. --- 4. "self" ist die zu Instanzierende Klasse. Meisterns ist self = Doh, aber +-- 4. "self" ist die zu Instanzierende Klasse. Meistern ist self = Dog, aber -- dies kann durch Vererbung geändert werden. newObj bekommt die Funktionen -- von self wenn wir die Metatabelle von newObj und __index von self auf -- self setzen. @@ -325,12 +324,12 @@ seymour:makeSound() -- 'woof woof woof' -- 4. -- denn LoudDog hat keinen 'new' Schlüssel, aber "__index = Dog" steht in der -- Metatabelle. -- Ergebnis: Die Metatabelle von seymour ist LoudDog und "LoudDog.__index = Dog". --- Daher ist seymour.key gleich seymour.key, LoudDog.key, Dog.key, je nacdem +-- Daher ist seymour.key gleich seymour.key, LoudDog.key, Dog.key, je nachdem -- welche Tabelle als erstes einen passenden Schlüssel hat. -- 4. Der 'makeSound' Schlüssel wird in LoudDog gefunden: Das ist das Gleiche -- wie "LoudDog.makeSound(seymour)". --- Wenn nötig, sieht new() eine Sub-Klasse genau so aus wie new() der +-- Wenn nötig, sieht new() einer Sub-Klasse genau so aus wie new() der -- Basis-Klasse: function LoudDog:new() local newObj = {} @@ -374,13 +373,13 @@ end)() -- Es ist als ob mod.lua eine Funktion wäre, sodass lokale Variablen in -- mod.lua ausserhalb unsichtbar sind. --- Das funktioniert weil mod hier ist M in mod.lua: +-- Das funktioniert weil mod hier das Gleiche wie M in mod.lua ist: mod.sayHello() -- Says hello to Hrunkner. --- Das ist Falsch: syMyName existiert nur in mod.lua: -mod.sayMyName() -- error +-- Das ist Falsch: sayMyName existiert nur in mod.lua: +mod.sayMyName() -- Fehler --- Der Rückgabe-Wert von require wird zwischengespeichert. Sodass module nur +-- Der Rückgabe-Wert von require wird zwischengespeichert. Sodass Module nur -- einmal abgearbeitet werden, auch wenn sie mit require öfters eingebunden -- werden. @@ -397,14 +396,14 @@ f = loadfile('mod2') -- Sobald f() aufgerufen wird läuft mod2.lua. -- loadstring ist loadfile für Zeichenketten g = loadstring('print(343)') -- Gibt eine Funktion zurück.. -g() -- Ausgabe 343; Es kam keine Ausgabe bevor hier. +g() -- Ausgabe 343; Vorher kam keine Ausgabe. --]] ``` ## Referenzen -Ich war so begeistert Lua zu lernen, um damit Spiele mit Love 2D game engine zu programmieren. +Ich war so begeistert Lua zu lernen, damit ich Spiele mit Love 2D game engine programmieren konnte. Ich habe angefangen mit BlackBulletIV's Lua for programmers. Danach habe ich das offizielle Lua Buch gelesen: Programming in Lua @@ -412,7 +411,7 @@ Danach habe ich das offizielle Lua Buch gelesen: Lua short reference -Wichtige Themen die hier nicht angesprochen wurden, die Standard-Bibliotheken: +Wichtige Themen die hier nicht angesprochen wurden; die Standard-Bibliotheken: * string library * table library @@ -420,7 +419,7 @@ Wichtige Themen die hier nicht angesprochen wurden, die Standard-Bibliotheken: * io library * os library -Übrigends, die gesamte Datei ist gültiges Lua. Speichere es als learn.lua und -starte es als "lua learn.lua" ! +Übrigends, die gesamte Datei ist gültiges Lua. Speichere sie als learn.lua und +starte sie als "lua learn.lua" ! Die Erstfassung ist von tylerneylon.com, und ist auch hier verfügbar: github gist. Viel Spaß mit Lua! -- cgit v1.2.3 From ec813df15e46c80401db83b5719d369dc8a9ff03 Mon Sep 17 00:00:00 2001 From: Vinh Nguyen Date: Sun, 11 Oct 2015 17:24:27 +0700 Subject: Translate Ruby-ecosystem to Vietnamese --- vi-vn/ruby-ecosystem-vi.html.markdown | 148 ++++++++++++++++++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 vi-vn/ruby-ecosystem-vi.html.markdown diff --git a/vi-vn/ruby-ecosystem-vi.html.markdown b/vi-vn/ruby-ecosystem-vi.html.markdown new file mode 100644 index 00000000..518cf072 --- /dev/null +++ b/vi-vn/ruby-ecosystem-vi.html.markdown @@ -0,0 +1,148 @@ +--- +category: tool +tool: ruby ecosystem +contributors: + - ["Jon Smock", "http://github.com/jonsmock"] + - ["Rafal Chmiel", "http://github.com/rafalchmiel"] + - ["Vinh Nguyen", "http://rubydaily.net"] +lang: vi-vn +--- + +Nhìn chung các lập trình viên Ruby luôn có cách để cài đặt các phiên bản +Ruby khác nhau, quản lý các gói (hoặc gems), và quản lý các thư viện. + +## Trình quản lý Ruby + +Một vài nền tảng phải có Ruby đã được cài đặt trước hoặc có sẵn như một gói. +Số đông lập trình viên Ruby không sử dụng cái này, hoặc nếu có, họ chỉ sử +dụng chúng để bootstrap cài đặt Ruby. Thay vào đó, các lập trình viên Ruby +có xu hướng cài đặt trình quản lý Ruby để cài đặt và chuyển đổi các phiên +bản của Ruby và môi trường Ruby cho dự án của họ. + +Dưới đây là các trình quản lý môi trường Ruby nổi tiếng: + +* [RVM](https://rvm.io/) - Cài đặt và chuyển đổi các phiên bản Ruby. RVM cũng + có các khái niệm về tập các gems để quản lý môi trường dự án một + cách tốt nhất. +* [ruby-build](https://github.com/sstephenson/ruby-build) - Chỉ cài đặt các + phiên bản Ruby. Sử dụng cái này giúp cho việc cài đặt Ruby tốt hơn. +* [rbenv](https://github.com/sstephenson/rbenv) - Chỉ dùng để chuyển đổi các + phiên bản Ruby. Được sử dụng đi kèm với ruby-build. Tiện ích này sẽ giúp + cho việc dùng Ruby tốt hơn. +* [chruby](https://github.com/postmodern/chruby) - Chỉ dùng để chuyển đổi các + phiên bản Ruby. Tương tự như rbenv. Không quan tâm làm thế nào Ruby được + cài đặt. + +## Các phiên bản Ruby + +Ruby được tạo ra bởi Yukihiro "Matz" Matsumoto, người được xem như là một +[BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), mặc dầu gần +đây luôn thay đổi. Kết quả là, tham chiếu của Ruby được gọi là MRI(Matz' +Reference Implementation), và khi bạn biết về một phiên bản Ruby, nó đang +được tham chiếu để phát hành một phiên bản của MRI. + +Có ba phiên bản Ruby chính thức được dùng là: + +* 2.0.0 - Được phát hành vào tháng 2 năm 2013. Hầu hết các thư viện lớn, và +nền tảng đều hỗ trợ 2.0.0. +* 1.9.3 - Được phát hành vào tháng 10 năm 2011. Đây là phiên bản hầu hết các +lập trình viên Ruby đang dùng. [Nhưng đã không còn hỗ trợ]( + https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended + /) +* 1.8.7 - [Ruby 1.8.7 đã không còn được sử dụng]( + http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). + +Sự thay đổi giữa phiên bản 1.8.7 đến 1.9.x lớn hơn nhiều so với thay đổi từ +1.9.3 đến 2.0.0. Ví dụ, các phiên bản 1.9 giới thiệu các bảng mã và một +byecote VM. Có các dự án vẫn đang ở 1.8.7, nhưng chúng chiếm một số lượng ít +, phần lớn cộng đồng đã chuyển sang ít nhất là 1.9.2 hoặc 1.9.3 + +## Các ứng dụng Ruby + +Hệ sinh thái Ruby có rất nhiều ứng dụng, với mỗi thế mạnh độc đáo và khả +năng tương thích. Để rõ ràng hơn, sự khác nhau giữa các ứng dụng được viết +bằng các ngôn ngữ khác nhau, nhưng *chúng vẫn là Ruby*. +Mỗi ứng dụng có các hook đặc trưng và những tính năng đặc biệt, nhưng tất cả +đều chạy Ruby rất tốt. Ví dụ, JRuby được viết bằng Java, nhưng bạn không +cần biết Java để sử dụng. + +Một số ứng dụng nổi tiếng/tương thích cao: + +* [MRI](https://github.com/ruby/ruby) - Được viết bằng C, đây là ứng dụng + tham chiếu của Ruby. Nó tương thích 100%. Tất cả các phiên bản Ruby có khả + năng duy trì với MRI(xem [RubySpec](#rubyspec) bên dưới). +* [JRuby](http://jruby.org/) - Được viết bằng Java và Ruby, ứng dụng này khá + nhanh. Điểm mạnh quan trọng nhất của JRuby là JVM/Java interop, tận dụng + các công cụ, dự án và ngôn ngữ hiện có của JVM. +* [Rubinius](http://rubini.us/) - Được viết bằng ngôn ngữ chính là Ruby với + một C++ bytecode VM. Rất nhanh. Bởi vì nó được phát triển bằng chính Ruby. + +Một số ứng dụng khá nổi tiếng/tương thích: + +* [Maglev](http://maglev.github.io/) - Đứng đầu Gemstone, một Smalltalk VM. + SmallTalk có một vài tiện ích hấp dẫn, và trong dự án này đã mang nó vào + môi trường Ruby. +* [RubyMotion](http://www.rubymotion.com/) - Mang Ruby đến việc phát triển iOS. + +Một số ứng dụng tốt/tương thích: + +* [Topaz](http://topazruby.com/) - Được biết bằng RPython (sử dụng Pypy), + Topaz vẫn còn rất trẻ và chưa hoàn toàn tương thích. Nó hứa hẹn khả năng + trở thành một ứng dụng Ruby tương thích cao. +* [IronRuby](http://ironruby.net/) - Được viết bằng C# hướng đến nền tảng .NET + , IronRuby dường như đã dừng hoạt động kể từ khi Microsoft rút hỗ trợ. + +Các ứng dụng Ruby có các phiên bản riêng của mình, nhưng chúng luôn luôn +hướng đến sự một phiên bản đặc biệt của MRI cho sự tương thích. Nhiều ứng +dụng có khả năng đến các chế độ khác nhau (ví dụ, 1.8 hoặc 1.9) để hướng đến +phiên bản MRI. + +## RubySpec + +Hầu hết các ứng dụng Ruby dựa vào [RubySpec](http://rubyspec.org/). Ruby không +có thông báo chính thức, nhưng cộng đồng đã viết những specs thực thi trong +Ruby để kiểm tra sự tương thích với MRI. + +## RubyGems + +[RubyGems](http://rubygems.org/) là một cộng đồng quản lý các gói cho Ruby. +RubyGems đi kèm với Ruby, bởi vậy không cần cài đặt riêng lẻ. + +Các gói Ruby được gọi là "gems", và chúng được host bởi cộng đồng tại +RubyGems.org. Một gem chứa mã nguồn của nó và một vài mô tả, bao gồm những +thứ như phiên bản, các thư viện độc lập, các tác giả và các loại giấy phép. + +## Bundler + +[Bundler](http://bundler.io/) là một gem giải quyết độc lập. Nó sử dụng một +Gemfile để tìm kiếm các thư viện độc lập trong dự án, và sau đó sẽ lấy về +các thư viện của các thư viện độc lập này. Nó thực hiện cho đến khi việc +tải các thư viện hoàn tất, hoặc nó sẽ dừng nếu xuất hiện bất kỳ xung đột nào. + +Bundler sẽ hiển thị lỗi nếu tìm thấy bất kỳ xung đột giữa các thư viện. Ví +dụ, nếu như gem A yêu cầu gem Z có phiên bản 3 hoặc cao hơn, nhưng gem B lại +yêu cầu gem Z phiên bản 2. Bundler sẽ thông báo cho bạn sự xung đột này. +Điều này đã rất hữu ích khi nhiều gem tham chiếu các các gem khác (trong +gem này lại tham chiếu đến các gem khác nữa), có thể hình thành một đồ thị +lớn để nói. + +# Kiểm thử + +Kiểm thử là một phần lớn của Ruby. Ruby mang đến một nền tảng kiểm thử theo +kiểu Unit được gọi là minitest (hoặc TestUnit for phiên bản Ruby 1.8.x). +Có nhiều thư viện kiểm thử với các mục đích khác nhau. + +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/ + Unit.html) - Nền tảng kiểm thử theo kiểu Unit của Ruby 1.8. +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest + /rdoc/MiniTest.html) -Nền tảng kiểm thử được xây dựng cho Ruby 1.9/2.0 +* [RSpec](http://rspec.info/) - Một nền tảng kiểm thử tập trung vào sự + hoạt động. +* [Cucumber](http://cukes.info/) - Một nền tảng kiểm thử theo kiểu BDD dưới + định dạng Gherkin. + +## Be Nice + +Cộng đồng Ruby tự hào là một cộng đồng mở, đa dạng và chào đón tất cả mọi +người. Bản thân Matz là một người cực kỳ thân thiện, và các lập trình viên +Ruby rất tuyệt vời. -- cgit v1.2.3 From 1ba31a4a46a34dacdc85780e5b76507336cf456c Mon Sep 17 00:00:00 2001 From: Robson Alves Date: Mon, 12 Oct 2015 06:36:53 -0300 Subject: Create a new translate for csharp to pt-br language I started the feature to translate csharp docs to portuguese from Brazil (pt-br). --- pt-br/csharp.html.markdown | 899 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 899 insertions(+) create mode 100644 pt-br/csharp.html.markdown diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown new file mode 100644 index 00000000..1f6bea18 --- /dev/null +++ b/pt-br/csharp.html.markdown @@ -0,0 +1,899 @@ +--- +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"] + - ["Wouter Van Schandevijl", "http://github.com/laoujin"] +filename: LearnCSharp.cs +--- + +C# é uma linguagem elegante e altamente tipado orientada a objetos que permite aos desenvolvedores criarem uma variedade de aplicações seguras e robustas que são executadas no .NET Framework. + +[Read more here.](http://msdn.microsoft.com/pt-br/library/vstudio/z1zx9t92.aspx) + +```c# +// Comentário de linha única começa com // +/* +Múltipas linhas é desta forma +*/ +/// +/// Esta é uma documentação comentário XML que pode ser usado para gerar externo +/// documentação ou fornecer ajuda de contexto dentro de um IDE +/// +//public void MethodOrClassOrOtherWithParsableHelp() {} + +// Especificar qual namespace seu código irá usar +// Os namespaces a seguir são padrões do .NET Framework Class Library +using System; +using System.Collections.Generic; +using System.Dynamic; +using System.Linq; +using System.Net; +using System.Threading.Tasks; +using System.IO; + +// Mas este aqui não é : +using System.Data.Entity; +// Para que consiga utiliza-lo, você precisa adicionar novas referências +// Isso pode ser feito com o gerenciador de pacotes NuGet : `Install-Package EntityFramework` + +// Namespaces são escopos definidos para organizar o códgo em "pacotes" or "módulos" +// Usando este código a partir de outra arquivo de origem: using Learning.CSharp; +namespace Learning.CSharp +{ + // Cada .cs deve conter uma classe com o mesmo nome do arquivo + // você está autorizado a contrariar isto, mas evite por sua sanidade. + public class AprenderCsharp + { + // Sintaxe Básica - Pule para as CARACTERÍSTICAS INTERESSANTES se você ja usou Java ou C++ antes. + public static void Syntax() + { + // Use Console.WriteLine para apresentar uma linha + Console.WriteLine("Hello World"); + Console.WriteLine( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Para apresentar sem incluir uma nova linha, use Console.Write + Console.Write("Hello "); + Console.Write("World"); + + /////////////////////////////////////////////////// + // Tpos e Variáveis + // + // Declare uma variável usando + /////////////////////////////////////////////////// + + // Sbyte - Signed 8-bit integer + // (-128 <= sbyte <= 127) + sbyte fooSbyte = 100; + + // Byte - Unsigned 8-bit integer + // (0 <= byte <= 255) + byte fooByte = 100; + + // Short - 16-bit integer + // Signed - (-32,768 <= short <= 32,767) + // Unsigned - (0 <= ushort <= 65,535) + short fooShort = 10000; + ushort fooUshort = 10000; + + // Integer - 32-bit integer + int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647) + uint fooUint = 1; // (0 <= uint <= 4,294,967,295) + + // Long - 64-bit integer + 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) + // Numbers default to being int or uint depending on size. + // L is used to denote that this variable value is of type long or ulong + + // Double - Double-precision 64-bit IEEE 754 Floating Point + double fooDouble = 123.4; // Precision: 15-16 digits + + // Float - Single-precision 32-bit IEEE 754 Floating Point + float fooFloat = 234.5f; // Precision: 7 digits + // f is used to denote that this variable value is of type float + + // Decimal - a 128-bits data type, with more precision than other floating-point types, + // suited for financial and monetary calculations + decimal fooDecimal = 150.3m; + + // Boolean - true & false + bool fooBoolean = true; // or false + + // Char - A single 16-bit Unicode character + char fooChar = 'A'; + + // Strings - ao contrário dos anteriores tipos base, que são todos os tipos de valor, +            // Uma string é um tipo de referência. Ou seja, você pode configurá-lo como nulo + string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)"; + Console.WriteLine(fooString); + + // Você pode acessar todos os caracteres de string com um indexador: + char charFromString = fooString[1]; // => 'e' + // Strings são imutáveis: você não pode fazer fooString[1] = 'X'; + + // Compare strings com sua atual cultura, ignorando maiúsculas e minúsculas + string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); + + // Formatando, baseado no sprintf + string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); + + // Datas e formatações + DateTime fooDate = DateTime.Now; + Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); + + // Você pode juntar um string em mais de duas linhas com o símbolo @. Para escapar do " use "" + string bazString = @"Here's some stuff +on a new line! ""Wow!"", the masses cried"; + + // Use const ou read-only para fazer uma variável imutável + // os valores da const são calculados durante o tempo de compilação + const int HoursWorkPerWeek = 9001; + + /////////////////////////////////////////////////// + // Data Structures + /////////////////////////////////////////////////// + + // Arrays - zero indexado + // The array size must be decided upon declaration + // The format for declaring an array is follows: + // [] = new []; + int[] intArray = new int[10]; + + // Another way to declare & initialize an array + int[] y = { 9000, 1000, 1337 }; + + // Indexing an array - Accessing an element + Console.WriteLine("intArray @ 0: " + intArray[0]); + // Arrays are mutable. + intArray[1] = 1; + + // Lists + // Lists are used more frequently than arrays as they are more flexible + // The format for declaring a list is follows: + // List = new List(); + List intList = new List(); + List stringList = new List(); + List z = new List { 9000, 1000, 1337 }; // intialize + // The <> are for generics - Check out the cool stuff section + + // Lists don't default to a value; + // A value must be added before accessing the index + intList.Add(1); + Console.WriteLine("intList @ 0: " + intList[0]); + + // Others data structures to check out: + // Stack/Queue + // Dictionary (an implementation of a hash map) + // HashSet + // Read-only Collections + // Tuple (.Net 4+) + + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + Console.WriteLine("\n->Operators"); + + int i1 = 1, i2 = 2; // Shorthand for multiple declarations + + // Arithmetic is straightforward + Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 + + // Modulo + Console.WriteLine("11%3 = " + (11 % 3)); // => 2 + + // Comparison operators + 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 + + // Bitwise operators! + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR + */ + + // Incrementations + int i = 0; + Console.WriteLine("\n->Inc/Dec-rementation"); + Console.WriteLine(i++); //i = 1. Post-Incrementation + Console.WriteLine(++i); //i = 2. Pre-Incrementation + Console.WriteLine(i--); //i = 1. Post-Decrementation + Console.WriteLine(--i); //i = 0. Pre-Decrementation + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + Console.WriteLine("\n->Control Structures"); + + // If statements are c-like + int j = 10; + if (j == 10) + { + Console.WriteLine("I get printed"); + } + else if (j > 10) + { + Console.WriteLine("I don't"); + } + else + { + Console.WriteLine("I also don't"); + } + + // Ternary operators + // A simple if/else can be written as follows + // ? : + int toCompare = 17; + string isTrue = toCompare == 17 ? "True" : "False"; + + // While loop + int fooWhile = 0; + while (fooWhile < 100) + { + //Iterated 100 times, fooWhile 0->99 + fooWhile++; + } + + // Do While Loop + int fooDoWhile = 0; + do + { + // Start iteration 100 times, fooDoWhile 0->99 + if (false) + continue; // skip the current iteration + + fooDoWhile++; + + if (fooDoWhile == 50) + break; // breaks from the loop completely + + } while (fooDoWhile < 100); + + //for loop structure => for(; ; ) + for (int fooFor = 0; fooFor < 10; fooFor++) + { + //Iterated 10 times, fooFor 0->9 + } + + // For Each Loop + // foreach loop structure => foreach( in ) + // The foreach loop loops over any object implementing IEnumerable or IEnumerable + // All the collection types (Array, List, Dictionary...) in the .Net framework + // implement one or both of these interfaces. + // (The ToCharArray() could be removed, because a string also implements IEnumerable) + foreach (char character in "Hello World".ToCharArray()) + { + //Iterated over all the characters in the string + } + + // Switch Case + // A switch works with the byte, short, char, and int data types. + // It also works with enumerated types (discussed in Enum Types), + // the String class, and a few special classes that wrap + // primitive types: Character, Byte, Short, and Integer. + int month = 3; + string monthString; + switch (month) + { + case 1: + monthString = "January"; + break; + case 2: + monthString = "February"; + break; + case 3: + monthString = "March"; + break; + // You can assign more than one case to an action + // But you can't add an action without a break before another case + // (if you want to do this, you would have to explicitly add a goto case x + case 6: + case 7: + case 8: + monthString = "Summer time!!"; + break; + default: + monthString = "Some other month"; + break; + } + + /////////////////////////////////////// + // Converting Data Types And Typecasting + /////////////////////////////////////// + + // Converting data + + // Convert String To Integer + // this will throw a FormatException on failure + int.Parse("123");//returns an integer version of "123" + + // try parse will default to type default on failure + // in this case: 0 + int tryInt; + if (int.TryParse("123", out tryInt)) // Function is boolean + Console.WriteLine(tryInt); // 123 + + // Convert Integer To String + // Convert class has a number of methods to facilitate conversions + Convert.ToString(123); + // or + tryInt.ToString(); + + // Casting + // Cast decimal 15 to a int + // and then implicitly cast to long + long x = (int) 15M; + } + + /////////////////////////////////////// + // CLASSES - see definitions at end of file + /////////////////////////////////////// + public static void Classes() + { + // See Declaration of objects at end of file + + // Use new to instantiate a class + Bicycle trek = new Bicycle(); + + // Call object methods + trek.SpeedUp(3); // You should always use setter and getter methods + trek.Cadence = 100; + + // ToString is a convention to display the value of this Object. + Console.WriteLine("trek info: " + trek.Info()); + + // Instantiate a new Penny Farthing + PennyFarthing funbike = new PennyFarthing(1, 10); + Console.WriteLine("funbike info: " + funbike.Info()); + + Console.Read(); + } // End main method + + // CONSOLE ENTRY A console application must have a main method as an entry point + public static void Main(string[] args) + { + OtherInterestingFeatures(); + } + + // + // INTERESTING FEATURES + // + + // DEFAULT METHOD SIGNATURES + + public // Visibility + static // Allows for direct call on class without object + int // Return Type, + MethodSignatures( + int maxCount, // First variable, expects an int + int count = 0, // will default the value to 0 if not passed in + int another = 3, + params string[] otherParams // captures all other parameters passed to method + ) + { + return -1; + } + + // Methods can have the same name, as long as the signature is unique + // A method that differs only in return type is not unique + public static void MethodSignatures( + ref int maxCount, // Pass by reference + out int count) + { + count = 15; // out param must be assigned before control leaves the method + } + + // GENERICS + // The classes for TKey and TValue is specified by the user calling this function. + // This method emulates the SetDefault of Python + public static TValue SetDefault( + IDictionary dictionary, + TKey key, + TValue defaultItem) + { + TValue result; + if (!dictionary.TryGetValue(key, out result)) + return dictionary[key] = defaultItem; + return result; + } + + // You can narrow down the objects that are passed in + public static void IterateAndPrint(T toPrint) where T: IEnumerable + { + // We can iterate, since T is a IEnumerable + foreach (var item in toPrint) + // Item is an int + Console.WriteLine(item.ToString()); + } + + public static void OtherInterestingFeatures() + { + // OPTIONAL PARAMETERS + MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); + MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones + + // BY REF AND OUT PARAMETERS + int maxCount = 0, count; // ref params must have value + MethodSignatures(ref maxCount, out count); + + // EXTENSION METHODS + int i = 3; + i.Print(); // Defined below + + // NULLABLE TYPES - great for database interaction / return values + // any value type (i.e. not a class) can be made nullable by suffixing a ? + // ? = + int? nullable = null; // short hand for Nullable + Console.WriteLine("Nullable variable: " + nullable); + bool hasValue = nullable.HasValue; // true if not null + + // ?? is syntactic sugar for specifying default value (coalesce) + // in case variable is null + int notNullable = nullable ?? 0; // 0 + + // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is: + var magic = "magic is a string, at compile time, so you still get type safety"; + // magic = 9; will not work as magic is a string, not an int + + // GENERICS + // + var phonebook = new Dictionary() { + {"Sarah", "212 555 5555"} // Add some entries to the phone book + }; + + // Calling SETDEFAULT defined as a generic above + Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // No Phone + // nb, you don't need to specify the TKey and TValue since they can be + // derived implicitly + Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 + + // LAMBDA EXPRESSIONS - allow you to write code in line + Func square = (x) => x * x; // Last T item is the return value + Console.WriteLine(square(3)); // 9 + + // ERROR HANDLING - coping with an uncertain world + try + { + var funBike = PennyFarthing.CreateWithGears(6); + + // will no longer execute because CreateWithGears throws an exception + string some = ""; + if (true) some = null; + some.ToLower(); // throws a NullReferenceException + } + catch (NotSupportedException) + { + Console.WriteLine("Not so much fun now!"); + } + catch (Exception ex) // catch all other exceptions + { + throw new ApplicationException("It hit the fan", ex); + // throw; // A rethrow that preserves the callstack + } + // catch { } // catch-all without capturing the Exception + finally + { + // executes after try or catch + } + + // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily. + // Most of objects that access unmanaged resources (file handle, device contexts, etc.) + // implement the IDisposable interface. The using statement takes care of + // cleaning those IDisposable objects for you. + using (StreamWriter writer = new StreamWriter("log.txt")) + { + writer.WriteLine("Nothing suspicious here"); + // At the end of scope, resources will be released. + // Even if an exception is thrown. + } + + // PARALLEL FRAMEWORK + // 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(); + + // Will spin up separate threads for each request, and join on them + // before going to the next step! + 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()) + { + responses[website] = r.ContentType; + } + }); + + // This won't happen till after all requests have been completed + foreach (var key in responses.Keys) + Console.WriteLine("{0}:{1}", key, responses[key]); + + // DYNAMIC OBJECTS (great for working with other languages) + dynamic student = new ExpandoObject(); + student.FirstName = "First Name"; // No need to define class first! + + // You can even add methods (returns a string, and takes in a string) + student.Introduce = new Func( + (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); + Console.WriteLine(student.Introduce("Beth")); + + // IQUERYABLE - almost all collections implement this, which gives you a lot of + // very useful Map / Filter / Reduce style methods + var bikes = new List(); + bikes.Sort(); // Sorts the array + bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Sorts based on wheels + var result = bikes + .Where(b => b.Wheels > 3) // Filters - chainable (returns IQueryable of previous type) + .Where(b => b.IsBroken && b.HasTassles) + .Select(b => b.ToString()); // Map - we only this selects, so result is a IQueryable + + var sum = bikes.Sum(b => b.Wheels); // Reduce - sums all the wheels in the collection + + // Create a list of IMPLICIT objects based on some parameters of the bike + var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); + // Hard to show here, but you get type ahead completion since the compiler can implicitly work + // out the types above! + foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) + Console.WriteLine(bikeSummary.Name); + + // ASPARALLEL + // And this is where things get wicked - combines linq and parallel operations + var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); + // this will happen in parallel! Threads will automagically be spun up and the + // results divvied amongst them! Amazing for large datasets when you have lots of + // cores + + // LINQ - maps a store to IQueryable objects, with delayed execution + // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document + var db = new BikeRepository(); + + // execution is delayed, which is great when querying a database + var filter = db.Bikes.Where(b => b.HasTassles); // no query run + if (42 > 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality + filter = filter.Where(b => b.IsBroken); // no query run + + var query = filter + .OrderBy(b => b.Wheels) + .ThenBy(b => b.Name) + .Select(b => b.Name); // still no query run + + // Now the query runs, but opens a reader, so only populates are you iterate through + foreach (string bike in query) + Console.WriteLine(result); + + + + } + + } // End LearnCSharp class + + // You can include other classes in a .cs file + + public static class Extensions + { + // EXTENSION FUNCTIONS + public static void Print(this object obj) + { + Console.WriteLine(obj.ToString()); + } + } + + // Class Declaration Syntax: + // class { + // //data fields, constructors, functions all inside. + // //functions are called as methods in Java. + // } + + public class Bicycle + { + // Bicycle's Fields/Variables + public int Cadence // Public: Can be accessed from anywhere + { + get // get - define a method to retrieve the property + { + return _cadence; + } + set // set - define a method to set a proprety + { + _cadence = value; // Value is the value passed in to the setter + } + } + private int _cadence; + + protected virtual int Gear // Protected: Accessible from the class and subclasses + { + get; // creates an auto property so you don't need a member field + set; + } + + internal int Wheels // Internal: Accessible from within the assembly + { + get; + private set; // You can set modifiers on the get/set methods + } + + int _speed; // Everything is private by default: Only accessible from within this class. + // can also use keyword private + public string Name { get; set; } + + // Enum is a value type that consists of a set of named constants + // It is really just mapping a name to a value (an int, unless specified otherwise). + // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. + // An enum can't contain the same value twice. + public enum BikeBrand + { + AIST, + BMC, + Electra = 42, //you can explicitly set a value to a name + Gitane // 43 + } + // We defined this type inside a Bicycle class, so it is a nested type + // Code outside of this class should reference this type as Bicycle.Brand + + public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type + + // Decorate an enum with the FlagsAttribute to indicate that multiple values can be switched on + [Flags] // Any class derived from Attribute can be used to decorate types, methods, parameters etc + public enum BikeAccessories + { + None = 0, + Bell = 1, + MudGuards = 2, // need to set the values manually! + Racks = 4, + Lights = 8, + FullPackage = Bell | MudGuards | Racks | Lights + } + + // Usage: aBike.Accessories.HasFlag(Bicycle.BikeAccessories.Bell) + // Before .NET 4: (aBike.Accessories & Bicycle.BikeAccessories.Bell) == Bicycle.BikeAccessories.Bell + public BikeAccessories Accessories { get; set; } + + // Static members belong to the type itself rather then specific object. + // You can access them without a reference to any object: + // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); + public static int BicyclesCreated { get; set; } + + // readonly values are set at run time + // they can only be assigned upon declaration or in a constructor + readonly bool _hasCardsInSpokes = false; // read-only private + + // Constructors are a way of creating classes + // This is a default constructor + public Bicycle() + { + this.Gear = 1; // you can access members of the object with the keyword this + Cadence = 50; // but you don't always need it + _speed = 5; + Name = "Bontrager"; + Brand = BikeBrand.AIST; + BicyclesCreated++; + } + + // This is a specified constructor (it contains arguments) + public Bicycle(int startCadence, int startSpeed, int startGear, + string name, bool hasCardsInSpokes, BikeBrand brand) + : base() // calls base first + { + Gear = startGear; + Cadence = startCadence; + _speed = startSpeed; + Name = name; + _hasCardsInSpokes = hasCardsInSpokes; + Brand = brand; + } + + // Constructors can be chained + public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : + this(startCadence, startSpeed, 0, "big wheels", true, brand) + { + } + + // Function Syntax: + // () + + // classes can implement getters and setters for their fields + // or they can implement properties (this is the preferred way in C#) + + // Method parameters can have default values. + // In this case, methods can be called with these parameters omitted + public void SpeedUp(int increment = 1) + { + _speed += increment; + } + + public void SlowDown(int decrement = 1) + { + _speed -= decrement; + } + + // properties get/set values + // when only data needs to be accessed, consider using properties. + // properties may have either get or set, or both + private bool _hasTassles; // private variable + public bool HasTassles // public accessor + { + get { return _hasTassles; } + set { _hasTassles = value; } + } + + // You can also define an automatic property in one line + // this syntax will create a backing field automatically. + // You can set an access modifier on either the getter or the setter (or both) + // to restrict its access: + public bool IsBroken { get; private set; } + + // Properties can be auto-implemented + public int FrameSize + { + get; + // you are able to specify access modifiers for either get or set + // this means only Bicycle class can call set on Framesize + private set; + } + + // It's also possible to define custom Indexers on objects. + // All though this is not entirely useful in this example, you + // could do bicycle[0] which yields "chris" to get the first passenger or + // bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle) + private string[] passengers = { "chris", "phil", "darren", "regina" }; + + public string this[int i] + { + get { + return passengers[i]; + } + + set { + return passengers[i] = value; + } + } + + //Method to display the attribute values of this Object. + public virtual string Info() + { + return "Gear: " + Gear + + " Cadence: " + Cadence + + " Speed: " + _speed + + " Name: " + Name + + " Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") + + "\n------------------------------\n" + ; + } + + // Methods can also be static. It can be useful for helper methods + public static bool DidWeCreateEnoughBycles() + { + // Within a static method, we only can reference static class members + return BicyclesCreated > 9000; + } // If your class only needs static members, consider marking the class itself as static. + + + } // end class Bicycle + + // PennyFarthing is a subclass of Bicycle + class PennyFarthing : Bicycle + { + // (Penny Farthings are those bicycles with the big front wheel. + // They have no gears.) + + // calling parent constructor + public PennyFarthing(int startCadence, int startSpeed) : + base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra) + { + } + + protected override int Gear + { + get + { + return 0; + } + set + { + throw new InvalidOperationException("You can't change gears on a PennyFarthing"); + } + } + + public static PennyFarthing CreateWithGears(int gears) + { + var penny = new PennyFarthing(1, 1); + penny.Gear = gears; // Oops, can't do this! + return penny; + } + + public override string Info() + { + string result = "PennyFarthing bicycle "; + result += base.ToString(); // Calling the base version of the method + return result; + } + } + + // Interfaces only contain signatures of the members, without the implementation. + interface IJumpable + { + void Jump(int meters); // all interface members are implicitly public + } + + interface IBreakable + { + bool Broken { get; } // interfaces can contain properties as well as methods & events + } + + // Class can inherit only one other class, but can implement any amount of interfaces + class MountainBike : Bicycle, IJumpable, IBreakable + { + int damage = 0; + + public void Jump(int meters) + { + damage += meters; + } + + public bool Broken + { + get + { + return damage > 100; + } + } + } + + /// + /// Used to connect to DB for LinqToSql example. + /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) + /// http://msdn.microsoft.com/en-us/data/jj193542.aspx + /// + public class BikeRepository : DbContext + { + public BikeRepository() + : base() + { + } + + public DbSet Bikes { get; set; } + } +} // End Namespace +``` + +## Topics Not Covered + + * Attributes + * async/await, yield, pragma directives + * Web Development + * ASP.NET MVC & WebApi (new) + * ASP.NET Web Forms (old) + * WebMatrix (tool) + * Desktop Development + * Windows Presentation Foundation (WPF) (new) + * Winforms (old) + +## Further Reading + + * [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) + * [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) -- cgit v1.2.3 From da6fc10553b457ef0d8ceb4f8898dfb2c5ddbbdd Mon Sep 17 00:00:00 2001 From: Robson Alves Date: Mon, 12 Oct 2015 07:03:18 -0300 Subject: Include and correct csharp docs Correct the csharp doc en-us language which was written intialize to initialize and include new more translated words to pt-br language. --- csharp.html.markdown | 2 +- pt-br/csharp.html.markdown | 92 +++++++++++++++++++++++----------------------- 2 files changed, 47 insertions(+), 47 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 02650038..811c2280 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -159,7 +159,7 @@ on a new line! ""Wow!"", the masses cried"; // List = new List(); List intList = new List(); List stringList = new List(); - List z = new List { 9000, 1000, 1337 }; // intialize + List z = new List { 9000, 1000, 1337 }; // initialize // The <> are for generics - Check out the cool stuff section // Lists don't default to a value; diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown index 1f6bea18..deba2263 100644 --- a/pt-br/csharp.html.markdown +++ b/pt-br/csharp.html.markdown @@ -136,76 +136,76 @@ on a new line! ""Wow!"", the masses cried"; const int HoursWorkPerWeek = 9001; /////////////////////////////////////////////////// - // Data Structures + // Estrutura de Dados /////////////////////////////////////////////////// - // Arrays - zero indexado - // The array size must be decided upon declaration - // The format for declaring an array is follows: - // [] = new []; + // Matrizes - zero indexado + // O tamanho do array pode ser decidido ainda na declaração + // O formato para declarar uma matriz é o seguinte: + // [] = new []; int[] intArray = new int[10]; - // Another way to declare & initialize an array + // Outra forma de declarar & inicializar uma matriz int[] y = { 9000, 1000, 1337 }; - // Indexing an array - Accessing an element + // Indexando uma matriz - Acessando um elemento Console.WriteLine("intArray @ 0: " + intArray[0]); - // Arrays are mutable. + // Matriz são alteráveis intArray[1] = 1; - // Lists - // Lists are used more frequently than arrays as they are more flexible - // The format for declaring a list is follows: - // List = new List(); + // Listas + // Listas são usadas frequentemente tanto quanto matriz por serem mais flexiveis + // O formato de declarar uma lista é o seguinte: + // List = new List(); List intList = new List(); List stringList = new List(); - List z = new List { 9000, 1000, 1337 }; // intialize - // The <> are for generics - Check out the cool stuff section + List z = new List { 9000, 1000, 1337 }; // inicializar + // O <> são para genéricos - Confira está interessante seção do material - // Lists don't default to a value; - // A value must be added before accessing the index + // Lista não possuem valores padrão. + // Um valor deve ser adicionado antes e depois acessado pelo indexador intList.Add(1); Console.WriteLine("intList @ 0: " + intList[0]); - // Others data structures to check out: - // Stack/Queue - // Dictionary (an implementation of a hash map) + // Outras estruturas de dados para conferir: + // Pilha/Fila + // Dicionário (uma implementação de map de hash) // HashSet - // Read-only Collections + // Read-only Coleção // Tuple (.Net 4+) /////////////////////////////////////// - // Operators + // Operadores /////////////////////////////////////// Console.WriteLine("\n->Operators"); - int i1 = 1, i2 = 2; // Shorthand for multiple declarations + int i1 = 1, i2 = 2; // Forma curta para declarar diversas variáveis - // Arithmetic is straightforward + // Aritmética é clara Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 // Modulo Console.WriteLine("11%3 = " + (11 % 3)); // => 2 - // Comparison operators - 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 + // Comparações de operadores + Console.WriteLine("3 == 2? " + (3 == 2)); // => falso + Console.WriteLine("3 != 2? " + (3 != 2)); // => verdadeiro + Console.WriteLine("3 > 2? " + (3 > 2)); // => verdadeiro + Console.WriteLine("3 < 2? " + (3 < 2)); // => falso + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => verdadeiro + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => verdadeiro - // Bitwise operators! + // Operadores bit a bit (bitwise) /* - ~ Unary bitwise complement + ~ Unário bitwise complemento << Signed left shift >> Signed right shift & Bitwise AND - ^ Bitwise exclusive OR - | Bitwise inclusive OR + ^ Bitwise exclusivo OR + | Bitwise inclusivo OR */ - // Incrementations + // Incrementações int i = 0; Console.WriteLine("\n->Inc/Dec-rementation"); Console.WriteLine(i++); //i = 1. Post-Incrementation @@ -214,11 +214,11 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine(--i); //i = 0. Pre-Decrementation /////////////////////////////////////// - // Control Structures + // Estrutura de Controle /////////////////////////////////////// Console.WriteLine("\n->Control Structures"); - // If statements are c-like + // Declaração if é como a linguagem C int j = 10; if (j == 10) { @@ -233,9 +233,9 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine("I also don't"); } - // Ternary operators - // A simple if/else can be written as follows - // ? : + // Operador Ternário + // Um simples if/else pode ser escrito da seguinte forma + // ? : int toCompare = 17; string isTrue = toCompare == 17 ? "True" : "False"; @@ -251,25 +251,25 @@ on a new line! ""Wow!"", the masses cried"; int fooDoWhile = 0; do { - // Start iteration 100 times, fooDoWhile 0->99 + // Inicia a interação 100 vezes, fooDoWhile 0->99 if (false) - continue; // skip the current iteration + continue; // pule a intereção atual para apróxima fooDoWhile++; if (fooDoWhile == 50) - break; // breaks from the loop completely + break; // Interrompe o laço inteiro } while (fooDoWhile < 100); - //for loop structure => for(; ; ) + //estrutura de loop for => for(; ; ) for (int fooFor = 0; fooFor < 10; fooFor++) { - //Iterated 10 times, fooFor 0->9 + //Iterado 10 vezes, fooFor 0->9 } // For Each Loop - // foreach loop structure => foreach( in ) + // Estrutura do foreach => foreach( in ) // The foreach loop loops over any object implementing IEnumerable or IEnumerable // All the collection types (Array, List, Dictionary...) in the .Net framework // implement one or both of these interfaces. -- cgit v1.2.3 From 6a6ac5560f6ec2813bff60b660b21d24bd80d011 Mon Sep 17 00:00:00 2001 From: Robson Alves Date: Mon, 12 Oct 2015 07:38:30 -0300 Subject: Included new more words to pt-br --- pt-br/csharp.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown index deba2263..02098ca8 100644 --- a/pt-br/csharp.html.markdown +++ b/pt-br/csharp.html.markdown @@ -270,20 +270,20 @@ on a new line! ""Wow!"", the masses cried"; // For Each Loop // Estrutura do foreach => foreach( in ) - // The foreach loop loops over any object implementing IEnumerable or IEnumerable - // All the collection types (Array, List, Dictionary...) in the .Net framework - // implement one or both of these interfaces. - // (The ToCharArray() could be removed, because a string also implements IEnumerable) + // O laço foreach percorre sobre qualquer objeto que implementa IEnumerable ou IEnumerable + // Toda a coleção de tipos (Array, List, Dictionary...) no .Net framework + // implementa uma ou mais destas interfaces. + // (O ToCharArray() pode ser removido, por que uma string também implementa IEnumerable) foreach (char character in "Hello World".ToCharArray()) { //Iterated over all the characters in the string } // Switch Case - // A switch works with the byte, short, char, and int data types. - // It also works with enumerated types (discussed in Enum Types), - // the String class, and a few special classes that wrap - // primitive types: Character, Byte, Short, and Integer. + // Um switch funciona com os tipos de dados byte, short, char, e int. + // Isto também funcional com tipos enumeradors (discutidos em Tipos Enum), + // A classe String, and a few special classes that wrap + // tipos primitívos: Character, Byte, Short, and Integer. int month = 3; string monthString; switch (month) -- cgit v1.2.3 From bf12497636d9bcb2e5bd15e88493f2c0f95ce4a7 Mon Sep 17 00:00:00 2001 From: Robson Alves Date: Mon, 12 Oct 2015 07:59:41 -0300 Subject: Alter the header file to correct contributor --- pt-br/csharp.html.markdown | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown index 02098ca8..9934afd9 100644 --- a/pt-br/csharp.html.markdown +++ b/pt-br/csharp.html.markdown @@ -1,12 +1,9 @@ --- language: c# +filename: learnruby-ptbr.cs 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"] - - ["Wouter Van Schandevijl", "http://github.com/laoujin"] -filename: LearnCSharp.cs + - ["Robson Alves", "http://robsonalves.net/"] +lang: pt-br --- C# é uma linguagem elegante e altamente tipado orientada a objetos que permite aos desenvolvedores criarem uma variedade de aplicações seguras e robustas que são executadas no .NET Framework. -- cgit v1.2.3 From 7b0c8231822472a1e0cdf99149b02aed21a71df0 Mon Sep 17 00:00:00 2001 From: Robson Alves Date: Mon, 12 Oct 2015 08:11:19 -0300 Subject: Correct the header file name --- pt-br/csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown index 9934afd9..547f4817 100644 --- a/pt-br/csharp.html.markdown +++ b/pt-br/csharp.html.markdown @@ -1,6 +1,6 @@ --- language: c# -filename: learnruby-ptbr.cs +filename: csharp-pt.cs contributors: - ["Robson Alves", "http://robsonalves.net/"] lang: pt-br -- cgit v1.2.3 From ac4823b3871010d90604daecc5f06c09859bacc2 Mon Sep 17 00:00:00 2001 From: Bruno Volcov Date: Tue, 13 Oct 2015 11:39:54 -0300 Subject: add pt-br translation to git tags documentation --- pt-br/git-pt.html.markdown | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown index 981da503..ea3570d6 100644 --- a/pt-br/git-pt.html.markdown +++ b/pt-br/git-pt.html.markdown @@ -5,8 +5,12 @@ lang: pt-br filename: LearnGit.txt contributors: - ["Jake Prather", "http://github.com/JakeHP"] + - ["Leo Rudberg" , "http://github.com/LOZORD"] + - ["Betsy Lorton" , "http://github.com/schbetsy"] + - ["Bruno Volcov", "http://github.com/volcov"] translators: - ["Suzane Sant Ana", "http://github.com/suuuzi"] + - ["Bruno Volcov", "http://github.com/volcov"] --- Git é um sistema distribuido de gestão para código fonte e controle de versões. @@ -84,6 +88,11 @@ Um *branch* é essencialmente uma referência que aponta para o último *commit* efetuado. Na medida que são feitos novos commits, esta referência é atualizada automaticamente e passa a apontar para o commit mais recente. +### *Tag* + +Uma tag é uma marcação em um ponto específico da história. Geralmente as +pessoas usam esta funcionalidade para marcar pontos de release (v2.0, e por aí vai) + ### *HEAD* e *head* (componentes do diretório .git) *HEAD* é a referência que aponta para o *branch* em uso. Um repositório só tem @@ -196,6 +205,29 @@ $ git branch -m myBranchName myNewBranchName $ git branch myBranchName --edit-description ``` +### Tag + +Gerencia as *tags* + +```bash +# Listar tags +$ git tag +# Criar uma tag anotada. +# O parâmetro -m define uma mensagem, que é armazenada com a tag. +# Se você não especificar uma mensagem para uma tag anotada, +# o Git vai rodar seu editor de texto para você digitar alguma coisa. +$ git tag -a v2.0 -m 'minha versão 2.0' +# Mostrar informações sobre a tag +# O comando mostra a informação da pessoa que criou a tag, +# a data de quando o commit foi taggeado, +# e a mensagem antes de mostrar a informação do commit. +$ git show v2.0 +# Enviar uma tag para o repositório remoto +$ git push origin v2.0 +# Enviar várias tags para o repositório remoto +$ git push origin --tags +``` + ### checkout Atualiza todos os arquivos no diretório do projeto para que fiquem iguais -- cgit v1.2.3 From eaeff26ba2fd921bb19db2e08a84d5e17019c5bf Mon Sep 17 00:00:00 2001 From: Serban Constantin Date: Tue, 13 Oct 2015 23:19:03 +0300 Subject: fix line lengths --- ro-ro/python-ro.html.markdown | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/ro-ro/python-ro.html.markdown b/ro-ro/python-ro.html.markdown index 125ba2f4..c96e30dc 100644 --- a/ro-ro/python-ro.html.markdown +++ b/ro-ro/python-ro.html.markdown @@ -8,14 +8,16 @@ filename: learnpython-ro.py lang: ro-ro --- -Python a fost creat de Guido Van Rossum la începutul anilor '90. Python a devenit astăzi unul din -cele mai populare limbaje de programare. M-am indrăgostit de Python pentru claritatea sa sintactică. -Python este aproape pseudocod executabil. +Python a fost creat de Guido Van Rossum la începutul anilor '90. Python a +devenit astăzi unul din cele mai populare limbaje de programare. +M-am indrăgostit de Python pentru claritatea sa sintactică. Python este aproape +pseudocod executabil. -Opinia dumneavoastră este binevenită! Puteţi sa imi scrieţi la [@ociule](http://twitter.com/ociule) sau ociule [at] [google's email service] +Opinia dumneavoastră este binevenită! Puteţi sa imi scrieţi la [@ociule](http://twitter.com/ociule) +sau ociule [at] [google's email service] -Notă: Acest articol descrie Python 2.7, dar este util şi pentru Python 2.x. O versiune Python 3 va apărea -în curând, în limba engleză mai întâi. +Notă: Acest articol descrie Python 2.7, dar este util şi pentru Python 2.x. +O versiune Python 3 va apărea în curând, în limba engleză mai întâi. ```python # Comentariile pe o singură linie încep cu un caracter diez. @@ -36,7 +38,8 @@ Notă: Acest articol descrie Python 2.7, dar este util şi pentru Python 2.x. O 10 * 2 #=> 20 35 / 5 #=> 7 -# Împărţirea este un pic surprinzătoare. Este de fapt împărţire pe numere întregi şi rotunjeşte +# Împărţirea este un pic surprinzătoare. Este de fapt împărţire pe numere +# întregi şi rotunjeşte # automat spre valoarea mai mică 5 / 2 #=> 2 -- cgit v1.2.3 From bbe6bb7e6bb426bb4f5280bc862327efda4a6c5a Mon Sep 17 00:00:00 2001 From: Urban Fuchs Date: Wed, 14 Oct 2015 08:45:03 +0200 Subject: change default text in case example --- de-de/bash-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown index fb9cd9d4..e3ebfc1b 100644 --- a/de-de/bash-de.html.markdown +++ b/de-de/bash-de.html.markdown @@ -80,7 +80,7 @@ in # Liste der Fälle, die unterschieden werden sollen 0) echo "Hier ist eine Null." 1) echo "Hier ist eine Eins." - *) echo "Das ist nicht Null." + *) echo "Das ist etwas anderes." esac # loops iterieren über die angegebene Zahl von Argumenten: -- cgit v1.2.3 From 35621e75390368075fa62c01979be6c10173fcc2 Mon Sep 17 00:00:00 2001 From: Urban Fuchs Date: Wed, 14 Oct 2015 08:46:52 +0200 Subject: minor spelling fixes --- de-de/css-de.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/de-de/css-de.html.markdown b/de-de/css-de.html.markdown index 23c1df94..c31e73d2 100644 --- a/de-de/css-de.html.markdown +++ b/de-de/css-de.html.markdown @@ -149,10 +149,10 @@ selector { ## Benutzung -Speichere das CSS, das du benutzen willst mit der endung '.css'. +Speichere das CSS, das du benutzen willst, mit der Endung '.css'. ```xml - + + + + + + Everyday Italian + Giada De Laurentiis + 2005 + 30.00 + + + Harry Potter + J K. Rowling + 2005 + 29.99 + + + Learning XML + Erik T. Ray + 2003 + 39.95 + + + + + + + +computer.gif + + +``` + +* Dokumen Format sempurna x Pengesahan + +Satu dokumen XML adalah format sempurna jika ia adalah sintaksis yang betul. +Walau bagaimanapun, ia mungkin menyuntik lebih banyak kekangan dalam dokumen itu, +menggunakan definasi dokumen, seperti DTD dan Skema XML. + +Satu dokumen XML yang mana mengikut definasi dokumen dipanggil sah, +mengenai dokumen itu. + +Dengan alat ini, anda boleh menyemak data XML di luar logik aplikasi. + +```xml + + + + + + + + Everyday Italian + 30.00 + + + + + + + + + + +]> + + + + + + + + + + + +]> + + + + Everyday Italian + 30.00 + + +``` -- cgit v1.2.3 From 78693f418632a805ee7d0857a9c771615d971d88 Mon Sep 17 00:00:00 2001 From: Gabriel SoHappy Date: Thu, 22 Oct 2015 02:13:01 +0800 Subject: Initial docs for messagepack using JAVA, RUBY and NODEJS --- messagepack.html.markdown | 171 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 messagepack.html.markdown diff --git a/messagepack.html.markdown b/messagepack.html.markdown new file mode 100644 index 00000000..0ee90742 --- /dev/null +++ b/messagepack.html.markdown @@ -0,0 +1,171 @@ +--- +language: messagepack +filename: learnmessagepack.mpac +contributors: + - ["Gabriel Chuan", "https://github.com/gczh"] +--- + +MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. The benefits over other formats is that it's faster and smaller. + +In MessagePack, small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves. This makes MessagePack useful for efficient transmission over wire. + +``` + +# 0. Understanding The Structure ==== + +JSON, 40 Bytes UTF-8 + +---------------------------------------------- +| {“name“:”John Doe“,”age“:12} | +---------------------------------------------- +| {" | 7B 22 | +| name | 6E 61 6D 65 | +| ":" | 22 3A 22 | +| John Doe | 4A 6F 68 6E 20 44 6F 65 | +| "," | 22 2C 22 | +| age | 61 67 65 | +| ": | 22 3A 20 | +| 12 | 31 32 | +| } | 7D | +---------------------------------------------- + + +MessagePack, 27 Bytes UTF-8 + +---------------------------------------------- +| ‚¤name¨John Doe£age.12 | +---------------------------------------------- +| ‚¤ | 82 84 | +| name | 6E 61 6D 65 | +| ¨ | A8 | +| John Doe | 4A 6F 68 6E 20 44 6F 65 | +| £ | A3 | +| age | 61 67 65 | +| . | 0C | +| 12 | 31 32 | +---------------------------------------------- + +# 1. JAVA ==== + +""" Installing with Maven +""" + + + ... + + org.msgpack + msgpack + ${msgpack.version} + + ... + + + +""" Simple Serialization/Deserialization +""" + +// Create serialize objects. +List src = new ArrayList(); +src.add("msgpack"); +src.add("kumofs"); + +MessagePack msgpack = new MessagePack(); +// Serialize +byte[] raw = msgpack.write(src); + +// Deserialize directly using a template +List dst1 = msgpack.read(raw, Templates.tList(Templates.TString)); +System.out.println(dst1.get(0)); +System.out.println(dst1.get(1)); + +// Or, Deserialze to Value then convert type. +Value dynamic = msgpack.read(raw); +List dst2 = new Converter(dynamic) + .read(Templates.tList(Templates.TString)); +System.out.println(dst2.get(0)); +System.out.println(dst2.get(1)); + + +# 2. RUBY ==== + +""" Installing the Gem +""" + +gem install msgpack + +""" Streaming API +""" + +# serialize a 2-element array [e1, e2] +pk = MessagePack::Packer.new(io) +pk.write_array_header(2).write(e1).write(e2).flush + +# deserialize objects from an IO +u = MessagePack::Unpacker.new(io) +u.each { |obj| ... } + +# event-driven deserialization +def on_read(data) + @u ||= MessagePack::Unpacker.new + @u.feed_each(data) { |obj| ... } +end + +# 3. NODE.JS ==== + +""" Installing with NPM +""" + +npm install msgpack5 --save + +""" Using in Node +""" + +var msgpack = require('msgpack5')() // namespace our extensions + , a = new MyType(2, 'a') + , encode = msgpack.encode + , decode = msgpack.decode + +msgpack.register(0x42, MyType, mytipeEncode, mytipeDecode) + +console.log(encode({ 'hello': 'world' }).toString('hex')) +// 81a568656c6c6fa5776f726c64 +console.log(decode(encode({ 'hello': 'world' }))) +// { hello: 'world' } +console.log(encode(a).toString('hex')) +// d5426161 +console.log(decode(encode(a)) instanceof MyType) +// true +console.log(decode(encode(a))) +// { value: 'a', size: 2 } + +function MyType(size, value) { + this.value = value + this.size = size +} + +function mytipeEncode(obj) { + var buf = new Buffer(obj.size) + buf.fill(obj.value) + return buf +} + +function mytipeDecode(data) { + var result = new MyType(data.length, data.toString('utf8', 0, 1)) + , i + + for (i = 0; i < data.length; i++) { + if (data.readUInt8(0) != data.readUInt8(i)) { + throw new Error('should all be the same') + } + } + + return result +} + +``` + + +# References + +- [MessagePack](http://msgpack.org/index.html) +- [MsgPack vs. JSON: Cut your client-server exchange traffic by 50% with one line of code](http://indiegamr.com/cut-your-data-exchange-traffic-by-up-to-50-with-one-line-of-code-msgpack-vs-json/) \ No newline at end of file -- cgit v1.2.3 From a6d6be3e30a113335fe14aa6248b7b8bff5a1487 Mon Sep 17 00:00:00 2001 From: Gabriel SoHappy Date: Thu, 22 Oct 2015 02:30:37 +0800 Subject: fix double quote formatting --- messagepack.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/messagepack.html.markdown b/messagepack.html.markdown index 0ee90742..9291fffc 100644 --- a/messagepack.html.markdown +++ b/messagepack.html.markdown @@ -16,7 +16,7 @@ In MessagePack, small integers are encoded into a single byte, and typical short JSON, 40 Bytes UTF-8 ---------------------------------------------- -| {“name“:”John Doe“,”age“:12} | +| {"name":"John Doe","age":12} | ---------------------------------------------- | {" | 7B 22 | | name | 6E 61 6D 65 | -- cgit v1.2.3 From 89876929cb4181cac29c8aef149ae140a8c570be Mon Sep 17 00:00:00 2001 From: Niels van Velzen Date: Wed, 21 Oct 2015 21:19:08 +0200 Subject: Add dutch translation of JSON Add dutch translation of JSON --- nl-nl/json-nl.html.markdown | 71 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 nl-nl/json-nl.html.markdown diff --git a/nl-nl/json-nl.html.markdown b/nl-nl/json-nl.html.markdown new file mode 100644 index 00000000..906112ff --- /dev/null +++ b/nl-nl/json-nl.html.markdown @@ -0,0 +1,71 @@ +--- +language: json +filename: learnjson-nl.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] +translators: + - ["Niels van Velzen", "https://nielsvanvelzen.me"] +lang: nl-nl +--- + +Gezien JSON een zeer eenvouding formaat heeft zal dit een van de simpelste +Learn X in Y Minutes ooit zijn. + +JSON heeft volgens de specificaties geen commentaar, ondanks dat hebben de +meeste parsers support voor C-stijl (`//`, `/* */`) commentaar. +Sommige parsers staan zelfs trailing komma's toe. +(Een komma na het laatste element in een array of ahter de laatste eigenshap van een object). +Het is wel beter om dit soort dingen te vermijden omdat het niet overal zal werken. + +In het voorbeeld zal alleen 100% geldige JSON gebruikt worden. + +Data types gesupport door JSON zijn: nummers, strings, booleans, arrays, objecten en null. +Gesupporte browsers zijn: Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4. +De extensie voor JSON bestanden is ".json". De MIME type is "application/json" +Enkele nadelen van JSON zijn het gebrek een type definities en een manier van DTD. + +```json +{ + "sleutel": "waarde", + + "sleutels": "zijn altijd in quotes geplaatst", + "nummers": 0, + "strings": "Hallø, wereld. Alle unicode karakters zijn toegestaan, samen met \"escaping\".", + "boolean": true, + "niks": null, + + "groot nummer": 1.2e+100, + + "objecten": { + "commentaar": "In JSON gebruik je vooral objecten voor je strutuur", + + "array": [0, 1, 2, 3, "Arrays kunnen alles in zich hebben.", 5], + + "nog een object": { + "commentaar": "Objecten kunnen genest worden, erg handig." + } + }, + + "dwaasheid": [ + { + "bronnen van kalium": ["bananen"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternatieve stijl": { + "commentaar": "Kijk dit!" + , "De komma positie": "maakt niet uit zolang het er maar is" + , "nog meer commentaar": "wat leuk" + }, + + "dat was kort": "En nu ben je klaar, dit was alles wat je moet weten over JSON." +} +``` -- cgit v1.2.3 From 5d09bdab933a6fca3eff2227714fac2da6b1538f Mon Sep 17 00:00:00 2001 From: Niels van Velzen Date: Wed, 21 Oct 2015 21:20:33 +0200 Subject: Add dutch translation of TypeScript Add dutch translation of TypeScript --- nl-nl/typescript-nl.html.markdown | 174 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 nl-nl/typescript-nl.html.markdown diff --git a/nl-nl/typescript-nl.html.markdown b/nl-nl/typescript-nl.html.markdown new file mode 100644 index 00000000..dcea2a4d --- /dev/null +++ b/nl-nl/typescript-nl.html.markdown @@ -0,0 +1,174 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +filename: learntypescript-nl.ts +translators: + - ["Niels van Velzen", "https://nielsvanvelzen.me"] +lang: nl-nl +--- + +TypeScript is een taal gericht op het versoepelen van de ontwikkeling van +grote applicaties gemaakt in JavaScript. +TypeScript voegt veelgebruikte technieken zoals klassen, modules, interfaces, +generieken en statische typen toe aan JavaScript. +TypeScript is een superset van JavaScript: alle JavaScript code is geldige +TypeScript code waardoor de overgang van JavaScript naar TypeScript wordt versoepeld. + +Dit artikel focust zich alleen op de extra's van TypeScript tegenover [JavaScript] (../javascript-nl/). + +Om de compiler van TypeScript te kunnen proberen kun je naar de [Playground] (http://www.typescriptlang.org/Playground) gaan. +Hier kun je automatisch aangevulde code typen in TypeScript en de JavaScript variant bekijken. + +```js +// Er zijn 3 basis typen in TypeScript +var isKlaar: boolean = false; +var lijnen: number = 42; +var naam: string = "Peter"; + +// Wanneer het type onbekend is gebruik je "Any" +var nietZeker: any = 4; +nietZeker = "misschien een string"; +nietZeker = false; // Toch een boolean + +// Voor collecties zijn er "typed arrays" +var lijst: number[] = [1, 2, 3]; +// of generieke arrays +var lijst: Array = [1, 2, 3]; + +// Voor enumeraties: +enum Kleur {Rood, Groen, Blauw}; +var c: Kleur = Kleur.Groen; + +// Als laatst, "void" wordt gebruikt voor als een functie geen resultaat geeft +function groteVerschrikkelijkeMelding(): void { + alert("Ik ben een vervelende melding!"); +} + +// Functies zijn eersteklas ?, supporten de lambda "fat arrow" syntax en +// gebruiken gebruiken "type inference" + +// Het volgende is allemaal hetzelfde +var f1 = function(i: number): number { return i * i; } +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +var f4 = (i: number) => { return i * i; } +// Omdat we maar 1 lijn gebruiken hoeft het return keyword niet gebruikt te worden +var f5 = (i: number) => i * i; + +// Interfaces zijn structureel, elk object wat de eigenschappen heeft +// is een gebruiker van de interface +interface Persoon { + naam: string; + // Optionele eigenschappen worden gemarkeerd met "?" + leeftijd?: number; + // En natuurlijk functies + verplaats(): void; +} + +// Object die gebruikt maakt van de "Persoon" interface +// Kan gezien worden als persoon sinds het de naam en verplaats eigenschappen bevat +var p: Persoon = { naam: "Bobby", verplaats: () => {} }; +// Object met de optionele leeftijd eigenschap +var geldigPersoon: Persoon = { naam: "Bobby", leeftijd: 42, verplaats: () => {} }; +// Ongeldig persoon vanwege de leeftijds type +var ongeldigPersoon: Persoon = { naam: "Bobby", leeftijd: true }; + +// Interfaces kunnen ook een functie ype beschrijven +interface ZoekFunc { + (bron: string, subString: string): boolean; +} +// Alleen de parameters types zijn belangrijk, namen maken niet uit. +var mySearch: ZoekFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// Classes - leden zijn standaard publiek +class Punt { + // Eigenschappen + x: number; + + // Constructor - de publieke / prive trefwoorden in deze context zullen + // eigenschappen in de klasse kunnen aanmaken zonder ze te defineren. + // In dit voorbeeld zal "y" net als "x" gedefineerd worden met minder code. + // Standaard waardes zijn ook gesupport + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Functies + dist(): number { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Statische leden + static origin = new Punt(0, 0); +} + +var p1 = new Punt(10 ,20); +var p2 = new Punt(25); // y zal de waarde 0 krijgen + +// Overnemen +class Punt3D extends Punt { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Constructor van ouder aanroepen (Punt) + } + + // Overschrijven + dist(): number { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Modules werken ongeveer hetzelfde als namespaces +// met "." kan je submodules defineren +module Geometrie { + export class Vierkant { + constructor(public zijLengte: number = 0) { + } + + oppervlakte() { + return Math.pow(this.zijLengte, 2); + } + } +} + +var s1 = new Geometrie.Vierkant(5); + +// Local alias for referencing a module +import G = Geometrie; + +var s2 = new G.Vierkant(10); + +// Generieken +// Classes +class Tupel { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interfaces +interface Paar { + item1: T; + item2: T; +} + +// En functies +var paarNaarTupel = function(p: Paar) { + return new Tupel(p.item1, p.item2); +}; + +var tupel = paarNaarTupel({ item1: "hallo", item2: "wereld" }); + +// Refferentie naar een definitie bestand: +/// + +``` + +## Verder lezen (engels) + * [TypeScript Official website] (http://www.typescriptlang.org/) + * [TypeScript language specifications (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Source Code on GitHub] (https://github.com/Microsoft/TypeScript) + * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/) -- cgit v1.2.3 From ac7d33f319dc9a8c9e26f68f558c834aaa3267f1 Mon Sep 17 00:00:00 2001 From: Scott Fisk Date: Wed, 21 Oct 2015 16:12:49 -0500 Subject: Changed wording for comments section Changed wording for overview of comments so it would make more sense to a beginner. Corrected grammar error. --- es-es/javascript-es.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index d475cf42..fdb938a8 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -23,7 +23,9 @@ Aunque JavaScript no sólo se limita a los navegadores web: Node.js, Un proyecto [adam@brenecki.id.au](mailto:adam@brenecki.id.au). ```js -// Los comentarios son como en C. Los comentarios de una sola línea comienzan con //, +// Los comentarios en JavaScript son los mismos como comentarios en C. + +//Los comentarios de una sola línea comienzan con //, /* y los comentarios multilínea comienzan y terminan con */ -- cgit v1.2.3 From ce85711575d8b481d9de1dc8823a1e8c62211248 Mon Sep 17 00:00:00 2001 From: Arashk-A Date: Thu, 22 Oct 2015 02:16:31 +0330 Subject: Edit some translation behavior in links and codes --- fa-ir/css.html.markdown | 62 ++++++++++++++++++++++++------------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/fa-ir/css.html.markdown b/fa-ir/css.html.markdown index 7214bb04..661cc5f2 100644 --- a/fa-ir/css.html.markdown +++ b/fa-ir/css.html.markdown @@ -34,6 +34,7 @@ selector { property: value; /* more properties...*/ }

با استفاده از ستاره می توان برای همه عناصر روی صفحه استایل تعریف کرد

+ ```CSS * { color:red; } ``` @@ -45,7 +46,8 @@ selector { property: value; /* more properties...*/ } ```

شما میتوانید با استفاده از نام کلاس آنرا انتخاب کنید

-‍‍```CSS + +```CSS .some-class { } ``` @@ -67,37 +69,37 @@ selector { property: value; /* more properties...*/ } div { } ``` -

یا با استفاده از 'attr'

+

یا با استفاده از `attr`

```CSS [attr] { font-size:smaller; } ``` -

یا با استفاده از ارزشی که برای 'attr' مشخص شده

+

یا با استفاده از ارزشی که برای `attr` مشخص شده

```CSS [attr='value'] { font-size:smaller; } ``` -

با استفاده از ارزشی که برای 'attr' مشخص شده و آن ارزش با 'val' شروع میشود در CSS3

+

با استفاده از ارزشی که برای `attr` مشخص شده و آن ارزش با `val` شروع میشود در CSS3

```CSS [attr^='val'] { font-size:smaller; } ``` -

با استفاده از ارزشی که برای 'attr' مشخص شده و آن ارزش با 'ue' به پایان میرسد در CSS3

+

با استفاده از ارزشی که برای `attr` مشخص شده و آن ارزش با `ue` به پایان میرسد در CSS3

```CSS [attr$='ue'] { font-size:smaller; } ``` -

یا با انتخاب بوسیله یکی از ارزشهایی که در لیست 'otherAttr' بوسیله فاصله از هم جدا شده اند در CSS3

+

یا با انتخاب بوسیله یکی از ارزشهایی که در لیست `otherAttr` بوسیله فاصله از هم جدا شده اند در CSS3

```CSS [attr$='ue'] { font-size:smaller; } ``` -

یا ارزش('value') دقیقاً خود ارزش('value') یا بوسیله '-' که یونیکد (U+002D) از حرف بعدی جدا شود

+

یا ارزش(`value`) دقیقاً خود ارزش(`value`) یا بوسیله `-` که یونیکد (U+002D) از حرف بعدی جدا شود

```CSS [otherAttr|='en'] { font-size:smaller; } @@ -110,14 +112,14 @@ div.some-class[attr$='ue'] { } ```

CSS این امکان را به شما میدهد که یک عنصر را بوسیله والدین آن انتخاب کنید

-

برای مثال دستور زیر همه عناصری را که نام کلاس آنها '.class-name' و دارای پدر و مادری با این مشخصه 'div.some-parent' هستند را انتخاب میکند.

+

برای مثال دستور زیر همه عناصری را که نام کلاس آنها `.class-name` و دارای پدر و مادری با این مشخصه `div.some-parent` هستند را انتخاب میکند.

```CSS div.some-parent > .class-name {} ``` -

یا دستور زیر که همه عناصری را که نام کلاس آنها '.class-name' و داخل عنصری با مشخصه 'div.some-parent' هستند را در هر عمقی که باشند (یعنی فرزندی از فرزندان 'div.some-parent' باشند) انتخاب میکند.

+

یا دستور زیر که همه عناصری را که نام کلاس آنها `.class-name` و داخل عنصری با مشخصه `div.some-parent` هستند را در هر عمقی که باشند (یعنی فرزندی از فرزندان `div.some-parent` باشند) انتخاب میکند.

```CSS div.some-parent .class-name {} @@ -129,13 +131,13 @@ div.some-parent .class-name {} div.some-parent.class-name {} ``` -

دستور زیر همه عناصری را که نام کلاس آنها '.this-element' و بلافاصله بعد از عنصری با مشخصه '.i-am-before' قرار دارد را انتخاب میکند.

+

دستور زیر همه عناصری را که نام کلاس آنها `.this-element` و بلافاصله بعد از عنصری با مشخصه `.i-am-before` قرار دارد را انتخاب میکند.

```CSS .i-am-before + .this-element { } ``` -

هر خواهر یا برادری که بعد از '.i-am-before' بیاید در اینجا لازم نیست بلافاصله بعد از هم قرار بگیرند ولی باید دارای پدر و مادری یکسان باشند.

+

هر خواهر یا برادری که بعد از `.i-am-before` بیاید در اینجا لازم نیست بلافاصله بعد از هم قرار بگیرند ولی باید دارای پدر و مادری یکسان باشند.

```CSS .i-am-any-before ~ .this-element {} @@ -178,8 +180,8 @@ selector { width: 5cm; /* بر اساس سانتیمتر */ min-width: 50mm; /* بر اساس میلیمتر */ max-width: 5in; /* بر اساس اینچ. max-(width|height) */ - height: 0.2vh; /* بر اساس ارتفاع دید 'vh = نسبت به 1٪ از ارتفاع دید' (CSS3) */ - width: 0.4vw; /* بر اساس عرض دید 'vw = نسبت به 1٪ از عرض دید' (CSS3) */ + height: 0.2vh; /* بر اساس ارتفاع دید `vh = نسبت به 1٪ از ارتفاع دید` (CSS3) */ + width: 0.4vw; /* بر اساس عرض دید `vw = نسبت به 1٪ از عرض دید` (CSS3) */ min-height: 0.1vmin; /* بر اساس کوچکترین مقدار از ارتفاع یا عرض دید (CSS3) */ max-width: 0.3vmax; /* مانند مثال بالا برای بیشترین مقدار (CSS3) */ @@ -208,13 +210,13 @@ selector {

نحوه استفاده

هر دستور CSS را که می خواهید در فایلی با پسوند .css ذخیره کنید

-

حالا با استفاده از کد زیر آنرا در قسمت 'head' داخل فایل html خود تعریف کنید

+

حالا با استفاده از کد زیر آنرا در قسمت `head` داخل فایل html خود تعریف کنید

```html ``` -

یا میتوان با استفاده از تگ 'style' درون 'head' دستورات CSS را به صورت درون برنامه ای تعریف کرد اما توسیه میشود تا جای ممکن از این کار اجتناب کنید.

+

یا میتوان با استفاده از تگ `style` درون `head` دستورات CSS را به صورت درون برنامه ای تعریف کرد اما توسیه میشود تا جای ممکن از این کار اجتناب کنید.

```html +``` + +

همچنین شما میتوانید دستورات CSS را به عنوان یک مشخصه برای عنصر تعریف کنید ولی تا جای ممکن باید از این کار اجتناب کنید.

+ +```html +
+
+``` + +

حق تقدم یا اولویت

+ +

همانگونه که مشاهده کردید یک مشخصه می تواند به وسیله چندین انتخابگر انتخاب گردد.

+

و همچنین یک ویژگی میتواند چندین بار برای یک عنصر تعریف شود.

+

در این صورت یک دستور میتواند بر دستورات دیگر حق تقدم یا اولویت پیدا کند.

+ +

به مثال زیر توجه کنید:

+ +```CSS +/*A*/ +p.class1[attr='value'] + +/*B*/ +p.class1 {} + +/*C*/ +p.class2 {} + +/*D*/ +p {} + +/*E*/ +p { property: value !important; } + +``` + +

و همچنین به کد زیر:

+ +```html +

+

+ +``` +‍‍ +

حق تقدم یا اولویت برای مثال بالا به این صورت است:

+

توجه داشته باشید که حق تقدم برای هر کدام از ویژگیها است نه برای کل مجموعه.

+ +

E دارای بیشترین الویت برای اینکه از `!important` استفاده کرده.

+

اما توصیه میشود تا جای ممکن از این کار اجتناب کنید مگر اینکه اینکار ضرورت داشته باشد

+

اولویت بعدی با F است زیرا که از روش درون برنامه ای استفاده کرده

+

اولویت بعدی با A است زیرا که بیشتر از بقیه مشخص تر تعریف شپه

+

مشخص تر = مشخص کننده بیشتر. دارای ۳ مشخص کننده: ۱ تگ `p` + ۱ کلاس با نام `class1` + ۱ خاصیت `attr="value"`

+

اولویت بعدی با C است که مشخصه یکسانی با B دارد ولی بعد از آن تعریف شده است.

+

اولویت بعدی با B

+

و در آخر D

+ +

سازگاری

+ +

بسیار از ویژگیهای CSS2 (و به تدریج CSS3) بر روی تمام مرورگرها و دستگاه ها سازگارند.اما همیشه حیاتی است که سازگاری CSS مورد استفاده خود را با مرورگر هدف چک کنید.

+ +

یک منبع خوب برای این کار است

+[QuirksMode CSS](http://www.quirksmode.org/css/) + +

برای یک تست سازگاری سریع, منبع زیر میتواند کمک بزرگی برای این کار باشد.

+[CanIUse](http://caniuse.com/) + +

منابع دیگر

+ + +[Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) + +[QuirksMode CSS](http://www.quirksmode.org/css/) + +[Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) + + diff --git a/fa-ir/css.html.markdown b/fa-ir/css.html.markdown deleted file mode 100644 index 661cc5f2..00000000 --- a/fa-ir/css.html.markdown +++ /dev/null @@ -1,299 +0,0 @@ ---- -language: CSS -translators: - - ["Arashk", "https://github.com/Arashk-A"] -lang: fa-ir ---- - -

در روزهای آغازین وب هیچگونه عنصر بصری مشاهده نمیشد و محتوا به صورت متن خالی بود.

-

اما با توسعه بیشتر مرورگرها صفحات وب کاملاً تصویری نیز رایج شد

-

CSS زبان استانداردی که موجودیت آن برای حفظ جدایی بین محتوا (HTML) و نگاه و احساس از

-

صفحات وب است.

- -

به طور خلاصه, کاری که CSS انجام میدهد ارائه نحوه ایست که شما را قادر به هدف قرار دادن

-

عناصر مختلف در یک صفحه HTML کرده و امکان اختصاص خواص متفاوت بصری به آنها را میدهد.

- - -

مانند هر زبانی, CSS نسخه های زیادی دارد که در اینجا توجه ما روی CSS2.0 است. با وجودی که این نسخه جدیدترین نسخه نمیباشد اما بیشترین پشتیبانی و سازگاری را در میان نسخه های مختلف را دارد

- -

توجه: برای مشاهده برخی از نتایج جلوه های تصویری CSS به منظور یادگیری بیشتر شما باید چیزهای گوناگونی در محیطی مثل [dabblet](http://dabblet.com/) امتحان کنید. توجه اصلی این مقاله روی دستورات و برخی از نکات عمومی است.

- - -

در CSS همه توضیحات داخل ستاره-بروم نوشته میشوند زیرا CSS دستوری برای توضیحات تک خطی مثل C ندارد

- -```CSS -/* comments appear inside slash-asterisk, just like this line! - there are no "one-line comments"; this is the only comment style */ -``` - -

به طور کلی دستورات CSS بسیار ساده هستند که در آن یک انتخابگر (selector) عنصری را در روی صفحه هدف قرار میدهد.

- -```CSS -selector { property: value; /* more properties...*/ } -``` - -

با استفاده از ستاره می توان برای همه عناصر روی صفحه استایل تعریف کرد

- - -```CSS -* { color:red; } -``` - -

فرض کنید عنصری مثل این بر روی صفحه قرار دارد

- -```html -
-``` -

شما میتوانید با استفاده از نام کلاس آنرا انتخاب کنید

- - -```CSS -.some-class { } -``` - -

یا با استفاده از نام دو کلاس

- -```CSS -.some-class.class2 { } -``` - -

یا با استفاده از نام id

- -```CSS -#someId { } -``` - -

یا با استفاده از نام خود عنصر

- -```CSS -div { } -``` - -

یا با استفاده از `attr`

- -```CSS -[attr] { font-size:smaller; } -``` - -

یا با استفاده از ارزشی که برای `attr` مشخص شده

- -```CSS -[attr='value'] { font-size:smaller; } -``` - -

با استفاده از ارزشی که برای `attr` مشخص شده و آن ارزش با `val` شروع میشود در CSS3

- -```CSS -[attr^='val'] { font-size:smaller; } -``` - -

با استفاده از ارزشی که برای `attr` مشخص شده و آن ارزش با `ue` به پایان میرسد در CSS3

- -```CSS -[attr$='ue'] { font-size:smaller; } -``` - -

یا با انتخاب بوسیله یکی از ارزشهایی که در لیست `otherAttr` بوسیله فاصله از هم جدا شده اند در CSS3

- -```CSS -[attr$='ue'] { font-size:smaller; } -``` - -

یا ارزش(`value`) دقیقاً خود ارزش(`value`) یا بوسیله `-` که یونیکد (U+002D) از حرف بعدی جدا شود

- -```CSS -[otherAttr|='en'] { font-size:smaller; } -``` - -

و مهمتر از همه اینکه میتوان آنها را ترکیب کرد. نکته مهمی که در اینجا باید مد نظر داشته باشید این است که هنگام ترکیب نباید هیچگونه فاصله ای بین آنها قرار گیرد زیرا در این حالت معنای دستور تغییر میکند

- -```CSS -div.some-class[attr$='ue'] { } -``` - -

CSS این امکان را به شما میدهد که یک عنصر را بوسیله والدین آن انتخاب کنید

-

برای مثال دستور زیر همه عناصری را که نام کلاس آنها `.class-name` و دارای پدر و مادری با این مشخصه `div.some-parent` هستند را انتخاب میکند.

- -```CSS -div.some-parent > .class-name {} -``` - - -

یا دستور زیر که همه عناصری را که نام کلاس آنها `.class-name` و داخل عنصری با مشخصه `div.some-parent` هستند را در هر عمقی که باشند (یعنی فرزندی از فرزندان `div.some-parent` باشند) انتخاب میکند.

- -```CSS -div.some-parent .class-name {} -``` - -

نکته ای که در اینجا باید به آن توجه کنید این است که این رستور با فاصله ای بین نام دو کلاس همراه است و با مثال زیر که در بالا هم ذکر شد تفاوت دارد.

- -```CSS -div.some-parent.class-name {} -``` - -

دستور زیر همه عناصری را که نام کلاس آنها `.this-element` و بلافاصله بعد از عنصری با مشخصه `.i-am-before` قرار دارد را انتخاب میکند.

- -```CSS -.i-am-before + .this-element { } -``` - -

هر خواهر یا برادری که بعد از `.i-am-before` بیاید در اینجا لازم نیست بلافاصله بعد از هم قرار بگیرند ولی باید دارای پدر و مادری یکسان باشند.

- -```CSS -.i-am-any-before ~ .this-element {} -``` -

در زیر چند نمونه از شبه کلاسها را معرفی میکنیم که به شما اجازه میدهد عناصر را بر اساس رفتار آنها در صفحه انتخاب کنید.

-

برای مثال زمانی که اشاره گر ماوس روی عنصری بر روی صفحه قرار دارد.

- -```CSS -selector:hover {} -``` - -

یا زمانی از یک لینک بازید کردید.

- -```CSS -selected:visited {} -``` - -

یا زمانی از لینکی بازید نشده است.

- -```CSS -selected:link {} -``` - -

یا زمانی که روی یک عنصر ورودی متمرکز شده.

- -```CSS -selected:focus {} -``` - -

واحدها

- -```CSS -selector { - - /* واحدها اندازه */ - width: 50%; /* در اساس درصد */ - font-size: 2em; /* بر اساس اندازه font-size یعنی دو برابر اندازه فونت فعلی */ - width: 200px; /* بر اساس پیکسل */ - font-size: 20pt; /* بر اساس points (نکات) */ - width: 5cm; /* بر اساس سانتیمتر */ - min-width: 50mm; /* بر اساس میلیمتر */ - max-width: 5in; /* بر اساس اینچ. max-(width|height) */ - height: 0.2vh; /* بر اساس ارتفاع دید `vh = نسبت به 1٪ از ارتفاع دید` (CSS3) */ - width: 0.4vw; /* بر اساس عرض دید `vw = نسبت به 1٪ از عرض دید` (CSS3) */ - min-height: 0.1vmin; /* بر اساس کوچکترین مقدار از ارتفاع یا عرض دید (CSS3) */ - max-width: 0.3vmax; /* مانند مثال بالا برای بیشترین مقدار (CSS3) */ - - /* رنگها */ - background-color: #F6E; /* بر اساس short hex */ - background-color: #F262E2; /* بر اساس long hex format */ - background-color: tomato; /* بر اساس نام رنگ */ - background-color: rgb(255, 255, 255); /* بر اساس rgb */ - background-color: rgb(10%, 20%, 50%); /* بر اساس درصد rgb , (rgb percent) */ - background-color: rgba(255, 0, 0, 0.3); /* بر اساس rgba (نیمه شفاف) , (semi-transparent rgb) (CSS3) */ - background-color: transparent; /* شفاف */ - background-color: hsl(0, 100%, 50%); /* بر اساس hsl format (CSS3). */ - background-color: hsla(0, 100%, 50%, 0.3); /* بر اساس hsla ,مثل RGBAکه میتوان شفافیت را در آخر انتخاب کرد (CSS3) */ - - - /* عکسها */ - background-image: url(/path-to-image/image.jpg); /* گذاشتن نقل قول داخل url() اختیاری است*/ - - /* فونتها */ - font-family: Arial; - font-family: "Courier New"; /* اگر اسم فونت با فاصله همراه باشد باید داخل نقل قول یک یا دو نوشته شود */ - font-family: "Courier New", Trebuchet, Arial, sans-serif; /* اگر فونت اولی پیدا نشد مرورگر به سراغ نام بعدی میرود */ -} -``` - -

نحوه استفاده

- -

هر دستور CSS را که می خواهید در فایلی با پسوند .css ذخیره کنید

-

حالا با استفاده از کد زیر آنرا در قسمت `head` داخل فایل html خود تعریف کنید

- -```html - -``` - -

یا میتوان با استفاده از تگ `style` درون `head` دستورات CSS را به صورت درون برنامه ای تعریف کرد اما توسیه میشود تا جای ممکن از این کار اجتناب کنید.

- -```html - -``` - -

همچنین شما میتوانید دستورات CSS را به عنوان یک مشخصه برای عنصر تعریف کنید ولی تا جای ممکن باید از این کار اجتناب کنید.

- -```html -
-
-``` - -

حق تقدم یا اولویت

- -

همانگونه که مشاهده کردید یک مشخصه می تواند به وسیله چندین انتخابگر انتخاب گردد.

-

و همچنین یک ویژگی میتواند چندین بار برای یک عنصر تعریف شود.

-

در این صورت یک دستور میتواند بر دستورات دیگر حق تقدم یا اولویت پیدا کند.

- -

به مثال زیر توجه کنید:

- -```CSS -/*A*/ -p.class1[attr='value'] - -/*B*/ -p.class1 {} - -/*C*/ -p.class2 {} - -/*D*/ -p {} - -/*E*/ -p { property: value !important; } - -``` - -

و همچنین به کد زیر:

- -```html -

-

- -``` -‍‍ -

حق تقدم یا اولویت برای مثال بالا به این صورت است:

-

توجه داشته باشید که حق تقدم برای هر کدام از ویژگیها است نه برای کل مجموعه.

- -

E دارای بیشترین الویت برای اینکه از `!important` استفاده کرده.

-

اما توصیه میشود تا جای ممکن از این کار اجتناب کنید مگر اینکه اینکار ضرورت داشته باشد

-

اولویت بعدی با F است زیرا که از روش درون برنامه ای استفاده کرده

-

اولویت بعدی با A است زیرا که بیشتر از بقیه مشخص تر تعریف شپه

-

مشخص تر = مشخص کننده بیشتر. دارای ۳ مشخص کننده: ۱ تگ `p` + ۱ کلاس با نام `class1` + ۱ خاصیت `attr="value"`

-

اولویت بعدی با C است که مشخصه یکسانی با B دارد ولی بعد از آن تعریف شده است.

-

اولویت بعدی با B

-

و در آخر D

- -

سازگاری

- -

بسیار از ویژگیهای CSS2 (و به تدریج CSS3) بر روی تمام مرورگرها و دستگاه ها سازگارند.اما همیشه حیاتی است که سازگاری CSS مورد استفاده خود را با مرورگر هدف چک کنید.

- -

یک منبع خوب برای این کار است

-[QuirksMode CSS](http://www.quirksmode.org/css/) - -

برای یک تست سازگاری سریع, منبع زیر میتواند کمک بزرگی برای این کار باشد.

-[CanIUse](http://caniuse.com/) - -

منابع دیگر

- - -[Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) - -[QuirksMode CSS](http://www.quirksmode.org/css/) - -[Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) - - -- cgit v1.2.3 From 1bec0f608977c00757c8f5732eedce2e57bb9bc3 Mon Sep 17 00:00:00 2001 From: s-webber Date: Sun, 13 Mar 2016 10:10:06 +0000 Subject: created kotlin markdown --- kotlin.html.markdown | 321 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 321 insertions(+) create mode 100644 kotlin.html.markdown diff --git a/kotlin.html.markdown b/kotlin.html.markdown new file mode 100644 index 00000000..ae0123a7 --- /dev/null +++ b/kotlin.html.markdown @@ -0,0 +1,321 @@ +--- +language: kotlin +contributors: + - ["S Webber", "https://github.com/s-webber"] +filename: LearnKotlin.kt +--- + +Kotlin is a Statically typed programming language for the JVM, Android and the +browser. It is 100% interoperable with Java. +[Read more here.](https://kotlinlang.org/) + +```kotlin +// Single-line comments start with // +/* +Multi-line comments look like this. +*/ + +// The "package" keyword works in the same way as in Java. +package com.learnxinyminutes.kotlin + +/* +The entry point to a Kotlin program is a function named "main". +The function is passed an array containing any command line arguments. +*/ +fun main(args: Array) { + /* + Declaring values is done using either "var" or "val". + "val" declarations cannot be reassigned, whereas "vars" can. + */ + val fooVal = 10 // we cannot later reassign fooVal to something else + var fooVar = 10 + fooVar = 20 // fooVar can be reassigned + + /* + In most cases, Kotlin can determine what the type of a variable is, + so we don't have to explicitly specify it every time. + We can explicitly declare the type of a variable like so: + */ + val foo : Int = 7 + + /* + Strings can be represented in a similar way as in Java. + Escaping is done with a backslash. + */ + val fooString = "My String Is Here!"; + val barString = "Printing on a new line?\nNo Problem!"; + val bazString = "Do you want to add a tab?\tNo Problem!"; + println(fooString); + println(barString); + println(bazString); + + /* + A raw string is delimited by a triple quote ("""). + Raw strings can contain newlines and any other characters. + */ + val fooRawString = """ +fun helloWorld(val name : String) { + println("Hello, world!") +} +""" + println(fooRawString) + + /* + Strings can contain template expressions. + A template expression starts with a dollar sign ($). + */ + val fooTemplateString = "$fooString has ${fooString.length} characters" + println(fooTemplateString) + + /* + For a variable to hold null it must be explicitly specified as nullable. + A variable can be specified as nullable by appending a ? to its type. + We can access a nullable variable by using the ?. operator. + We can use the ?: operator to specify an alternative value to use + if a variable is null + */ + var fooNullable: String? = "abc" + println(fooNullable?.length) // => 3 + println(fooNullable?.length ?: -1) // => 3 + fooNullable = null + println(fooNullable?.length) // => null + println(fooNullable?.length ?: -1) // => -1 + + /* + Functions can be declared using the "fun" keyword. + Function arguments are specified in brackets after the function name. + Function arguments can optionally have a default value. + The function return type, if required, is specified after the arguments. + */ + fun hello(name: String = "world") : String { + return "Hello, $name!" + } + println(hello("foo")) // => Hello, foo! + println(hello(name = "bar")) // => Hello, bar! + println(hello()) // => Hello, world! + + /* + A function parameter may be marked with the "vararg" keyword + to allow a variable number of arguments to be passed to the function. + */ + fun varargExample(vararg names: Int) { + println("Argument has ${names.size} elements") + } + varargExample() // => Argument has 0 elements + varargExample(1) // => Argument has 1 elements + varargExample(1, 2, 3) // => Argument has 3 elements + + /* + When a function consists of a single expression then the curly brackets can + be omitted. The body is specified after a = symbol. + */ + fun odd(x: Int): Boolean = x % 2 == 1 + println(odd(6)) // => false + println(odd(7)) // => true + + // If the return type can be inferred then we don't need to specify it. + fun even(x: Int) = x % 2 == 0 + println(even(6)) // => true + println(even(7)) // => false + + // Functions can take functions as arguments and return functions. + fun not(f: (Int) -> Boolean) : (Int) -> Boolean { + return {n -> !f.invoke(n)} + } + // Named functions can be specified as arguments using the :: operator. + val notOdd = not(::odd) + val notEven = not(::even) + // Anonymous functions can be specified as arguments. + val notZero = not {n -> n == 0} + /* + If an anonymous function has only one parameter + then its declaration can be omitted (along with the ->). + The name of the single parameter will be "it". + */ + val notPositive = not {it > 0} + for (i in (0..4)) { + println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}") + } + + //The "class" keyword is used to declare classes. + class ExampleClass(val x: Int) { + fun memberFunction(y: Int) : Int { + return x + y + } + + infix fun infixMemberFunction(y: Int) : Int { + return x * y + } + } + /* + To create a new instance we call the constructor. + Note that Kotlin does not have a "new" keyword. + */ + val fooExampleClass = ExampleClass(7) + // Member functions can be called using dot notation. + println(fooExampleClass.memberFunction(4)) // => 11 + /* + If a function has been marked with the "infix" keyword then it can be + called using infix notation. + */ + println(fooExampleClass infixMemberFunction 4) // => 28 + + /* + Data classes are a concise way to create classes that just hold data. + The "hashCode"/"equals" and "toString" methods are automatically generated. + */ + data class DataClassExample (val x: Int, val y: Int, val z: Int) + val fooData = DataClassExample(1, 2, 4) + println(fooData) // => DataClassExample(x=1, y=2, z=4) + + // Data classes have a "copy" function. + val fooCopy = fooData.copy(y = 100) + println(fooCopy) // => DataClassExample(x=1, y=100, z=4) + + // Objects can be destructured into multiple variables. + val (a, b, c) = fooCopy + println("$a $b $c") // => 1 100 4 + + // The "with" function is similar to the JavaScript "with" statement. + data class MutableDataClassExample (var x: Int, var y: Int, var z: Int) + val fooMutableDate = MutableDataClassExample(7, 4, 9) + with (fooMutableDate) { + x -= 2 + y += 2 + z-- + } + println(fooMutableDate) // => MutableDataClassExample(x=5, y=6, z=8) + + /* + We can create a list using the "listOf" function. + The list will be immutable - elements cannot be added or removed. + */ + val fooList = listOf("a", "b", "c") + println(fooList.size) // => 3 + println(fooList.first()) // => a + println(fooList.last()) // => c + // elements can be accessed by index + println(fooList[1]) // => b + + // A mutable list can be created using the "mutableListOf" function. + val fooMutableList = mutableListOf("a", "b", "c") + fooMutableList.add("d") + println(fooMutableList.last()) // => d + println(fooMutableList.size) // => 4 + + // We can create a set using the "setOf" function. + val fooSet = setOf("a", "b", "c") + println(fooSet.contains("a")) // => true + println(fooSet.contains("z")) // => false + + // We can create a map using the "mapOf" function. + val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9) + // Map values can be accessed by their key. + println(fooMap["a"]) // => 8 + + // Kotlin provides higher-order functions for working with collections. + val x = (1..9).map {it * 3} + .filter {it < 20} + .groupBy {it % 2 == 0} + .mapKeys {if (it.key) "even" else "odd"} + println(x) // => {odd=[3, 9, 15], even=[6, 12, 18]} + + // A "for" loop can be used with anything that provides an iterator. + for (c in "hello") { + println(c) + } + + // "while" loops work in the same way as other languages. + var ctr = 0 + while (ctr < 5) { + println(ctr) + ctr++ + } + do { + println(ctr) + ctr++ + } while (ctr < 10) + + // "when" can be used as an alternative to "if-else if" chains. + val i = 10 + when { + i < 7 -> println("first block") + fooString.startsWith("hello") -> println("second block") + else -> println("else block") + } + + // "when" can be used with an argument. + when (i) { + 0, 21 -> println("0 or 21") + in 1..20 -> println("in the range 1 to 20") + else -> println("none of the above") + } + + // "when" can be used as a function that returns a value. + var result = when (i) { + 0, 21 -> "0 or 21" + in 1..20 -> "in the range 1 to 20" + else -> "none of the above" + } + println(result) + + /* + We can check if an object is a particular type by using the "is" operator. + If an object passes a type check then it can be used as that type without + explicitly casting it. + */ + fun smartCastExample(x: Any) : Boolean { + if (x is Boolean) { + // x is automatically cast to Boolean + return x + } else if (x is Int) { + // x is automatically cast to Int + return x > 0 + } else if (x is String) { + // x is automatically cast to String + return x.isNotEmpty() + } else { + return false + } + } + println(smartCastExample("Hello, world!")) // => true + println(smartCastExample("")) // => false + println(smartCastExample(5)) // => true + println(smartCastExample(0)) // => false + println(smartCastExample(true)) // => true + + /* + Extensions are a way to add new functionality to a class. + This is similar to C# extension methods. + */ + fun String.remove(c: Char): String { + return this.filter {it != c} + } + println("Hello, world!".remove('l')) // => Heo, word! + + println(EnumExample.A) // => A + println(ObjectExample.hello()) // => hello +} + +// Enum classes are similar to Java enum types. +enum class EnumExample { + A, B, C +} + +/* +The "object" keyword can be used to create singleton objects. +We cannot assign it to a variable, but we can refer to it by its name. +This is similar to Scala singleton objects. +*/ +object ObjectExample { + fun hello() : String { + return "hello" + } +} + +``` + +### Further Reading + +A web-based mini-IDE for Kotlin: +[http://try.kotlinlang.org/) -- cgit v1.2.3 From 2be7e5512058dedb14d6e66cca0cb5e54476f20e Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Mon, 14 Mar 2016 10:18:27 +0530 Subject: Added .gitignore file, referencing #2185 --- .gitignore | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..2efdef42 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +**/*~ +**/*# +**/*.swp +**/*.swo +**/*.bak +**/*.log* +**/*.sublime-workspace +**/.DS_Store +**/.DS_Store? +**/._* +**/.Spotlight-V100 +**/.Trashes +**/ehthumbs.db +**/Thumbs.db +**/desktop.ini \ No newline at end of file -- cgit v1.2.3 From d47f315b7ccea2fbcbeb33acd00765dd942df35a Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Mon, 14 Mar 2016 10:22:22 +0530 Subject: Updated .gitignore file, referencing #2185 --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 2efdef42..553029fe 100644 --- a/.gitignore +++ b/.gitignore @@ -12,4 +12,4 @@ **/.Trashes **/ehthumbs.db **/Thumbs.db -**/desktop.ini \ No newline at end of file +**/desktop.ini -- cgit v1.2.3 From 2e2f9c1f72fd6868401f8126ddb8f1ce21b75112 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Mon, 14 Mar 2016 10:41:53 +0530 Subject: New .gitignore file, referencing #2185 --- .gitignore | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/.gitignore b/.gitignore index 553029fe..62ce4609 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,4 @@ -**/*~ -**/*# -**/*.swp -**/*.swo -**/*.bak -**/*.log* -**/*.sublime-workspace -**/.DS_Store -**/.DS_Store? -**/._* -**/.Spotlight-V100 -**/.Trashes -**/ehthumbs.db -**/Thumbs.db -**/desktop.ini +!**/*.markdown +!**/*.md +!**/*.csv +!**/*.erb -- cgit v1.2.3 From f86fcf1e9b2451439150672368dc720bcace6320 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Mon, 14 Mar 2016 12:36:52 +0530 Subject: Updated, referencing #2185 --- .gitignore | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 62ce4609..91678344 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,16 @@ -!**/*.markdown -!**/*.md -!**/*.csv -!**/*.erb +**/*~ +**/*# +**/*#* +**/*.swp +**/*.swo +**/*.bak +**/*.log* +**/*.sublime-workspace +**/.DS_Store +**/.DS_Store? +**/._* +**/.Spotlight-V100 +**/.Trashes +**/ehthumbs.db +**/Thumbs.db +**/desktop.ini \ No newline at end of file -- cgit v1.2.3 From 9950c038fb8bba0055ee7964d8523d43d7dce0a2 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Mon, 14 Mar 2016 12:38:47 +0530 Subject: Updated, referencing #2185 --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 91678344..dd41ec4a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,6 @@ **/*~ **/*# -**/*#* +**/#*# **/*.swp **/*.swo **/*.bak -- cgit v1.2.3 From 03da44dd0b5ef9e351adf5881c25d1d25803c496 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Mon, 14 Mar 2016 10:26:18 -0600 Subject: [forth/en] don't -> don't --- forth.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forth.html.markdown b/forth.html.markdown index b4a5581b..55d755b2 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -54,7 +54,7 @@ Forth, but most of what is written here should work elsewhere. 3 dup - \ duplicate the top item (1st now equals 2nd): 3 - 3 2 5 swap / \ swap the top with the second element: 5 / 2 6 4 5 rot .s \ rotate the top 3 elements: 4 5 6 -4 0 drop 2 / \ remove the top item (dont print to screen): 4 / 2 +4 0 drop 2 / \ remove the top item (don't print to screen): 4 / 2 1 2 3 nip .s \ remove the second item (similar to drop): 1 3 \ ---------------------- More Advanced Stack Manipulation ---------------------- -- cgit v1.2.3 From 072424afd77b9d772102f83508fcc337ffc81a7d Mon Sep 17 00:00:00 2001 From: "Shawn.Zhang" Date: Tue, 15 Mar 2016 02:29:56 +0800 Subject: fixed some sentences --- zh-cn/typescript-cn.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/zh-cn/typescript-cn.html.markdown b/zh-cn/typescript-cn.html.markdown index af870279..2651b1cb 100644 --- a/zh-cn/typescript-cn.html.markdown +++ b/zh-cn/typescript-cn.html.markdown @@ -11,7 +11,7 @@ lang: zh-cn TypeScript是一门为开发大型JavaScript应用而设计的语言。TypeScript在JavaScript的基础上增加了类、模块、接口、泛型和静态类型(可选)等常见的概念。它是JavaScript的一个超集:所有JavaScript代码都是有效的TypeScript代码,所以任何JavaScript项目都可以无缝引入TypeScript. TypeScript编译器会把TypeScript代码编译成JavaScript代码。 -本文只关注TypeScript额外增加的语法,区别于[JavaScript](../javascript-cn/). +本文只关注TypeScript额外增加的区别于[JavaScript](../javascript-cn/)的语法,. 如需测试TypeScript编译器,你可以在[Playground](http://www.typescriptlang.org/Playground)码代码,它会自动编译成JavaScript代码然后直接显示出来。 @@ -21,7 +21,7 @@ var isDone: boolean = false; var lines: number = 42; var name: string = "Anders"; -// 如果不知道是什么类型,可以使用"Any"(任意)类型 +// 如果不知道是什么类型,可以使用"any"(任意)类型 var notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // 亦可,定义为布尔型 @@ -52,7 +52,7 @@ var f4 = (i: number) => { return i * i; } // 返回推断类型的值, 单行程式可以不需要return关键字和大括号 var f5 = (i: number) => i * i; -// 接口是结构化的,任何具有这些属性的都需要兼容该接口 +// 接口是结构化的,任何具有这些属性的对象都与该接口兼容 interface Person { name: string; // 可选属性,使用"?"标识 @@ -83,8 +83,8 @@ class Point { // 属性 x: number; - // 构造器 - 这里面的public/private关键字会为属性和初始化值生成样板化代码 - // 这个例子中, 不需要更多的代码就可以把"y"定义成和"x"一样 + // 构造器 - 这里面的public/private关键字会为属性生成样板代码和初始化值 + // 这个例子中,y会被同x一样定义,不需要额外代码 // 同样支持默认值 constructor(x: number, public y: number = 0) { -- cgit v1.2.3 From dabebb1cffafa5e37ad5c4266918e5f7097568db Mon Sep 17 00:00:00 2001 From: Urban Fuchs Date: Tue, 15 Mar 2016 15:19:54 +0100 Subject: add translator and fix typo --- de-de/brainfuck-de.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/de-de/brainfuck-de.html.markdown b/de-de/brainfuck-de.html.markdown index c1050a5b..dd62dd67 100644 --- a/de-de/brainfuck-de.html.markdown +++ b/de-de/brainfuck-de.html.markdown @@ -3,6 +3,8 @@ language: brainfuck contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["urfuchs", "https://github.com/urfuchs"] filename: brainfuck-de lang: de-de @@ -81,7 +83,7 @@ erhöht und anschließend in Zelle #2 zurückkopiert. Am Ende steht in Zelle #3 das Ergebnis. ``` -Das ist Brainfuck. Nicht so schwierig, oder? Zum Spaß kannst du dein eigenes Brainfuchs +Das ist Brainfuck. Nicht so schwierig, oder? Zum Spaß kannst du dein eigenes Brainfuck Programm schreiben oder du schreibst einen Brainfuck Interpreter in einer anderen Programmiersprache. Der Interpreter lässt sich ziemlich einfach implementieren. Falls du Masochist bist, kannst du auch versuchen, einen Brainfuck Interpreter in Brainfuck zu implementieren. -- cgit v1.2.3 From 9b7d5bee955cd64041fe0799d8c808ede05234a5 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Tue, 15 Mar 2016 08:28:11 -0600 Subject: [fsharp/en] typos MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit dont -> don’t defintion -> definition --- fsharp.html.markdown | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/fsharp.html.markdown b/fsharp.html.markdown index 809a1da2..e345201d 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -346,7 +346,7 @@ module DataTypeExamples = let trySendEmail email = match email with // use pattern matching | ValidEmailAddress address -> () // send - | InvalidEmailAddress address -> () // dont send + | InvalidEmailAddress address -> () // don't send // The combination of union types and record types together // provide a great foundation for domain driven design. @@ -426,7 +426,7 @@ module ActivePatternExamples = // ----------------------------------- // You can create partial matching patterns as well - // Just use underscore in the defintion, and return Some if matched. + // Just use underscore in the definition, and return Some if matched. let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None @@ -627,7 +627,3 @@ module NetCompatibilityExamples = For more demonstrations of F#, go to the [Try F#](http://www.tryfsharp.org/Learn) site, or my [why use F#](http://fsharpforfunandprofit.com/why-use-fsharp/) series. Read more about F# at [fsharp.org](http://fsharp.org/). - - - - -- cgit v1.2.3 From a3ff83350e0607446d14b32134510a6b414abcc8 Mon Sep 17 00:00:00 2001 From: Vitaliy Petrov Date: Tue, 15 Mar 2016 18:29:58 +0300 Subject: Update c-ru.html.markdown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Поправил "Можно можно" =) --- ru-ru/c-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown index 63bcfe76..5e967181 100644 --- a/ru-ru/c-ru.html.markdown +++ b/ru-ru/c-ru.html.markdown @@ -422,7 +422,7 @@ void function_1() { // Вы можете объявить указатель на структуру struct rectangle *my_rec_ptr = &my_rec; - // Можно можно получить доступ к структуре и через указатель + // Можно получить доступ к структуре и через указатель (*my_rec_ptr).width = 30; // ... или ещё лучше: используйте оператор -> для лучшей читабельночти -- cgit v1.2.3 From d1ad5854bcd261ade7e7ef17a00e7f1e643060d5 Mon Sep 17 00:00:00 2001 From: Lidenburg Date: Tue, 15 Mar 2016 19:03:03 +0100 Subject: Fix folder name, lang value and a typo Changed lang from "sv-sv" to "sv-se" and same for the folder name. Also added a missing space. --- sv-se/brainfuck-sv.html.markdown | 85 ++++++++++++++++++++++++++++++++++++++++ sv-sv/brainfuck-sv.html.markdown | 85 ---------------------------------------- 2 files changed, 85 insertions(+), 85 deletions(-) create mode 100644 sv-se/brainfuck-sv.html.markdown delete mode 100644 sv-sv/brainfuck-sv.html.markdown diff --git a/sv-se/brainfuck-sv.html.markdown b/sv-se/brainfuck-sv.html.markdown new file mode 100644 index 00000000..e9fbc436 --- /dev/null +++ b/sv-se/brainfuck-sv.html.markdown @@ -0,0 +1,85 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Richard Lindberg", "https://github.com/Lidenburg"] +lang: sv-se +--- + +Brainfuck (ej versaliserat förutom vid ny mening) är ett extremt +minimalistiskt Turing-komplett programmeringsspråk med endast 8 kommandon. + +Du kan testa brainfuck i din webbläsare via [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` +Alla karaktärer förutom "><+-.,[]" (inte inkluderat citattecken) ignoreras. + +Brainfuck är representerat av ett fält med 30 000 celler initialiserade till +noll och en data pekare som pekar på den valda cellen. + +Det finns åtta kommandon: ++ : Ökar värdet av den valda cellen med ett. +- : Minskar värdet av den valda cellen med ett. +> : Flyttar data pekaren till nästa cell (cellen till höger). +< : Flyttar data pekaren till förra cellen (cellen till vänster). +. : Skriver ut ASCII värdet av den valda cellen (t.ex. 65 = 'A'). +, : Läser in en karaktär till den valda cellen. +[ : Om värdet vid den valda cellen är noll, hoppa till matchande ]. + Annars fortsätts till nästa instruktion. +] : Om värdet vid den valda cellen är noll, fortsätt till nästa instruktion. + Annars, gå tillbaka till matchande ]. + +[ och ] formar en while loop. + +Nedan är ett exempel på ett simpelt brainfuck program. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Programmet skriver ut bokstaven 'A'. Först ökar den värdet av cell #1 till 6. +Cell #1 kommer att användas för att loopa. Sen börjar den loopen (vid '[') och +flyttar till cell #2. Den ökar värdet av cell #2 10 gånger, går tillbaka till +cell #1 och minskar den med 1. Den gör det här 6 gånger (så många iterationer +det tar för cell #1 att bli noll). + +Nu är programmet på cell #1, vilket har ett värde av 0 och cell #2 har värdet 60. +Programmet flyttar pekaren till cell #2 och ökar värdet med 5, vilket leder till +att cell #2 har ett värde av 65 (vilket är bokstaven 'A' i ASCII), sedan skriver +den ut cell #2 och bokstaven 'A' skrivs ut till skärmen. + + +, [ > + < - ] > . + +Det här programmet läser en karaktär från användaren och kopierar karaktären +till cell #1. Sedan startas en loop. Pekaren flyttas till cell #2, värder ökas +med ett, pekaren flyttas tillbaka till cell #1 och minskar värdet med ett. +Det här fortsätter tills cell #1 innehåller noll och cell #2 innehåller det +värde som cell #1 innehöll från början. Eftersom att programmet vid slutet av +loopen är på cell #1 flyttas pekaren till cell #2 och sedan skriver den ut +värdet av cell #2 i ASCII. + +Värt att komma ihåg är att programmet ovan kan skrivas utan mellanslag också: + +,[>+<-]>. + + +Försök och lista ut vad det här programmet gör: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Programmet tar två nummer som indata, och multiplicerar dem. + +Kärnan av det är att den först läser in två tal/bokstäver. Sedan startar +den yttre loopen som beror på cell #1. Sedan går den vidare till cell #2 och +startar den innre loopen som beror på cell #2 och ökar cell #3. Men det uppstår +ett problem: Vid slutet av den innre loopen är cell #2 noll. Vilket betyder att +den inre loopen inte kommer att fungera tills nästa gång. För att lösa det här +problemet ökas också cell #4 som sedan kopieras till cell #2. +Sedan är resultatet i cell #3. +``` + +Och det är brainfuck. Inte så svårt va? För skojs skull kan du skriva dina egna +brainfuck program, eller skriva en egen brainfuck interpretator i ett annat +språk. interpretatorn är ganska simpel att implementera, men om man är en +masochist, testa att skriva en brainfuck interpretator… i brainfuck. diff --git a/sv-sv/brainfuck-sv.html.markdown b/sv-sv/brainfuck-sv.html.markdown deleted file mode 100644 index dc65da06..00000000 --- a/sv-sv/brainfuck-sv.html.markdown +++ /dev/null @@ -1,85 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Richard Lindberg", "https://github.com/Lidenburg"] -lang: sv-sv ---- - -Brainfuck (ej versaliserat förutom vid ny mening) är ett extremt -minimalistiskt Turing-komplett programmeringsspråk med endast 8 kommandon. - -Du kan testa brainfuck i din webbläsare via [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). - -``` -Alla karaktärer förutom "><+-.,[]" (inte inkluderat citattecken) ignoreras. - -Brainfuck är representerat av ett fält med 30 000 celler initialiserade till -noll och en data pekare som pekar på den valda cellen. - -Det finns åtta kommandon: -+ : Ökar värdet av den valda cellen med ett. -- : Minskar värdet av den valda cellen med ett. -> : Flyttar data pekaren till nästa cell (cellen till höger). -< : Flyttar data pekaren till förra cellen (cellen till vänster). -. : Skriver ut ASCII värdet av den valda cellen (t.ex. 65 = 'A'). -, : Läser in en karaktär till den valda cellen. -[ : Om värdet vid den valda cellen är noll, hoppa till matchande ]. - Annars fortsätts till nästa instruktion. -] : Om värdet vid den valda cellen är noll, fortsätt till nästa instruktion. - Annars, gå tillbaka till matchande ]. - -[ och ] formar en while loop. - -Nedan är ett exempel på ett simpelt brainfuck program. - -++++++ [ > ++++++++++ < - ] > +++++ . - -Programmet skriver ut bokstaven 'A'. Först ökar den värdet av cell #1 till 6. -Cell #1 kommer att användas för att loopa. Sen börjar den loopen (vid '[') och -flyttar till cell #2. Den ökar värdet av cell #2 10 gånger, går tillbaka till -cell #1 och minskar den med 1. Den gör det här 6 gånger (så många iterationer -det tar för cell #1 att bli noll). - -Nu är programmet på cell #1, vilket har ett värde av 0 och cell #2 har värdet 60. -Programmet flyttar pekaren till cell #2 och ökar värdet med 5, vilket leder till -att cell #2 har ett värde av 65 (vilket är bokstaven 'A' i ASCII), sedan skriver -den ut cell #2 och bokstaven 'A' skrivs ut till skärmen. - - -, [ > + < - ] > . - -Det här programmet läser en karaktär från användaren och kopierar karaktären -till cell #1. Sedan startas en loop. Pekaren flyttas till cell #2, värder ökas -med ett, pekaren flyttas tillbaka till cell #1 och minskar värdet med ett. -Det här fortsätter tills cell #1 innehåller noll och cell #2 innehåller det -värde som cell #1 innehöll från början. Eftersom att programmet vid slutet av -loopen är på cell #1 flyttas pekaren till cell #2 och sedan skriver den ut -värdet av cell #2 i ASCII. - -Värt att kommaihåg är att programmet ovan kan skrivas utan mellanslag också: - -,[>+<-]>. - - -Försök och lista ut vad det här programmet gör: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Programmet tar två nummer som indata, och multiplicerar dem. - -Kärnan av det är att den först läser in två tal/bokstäver. Sedan startar -den yttre loopen som beror på cell #1. Sedan går den vidare till cell #2 och -startar den innre loopen som beror på cell #2 och ökar cell #3. Men det uppstår -ett problem: Vid slutet av den innre loopen är cell #2 noll. Vilket betyder att -den inre loopen inte kommer att fungera tills nästa gång. För att lösa det här -problemet ökas också cell #4 som sedan kopieras till cell #2. -Sedan är resultatet i cell #3. -``` - -Och det är brainfuck. Inte så svårt va? För skojs skull kan du skriva dina egna -brainfuck program, eller skriva en egen brainfuck interpretator i ett annat -språk. interpretatorn är ganska simpel att implementera, men om man är en -masochist, testa att skriva en brainfuck interpretator… i brainfuck. -- cgit v1.2.3 From 814e9d4e92cc996b0ddea7d743c9bd81bc6620e9 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Tue, 15 Mar 2016 15:33:01 -0700 Subject: Remove BOM from forth-es --- es-es/forth-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/forth-es.html.markdown b/es-es/forth-es.html.markdown index 05dc0cc5..edc5d38c 100644 --- a/es-es/forth-es.html.markdown +++ b/es-es/forth-es.html.markdown @@ -1,4 +1,4 @@ ---- +--- language: forth contributors: - ["Horse M.D.", "http://github.com/HorseMD/"] -- cgit v1.2.3 From 636a9fef8362aff5c8f13ed1c2d44447af223de9 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Tue, 15 Mar 2016 15:33:36 -0700 Subject: Fix json-id header --- id-id/json-id.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/id-id/json-id.html.markdown b/id-id/json-id.html.markdown index 52e61449..ca346f6c 100644 --- a/id-id/json-id.html.markdown +++ b/id-id/json-id.html.markdown @@ -1,11 +1,12 @@ --- language: json -filename: learnjson.json +filename: learnjson-id.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] -translators +translators: - ["Rizky Luthfianto", "https://github.com/rilut"] +lang: id-id --- JSON adalah format pertukaran data yang sangat simpel, kemungkinan besar, -- cgit v1.2.3 From f32379a55853db947c2512982d3979341119807f Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Tue, 15 Mar 2016 15:34:19 -0700 Subject: Set kotlin highlighting to java --- kotlin.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kotlin.html.markdown b/kotlin.html.markdown index ae0123a7..57f311f9 100644 --- a/kotlin.html.markdown +++ b/kotlin.html.markdown @@ -9,7 +9,7 @@ Kotlin is a Statically typed programming language for the JVM, Android and the browser. It is 100% interoperable with Java. [Read more here.](https://kotlinlang.org/) -```kotlin +```java // Single-line comments start with // /* Multi-line comments look like this. -- cgit v1.2.3 From 319d4265073523f076beb7a98d4bb5e844b01a81 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Tue, 15 Mar 2016 15:35:51 -0700 Subject: Update objective-c-vi.html.markdown --- vi-vn/objective-c-vi.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown index 38e418e9..8bc334ab 100644 --- a/vi-vn/objective-c-vi.html.markdown +++ b/vi-vn/objective-c-vi.html.markdown @@ -1,12 +1,10 @@ --- - 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 OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch. -- cgit v1.2.3 From 1da996d5a587d963be7b7b968b7f99d4d015bfd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20S=C3=BC=C3=9F?= Date: Wed, 16 Mar 2016 12:38:14 +0100 Subject: Update d-de.html.markdown --- de-de/d-de.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/de-de/d-de.html.markdown b/de-de/d-de.html.markdown index 94519b28..ae036d70 100644 --- a/de-de/d-de.html.markdown +++ b/de-de/d-de.html.markdown @@ -3,6 +3,7 @@ language: D filename: learnd-de.d contributors: - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] +translators: - ["Dominik Süß", "www.thesuess.me"] lang: de-de --- @@ -22,7 +23,7 @@ void main(string[] args) { Wenn du so wie ich bist und viel zeit im Internet verbringst stehen die Chancen gut das du schonmal über [D](http://dlang.org/) gehört hast. Die D-Sprache ist eine moderne, überall einsetzbare programmiersprache die von Low bis -High Level verwendet werden kann und dabei viele stile anbietet. +High Level verwendet werden kann und dabei viele Stile anbietet. D wird aktiv von Walter Bright und Andrei Alexandrescu entwickelt, zwei super schlaue, richtig coole leute. Da das jetzt alles aus dem weg ist - auf zu den Beispielen! @@ -128,8 +129,8 @@ auto mat = new Matrix!(3, 3); // Standardmäßig ist T vom typ Integer ``` Wo wir schon bei Klassen sind - Wie wäre es mit Properties! Eine Property -ist eine Funktion die wie ein Wert agiert. Das gibt uns viel klarere syntax -im stil von `structure.x = 7` was gleichgültig wäre zu `structure.setX(7)` +ist eine Funktion die wie ein Wert agiert. Das gibt uns viel klarere Syntax +im Stil von `structure.x = 7` was gleichgültig wäre zu `structure.setX(7)` ```c // Diese Klasse ist parameterisiert mit T, U -- cgit v1.2.3 From c7a157948bf54b15cb2eb4e5635218c101aead2e Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Wed, 16 Mar 2016 10:37:27 -0600 Subject: [css/en] several fixes - Reduced almost all lines to less than 80 characters in length. - ie -> e.g. - occuring -> occurring (line 209) --- css.html.markdown | 58 +++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 39 insertions(+), 19 deletions(-) diff --git a/css.html.markdown b/css.html.markdown index 4ec95f8b..5dae06ca 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -7,17 +7,23 @@ contributors: - ["Connor Shea", "https://github.com/connorshea"] - ["Deepanshu Utkarsh", "https://github.com/duci9y"] - ["Tyler Mumford", "https://tylermumford.com"] - + filename: learncss.css --- -Web pages are built with HTML, which specifies the content of a page. CSS (Cascading Style Sheets) is a separate language which specifies a page's **appearance**. +Web pages are built with HTML, which specifies the content of a page. +CSS (Cascading Style Sheets) is a separate language which specifies +a page's **appearance**. -CSS code is made of static *rules*. Each rule takes one or more *selectors* and gives specific *values* to a number of visual *properties*. Those properties are then applied to the page elements indicated by the selectors. +CSS code is made of static *rules*. Each rule takes one or more *selectors* and +gives specific *values* to a number of visual *properties*. Those properties are +then applied to the page elements indicated by the selectors. -This guide has been written with CSS 2 in mind, which is extended by the new features of CSS 3. +This guide has been written with CSS 2 in mind, which is extended by the new +features of CSS 3. -**NOTE:** Because CSS produces visual results, in order to learn it, you need to try everything in a CSS playground like [dabblet](http://dabblet.com/). +**NOTE:** Because CSS produces visual results, in order to learn it, you need to +try everything in a CSS playground like [dabblet](http://dabblet.com/). The main focus of this article is on the syntax and some general tips. ## Syntax @@ -67,7 +73,7 @@ div { } [otherAttr~='foo'] { } [otherAttr~='bar'] { } -/* or contains a value in a dash-separated list, ie, "-" (U+002D) */ +/* or contains a value in a dash-separated list, e.g., "-" (U+002D) */ [otherAttr|='en'] { font-size:smaller; } @@ -114,7 +120,8 @@ selector:first-child {} /* any element that is the last child of its parent */ selector:last-child {} -/* Just like pseudo classes, pseudo elements allow you to style certain parts of a document */ +/* Just like pseudo classes, pseudo elements allow you to style certain parts of + a document */ /* matches a virtual first child of the selected element */ selector::before {} @@ -133,9 +140,9 @@ selector::after {} #################### */ selector { - + /* Units of length can be absolute or relative. */ - + /* Relative units */ width: 50%; /* percentage of parent element width */ font-size: 2em; /* multiples of element's original font-size */ @@ -144,14 +151,14 @@ selector { font-size: 2vh; /* or its height */ font-size: 2vmin; /* whichever of a vh or a vw is smaller */ font-size: 2vmax; /* or greater */ - + /* Absolute units */ width: 200px; /* pixels */ font-size: 20pt; /* points */ width: 5cm; /* centimeters */ min-width: 50mm; /* millimeters */ max-width: 5in; /* inches */ - + /* Colors */ color: #F6E; /* short hex format */ color: #FF66EE; /* long hex format */ @@ -162,10 +169,10 @@ selector { color: transparent; /* equivalent to setting the alpha to 0 */ color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */ color: hsla(0, 100%, 50%, 0.3); /* as hsl percentages with alpha */ - + /* Images as backgrounds of elements */ background-image: url(/img-path/img.jpg); /* quotes inside url() optional */ - + /* Fonts */ font-family: Arial; /* if the font family name has a space, it must be quoted */ @@ -196,7 +203,13 @@ Save a CSS stylesheet with the extension `.css`. ## Precedence or Cascade -An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Rules with a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one (which also means that if two different linked stylesheets contain rules for an element and if the rules are of the same specificity, then order of linking would take precedence and the sheet linked latest would govern styling) . +An element may be targeted by multiple selectors and may have a property set on +it in more than once. In these cases, one of the rules takes precedence over +others. Rules with a more specific selector take precedence over a less specific +one, and a rule occurring later in the stylesheet overwrites a previous one +(which also means that if two different linked stylesheets contain rules for an +element and if the rules are of the same specificity, then order of linking +would take precedence and the sheet linked latest would govern styling) . This process is called cascading, hence the name Cascading Style Sheets. @@ -225,18 +238,25 @@ and the following markup:

``` -The precedence of style is as follows. Remember, the precedence is for each **property**, not for the entire block. +The precedence of style is as follows. Remember, the precedence is for each +**property**, not for the entire block. -* `E` has the highest precedence because of the keyword `!important`. It is recommended that you avoid its usage. +* `E` has the highest precedence because of the keyword `!important`. It is +recommended that you avoid its usage. * `F` is next, because it is an inline style. -* `A` is next, because it is more "specific" than anything else. It has 3 specifiers: The name of the element `p`, its class `class1`, an attribute `attr='value'`. -* `C` is next, even though it has the same specificity as `B`. This is because it appears after `B`. +* `A` is next, because it is more "specific" than anything else. It has 3 + specifiers: The name of the element `p`, its class `class1`, an attribute + `attr='value'`. +* `C` is next, even though it has the same specificity as `B`. + This is because it appears after `B`. * `B` is next. * `D` is the last one. ## Compatibility -Most of the features in CSS 2 (and many in CSS 3) are available across all browsers and devices. But it's always good practice to check before using a new feature. +Most of the features in CSS 2 (and many in CSS 3) are available across all +browsers and devices. But it's always good practice to check before using +a new feature. ## Resources -- cgit v1.2.3 From 5f89f277b9b2ee778ccc2e2f044b3f7dbbb6c5ea Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Fri, 18 Mar 2016 12:23:18 +0530 Subject: fixed whitespaces & content extending beyond 80 chars --- python.html.markdown | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 12be4be1..28b0a7ae 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -8,20 +8,22 @@ contributors: filename: learnpython.py --- -Python was created by Guido Van Rossum in the early 90s. It is now one of the most popular -languages in existence. I fell in love with Python for its syntactic clarity. It's basically -executable pseudocode. +Python was created by Guido Van Rossum in the early 90s. It is now one of the +most popular languages in existence. I fell in love with Python for its +syntactic clarity. It's basically executable pseudocode. -Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] +Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) +or louiedinh [at] [google's email service] -Note: This article applies to Python 2.7 specifically, but should be applicable -to Python 2.x. Python 2.7 is reaching end of life and will stop being maintained in 2020, -it is though recommended to start learning Python with Python 3. -For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). +Note: This article applies to Python 2.7 specifically, but should be applicable +to Python 2.x. Python 2.7 is reaching end of life and will stop being +maintained in 2020, it is though recommended to start learning Python with +Python 3. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). -It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same time, -using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports -allow you to write Python 3 code that will run on Python 2, so check out the Python 3 tutorial. +It is also possible to write Python code which is compatible with Python 2.7 +and 3.x at the same time, using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports +allow you to write Python 3 code that will run on Python 2, so check out the +Python 3 tutorial. ```python @@ -32,6 +34,7 @@ allow you to write Python 3 code that will run on Python 2, so check out the Pyt as comments """ + #################################################### ## 1. Primitive Datatypes and Operators #################################################### @@ -188,6 +191,7 @@ some_other_var # Raises a name error # Equivalent of C's '?:' ternary operator "yahoo!" if 3 > 2 else 2 # => "yahoo!" + # Lists store sequences li = [] # You can start with a prefilled list @@ -441,6 +445,7 @@ with open("myfile.txt") as f: for line in f: print line + #################################################### ## 4. Functions #################################################### @@ -464,7 +469,6 @@ def varargs(*args): varargs(1, 2, 3) # => (1, 2, 3) - # You can define functions that take a variable number of # keyword args, as well, which will be interpreted as a dict by using ** def keyword_args(**kwargs): @@ -698,7 +702,6 @@ for i in double_numbers(xrange_): # message from functools import wraps - def beg(target_function): @wraps(target_function) def wrapper(*args, **kwargs): @@ -709,13 +712,11 @@ def beg(target_function): return wrapper - @beg def say(say_please=False): msg = "Can you buy me a beer?" return msg, say_please - print say() # Can you buy me a beer? print say(say_please=True) # Can you buy me a beer? Please! I am poor :( ``` -- cgit v1.2.3 From 2f772fff3ec4192d7fcda6b7335a46cf73bed435 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Fri, 18 Mar 2016 12:31:55 +0530 Subject: fixed content extending beyond 80 chars --- markdown.html.markdown | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/markdown.html.markdown b/markdown.html.markdown index b4ad3202..bdf42368 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -7,7 +7,9 @@ filename: markdown.md --- -Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). +Markdown was created by John Gruber in 2004. It's meant to be an easy to read +and write syntax which converts easily to HTML (and now many other formats as +well). Markdown also varies in implementation from one parser to a next. This guide will attempt to clarify when features are universal or when they are @@ -28,9 +30,10 @@ specific to a certain parser. Markdown is a superset of HTML, so any HTML file is valid Markdown. ```markdown - + ``` ## Headings @@ -214,8 +217,8 @@ highlighting of the language you specify after the \`\`\` ## Horizontal rule -Horizontal rules (`


`) are easily added with three or more asterisks or hyphens, -with or without spaces. +Horizontal rules (`
`) are easily added with three or more asterisks or +hyphens, with or without spaces. ```markdown *** @@ -298,7 +301,8 @@ in italics, so I do this: \*this text surrounded by asterisks\*. ### Keyboard keys -In GitHub Flavored Markdown, you can use a `` tag to represent keyboard keys. +In GitHub Flavored Markdown, you can use a `` tag to represent keyboard +keys. ```markdown Your computer crashed? Try sending a -- cgit v1.2.3 From 01bf2b1ec603e20592e6db60a8f5b568ecd18509 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Fri, 18 Mar 2016 12:51:27 +0530 Subject: fixed whitespaces, content extending beyond 80 chars --- git.html.markdown | 97 ++++++++++++++++++++++++++++++++----------------------- 1 file changed, 56 insertions(+), 41 deletions(-) diff --git a/git.html.markdown b/git.html.markdown index 282abbd2..6472c462 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -24,9 +24,12 @@ Version control is a system that records changes to a file(s), over time. ### Centralized Versioning VS Distributed Versioning -* Centralized version control focuses on synchronizing, tracking, and backing up files. -* Distributed version control focuses on sharing changes. Every change has a unique id. -* Distributed systems have no defined structure. You could easily have a SVN style, centralized system, with git. +* Centralized version control focuses on synchronizing, tracking, and backing +up files. +* Distributed version control focuses on sharing changes. Every change has a +unique id. +* Distributed systems have no defined structure. You could easily have a SVN +style, centralized system, with git. [Additional Information](http://git-scm.com/book/en/Getting-Started-About-Version-Control) @@ -42,7 +45,6 @@ Version control is a system that records changes to a file(s), over time. ## Git Architecture - ### Repository A set of files, directories, historical records, commits, and heads. Imagine it @@ -53,7 +55,8 @@ A git repository is comprised of the .git directory & working tree. ### .git Directory (component of repository) -The .git directory contains all the configurations, logs, branches, HEAD, and more. +The .git directory contains all the configurations, logs, branches, HEAD, and +more. [Detailed List.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) ### Working Tree (component of repository) @@ -63,16 +66,16 @@ referred to as your working directory. ### Index (component of .git dir) -The Index is the staging area in git. It's basically a layer that separates your working tree -from the Git repository. This gives developers more power over what gets sent -to the Git repository. +The Index is the staging area in git. It's basically a layer that separates +your working tree from the Git repository. This gives developers more power +over what gets sent to the Git repository. ### Commit -A git commit is a snapshot of a set of changes, or manipulations to your Working -Tree. For example, if you added 5 files, and removed 2 others, these changes -will be contained in a commit (or snapshot). This commit can then be pushed to -other repositories, or not! +A git commit is a snapshot of a set of changes, or manipulations to your +Working Tree. For example, if you added 5 files, and removed 2 others, these +changes will be contained in a commit (or snapshot). This commit can then be +pushed to other repositories, or not! ### Branch @@ -86,11 +89,14 @@ functionality to mark release points (v1.0, and so on) ### HEAD and head (component of .git dir) -HEAD is a pointer that points to the current branch. A repository only has 1 *active* HEAD. -head is a pointer that points to any commit. A repository can have any number of heads. +HEAD is a pointer that points to the current branch. A repository only has 1 +*active* HEAD. +head is a pointer that points to any commit. A repository can have any number +of heads. ### Stages of Git -* Modified - Changes have been made to a file but file has not been committed to Git Database yet +* Modified - Changes have been made to a file but file has not been committed +to Git Database yet * Staged - Marks a modified file to go into your next commit snapshot * Committed - Files have been committed to the Git Database @@ -99,14 +105,12 @@ head is a pointer that points to any commit. A repository can have any number of * [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/) * [Git For Designers](http://hoth.entp.com/output/git_for_designers.html) - ## Commands - ### init -Create an empty Git repository. The Git repository's settings, stored information, -and more is stored in a directory (a folder) named ".git". +Create an empty Git repository. The Git repository's settings, stored +information, and more is stored in a directory (a folder) named ".git". ```bash $ git init @@ -117,7 +121,6 @@ $ git init To configure settings. Whether it be for the repository, the system itself, or global configurations ( global config file is `~/.gitconfig` ). - ```bash # Print & Set Some Basic Config Variables (Global) $ git config --global user.email "MyEmail@Zoho.com" @@ -158,13 +161,11 @@ $ echo "temp/" >> .gitignore $ echo "private_key" >> .gitignore ``` - ### status To show differences between the index file (basically your working copy/repo) and the current HEAD commit. - ```bash # Will display the branch, untracked files, changes and other differences $ git status @@ -175,8 +176,8 @@ $ git help status ### add -To add files to the staging area/index. If you do not `git add` new files to the -staging area/index, they will not be included in commits! +To add files to the staging area/index. If you do not `git add` new files to +the staging area/index, they will not be included in commits! ```bash # add a file in your current working directory @@ -194,7 +195,8 @@ working directory/repo. ### branch -Manage your branches. You can view, edit, create, delete branches using this command. +Manage your branches. You can view, edit, create, delete branches using this +command. ```bash # list existing branches & remotes @@ -221,54 +223,64 @@ Manage your tags ```bash # List tags $ git tag + # Create a annotated tag # The -m specifies a tagging message,which is stored with the tag. # If you don’t specify a message for an annotated tag, # Git launches your editor so you can type it in. $ git tag -a v2.0 -m 'my version 2.0' + # Show info about tag # That shows the tagger information, the date the commit was tagged, # and the annotation message before showing the commit information. $ git show v2.0 + # Push a single tag to remote $ git push origin v2.0 + # Push a lot of tags to remote $ git push origin --tags ``` ### checkout -Updates all files in the working tree to match the version in the index, or specified tree. +Updates all files in the working tree to match the version in the index, or +specified tree. ```bash # Checkout a repo - defaults to master branch $ git checkout + # Checkout a specified branch $ git checkout branchName + # Create a new branch & switch to it # equivalent to "git branch ; git checkout " + $ git checkout -b newBranch ``` ### clone Clones, or copies, an existing repository into a new directory. It also adds -remote-tracking branches for each branch in the cloned repo, which allows you to push -to a remote branch. +remote-tracking branches for each branch in the cloned repo, which allows you +to push to a remote branch. ```bash # Clone learnxinyminutes-docs $ git clone https://github.com/adambard/learnxinyminutes-docs.git + # shallow clone - faster cloning that pulls only latest snapshot $ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git + # clone only a specific branch $ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch ``` ### commit -Stores the current contents of the index in a new "commit." This commit contains -the changes made and a message created by the user. +Stores the current contents of the index in a new "commit." This commit +contains the changes made and a message created by the user. ```bash # commit with a message @@ -383,7 +395,8 @@ $ git pull origin master $ git pull # Merge in changes from remote branch and rebase -# branch commits onto your local repo, like: "git pull , git rebase " +# branch commits onto your local repo, like: "git pull , git +# rebase " $ git pull origin master --rebase ``` @@ -409,8 +422,8 @@ $ git push ### stash -Stashing takes the dirty state of your working directory and saves it on a stack -of unfinished changes that you can reapply at any time. +Stashing takes the dirty state of your working directory and saves it on a +stack of unfinished changes that you can reapply at any time. Let's say you've been doing some work in your git repo, but you want to pull from the remote. Since you have dirty (uncommited) changes to some files, you @@ -441,7 +454,8 @@ nothing to commit, working directory clean ``` You can see what "hunks" you've stashed so far using `git stash list`. -Since the "hunks" are stored in a Last-In-First-Out stack, our most recent change will be at top. +Since the "hunks" are stored in a Last-In-First-Out stack, our most recent +change will be at top. ```bash $ git stash list @@ -471,7 +485,8 @@ Now you're ready to get back to work on your stuff! ### rebase (caution) -Take all changes that were committed on one branch, and replay them onto another branch. +Take all changes that were committed on one branch, and replay them onto +another branch. *Do not rebase commits that you have pushed to a public repo*. ```bash @@ -485,8 +500,8 @@ $ git rebase master experimentBranch ### reset (caution) Reset the current HEAD to the specified state. This allows you to undo merges, -pulls, commits, adds, and more. It's a great command but also dangerous if you don't -know what you are doing. +pulls, commits, adds, and more. It's a great command but also dangerous if you +don't know what you are doing. ```bash # Reset the staging area, to match the latest commit (leaves dir unchanged) @@ -504,11 +519,12 @@ $ git reset 31f2bb1 # after the specified commit). $ git reset --hard 31f2bb1 ``` + ### revert -Revert can be used to undo a commit. It should not be confused with reset which restores -the state of a project to a previous point. Revert will add a new commit which is the -inverse of the specified commit, thus reverting it. +Revert can be used to undo a commit. It should not be confused with reset which +restores the state of a project to a previous point. Revert will add a new +commit which is the inverse of the specified commit, thus reverting it. ```bash # Revert a specified commit @@ -550,4 +566,3 @@ $ git rm /pather/to/the/file/HelloWorld.c * [Pro Git](http://www.git-scm.com/book/en/v2) * [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) - -- cgit v1.2.3 From 90f68920b97ec6384933de323e8d7f260d3ae944 Mon Sep 17 00:00:00 2001 From: Jason Kinetec Date: Fri, 18 Mar 2016 12:29:29 -0400 Subject: Update pythonstatcomp.html.markdown --- pythonstatcomp.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 0b02dca8..7cf6862e 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -1,8 +1,9 @@ --- -language: Statistical computing with Python +category: tool +tool: Statistical Computing with Python contributors: - ["e99n09", "https://github.com/e99n09"] -filename: pythonstatcomp.py + - ["acidflip", "https://github.com/acidflip"] --- This is a tutorial on how to do some typical statistical programming tasks using Python. It's intended for people basically familiar with Python and experienced at statistical programming in a language like R, Stata, SAS, SPSS, or MATLAB. -- cgit v1.2.3 From 12f0b9442a680e27ec23504e5f43e13143c121b4 Mon Sep 17 00:00:00 2001 From: Jason Kinetec Date: Fri, 18 Mar 2016 14:07:03 -0400 Subject: Update pythonstatcomp.html.markdown --- pythonstatcomp.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 7cf6862e..8ee3aa64 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -3,7 +3,6 @@ category: tool tool: Statistical Computing with Python contributors: - ["e99n09", "https://github.com/e99n09"] - - ["acidflip", "https://github.com/acidflip"] --- This is a tutorial on how to do some typical statistical programming tasks using Python. It's intended for people basically familiar with Python and experienced at statistical programming in a language like R, Stata, SAS, SPSS, or MATLAB. -- cgit v1.2.3 From f8f644d891ba8dede049e27f8ede47a060b74603 Mon Sep 17 00:00:00 2001 From: s-webber Date: Sat, 19 Mar 2016 10:06:54 +0000 Subject: removed unnecessary brackets --- kotlin.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kotlin.html.markdown b/kotlin.html.markdown index ae0123a7..47577906 100644 --- a/kotlin.html.markdown +++ b/kotlin.html.markdown @@ -133,7 +133,7 @@ fun helloWorld(val name : String) { The name of the single parameter will be "it". */ val notPositive = not {it > 0} - for (i in (0..4)) { + for (i in 0..4) { println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}") } -- cgit v1.2.3 From 9ccc431ea31f53040fd693384ddfeaa75e834fc9 Mon Sep 17 00:00:00 2001 From: s-webber Date: Sat, 19 Mar 2016 10:08:01 +0000 Subject: updated further reading section --- kotlin.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/kotlin.html.markdown b/kotlin.html.markdown index 47577906..72018f51 100644 --- a/kotlin.html.markdown +++ b/kotlin.html.markdown @@ -317,5 +317,6 @@ object ObjectExample { ### Further Reading -A web-based mini-IDE for Kotlin: -[http://try.kotlinlang.org/) +* [Kotlin tutorials](https://kotlinlang.org/docs/tutorials/) +* [Try Kotlin in your browser](http://try.kotlinlang.org/) +* [A list of Kotlin resources](http://kotlin.link/) -- cgit v1.2.3 From 98651771ed1f2d3a9494271e2e9a7ee9ca1feb9a Mon Sep 17 00:00:00 2001 From: oliverpool Date: Sun, 20 Mar 2016 14:26:12 +0100 Subject: Typo: LaTeX table columns are separated by '&' --- latex.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/latex.html.markdown b/latex.html.markdown index d41f6b2f..0c443c8a 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -178,7 +178,7 @@ We can also insert Tables in the same way as figures. % the {} arguments below describe how each row of the table is drawn. % Again, I have to look these up. Each. And. Every. Time. \begin{tabular}{c|cc} - Number & Last Name & First Name \\ % Column rows are separated by $ + Number & Last Name & First Name \\ % Column rows are separated by & \hline % a horizontal line 1 & Biggus & Dickus \\ 2 & Monty & Python -- cgit v1.2.3 From 74ea20793d8ab73ab93f16646b363c1920e48e15 Mon Sep 17 00:00:00 2001 From: Dustin Williams Date: Sun, 20 Mar 2016 20:02:02 -0700 Subject: Fixed instance where wrong variable name was used --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 5082a433..b5a25a41 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -824,7 +824,7 @@ say why-not[^5]; #=> 5 15 25 35 45 # (they exist in other langages such as C as `static`) sub fixed-rand { state $val = rand; - say $rand; + say $val; } fixed-rand for ^10; # will print the same number 10 times -- cgit v1.2.3 From 1a5c738f7bfc4745ddf6d1d8cf79f744d049d024 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Mon, 21 Mar 2016 16:30:46 -0700 Subject: Update c++-es.html.markdown --- es-es/c++-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/c++-es.html.markdown b/es-es/c++-es.html.markdown index bcc775e5..07c8bc03 100644 --- a/es-es/c++-es.html.markdown +++ b/es-es/c++-es.html.markdown @@ -1,6 +1,6 @@ --- language: c++ -filename: learncpp.cpp +filename: learncpp-es.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] - ["Matt Kline", "https://github.com/mrkline"] -- cgit v1.2.3 From 81e3152c4a5a7b0ed120ba10e73827bdf3a50016 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Mon, 21 Mar 2016 16:31:18 -0700 Subject: Update python3.html.markdown --- cs-cz/python3.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index b498046a..581ed3a3 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -7,7 +7,7 @@ contributors: - ["Tomáš Bedřich", "http://tbedrich.cz"] translators: - ["Tomáš Bedřich", "http://tbedrich.cz"] -filename: learnpython3.py +filename: learnpython3-cz.py lang: cs-cz --- -- cgit v1.2.3 From 3653b3193a5507a302e69d6fd63f10e1896f59d6 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Mon, 21 Mar 2016 16:31:47 -0700 Subject: Update bash-it.html.markdown --- it-it/bash-it.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/it-it/bash-it.html.markdown b/it-it/bash-it.html.markdown index af8823c4..d535babc 100644 --- a/it-it/bash-it.html.markdown +++ b/it-it/bash-it.html.markdown @@ -10,7 +10,7 @@ contributors: - ["Anton Strömkvist", "http://lutic.org/"] - ["Rahil Momin", "https://github.com/iamrahil"] - ["Gregrory Kielian", "https://github.com/gskielian"] -filename: LearnBash.sh +filename: LearnBash-it.sh translators: - ["Robert Margelli", "http://github.com/sinkswim/"] - ["Tommaso Pifferi", "http://github.com/neslinesli93/"] -- cgit v1.2.3 From bcac9e126ca6fe617e05c8a9e54b4d8d93110b2f Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Mon, 21 Mar 2016 16:32:07 -0700 Subject: Update json-lt.html.markdown --- lt-lt/json-lt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lt-lt/json-lt.html.markdown b/lt-lt/json-lt.html.markdown index 8c97e598..50e52a7a 100644 --- a/lt-lt/json-lt.html.markdown +++ b/lt-lt/json-lt.html.markdown @@ -1,6 +1,6 @@ --- language: json -filename: learnjson.json +filename: learnjson-lt.json lang: lt-lt contributors: - ["Zygimantus", "https://github.com/zygimantus"] -- cgit v1.2.3 From 7b78232897c00ebb781f28a21b96f1863c073ac8 Mon Sep 17 00:00:00 2001 From: Ryan Rauschenberg Date: Tue, 22 Mar 2016 11:15:26 -0400 Subject: issue 2205: Change variable 'size' to 'array_size' --- c.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 7c9dd590..2fad5348 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -143,9 +143,9 @@ int main (int argc, char** argv) // can be declared as well. The size of such an array need not be a compile // time constant: printf("Enter the array size: "); // ask the user for an array size - int size; - fscanf(stdin, "%d", &size); - int var_length_array[size]; // declare the VLA + int array_size; + fscanf(stdin, "%d", &array_size); + int var_length_array[array_size]; // declare the VLA printf("sizeof array = %zu\n", sizeof var_length_array); // Example: -- cgit v1.2.3 From cae73192afb444010553e4ed9035562d477496a9 Mon Sep 17 00:00:00 2001 From: ajimu Date: Wed, 23 Mar 2016 13:50:24 -0500 Subject: [nim/en] Correct syntax highlighting The language was changed to JavaScript in [this commit](https://github.com/adambard/learnxinyminutes-docs/commit/f3b10beb01795bf7513ec8d06c9e90ab98df7a83). --- nim.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nim.html.markdown b/nim.html.markdown index 4901ebfe..5d00304d 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -11,7 +11,7 @@ that gives the programmer power without compromises on runtime efficiency. Nim is efficient, expressive, and elegant. -```javascript +```nim var # Declare (and assign) variables, letter: char = 'n' # with or without type annotations lang = "N" & "im" -- cgit v1.2.3 From a69b31cd3e2a29bbe130be4b90d1a8d0d72a813b Mon Sep 17 00:00:00 2001 From: juan70 Date: Sat, 26 Mar 2016 12:27:56 +0000 Subject: Change anonymous function in List.filter example Change into what is supposed to be better style, or maybe a more idiomatic way of writing the predicate. --- ocaml.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ocaml.html.markdown b/ocaml.html.markdown index a346550c..59ead9ec 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -216,7 +216,7 @@ List.nth my_list 1 ;; (* There are higher-order functions for lists such as map and filter. *) List.map (fun x -> x * 2) [1; 2; 3] ;; -List.filter (fun x -> if x mod 2 = 0 then true else false) [1; 2; 3; 4] ;; +List.filter (fun x -> x mod 2 = 0) [1; 2; 3; 4] ;; (* You can add an item to the beginning of a list with the "::" constructor often referred to as "cons". *) -- cgit v1.2.3 From 0dc90d1d6961eaecad66a94d63bc296853d3903e Mon Sep 17 00:00:00 2001 From: Louis Victory Alis Date: Sun, 27 Mar 2016 12:53:50 +0800 Subject: Update common-lisp-cn.html.markdown add ANSI Common Lisp --- zh-cn/common-lisp-cn.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/zh-cn/common-lisp-cn.html.markdown b/zh-cn/common-lisp-cn.html.markdown index b82829a9..c7fe7e2c 100644 --- a/zh-cn/common-lisp-cn.html.markdown +++ b/zh-cn/common-lisp-cn.html.markdown @@ -14,6 +14,8 @@ ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范 免费的经典的入门书籍[《实用 Common Lisp 编程》](http://www.gigamonkeys.com/book/) +许多人都抱怨上面这本书的翻译。[《ANSI Common Lisp》](http://acl.readthedocs.org/en/latest/)也许对中文读者更友好一些。 + 另外还有一本热门的近期出版的 [Land of Lisp](http://landoflisp.com/). -- cgit v1.2.3 From 5c1d6b2d59c6f2f419958004ac0035cd6f9b45c8 Mon Sep 17 00:00:00 2001 From: Cristian Achille Date: Mon, 28 Mar 2016 12:57:35 +0200 Subject: Add `lang: it-it` to metadata --- it-it/ruby-ecosystem-it.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/it-it/ruby-ecosystem-it.html.markdown b/it-it/ruby-ecosystem-it.html.markdown index 72ab579d..d745399b 100644 --- a/it-it/ruby-ecosystem-it.html.markdown +++ b/it-it/ruby-ecosystem-it.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Rafal Chmiel", "http://github.com/rafalchmiel"] translators: - ["Cristian Achille", "http://github.com/blackdev1l/"] +lang: it-it --- Generalmente chi usa ruby ha l'esigenza di avere differenti versioni di Ruby -- cgit v1.2.3 From 09b1c7893d71327b21267bfd4aa0e794c71e1797 Mon Sep 17 00:00:00 2001 From: ven Date: Tue, 29 Mar 2016 10:13:20 +0200 Subject: Delete r.html.markdown~ --- r.html.markdown~ | 807 ------------------------------------------------------- 1 file changed, 807 deletions(-) delete mode 100644 r.html.markdown~ diff --git a/r.html.markdown~ b/r.html.markdown~ deleted file mode 100644 index ee9e7c90..00000000 --- a/r.html.markdown~ +++ /dev/null @@ -1,807 +0,0 @@ ---- -language: R -contributors: - - ["e99n09", "http://github.com/e99n09"] -<<<<<<< HEAD -======= - - ["isomorphismes", "http://twitter.com/isomorphisms"] - - ["kalinn", "http://github.com/kalinn"] ->>>>>>> 6e38442b857a9d8178b6ce6713b96c52bf4426eb -filename: learnr.r ---- - -R is a statistical computing language. It has lots of libraries for uploading and cleaning data sets, running statistical procedures, and making graphs. You can also run `R` commands within a LaTeX document. - -```r - -# Comments start with number symbols. - -# You can't make multi-line comments, -# but you can stack multiple comments like so. - -# in Windows you can use CTRL-ENTER to execute a line. -# on Mac it is COMMAND-ENTER - - - -############################################################################# -# Stuff you can do without understanding anything about programming -############################################################################# - -# In this section, we show off some of the cool stuff you can do in -# R without understanding anything about programming. Do not worry -# about understanding everything the code does. Just enjoy! - -data() # browse pre-loaded data sets -data(rivers) # get this one: "Lengths of Major North American Rivers" -ls() # notice that "rivers" now appears in the workspace -head(rivers) # peek at the data set -# 735 320 325 392 524 450 - -length(rivers) # how many rivers were measured? -# 141 -summary(rivers) # what are some summary statistics? -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 135.0 310.0 425.0 591.2 680.0 3710.0 - -# make a stem-and-leaf plot (a histogram-like data visualization) -stem(rivers) - -# The decimal point is 2 digit(s) to the right of the | -# -# 0 | 4 -# 2 | 011223334555566667778888899900001111223333344455555666688888999 -# 4 | 111222333445566779001233344567 -# 6 | 000112233578012234468 -# 8 | 045790018 -# 10 | 04507 -# 12 | 1471 -# 14 | 56 -# 16 | 7 -# 18 | 9 -# 20 | -# 22 | 25 -# 24 | 3 -# 26 | -# 28 | -# 30 | -# 32 | -# 34 | -# 36 | 1 - -stem(log(rivers)) # Notice that the data are neither normal nor log-normal! -# Take that, Bell curve fundamentalists. - -# The decimal point is 1 digit(s) to the left of the | -# -# 48 | 1 -# 50 | -# 52 | 15578 -# 54 | 44571222466689 -# 56 | 023334677000124455789 -# 58 | 00122366666999933445777 -# 60 | 122445567800133459 -# 62 | 112666799035 -# 64 | 00011334581257889 -# 66 | 003683579 -# 68 | 0019156 -# 70 | 079357 -# 72 | 89 -# 74 | 84 -# 76 | 56 -# 78 | 4 -# 80 | -# 82 | 2 - -# make a histogram: -hist(rivers, col="#333333", border="white", breaks=25) # play around with these parameters -hist(log(rivers), col="#333333", border="white", breaks=25) # you'll do more plotting later - -# Here's another neat data set that comes pre-loaded. R has tons of these. -data(discoveries) -plot(discoveries, col="#333333", lwd=3, xlab="Year", - main="Number of important discoveries per year") -plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year", - main="Number of important discoveries per year") - -# Rather than leaving the default ordering (by year), -# we could also sort to see what's typical: -sort(discoveries) -# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 -# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 -# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 -# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 - -stem(discoveries, scale=2) -# -# The decimal point is at the | -# -# 0 | 000000000 -# 1 | 000000000000 -# 2 | 00000000000000000000000000 -# 3 | 00000000000000000000 -# 4 | 000000000000 -# 5 | 0000000 -# 6 | 000000 -# 7 | 0000 -# 8 | 0 -# 9 | 0 -# 10 | 0 -# 11 | -# 12 | 0 - -max(discoveries) -# 12 -summary(discoveries) -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 0.0 2.0 3.0 3.1 4.0 12.0 - -# Roll a die a few times -round(runif(7, min=.5, max=6.5)) -# 1 4 6 1 4 6 4 -# Your numbers will differ from mine unless we set the same random.seed(31337) - -# Draw from a standard Gaussian 9 times -rnorm(9) -# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271 -# [7] -0.59975593 0.57629164 1.08455362 - - - -################################################## -# Data types and basic arithmetic -################################################## - -# Now for the programming-oriented part of the tutorial. -# In this section you will meet the important data types of R: -# integers, numerics, characters, logicals, and factors. -# There are others, but these are the bare minimum you need to -# get started. - -# INTEGERS -# Long-storage integers are written with L -5L # 5 -class(5L) # "integer" -# (Try ?class for more information on the class() function.) -# In R, every single value, like 5L, is considered a vector of length 1 -length(5L) # 1 -# You can have an integer vector with length > 1 too: -c(4L, 5L, 8L, 3L) # 4 5 8 3 -length(c(4L, 5L, 8L, 3L)) # 4 -class(c(4L, 5L, 8L, 3L)) # "integer" - -# NUMERICS -# A "numeric" is a double-precision floating-point number -5 # 5 -class(5) # "numeric" -# Again, everything in R is a vector; -# you can make a numeric vector with more than one element -c(3,3,3,2,2,1) # 3 3 3 2 2 1 -# You can use scientific notation too -5e4 # 50000 -6.02e23 # Avogadro's number -1.6e-35 # Planck length -# You can also have infinitely large or small numbers -class(Inf) # "numeric" -class(-Inf) # "numeric" -# You might use "Inf", for example, in integrate(dnorm, 3, Inf); -# this obviates Z-score tables. - -# BASIC ARITHMETIC -# You can do arithmetic with numbers -# Doing arithmetic on a mix of integers and numerics gives you another numeric -10L + 66L # 76 # integer plus integer gives integer -53.2 - 4 # 49.2 # numeric minus numeric gives numeric -2.0 * 2L # 4 # numeric times integer gives numeric -3L / 4 # 0.75 # integer over numeric gives numeric -3 %% 2 # 1 # the remainder of two numerics is another numeric -# Illegal arithmetic yeilds you a "not-a-number": -0 / 0 # NaN -class(NaN) # "numeric" -# You can do arithmetic on two vectors with length greater than 1, -# so long as the larger vector's length is an integer multiple of the smaller -c(1,2,3) + c(1,2,3) # 2 4 6 -# Since a single number is a vector of length one, scalars are applied -# elementwise to vectors -(4 * c(1,2,3) - 2) / 2 # 1 3 5 -# Except for scalars, use caution when performing arithmetic on vectors with -# different lengths. Although it can be done, -c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6 -# Matching lengths is better practice and easier to read -c(1,2,3,1,2,3) * c(1,2,1,2,1,2) - -# CHARACTERS -# There's no difference between strings and characters in R -"Horatio" # "Horatio" -class("Horatio") # "character" -class('H') # "character" -# Those were both character vectors of length 1 -# Here is a longer one: -c('alef', 'bet', 'gimmel', 'dalet', 'he') -# => -# "alef" "bet" "gimmel" "dalet" "he" -length(c("Call","me","Ishmael")) # 3 -# You can do regex operations on character vectors: -substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " -gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." -# R has several built-in character vectors: -letters -# => -# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" -# [20] "t" "u" "v" "w" "x" "y" "z" -month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" - -# LOGICALS -# In R, a "logical" is a boolean -class(TRUE) # "logical" -class(FALSE) # "logical" -# Their behavior is normal -TRUE == TRUE # TRUE -TRUE == FALSE # FALSE -FALSE != FALSE # FALSE -FALSE != TRUE # TRUE -# Missing data (NA) is logical, too -class(NA) # "logical" -# Use | and & for logic operations. -# OR -TRUE | FALSE # TRUE -# AND -TRUE & FALSE # FALSE -# Applying | and & to vectors returns elementwise logic operations -c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE -c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE -# You can test if x is TRUE -isTRUE(TRUE) # TRUE -# Here we get a logical vector with many elements: -c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE -c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE - -# FACTORS -# The factor class is for categorical data -# Factors can be ordered (like childrens' grade levels) or unordered (like gender) -factor(c("female", "female", "male", NA, "female")) -# female female male female -# Levels: female male -# The "levels" are the values the categorical data can take -# Note that missing data does not enter the levels -levels(factor(c("male", "male", "female", NA, "female"))) # "female" "male" -# If a factor vector has length 1, its levels will have length 1, too -length(factor("male")) # 1 -length(levels(factor("male"))) # 1 -# Factors are commonly seen in data frames, a data structure we will cover later -data(infert) # "Infertility after Spontaneous and Induced Abortion" -levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" - -# NULL -# "NULL" is a weird one; use it to "blank out" a vector -class(NULL) # NULL -parakeet = c("beak", "feathers", "wings", "eyes") -parakeet -# => -# [1] "beak" "feathers" "wings" "eyes" -parakeet <- NULL -parakeet -# => -# NULL - -# TYPE COERCION -# Type-coercion is when you force a value to take on a different type -as.character(c(6, 8)) # "6" "8" -as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE -# If you put elements of different types into a vector, weird coercions happen: -c(TRUE, 4) # 1 4 -c("dog", TRUE, 4) # "dog" "TRUE" "4" -as.numeric("Bilbo") -# => -# [1] NA -# Warning message: -# NAs introduced by coercion - -# Also note: those were just the basic data types -# There are many more data types, such as for dates, time series, etc. - - - -################################################## -# Variables, loops, if/else -################################################## - -# A variable is like a box you store a value in for later use. -# We call this "assigning" the value to the variable. -# Having variables lets us write loops, functions, and if/else statements - -# VARIABLES -# Lots of way to assign stuff: -x = 5 # this is possible -y <- "1" # this is preferred -TRUE -> z # this works but is weird - -# LOOPS -# We've got for loops -for (i in 1:4) { - print(i) -} -# We've got while loops -a <- 10 -while (a > 4) { - cat(a, "...", sep = "") - a <- a - 1 -} -# Keep in mind that for and while loops run slowly in R -# Operations on entire vectors (i.e. a whole row, a whole column) -# or apply()-type functions (we'll discuss later) are preferred - -# IF/ELSE -# Again, pretty standard -if (4 > 3) { - print("4 is greater than 3") -} else { - print("4 is not greater than 3") -} -# => -# [1] "4 is greater than 3" - -# FUNCTIONS -# Defined like so: -jiggle <- function(x) { - x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise - return(x) -} -# Called like any other R function: -jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 - - - -########################################################################### -# Data structures: Vectors, matrices, data frames, and arrays -########################################################################### - -# ONE-DIMENSIONAL - -# Let's start from the very beginning, and with something you already know: vectors. -vec <- c(8, 9, 10, 11) -vec # 8 9 10 11 -# We ask for specific elements by subsetting with square brackets -# (Note that R starts counting from 1) -vec[1] # 8 -letters[18] # "r" -LETTERS[13] # "M" -month.name[9] # "September" -c(6, 8, 7, 5, 3, 0, 9)[3] # 7 -# We can also search for the indices of specific components, -which(vec %% 2 == 0) # 1 3 -# grab just the first or last few entries in the vector, -head(vec, 1) # 8 -tail(vec, 2) # 10 11 -# or figure out if a certain value is in the vector -any(vec == 10) # TRUE -# If an index "goes over" you'll get NA: -vec[6] # NA -# You can find the length of your vector with length() -length(vec) # 4 -# You can perform operations on entire vectors or subsets of vectors -vec * 4 # 16 20 24 28 -vec[2:3] * 5 # 25 30 -any(vec[2:3] == 8) # FALSE -# and R has many built-in functions to summarize vectors -mean(vec) # 9.5 -var(vec) # 1.666667 -sd(vec) # 1.290994 -max(vec) # 11 -min(vec) # 8 -sum(vec) # 38 -# Some more nice built-ins: -5:15 # 5 6 7 8 9 10 11 12 13 14 15 -seq(from=0, to=31337, by=1337) -# => -# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 -# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 - -# TWO-DIMENSIONAL (ALL ONE CLASS) - -# You can make a matrix out of entries all of the same type like so: -mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) -mat -# => -# [,1] [,2] -# [1,] 1 4 -# [2,] 2 5 -# [3,] 3 6 -# Unlike a vector, the class of a matrix is "matrix", no matter what's in it -class(mat) # => "matrix" -# Ask for the first row -mat[1,] # 1 4 -# Perform operation on the first column -3 * mat[,1] # 3 6 9 -# Ask for a specific cell -mat[3,2] # 6 - -# Transpose the whole matrix -t(mat) -# => -# [,1] [,2] [,3] -# [1,] 1 2 3 -# [2,] 4 5 6 - -# Matrix multiplication -mat %*% t(mat) -# => -# [,1] [,2] [,3] -# [1,] 17 22 27 -# [2,] 22 29 36 -# [3,] 27 36 45 - -# cbind() sticks vectors together column-wise to make a matrix -mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) -mat2 -# => -# [,1] [,2] -# [1,] "1" "dog" -# [2,] "2" "cat" -# [3,] "3" "bird" -# [4,] "4" "dog" -class(mat2) # matrix -# Again, note what happened! -# Because matrices must contain entries all of the same class, -# everything got converted to the character class -c(class(mat2[,1]), class(mat2[,2])) - -# rbind() sticks vectors together row-wise to make a matrix -mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) -mat3 -# => -# [,1] [,2] [,3] [,4] -# [1,] 1 2 4 5 -# [2,] 6 7 0 4 -# Ah, everything of the same class. No coercions. Much better. - -# TWO-DIMENSIONAL (DIFFERENT CLASSES) - -# For columns of different types, use a data frame -# This data structure is so useful for statistical programming, -# a version of it was added to Python in the package "pandas". - -students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"), - c(3,2,2,1,0,-1), - c("H", "G", "G", "R", "S", "G")) -names(students) <- c("name", "year", "house") # name the columns -class(students) # "data.frame" -students -# => -# name year house -# 1 Cedric 3 H -# 2 Fred 2 G -# 3 George 2 G -# 4 Cho 1 R -# 5 Draco 0 S -# 6 Ginny -1 G -class(students$year) # "numeric" -class(students[,3]) # "factor" -# find the dimensions -nrow(students) # 6 -ncol(students) # 3 -dim(students) # 6 3 -# The data.frame() function converts character vectors to factor vectors -# by default; turn this off by setting stringsAsFactors = FALSE when -# you create the data.frame -?data.frame - -# There are many twisty ways to subset data frames, all subtly unalike -students$year # 3 2 2 1 0 -1 -students[,2] # 3 2 2 1 0 -1 -students[,"year"] # 3 2 2 1 0 -1 - -# An augmented version of the data.frame structure is the data.table -# If you're working with huge or panel data, or need to merge a few data -# sets, data.table can be a good choice. Here's a whirlwind tour: -install.packages("data.table") # download the package from CRAN -require(data.table) # load it -students <- as.data.table(students) -students # note the slightly different print-out -# => -# name year house -# 1: Cedric 3 H -# 2: Fred 2 G -# 3: George 2 G -# 4: Cho 1 R -# 5: Draco 0 S -# 6: Ginny -1 G -students[name=="Ginny"] # get rows with name == "Ginny" -# => -# name year house -# 1: Ginny -1 G -students[year==2] # get rows with year == 2 -# => -# name year house -# 1: Fred 2 G -# 2: George 2 G -# data.table makes merging two data sets easy -# let's make another data.table to merge with students -founders <- data.table(house=c("G","H","R","S"), - founder=c("Godric","Helga","Rowena","Salazar")) -founders -# => -# house founder -# 1: G Godric -# 2: H Helga -# 3: R Rowena -# 4: S Salazar -setkey(students, house) -setkey(founders, house) -students <- founders[students] # merge the two data sets by matching "house" -setnames(students, c("house","houseFounderName","studentName","year")) -students[,order(c("name","year","house","houseFounderName")), with=F] -# => -# studentName year house houseFounderName -# 1: Fred 2 G Godric -# 2: George 2 G Godric -# 3: Ginny -1 G Godric -# 4: Cedric 3 H Helga -# 5: Cho 1 R Rowena -# 6: Draco 0 S Salazar - -# data.table makes summary tables easy -students[,sum(year),by=house] -# => -# house V1 -# 1: G 3 -# 2: H 3 -# 3: R 1 -# 4: S 0 - -# To drop a column from a data.frame or data.table, -# assign it the NULL value -students$houseFounderName <- NULL -students -# => -# studentName year house -# 1: Fred 2 G -# 2: George 2 G -# 3: Ginny -1 G -# 4: Cedric 3 H -# 5: Cho 1 R -# 6: Draco 0 S - -# Drop a row by subsetting -# Using data.table: -students[studentName != "Draco"] -# => -# house studentName year -# 1: G Fred 2 -# 2: G George 2 -# 3: G Ginny -1 -# 4: H Cedric 3 -# 5: R Cho 1 -# Using data.frame: -students <- as.data.frame(students) -students[students$house != "G",] -# => -# house houseFounderName studentName year -# 4 H Helga Cedric 3 -# 5 R Rowena Cho 1 -# 6 S Salazar Draco 0 - -# MULTI-DIMENSIONAL (ALL ELEMENTS OF ONE TYPE) - -# Arrays creates n-dimensional tables -# All elements must be of the same type -# You can make a two-dimensional table (sort of like a matrix) -array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) -# => -# [,1] [,2] [,3] [,4] -# [1,] 1 4 8 3 -# [2,] 2 5 9 6 -# You can use array to make three-dimensional matrices too -array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) -# => -# , , 1 -# -# [,1] [,2] -# [1,] 2 8 -# [2,] 300 9 -# [3,] 4 0 -# -# , , 2 -# -# [,1] [,2] -# [1,] 5 66 -# [2,] 60 7 -# [3,] 0 847 - -# LISTS (MULTI-DIMENSIONAL, POSSIBLY RAGGED, OF DIFFERENT TYPES) - -# Finally, R has lists (of vectors) -list1 <- list(time = 1:40) -list1$price = c(rnorm(40,.5*list1$time,4)) # random -list1 -# You can get items in the list like so -list1$time # one way -list1[["time"]] # another way -list1[[1]] # yet another way -# => -# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 -# [34] 34 35 36 37 38 39 40 -# You can subset list items like any other vector -list1$price[4] - -# Lists are not the most efficient data structure to work with in R; -# unless you have a very good reason, you should stick to data.frames -# Lists are often returned by functions that perform linear regressions - -################################################## -# The apply() family of functions -################################################## - -# Remember mat? -mat -# => -# [,1] [,2] -# [1,] 1 4 -# [2,] 2 5 -# [3,] 3 6 -# Use apply(X, MARGIN, FUN) to apply function FUN to a matrix X -# over rows (MAR = 1) or columns (MAR = 2) -# That is, R does FUN to each row (or column) of X, much faster than a -# for or while loop would do -apply(mat, MAR = 2, jiggle) -# => -# [,1] [,2] -# [1,] 3 15 -# [2,] 7 19 -# [3,] 11 23 -# Other functions: ?lapply, ?sapply - -# Don't feel too intimidated; everyone agrees they are rather confusing - -# The plyr package aims to replace (and improve upon!) the *apply() family. -install.packages("plyr") -require(plyr) -?plyr - - - -######################### -# Loading data -######################### - -# "pets.csv" is a file on the internet -# (but it could just as easily be be a file on your own computer) -pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv") -pets -head(pets, 2) # first two rows -tail(pets, 1) # last row - -# To save a data frame or matrix as a .csv file -write.csv(pets, "pets2.csv") # to make a new .csv file -# set working directory with setwd(), look it up with getwd() - -# Try ?read.csv and ?write.csv for more information - - - -######################### -# Statistical Analysis -######################### - -# Linear regression! -linearModel <- lm(price ~ time, data = list1) -linearModel # outputs result of regression -# => -# Call: -# lm(formula = price ~ time, data = list1) -# -# Coefficients: -# (Intercept) time -# 0.1453 0.4943 -summary(linearModel) # more verbose output from the regression -# => -# Call: -# lm(formula = price ~ time, data = list1) -# -# Residuals: -# Min 1Q Median 3Q Max -# -8.3134 -3.0131 -0.3606 2.8016 10.3992 -# -# Coefficients: -# Estimate Std. Error t value Pr(>|t|) -# (Intercept) 0.14527 1.50084 0.097 0.923 -# time 0.49435 0.06379 7.749 2.44e-09 *** -# --- -# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 -# -# Residual standard error: 4.657 on 38 degrees of freedom -# Multiple R-squared: 0.6124, Adjusted R-squared: 0.6022 -# F-statistic: 60.05 on 1 and 38 DF, p-value: 2.44e-09 -coef(linearModel) # extract estimated parameters -# => -# (Intercept) time -# 0.1452662 0.4943490 -summary(linearModel)$coefficients # another way to extract results -# => -# Estimate Std. Error t value Pr(>|t|) -# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01 -# time 0.4943490 0.06379348 7.74920901 2.440008e-09 -summary(linearModel)$coefficients[,4] # the p-values -# => -# (Intercept) time -# 9.234021e-01 2.440008e-09 - -# GENERAL LINEAR MODELS -# Logistic regression -set.seed(1) -list1$success = rbinom(length(list1$time), 1, .5) # random binary -glModel <- glm(success ~ time, data = list1, - family=binomial(link="logit")) -glModel # outputs result of logistic regression -# => -# Call: glm(formula = success ~ time, -# family = binomial(link = "logit"), data = list1) -# -# Coefficients: -# (Intercept) time -# 0.17018 -0.01321 -# -# Degrees of Freedom: 39 Total (i.e. Null); 38 Residual -# Null Deviance: 55.35 -# Residual Deviance: 55.12 AIC: 59.12 -summary(glModel) # more verbose output from the regression -# => -# Call: -# glm(formula = success ~ time, -# family = binomial(link = "logit"), data = list1) - -# Deviance Residuals: -# Min 1Q Median 3Q Max -# -1.245 -1.118 -1.035 1.202 1.327 -# -# Coefficients: -# Estimate Std. Error z value Pr(>|z|) -# (Intercept) 0.17018 0.64621 0.263 0.792 -# time -0.01321 0.02757 -0.479 0.632 -# -# (Dispersion parameter for binomial family taken to be 1) -# -# Null deviance: 55.352 on 39 degrees of freedom -# Residual deviance: 55.121 on 38 degrees of freedom -# AIC: 59.121 -# -# Number of Fisher Scoring iterations: 3 - - -######################### -# Plots -######################### - -# BUILT-IN PLOTTING FUNCTIONS -# Scatterplots! -plot(list1$time, list1$price, main = "fake data") -# Plot regression line on existing plot -abline(linearModel, col = "red") -# Get a variety of nice diagnostics -plot(linearModel) -# Histograms! -hist(rpois(n = 10000, lambda = 5), col = "thistle") -# Barplots! -barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) - -# GGPLOT2 -# But these are not even the prettiest of R's plots -# Try the ggplot2 package for more and better graphics -install.packages("ggplot2") -require(ggplot2) -?ggplot2 -pp <- ggplot(students, aes(x=house)) -pp + geom_histogram() -ll <- as.data.table(list1) -pp <- ggplot(ll, aes(x=time,price)) -pp + geom_point() -# ggplot2 has excellent documentation (available http://docs.ggplot2.org/current/) - - - -``` - -## How do I get R? - -* Get R and the R GUI from [http://www.r-project.org/](http://www.r-project.org/) -* [RStudio](http://www.rstudio.com/ide/) is another GUI -- cgit v1.2.3 From 5481cbfd3662390a967d6a7695815fe0a0e85cd8 Mon Sep 17 00:00:00 2001 From: William Chang Date: Tue, 29 Mar 2016 22:31:15 +0800 Subject: Update lua-cn.html.markdown the filenameis is "learn-cn.lua", so the command should be "lua learn-cn.lua". --- zh-cn/lua-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index f7065445..6736dc2a 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -416,7 +416,7 @@ lua-users.org上的[Lua简明参考](http://lua-users.org/files/wiki_insecure/us * os library 顺便说一下,整个文件是可运行的Lua; -保存为 learn-cn.lua 用命令 `lua learn.lua` 启动吧! +保存为 learn-cn.lua 用命令 `lua learn-cn.lua` 启动吧! 本文首次撰写于 [tylerneylon.com](http://tylerneylon.com) 同时也有 [github gist](https://gist.github.com/tylerneylon/5853042) 版. -- cgit v1.2.3 From 9dca295c055502d333e2ab1f4a1f9ae6f39f4b9e Mon Sep 17 00:00:00 2001 From: Alfredo Canziani Date: Wed, 30 Mar 2016 11:17:12 -0400 Subject: Update python3.html.markdown `map` requires `list` in order to convert the mapping to its list. E.g. `` to `[11, 12, 13]`. --- python3.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index ea29fdba..7864ae3f 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -589,8 +589,8 @@ add_10(3) # => 13 # TODO - Fix for iterables # There are built-in higher order functions -map(add_10, [1, 2, 3]) # => [11, 12, 13] -map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] -- cgit v1.2.3 From 6248cd1f84401548b80b48c9f1c4b55502c20095 Mon Sep 17 00:00:00 2001 From: Alfredo Canziani Date: Wed, 30 Mar 2016 11:24:05 -0400 Subject: Update python3.html.markdown The same happens for `filter`. ```pythob filter(lambda x: x > 5, [3, 4, 5, 6, 7]) list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) [6, 7] ``` --- python3.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index 7864ae3f..c2454076 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -592,7 +592,7 @@ add_10(3) # => 13 list(map(add_10, [1, 2, 3])) # => [11, 12, 13] list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] # We can use list comprehensions for nice maps and filters # List comprehension stores the output as a list which can itself be a nested list -- cgit v1.2.3 From f75cb997b0135a2ab8341c2043dfc0b78d3f2535 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 30 Mar 2016 13:04:32 -0700 Subject: Update python3.html.markdown Remove TODO --- python3.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index c2454076..2e37fccb 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -587,7 +587,6 @@ add_10(3) # => 13 (lambda x: x > 2)(3) # => True (lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 -# TODO - Fix for iterables # There are built-in higher order functions list(map(add_10, [1, 2, 3])) # => [11, 12, 13] list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] -- cgit v1.2.3 From 6fe6a9b16bae20a0770bdfa78e67423e9b154d3b Mon Sep 17 00:00:00 2001 From: Maxim Berman Date: Thu, 31 Mar 2016 10:09:45 +0200 Subject: Replace invite sign $ by > in compilation example $ sign messes with syntax highlighting (it stays in math mode for the rest of the document). Using > fixes this easily. --- latex.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/latex.html.markdown b/latex.html.markdown index 0c443c8a..81c0d24c 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -212,7 +212,7 @@ Getting to the final document using LaTeX consists of the following steps: \item Compile source code to produce a pdf. The compilation step looks something like this (in Linux): \\ \begin{verbatim} - $pdflatex learn-latex.tex learn-latex.pdf + > pdflatex learn-latex.tex learn-latex.pdf \end{verbatim} \end{enumerate} -- cgit v1.2.3 From f7e0953340fea2cd4831f4aab795333624c96e29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robin=20Pokorn=C3=BD?= Date: Sun, 3 Apr 2016 14:47:59 +0200 Subject: Add Czech translation of Elm --- cs-cz/elm.html.markdown | 373 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 373 insertions(+) create mode 100644 cs-cz/elm.html.markdown diff --git a/cs-cz/elm.html.markdown b/cs-cz/elm.html.markdown new file mode 100644 index 00000000..26533c14 --- /dev/null +++ b/cs-cz/elm.html.markdown @@ -0,0 +1,373 @@ +--- +language: Elm +contributors: + - ["Max Goldstein", "http://maxgoldste.in/"] +translators: + - ["Robin Pokorný", "http://robinpokorny.com/"] +filename: learnelm-cz.elm +lang: cs-cz +--- + +Elm je funkcionální reaktivní jazyk, který se kompiluje do (klientského) JavaScriptu. +Elm je silně typovaný, díky tomu je překladač schopen zachytit většinu chyb okamžitě a +vypsat snadno srozumitelná chybová hlášení. +Elm se hodí k tvorbě webových uživatelských rozhraní a her. + + +```haskell +-- Jednořádkové komentáře začínají dvěma pomlčkami. +{- Víceřádkové komentáře mohou být takto uzavřeny do bloku. +{- Mohou být i zanořeny. -} +-} + +{-- Základy --} + +-- Aritmetika +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 + +-- Každý číselný literál bez desetinné tečky je typu Int nebo Float. +33 / 2 -- 16.5 s reálným dělením +33 // 2 -- 16 s celočíselným dělením + +-- Umocňování +5 ^ 2 -- 25 + +-- Logické proměnné +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- Řetězce a znaky +"Toto je textový řetězec, protože používá dvojité uvozovky." +'a' -- znak v jednoduchých uvozovkách + +-- Řetězce lze spojovat. +"Ahoj " ++ "světe!" -- "Ahoj světe!" + +{-- Seznamy (List), n-tice (Tuple) a Záznamy (Record) --} + +-- Každá položka seznamu musí být stejného typu. +["příliš", "žluťoučký", "kůň", "úpěl"] +[1, 2, 3, 4, 5] +-- Druhý příklad lze také zapsat pomocí dvou teček. +[1..5] + +-- Spojovat seznamy lze stejně jako řetězce. +[1..5] ++ [6..10] == [1..10] -- True + +-- K přidání položky do seznamu použijte funkci "cons". +0 :: [1..5] -- [0, 1, 2, 3, 4, 5] + +-- Funkce "head" pro získání první položky seznamu i funkce "tail" pro získání následujích položek +-- vrací typ Maybe. Místo zjišťování, jestli nějaká položka není null, +-- se s chybějcími hodnotami vypořádáme explicitně. +List.head [1..5] -- Just 1 +List.tail [1..5] -- Just [2, 3, 4, 5] +List.head [] -- Nothing +-- List.nazevFunkce odkazuje na funkci, která žije v modulu List. + +-- Každý prvek v n-tici může být jiného typu, ale n-tice má pevný počet prvků. +("elm", 42) + +-- K získání hodnot z dvojice použijte funkce first a second. +-- (Toto je pouze zkratka. Brzy si ukážeme, jak na to "správně".) +fst ("elm", 42) -- "elm" +snd ("elm", 42) -- 42 + +-- Prázná n-tice, neboli "unit", se občas používá jako placeholder. +-- Je to jediná hodnota svého typu, který se také nazývá "Unit". +() + +-- Záznamy jsou podobné n-ticím, ale prvky jsou pojmenovány. Na pořadí nezáleží. +-- Povšimněte si, že hodnoty vlastností se přiřazují rovnítky, ne dvojtečkami. +{ x = 3, y = 7 } + +-- K hodnotám se přistupuje pomocí tečky a názvu vlastnosti. +{ x = 3, y = 7 }.x -- 3 + +-- Nebo využitím přístupové funkce, což je jen tečka a název vlastnosti. +.y { x = 3, y = 7 } -- 7 + +-- Změna hodnoty vlastnosti v záznamu. (Záznam tuto vlastnost už musí mít.) +{ osoba | + jmeno = "Jiří" } + +-- Změna více vlastností s využitím aktuálních hodnot. +{ hmotnyBod | + poloha = hmotnyBod.poloha + hmotnyBod.rychlost, + rychlost = hmotnyBod.rychlost + hmotnyBod.zrychleni } + +{-- Řídicí struktury --} + +-- Podmínky vždy musí mít větev "else" a obě větve musí být stejného typu. +if powerLevel > 9000 then + "PÁNI!" +else + "hmm" + +-- Podmínky lze skládat za sebe. +if n < 0 then + "n je záporné" +else if n > 0 then + "n je kladné" +else + "n je nula" + +-- Použíjte příkaz "case" k nalezení shody vzoru a různých možností. +case seznam of + [] -> "odpovídá práznému seznamu" + [x]-> "odpovídá seznamu o právě jedné položce, " ++ toString x + x::xs -> "odpovídá seznamu o alespoň jedné položce, jehož prvním prvkem je " ++ toString x +-- Shody se vyhodnocují v zapsaném pořadí. Kdybychom umístili [x] poslední, nikdy by nenastala shoda, +-- protože x::xs také odpovídá (xs by byl prázdný seznam). Shody "nepropadají". +-- Překladač vždy upozorní na chybějící nebo přebývající větve. + +-- Větvení typu Maybe. +case List.head seznam of + Just x -> "První položka je " ++ toString x + Nothing -> "Seznam byl prázdný." + +{-- Funkce --} + +-- Syntaxe funkcí je v Elmu velmi úsporná, založená spíše na mezerách +-- než na závorkách. Neexistuje tu klíčové slovo "return". + +-- Funkci defunujeme jejím jménem, argumenty, rovnítkem a tělem. +vynasob a b = + a * b + +-- Funkci voláme předáním argumentů (bez oddělujících čárek). +vynasob 7 6 -- 42 + +-- Částečně aplikované funkci předáme pouzne některé argumenty. +-- Poté zvolíme nové jméno. +zdvoj = + vynasob 2 + +-- Konstanty jsou podobné, ale nepřijímají žádné argumenty. +odpoved = + 42 + +-- Předejte funkci jako argument jiným funkcím. +List.map zdvoj [1..4] -- [2, 4, 6, 8] + +-- Nebo použijte anonymní funkci. +List.map (\a -> a * 2) [1..4] -- [2, 4, 6, 8] + +-- V definici funkce lze zapsat vzor, může-li nastat pouze jeden případ. +-- Tato funkce přijímá jednu dvojici místo dvou argumentů. +obsah (sirka, delka) = + sirka * delka + +obsah (6, 7) -- 42 + +-- Složenými závorkami vytvořte vzor pro názvy vlastností v záznamu. +-- Použijte "let" k definici lokálních proměnných. +objem {sirka, delka, hloubka} = + let + obsah = sirka * delka + in + obsah * hloubka + +objem { sirka = 3, delka = 2, hloubka = 7 } -- 42 + +-- Funkce mohou být rekurzivní. +fib n = + if n < 2 then + 1 + else + fib (n - 1) + fib (n - 2) + +List.map fib [0..8] -- [1, 1, 2, 3, 5, 8, 13, 21, 34] + +-- Jiná rekurzivní funkce (v praxi použijte List.length). +delkaSeznamu seznam = + case seznam of + [] -> 0 + x::xs -> 1 + delkaSeznamu xs + +-- Funkce se volají před jakýmkoli infixovým operátorem. Závorky určují prioritu. +cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1 +-- Nejprve se aplikuje "degrees" na číslo 30, výsledek je pak předán trigonometrickým +-- funkcím, které jsou poté umocněny na druhou, na závěr proběhne sčítání. + +{-- Typy a typové anotace --} + +-- Překladač odvodí typ každé hodnoty ve vašem programu. +-- Typy vždy začínají velkým písmenem. Čtete x : T jako "x je typu T". +-- Některé běžné typy, které můžete videt v Elmovém REPLu. +5 : Int +6.7 : Float +"ahoj" : String +True : Bool + +-- Funkce mají také typy. Čtěte -> jako "vrací". +-- O typu na konci uvažujte jako návratovém typu, o ostatních jako typech argumentů. +not : Bool -> Bool +round : Float -> Int + +-- Když definujete hodnotu je dobrým zvykem zapsat nad ní její typ. +-- Anotace je formou dokumentace, která je ověřována překladačem. +zdvoj : Int -> Int +zdvoj x = x * 2 + +-- Funkce jako argument je uzavřena v závorkách. +-- Typy s malým počátečním písmenem jsou typové proměnné: +-- mohou být libovolného typu, ale v každém volání musí být konzistetní. +List.map : (a -> b) -> List a -> List b +-- "List tečka map je typu a-vrací-b, vrací seznam-položek-typu-a, vrací seznam-položek-typu-b." + +-- Existují tři speciální typové proměnné: +-- číslo (number), porovnatelné (comparable), and spojitelné (appendable). +-- Čísla dovolují použít aritmetiku na Int a Float. +-- Porovnatelné dovolují uspořádat čísla a řetězce, např. a < b. +-- Spojitelné lze zřetězit pomocí a ++ b. + +{-- Typové aliasy a výčtové typy --} + +-- Pro záznamy a n-tice již typy automaticky existují. +-- (Povšimněte si, že typ vlatnosti záznamu přiřazujeme dvojtečkou a hodnotu rovnítkem.) +pocatek : { x : Float, y : Float, z : Float } +pocatek = + { x = 0, y = 0, z = 0 } + +-- Stávajícím typům lze dávat jména využitím aliasů. +type alias Bod3D = + { x : Float, y : Float, z : Float } + +-- Alias pro záznam funguje také jako jeho konstruktor. +jinyPocatek : Bod3D +jinyPocatek = + Bod3D 0 0 0 + +-- Jedná se stále o stejný typ, lze je tedy porovnat. +pocatek == jinyPocatek -- True + +-- Oproti tomu výčtový (union) typ definuje zcela nový typ. +-- Výčtový typ se takto jmenuje, protože může být jedním z několika vybraných možností. +-- Každá možnost je reprezentována jako "tag". +type Smer = + Sever | Jih | Vychod | Zapad + +-- Tagy mohou obsahovat další hodnoty známých typů. Lze využít i rekurze. +type IntStrom = + Vrchol | Uzel Int IntStrom IntStrom +-- "Vrchol" i "Uzel" jsou tagy. Vše, co následuje za tagem, je typ. + +-- Tagy lze použít jako hodnoty funkcí. +koren : IntStrom +koren = + Vrchol 7 List List + +-- Výčtové typy (a typové aliasy) mohou obsahovat typové proměnné. +type Strom a = + Vrchol | Uzel a (Strom a) (Strom a) +-- "Typ strom-prvků-a je vrchol, nebo uzel obsahující a, strom-prvků-a a strom-prvků-a." + +-- Vzory se shodují s tagy. Tagy s velkým počátečním písmenem odpovídají přesně. +-- Proměnné malým písmem odpovídají čemukoli. Podtržítko jaké odpovídá čemukoli, +-- ale symbolizuje, že se nebude dále používat. +nejviceVlevo : Strom a -> Maybe a +nejviceVlevo strom = + case strom of + Vrchol -> Nothing + Uzel x Vrchol _ -> Just x + Uzel _ podstrom _ -> nejviceVlevo podstrom + +-- To je víceméně vše o jazyku samotném. +-- Podívejme se nyní, jak organizovat a spouštět náš kód. + +{-- Moduly a importování --} + +-- Standardní knihovny jsou organizovány do modulů, stejně jako knihovny třetích stran, +-- které můžete využívat. Ve větších projektech můžete definovat vlastní moduly. + +-- Vložte toto na začátek souboru. Pokud nic neuvedete, předpokládá se "Main". +module Jmeno where + +-- Výchozím chováním je, že se exportuje vše. +-- Případně můžete definovat exportované vlastnosti explicitně. +module Jmeno (MujTyp, mojeHodnota) where + +-- Běžný návrhový vzor je expotovat pouze výčtový typ bez jeho tagů. +-- Tento vzor je znám jako krycí typ a často se využívá v knihovnách. + +-- Z jiných modulů lze importovat kód a použít jej v aktuálním modulu. +-- Nasledující umístí Dict do aktuálního scope, takže lze volat Dict.insert. +import Dict + +-- Importuje modul Dict a typ Dict, takže v anotacích není nutné psát Dict.Dict. +-- Stále lze volat Dict.insert. +import Dict exposing (Dict) + +-- Přejmonování importu. +import Graphics.Collage as C + +{-- Porty --} + +-- Port oznamuje, že budete komunikovat s vnějším světem. +-- Porty jsou dovoleny pouze v modulu Main. + +-- Příchozí port je jen typová anotace. +port idKlienta : Int + +-- Odchozí port má definici. +port objednavkaKlienta : List String +port objednavkaKlienta = ["Knihy", "Potraviny", "Nábytek"] + +-- Nebudeme zacházet do detailů, ale v JavaScriptu se dají nastavit +-- callbacky pro zasílání na příchozí porty a čtení z odchozích portů. + +{-- Nástroje pro příkazovou řádku --} + +-- Kompilace souboru. +$ elm make MujSoubor.elm + +-- Při prvním spuštění nainstaluje Elm standardní knihovny a vytvoří soubor +-- elm-package.json, kde jsou uloženy informace o vašem projektu. + +-- Elm reactor je server, který překládá a spouští vaše soubory. +-- Kliknutím na klíč vedle názvu souboru spustíte debugger s cestovám v čase! +$ elm reactor + +-- Zkoušejte si jednoduché příkazy v Read-Eval-Print Loop. +$ elm repl + +-- Balíčky jsou určeny uživatelským jménem na GitHubu a názvem repozitáře. +-- Nainstalujte nový balíček a uložte jej v souboru elm-package.json. +$ elm package install evancz/elm-html + +-- Porovnejte změny mezi verzemi jednoho balíčku. +$ elm package diff evancz/elm-html 3.0.0 4.0.2 +-- Správce balíčků v Elmu vyžaduje sémantické verzování, +-- takže minor verze nikdy nerozbije váš build. +``` + +Jazyk Elm je překvapivě malý. Nyní se můžete podívat do skoro jakéhokoli zdrojového kódu +v Elmu a budete mít zběžnou představu o jeho fungování. +Ovšem možnosti, jak psát kód, který je odolný vůči chybám a snadno se refaktoruje, jsou neomezené! + +Zde jsou některé užitečné zdroje (v angličtině). + +* [Hlavní stránka Elmu](http://elm-lang.org/). Obsahuje: + * Odkazy na [instalátory](http://elm-lang.org/install) + * [Documentaci](http://elm-lang.org/docs), včetně [popisu syntaxe](http://elm-lang.org/docs/syntax) + * Spoustu nápomocných [příkladů](http://elm-lang.org/examples) + +* Documentace pro [standardní knihovny Elmu](http://package.elm-lang.org/packages/elm-lang/core/latest/). Povšimněte si: + * [Základy](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics), které jsou automaticky importovány + * Typ [Maybe](http://package.elm-lang.org/packages/elm-lang/core/latest/Maybe) a jeho bratranec typ [Result](http://package.elm-lang.org/packages/elm-lang/core/latest/Result), které se běžně používají pro chybějící hodnoty a ošetření chyb. + * Datové struktury jako [List](http://package.elm-lang.org/packages/elm-lang/core/latest/List), [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict) a [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set) + * JSON [enkódování](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Encode) a [dekódování](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode) + +* [Architektura Elmu](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). Esej od tvůrce Elmu s příklady, jak organizovat kód do komponent. + +* [Elm mailing list](https://groups.google.com/forum/#!forum/elm-discuss). Všichni jsou přátelští a nápomocní. + +* [Scope v Elmu](https://github.com/elm-guides/elm-for-js/blob/master/Scope.md#scope-in-elm) a [Jak číst typové anotace](https://github.com/elm-guides/elm-for-js/blob/master/How%20to%20Read%20a%20Type%20Annotation.md#how-to-read-a-type-annotation). Další komunitní návody o základech Elmu, psáno pro JavaScriptové vývojáře. + +Běžte si zkusit něco napsat v Elmu! -- cgit v1.2.3 From 1d15820b8f13a8b96f71d24265a8abd63f73966b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20=C5=BD=C3=A1ra?= Date: Mon, 4 Apr 2016 12:27:54 +0200 Subject: Update elm.html.markdown --- cs-cz/elm.html.markdown | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/cs-cz/elm.html.markdown b/cs-cz/elm.html.markdown index 26533c14..904507e2 100644 --- a/cs-cz/elm.html.markdown +++ b/cs-cz/elm.html.markdown @@ -27,14 +27,14 @@ Elm se hodí k tvorbě webových uživatelských rozhraní a her. 8 - 1 -- 7 10 * 2 -- 20 --- Každý číselný literál bez desetinné tečky je typu Int nebo Float. +-- Každé číslo bez desetinné tečky je typu Int nebo Float. 33 / 2 -- 16.5 s reálným dělením 33 // 2 -- 16 s celočíselným dělením -- Umocňování 5 ^ 2 -- 25 --- Logické proměnné +-- Pravdivostní proměnné not True -- False not False -- True 1 == 1 -- True @@ -53,7 +53,7 @@ not False -- True -- Každá položka seznamu musí být stejného typu. ["příliš", "žluťoučký", "kůň", "úpěl"] [1, 2, 3, 4, 5] --- Druhý příklad lze také zapsat pomocí dvou teček. +-- Druhý příklad lze zapsat také pomocí dvou teček. [1..5] -- Spojovat seznamy lze stejně jako řetězce. @@ -78,7 +78,7 @@ List.head [] -- Nothing fst ("elm", 42) -- "elm" snd ("elm", 42) -- 42 --- Prázná n-tice, neboli "unit", se občas používá jako placeholder. +-- Prázná n-tice, neboli "unit", se občas používá jako zástupný symbol. -- Je to jediná hodnota svého typu, který se také nazývá "Unit". () @@ -136,30 +136,30 @@ case List.head seznam of -- Syntaxe funkcí je v Elmu velmi úsporná, založená spíše na mezerách -- než na závorkách. Neexistuje tu klíčové slovo "return". --- Funkci defunujeme jejím jménem, argumenty, rovnítkem a tělem. +-- Funkci definujeme jejím jménem, parametry, rovnítkem a tělem. vynasob a b = a * b --- Funkci voláme předáním argumentů (bez oddělujících čárek). +-- Funkci voláme předáním parametrů (bez oddělujících čárek). vynasob 7 6 -- 42 --- Částečně aplikované funkci předáme pouzne některé argumenty. +-- Částečně aplikované funkci předáme pouzne některé parametry. -- Poté zvolíme nové jméno. zdvoj = vynasob 2 --- Konstanty jsou podobné, ale nepřijímají žádné argumenty. +-- Konstanty jsou podobné, ale nepřijímají žádné parametry. odpoved = 42 --- Předejte funkci jako argument jiným funkcím. +-- Předejte funkci jako parametr jiným funkcím. List.map zdvoj [1..4] -- [2, 4, 6, 8] -- Nebo použijte anonymní funkci. List.map (\a -> a * 2) [1..4] -- [2, 4, 6, 8] -- V definici funkce lze zapsat vzor, může-li nastat pouze jeden případ. --- Tato funkce přijímá jednu dvojici místo dvou argumentů. +-- Tato funkce přijímá jednu dvojici místo dvou parametrů. obsah (sirka, delka) = sirka * delka @@ -193,7 +193,7 @@ delkaSeznamu seznam = -- Funkce se volají před jakýmkoli infixovým operátorem. Závorky určují prioritu. cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1 -- Nejprve se aplikuje "degrees" na číslo 30, výsledek je pak předán trigonometrickým --- funkcím, které jsou poté umocněny na druhou, na závěr proběhne sčítání. +-- funkcím, které jsou následně umocněny na druhou, na závěr proběhne sčítání. {-- Typy a typové anotace --} @@ -205,19 +205,19 @@ cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1 "ahoj" : String True : Bool --- Funkce mají také typy. Čtěte -> jako "vrací". +-- Funkce mají také typy. Čtěte "->" jako "vrací". -- O typu na konci uvažujte jako návratovém typu, o ostatních jako typech argumentů. not : Bool -> Bool round : Float -> Int --- Když definujete hodnotu je dobrým zvykem zapsat nad ní její typ. +-- Když definujete hodnotu, je dobrým zvykem zapsat nad ni její typ. -- Anotace je formou dokumentace, která je ověřována překladačem. zdvoj : Int -> Int zdvoj x = x * 2 --- Funkce jako argument je uzavřena v závorkách. +-- Funkce jako parametr je uzavřena v závorkách. -- Typy s malým počátečním písmenem jsou typové proměnné: --- mohou být libovolného typu, ale v každém volání musí být konzistetní. +-- mohou být libovolného typu, ale v každém volání musí být stejné. List.map : (a -> b) -> List a -> List b -- "List tečka map je typu a-vrací-b, vrací seznam-položek-typu-a, vrací seznam-položek-typu-b." @@ -269,8 +269,8 @@ type Strom a = -- "Typ strom-prvků-a je vrchol, nebo uzel obsahující a, strom-prvků-a a strom-prvků-a." -- Vzory se shodují s tagy. Tagy s velkým počátečním písmenem odpovídají přesně. --- Proměnné malým písmem odpovídají čemukoli. Podtržítko jaké odpovídá čemukoli, --- ale symbolizuje, že se nebude dále používat. +-- Proměnné malým písmem odpovídají čemukoli. Podtržítko také odpovídá čemukoli, +-- ale určuje, že tuto hodnotu dále nechceme používat. nejviceVlevo : Strom a -> Maybe a nejviceVlevo strom = case strom of @@ -304,7 +304,7 @@ import Dict -- Stále lze volat Dict.insert. import Dict exposing (Dict) --- Přejmonování importu. +-- Přejmenování importu. import Graphics.Collage as C {-- Porty --} -- cgit v1.2.3 From 5ad3c1d9d197c1226b593bf4fa7243b33cf2e870 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robin=20Pokorn=C3=BD?= Date: Tue, 5 Apr 2016 09:20:00 +0200 Subject: Fix typo --- cs-cz/elm.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cs-cz/elm.html.markdown b/cs-cz/elm.html.markdown index 904507e2..babd46a2 100644 --- a/cs-cz/elm.html.markdown +++ b/cs-cz/elm.html.markdown @@ -143,7 +143,7 @@ vynasob a b = -- Funkci voláme předáním parametrů (bez oddělujících čárek). vynasob 7 6 -- 42 --- Částečně aplikované funkci předáme pouzne některé parametry. +-- Částečně aplikované funkci předáme pouze některé parametry. -- Poté zvolíme nové jméno. zdvoj = vynasob 2 -- cgit v1.2.3 From daf150a9fe26223ad5c2f0dc7c6db4d653def554 Mon Sep 17 00:00:00 2001 From: Witcharrr Date: Tue, 5 Apr 2016 20:01:33 +0300 Subject: Small change MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "A constant" should be translated as a "Константа" --- ru-ru/php-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown index d17f24fc..42c4d360 100644 --- a/ru-ru/php-ru.html.markdown +++ b/ru-ru/php-ru.html.markdown @@ -451,7 +451,7 @@ $value = include 'my-include.php'; class MyClass { - const MY_CONST = 'value'; // A constant + const MY_CONST = 'value'; // Константа static $staticVar = 'static'; -- cgit v1.2.3 From 0aaa5a232c8112775a23ba706347c31525c92c27 Mon Sep 17 00:00:00 2001 From: Bohdan Shtepan Date: Wed, 6 Apr 2016 03:07:54 +0300 Subject: Update ru-ru/c++-ru.html.markdown --- ru-ru/c++-ru.html.markdown | 183 ++++++++++++++++++++++----------------------- 1 file changed, 91 insertions(+), 92 deletions(-) diff --git a/ru-ru/c++-ru.html.markdown b/ru-ru/c++-ru.html.markdown index 5137ec1f..0cf580d5 100644 --- a/ru-ru/c++-ru.html.markdown +++ b/ru-ru/c++-ru.html.markdown @@ -21,7 +21,7 @@ C++ - компилируемый, статически типизированн - язык с поддержкой обобщенного программирования Хотя его синтаксис может показаться более трудным или сложным для понимания, чем в более современных языках, -он широко применяется т.к. код написанный на C++ компилируется в набор инструкций, которые могут быть выполнены напрямую +он широко применяется, так как код, написанный на C++, компилируется в набор инструкций, которые могут быть выполнены напрямую процессором. C++ широко используется для разработки программного обеспечения, являясь одним из самых популярных языков программирования. Область его применения включает создание операционных систем, разнообразных прикладных программ, драйверов устройств, приложений для встраиваемых систем, высокопроизводительных серверов, а также развлекательных приложений (игр). @@ -34,21 +34,21 @@ C++ - компилируемый, статически типизированн // C++ практически представляет собой надмножество C и имеет схожий синтаксис // для объявления переменных, примитивов и функций. -// Также как и в С, точкой входа в программу является функция с именем main, +// Так же, как и в С, точкой входа в программу является функция с именем main, // которая возвращает целочисленное значение. // Это значение является кодом ответа программы. // Смотрите https://goo.gl/JYGKyv для более подробной информации. int main(int argc, char** argv) { - // Аргументы командной строки переданные в программу хранятся в переменных - // argc и argv, также как и в C. + // Аргументы командной строки, переданные в программу, хранятся в переменных + // argc и argv, так же, как и в C. // argc указывает на количество аргументов, - // а argv является масивом C-подобных строк (char*), который непосредсвенно + // а argv является массивом C-подобных строк (char*), который непосредсвенно // содержит аргументы. // Первым аргументом всегда передается имя программы. - // argc и argv могут быть опущены если вы не планируете работать с аругментамы + // argc и argv могут быть опущены, если вы не планируете работать с аругментами // коммандной строки. - // Тогда сигнатура функции будет иметь следующий вид int main() + // Тогда сигнатура функции будет иметь следующий вид: int main() // Возвращаемое значение 0 указывает на успешное завершение программы. return 0; @@ -56,17 +56,17 @@ int main(int argc, char** argv) // Тем не менее, C++ имеет свои отличия: -// В C++, символьные литералы являются символами. +// В C++ символьные литералы имеют тип char. sizeof('c') == sizeof(char) == 1 -// В С, символьные литералы - целые числа. +// В C символьные литералы - целые числа. sizeof('c') == sizeof(int) -// C++ имеет строго прототипирование. +// C++ имеет строгое прототипирование. void func(); // функция, которая не принимает аргументов. -// In C +// В языке C void func(); // функция, которая может принять сколько угодно аргументов. // Использование nullptr вместо NULL в C++. @@ -124,7 +124,7 @@ int main() doSomethingWithInts(20, 5); // a = 20, b = 5 } -// Аргументы по умолчанию должен быть в конце списка аргументов. +// Аргументы по умолчанию должны быть в конце списка аргументов. void invalidDeclaration(int a = 1, int b) // Ошибка! { @@ -162,9 +162,9 @@ void foo() int main() { - // Включает все функци с пространства имен Second в текущую область видимости. + // Включает все функци из пространства имен Second в текущую область видимости. // Обратите внимание, что простой вызов foo() больше не работает, - // так как теперь не ясно вызываем ли мы foo с пространства имен Second или + // так как теперь не ясно, вызываем ли мы foo из пространства имен Second, или // из глобальной области видимости. using namespace Second; @@ -174,11 +174,11 @@ int main() } /////////////// -// Ввод/Вывод +// Ввод и вывод /////////////// -// Вводи и вывод в C++ использует потоки -// cin, cout и cerr предоставлнеы методами stdin, stdout и stderr. +// Ввод и вывод в C++ использует потоки +// cin, cout и cerr представляют потоки stdin, stdout и stderr. // << - оператор вставки, >> - оператор извлечения. #include // Включение файла для работы с потоками Ввода\Вывода. @@ -189,7 +189,7 @@ int main() { int myInt; - // Выводит stdout (или терминал\экран) + // Выводит в stdout (или в терминал/на экран) cout << "Enter your favorite number:\n"; // Принимает ввод cin >> myInt; @@ -208,7 +208,7 @@ int main() // Строки в C++ являются объектами и имеют много функций-членов. #include -using namespace std; // Строки также доступны в пространстве имен std (стандартная библиотек) +using namespace std; // Строки также доступны в пространстве имен std (стандартная библиотека) string myString = "Hello"; string myOtherString = " World"; @@ -227,7 +227,7 @@ cout << myString; // "Hello Dog" // Ссылки ///////////// -// В добавок к указателям доступных в C, +// Кроме указателей, доступных в C, // C++ имеет _ссылки_. // Это такой тип указателя, который не может быть переназначен после инициализации // и не может иметь значения null. @@ -241,11 +241,11 @@ string foo = "I am foo"; string bar = "I am bar"; -string& fooRef = foo; // Здесь создается указатель на foo. +string& fooRef = foo; // Здесь создается ссылка на foo. fooRef += ". Hi!"; // Изменяет foo по ссылке cout << fooRef; // Печатает "I am foo. Hi!" -// Не переназначает "fooRef". Это тоже самое как "foo = bar", и +// Не переназначает "fooRef". Это то же самое, что и "foo = bar", и // foo == "I am bar" // после этой строчки. cout << &fooRef << endl; // Печатает адрес foo @@ -256,31 +256,31 @@ cout << fooRef; // Печатает "I am bar" // Адрес fooRef остается тем же, то есть он по-прежнему ссылается на foo. -const string& barRef = bar; // Создает const со ссылкой на bar. -// Также как и C, значения const (и указателей и ссылок) не могут быть изменены. -barRef += ". Hi!"; // Ошибка, указатель const не может быть изменен. +const string& barRef = bar; // Создает константную ссылку. +// Так же, как и в C, константные значения (а также указатели и ссылки) не могут быть изменены. +barRef += ". Hi!"; // Ошибка, константная ссылка не может быть изменена. -// Обходной путь: Прежде чем мы рассмотрим указатели более детально, нам нужно ознакомится -// с концепцией известной как "временный объект". Представьте, что мы имеем следующий код +// Обходной путь: Прежде чем мы рассмотрим указатели более детально, нам нужно ознакомиться +// с концепцией, известной как "временный объект". Представьте, что мы имеем следующий код string tempObjectFun() { ... } string retVal = tempObjectFun(); -// Вот что на самом деле происходит во второй строе: +// Вот что на самом деле происходит во второй строке: // - tempObjectFun возвращает строковый объект -// - с возвращаемого объекта создается новая строка в качестве аргумента конструктору +// - из возвращаемого объекта создается новая строка в качестве аргумента конструктору // - возвращаемый объект уничтожается -// Возвращаемый объект называется временным объектом. Временные объекты создаются +// Возвращаемый объект называется временным объектом. Временные объекты создаются, // когда функция возвращает объект, и уничтожаются в конце выполнения обрамляющего // выражения (По крайней мере, так это описывает спецификация, хотя компиляторы могут // изменять это поведение. Для более подробной информации смотрите "оптимизация -// возвращаемого значения". Таким образом в этом коде: +// возвращаемого значения".) Таким образом в этом коде: foo(bar(tempObjectFun())) -// предполагая, что foo и bar существуют, объект возвращаемый tempObjectFun передается +// предполагая, что foo и bar существуют, объект, возвращаемый tempObjectFun, передается // в bar, и уничтожается перед вызовом foo. // Возвращаемся к указателям. Исключением для правила "в конце выполнения обрамляющего -// выражения" является временный объект привязанный к ссылке const, в этом случае +// выражения" является временный объект, привязанный к ссылке const, в этом случае // его жизненный цикл продлевается до текущей области видимости: void constReferenceTempObjectFun() { @@ -290,7 +290,7 @@ void constReferenceTempObjectFun() { } // В C++11 предоставлен еще один тип ссылок специально для временных объектов. -// objects. Вы не можете объявить переменную этого типа, но он имеет приоритет в +// objects. Вы не можете объявить переменную этого типа, но он имеет приоритет // в резолюции перегрузки: void someFun(string& s) { ... } // Обычная ссылка @@ -304,7 +304,7 @@ someFun(tempObjectFun()); // Выполняет версию с временн basic_string(const basic_string& other); basic_string(basic_string&& other); -// Идея в том, если мы конструируем новую строку из временного объекта (который +// Идея в том, что если мы конструируем новую строку из временного объекта (который // так или иначе будет уничтожен), мы можем использовать более эффективный конструктор, // который "спасает" части этой временной строки. Эта концепция была названа // "move semantics". @@ -313,7 +313,7 @@ basic_string(basic_string&& other); // Перечисления ///////////////////// -// Перечисления - способ объявления констант и установки их значений в основном +// Перечисления - способ объявления констант и установки их значений, в основном // использующийся для упрощения чтения кода. enum ECarTypes { @@ -346,7 +346,7 @@ void WriteByteToFile(uint8_t InputValue) void WritePreferredCarTypeToFile(ECarTypes InputCarType) { - // Перечисление неявно преобразуется в uint8_t из-за раннее объявленного + // Перечисление неявно преобразуется в uint8_t из-за ранее объявленного // типа перечисления. WriteByteToFile(InputCarType); } @@ -384,7 +384,7 @@ void WritePreferredCarTypeToFile(ECarTypes InputCarType) // Объявление класса. // Обычно классы объявляют в заголовочном (.h или .hpp) файле. class Dog { - // Переменный-члены и функции являются частными по умолчанию. + // Переменные-члены и функции являются приватными по умолчанию. std::string name; int weight; @@ -406,27 +406,26 @@ public: // Функции, которые не изменяют состояние объекта, // должны быть помечены как const. - // Это позволяет вызывать их если дана const ссылка на объект. - // Обратите внимание, функции должны быть явно объявлены как _virtual_ + // Это позволяет вызывать их, если дана const ссылка на объект. + // Обратите внимание, функции должны быть явно объявлены как _virtual_, // если вы хотите перегрузить их в производных классах. - // Функции не являются виртуальными по умолчания для повышения производительности. + // Функции не являются виртуальными по умолчанию для повышения производительности. virtual void print() const; - // Такде функции могут быть определены внутри тела класса. + // Также функции могут быть определены внутри тела класса. // Функции, определенные следующим образом, автоматически встроены. void bark() const { std::cout << name << " barks!\n"; } // Наряду с конструкторами, в C++ есть деструкторы. - // Они вызываются, когда объект удаляется или выпадает с области видимости. - // Это активирует мощную парадигму программирования известную как RAII + // Они вызываются, когда объект удаляется или выпадает из области видимости. + // Это активирует мощную парадигму программирования, известную как RAII // (смотрите ниже) // Деструктор должен быть виртуальным, если класс будет производным. - // Если он не виртуальный, тогда деструктор производного класса не будет вызван + // Если он не виртуальный, тогда деструктор производного класса не будет вызван, // если объект удален по ссылке или указателю базового класса. - // or pointer. virtual ~Dog(); -}; // Определение класса должно завершатся точкой с запятой. +}; // Определение класса должно завершаться точкой с запятой. // Функции-члены класса, как правило, реализуются в .cpp файлах. Dog::Dog() @@ -468,7 +467,7 @@ int main() { // Интерфейсы: // Этот класс наследует все открытые и защищенные члены класса Dog -// также как и все закрытые, но не может непосредственно получить доступ к закрытым +// так же, как и все закрытые, но не может непосредственно получить доступ к закрытым // членам\методам без открытых или защищенных методов для этого. class OwnedDog : public Dog { @@ -477,7 +476,7 @@ class OwnedDog : public Dog { // Переопределяем поведение функции печати для всех OwnedDog. Смотрите // https://goo.gl/3kuH2x для боле общего введения, если вы не знакомы // с концепцией полиморфизма подтипов (включения). - // Ключевое слово override является необязательным, но указывает что метод + // Ключевое слово override является необязательным, но указывает, что метод // на самом деле перегружается в базовом классе. void print() const override; @@ -527,9 +526,9 @@ public: Point (double a, double b) : x(a), y(b) - { /* Ничего не делайте кроме инициализации значений */ } + { /* Ничего не делайте, кроме инициализации значений */ } - // Перегружаем оперот +. + // Перегружаем оператор +. Point operator+(const Point& rhs) const; // Перегружаем оператор +=. @@ -568,9 +567,9 @@ int main () { ///////////////////// // Шаблоны в С++, в основном, используются для обобщенного программирования, хотя -// они гораздо более мощны чем дженерики в других языках. Они также поддерживают +// они гораздо более мощны, чем дженерики в других языках. Они также поддерживают // явные, частные и функциональные типы классов; на самом деле, они являются -// тьюринг-полным языком встроенным в C++! +// тьюринг-полным языком, встроенным в C++! // Мы начнем с наиболее распространенного типа обобщенного программирования. Чтобы // определить класс или функцию, которая принимает параметр типа: @@ -581,9 +580,9 @@ public: void insert(const T&) { ... } }; -// Во время компиляции, компилятор фактически генерирует копии каждого шаблона -// с замещенными параметрами, по-этому полное определение класса должно присутствовать -// при каждом вызове. Именно по-этому классы шаблонов полностью определены в +// Во время компиляции компилятор фактически генерирует копии каждого шаблона +// с замещенными параметрами, поэтому полное определение класса должно присутствовать +// при каждом вызове. Именно поэтому классы шаблонов полностью определены в // заголовочных файлах. // Чтобы создать экземпляр класса шаблона на стеке: @@ -597,11 +596,11 @@ Box > boxOfBox; boxOfBox.insert(intBox); // Вплоть до С++11, вы должны были ставить пробел между двумя символами '>', иначе '>>' -// принимался парсером, как оператор правого сдвига. +// принимался парсером, как оператор сдвига вправо. // Иногда вы можете увидеть // template -// вместо этого. В этом случае, ключевые слова 'class' и 'typename' _в основном_ +// вместо этого. В этом случае ключевые слова 'class' и 'typename' _в основном_ // взаимозаменяемыми. Для более подробной информации смотрите // http://en.wikipedia.org/wiki/Typename // (да-да, это ключевое слово имеет собственную страничку на вики). @@ -616,11 +615,11 @@ void barkThreeTimes(const T& input) } // Обратите внимание, что здесь ничего не указано о типе параметра. Компилятор -// будет генерировать и затем проверять тип каждый вызов шаблона, по-этому +// будет генерировать и затем проверять на тип каждый вызов шаблона, поэтому // данная функция работает с любым типом 'T', который имеет метод 'bark'. Dog fluffy; -fluffy.setName("Fluffy") +fluffy.setName("Fluffy"); barkThreeTimes(fluffy); // Печатает "Fluffy barks" три раза. //Параметры шаблона не должны быть классами: @@ -652,20 +651,20 @@ printMessage<10>(); // Печатает "Learn C++ faster in only 10 minutes!" #include #include -// Все исключения брошены внутри блока _try_ могут быть пойманы в последующем блоке +// Все исключения, брошенные в блоке _try_ могут быть пойманы в последующем блоке // _catch_. try { // Не выделяйте память в куче для исключений с помощью ключевого слова _new_. throw std::runtime_error("A problem occurred"); } -// Поймайте исключение по константной ссылке, если они являются объектами +// Поймайте исключение по константной ссылке, если оно является объектом catch (const std::exception& ex) { std::cout << ex.what(); } -// Ловит любое исключение не пойманное предыдущим блоком _catch_ +// Ловит любое исключение, не пойманное предыдущим блоком _catch_ catch (...) { std::cout << "Unknown exception caught"; @@ -681,7 +680,7 @@ catch (...) // некоторого ресурса неразрывно совмещается с инициализацией, а освобождение - // с уничтожением объекта. -// Чтобы понять на сколько это полезно, +// Чтобы понять, на сколько это полезно, // рассмотрим функцию, которая использует обработчик файлов в С: void doSomethingWithAFile(const char* filename) { @@ -695,31 +694,31 @@ void doSomethingWithAFile(const char* filename) fclose(fh); // Закрываем обработчик файла. } -// К сожалению, вещи быстро осложняется обработкой ошибок. -// Предположим fopen может потерпеть неудачу, тогда doSomethingWithTheFile и -// doSomethingElseWithIt вернут коды ошибок если потерпят неудачу. +// К сожалению, вещи быстро осложняются обработкой ошибок. +// Предположим, fopen может потерпеть неудачу, тогда doSomethingWithTheFile и +// doSomethingElseWithIt вернут коды ошибок, если потерпят неудачу. // (Исключения являются предпочтительным способом обработки ошибок, // но некоторые программисты, особенно те, кто имеет большой опыт работы с С, // не согласны с аргументами о полезности исключений). // Теперь мы должны проверить каждый вызов на наличие ошибок и закрыть обработчик -// файла если таковы есть. +// файла, если он есть. bool doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); // Открывает файл в режиме чтения - if (fh == nullptr) // В случае неудачи возвращаемый указатель принимает null. - return false; // Сообщает об неудаче вызывающему. + if (fh == nullptr) // В случае неудачи возвращаемый указатель принимает значение null. + return false; // Сообщает о неудаче вызывающему. // Предположим, каждая функция возвращает false в случае неудачи if (!doSomethingWithTheFile(fh)) { - fclose(fh); // Закрываем обработчик файл чтобы не было утечек + fclose(fh); // Закрываем обработчик файла, чтобы не было утечек return false; // Сообщает об ошибке. } if (!doSomethingElseWithIt(fh)) { - fclose(fh); // Закрываем обработчик файл чтобы не было утечек + fclose(fh); // Закрываем обработчик файла, чтобы не было утечек return false; // Сообщает об ошибке. } - fclose(fh); // Закрываем обработчик файл чтобы не было утечек + fclose(fh); // Закрываем обработчик файла, чтобы не было утечек return true; // Указывает на успех } @@ -736,7 +735,7 @@ bool doSomethingWithAFile(const char* filename) if (!doSomethingElseWithIt(fh)) goto failure; - fclose(fh); // Close the file + fclose(fh); // Закрываем файл. return true; // Указывает на успех failure: @@ -761,12 +760,12 @@ void doSomethingWithAFile(const char* filename) throw; // Затем повторно бросает исключение. } - fclose(fh); // Close the file + fclose(fh); // Закрываем файл. // Успех } // Сравните это с использованием класса потока файла (fstream) в С++, который -// использует свой деструктор чтобы закрыть файл. Еще раз взгляните выше, +// использует свой деструктор, чтобы закрыть файл. Еще раз взгляните выше, // деструктор вызывается автоматически, когда объект выпадает из области видимости. void doSomethingWithAFile(const std::string& filename) { @@ -781,26 +780,26 @@ void doSomethingWithAFile(const std::string& filename) // Это имеет _огромнейшие_ преимущества: // 1. Неважно, что произойдет, -// ресурсы (в данном случае обработчик файлов) будут очищены. -// После того, как вы правильно напишите деструктор, -// Больше будет _не возможно_ закрыть обработчик файлов или допустить утечку. +// ресурсы (в данном случае дескриптор файла) будут очищены. +// После того, как вы правильно напишете деструктор, +// Больше будет _невозможно_ закрыть обработчик файлов или допустить утечку. // 2. Обратите внимание, что код намного проще. -// Деструктор закрывает файловый поток "за кулисами" и вам больше не нужно об -// этом беспокоится. +// Деструктор закрывает файловый поток "за кулисами", и вам больше не нужно об +// этом беспокоиться. // 3. Код устойчив к исключениям. -// Исключение может быть брошено в любом месте в функции и это никак не повлияет +// Исключение может быть брошено в любом месте в функции, и это никак не повлияет // на очистку. // Весь идиоматический код на С++ широко использует RAII для всех ресурсов. -// Дополнительные примеры включат +// Дополнительные примеры включат: // - Использование памяти unique_ptr и shared_ptr // - Контейнеры - стандартная библиотека связанных списков, векторы -// (т.е. самоизменяемые массивы), хэш-карты и все остальное автоматически -// уничтожается сразу-же, когда выходит за пределы области видимости. -// - Ипользование мютексов lock_guard и unique_lock +// (т.е. самоизменяемые массивы), хэш-таблицы и все остальное автоматически +// уничтожается сразу же, когда выходит за пределы области видимости. +// - Ипользование мьютексов lock_guard и unique_lock // Контейнеры с пользовательскими классами в качестве ключей требуют -// функций-компаратор в самом объекте или как указатель на функцию. Примитивы +// сравнивающих функций в самом объекте или как указатель на функцию. Примитивы // имеют компараторы по умолчанию, но вы можете перегрузить их. class Foo { public: @@ -822,7 +821,7 @@ fooMap.find(Foo(1)); //true // Веселые вещи ///////////////////// -// Аспекты С++, которые могут быть удивительными для новичком (и даже для некоторых +// Аспекты С++, которые могут быть удивительными для новичков (и даже для некоторых // ветеранов). Этот раздел, к сожалению, очень неполон. С++ является одним из самых // простых языков, где очень легко выстрелить себе в ногу. @@ -838,7 +837,7 @@ class FooSub : public Foo { // 0 == false == NULL (в основном)! bool* pt = new bool; *pt = 0; // Устанавливает значение указателя 'pt' в false. -pt = 0; // Устанавливает значение 'pt' в нулевой указатель. Обе линии проходят +pt = 0; // Устанавливает значение 'pt' в нулевой указатель. Обе строки проходят // компиляцию без ошибок. // nullptr приходит на помощь: @@ -875,17 +874,17 @@ vector v; for (int i = 0; i < 10; ++i) v.push_back(Foo()); -// В слудующей точке размер v устанавливается в 0, но деструктор не вызывается +// В следующей точке размер v устанавливается в 0, но деструктор не вызывается // и не происходит очистка ресурсов! v.empty(); v.push_back(Foo()); // Новые значения копируются в первый вставленный Foo -// Настоящие уничтожение всех значений v. Смотрите раздел о временном объекте +// Настоящее уничтожение всех значений v. Смотрите раздел о временном объекте // для объяснения того, как это работает. v.swap(vector()); ``` -Дальнейшее чтение: +## Дальнейшее чтение: Наиболее полное и обновленное руководство по С++ можно найти на -- cgit v1.2.3 From 591eab5e4f8f0a27306588d78964a4879368ca6c Mon Sep 17 00:00:00 2001 From: jesusjjf Date: Tue, 5 Apr 2016 20:02:46 -0700 Subject: grammar + spelling errors --- objective-c.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 097cb846..0dbb3ae3 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -110,7 +110,7 @@ int main (int argc, const char * argv[]) NSLog(@"%f", piDouble); NSLog(@"%4.2f", piDouble); // prints => "3.14" - // NSDecimalNumber is a fixed-point class that's more precise then float or double + // NSDecimalNumber is a fixed-point class that's more precise than float or double NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"]; NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"]; // NSDecimalNumber isn't able to use standard +, -, *, / operators so it provides its own: @@ -700,7 +700,7 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { // NOTE: If two or more protocols rely on each other, make sure to forward-declare them: #import "Brother.h" -@protocol Brother; // Forward-declare statement. Without it, compiler would through error. +@protocol Brother; // Forward-declare statement. Without it, compiler will throw error. @protocol Sister -- cgit v1.2.3 From f6b16c69bb7631be65b60f866928d06dc6453e96 Mon Sep 17 00:00:00 2001 From: Dan Book Date: Fri, 15 Apr 2016 03:23:10 -0400 Subject: [perl/en] Fix line formatting and use $x instead of $a --- perl.html.markdown | 85 +++++++++++++++++++++++++++++------------------------- 1 file changed, 45 insertions(+), 40 deletions(-) diff --git a/perl.html.markdown b/perl.html.markdown index 61e8cd0e..3cbd2801 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -21,9 +21,9 @@ use strict; use warnings; # All perl scripts and modules should include these lines. Strict causes -# compilation to fail in cases like misspelled variable names, and warnings -# will print warning messages in case of common pitfalls like concatenating -# to an undefined value. +# compilation to fail in cases like misspelled variable names, and +# warnings will print warning messages in case of common pitfalls like +# concatenating to an undefined value. #### Perl variable types @@ -47,8 +47,8 @@ my @animals = ("camel", "llama", "owl"); my @numbers = (23, 42, 69); my @mixed = ("camel", 42, 1.23); -# Array elements are accessed using square brackets, with a $ to indicate -# one value will be returned. +# Array elements are accessed using square brackets, with a $ to +# indicate one value will be returned. my $second = $animals[1]; ## Hashes @@ -56,7 +56,8 @@ my $second = $animals[1]; my %fruit_color = ("apple", "red", "banana", "yellow"); -# You can use whitespace and the "=>" operator to lay them out more nicely: +# You can use whitespace and the "=>" operator to lay them out more +# nicely: my %fruit_color = ( apple => "red", @@ -71,8 +72,8 @@ my $color = $fruit_color{apple}; #### References -# More complex data types can be constructed using references, which allow -# you to build arrays and hashes within arrays and hashes. +# More complex data types can be constructed using references, which +# allow you to build arrays and hashes within arrays and hashes. my $array_ref = \@array; my $hash_ref = \%hash; @@ -88,13 +89,14 @@ my $colors = {apple => "red", banana => "yellow"}; my @fruits_array = @$fruits; my %colors_hash = %$colors; -# As a shortcut, the arrow operator can be used to dereference and access a -# single value. +# As a shortcut, the arrow operator can be used to dereference and +# access a single value. my $first = $array_ref->[0]; my $value = $hash_ref->{banana}; -# See perlreftut and perlref for more in-depth documentation on references. +# See perlreftut and perlref for more in-depth documentation on +# references. #### Conditional and looping constructs @@ -150,18 +152,18 @@ print $hash_ref->{$_} for keys %$hash_ref; #### Regular expressions -# Perl's regular expression support is both broad and deep, and is the subject -# of lengthy documentation in perlrequick, perlretut, and elsewhere. -# However, in short: +# Perl's regular expression support is both broad and deep, and is the +# subject of lengthy documentation in perlrequick, perlretut, and +# elsewhere. However, in short: # Simple matching if (/foo/) { ... } # true if $_ contains "foo" -if ($a =~ /foo/) { ... } # true if $a contains "foo" +if ($x =~ /foo/) { ... } # true if $x contains "foo" # Simple substitution -$a =~ s/foo/bar/; # replaces foo with bar in $a -$a =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar in $a +$x =~ s/foo/bar/; # replaces foo with bar in $x +$x =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar in $x #### Files and I/O @@ -172,9 +174,10 @@ open(my $in, "<", "input.txt") or die "Can't open input.txt: $!"; open(my $out, ">", "output.txt") or die "Can't open output.txt: $!"; open(my $log, ">>", "my.log") or die "Can't open my.log: $!"; -# You can read from an open filehandle using the "<>" operator. In scalar -# context it reads a single line from the filehandle, and in list context it -# reads the whole file in, assigning each line to an element of the list: +# You can read from an open filehandle using the "<>" operator. In +# scalar context it reads a single line from the filehandle, and in list +# context it reads the whole file in, assigning each line to an element +# of the list: my $line = <$in>; my @lines = <$in>; @@ -197,9 +200,9 @@ logger("We have a logger subroutine!"); #### Modules -# A module is a set of Perl code, usually subroutines, which can be used in -# other Perl code. It is usually stored in a file with the extension .pm so -# that Perl can find it. +# A module is a set of Perl code, usually subroutines, which can be used +# in other Perl code. It is usually stored in a file with the extension +# .pm so that Perl can find it. package MyModule; use strict; @@ -219,24 +222,25 @@ sub trim { use MyModule; MyModule::trim($string); -# The Exporter module can help with making subroutines exportable, so they -# can be used like this: +# The Exporter module can help with making subroutines exportable, so +# they can be used like this: use MyModule 'trim'; trim($string); -# Many Perl modules can be downloaded from CPAN (http://www.cpan.org/) and -# provide a range of features to help you avoid reinventing the wheel. A -# number of popular modules like Exporter are included with the Perl -# distribution itself. See perlmod for more details on modules in Perl. +# Many Perl modules can be downloaded from CPAN (http://www.cpan.org/) +# and provide a range of features to help you avoid reinventing the +# wheel. A number of popular modules like Exporter are included with +# the Perl distribution itself. See perlmod for more details on modules +# in Perl. #### Objects -# Objects in Perl are just references that know which class (package) they -# belong to, so that methods (subroutines) called on it can be found there. -# The bless function is used in constructors (usually new) to set this up. -# However, you never need to call it yourself if you use a module like Moose -# or Moo (see below). +# Objects in Perl are just references that know which class (package) +# they belong to, so that methods (subroutines) called on it can be +# found there. The bless function is used in constructors (usually new) +# to set this up. However, you never need to call it yourself if you use +# a module like Moose or Moo (see below). package MyCounter; use strict; @@ -260,7 +264,8 @@ sub increment { 1; -# Methods can be called on a class or object instance with the arrow operator. +# Methods can be called on a class or object instance with the arrow +# operator. use MyCounter; my $counter = MyCounter->new; @@ -268,9 +273,9 @@ print $counter->count, "\n"; # 0 $counter->increment; print $counter->count, "\n"; # 1 -# The modules Moose and Moo from CPAN can help you set up your object classes. -# They provide a constructor and simple syntax for declaring attributes. This -# class can be used equivalently to the one above. +# The modules Moose and Moo from CPAN can help you set up your object +# classes. They provide a constructor and simple syntax for declaring +# attributes. This class can be used equivalently to the one above. package MyCounter; use Moo; # imports strict and warnings @@ -284,8 +289,8 @@ sub increment { 1; -# Object-oriented programming is covered more thoroughly in perlootut, and its -# low-level implementation in Perl is covered in perlobj. +# Object-oriented programming is covered more thoroughly in perlootut, +# and its low-level implementation in Perl is covered in perlobj. ``` #### FAQ -- cgit v1.2.3 From 0edf991301fc4bafeda383649361c67f2f4e0235 Mon Sep 17 00:00:00 2001 From: Vojta Svoboda Date: Fri, 15 Apr 2016 12:08:55 +0200 Subject: [hack/cs] Add cs_CZ locale for Hack * [hack/cs] Add cs_CZ locale for Hack * Add -cs suffix Add -cs suffix --- cs-cz/hack.html.markdown | 309 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 309 insertions(+) create mode 100644 cs-cz/hack.html.markdown diff --git a/cs-cz/hack.html.markdown b/cs-cz/hack.html.markdown new file mode 100644 index 00000000..736ad7e0 --- /dev/null +++ b/cs-cz/hack.html.markdown @@ -0,0 +1,309 @@ +--- +language: Hack +filename: learnhack-cs.hh +contributors: + - ["Stephen Holdaway", "https://github.com/stecman"] +translators: + - ["Vojta Svoboda", "https://github.com/vojtasvoboda/"] +lang: cs-cz +--- + +Hack je nadmnožinou PHP a běží v rámci virtuálního stroje zvaného HHVM. Hack +dokáže skoro plně spolupracovat s existujícím PHP a přidává několik vylepšení, +které známe ze staticky typovaných jazyků. + +Níže jsou popsané pouze vlastnosti jazyka Hack. Detaily ohledně jazyka PHP a jeho +syntaxe pak najdete na těchto stránkách v samostatném +[článku o PHP](http://learnxinyminutes.com/docs/php/). + +```php +id = $id; + } +} + + +// Stručné anonymní funkce (lambda funkce) +$multiplier = 5; +array_map($y ==> $y * $multiplier, [1, 2, 3]); + + +// Generika (generické funkce) +class Box +{ + protected T $data; + + public function __construct(T $data) { + $this->data = $data; + } + + public function getData(): T { + return $this->data; + } +} + +function openBox(Box $box) : int +{ + return $box->getData(); +} + + +// Tvary +// +// Hack zavádí koncept tvaru pro definování strukturovaných polí s garantovanou +// typovou kontrolou pro klíče. +type Point2D = shape('x' => int, 'y' => int); + +function distance(Point2D $a, Point2D $b) : float +{ + return sqrt(pow($b['x'] - $a['x'], 2) + pow($b['y'] - $a['y'], 2)); +} + +distance( + shape('x' => -1, 'y' => 5), + shape('x' => 2, 'y' => 50) +); + + +// Type aliasing +// +// Hack přidává několik vylepšení pro lepší čitelnost komplexních typů +newtype VectorArray = array>; + +// Množina obsahující čísla +newtype Point = (int, int); + +function addPoints(Point $p1, Point $p2) : Point +{ + return tuple($p1[0] + $p2[0], $p1[1] + $p2[1]); +} + +addPoints( + tuple(1, 2), + tuple(5, 6) +); + + +// Výčtový typ +enum RoadType : int +{ + Road = 0; + Street = 1; + Avenue = 2; + Boulevard = 3; +} + +function getRoadType() : RoadType +{ + return RoadType::Avenue; +} + + +// Automatické nastavení proměnných třídy +// +// Aby se nemuseli definovat proměnné třídy a její konstruktor, +// který pouze nastavuje třídní proměnné, můžeme v Hacku vše +// definovat najednou. +class ArgumentPromotion +{ + public function __construct(public string $name, + protected int $age, + private bool $isAwesome) {} +} + +// Takto by to vypadalo bez automatického nastavení proměnných +class WithoutArugmentPromotion +{ + public string $name; + + protected int $age; + + private bool $isAwesome; + + public function __construct(string $name, int $age, bool $isAwesome) + { + $this->name = $name; + $this->age = $age; + $this->isAwesome = $isAwesome; + } +} + + +// Ko-operativní multi-tasking +// +// Nová klíčová slova "async" and "await" mohou být použité pro spuštění mutli-taskingu +// Tato vlastnost ovšem zahrnuje vícevláknové zpracování, pouze povolí řízení přenosu +async function cooperativePrint(int $start, int $end) : Awaitable +{ + for ($i = $start; $i <= $end; $i++) { + echo "$i "; + + // Dává ostatním úlohám šanci něco udělat + await RescheduleWaitHandle::create(RescheduleWaitHandle::QUEUE_DEFAULT, 0); + } +} + +// Toto vypíše "1 4 7 2 5 8 3 6 9" +AwaitAllWaitHandle::fromArray([ + cooperativePrint(1, 3), + cooperativePrint(4, 6), + cooperativePrint(7, 9) +])->getWaitHandle()->join(); + + +// Atributy +// +// Atributy jsou určitou formou metadat pro funkce. Hack přidává některé vestavěné +// atributy které aktivnují uživatečné chování funkcí. + +// Speciální atribut __Memoize způsobí, že výsledek funkce je uložen do cache +<<__Memoize>> +function doExpensiveTask() : ?string +{ + return file_get_contents('http://example.com'); +} + +// Tělo funkce je v tomto případě vykonáno pouze jednou: +doExpensiveTask(); +doExpensiveTask(); + + +// Speciální atribut __ConsistentConstruct signalizuje typové kontrole Hacku, že +// zápis __construct bude stejný pro všechny podtřídy. +<<__ConsistentConstruct>> +class ConsistentFoo +{ + public function __construct(int $x, float $y) + { + // ... + } + + public function someMethod() + { + // ... + } +} + +class ConsistentBar extends ConsistentFoo +{ + public function __construct(int $x, float $y) + { + // Typová kontrola Hacku zajistí volání konstruktoru rodičovské třídy + parent::__construct($x, $y); + + // ... + } + + // Anotace __Override je volitelný signál pro typovou kontrolu Hacku, že + // tato metoda přetěžuje metodu rodičovské třídy, nebo traitu. Bez uvedení + // této anotace vyhodí typová kontrola chybu. + <<__Override>> + public function someMethod() + { + // ... + } +} + +class InvalidFooSubclass extends ConsistentFoo +{ + // Nedodržení zápisu dle rodičovského konstruktoru způsobí syntaktickou chybu: + // + // "Tento objekt je typu ConsistentBaz a není kompatibilní v tímto objektem, + // který je typu ConsistentFoo protože některé jeho metody nejsou kompatibilní." + // + public function __construct(float $x) + { + // ... + } + + // Použitím anotace __Override na nepřetíženou metodu způsobí chybu typové kontroly: + // + // "InvalidFooSubclass::otherMethod() je označená jako přetížená, ale nebyla nalezena + // taková rodičovská metoda, nebo rodič kterého přetěžujete není zapsán v > + public function otherMethod() + { + // ... + } +} + + +// Traity mohou implementovat rozhraní, což standardní PHP neumí +interface KittenInterface +{ + public function play() : void; +} + +trait CatTrait implements KittenInterface +{ + public function play() : void + { + // ... + } +} + +class Samuel +{ + use CatTrait; +} + + +$cat = new Samuel(); +$cat instanceof KittenInterface === true; // True + +``` + +## Více informací + +Pro více informací navštivte [referenční příručku jazyka Hack](http://docs.hhvm.com/manual/en/hacklangref.php), +kde se dozvíte více detailu a vylepšení, které jazyk Hack přidává do PHP, a nebo navštivte [oficiální stránky jazyka Hack](http://hacklang.org/) +pro obecné informace. + +Pro instrukce k instalaci jazyka Hack navštivte [oficiální HHVM stránky](http://hhvm.com/). + +Pro více informací ohledně zpětné kompatibility s PHP navštivte článek o [nepodporovaných PHP vlastnostech Hacku](http://docs.hhvm.com/manual/en/hack.unsupported.php). -- cgit v1.2.3 From 8fadd651784ace9109cf71447a58917899a44b93 Mon Sep 17 00:00:00 2001 From: Martin Schimandl Date: Fri, 15 Apr 2016 19:11:30 +0200 Subject: Remove unnecessary meta info --- de-de/perl-de.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/de-de/perl-de.html.markdown b/de-de/perl-de.html.markdown index b51731b9..016c273f 100644 --- a/de-de/perl-de.html.markdown +++ b/de-de/perl-de.html.markdown @@ -1,6 +1,4 @@ --- -name: perl -category: language language: perl filename: learnperl-de.pl contributors: -- cgit v1.2.3 From 2e77f54c34fb8d8818c43fbb84711188b0e5cb8b Mon Sep 17 00:00:00 2001 From: "Andreas Loizou (LACK3R)" Date: Sun, 17 Apr 2016 00:56:09 +0300 Subject: [Java/el] Translated Java to Greek [Java/el] Translated Java to Greek --- el-gr/java-gr.html.markdown | 858 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 858 insertions(+) create mode 100644 el-gr/java-gr.html.markdown diff --git a/el-gr/java-gr.html.markdown b/el-gr/java-gr.html.markdown new file mode 100644 index 00000000..10784d54 --- /dev/null +++ b/el-gr/java-gr.html.markdown @@ -0,0 +1,858 @@ +--- +language: java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Jakukyo Friel", "http://weakish.github.io"] + - ["Madison Dickson", "http://github.com/mix3d"] + - ["Simon Morgan", "http://sjm.io/"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] + - ["Rachel Stiyer", "https://github.com/rstiyer"] +filename: LearnJava.java +translators: + - ["Andreas Loizou" , "https://github.com/lack3r/"] +lang: el-gr +--- + +H Java είναι μία γενικού-σκοπού, συντρέχων (concurrent), βασισμένη σε κλάσεις, +αντικειμενοστρεφής (object oriented) γλώσσα προγραμματισμού. +[Διαβάστε περισσότερα εδώ.](http://docs.oracle.com/javase/tutorial/java/) + +```java +// Τα σχόλια μονής γραμμής ξεκινούν με // +/* +Τα σχόλια πολλών γραμμών μοιάζουν κάπως έτσι. +*/ +/** +Τα σχόλια JavaDoc μοιάζουν κάπως έτσι. Χρησιμοποιούνται για να περιγράψουν την +Κλάση ή διάφορα χαρακτηριστικά της Κλάσης. +*/ + +// Εισαγωγή της κλάσης ArrayList η οποία βρίσκεται εντός του πακέτου java.util +import java.util.ArrayList; +// Εισαγωγή όλων των κλάσεων που βρίσκονται εντός του πακέτου java.security +import java.security.*; + +// Κάθε αρχείο .java περιέχει μία δημόσια(public) κλάση εξωτερικού-επιπέδου +// (outer-level), η οποία έχει το ίδιο ονομα με το αρχείο. +public class LearnJava { + + // Για να τρέξει ένα πρόγραμμα java, πρέπει να έχει μία κύρια μέθοδο (main + // method) ως αρχικό σημείο. + public static void main (String[] args) { + + // Χρησιμοποιούμε τη μέθοδο System.out.println() για να τυπώσουμε + // γραμμές. + System.out.println("Hello World!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Για να τυπώσουμε χωρίς να τυπωθεί αλλαγή γραμμής (newline), + // χρησιμοποιούμε System.out.print(). + System.out.print("Hello "); + System.out.print("World"); + + // Χρησιμοποιούμε τη μέθοδο System.out.printf() για έυκολη μορφοποίηση + // της εκτύπωσης. + System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159 + + /////////////////////////////////////// + // Μεταβλητές(Variables) + /////////////////////////////////////// + + /* + * Δήλωση Μεταβλητών + */ + // Δηλώνουμε μία μεταβλητή χρησιμοποιώντας τη μορφή + // <Τύπος Μεταβλητής> <Όνομα Μεταβλητής> + int fooInt; + // Δηλώνουμε πολλαπλές μεταβλητές ίδιου τύπου χρησιμοποιώντας τη μορφή + // <Τύπος> <Όνομα1>, <Όνομα2>, <Όνομα3> + int fooInt1, fooInt2, fooInt3; + + /* + * Αρχικοποίηση Μεταβλητών + */ + + // Αρχικοποιούμε μια μεταβλητή χρησιμοποιώντας τη μορφή + // <τύπος> <όνομα> = <τιμή> + int fooInt = 1; + // Αρχικοποιούμε πολλαπλές μεταβλητές ιδίου τύπου με την ίδια τιμή + // χρησιμοποιώντας <τύπος> <Όνομα1>, <Όνομα2>, <Όνομα3> = <τιμή> + int fooInt1, fooInt2, fooInt3; + fooInt1 = fooInt2 = fooInt3 = 1; + + /* + * Τύποι μεταβλητών + */ + // Byte - 8-bit signed two's complement integer + // (-128 <= byte <= 127) + byte fooByte = 100; + + // Short - 16-bit signed two's complement integer + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Integer - 32-bit signed two's complement integer + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Long - 64-bit signed two's complement integer + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // Το L χρησιμοποιείται για να δηλώσει ότι η συγκεκριμένη τιμή της + // μεταβλητής είναι τύπου Long; + // Ό,τιδήποτε χρησιμοποιείται χωρίς αυτό τυχαίνει μεταχείρισης όπως + // μία τιμή μεταβλητής integer by default. + + // Σημείωση: Η Java δεν έχει unsigned τύπους. + + // Float - Single-precision 32-bit IEEE 754 Floating Point + // 2^-149 <= float <= (2-2^-23) * 2^127 + float fooFloat = 234.5f; + // f or F χρησιμοποιείται για να δηλώσει ότι η συγκεκριμένη τιμή + // μεταβλητής είναι τύπου float; + // αλλιώς τυγχαίνει μεταχείρισης όπως μία τιμή μεταβλητής double. + + // Double - Double-precision 64-bit IEEE 754 Floating Point + // 2^-1074 <= x <= (2-2^-52) * 2^1023 + double fooDouble = 123.4; + + // Boolean - Αληθής και Ψευδής (true & false) + boolean fooBoolean = true; + boolean barBoolean = false; + + // Char - Ένας μόνο χαρακτήρας 16-bit Unicode + char fooChar = 'A'; + + // Οι μεταβλητές final δεν μπορούν να ανατεθούν ξανά σε άλλο + // αντικείμενο, + final int HOURS_I_WORK_PER_WEEK = 9001; + // αλλά μπορούν να αρχικοποιηθούν αργότερα. + final double E; + E = 2.71828; + + + // BigInteger - Immutable αυθαίρετης-ακρίβειας ακέραιος + // + // Ο BigInteger είναι ένας τύπος δεδομένων ο οποίος επιτρέπει στους + // προγραμματιστές να χειρίζονται ακέραιους μεγαλύτερους από 64-bits. + // Οι ακέραιοι αποθηκεύονται ως πίνακας από bytes και τυχαίνουν + // επεξεργασίας χρησιμοποιώντας συναρτήσεις εσωματωμένες στην κλάση + // BigInteger + // Ένας BigInteger μπορεί να αρχικοποιηθεί χρησιμοποιώντας ένα πίνακα + // από bytes ή γραμματοσειρά (string). + + BigInteger fooBigInteger = new BigInteger(fooByteArray); + + + // BigDecimal - Immutable, αυθαίρετης-ακρίβειας, εμπρόσημος (signed) + // δεκαδικός αριθμός + // + // Ένας BigDecimal παίρνει δύο μέρη: Μία αυθαίρετης ακρίβειας, + // ακέραια, unscaled τιμή και μία κλιμάκωση(scale) ως ένα 32-bit + // ακέραιο (integer). + // + // Ο BigDecimal επιτρέπει στον προγραμματιστή να έχει πλήρη έλεγχο + // όσον αφορά τη δεκαδική στρογγυλοποίηση (rounding). Προτείνεται η + // χρήση του BigDecimal με τιμές νομισμάτων και όπου απαιτείται η + // ακριβής δεκαδική ακρίβεια. + // + // Ο BigDecimal μπορεί να αρχικοποιηθεί με int, long, double ή String + // ή με την αρχικοποίηση της unscaled τιμής (BigInteger) και της + // κλίμακας (scale) (int). + + BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); + + // Χρειάζεται να είμαστε προσεκτικοί με τον κατασκευαστή (constructor) + // ο οποίος παίρνει float ή double καθώς η ανακρίβεια του float/double + // θα αντιγραφεί στον BigDecimal. + // Είναι προτιμότερο να χρησιμοποιείται ο κατασκευαστής String (String + // constructor) όταν χρειάζεται ακριβής τιμή. + + BigDecimal tenCents = new BigDecimal("0.1"); + + // Strings - Γραμματοσειρές + String fooString = "My String Is Here!"; + + // Ο χαρακτήρας \n είναι ένας χαρακτήρας διαφυγής (escaped character) + // ο οποίος ξεκινά μία νέα γραμμή + String barString = "Printing on a new line?\nNo Problem!"; + // Ο χαρακτήρας \t είναι ένας χαρακτήρας διαφυγής (escaped character) + // ο οποίος προσθέτει ένα χαρακτήρα tab + String bazString = "Do you want to add a tab?\tNo Problem!"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // Πίνακες (Arrays) + // Το μέγεθος του πίνακα πρέπει να αποφασιστεί με την αρχικοποίηση του + // πίνακα + // Οι ακόλουθες μορφές μπορούν να χρησιμοποιηθούν για την δήλωση ενός + // πίνακα + // <Τυπος δεδομένων>[] <Όνομα Μεταβλητής> = new <Τύπος Δεδομένων>[<μέγεθος πίνακα>]; + // <Τυπος δεδομένων> <Όνομα Μεταβλητής>[] = new <Τυπος δεδομένων>[<μέγεθος πίνακα>]; + int[] intArray = new int[10]; + String[] stringArray = new String[1]; + boolean boolArray[] = new boolean[100]; + + // Ακόμη ένας τρόπος για να δηλώσεις (to declare) και να + // αρχικοποιήσεις ένα πίνακα + int[] y = {9000, 1000, 1337}; + String names[] = {"Bob", "John", "Fred", "Juan Pedro"}; + boolean bools[] = new boolean[] {true, false, false}; + + // Ευρετηρίαση (indexing) ενός πίνακα - Πρόσβαση (accessing) ενός + // στοιχείου + System.out.println("intArray @ 0: " + intArray[0]); + + // Οι πίνακες ξεκινούν από το μηδέν (zero-indexed) και είναι ευμετάβλητοι (mutable). + intArray[1] = 1; + System.out.println("intArray @ 1: " + intArray[1]); // => 1 + + // Παρόμοια + // ArrayLists - Παρόμοιοι με τους πίνακες με τη διαφορά ότι προσφέρουν + // περισσότερη λειτουργικότητα και το μέγεθος είναι ευμετάβλητο + // (mutable). + // LinkedLists - Υλοποίηση διπλά-συνδεδεμένης λίστας(doubly-linked + // list). Όλες οι λειτουργίες εκτελώνται όπως αναμένεται σε μία διπλά + // συνδεδεμένη (doubly-linked) λίστα. + // Maps - Ένα σύνολο αντικειμένων τα οποία συνδέου (map) κλειδιά (keys) + // σε τιμές (values). Ο Map είναι διεπαφή (interface) και συνεπώς δεν + // μπορεί να συγκεκριμενοποίηθεί (instantiated). + // Ο τύπος των κλειδιών και των τιμών τα οποία συμπεριλαμβάνονται σε + // ένα Map πρέπει να καθοριστεί κατά τη διάρκεια της + // συγκεκριμενοποίησης (instantiation) της κλάσης που υλοποιεί τη + // διεπαφή Map. Κάθε κλειδί (key) μπορεί να συνδεθεί (map) σε μόνο μία + // αντίστοιχη τιμή και κάθε κλειδί μπορεί να εμφανιστεί μόνο μία φορά + // (no duplicates). + // HashMaps - Η κλάση αυτή χρησιμοποιεί ένα πίνακα-κατακερματισμού + // (hashtable) για να υλοποιήσει τη διεπαφή Map. Αυτό επιτρέπει το + // χρόνο εκτέλεσης βασικών λειτουργιών, όπως της get και insert + // στοιχείου να παραμείνει σταθερός (constant) ακόμη και για μεγάλα + // σύνολα (sets.) + + + /////////////////////////////////////// + // Τελεστές (Operators) + /////////////////////////////////////// + System.out.println("\n->Operators"); + + int i1 = 1, i2 = 2; // Συντομογραφία για πολλαπλές δηλώσεις + + // Οι αριθμητικοί τελεστές είναι απλοί + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns int) + System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 + + // Υπόλοιπο (Modulo) + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Τελεστές σύγκρισης + System.out.println("3 == 2? " + (3 == 2)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // Λογικοί Τελεστές (Boolean) + System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false + System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true + System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true + + // Τελεστές πράξεων με bits (Bitwise)! + /* + ~ bitwise τελεστής μοναδιαίου συμπληρώματος (Unary bitwise complement) + << Προσημασμένη ολίσθηση αριστερά (Signed left shift) + >> Προσημασμένη/Αριθμητική ολίσθηση Δεξιά (Signed/Arithmetic right shift) + >>> Μη προσημασμένη/Λογική ολίσθηση δεξιά (Unsigned/Logical right shift) + & Διαδικός τελεστής AND (Bitwise AND) + ^ Διαδικός τελεστής XOR (Bitwise exclusive OR) + | Διαδικός τελεστής OR (Bitwise inclusive OR) + */ + + // Αυξητικοί τελεστές + int i = 0; + System.out.println("\n->Inc/Dec-rementation"); + // Οι τελεστές ++ και -- μειώνουν και αυξάνουν κατά 1 αντίστοιχα. + // Εάν τοποθετητούν πριν τη μεταβλητή, αυξάνουν και μετά επιστρέφουν. + // Μετά τη μεταβλητή επιστρέφουν και μετά αυξάνουν. + System.out.println(i++); // i = 1, τυπώνει 0 (post-increment) + System.out.println(++i); // i = 2, τυπώνει 2 (pre-increment) + System.out.println(i--); // i = 1, τυπώνει 2 (post-decrement) + System.out.println(--i); // i = 0, τυπώνει 0 (pre-decrement) + + /////////////////////////////////////// + // Δομές ελέγχου (Control Structures) + /////////////////////////////////////// + System.out.println("\n->Control Structures"); + + // Οι δηλώσεις If είναι c-like + int j = 10; + if (j == 10) { + System.out.println("I get printed"); + } else if (j > 10) { + System.out.println("I don't"); + } else { + System.out.println("I also don't"); + } + + // Επανάληψη While (While loop) + int fooWhile = 0; + while(fooWhile < 100) { + System.out.println(fooWhile); + // Άυξησε τον μετρητή + // Επανάλαβε 100 φορές, fooWhile 0,1,2...99 + fooWhile++; + } + System.out.println("fooWhile Value: " + fooWhile); + + // Επανάληψη Do While (Do While Loop) + int fooDoWhile = 0; + do { + System.out.println(fooDoWhile); + // Άυξησε το μετρητή(counter) + // Επανάλαβε 99 times, fooDoWhile 0->99 + fooDoWhile++; + } while(fooDoWhile < 100); + System.out.println("fooDoWhile Value: " + fooDoWhile); + + // Επανάληψη For (For Loop) + // Δομή επανάληψης for => + // for(<Αρχική Δήλωση>; <προυπόθεση (conditional)>; <βήμα (step)>) + for (int fooFor = 0; fooFor < 10; fooFor++) { + System.out.println(fooFor); + // Iterated 10 times, fooFor 0->9 + } + System.out.println("fooFor Value: " + fooFor); + + // Έξοδος από εμφωλευμένη (nested) επανάληψη For με ετικέττα (Label) + outer: + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // δραπετεύει εκτός της εξωτερικής(outer) επανάληψης αντί μόνο της εσωτερικής + } + } + } + + // Επανάληψη For Each + // Η επανάληψη for είναι επίσης ικανή να επαναλαμβάνεται τόσο σε + // πίνακες όσο και σε αντικείμενα τα οποία υλοποιούν τη διεπαφή + // Iterable. + int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + // Σύνταξη της επανάληψης for each => for (<αντικείμενο> : ) + // Διαβάζεται ως: Για κάθε αντικείμενο στο iterable + // Σημείωση: ο τύπος του αντικειμένου πρέπει να τεριάζει με τον τύπο του στοιχείου του iterable. + + for (int bar : fooList) { + System.out.println(bar); + //Επαναλαμβάνεται 9 φορές και τυπώνει 1-9 σε καινούριες γραμμές + } + + // Switch Case + // Ένα switch δουλέυει με byte, short, char, και int τύπους δεδομένων. + // Δουλέυει επίσης με τύπους enumerated (Συζήτηση στους τύπους Enum), + // τη κλάση String, και μερικές ειδικές περιπτώσεις οι οποίες + // περιλαμβάνουν primitive τύπους: Character, Byte, Short, and Integer. + int month = 3; + String monthString; + switch (month) { + case 1: monthString = "January"; + break; + case 2: monthString = "February"; + break; + case 3: monthString = "March"; + break; + default: monthString = "Some other month"; + break; + } + System.out.println("Switch Case Result: " + monthString); + + // Αρχίζοντας από τη Java 7, switching για Strings δουλεύει έτσι: + String myAnswer = "maybe"; + switch(myAnswer) { + case "yes": + System.out.println("You answered yes."); + break; + case "no": + System.out.println("You answered no."); + break; + case "maybe": + System.out.println("You answered maybe."); + break; + default: + System.out.println("You answered " + myAnswer); + break; + } + + // Συντομογραφία του Conditional + // Μπορείς να χρησιμοποιήσεις τον τελεστή '?' για γρήγορες αναθέσεις ή + // logic forks. Διαβάζεται ως "Αν η (πρόταση) είναι αληθής, + // χρησιμοποίησε <την πρώτη τιμή>, αλλιώς, χρησιμοποία <την δεύτερη + // τιμή>" + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println(bar); // Prints A, because the statement is true + + + //////////////////////////////////////// + // Μετατροπή Τύπων Δεδομένων και Typecasting + //////////////////////////////////////// + + // Μετατροπή δεδομένων + + // Μετατροπή από String σε Integer + Integer.parseInt("123");//returns an integer version of "123" + + // Μετατροπή από Integer σε String + Integer.toString(123);//returns a string version of 123 + + // Για άλλες μετατροπές δες τις ακόλουθες κλάσεις: + // Double + // Long + // String + + // Typecasting + // Μπορείς επίσης να κάνεις cast αντικείμενα Java. Υπάρχουν πολλές + // λεπτομέρειες και μερικές πραγματεύονται κάποιες πιο προχωρημένες + // ένοιες. Για δες εδώ: + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Κλάσεις και Συναρτήσεις + /////////////////////////////////////// + + System.out.println("\n->Classes & Functions"); + + // (Ο ορισμός της κλάσης Bicycle ακολουθεί) + + // Χρησιμοποία το new για να δημιουργήσεις ένα αντικείμενο μίας κλάσης + Bicycle trek = new Bicycle(); + + // Κλήση μεθόδων του αντικειμένου + trek.speedUp(3); // Πάντοτε πρέπει να χρησιμοποιείς μεθόδους setter + // και getter + trek.setCadence(100); + + // Το toString επιστρέφει την αναπαράσταση σε String μορφή του + // αντικειμένου αυτού. + System.out.println("trek info: " + trek.toString()); + + // Double Brace Initialization + // Η Γλώσσα Java δεν έχει σύνταξη για το πως να δημιουργήσεις static + // Collections με κάποιο εύκολο τρόπο. Συνήθως θα το κάνεις αυτό με + // τον παρακάτω τρόπο: + + private static final Set COUNTRIES = new HashSet(); + static { + validCodes.add("DENMARK"); + validCodes.add("SWEDEN"); + validCodes.add("FINLAND"); + } + + // Αλλά υπάρχει ένας κομψός τρόπος να επιτύχεις το ίδιο πράγμα + // ευκολότερα, χρησιμοποιώντας κάτι το οποίο λέγεται Double Brace + // Initialization. + + private static final Set COUNTRIES = new HashSet() {{ + add("DENMARK"); + add("SWEDEN"); + add("FINLAND"); + }} + + // Η πρώτη αγκύλη δημιουργεί μία νέα AnonymousInnerClass και η + // δεύτερη δηλώνει ένα instance initializer block. Το block + // καλείται όταν η ανώνυμη εσωτερική κλάση δημιουργηθεί. + // Η μέθοδος αύτή δεν δουλεύει μόνο για τις Collections, αλλά για όλες + // τις non-final κλάσεις. + + } // Τέλος μεθόδου main +} // Τέλος κλάσης LearnJava + + +// Μπορείς να κάνεις include άλλες, όχι-δημόσιες (non-public) +// εξωτερικού-επιπέδου (outer-level) κλάσεις σε ένα αρχείο .java, αλλά δεν +// είναι καλή πρακτική. Αντί αυτού, διαχώρησε τις κλάσεις σε ξεχωριστά αρχεία. + +// Σύνταξη Δήλωσης Κλάσης (Class Declaration Syntax): +// class { +// // Συμπεριλαμβάνονται πεδία δεδομένων (data fields), κατασκευαστές (constructors), συναρτήσεις (functions) . +// // Οι συναρτήσεις ονομάζονται "μεθόδοι" στη Java. +// } + +class Bicycle { + + // Πεδία/μεταβλητές της Κλάσης Bicycle + // Public(Δημόσιες): Μπορούν να γίνουν προσβάσιμες από παντού + public int cadence; + // Private(Ιδιωτικές): Προσβάσιμες μόνο εντός της κλάσης + private int speed; + // Protected(Προστατευμένες): Προσβάσιμες από την κλάση και τις υποκλάσεις (subclasses) της + protected int gear; + String name; // Προκαθορισμένο: Προσβάσιμη μόνο εντός του πακέτου + + static String className; // Static μεταβλητή κλάσης + + // Static block + // H Java δεν υποστηρίζει υλοποίησεις στατικών κατασκευαστών (static + // constructors), αλλά έχει ένα static block το οποίο μπορεί να + // χρησιμοποιηθεί για να αρχικοποιήσει στατικές μεταβλητές (static + // variables). Το block αυτό θα καλεσθεί όταν η κλάση φορτωθεί. + static { + className = "Bicycle"; + } + + // Οι κατασκευαστές (constructors) είναι ένας τρόπος για δημιουργία κλάσεων + // Αυτός είναι ένας κατασκευαστής (constructor) + public Bicycle() { + // Μπορείς επίσης να καλέσεις άλλο κατασκευαστή: + // this(1, 50, 5, "Bontrager"); + gear = 1; + cadence = 50; + speed = 5; + name = "Bontrager"; + } + + // Αυτός είναι ένας κατασκευαστής ο οποίος δέχεται arguments + public Bicycle(int startCadence, int startSpeed, int startGear, + String name) { + this.gear = startGear; + this.cadence = startCadence; + this.speed = startSpeed; + this.name = name; + } + + // Οι μεθόδοι (Methods) συντάσσονται ως ακολούθως: + // <όνομα μεθόδου>() + + // Οι κλάσεις Java συχνά υλοποιούν getters and setters for their fields + + // Σύνταξη δήλωσης μεθόδου: + // <Προσδιοριστές πρόσβασης> <τύπος επιστροφής> <όνομα μεθόδου>() + public int getCadence() { + return cadence; + } + + // Οι μεθόδοι void δεν απαιτούν return statement + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void speedUp(int increment) { + speed += increment; + } + + public void slowDown(int decrement) { + speed -= decrement; + } + + public void setName(String newName) { + name = newName; + } + + public String getName() { + return name; + } + + //Μέθοδος η οποία επιστρέφει ως String τις τιμές των χαρακτηριστικών του + // αντικειμένου. + @Override // Χρησιμοποιείται, καθώς η συγκεκριμένη μέθοδος κληρονομήθηκε από τη κλάση Object. + public String toString() { + return "gear: " + gear + " cadence: " + cadence + " speed: " + speed + + " name: " + name; + } +} // Τέλος κλάσης Bicycle + +// Η PennyFarthing είναι υποκλάση της Bicycle +class PennyFarthing extends Bicycle { + // (Tα Penny Farthings είναι τα ποδήλατα με τον μεγάλο μπροστινό τροχό. + // Δεν έχουν ταχύτητες.) + + public PennyFarthing(int startCadence, int startSpeed) { + // Κάλεσε τον parent constructor χρησιμοποιώντας το super + super(startCadence, startSpeed, 0, "PennyFarthing"); + } + + // Χρειάζεται να μαρκάρεις τη μέθοδο την οποία κάνεις overriding + // χρησιμοποιώντας ένα @annotation. + // Για να μάθεις περισσότερα σχετικά με το τι είναι οι επισημάνσεις + // (annotations) και τον σκοπό τους δες αυτό: + // http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setGear(int gear) { + gear = 0; + } +} + +// Διεπαφές (Interfaces) +// Σύνταξη δήλωσης διεπαφής +// interface extends { +// // Σταθερές (Constants) +// // Δηλώσεις Μεθόδων (Method declarations) +// } + +// Παράδειγμα - Food: +public interface Edible { + public void eat(); // Κάθε κλάση η οποία υλοποιεί τη διεπαφή αυτή πρέπει + // να υλοποιήσει τη συγκεκριμένη μέθοδο. +} + +public interface Digestible { + public void digest(); +} + + +// Μπορούμε να δημιουργήσουμε μία κλάση η οποία υλοποιεί και τις δύο αυτές διεπαφές. +public class Fruit implements Edible, Digestible { + + @Override + public void eat() { + // ... + } + + @Override + public void digest() { + // ... + } +} + +// Στην Java, μπορείς να κληρονομήσεις (extend) από μόνο μία κλάση, +// αλλά μπορείς να υλοποιήσεις πολλές διεπαφές. Για παράδειγμα: +public class ExampleClass extends ExampleClassParent implements InterfaceOne, + InterfaceTwo { + + @Override + public void InterfaceOneMethod() { + } + + @Override + public void InterfaceTwoMethod() { + } + +} + +// Abstract (Αφηρημένες) Κλάσεις + +// Σύνταξη Δήλωσης Abstract Κλάσης +// abstract extends { +// // Σταθερές και μεταβλητές +// // Δηλώσεις μεθόδων +// } + +// Μαρκάροντας μία κλάση ως abstract σημαίνει ότι περιέχει abstract μεθόδους +// οι οποίες πρέπει να οριστούν σε μία κλάση παιδί (child class). +// Παρόμοια με τις διεπαφές (interfaces), οι abstract κλάσεις δεν μπορούν να +// γίνουν instantiated, αλλά αντί αυτού πρέπει να γίνει extend και οι abstract +// μεθόδοι πρέπει να οριστούν. Διαφορετικά από τις Διεπαφές, οι abstract +// κλάσεις μπορούν να περιέχουν τόσο υλοποιημένες όσο και abstract μεθόδους. +// Οι μεθόδοι σε μια Διεπαφή δεν μπορούν να έχουν σώμα (δεν είναι υλοποιημένες +// δηλαδή εκτός εάν η μέθοδος είναι στατική και οι μεταβλητές είναι final by +// default αντίθετα απο μία abstract κλάση. Επίσης, οι abstract κλάσεις +// ΜΠΟΡΟΥΝ να έχουν την μέθοδο "main". + +public abstract class Animal +{ + public abstract void makeSound(); + + // Οι μεθόδοι μπορούν να έχουν σώμα (body) + public void eat() + { + System.out.println("I am an animal and I am Eating."); + // Σημείωση: Μπορούμε να έχουμε πρόσβαση σε ιδιωτικές (private) μεταβλητές εδώ. + age = 30; + } + + // Δεν χρειάζεται να αρχικοποιηθεί, εντούτοις σε ένα interface μία + // μεταβλητή είναι implicitly final και έτσι χρειάζεται να αρχικοποιηθεί + protected int age; + + public void printAge() + { + System.out.println(age); + } + + // Οι Abstract κλάσεις μπορούν να έχουν συνάρτηση main. + public static void main(String[] args) + { + System.out.println("I am abstract"); + } +} + +class Dog extends Animal +{ + // Σημείωση ότι χρειάζεται να κάνουμε override τις abstract μεθόδους στην + // abstract κλάση. + @Override + public void makeSound() + { + System.out.println("Bark"); + // age = 30; ==> ERROR! Το πεδίο age είναι private στο Animal + } + + // ΣΗΜΕΙΩΣΗ: Θα πάρεις error εάν χρησιμοποίησεις το + // @Override annotation εδώ, καθώς η java δεν επιτρέπει + // να γίνονται override οι static μεθόδοι. + // Αυτό που γίνεται εδώ ονομάζεται METHOD HIDING. + // Για δες αυτό το εξαιρετικό ποστ στο SO (Stack Overflow): http://stackoverflow.com/questions/16313649/ + public static void main(String[] args) + { + Dog pluto = new Dog(); + pluto.makeSound(); + pluto.eat(); + pluto.printAge(); + } +} + +// Κλάσεις Final + +// Σύνταξη δήλωσης μίας Final κλάσης +// final { +// // Σταθερές και μεταβλητές +// // Δήλωση μεθόδων +// } + +// Οι κλάσεις Final είναι κλάσεις οι οποίες δεν μπορούν να κληρονομηθούν και +// συνεπώς είναι final child. In a way, final classes are the opposite of +// abstract classes because abstract classes must be extended, but final +// classes cannot be extended. +public final class SaberToothedCat extends Animal +{ + // Σημείωση ότι χρειάζεται και πάλι να κάνουμε override τις abstract + // μεθόδους στην abstract κλάση. + @Override + public void makeSound() + { + System.out.println("Roar"); + } +} + +// Τελικές (Final) μεθόδοι +public abstract class Mammal() +{ + // Σύνταξη μίας Final μεθόδου: + // <Προσδιοριστής πρόσβασης (access modifier)> final <τύπος επιστροφής> <Όνομα μεθόδου>() + + // Οι Final μεθόδοι, όπως και οι final κλάσεις δεν μπορούν να γίνουν + // overridden από κλάση παιδί, + // και είναι συνεπώς η τελική υλοποίηση της μεθόδου. + public final boolean isWarmBlooded() + { + return true; + } +} + + +// Τύποι Enum +// +// Ένας τύπος enum είναι ένας ειδικός τύπος δεδομένων, ο οποίος επιτρέπει σε +// μια μεταβλητή να είναι ένα σύνολο από προκαθορισμένες σταθερές. Η μεταβλητή +// πρέπει να είναι ίση με μία από τις τιμές αυτές που έχουν προκαθοριστεί. +// Επειδή είναι σταθερές, τα ονόματα ενός enum πεδίου γράφονται με κεφαλαίους +// χαρακτήρες. Στην γλώσσα προγραμματισμού Java, ορίζεις ένα τύπο enum +// χρησιμοποιώντας τη δεσμευμένη λέξη enum. Για παράδειγμα, θα μπορούσες να +// καθορίσεις ένα τύπο enum με όνομα days-of-the-week ως: + +public enum Day { + SUNDAY, MONDAY, TUESDAY, WEDNESDAY, + THURSDAY, FRIDAY, SATURDAY +} + +// Μπορούμε να χρησιμοποιήσουμε τον enum Day όπως παρακάτω: + +public class EnumTest { + + // Μεταβλητή Enum + Day day; + + public EnumTest(Day day) { + this.day = day; + } + + public void tellItLikeItIs() { + switch (day) { + case MONDAY: + System.out.println("Mondays are bad."); + break; + + case FRIDAY: + System.out.println("Fridays are better."); + break; + + case SATURDAY: + case SUNDAY: + System.out.println("Weekends are best."); + break; + + default: + System.out.println("Midweek days are so-so."); + break; + } + } + + public static void main(String[] args) { + EnumTest firstDay = new EnumTest(Day.MONDAY); + firstDay.tellItLikeItIs(); // => Mondays are bad. + EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); + thirdDay.tellItLikeItIs(); // => Midweek days are so-so. + } +} + +// Οι τύποι Enum είναι πολύ πιο δυνατοί από όσο έχουμε δείξει πιο πάνω. +// Το σώμα του enum (enum body) μπορεί να περιέχει μεθόδους και άλλα πεδία. +// Μπορείς να δεις περισσότερα στο +// https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html + +``` + +## Επιπλέων διάβασμα + +Οι σύνδεσμοι που παρέχονται εδώ είναι απλά για να κατανοήσεις περισσότερο το θέμα. +Σε προτρύνουμε να ψάξεις στο Google και να βρεις συγκεκριμένα παραδείγματα. + +**Eπίσημοι Οδηγοί της Oracle**: + +* [Φροντιστήριο εκμάθησης Java από τη Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Τροποποιητές επιπέδου πρόσβασης(Access level modifiers) Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Έννοιες αντικειμενοστραφούς (Object-Oriented) προγραμματισμού](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Κληρονομικότητα (Inheritance)](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Πολυμορφισμός (Polymorphism)](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Αφαιρετικότητα (Abstraction)](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Εξαιρέσεις (Exceptions)](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Διεπαφές (Interfaces)](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Συμβάσεις κώδικα Java (Code Conventions)](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) + +**Πρακτικές και Φροντιστήρια Online** + +* [Learneroo.com - Μάθε Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Βιβλία**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Thinking in Java](http://www.mindview.net/Books/TIJ/) + +* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) -- cgit v1.2.3 From 898dcda0f2be31ed3ee232a623d854e63c373082 Mon Sep 17 00:00:00 2001 From: Justin Tervay Date: Tue, 19 Apr 2016 12:28:31 -0400 Subject: Fixed typo(s) in Java (EN) --- java.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 48e6ec75..ed7e4f53 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -407,9 +407,9 @@ public class LearnJava { // in an easy way. Usually you end up in the following way: private static final Set COUNTRIES = new HashSet(); static { - validCodes.add("DENMARK"); - validCodes.add("SWEDEN"); - validCodes.add("FINLAND"); + COUNTRIES.add("DENMARK"); + COUNTRIES.add("SWEDEN"); + COUNTRIES.add("FINLAND"); } // But there's a nifty way to achieve the same thing in an -- cgit v1.2.3 From 4daae2c6273ba4365937a81229981c225950f70e Mon Sep 17 00:00:00 2001 From: Tai An Su Date: Fri, 22 Apr 2016 04:52:12 +0800 Subject: [Elixir/zh-Tw]Translation for Elixir of zh-tw --- zh-tw/elixir-tw.html.markdown | 413 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 413 insertions(+) create mode 100644 zh-tw/elixir-tw.html.markdown diff --git a/zh-tw/elixir-tw.html.markdown b/zh-tw/elixir-tw.html.markdown new file mode 100644 index 00000000..c15f90c1 --- /dev/null +++ b/zh-tw/elixir-tw.html.markdown @@ -0,0 +1,413 @@ +--- +language: elixir +contributors: + - ["Joao Marques", "http://github.com/mrshankly"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] +translators: + - ["Tai An Su", "https://github.com/taiansu"] +filename: learnelixir-tw.ex +lang: zh-tw +--- + +Elixir 是一門建構在 Erlang 虛擬機上的現代函數式語言。它完全與 Erlang 相容,但 +採行了比較常見的語法,並提供更多的功能。 + +```elixir + +# 單行註解以井字號開頭 + +# 沒有多行註解的功能 +# 但你可以連續使用多個單行 + +# 用 `iex` 來進入 elixir shell +# 用 `elixirc` 來編譯你的模組 + +# 如果你已成功安裝 elixir 的話,這兩個命令應已在你的 path 下。 + +## --------------------------- +## -- 基本型別 +## --------------------------- + +# 數字 +3 # 整數 +0x1F # 整數 +3.0 # 浮點數 + +# 原子 (Atoms) 是不可變的字面常數,以 `:` 開頭。 +:hello # atom + +# 元組(Tuples) 會存在記憶體連續的區段裡。 +{1,2,3} # tuple + +# 我們可以用 `elem` 函式來取得 tuple 中的元素。 +elem({1, 2, 3}, 0) #=> 1 + +# 串列 (List) 是用連結串列實作的。 +[1,2,3] # list + +# 我們可以這樣取得串列的頭尾元素: +[head | tail] = [1,2,3] +head #=> 1 +tail #=> [2,3] + +# 在 elixir 中,就如同 Erlang 裡一樣,`=` 代表的是模式比對,而非指派。 +# +# 這代表將使用左手邊的模式 (pattern) 去與右手邊的值進行比對。 +# +# 這也是先前取得串列的頭尾元素的運作原理 + +# 當模式比對無法找到合適的配對時,將會回報錯誤,如下例中兩個 tuple 的大小不一致。 +# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} + +# 還有二進位的型別 +<<1,2,3>> # binary + +# 字串與字母串列 +"hello" # string +'hello' # char list + +# 多行字串 +""" +I'm a multi-line +string. +""" +#=> "I'm a multi-line\nstring.\n" + +# 字串皆使用 UTF-8 編碼 +"héllò" #=> "héllò" + +# 字串其實是以二進位實作,而字母串列就只是單純的串列。 +<> #=> "abc" +[?a, ?b, ?c] #=> 'abc' + +# `?a` 在 elixir 中會回傳字母 `a` 的 ASCII 整數 +?a #=> 97 + +# 用 `++` 來合併串列,而合併二進位則要用 `<>` +[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" + +# 範圍 (Ranges) 則是以 `開頭..結尾`來宣告 (頭尾都包含在內) +1..10 #=> 1..10 +lower..upper = 1..10 # 可以對 range 進行模式比對 +[lower, upper] #=> [1, 10] + +## --------------------------- +## -- 運算元 +## --------------------------- + +# 簡單算數 +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 + +# 在 elixir 中, `/` 運算元永遠回傳浮點數。 + +# 若需要回傳整數的除法,用 `div` +div(10, 2) #=> 5 + +# 要得到除法的餘數時,用 `rem` +rem(10, 3) #=> 1 + +# 還有布林運算元: `or`, `and` and `not`. +# 這些運算元要求第一個參數必需為布林值。 +true and true #=> true +false or true #=> true +# 1 and true #=> ** (ArgumentError) argument error + +# Elixir 也提供了 `||`, `&&` 及 `!`,它們接受任何型別的參數。 +# 除了 `false` 與 `nil` 之外的值都會被當做 true。 +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil +!true #=> false + +# 用來比較的運算元有:`==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` and `>` +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true + +# `===` 和 `!==` 會嚴格比較整數與浮點數 +1 == 1.0 #=> true +1 === 1.0 #=> false + +# 兩個不同的型別也可以比較 +1 < :hello #=> true + +# 所有型別的排序如下: +# number < atom < reference < functions < port < pid < tuple < list < bit string + +# 引用 Joe Armstrong 的話: "實際排序的先後並不重要, 但有明確排出全體順序的定 +# 義才是重要的。" + +## --------------------------- +## -- 控制流程 +## --------------------------- + +# `if` 表達式 +if false do + "This will never be seen" +else + "This will" +end + +# 也有 `unless` +unless true do + "This will never be seen" +else + "This will" +end + +# 還記得模式比對嗎?Elixir 中許多控制流程的結構都依賴模式比對來運作。 + +# `case` 讓我們可以將一個值與許多模式進行比對: +case {:one, :two} do + {:four, :five} -> + "This won't match" + {:one, x} -> + "This will match and bind `x` to `:two` in this clause" + _ -> + "This will match any value" +end + +# 當我們不需要某個值的時候,通常會將它比對成 `_`。 +# 例如我們只關心串列的第一個值的情況時: +[head | _] = [1,2,3] +head #=> 1 + +# 若希望程式更好懂時,我們會這樣處理: +[head | _tail] = [:a, :b, :c] +head #=> :a + +# `cond` 讓我們可以同時檢測多個不同的值。 +# 用 `cond` 來代替巢狀的 `if` 表達式 +cond do + 1 + 1 == 3 -> + "I will never be seen" + 2 * 5 == 12 -> + "Me neither" + 1 + 2 == 3 -> + "But I will" +end + +# 把最後一個條件設為 `true` 來捕捉剩下的所有情況是很常見的作法。 +cond do + 1 + 1 == 3 -> + "I will never be seen" + 2 * 5 == 12 -> + "Me neither" + true -> + "But I will (this is essentially an else)" +end + +# `try/catch` 用來捕捉拋出的值,它也提供 `after` 子句,無論是否有接到拋出的值, +# 最後都會調用其下的程式。 +try do + throw(:hello) +catch + message -> "Got #{message}." +after + IO.puts("I'm the after clause.") +end +#=> I'm the after clause +# "Got :hello" + +## --------------------------- +## -- 模組與函式 +## --------------------------- + +# 匿名函式 (注意那個句點) +square = fn(x) -> x * x end +square.(5) #=> 25 + +# 匿名函式也接受多個子句及防衛(guards) +# Guards 可以進行模式比對 +# 用 `when` 來描述 guards +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# Elixir 也提供許多內建的函式 +# 這些在預設的作用域下都可以使用 +is_number(10) #=> true +is_list("hello") #=> false +elem({1,2,3}, 0) #=> 1 + +# 你可以用模組將多個的函式集合在一起。在模組裡,用 `def` 來定義函式。 +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 + +# 要編譯我們的 Math 模組時,先將它存成 `math.ex`,再用 `elixirc` 進行編譯。 +# 在終端機輸入: elixirc math.ex + +# 在模組中我們可以用 `def` 宣告函式,及用 `defp` 宣告私有 (private) 函式。 +# 使用 `def` 定義的函式可以在其它的模組中被調用。 +# 私有的函式只能在這個模組內部調用。 +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) + +# 函式宣告也支援用防衛條件及多個條件子句 +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 + +# 由於不可變特性 (immutability),遞迴在 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 模組也支援屬性,模組有內建一些屬性,而你也可以定義自己的屬性。 +defmodule MyMod do + @moduledoc """ + 這是內建的屬性,模組文件 + """ + + @my_data 100 # 這是自訂的屬性 + IO.inspect(@my_data) #=> 100 +end + +## --------------------------- +## -- 結構與例外 (Structs and Exceptions) +## --------------------------- + +# 結構 (structs) 是 maps 的擴展。是 Elixir 裡可以有預設值,編譯期檢查及 +# 多形 (polymorphism) 的資料結構。 +defmodule Person do + defstruct name: nil, age: 0, height: 0 +end + +joe_info = %Person{ name: "Joe", age: 30, height: 180 } +#=> %Person{age: 30, height: 180, name: "Joe"} + +# 取得 name 的值 +joe_info.name #=> "Joe" + +# 更新 age 的值 +older_joe_info = %{ joe_info | age: 31 } +#=> %Person{age: 31, height: 180, name: "Joe"} + +# The `try` block with the `rescue` keyword is used to handle exceptions +# 帶有 `rescue` 關鍵字的 `try` 區塊是用來進行例外處理的。 +try do + raise "some error" +rescue + RuntimeError -> "rescued a runtime error" + _error -> "this will rescue any error" +end +#=> "rescued a runtime error" + +# 所有的異常都有帶著一個訊息 +try do + raise "some error" +rescue + x in [RuntimeError] -> + x.message +end +#=> "some error" + +## --------------------------- +## -- 平行處理 +## --------------------------- + +# Elixir 依靠 actor 模式來進行平行處理。在 elixir 中要寫出平行處理程式, +# 只需要三個基本要素:建立行程,發送訊息及接收訊息。 + +# 我們用 `spawn` 函式來建立行程,它接收一個函式當參數。 +f = fn -> 2 * 2 end #=> #Function +spawn(f) #=> #PID<0.40.0> + +# `spawn` 會回傳一個 pid (行程識別碼),你可以利用這個 pid 來對該行程傳送訊息。 +# 我們會使用 `send` 運算元來傳送訊息。但首先我們要讓該行程可以接收訊息。這要用 +# 到 `receive` 機制來達成。 + +# `receive` 區塊能讓行程監聽接收到的訊息。每個 `receive do` 區塊只能接收一條 +# 訊息。若要接收多條訊息時,含有 `receive do` 的函式必須要在接到訊息後,遞迴呼 +# 叫自己以再次進入 `receive do` 區塊。 + +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 + +# 編譯模組,並在 shell 中創造一個行程來執行 `area_loop`。 +pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> +# 更簡潔的替代寫法 +pid = spawn(Geometry, :area_loop, []) + +# 對 `pid` 傳送訊息,則會與接收區塊進行樣式比對。 +send pid, {:rectangle, 2, 3} +#=> Area = 6 +# {:rectangle,2,3} + +send pid, {:circle, 2} +#=> Area = 12.56000000000000049738 +# {:circle,2} + +# The shell is also a process, you can use `self` to get the current pid +# shell 也是一個行程 (process),你可以用 `self` 拿到目前的 pid +self() #=> #PID<0.27.0> +``` + +## 參考資料 + +* [Getting started guide](http://elixir-lang.org/getting-started/introduction.html) from the [Elixir website](http://elixir-lang.org) +* [Elixir Documentation](http://elixir-lang.org/docs/master/) +* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) by Dave Thomas +* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) +* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) by Fred Hebert +* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) by Joe Armstrong -- cgit v1.2.3 From ab4fa4ea02e29c8f680aa70a01da082c08cb11d8 Mon Sep 17 00:00:00 2001 From: Mustafa Zengin Date: Sun, 24 Apr 2016 22:57:21 -0700 Subject: fsharp translation to Turkish in progress --- tr-tr/fsharp-tr.html.markdown | 630 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 630 insertions(+) create mode 100644 tr-tr/fsharp-tr.html.markdown diff --git a/tr-tr/fsharp-tr.html.markdown b/tr-tr/fsharp-tr.html.markdown new file mode 100644 index 00000000..b844f552 --- /dev/null +++ b/tr-tr/fsharp-tr.html.markdown @@ -0,0 +1,630 @@ +--- +language: F# +contributors: + - ["Scott Wlaschin", "http://fsharpforfunandprofit.com/"] +translators: + - ["Mustafa Zengin", "http://zengin.github.com/"] +filename: learnfsharp.fs +--- + +F# fonksiyonel ve nesne tabanlı, genel amaçlı bir programlama dilidir. Bedava ve açık kaynaklıdır ve Linux, Mac, Windows ve dahasında çalışır. + +Hataları derleme zamanında yakalayan çok güçlü bir tip sistemine sahiptir, ancak tip çıkarımı yaptığından dinamik bir dil gibi görünür. + +F#'ın söz dizimi C-stili dillerden farklıdır: + +* Küme parantezi kod bloklarını ayırmak için kullanılmaz. Bunun yerine Python'da olduğu gibi girinti kullanılır. +* Parametreleri birbirinden ayırmak için virgül yerine boşluk karakteri kullanılır. + +Aşağıdaki kodu denemek istiyorsanız, [tryfsharp.org](http://www.tryfsharp.org/Create)'a gidin be interaktif REPL'e kodu yapıştırın. + +```csharp + +// tek satır yorumlar ikili bölme işareti kullanılır +(* çok satırlı yorumlar (* . . . *) ikilisini kullanır + +-çok satırlı yorumun sonu- *) + +// ================================================ +// Temel Söz Dizimi +// ================================================ + +// ------ "Değişkenler" (tam da değil) ------ +// "let" anahtar kelimesi (değişmez) değer tanımlar +let myInt = 5 +let myFloat = 3.14 +let myString = "hello" // tip bilgisi olmamasına dikkat + +// ------ Listeler ------ +let twoToFive = [2; 3; 4; 5] // Köşeli parantezler listeleri oluşturur, + // değerler ise noktalı virgülle ayrılır. +let oneToFive = 1 :: twoToFive // :: yeni birinci elemanı olan bir liste oluşturur. +// Sonuç: [1; 2; 3; 4; 5] +let zeroToFive = [0; 1] @ twoToFive // @ iki listeyi birbirine ekler. + +// ÖNEMLİ: virgüller hiçbir zaman ayraç olarak kullanılmaz, sadece noktalı virgüller! + +// ------ Fonksiyonlar ------ +// "let" anahtar kelimesi isimlendirilmiş fonksiyonları da tanımlar. +let square x = x * x // Parantez kullanılmadığına dikkat. +square 3 // Şimdi fonksiyonu uygula. Yine parantez yok. + +let add x y = x + y // add (x,y) kullanmayın! Bu tamamen başka bir anlama geliyor. +add 2 3 // Şimdi fonksiyonu uygula. + +// çok satırlı bir fonksiyon tanımlamak için sadece girinti kullan. Noktalıı virgül gerekmez. +let evens list = + let isEven x = x % 2 = 0 // "isEven"ı alt fonksiyon olarak tanımla + List.filter isEven list // List.filter boolean bir fonksiyon ve + // üzerinde çalışılacak bir liste parametrelerinden oluşan + // bir kütüphane fonksiyonu + +evens oneToFive // Şimdi fonksiyonu uygula. + +// Parantezleri önceliği netleştirmek için kullanabilirsin. Bu örnekte +// "map"i önce iki argümanla uygula, sonra sonuç üzerinde "sum" uygula. +// Parantezler olmasaydı, "List.map" List.sum'ın ilk argümanı olurdu. +let sumOfSquaresTo100 = + List.sum ( List.map square [1..100] ) + +// Bir operasyonun sonucunu bir sonrakine "|>" kullanarak besleyebilirsin. +// Veri beslemek F#'ta UNIX'te olduğu gibi yaygındır.. + +// Burada sumOfSquares fonksiyonunun veri beslemeyle yazılmış hali var: +let sumOfSquaresTo100piped = + [1..100] |> List.map square |> List.sum // "square" önceden tanımlanmıştı + +// Lambda'ları (anonim fonksiyonları) "fun" anahtar kelimesiyle tanımlayabilirsin +let sumOfSquaresTo100withFun = + [1..100] |> List.map (fun x -> x * x) |> List.sum + +// F#'ta "return" anahtar kelimesi yoktur. Bir fonksiyon +// her zaman son kullanılan ifadeyi döndürür. + +// ------ Kalıp eşleştirme ------ +// Match..with.. çok güçlü bir case/switch türevidir. +let simplePatternMatch = + let x = "a" + match x with + | "a" -> printfn "x is a" + | "b" -> printfn "x is b" + | _ -> printfn "x is something else" // alt çizgi bütün kalıplarla eşleşir + +// F# varsayılan olarak null'lara izin vermez -- Option tipini kullanıp +// kalıp eşleştirme yapmalısın. +// Some(..) ve None, Nullable tipler gibidir. +let validValue = Some(99) +let invalidValue = None + +// Bu örnekte, match..with "Some" ve "None"la eşleştirme yapıyor, +// ve ayrıca "Some" içerisindeki değeri de çıkarıyor. +let optionPatternMatch input = + match input with + | Some i -> printfn "input is an int=%d" i + | None -> printfn "input is missing" + +optionPatternMatch validValue +optionPatternMatch invalidValue + +// ------ Printing ------ +// The printf/printfn functions are similar to the +// Console.Write/WriteLine functions in C#. +printfn "Printing an int %i, a float %f, a bool %b" 1 2.0 true +printfn "A string %s, and something generic %A" "hello" [1; 2; 3; 4] + +// There are also sprintf/sprintfn functions for formatting data +// into a string, similar to String.Format in C#. + +// ================================================ +// More on functions +// ================================================ + +// F# is a true functional language -- functions are first +// class entities and can be combined easily to make powerful +// constructs + +// Modules are used to group functions together +// Indentation is needed for each nested module. +module FunctionExamples = + + // define a simple adding function + let add x y = x + y + + // basic usage of a function + let a = add 1 2 + printfn "1 + 2 = %i" a + + // partial application to "bake in" parameters + let add42 = add 42 + let b = add42 1 + printfn "42 + 1 = %i" b + + // composition to combine functions + let add1 = add 1 + let add2 = add 2 + let add3 = add1 >> add2 + let c = add3 7 + printfn "3 + 7 = %i" c + + // higher order functions + [1..10] |> List.map add3 |> printfn "new list is %A" + + // lists of functions, and more + let add6 = [add1; add2; add3] |> List.reduce (>>) + let d = add6 7 + printfn "1 + 2 + 3 + 7 = %i" d + +// ================================================ +// Lists and collection +// ================================================ + +// There are three types of ordered collection: +// * Lists are most basic immutable collection. +// * Arrays are mutable and more efficient when needed. +// * Sequences are lazy and infinite (e.g. an enumerator). +// +// Other collections include immutable maps and sets +// plus all the standard .NET collections + +module ListExamples = + + // lists use square brackets + let list1 = ["a"; "b"] + let list2 = "c" :: list1 // :: is prepending + let list3 = list1 @ list2 // @ is concat + + // list comprehensions (aka generators) + let squares = [for i in 1..10 do yield i * i] + + // prime number generator + let rec sieve = function + | (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ] + | [] -> [] + let primes = sieve [2..50] + printfn "%A" primes + + // pattern matching for lists + let listMatcher aList = + match aList with + | [] -> printfn "the list is empty" + | [first] -> printfn "the list has one element %A " first + | [first; second] -> printfn "list is %A and %A" first second + | _ -> printfn "the list has more than two elements" + + listMatcher [1; 2; 3; 4] + listMatcher [1; 2] + listMatcher [1] + listMatcher [] + + // recursion using lists + let rec sum aList = + match aList with + | [] -> 0 + | x::xs -> x + sum xs + sum [1..10] + + // ----------------------------------------- + // Standard library functions + // ----------------------------------------- + + // map + let add3 x = x + 3 + [1..10] |> List.map add3 + + // filter + let even x = x % 2 = 0 + [1..10] |> List.filter even + + // many more -- see documentation + +module ArrayExamples = + + // arrays use square brackets with bar + let array1 = [| "a"; "b" |] + let first = array1.[0] // indexed access using dot + + // pattern matching for arrays is same as for lists + let arrayMatcher aList = + match aList with + | [| |] -> printfn "the array is empty" + | [| first |] -> printfn "the array has one element %A " first + | [| first; second |] -> printfn "array is %A and %A" first second + | _ -> printfn "the array has more than two elements" + + arrayMatcher [| 1; 2; 3; 4 |] + + // Standard library functions just as for List + + [| 1..10 |] + |> Array.map (fun i -> i + 3) + |> Array.filter (fun i -> i % 2 = 0) + |> Array.iter (printfn "value is %i. ") + + +module SequenceExamples = + + // sequences use curly braces + let seq1 = seq { yield "a"; yield "b" } + + // sequences can use yield and + // can contain subsequences + let strange = seq { + // "yield" adds one element + yield 1; yield 2; + + // "yield!" adds a whole subsequence + yield! [5..10] + yield! seq { + for i in 1..10 do + if i % 2 = 0 then yield i }} + // test + strange |> Seq.toList + + + // Sequences can be created using "unfold" + // Here's the fibonacci series + let fib = Seq.unfold (fun (fst,snd) -> + Some(fst + snd, (snd, fst + snd))) (0,1) + + // test + let fib10 = fib |> Seq.take 10 |> Seq.toList + printf "first 10 fibs are %A" fib10 + + +// ================================================ +// Data Types +// ================================================ + +module DataTypeExamples = + + // All data is immutable by default + + // Tuples are quick 'n easy anonymous types + // -- Use a comma to create a tuple + let twoTuple = 1, 2 + let threeTuple = "a", 2, true + + // Pattern match to unpack + let x, y = twoTuple // sets x = 1, y = 2 + + // ------------------------------------ + // Record types have named fields + // ------------------------------------ + + // Use "type" with curly braces to define a record type + type Person = {First:string; Last:string} + + // Use "let" with curly braces to create a record + let person1 = {First="John"; Last="Doe"} + + // Pattern match to unpack + let {First = first} = person1 // sets first="John" + + // ------------------------------------ + // Union types (aka variants) have a set of choices + // Only case can be valid at a time. + // ------------------------------------ + + // Use "type" with bar/pipe to define a union type + type Temp = + | DegreesC of float + | DegreesF of float + + // Use one of the cases to create one + let temp1 = DegreesF 98.6 + let temp2 = DegreesC 37.0 + + // Pattern match on all cases to unpack + let printTemp = function + | DegreesC t -> printfn "%f degC" t + | DegreesF t -> printfn "%f degF" t + + printTemp temp1 + printTemp temp2 + + // ------------------------------------ + // Recursive types + // ------------------------------------ + + // Types can be combined recursively in complex ways + // without having to create subclasses + type Employee = + | Worker of Person + | Manager of Employee list + + let jdoe = {First="John"; Last="Doe"} + let worker = Worker jdoe + + // ------------------------------------ + // Modeling with types + // ------------------------------------ + + // Union types are great for modeling state without using flags + type EmailAddress = + | ValidEmailAddress of string + | InvalidEmailAddress of string + + let trySendEmail email = + match email with // use pattern matching + | ValidEmailAddress address -> () // send + | InvalidEmailAddress address -> () // don't send + + // The combination of union types and record types together + // provide a great foundation for domain driven design. + // You can create hundreds of little types that accurately + // reflect the domain. + + type CartItem = { ProductCode: string; Qty: int } + type Payment = Payment of float + type ActiveCartData = { UnpaidItems: CartItem list } + type PaidCartData = { PaidItems: CartItem list; Payment: Payment} + + type ShoppingCart = + | EmptyCart // no data + | ActiveCart of ActiveCartData + | PaidCart of PaidCartData + + // ------------------------------------ + // Built in behavior for types + // ------------------------------------ + + // Core types have useful "out-of-the-box" behavior, no coding needed. + // * Immutability + // * Pretty printing when debugging + // * Equality and comparison + // * Serialization + + // Pretty printing using %A + printfn "twoTuple=%A,\nPerson=%A,\nTemp=%A,\nEmployee=%A" + twoTuple person1 temp1 worker + + // Equality and comparison built in. + // Here's an example with cards. + type Suit = Club | Diamond | Spade | Heart + type Rank = Two | Three | Four | Five | Six | Seven | Eight + | Nine | Ten | Jack | Queen | King | Ace + + let hand = [ Club, Ace; Heart, Three; Heart, Ace; + Spade, Jack; Diamond, Two; Diamond, Ace ] + + // sorting + List.sort hand |> printfn "sorted hand is (low to high) %A" + List.max hand |> printfn "high card is %A" + List.min hand |> printfn "low card is %A" + + +// ================================================ +// Active patterns +// ================================================ + +module ActivePatternExamples = + + // F# has a special type of pattern matching called "active patterns" + // where the pattern can be parsed or detected dynamically. + + // "banana clips" are the syntax for active patterns + + // for example, define an "active" pattern to match character types... + let (|Digit|Letter|Whitespace|Other|) ch = + if System.Char.IsDigit(ch) then Digit + else if System.Char.IsLetter(ch) then Letter + else if System.Char.IsWhiteSpace(ch) then Whitespace + else Other + + // ... and then use it to make parsing logic much clearer + let printChar ch = + match ch with + | Digit -> printfn "%c is a Digit" ch + | Letter -> printfn "%c is a Letter" ch + | Whitespace -> printfn "%c is a Whitespace" ch + | _ -> printfn "%c is something else" ch + + // print a list + ['a'; 'b'; '1'; ' '; '-'; 'c'] |> List.iter printChar + + // ----------------------------------- + // FizzBuzz using active patterns + // ----------------------------------- + + // You can create partial matching patterns as well + // Just use underscore in the definition, and return Some if matched. + let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None + let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None + + // the main function + let fizzBuzz i = + match i with + | MultOf3 & MultOf5 -> printf "FizzBuzz, " + | MultOf3 -> printf "Fizz, " + | MultOf5 -> printf "Buzz, " + | _ -> printf "%i, " i + + // test + [1..20] |> List.iter fizzBuzz + +// ================================================ +// Conciseness +// ================================================ + +module AlgorithmExamples = + + // F# has a high signal/noise ratio, so code reads + // almost like the actual algorithm + + // ------ Example: define sumOfSquares function ------ + let sumOfSquares n = + [1..n] // 1) take all the numbers from 1 to n + |> List.map square // 2) square each one + |> List.sum // 3) sum the results + + // test + sumOfSquares 100 |> printfn "Sum of squares = %A" + + // ------ Example: define a sort function ------ + let rec sort list = + match list with + // If the list is empty + | [] -> + [] // return an empty list + // If the list is not empty + | firstElem::otherElements -> // take the first element + let smallerElements = // extract the smaller elements + otherElements // from the remaining ones + |> List.filter (fun e -> e < firstElem) + |> sort // and sort them + let largerElements = // extract the larger ones + otherElements // from the remaining ones + |> List.filter (fun e -> e >= firstElem) + |> sort // and sort them + // Combine the 3 parts into a new list and return it + List.concat [smallerElements; [firstElem]; largerElements] + + // test + sort [1; 5; 23; 18; 9; 1; 3] |> printfn "Sorted = %A" + +// ================================================ +// Asynchronous Code +// ================================================ + +module AsyncExample = + + // F# has built-in features to help with async code + // without encountering the "pyramid of doom" + // + // The following example downloads a set of web pages in parallel. + + open System.Net + open System + open System.IO + open Microsoft.FSharp.Control.CommonExtensions + + // Fetch the contents of a URL asynchronously + let fetchUrlAsync url = + async { // "async" keyword and curly braces + // creates an "async" object + let req = WebRequest.Create(Uri(url)) + use! resp = req.AsyncGetResponse() + // use! is async assignment + use stream = resp.GetResponseStream() + // "use" triggers automatic close() + // on resource at end of scope + use reader = new IO.StreamReader(stream) + let html = reader.ReadToEnd() + printfn "finished downloading %s" url + } + + // a list of sites to fetch + let sites = ["http://www.bing.com"; + "http://www.google.com"; + "http://www.microsoft.com"; + "http://www.amazon.com"; + "http://www.yahoo.com"] + + // do it + sites + |> List.map fetchUrlAsync // make a list of async tasks + |> Async.Parallel // set up the tasks to run in parallel + |> Async.RunSynchronously // start them off + +// ================================================ +// .NET compatibility +// ================================================ + +module NetCompatibilityExamples = + + // F# can do almost everything C# can do, and it integrates + // seamlessly with .NET or Mono libraries. + + // ------- work with existing library functions ------- + + let (i1success, i1) = System.Int32.TryParse("123"); + if i1success then printfn "parsed as %i" i1 else printfn "parse failed" + + // ------- Implement interfaces on the fly! ------- + + // create a new object that implements IDisposable + let makeResource name = + { new System.IDisposable + with member this.Dispose() = printfn "%s disposed" name } + + let useAndDisposeResources = + use r1 = makeResource "first resource" + printfn "using first resource" + for i in [1..3] do + let resourceName = sprintf "\tinner resource %d" i + use temp = makeResource resourceName + printfn "\tdo something with %s" resourceName + use r2 = makeResource "second resource" + printfn "using second resource" + printfn "done." + + // ------- Object oriented code ------- + + // F# is also a fully fledged OO language. + // It supports classes, inheritance, virtual methods, etc. + + // interface with generic type + type IEnumerator<'a> = + abstract member Current : 'a + abstract MoveNext : unit -> bool + + // abstract base class with virtual methods + [] + type Shape() = + // readonly properties + abstract member Width : int with get + abstract member Height : int with get + // non-virtual method + member this.BoundingArea = this.Height * this.Width + // virtual method with base implementation + abstract member Print : unit -> unit + default this.Print () = printfn "I'm a shape" + + // concrete class that inherits from base class and overrides + type Rectangle(x:int, y:int) = + inherit Shape() + override this.Width = x + override this.Height = y + override this.Print () = printfn "I'm a Rectangle" + + // test + let r = Rectangle(2, 3) + printfn "The width is %i" r.Width + printfn "The area is %i" r.BoundingArea + r.Print() + + // ------- extension methods ------- + + // Just as in C#, F# can extend existing classes with extension methods. + type System.String with + member this.StartsWithA = this.StartsWith "A" + + // test + let s = "Alice" + printfn "'%s' starts with an 'A' = %A" s s.StartsWithA + + // ------- events ------- + + type MyButton() = + let clickEvent = new Event<_>() + + [] + member this.OnClick = clickEvent.Publish + + member this.TestEvent(arg) = + clickEvent.Trigger(this, arg) + + // test + let myButton = new MyButton() + myButton.OnClick.Add(fun (sender, arg) -> + printfn "Click event with arg=%O" arg) + + myButton.TestEvent("Hello World!") + +``` + +## More Information + +For more demonstrations of F#, go to the [Try F#](http://www.tryfsharp.org/Learn) site, or my [why use F#](http://fsharpforfunandprofit.com/why-use-fsharp/) series. + +Read more about F# at [fsharp.org](http://fsharp.org/). -- cgit v1.2.3 From ca208c9473e82a8fd3fb83042f0b1ca82d247e1b Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Mon, 25 Apr 2016 11:55:28 -0700 Subject: Update java-gr.html.markdown --- el-gr/java-gr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/el-gr/java-gr.html.markdown b/el-gr/java-gr.html.markdown index 10784d54..21c4023b 100644 --- a/el-gr/java-gr.html.markdown +++ b/el-gr/java-gr.html.markdown @@ -8,7 +8,7 @@ contributors: - ["Zachary Ferguson", "http://github.com/zfergus2"] - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] - ["Rachel Stiyer", "https://github.com/rstiyer"] -filename: LearnJava.java +filename: LearnJava-gr.java translators: - ["Andreas Loizou" , "https://github.com/lack3r/"] lang: el-gr -- cgit v1.2.3 From 9b400a620a189c21c41ea3aa36c81726c134af81 Mon Sep 17 00:00:00 2001 From: kahredici Date: Tue, 26 Apr 2016 00:59:57 +0300 Subject: small additions. --- tr-tr/python3-tr.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index c7de2922..e53d5568 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -618,14 +618,19 @@ print(soyle(lutfen_soyle=True)) # Ban soda alır mısın? Lutfen! Artık dayana ### Ücretsiz Online +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Dive Into Python](http://www.diveintopython.net/) * [Ideas for Python Projects](http://pythonpracticeprojects.com) - * [The Official Docs](http://docs.python.org/3/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) ### Kitaplar -- cgit v1.2.3 From 67a867ac0a96e6b5bdce8ab9cb700f3039741447 Mon Sep 17 00:00:00 2001 From: Mustafa Zengin Date: Mon, 25 Apr 2016 16:02:07 -0700 Subject: fsharp tutorial Turkish translation first pass complete --- tr-tr/fsharp-tr.html.markdown | 300 +++++++++++++++++++++--------------------- 1 file changed, 150 insertions(+), 150 deletions(-) diff --git a/tr-tr/fsharp-tr.html.markdown b/tr-tr/fsharp-tr.html.markdown index b844f552..828d7327 100644 --- a/tr-tr/fsharp-tr.html.markdown +++ b/tr-tr/fsharp-tr.html.markdown @@ -7,7 +7,7 @@ translators: filename: learnfsharp.fs --- -F# fonksiyonel ve nesne tabanlı, genel amaçlı bir programlama dilidir. Bedava ve açık kaynaklıdır ve Linux, Mac, Windows ve dahasında çalışır. +F# fonksiyonel ve nesne yönelimli, genel amaçlı bir programlama dilidir. Bedava ve açık kaynaklıdır ve Linux, Mac, Windows ve dahasında çalışır. Hataları derleme zamanında yakalayan çok güçlü bir tip sistemine sahiptir, ancak tip çıkarımı yaptığından dinamik bir dil gibi görünür. @@ -106,84 +106,84 @@ let optionPatternMatch input = optionPatternMatch validValue optionPatternMatch invalidValue -// ------ Printing ------ -// The printf/printfn functions are similar to the -// Console.Write/WriteLine functions in C#. +// ------ Yazdırma ------ +// printf/printfn fonksiyonları C#'taki +// Console.Write/WriteLine fonksiyonlarına benzer. printfn "Printing an int %i, a float %f, a bool %b" 1 2.0 true printfn "A string %s, and something generic %A" "hello" [1; 2; 3; 4] -// There are also sprintf/sprintfn functions for formatting data -// into a string, similar to String.Format in C#. +// sprintf/sprintfn fonksiyonları ise veriyi string'e +// çevirmek içindir, C#'taki String.Format gibi. // ================================================ -// More on functions +// Fonksiyonlar hakkında dahası // ================================================ -// F# is a true functional language -- functions are first -// class entities and can be combined easily to make powerful -// constructs +// F# gerçek bir fonksiyonel dildir. Fonksiyonlar birinci +// sınıf varlıklardır ve güçlü yapılar oluşturmak için +// birleştirilebilirler. -// Modules are used to group functions together -// Indentation is needed for each nested module. +// Modüller fonksiyonları gruplamak için kullanılır. +// Her bir modül için girinti gerekir. module FunctionExamples = - // define a simple adding function + // Temel bir ekleme fonksiyonu tanımla let add x y = x + y - // basic usage of a function + // Bir fonksiyonun temel kullanımı let a = add 1 2 printfn "1 + 2 = %i" a - // partial application to "bake in" parameters + // Parametreleri kaynaklamak için parçalı uygulama let add42 = add 42 let b = add42 1 printfn "42 + 1 = %i" b - // composition to combine functions + // Fonksiyonları birleştirmek için kompozisyon let add1 = add 1 let add2 = add 2 let add3 = add1 >> add2 let c = add3 7 printfn "3 + 7 = %i" c - // higher order functions + // Yüksek dereceli fonksiyonlar [1..10] |> List.map add3 |> printfn "new list is %A" - // lists of functions, and more + // Fonksiyonlar listesi ve dahası let add6 = [add1; add2; add3] |> List.reduce (>>) let d = add6 7 printfn "1 + 2 + 3 + 7 = %i" d // ================================================ -// Lists and collection +// Listeler ve kolleksiyonlar // ================================================ -// There are three types of ordered collection: -// * Lists are most basic immutable collection. -// * Arrays are mutable and more efficient when needed. -// * Sequences are lazy and infinite (e.g. an enumerator). -// -// Other collections include immutable maps and sets -// plus all the standard .NET collections +// Üç çesit sıralı fonksiyon vardır: +// * Listeler en temel değiştirilemez kolleksiyonlardır. +// * Diziler değiştirilebilir ve gerektiğinde daha verimlidirler. +// * Seriler tembel (lazy evaluation) ve sonsuzdurlar (Enumeratörler gibi). +// +// Değiştirilmez map'ler ve kümeler ve bütün .NET kolleksiyonları +// diğer kolleksiyon türleridir. module ListExamples = - // lists use square brackets + // listeler köşeli parantez kullanır let list1 = ["a"; "b"] - let list2 = "c" :: list1 // :: is prepending - let list3 = list1 @ list2 // @ is concat + let list2 = "c" :: list1 // :: başa eleman ekler + let list3 = list1 @ list2 // @ listeleri birbirine ekler - // list comprehensions (aka generators) + // Liste comprehension'ları (jeneratörler olarak da bilinir) let squares = [for i in 1..10 do yield i * i] - // prime number generator + // asal sayı jeneratörü let rec sieve = function | (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ] | [] -> [] let primes = sieve [2..50] printfn "%A" primes - // pattern matching for lists + // Listelerle kalıp eşleştirme let listMatcher aList = match aList with | [] -> printfn "the list is empty" @@ -196,7 +196,7 @@ module ListExamples = listMatcher [1] listMatcher [] - // recursion using lists + // Listeleri kullanarak recursion let rec sum aList = match aList with | [] -> 0 @@ -204,7 +204,7 @@ module ListExamples = sum [1..10] // ----------------------------------------- - // Standard library functions + // Standart kütüphane fonksiyonları // ----------------------------------------- // map @@ -215,15 +215,15 @@ module ListExamples = let even x = x % 2 = 0 [1..10] |> List.filter even - // many more -- see documentation + // ve dahası -- dökümantasyonu bakınız module ArrayExamples = - // arrays use square brackets with bar + // Diziler köşeli parantezle birlikte çubuk karakterini kullanır let array1 = [| "a"; "b" |] - let first = array1.[0] // indexed access using dot + let first = array1.[0] // nokta kullanarak indeks erişimi - // pattern matching for arrays is same as for lists + // Diziler için kalıp eşleştirme listlerle aynıdır let arrayMatcher aList = match aList with | [| |] -> printfn "the array is empty" @@ -233,7 +233,7 @@ module ArrayExamples = arrayMatcher [| 1; 2; 3; 4 |] - // Standard library functions just as for List + // Listede olduğu gibi kütüphane fonksiyonları [| 1..10 |] |> Array.map (fun i -> i + 3) @@ -243,16 +243,16 @@ module ArrayExamples = module SequenceExamples = - // sequences use curly braces + // seriler kıvrık parantez kullanır let seq1 = seq { yield "a"; yield "b" } - // sequences can use yield and - // can contain subsequences + // seriler yield'ı kullanabilir + // ve alt seriler barındırabilir let strange = seq { - // "yield" adds one element + // "yield" bir eleman ekliyor yield 1; yield 2; - // "yield!" adds a whole subsequence + // "yield!" bütün bir alt seriyi ekliyor yield! [5..10] yield! seq { for i in 1..10 do @@ -261,8 +261,8 @@ module SequenceExamples = strange |> Seq.toList - // Sequences can be created using "unfold" - // Here's the fibonacci series + // Seriler "unfold" kullanılarak oluşturulabilir + // Fibonacci serisi örneği let fib = Seq.unfold (fun (fst,snd) -> Some(fst + snd, (snd, fst + snd))) (0,1) @@ -272,49 +272,49 @@ module SequenceExamples = // ================================================ -// Data Types +// Veri Tipleri // ================================================ module DataTypeExamples = - // All data is immutable by default + // Bütün veriler varsayılan olarak değiştirilemezdir. - // Tuples are quick 'n easy anonymous types - // -- Use a comma to create a tuple + // Tuple'lar çabuk ve kolay anonim tiplerdir. + // -- Tuple oluşturmak için virgül kullan let twoTuple = 1, 2 let threeTuple = "a", 2, true - // Pattern match to unpack - let x, y = twoTuple // sets x = 1, y = 2 + // paketi açmak için kalıp eşleştirme kullan + let x, y = twoTuple // x = 1, y = 2 // ------------------------------------ - // Record types have named fields + // Record tipi isimlendirilmiş alanlara sahiptir // ------------------------------------ - // Use "type" with curly braces to define a record type + // "type" ile kıvrık parantezleri record tipi oluşturmak için kullan type Person = {First:string; Last:string} - // Use "let" with curly braces to create a record + // "let" ile kıvrık parantezi record tipi oluşturmak için kullan let person1 = {First="John"; Last="Doe"} - // Pattern match to unpack - let {First = first} = person1 // sets first="John" + // paketi açmak için kalıp eşleştirme kullan + let {First = first} = person1 // first="John" // ------------------------------------ - // Union types (aka variants) have a set of choices - // Only case can be valid at a time. + // Union tipleri (değişkenler olarak da bilinir) birden fazla + // seçeneğe sahiptir. Belli bir zamanda sadece bir tanesi geçerlidir. // ------------------------------------ - // Use "type" with bar/pipe to define a union type + // "type" ile çubuk karakterini union tipi tanımlamak için kullan type Temp = | DegreesC of float | DegreesF of float - // Use one of the cases to create one + // Seçeneklerden birini kullan let temp1 = DegreesF 98.6 let temp2 = DegreesC 37.0 - // Pattern match on all cases to unpack + // Paketi açmak için bütün seçenekler üzerinde kalıp eşleştirme kullan let printTemp = function | DegreesC t -> printfn "%f degC" t | DegreesF t -> printfn "%f degF" t @@ -323,11 +323,11 @@ module DataTypeExamples = printTemp temp2 // ------------------------------------ - // Recursive types + // Yinelgen (Recursive) tipler // ------------------------------------ - // Types can be combined recursively in complex ways - // without having to create subclasses + // Tipler alt sınıflar oluşturmadan karmaşık şekillerde + // yinelgen olarak birleştirilebilirler. type Employee = | Worker of Person | Manager of Employee list @@ -336,23 +336,22 @@ module DataTypeExamples = let worker = Worker jdoe // ------------------------------------ - // Modeling with types + // Tipleri Kullanarak Modelleme // ------------------------------------ - // Union types are great for modeling state without using flags + // Union tipleri bayrak kullanmadan durum modelleme için harikadır. type EmailAddress = | ValidEmailAddress of string | InvalidEmailAddress of string let trySendEmail email = - match email with // use pattern matching - | ValidEmailAddress address -> () // send - | InvalidEmailAddress address -> () // don't send + match email with // kalıp eşleştirme kullan + | ValidEmailAddress address -> () // gönder + | InvalidEmailAddress address -> () // gönderme - // The combination of union types and record types together - // provide a great foundation for domain driven design. - // You can create hundreds of little types that accurately - // reflect the domain. + // Union tiplerin record tiplerle birleşimi + // domain driven design için iyi bir temel oluşturur. + // Domain'i yansıtan yüzlerce ufak tip oluşturabilirsiniz. type CartItem = { ProductCode: string; Qty: int } type Payment = Payment of float @@ -360,26 +359,27 @@ module DataTypeExamples = type PaidCartData = { PaidItems: CartItem list; Payment: Payment} type ShoppingCart = - | EmptyCart // no data + | EmptyCart // veri yok | ActiveCart of ActiveCartData | PaidCart of PaidCartData // ------------------------------------ - // Built in behavior for types + // Tipler için içgüdüsel davranış // ------------------------------------ - // Core types have useful "out-of-the-box" behavior, no coding needed. - // * Immutability - // * Pretty printing when debugging - // * Equality and comparison + // Çekirdek tipler kendinden çok kullanışlı özelliklere sahiptir + // Ek kodlama gerektirmez + // * Değişmezlik + // * Debug ederken yazdırma + // * Eşitlik ve kıyaslama // * Serialization - // Pretty printing using %A + // %A kullanarak yazdırma printfn "twoTuple=%A,\nPerson=%A,\nTemp=%A,\nEmployee=%A" twoTuple person1 temp1 worker - // Equality and comparison built in. - // Here's an example with cards. + // Eşitlik ve kıyaslama içgüdüseldir. + // İskambil kartlarıyla bir örnek type Suit = Club | Diamond | Spade | Heart type Rank = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace @@ -387,31 +387,31 @@ module DataTypeExamples = let hand = [ Club, Ace; Heart, Three; Heart, Ace; Spade, Jack; Diamond, Two; Diamond, Ace ] - // sorting + // Sıralama List.sort hand |> printfn "sorted hand is (low to high) %A" List.max hand |> printfn "high card is %A" List.min hand |> printfn "low card is %A" // ================================================ -// Active patterns +// Aktif Kalıplar // ================================================ module ActivePatternExamples = - // F# has a special type of pattern matching called "active patterns" - // where the pattern can be parsed or detected dynamically. + // F# "aktif kalıplar" denen bir kalıp eşleştirmeye sahiptir. + // Kalıplar dinamik bir şekilde tespit edilip eşleştirilebilir. - // "banana clips" are the syntax for active patterns + // Aktif kalıplar için söz dizimi (| ... |) şeklindedir - // for example, define an "active" pattern to match character types... + // Örneğin, karakter tiplerini eşleyen bir "aktif" kalıp tanımlayın... let (|Digit|Letter|Whitespace|Other|) ch = if System.Char.IsDigit(ch) then Digit else if System.Char.IsLetter(ch) then Letter else if System.Char.IsWhiteSpace(ch) then Whitespace else Other - // ... and then use it to make parsing logic much clearer + // ... daha sonra eşleme mantığı çok daha net yapmak için bunu kullanın let printChar ch = match ch with | Digit -> printfn "%c is a Digit" ch @@ -419,19 +419,19 @@ module ActivePatternExamples = | Whitespace -> printfn "%c is a Whitespace" ch | _ -> printfn "%c is something else" ch - // print a list + // Bir liste yazdırma ['a'; 'b'; '1'; ' '; '-'; 'c'] |> List.iter printChar // ----------------------------------- - // FizzBuzz using active patterns + // Aktif Kalıpları Kullanarak FizzBuzz // ----------------------------------- - // You can create partial matching patterns as well - // Just use underscore in the definition, and return Some if matched. + // Parçalı eşleşen kalıplar da oluşturabilirsiniz + // Tanımda alt çizgi karakterini kullanın ve eşleşince Some döndürün. let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None - // the main function + // Ana fonksiyon let fizzBuzz i = match i with | MultOf3 & MultOf5 -> printf "FizzBuzz, " @@ -443,106 +443,106 @@ module ActivePatternExamples = [1..20] |> List.iter fizzBuzz // ================================================ -// Conciseness +// Sadelik // ================================================ module AlgorithmExamples = - // F# has a high signal/noise ratio, so code reads - // almost like the actual algorithm + // F#'ın sinyal/gürültü oranı yüksektir, dolayısıyla + // kod algoritmayla hemen hemen aynı görünür. - // ------ Example: define sumOfSquares function ------ + // ------ Örnek: sumOfSquares fonksiyonunu tanımla ------ let sumOfSquares n = - [1..n] // 1) take all the numbers from 1 to n - |> List.map square // 2) square each one - |> List.sum // 3) sum the results + [1..n] // 1) 1'den n'e kadar bütün sayıları al + |> List.map square // 2) hepsinin karesini al + |> List.sum // 3) sonuçları topla // test sumOfSquares 100 |> printfn "Sum of squares = %A" - // ------ Example: define a sort function ------ + // ------ Örnek: bir sıralama fonksiyonu tanımla ------ let rec sort list = match list with - // If the list is empty + // Liste boşsa | [] -> - [] // return an empty list - // If the list is not empty - | firstElem::otherElements -> // take the first element - let smallerElements = // extract the smaller elements - otherElements // from the remaining ones + [] // boş listeyi döndür + // Liste boş değilse + | firstElem::otherElements -> // İlk elemanı al + let smallerElements = // Daha küçük elemanları + otherElements // diğerlerinden ayır |> List.filter (fun e -> e < firstElem) - |> sort // and sort them - let largerElements = // extract the larger ones - otherElements // from the remaining ones + |> sort // ve sırala + let largerElements = // Daha büyük elemanları + otherElements // diğerlerinden ayır |> List.filter (fun e -> e >= firstElem) - |> sort // and sort them - // Combine the 3 parts into a new list and return it + |> sort // ve sırala + // 3 parçayı birbirine ekle ve listeyi döndür List.concat [smallerElements; [firstElem]; largerElements] // test sort [1; 5; 23; 18; 9; 1; 3] |> printfn "Sorted = %A" // ================================================ -// Asynchronous Code +// Eşzamanlı olmayan kod // ================================================ module AsyncExample = - // F# has built-in features to help with async code - // without encountering the "pyramid of doom" + // F# "pyramid of doom" durumuyla karşılaştırmayacak şekilde + // içgüdüsel eşzamanlı olmayan özelliklere sahiptir. // - // The following example downloads a set of web pages in parallel. + // Bir sonraki örnek bir web sayfasını paralel bir şekilde indirir. open System.Net open System open System.IO open Microsoft.FSharp.Control.CommonExtensions - // Fetch the contents of a URL asynchronously + // İçeriği eşzamanlı olmayan bir şekilde getir let fetchUrlAsync url = - async { // "async" keyword and curly braces - // creates an "async" object + async { // "async" anahtar kelimesi ve kıvrık parantez + // "async (eşzamanlı olmayan)" nesneyi oluşturur let req = WebRequest.Create(Uri(url)) use! resp = req.AsyncGetResponse() - // use! is async assignment + // use! eşzamanlı olmayan atamadır use stream = resp.GetResponseStream() - // "use" triggers automatic close() - // on resource at end of scope + // "use" kullanılan bloğun dışına çıkınca + // close()'u otomatik olarak tetikler use reader = new IO.StreamReader(stream) let html = reader.ReadToEnd() printfn "finished downloading %s" url } - // a list of sites to fetch + // İndirmek için bir web sitesi listesi let sites = ["http://www.bing.com"; "http://www.google.com"; "http://www.microsoft.com"; "http://www.amazon.com"; "http://www.yahoo.com"] - // do it + // İndir sites - |> List.map fetchUrlAsync // make a list of async tasks - |> Async.Parallel // set up the tasks to run in parallel - |> Async.RunSynchronously // start them off + |> List.map fetchUrlAsync // async görevlerden oluşan bir liste yap + |> Async.Parallel // bu görevleri paralel çalışacak şekilde ayarla + |> Async.RunSynchronously // başlat // ================================================ -// .NET compatibility +// .NET uyumluluğu // ================================================ module NetCompatibilityExamples = - // F# can do almost everything C# can do, and it integrates - // seamlessly with .NET or Mono libraries. + // F#, C#'ın yapabildiği hemen herşeyi yapabilir, + // ve .NET ve Mono kütüphaneleriyle tereyağından kıl çeker gibi çalışır. - // ------- work with existing library functions ------- + // ------- var olan kütüphane fonksiyonları ile çalışma ------- let (i1success, i1) = System.Int32.TryParse("123"); if i1success then printfn "parsed as %i" i1 else printfn "parse failed" - // ------- Implement interfaces on the fly! ------- + // ------- Arayüzleri yol üstünde tanımla! ------- - // create a new object that implements IDisposable + // IDisposable'ı sağlayan yeni bir nesne oluştur let makeResource name = { new System.IDisposable with member this.Dispose() = printfn "%s disposed" name } @@ -558,29 +558,29 @@ module NetCompatibilityExamples = printfn "using second resource" printfn "done." - // ------- Object oriented code ------- + // ------- Nesne yönelimli kod ------- - // F# is also a fully fledged OO language. - // It supports classes, inheritance, virtual methods, etc. + // F# aynı zamanda tam bir nesne yönelimli dildir. + // Sınıfları, kalıtımı ve sanal metotları destekler. - // interface with generic type + // Genel ipli bir arayüz type IEnumerator<'a> = abstract member Current : 'a abstract MoveNext : unit -> bool - // abstract base class with virtual methods + // Sanal metotları olan soyut temel sınıflar [] type Shape() = - // readonly properties + // sadece okunabilir özellikler abstract member Width : int with get abstract member Height : int with get - // non-virtual method + // sanal olmayan metot member this.BoundingArea = this.Height * this.Width - // virtual method with base implementation + // temel uygulamasıyla bir sanal metot abstract member Print : unit -> unit default this.Print () = printfn "I'm a shape" - // concrete class that inherits from base class and overrides + // Somut bir sınıfın soyut sınıftan kalıtımı type Rectangle(x:int, y:int) = inherit Shape() override this.Width = x @@ -593,9 +593,9 @@ module NetCompatibilityExamples = printfn "The area is %i" r.BoundingArea r.Print() - // ------- extension methods ------- + // ------- ekleme metotları ------- - // Just as in C#, F# can extend existing classes with extension methods. + // C#'ta olduğu gibi F# da var olan sınıfları ekleme metotları ile genişletebilir. type System.String with member this.StartsWithA = this.StartsWith "A" @@ -603,7 +603,7 @@ module NetCompatibilityExamples = let s = "Alice" printfn "'%s' starts with an 'A' = %A" s s.StartsWithA - // ------- events ------- + // ------- olaylar ------- type MyButton() = let clickEvent = new Event<_>() @@ -623,8 +623,8 @@ module NetCompatibilityExamples = ``` -## More Information +## Daha fazla bilgi -For more demonstrations of F#, go to the [Try F#](http://www.tryfsharp.org/Learn) site, or my [why use F#](http://fsharpforfunandprofit.com/why-use-fsharp/) series. +F# hakkında daha fazla demo için [Try F#](http://www.tryfsharp.org/Learn) sitesine gidin, veya benim (yazarın) [why use F#](http://fsharpforfunandprofit.com/why-use-fsharp/) serimi okuyun. -Read more about F# at [fsharp.org](http://fsharp.org/). +F# hakkında daha fazla bilgi için: [fsharp.org](http://fsharp.org/). -- cgit v1.2.3 From 6136efa772228ce6ac6d6c98f33efd1b864fab0e Mon Sep 17 00:00:00 2001 From: Sergey Isaev Date: Tue, 26 Apr 2016 03:58:30 +0400 Subject: Fix url for language specifications --- typescript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 47e41405..260e1d55 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -171,7 +171,7 @@ of a multiline string`; ## Further Reading * [TypeScript Official website] (http://www.typescriptlang.org/) - * [TypeScript language specifications (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [TypeScript language specifications (pdf)] (https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md) * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) * [Source Code on GitHub] (https://github.com/Microsoft/TypeScript) * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/) -- cgit v1.2.3 From 343b7e20cad729e35f86a0563d943f68903f9752 Mon Sep 17 00:00:00 2001 From: Sergey Isaev Date: Tue, 26 Apr 2016 03:59:06 +0400 Subject: Update typescript.html.markdown --- typescript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 260e1d55..21f1ce7d 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -171,7 +171,7 @@ of a multiline string`; ## Further Reading * [TypeScript Official website] (http://www.typescriptlang.org/) - * [TypeScript language specifications (pdf)] (https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md) + * [TypeScript language specifications] (https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md) * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) * [Source Code on GitHub] (https://github.com/Microsoft/TypeScript) * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/) -- cgit v1.2.3 From 71cf39f9c20f09bfd9b7dd60f3ec577420b0709d Mon Sep 17 00:00:00 2001 From: Mustafa Zengin Date: Mon, 25 Apr 2016 19:22:56 -0700 Subject: translation within the code --- tr-tr/fsharp-tr.html.markdown | 400 +++++++++++++++++++++--------------------- 1 file changed, 200 insertions(+), 200 deletions(-) diff --git a/tr-tr/fsharp-tr.html.markdown b/tr-tr/fsharp-tr.html.markdown index 828d7327..c89b2e34 100644 --- a/tr-tr/fsharp-tr.html.markdown +++ b/tr-tr/fsharp-tr.html.markdown @@ -33,84 +33,84 @@ Aşağıdaki kodu denemek istiyorsanız, [tryfsharp.org](http://www.tryfsharp.or // "let" anahtar kelimesi (değişmez) değer tanımlar let myInt = 5 let myFloat = 3.14 -let myString = "hello" // tip bilgisi olmamasına dikkat +let myString = "merhaba" // tip bilgisi olmamasına dikkat // ------ Listeler ------ -let twoToFive = [2; 3; 4; 5] // Köşeli parantezler listeleri oluşturur, - // değerler ise noktalı virgülle ayrılır. -let oneToFive = 1 :: twoToFive // :: yeni birinci elemanı olan bir liste oluşturur. +let ikidenBese = [2; 3; 4; 5] // Köşeli parantezler listeleri oluşturur, + // değerler ise noktalı virgülle ayrılır. +let birdenBese = 1 :: ikidenBese // :: yeni birinci elemanı olan bir liste oluşturur. // Sonuç: [1; 2; 3; 4; 5] -let zeroToFive = [0; 1] @ twoToFive // @ iki listeyi birbirine ekler. +let sifirdanBese = [0; 1] @ ikidenBese // @ iki listeyi birbirine ekler. // ÖNEMLİ: virgüller hiçbir zaman ayraç olarak kullanılmaz, sadece noktalı virgüller! // ------ Fonksiyonlar ------ // "let" anahtar kelimesi isimlendirilmiş fonksiyonları da tanımlar. -let square x = x * x // Parantez kullanılmadığına dikkat. -square 3 // Şimdi fonksiyonu uygula. Yine parantez yok. +let kare x = x * x // Parantez kullanılmadığına dikkat. +kare 3 // Şimdi fonksiyonu uygula. Yine parantez yok. -let add x y = x + y // add (x,y) kullanmayın! Bu tamamen başka bir anlama geliyor. -add 2 3 // Şimdi fonksiyonu uygula. +let topla x y = x + y // topla (x,y) kullanmayın! Bu tamamen başka bir anlama geliyor. +topla 2 3 // Şimdi fonksiyonu uygula. // çok satırlı bir fonksiyon tanımlamak için sadece girinti kullan. Noktalıı virgül gerekmez. -let evens list = - let isEven x = x % 2 = 0 // "isEven"ı alt fonksiyon olarak tanımla - List.filter isEven list // List.filter boolean bir fonksiyon ve - // üzerinde çalışılacak bir liste parametrelerinden oluşan - // bir kütüphane fonksiyonu +let ciftler liste = + let ciftMi x = x % 2 = 0 // "ciftMi"yi alt fonksiyon olarak tanımla + List.filter ciftMi liste // List.filter boolean bir fonksiyon ve + // üzerinde çalışılacak bir liste parametrelerinden oluşan + // bir kütüphane fonksiyonu -evens oneToFive // Şimdi fonksiyonu uygula. +evens birdenBese // Şimdi fonksiyonu uygula. // Parantezleri önceliği netleştirmek için kullanabilirsin. Bu örnekte -// "map"i önce iki argümanla uygula, sonra sonuç üzerinde "sum" uygula. -// Parantezler olmasaydı, "List.map" List.sum'ın ilk argümanı olurdu. -let sumOfSquaresTo100 = - List.sum ( List.map square [1..100] ) +// "map"i önce iki argümanla uygula, sonra sonuç üzerinde "ekle" uygula. +// Parantezler olmasaydı, "List.map" List.ekle'ın ilk argümanı olurdu. +let yuzeKadarKarelerinToplami = + List.ekle ( List.map kare [1..100] ) // Bir operasyonun sonucunu bir sonrakine "|>" kullanarak besleyebilirsin. // Veri beslemek F#'ta UNIX'te olduğu gibi yaygındır.. -// Burada sumOfSquares fonksiyonunun veri beslemeyle yazılmış hali var: -let sumOfSquaresTo100piped = - [1..100] |> List.map square |> List.sum // "square" önceden tanımlanmıştı +// Burada karelerToplami fonksiyonunun veri beslemeyle yazılmış hali var: +let veriBeslemeyleYuzeKadarKarelerinToplami = + [1..100] |> List.map kare |> List.ekle // "kare" önceden tanımlanmıştı // Lambda'ları (anonim fonksiyonları) "fun" anahtar kelimesiyle tanımlayabilirsin -let sumOfSquaresTo100withFun = - [1..100] |> List.map (fun x -> x * x) |> List.sum +let funlaYuzeKadarKarelerinToplami = + [1..100] |> List.map (fun x -> x * x) |> List.ekle // F#'ta "return" anahtar kelimesi yoktur. Bir fonksiyon // her zaman son kullanılan ifadeyi döndürür. // ------ Kalıp eşleştirme ------ // Match..with.. çok güçlü bir case/switch türevidir. -let simplePatternMatch = +let basitKalipEslestirme = let x = "a" match x with - | "a" -> printfn "x is a" - | "b" -> printfn "x is b" - | _ -> printfn "x is something else" // alt çizgi bütün kalıplarla eşleşir + | "a" -> printfn "x a'dır" + | "b" -> printfn "x b'dir" + | _ -> printfn "x başka bir şeydir" // alt çizgi bütün kalıplarla eşleşir // F# varsayılan olarak null'lara izin vermez -- Option tipini kullanıp // kalıp eşleştirme yapmalısın. // Some(..) ve None, Nullable tipler gibidir. -let validValue = Some(99) -let invalidValue = None +let gecerliDeger = Some(99) +let gecersizDeger = None // Bu örnekte, match..with "Some" ve "None"la eşleştirme yapıyor, // ve ayrıca "Some" içerisindeki değeri de çıkarıyor. -let optionPatternMatch input = +let optionKalipEslestirme input = match input with | Some i -> printfn "input is an int=%d" i | None -> printfn "input is missing" -optionPatternMatch validValue -optionPatternMatch invalidValue +optionKalipEslestirme gecerliDeger +optionKalipEslestirme gecersizDeger // ------ Yazdırma ------ // printf/printfn fonksiyonları C#'taki // Console.Write/WriteLine fonksiyonlarına benzer. -printfn "Printing an int %i, a float %f, a bool %b" 1 2.0 true -printfn "A string %s, and something generic %A" "hello" [1; 2; 3; 4] +printfn "Bir int %i, bir ondalık %f, bir boolean %b yazdırma" 1 2.0 true +printfn "Bir string %s, ve jenerik bir tip %A" "hello" [1; 2; 3; 4] // sprintf/sprintfn fonksiyonları ise veriyi string'e // çevirmek içindir, C#'taki String.Format gibi. @@ -125,33 +125,33 @@ printfn "A string %s, and something generic %A" "hello" [1; 2; 3; 4] // Modüller fonksiyonları gruplamak için kullanılır. // Her bir modül için girinti gerekir. -module FunctionExamples = +module FonksiyonOrnekleri = // Temel bir ekleme fonksiyonu tanımla - let add x y = x + y + let topla x y = x + y // Bir fonksiyonun temel kullanımı - let a = add 1 2 + let a = topla 1 2 printfn "1 + 2 = %i" a // Parametreleri kaynaklamak için parçalı uygulama - let add42 = add 42 - let b = add42 1 + let kirkIkiEkle = topla 42 + let b = kirkIkiEkle 1 printfn "42 + 1 = %i" b // Fonksiyonları birleştirmek için kompozisyon - let add1 = add 1 - let add2 = add 2 - let add3 = add1 >> add2 - let c = add3 7 + let birEkle = topla 1 + let ikiEkle = topla 2 + let ucEkle = birEkle >> ikiEkle + let c = ucEkle 7 printfn "3 + 7 = %i" c // Yüksek dereceli fonksiyonlar - [1..10] |> List.map add3 |> printfn "new list is %A" + [1..10] |> List.map ucEkle |> printfn "yeni liste: %A" // Fonksiyonlar listesi ve dahası - let add6 = [add1; add2; add3] |> List.reduce (>>) - let d = add6 7 + let altiEkle = [birEkle; ikiEkle; ucEkle] |> List.reduce (>>) + let d = altiEkle 7 printfn "1 + 2 + 3 + 7 = %i" d // ================================================ @@ -169,27 +169,27 @@ module FunctionExamples = module ListExamples = // listeler köşeli parantez kullanır - let list1 = ["a"; "b"] - let list2 = "c" :: list1 // :: başa eleman ekler - let list3 = list1 @ list2 // @ listeleri birbirine ekler + let liste1 = ["a"; "b"] + let liste2 = "c" :: liste1 // :: başa eleman ekler + let liste3 = liste1 @ liste2 // @ listeleri birbirine ekler // Liste comprehension'ları (jeneratörler olarak da bilinir) - let squares = [for i in 1..10 do yield i * i] + let kareler = [for i in 1..10 do yield i * i] // asal sayı jeneratörü - let rec sieve = function - | (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ] + let rec elek = function + | (p::xler) -> p :: elek [ for x in xler do if x % p > 0 then yield x ] | [] -> [] - let primes = sieve [2..50] - printfn "%A" primes + let asallar = elek [2..50] + printfn "%A" asallar // Listelerle kalıp eşleştirme - let listMatcher aList = - match aList with - | [] -> printfn "the list is empty" - | [first] -> printfn "the list has one element %A " first - | [first; second] -> printfn "list is %A and %A" first second - | _ -> printfn "the list has more than two elements" + let listMatcher liste = + match liste with + | [] -> printfn "liste boş" + | [birinci] -> printfn "listede sadece bir eleman var: %A " birinci + | [birinci; ikinci] -> printfn "liste: %A ve %A" birinci ikinci + | _ -> printfn "listede ikiden fazla eleman var" listMatcher [1; 2; 3; 4] listMatcher [1; 2] @@ -197,58 +197,58 @@ module ListExamples = listMatcher [] // Listeleri kullanarak recursion - let rec sum aList = - match aList with + let rec ekle liste = + match liste with | [] -> 0 - | x::xs -> x + sum xs - sum [1..10] + | x::xler -> x + ekle xler + ekle [1..10] // ----------------------------------------- // Standart kütüphane fonksiyonları // ----------------------------------------- // map - let add3 x = x + 3 - [1..10] |> List.map add3 + let ucEkle x = x + 3 + [1..10] |> List.map ucEkle // filter - let even x = x % 2 = 0 - [1..10] |> List.filter even + let cift x = x % 2 = 0 + [1..10] |> List.filter cift - // ve dahası -- dökümantasyonu bakınız + // ve dahası -- dökümantasyona bakınız -module ArrayExamples = +module DiziOrnekleri = // Diziler köşeli parantezle birlikte çubuk karakterini kullanır - let array1 = [| "a"; "b" |] - let first = array1.[0] // nokta kullanarak indeks erişimi + let dizi1 = [| "a"; "b" |] + let birinci = dizi1.[0] // nokta kullanarak indeks erişimi // Diziler için kalıp eşleştirme listlerle aynıdır - let arrayMatcher aList = - match aList with - | [| |] -> printfn "the array is empty" - | [| first |] -> printfn "the array has one element %A " first - | [| first; second |] -> printfn "array is %A and %A" first second - | _ -> printfn "the array has more than two elements" + let diziEslestirici liste = + match liste with + | [| |] -> printfn "dizi boş" + | [| birinci |] -> printfn "dizide sadece bir eleman var: %A " birinci + | [| birinci; ikinci |] -> printfn "dizi: %A ve %A" birinci ikinci + | _ -> printfn "dizide ikiden fazla eleman var" - arrayMatcher [| 1; 2; 3; 4 |] + diziEslestirici [| 1; 2; 3; 4 |] // Listede olduğu gibi kütüphane fonksiyonları [| 1..10 |] |> Array.map (fun i -> i + 3) |> Array.filter (fun i -> i % 2 = 0) - |> Array.iter (printfn "value is %i. ") + |> Array.iter (printfn "değer: %i. ") -module SequenceExamples = +module SeriOrnekleri = // seriler kıvrık parantez kullanır - let seq1 = seq { yield "a"; yield "b" } + let seri1 = seq { yield "a"; yield "b" } // seriler yield'ı kullanabilir // ve alt seriler barındırabilir - let strange = seq { + let garip = seq { // "yield" bir eleman ekliyor yield 1; yield 2; @@ -258,47 +258,47 @@ module SequenceExamples = for i in 1..10 do if i % 2 = 0 then yield i }} // test - strange |> Seq.toList + garip |> Seq.toList // Seriler "unfold" kullanılarak oluşturulabilir // Fibonacci serisi örneği - let fib = Seq.unfold (fun (fst,snd) -> - Some(fst + snd, (snd, fst + snd))) (0,1) + let fib = Seq.unfold (fun (birinci,ikinci) -> + Some(birinci + ikinci, (ikinci, birinci + ikinci))) (0,1) // test let fib10 = fib |> Seq.take 10 |> Seq.toList - printf "first 10 fibs are %A" fib10 + printf "ilk 10 fibonacci sayısı: %A" fib10 // ================================================ // Veri Tipleri // ================================================ -module DataTypeExamples = +module VeriTipiOrnekleri = // Bütün veriler varsayılan olarak değiştirilemezdir. // Tuple'lar çabuk ve kolay anonim tiplerdir. - // -- Tuple oluşturmak için virgül kullan - let twoTuple = 1, 2 - let threeTuple = "a", 2, true - // paketi açmak için kalıp eşleştirme kullan - let x, y = twoTuple // x = 1, y = 2 + let x, y = ikiliTuple // x = 1, y = 2 + + // -- Tuple oluşturmak için virgül kullan + let ikiliTuple = 1, 2 + let ucluTuple = "a", 2, true // ------------------------------------ // Record tipi isimlendirilmiş alanlara sahiptir // ------------------------------------ // "type" ile kıvrık parantezleri record tipi oluşturmak için kullan - type Person = {First:string; Last:string} + type Kisi = {birinci:string; Last:string} // "let" ile kıvrık parantezi record tipi oluşturmak için kullan - let person1 = {First="John"; Last="Doe"} + let kisi1 = {birinci="John"; Last="Doe"} // paketi açmak için kalıp eşleştirme kullan - let {First = first} = person1 // first="John" + let {birinci = birinci} = kisi1 // birinci="John" // ------------------------------------ // Union tipleri (değişkenler olarak da bilinir) birden fazla @@ -306,21 +306,21 @@ module DataTypeExamples = // ------------------------------------ // "type" ile çubuk karakterini union tipi tanımlamak için kullan - type Temp = - | DegreesC of float - | DegreesF of float + type Derece = + | Santigrat of float + | Fahrenhayt of float // Seçeneklerden birini kullan - let temp1 = DegreesF 98.6 - let temp2 = DegreesC 37.0 + let derece1 = Fahrenhayt 98.6 + let derece2 = Santigrat 37.0 // Paketi açmak için bütün seçenekler üzerinde kalıp eşleştirme kullan - let printTemp = function - | DegreesC t -> printfn "%f degC" t - | DegreesF t -> printfn "%f degF" t + let dereceYazdir = function + | Santigrat t -> printfn "%f C" t + | Fahrenhayt t -> printfn "%f F" t - printTemp temp1 - printTemp temp2 + dereceYazdir derece1 + dereceYazdir derece2 // ------------------------------------ // Yinelgen (Recursive) tipler @@ -328,40 +328,40 @@ module DataTypeExamples = // Tipler alt sınıflar oluşturmadan karmaşık şekillerde // yinelgen olarak birleştirilebilirler. - type Employee = - | Worker of Person - | Manager of Employee list + type Calisan = + | Isci of Kisi + | Yonetici of Calisan liste - let jdoe = {First="John"; Last="Doe"} - let worker = Worker jdoe + let falancaKisi = {birinci="John"; Last="Doe"} + let isci = Isci falancaKisi // ------------------------------------ // Tipleri Kullanarak Modelleme // ------------------------------------ // Union tipleri bayrak kullanmadan durum modelleme için harikadır. - type EmailAddress = - | ValidEmailAddress of string - | InvalidEmailAddress of string + type EpostaAdresi = + | GecerliEpostaAdresi of string + | GecersizEpostaAdresi of string - let trySendEmail email = - match email with // kalıp eşleştirme kullan - | ValidEmailAddress address -> () // gönder - | InvalidEmailAddress address -> () // gönderme + let epostaGondermeyiDene eposta = + match eposta with // kalıp eşleştirme kullan + | GecerliEpostaAdresi adres -> () // gönder + | GecersizEpostaAdresi adres -> () // gönderme // Union tiplerin record tiplerle birleşimi // domain driven design için iyi bir temel oluşturur. // Domain'i yansıtan yüzlerce ufak tip oluşturabilirsiniz. - type CartItem = { ProductCode: string; Qty: int } - type Payment = Payment of float - type ActiveCartData = { UnpaidItems: CartItem list } - type PaidCartData = { PaidItems: CartItem list; Payment: Payment} + type Urun = { UrunKodu: string; Miktar: int } + type Odeme = Odeme of float + type AktifSepetVerisi = { OdenmemisUrunler: Urun liste } + type OndenmisSepetVerisi = { OdenmisUrunler: Urun liste; Odeme: Odeme} - type ShoppingCart = - | EmptyCart // veri yok - | ActiveCart of ActiveCartData - | PaidCart of PaidCartData + type AlisverisSepeti = + | BosSepet // veri yok + | AktifSepet of AktifSepetVerisi + | OdenmisSepet of OndenmisSepetVerisi // ------------------------------------ // Tipler için içgüdüsel davranış @@ -375,29 +375,29 @@ module DataTypeExamples = // * Serialization // %A kullanarak yazdırma - printfn "twoTuple=%A,\nPerson=%A,\nTemp=%A,\nEmployee=%A" - twoTuple person1 temp1 worker + printfn "ikiliTuple=%A,\nKisi=%A,\nDerece=%A,\nCalisan=%A" + ikiliTuple kisi1 derece1 isci // Eşitlik ve kıyaslama içgüdüseldir. // İskambil kartlarıyla bir örnek - type Suit = Club | Diamond | Spade | Heart - type Rank = Two | Three | Four | Five | Six | Seven | Eight - | Nine | Ten | Jack | Queen | King | Ace + type Simge = Sinek | Karo | Maca | Kupa + type Sira = Iki | Uc | Dort | Bes | Alti | Yedi | Sekiz + | Dokuz | On | Bacak | Kiz | Papaz | As - let hand = [ Club, Ace; Heart, Three; Heart, Ace; - Spade, Jack; Diamond, Two; Diamond, Ace ] + let el = [ Sinek, As; Kupa, Uc; Kupa, As; + Maca, Bacak; Karo, Iki; Karo, As ] // Sıralama - List.sort hand |> printfn "sorted hand is (low to high) %A" - List.max hand |> printfn "high card is %A" - List.min hand |> printfn "low card is %A" + List.sirala el |> printfn "artarak dizilen el: %A" + List.max el |> printfn "en yüksek kart: %A" + List.min el |> printfn "en düşük kart: %A" // ================================================ // Aktif Kalıplar // ================================================ -module ActivePatternExamples = +module AktifKalipOrnekleri = // F# "aktif kalıplar" denen bir kalıp eşleştirmeye sahiptir. // Kalıplar dinamik bir şekilde tespit edilip eşleştirilebilir. @@ -405,22 +405,22 @@ module ActivePatternExamples = // Aktif kalıplar için söz dizimi (| ... |) şeklindedir // Örneğin, karakter tiplerini eşleyen bir "aktif" kalıp tanımlayın... - let (|Digit|Letter|Whitespace|Other|) ch = - if System.Char.IsDigit(ch) then Digit - else if System.Char.IsLetter(ch) then Letter - else if System.Char.IsWhiteSpace(ch) then Whitespace - else Other + let (|Rakam|Harf|Bosluk|Diger|) karakter = + if System.Char.IsDigit(karakter) then Rakam + else if System.Char.IsLetter(karakter) then Harf + else if System.Char.IsWhiteSpace(karakter) then Bosluk + else Diger // ... daha sonra eşleme mantığı çok daha net yapmak için bunu kullanın - let printChar ch = - match ch with - | Digit -> printfn "%c is a Digit" ch - | Letter -> printfn "%c is a Letter" ch - | Whitespace -> printfn "%c is a Whitespace" ch - | _ -> printfn "%c is something else" ch + let karakterYazdir karakter = + match karakter with + | Rakam -> printfn "%c bir rakamdır" karakter + | Harf -> printfn "%c bir harftir" karakter + | Bosluk -> printfn "%c bir boşluktur" karakter + | _ -> printfn "%c başka bir şeydir" karakter // Bir liste yazdırma - ['a'; 'b'; '1'; ' '; '-'; 'c'] |> List.iter printChar + ['a'; 'b'; '1'; ' '; '-'; 'c'] |> List.iter karakterYazdir // ----------------------------------- // Aktif Kalıpları Kullanarak FizzBuzz @@ -428,15 +428,15 @@ module ActivePatternExamples = // Parçalı eşleşen kalıplar da oluşturabilirsiniz // Tanımda alt çizgi karakterini kullanın ve eşleşince Some döndürün. - let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None - let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None + let (|UcunKati|_|) i = if i % 3 = 0 then Some UcunKati else None + let (|BesinKati|_|) i = if i % 5 = 0 then Some BesinKati else None // Ana fonksiyon let fizzBuzz i = match i with - | MultOf3 & MultOf5 -> printf "FizzBuzz, " - | MultOf3 -> printf "Fizz, " - | MultOf5 -> printf "Buzz, " + | UcunKati & BesinKati -> printf "FizzBuzz, " + | UcunKati -> printf "Fizz, " + | BesinKati -> printf "Buzz, " | _ -> printf "%i, " i // test @@ -446,50 +446,50 @@ module ActivePatternExamples = // Sadelik // ================================================ -module AlgorithmExamples = +module AlgoritmaOrnekleri = // F#'ın sinyal/gürültü oranı yüksektir, dolayısıyla // kod algoritmayla hemen hemen aynı görünür. - // ------ Örnek: sumOfSquares fonksiyonunu tanımla ------ - let sumOfSquares n = - [1..n] // 1) 1'den n'e kadar bütün sayıları al - |> List.map square // 2) hepsinin karesini al - |> List.sum // 3) sonuçları topla + // ------ Örnek: karelerToplami fonksiyonunu tanımla ------ + let karelerToplami n = + [1..n] // 1) 1'den n'e kadar bütün sayıları al + |> List.map kare // 2) hepsinin karesini al + |> List.ekle // 3) sonuçları topla // test - sumOfSquares 100 |> printfn "Sum of squares = %A" + karelerToplami 100 |> printfn "kareler toplamı = %A" // ------ Örnek: bir sıralama fonksiyonu tanımla ------ - let rec sort list = - match list with + let rec sirala liste = + match liste with // Liste boşsa | [] -> - [] // boş listeyi döndür + [] // boş listeyi döndür // Liste boş değilse - | firstElem::otherElements -> // İlk elemanı al - let smallerElements = // Daha küçük elemanları - otherElements // diğerlerinden ayır - |> List.filter (fun e -> e < firstElem) - |> sort // ve sırala - let largerElements = // Daha büyük elemanları - otherElements // diğerlerinden ayır - |> List.filter (fun e -> e >= firstElem) - |> sort // ve sırala + | ilkEleman::digerElemanlar -> // İlk elemanı al + let kucukElemanlar = // Daha küçük elemanları + digerElemanlar // diğerlerinden ayır + |> List.filter (fun e -> e < ilkEleman) + |> sirala // ve sırala + let buyukElemanlar = // Daha büyük elemanları + digerElemanlar // diğerlerinden ayır + |> List.filter (fun e -> e >= ilkEleman) + |> sirala // ve sırala // 3 parçayı birbirine ekle ve listeyi döndür - List.concat [smallerElements; [firstElem]; largerElements] + List.concat [kucukElemanlar; [ilkEleman]; buyukElemanlar] // test - sort [1; 5; 23; 18; 9; 1; 3] |> printfn "Sorted = %A" + sirala [1; 5; 23; 18; 9; 1; 3] |> printfn "Sırala = %A" // ================================================ -// Eşzamanlı olmayan kod +// Eşzamansız kod // ================================================ -module AsyncExample = +module EszamansizOrnegi = // F# "pyramid of doom" durumuyla karşılaştırmayacak şekilde - // içgüdüsel eşzamanlı olmayan özelliklere sahiptir. + // içgüdüsel eşzamansız özelliklere sahiptir. // // Bir sonraki örnek bir web sayfasını paralel bir şekilde indirir. @@ -498,39 +498,39 @@ module AsyncExample = open System.IO open Microsoft.FSharp.Control.CommonExtensions - // İçeriği eşzamanlı olmayan bir şekilde getir - let fetchUrlAsync url = + // İçeriği eşzamansız bir şekilde getir + let eszamansizUrlGetir url = async { // "async" anahtar kelimesi ve kıvrık parantez - // "async (eşzamanlı olmayan)" nesneyi oluşturur - let req = WebRequest.Create(Uri(url)) - use! resp = req.AsyncGetResponse() - // use! eşzamanlı olmayan atamadır - use stream = resp.GetResponseStream() + // "async (eşzamansız)" nesneyi oluşturur + let istek = WebRequest.Create(Uri(url)) + use! cevap = istek.AsyncGetResponse() + // use! eşzamansız atamadır + use akis = cevap.GetResponseStream() // "use" kullanılan bloğun dışına çıkınca // close()'u otomatik olarak tetikler - use reader = new IO.StreamReader(stream) - let html = reader.ReadToEnd() - printfn "finished downloading %s" url + use okuyucu = new IO.StreamReader(akis) + let html = okuyucu.ReadToEnd() + printfn "İndirme tamamlandı: %s" url } // İndirmek için bir web sitesi listesi - let sites = ["http://www.bing.com"; + let siteler = ["http://www.bing.com"; "http://www.google.com"; "http://www.microsoft.com"; "http://www.amazon.com"; "http://www.yahoo.com"] // İndir - sites - |> List.map fetchUrlAsync // async görevlerden oluşan bir liste yap - |> Async.Parallel // bu görevleri paralel çalışacak şekilde ayarla - |> Async.RunSynchronously // başlat + siteler + |> List.map eszamansizUrlGetir // eşzamansız görevlerden oluşan bir liste yap + |> Async.Parallel // bu görevleri paralel çalışacak şekilde ayarla + |> Async.RunSynchronously // başlat // ================================================ // .NET uyumluluğu // ================================================ -module NetCompatibilityExamples = +module NetUyumlulukOrnekleri = // F#, C#'ın yapabildiği hemen herşeyi yapabilir, // ve .NET ve Mono kütüphaneleriyle tereyağından kıl çeker gibi çalışır. @@ -548,14 +548,14 @@ module NetCompatibilityExamples = with member this.Dispose() = printfn "%s disposed" name } let useAndDisposeResources = - use r1 = makeResource "first resource" - printfn "using first resource" + use r1 = makeResource "birinci resource" + printfn "using birinci resource" for i in [1..3] do let resourceName = sprintf "\tinner resource %d" i use temp = makeResource resourceName printfn "\tdo something with %s" resourceName - use r2 = makeResource "second resource" - printfn "using second resource" + use r2 = makeResource "ikinci resource" + printfn "using ikinci resource" printfn "done." // ------- Nesne yönelimli kod ------- @@ -616,7 +616,7 @@ module NetCompatibilityExamples = // test let myButton = new MyButton() - myButton.OnClick.Add(fun (sender, arg) -> + myButton.OnClick.topla(fun (sender, arg) -> printfn "Click event with arg=%O" arg) myButton.TestEvent("Hello World!") -- cgit v1.2.3 From 8bd2fd283a5441f8be1382c536fb443baf1ab911 Mon Sep 17 00:00:00 2001 From: Mustafa Zengin Date: Mon, 25 Apr 2016 22:34:41 -0700 Subject: fsharp turkish translation, translation for code piece is also complete --- tr-tr/fsharp-tr.html.markdown | 368 +++++++++++++++++++++--------------------- 1 file changed, 184 insertions(+), 184 deletions(-) diff --git a/tr-tr/fsharp-tr.html.markdown b/tr-tr/fsharp-tr.html.markdown index c89b2e34..d88e2594 100644 --- a/tr-tr/fsharp-tr.html.markdown +++ b/tr-tr/fsharp-tr.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Scott Wlaschin", "http://fsharpforfunandprofit.com/"] translators: - ["Mustafa Zengin", "http://zengin.github.com/"] -filename: learnfsharp.fs +filename: learnfsharp-tr.fs --- F# fonksiyonel ve nesne yönelimli, genel amaçlı bir programlama dilidir. Bedava ve açık kaynaklıdır ve Linux, Mac, Windows ve dahasında çalışır. @@ -20,8 +20,8 @@ Aşağıdaki kodu denemek istiyorsanız, [tryfsharp.org](http://www.tryfsharp.or ```csharp -// tek satır yorumlar ikili bölme işareti kullanılır -(* çok satırlı yorumlar (* . . . *) ikilisini kullanır +// tek satır yorumlar ikili bölme işareti ile başlar +(* çok satırlı yorumlar ( * . . . * ) ikilisini kullanır -çok satırlı yorumun sonu- *) @@ -31,59 +31,59 @@ Aşağıdaki kodu denemek istiyorsanız, [tryfsharp.org](http://www.tryfsharp.or // ------ "Değişkenler" (tam da değil) ------ // "let" anahtar kelimesi (değişmez) değer tanımlar -let myInt = 5 -let myFloat = 3.14 -let myString = "merhaba" // tip bilgisi olmamasına dikkat +let tamsayım = 5 +let ondalığım = 3.14 +let stringim = "merhaba" // tip bilgisi olmamasına dikkat // ------ Listeler ------ -let ikidenBese = [2; 3; 4; 5] // Köşeli parantezler listeleri oluşturur, - // değerler ise noktalı virgülle ayrılır. -let birdenBese = 1 :: ikidenBese // :: yeni birinci elemanı olan bir liste oluşturur. +let ikidenBeşe = [2; 3; 4; 5] // Köşeli parantezler listeleri oluşturur, + // değerler ise noktalı virgülle ayrılır. +let birdenBeşe = 1 :: ikidenBeşe // :: yeni birinci elemanı olan bir liste oluşturur. // Sonuç: [1; 2; 3; 4; 5] -let sifirdanBese = [0; 1] @ ikidenBese // @ iki listeyi birbirine ekler. +let sıfırdanBeşe = [0; 1] @ ikidenBeşe // @ iki listeyi birbirine ekler. // ÖNEMLİ: virgüller hiçbir zaman ayraç olarak kullanılmaz, sadece noktalı virgüller! // ------ Fonksiyonlar ------ // "let" anahtar kelimesi isimlendirilmiş fonksiyonları da tanımlar. let kare x = x * x // Parantez kullanılmadığına dikkat. -kare 3 // Şimdi fonksiyonu uygula. Yine parantez yok. +kare 3 // Şimdi fonksiyonu uygulayın. Yine parantez yok. let topla x y = x + y // topla (x,y) kullanmayın! Bu tamamen başka bir anlama geliyor. -topla 2 3 // Şimdi fonksiyonu uygula. - -// çok satırlı bir fonksiyon tanımlamak için sadece girinti kullan. Noktalıı virgül gerekmez. -let ciftler liste = - let ciftMi x = x % 2 = 0 // "ciftMi"yi alt fonksiyon olarak tanımla - List.filter ciftMi liste // List.filter boolean bir fonksiyon ve - // üzerinde çalışılacak bir liste parametrelerinden oluşan - // bir kütüphane fonksiyonu +topla 2 3 // Şimdi fonksiyonu uygulayın. + +// çok satırlı bir fonksiyon tanımlamak için sadece girinti kullanın. Noktalı virgül gerekmez. +let çiftler liste = + let çiftMi x = x % 2 = 0 // "çiftMi"yi alt fonksiyon olarak tanımlayın + List.filter çiftMi liste // List.filter 'boolean bir fonksiyon' ve + // 'üzerinde çalışılacak bir liste' parametrelerinden oluşan + // bir kütüphane fonksiyonu -evens birdenBese // Şimdi fonksiyonu uygula. +çiftler birdenBeşe // Şimdi fonksiyonu uygula. -// Parantezleri önceliği netleştirmek için kullanabilirsin. Bu örnekte -// "map"i önce iki argümanla uygula, sonra sonuç üzerinde "ekle" uygula. -// Parantezler olmasaydı, "List.map" List.ekle'ın ilk argümanı olurdu. -let yuzeKadarKarelerinToplami = - List.ekle ( List.map kare [1..100] ) +// Parantezleri önceliği netleştirmek için kullanabilirsiniz. Bu örnek +// "map"i önce iki argümana, sonra sonuç üzerinde "ekle" uyguluyor. +// Parantezler olmasaydı, "List.map" List.sum'ın ilk argümanı olurdu. +let yüzeKadarKarelerinToplamı = + List.sum ( List.map kare [1..100] ) // Bir operasyonun sonucunu bir sonrakine "|>" kullanarak besleyebilirsin. // Veri beslemek F#'ta UNIX'te olduğu gibi yaygındır.. -// Burada karelerToplami fonksiyonunun veri beslemeyle yazılmış hali var: -let veriBeslemeyleYuzeKadarKarelerinToplami = - [1..100] |> List.map kare |> List.ekle // "kare" önceden tanımlanmıştı +// Burada yüzeKadarKarelerinToplamı fonksiyonunun veri beslemeyle yazılmış hali var: +let veriBeslemeyleYüzeKadarKarelerinToplamı = + [1..100] |> List.map kare |> List.sum // "kare" önceden tanımlanmıştı // Lambda'ları (anonim fonksiyonları) "fun" anahtar kelimesiyle tanımlayabilirsin -let funlaYuzeKadarKarelerinToplami = - [1..100] |> List.map (fun x -> x * x) |> List.ekle +let funlaYüzeKadarKarelerinToplamı = + [1..100] |> List.map (fun x -> x * x) |> List.sum // F#'ta "return" anahtar kelimesi yoktur. Bir fonksiyon // her zaman son kullanılan ifadeyi döndürür. // ------ Kalıp eşleştirme ------ // Match..with.. çok güçlü bir case/switch türevidir. -let basitKalipEslestirme = +let basitKalıpEşleştirme = let x = "a" match x with | "a" -> printfn "x a'dır" @@ -93,24 +93,24 @@ let basitKalipEslestirme = // F# varsayılan olarak null'lara izin vermez -- Option tipini kullanıp // kalıp eşleştirme yapmalısın. // Some(..) ve None, Nullable tipler gibidir. -let gecerliDeger = Some(99) -let gecersizDeger = None +let geçerliDeğer = Some(99) +let geçersizDeğer = None // Bu örnekte, match..with "Some" ve "None"la eşleştirme yapıyor, // ve ayrıca "Some" içerisindeki değeri de çıkarıyor. -let optionKalipEslestirme input = +let optionKalıpEşleştirme input = match input with | Some i -> printfn "input is an int=%d" i | None -> printfn "input is missing" -optionKalipEslestirme gecerliDeger -optionKalipEslestirme gecersizDeger +optionKalıpEşleştirme geçerliDeğer +optionKalıpEşleştirme geçersizDeğer // ------ Yazdırma ------ // printf/printfn fonksiyonları C#'taki // Console.Write/WriteLine fonksiyonlarına benzer. -printfn "Bir int %i, bir ondalık %f, bir boolean %b yazdırma" 1 2.0 true -printfn "Bir string %s, ve jenerik bir tip %A" "hello" [1; 2; 3; 4] +printfn "Bir tamsayı %i, bir ondalık %f, bir boolean %b yazdırma" 1 2.0 true +printfn "Bir string %s, ve jenerik bir tip %A" "merhaba" [1; 2; 3; 4] // sprintf/sprintfn fonksiyonları ise veriyi string'e // çevirmek içindir, C#'taki String.Format gibi. @@ -135,23 +135,23 @@ module FonksiyonOrnekleri = printfn "1 + 2 = %i" a // Parametreleri kaynaklamak için parçalı uygulama - let kirkIkiEkle = topla 42 - let b = kirkIkiEkle 1 + let kırkİkiEkle = topla 42 + let b = kırkİkiEkle 1 printfn "42 + 1 = %i" b // Fonksiyonları birleştirmek için kompozisyon let birEkle = topla 1 let ikiEkle = topla 2 - let ucEkle = birEkle >> ikiEkle - let c = ucEkle 7 + let üçEkle = birEkle >> ikiEkle + let c = üçEkle 7 printfn "3 + 7 = %i" c // Yüksek dereceli fonksiyonlar - [1..10] |> List.map ucEkle |> printfn "yeni liste: %A" + [1..10] |> List.map üçEkle |> printfn "yeni liste: %A" // Fonksiyonlar listesi ve dahası - let altiEkle = [birEkle; ikiEkle; ucEkle] |> List.reduce (>>) - let d = altiEkle 7 + let altıEkle = [birEkle; ikiEkle; üçEkle] |> List.reduce (>>) + let d = altıEkle 7 printfn "1 + 2 + 3 + 7 = %i" d // ================================================ @@ -166,7 +166,7 @@ module FonksiyonOrnekleri = // Değiştirilmez map'ler ve kümeler ve bütün .NET kolleksiyonları // diğer kolleksiyon türleridir. -module ListExamples = +module ListeÖrnekleri = // listeler köşeli parantez kullanır let liste1 = ["a"; "b"] @@ -184,17 +184,17 @@ module ListExamples = printfn "%A" asallar // Listelerle kalıp eşleştirme - let listMatcher liste = + let listeEşleyici liste = match liste with | [] -> printfn "liste boş" | [birinci] -> printfn "listede sadece bir eleman var: %A " birinci | [birinci; ikinci] -> printfn "liste: %A ve %A" birinci ikinci | _ -> printfn "listede ikiden fazla eleman var" - listMatcher [1; 2; 3; 4] - listMatcher [1; 2] - listMatcher [1] - listMatcher [] + listeEşleyici [1; 2; 3; 4] + listeEşleyici [1; 2] + listeEşleyici [1] + listeEşleyici [] // Listeleri kullanarak recursion let rec ekle liste = @@ -208,30 +208,30 @@ module ListExamples = // ----------------------------------------- // map - let ucEkle x = x + 3 - [1..10] |> List.map ucEkle + let üçEkle x = x + 3 + [1..10] |> List.map üçEkle // filter - let cift x = x % 2 = 0 - [1..10] |> List.filter cift + let çift x = x % 2 = 0 + [1..10] |> List.filter çift // ve dahası -- dökümantasyona bakınız -module DiziOrnekleri = +module DiziÖrnekleri = // Diziler köşeli parantezle birlikte çubuk karakterini kullanır let dizi1 = [| "a"; "b" |] let birinci = dizi1.[0] // nokta kullanarak indeks erişimi // Diziler için kalıp eşleştirme listlerle aynıdır - let diziEslestirici liste = + let diziEşleştirici liste = match liste with | [| |] -> printfn "dizi boş" | [| birinci |] -> printfn "dizide sadece bir eleman var: %A " birinci | [| birinci; ikinci |] -> printfn "dizi: %A ve %A" birinci ikinci | _ -> printfn "dizide ikiden fazla eleman var" - diziEslestirici [| 1; 2; 3; 4 |] + diziEşleştirici [| 1; 2; 3; 4 |] // Listede olduğu gibi kütüphane fonksiyonları @@ -241,7 +241,7 @@ module DiziOrnekleri = |> Array.iter (printfn "değer: %i. ") -module SeriOrnekleri = +module SeriÖrnekleri = // seriler kıvrık parantez kullanır let seri1 = seq { yield "a"; yield "b" } @@ -275,38 +275,38 @@ module SeriOrnekleri = // Veri Tipleri // ================================================ -module VeriTipiOrnekleri = +module VeriTipiÖrnekleri = // Bütün veriler varsayılan olarak değiştirilemezdir. + // -- Tuple oluşturmak için virgül kullan + let ikiliTuple = 1, 2 + let üçlüTuple = "a", 2, true + // Tuple'lar çabuk ve kolay anonim tiplerdir. // paketi açmak için kalıp eşleştirme kullan let x, y = ikiliTuple // x = 1, y = 2 - // -- Tuple oluşturmak için virgül kullan - let ikiliTuple = 1, 2 - let ucluTuple = "a", 2, true - // ------------------------------------ // Record tipi isimlendirilmiş alanlara sahiptir // ------------------------------------ // "type" ile kıvrık parantezleri record tipi oluşturmak için kullan - type Kisi = {birinci:string; Last:string} + type Kişi = {Ad:string; Soyad:string} // "let" ile kıvrık parantezi record tipi oluşturmak için kullan - let kisi1 = {birinci="John"; Last="Doe"} + let kişi1 = {Ad="Falanca"; Soyad="Kişi"} // paketi açmak için kalıp eşleştirme kullan - let {birinci = birinci} = kisi1 // birinci="John" + let {Ad = Ad} = kişi1 // birinci="John" // ------------------------------------ // Union tipleri (değişkenler olarak da bilinir) birden fazla - // seçeneğe sahiptir. Belli bir zamanda sadece bir tanesi geçerlidir. + // seçeneğe sahiptir. Belli bir zamanda sadece bir tanesi geçerlidir. // ------------------------------------ // "type" ile çubuk karakterini union tipi tanımlamak için kullan - type Derece = + type Sıcaklık = | Santigrat of float | Fahrenhayt of float @@ -315,25 +315,25 @@ module VeriTipiOrnekleri = let derece2 = Santigrat 37.0 // Paketi açmak için bütün seçenekler üzerinde kalıp eşleştirme kullan - let dereceYazdir = function + let dereceYazdır = function | Santigrat t -> printfn "%f C" t | Fahrenhayt t -> printfn "%f F" t - dereceYazdir derece1 - dereceYazdir derece2 + dereceYazdır derece1 + dereceYazdır derece2 // ------------------------------------ // Yinelgen (Recursive) tipler // ------------------------------------ - // Tipler alt sınıflar oluşturmadan karmaşık şekillerde - // yinelgen olarak birleştirilebilirler. - type Calisan = - | Isci of Kisi - | Yonetici of Calisan liste + // Tipler alt sınıflar oluşturmadan karmaşık şekillerde + // yinelgen olarak birleştirilebilirler. + type Çalışan = + | İşçi of Kişi + | Yönetici of Çalışan list - let falancaKisi = {birinci="John"; Last="Doe"} - let isci = Isci falancaKisi + let falancaKişi = {Ad="Falanca"; Soyad="Kişi"} + let işçi = İşçi falancaKişi // ------------------------------------ // Tipleri Kullanarak Modelleme @@ -341,54 +341,54 @@ module VeriTipiOrnekleri = // Union tipleri bayrak kullanmadan durum modelleme için harikadır. type EpostaAdresi = - | GecerliEpostaAdresi of string - | GecersizEpostaAdresi of string + | GeçerliEpostaAdresi of string + | GeçersizEpostaAdresi of string - let epostaGondermeyiDene eposta = - match eposta with // kalıp eşleştirme kullan - | GecerliEpostaAdresi adres -> () // gönder - | GecersizEpostaAdresi adres -> () // gönderme + let epostaGöndermeyiDene eposta = + match eposta with // kalıp eşleştirme kullan + | GeçerliEpostaAdresi adres -> () // gönder + | GeçersizEpostaAdresi adres -> () // gönderme - // Union tiplerin record tiplerle birleşimi - // domain driven design için iyi bir temel oluşturur. + // Union tiplerin record tiplerle birleşimi + // domain driven design için iyi bir temel oluşturur. // Domain'i yansıtan yüzlerce ufak tip oluşturabilirsiniz. - type Urun = { UrunKodu: string; Miktar: int } - type Odeme = Odeme of float - type AktifSepetVerisi = { OdenmemisUrunler: Urun liste } - type OndenmisSepetVerisi = { OdenmisUrunler: Urun liste; Odeme: Odeme} + type Ürün = { ÜrünKodu: string; Miktar: int } + type Ödeme = Ödeme of float + type AktifSepetVerisi = { ÖdenmemişÜrünler: Ürün list } + type ÖdenmişSepetVerisi = { ÖdenmişÜrünler: Ürün list; Ödeme: Ödeme} - type AlisverisSepeti = + type AlışverişSepeti = | BosSepet // veri yok | AktifSepet of AktifSepetVerisi - | OdenmisSepet of OndenmisSepetVerisi + | ÖdenmişSepet of ÖdenmişSepetVerisi // ------------------------------------ // Tipler için içgüdüsel davranış // ------------------------------------ // Çekirdek tipler kendinden çok kullanışlı özelliklere sahiptir - // Ek kodlama gerektirmez + // Ek kodlama gerektirmez // * Değişmezlik // * Debug ederken yazdırma // * Eşitlik ve kıyaslama // * Serialization // %A kullanarak yazdırma - printfn "ikiliTuple=%A,\nKisi=%A,\nDerece=%A,\nCalisan=%A" - ikiliTuple kisi1 derece1 isci + printfn "ikiliTuple=%A,\nKişi=%A,\Sıcaklık=%A,\nÇalışan=%A" + ikiliTuple kişi1 derece1 işçi // Eşitlik ve kıyaslama içgüdüseldir. // İskambil kartlarıyla bir örnek - type Simge = Sinek | Karo | Maca | Kupa - type Sira = Iki | Uc | Dort | Bes | Alti | Yedi | Sekiz - | Dokuz | On | Bacak | Kiz | Papaz | As + type Simge = Sinek | Karo | Maça | Kupa + type Sıra = İki | Üç | Dört | Beş | Altı | Yedi | Sekiz + | Dokuz | On | Bacak | Kız | Papaz | As - let el = [ Sinek, As; Kupa, Uc; Kupa, As; - Maca, Bacak; Karo, Iki; Karo, As ] + let el = [ Sinek, As; Kupa, Üç; Kupa, As; + Maça, Bacak; Karo, İki; Karo, As ] // Sıralama - List.sirala el |> printfn "artarak dizilen el: %A" + List.sort el |> printfn "artarak dizilen el: %A" List.max el |> printfn "en yüksek kart: %A" List.min el |> printfn "en düşük kart: %A" @@ -397,7 +397,7 @@ module VeriTipiOrnekleri = // Aktif Kalıplar // ================================================ -module AktifKalipOrnekleri = +module AktifKalıpÖrnekleri = // F# "aktif kalıplar" denen bir kalıp eşleştirmeye sahiptir. // Kalıplar dinamik bir şekilde tespit edilip eşleştirilebilir. @@ -405,38 +405,38 @@ module AktifKalipOrnekleri = // Aktif kalıplar için söz dizimi (| ... |) şeklindedir // Örneğin, karakter tiplerini eşleyen bir "aktif" kalıp tanımlayın... - let (|Rakam|Harf|Bosluk|Diger|) karakter = + let (|Rakam|Harf|Boşluk|Diğer|) karakter = if System.Char.IsDigit(karakter) then Rakam else if System.Char.IsLetter(karakter) then Harf - else if System.Char.IsWhiteSpace(karakter) then Bosluk - else Diger + else if System.Char.IsWhiteSpace(karakter) then Boşluk + else Diğer // ... daha sonra eşleme mantığı çok daha net yapmak için bunu kullanın - let karakterYazdir karakter = + let karakterYazdır karakter = match karakter with | Rakam -> printfn "%c bir rakamdır" karakter | Harf -> printfn "%c bir harftir" karakter - | Bosluk -> printfn "%c bir boşluktur" karakter + | Boşluk -> printfn "%c bir boşluktur" karakter | _ -> printfn "%c başka bir şeydir" karakter // Bir liste yazdırma - ['a'; 'b'; '1'; ' '; '-'; 'c'] |> List.iter karakterYazdir + ['a'; 'b'; '1'; ' '; '-'; 'c'] |> List.iter karakterYazdır // ----------------------------------- // Aktif Kalıpları Kullanarak FizzBuzz // ----------------------------------- - // Parçalı eşleşen kalıplar da oluşturabilirsiniz + // Parçalı eşleşen kalıplar da oluşturabilirsiniz // Tanımda alt çizgi karakterini kullanın ve eşleşince Some döndürün. - let (|UcunKati|_|) i = if i % 3 = 0 then Some UcunKati else None - let (|BesinKati|_|) i = if i % 5 = 0 then Some BesinKati else None + let (|ÜçünKatı|_|) i = if i % 3 = 0 then Some ÜçünKatı else None + let (|BeşinKatı|_|) i = if i % 5 = 0 then Some BeşinKatı else None // Ana fonksiyon let fizzBuzz i = match i with - | UcunKati & BesinKati -> printf "FizzBuzz, " - | UcunKati -> printf "Fizz, " - | BesinKati -> printf "Buzz, " + | ÜçünKatı & BeşinKatı -> printf "FizzBuzz, " + | ÜçünKatı -> printf "Fizz, " + | BeşinKatı -> printf "Buzz, " | _ -> printf "%i, " i // test @@ -446,50 +446,50 @@ module AktifKalipOrnekleri = // Sadelik // ================================================ -module AlgoritmaOrnekleri = +module AlgoritmaÖrnekleri = // F#'ın sinyal/gürültü oranı yüksektir, dolayısıyla // kod algoritmayla hemen hemen aynı görünür. // ------ Örnek: karelerToplami fonksiyonunu tanımla ------ - let karelerToplami n = - [1..n] // 1) 1'den n'e kadar bütün sayıları al - |> List.map kare // 2) hepsinin karesini al - |> List.ekle // 3) sonuçları topla + let karelerToplamı n = + [1..n] // 1) 1'den n'e kadar bütün sayıları al + |> List.map kare // 2) hepsinin karesini al + |> List.sum // 3) sonuçları topla // test - karelerToplami 100 |> printfn "kareler toplamı = %A" + karelerToplamı 100 |> printfn "kareler toplamı = %A" // ------ Örnek: bir sıralama fonksiyonu tanımla ------ - let rec sirala liste = + let rec sırala liste = match liste with // Liste boşsa | [] -> - [] // boş listeyi döndür + [] // boş listeyi döndür // Liste boş değilse - | ilkEleman::digerElemanlar -> // İlk elemanı al - let kucukElemanlar = // Daha küçük elemanları - digerElemanlar // diğerlerinden ayır + | ilkEleman::diğerElemanlar -> // İlk elemanı al + let küçükElemanlar = // Daha küçük elemanları + diğerElemanlar // diğerlerinden ayır |> List.filter (fun e -> e < ilkEleman) - |> sirala // ve sırala - let buyukElemanlar = // Daha büyük elemanları - digerElemanlar // diğerlerinden ayır + |> sırala // ve sırala + let büyükElemanlar = // Daha büyük elemanları + diğerElemanlar // diğerlerinden ayır |> List.filter (fun e -> e >= ilkEleman) - |> sirala // ve sırala + |> sırala // ve sırala // 3 parçayı birbirine ekle ve listeyi döndür - List.concat [kucukElemanlar; [ilkEleman]; buyukElemanlar] + List.concat [küçükElemanlar; [ilkEleman]; büyükElemanlar] // test - sirala [1; 5; 23; 18; 9; 1; 3] |> printfn "Sırala = %A" + sırala [1; 5; 23; 18; 9; 1; 3] |> printfn "Sırala = %A" // ================================================ // Eşzamansız kod // ================================================ -module EszamansizOrnegi = +module EşzamansızÖrneği = // F# "pyramid of doom" durumuyla karşılaştırmayacak şekilde - // içgüdüsel eşzamansız özelliklere sahiptir. + // içgüdüsel eşzamansız özelliklere sahiptir. // // Bir sonraki örnek bir web sayfasını paralel bir şekilde indirir. @@ -499,16 +499,16 @@ module EszamansizOrnegi = open Microsoft.FSharp.Control.CommonExtensions // İçeriği eşzamansız bir şekilde getir - let eszamansizUrlGetir url = + let eşzamansızUrlGetir url = async { // "async" anahtar kelimesi ve kıvrık parantez // "async (eşzamansız)" nesneyi oluşturur let istek = WebRequest.Create(Uri(url)) use! cevap = istek.AsyncGetResponse() // use! eşzamansız atamadır - use akis = cevap.GetResponseStream() + use akış = cevap.GetResponseStream() // "use" kullanılan bloğun dışına çıkınca // close()'u otomatik olarak tetikler - use okuyucu = new IO.StreamReader(akis) + use okuyucu = new IO.StreamReader(akış) let html = okuyucu.ReadToEnd() printfn "İndirme tamamlandı: %s" url } @@ -522,76 +522,76 @@ module EszamansizOrnegi = // İndir siteler - |> List.map eszamansizUrlGetir // eşzamansız görevlerden oluşan bir liste yap - |> Async.Parallel // bu görevleri paralel çalışacak şekilde ayarla - |> Async.RunSynchronously // başlat + |> List.map eşzamansızUrlGetir // eşzamansız görevlerden oluşan bir liste yap + |> Async.Parallel // bu görevleri paralel çalışacak şekilde ayarla + |> Async.RunSynchronously // başlat // ================================================ // .NET uyumluluğu // ================================================ -module NetUyumlulukOrnekleri = +module NetUyumlulukÖrnekleri = // F#, C#'ın yapabildiği hemen herşeyi yapabilir, // ve .NET ve Mono kütüphaneleriyle tereyağından kıl çeker gibi çalışır. // ------- var olan kütüphane fonksiyonları ile çalışma ------- - let (i1success, i1) = System.Int32.TryParse("123"); - if i1success then printfn "parsed as %i" i1 else printfn "parse failed" + let (i1başarılı, i1) = System.Int32.TryParse("123"); + if i1başarılı then printfn "%i olarak dönüştürüldü" i1 else printfn "dönüştürme başarısız" - // ------- Arayüzleri yol üstünde tanımla! ------- + // ------- Arayüzleri yol üstünde tanımlayın! ------- // IDisposable'ı sağlayan yeni bir nesne oluştur - let makeResource name = + let kaynakOluştur isim = { new System.IDisposable - with member this.Dispose() = printfn "%s disposed" name } + with member this.Dispose() = printfn "%s atıldı" isim } - let useAndDisposeResources = - use r1 = makeResource "birinci resource" - printfn "using birinci resource" + let kaynakKullanVeAt = + use r1 = kaynakOluştur "birinci kaynak" + printfn "birinci kaynağı kullanıyor" for i in [1..3] do - let resourceName = sprintf "\tinner resource %d" i - use temp = makeResource resourceName - printfn "\tdo something with %s" resourceName - use r2 = makeResource "ikinci resource" - printfn "using ikinci resource" - printfn "done." + let kaynakİsmi = sprintf "\tiç kaynak %d" i + use geçici = kaynakOluştur kaynakİsmi + printfn "\t%s ile bir şey yap" kaynakİsmi + use r2 = kaynakOluştur "ikinci kaynak" + printfn "ikinci kaynağı kullanıyor" + printfn "bitti." // ------- Nesne yönelimli kod ------- // F# aynı zamanda tam bir nesne yönelimli dildir. // Sınıfları, kalıtımı ve sanal metotları destekler. - // Genel ipli bir arayüz + // Genel tipli bir arayüz type IEnumerator<'a> = - abstract member Current : 'a - abstract MoveNext : unit -> bool + abstract member Şimdiki : 'a + abstract SonrakineGeç : unit -> bool // Sanal metotları olan soyut temel sınıflar [] - type Shape() = + type Şekil() = // sadece okunabilir özellikler - abstract member Width : int with get - abstract member Height : int with get + abstract member Genişlik : int with get + abstract member Yükseklik : int with get // sanal olmayan metot - member this.BoundingArea = this.Height * this.Width + member this.ÇevreleyenAlan = this.Yükseklik * this.Genişlik // temel uygulamasıyla bir sanal metot - abstract member Print : unit -> unit - default this.Print () = printfn "I'm a shape" + abstract member Yazdır : unit -> unit + default this.Yazdır () = printfn "Ben bir şekil (önümden çekil!)" // Somut bir sınıfın soyut sınıftan kalıtımı - type Rectangle(x:int, y:int) = - inherit Shape() - override this.Width = x - override this.Height = y - override this.Print () = printfn "I'm a Rectangle" + type Dikdörtgen(x:int, y:int) = + inherit Şekil() + override this.Genişlik = x + override this.Yükseklik = y + override this.Yazdır () = printfn "Ben bir dikdörtgenim" // test - let r = Rectangle(2, 3) - printfn "The width is %i" r.Width - printfn "The area is %i" r.BoundingArea - r.Print() + let r = Dikdörtgen(2, 3) + printfn "Genişlik: %i" r.Genişlik + printfn "Çevreleyen Alan: %i" r.ÇevreleyenAlan + r.Yazdır() // ------- ekleme metotları ------- @@ -600,26 +600,26 @@ module NetUyumlulukOrnekleri = member this.StartsWithA = this.StartsWith "A" // test - let s = "Alice" - printfn "'%s' starts with an 'A' = %A" s s.StartsWithA + let s = "Ahmet" + printfn "'%s' 'A' ile başlar = %A" s s.StartsWithA // ------- olaylar ------- - type MyButton() = - let clickEvent = new Event<_>() + type Butonum() = + let tıklamaOlayı = new Event<_>() [] - member this.OnClick = clickEvent.Publish + member this.OnClick = tıklamaOlayı.Publish - member this.TestEvent(arg) = - clickEvent.Trigger(this, arg) + member this.DenemeOlayı(arg) = + tıklamaOlayı.Trigger(this, arg) // test - let myButton = new MyButton() - myButton.OnClick.topla(fun (sender, arg) -> - printfn "Click event with arg=%O" arg) + let butonum = new Butonum() + butonum.OnClick.Add(fun (sender, arg) -> + printfn "arg=%O ile beraber bir tıklama olayı" arg) - myButton.TestEvent("Hello World!") + butonum.DenemeOlayı("Merhaba Dünya!") ``` -- cgit v1.2.3 From 02fb96d6998df7f5ecfc3b546d323547c135584e Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Mon, 25 Apr 2016 22:51:05 -0700 Subject: Update fsharp-tr.html.markdown --- tr-tr/fsharp-tr.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/tr-tr/fsharp-tr.html.markdown b/tr-tr/fsharp-tr.html.markdown index d88e2594..8c47397c 100644 --- a/tr-tr/fsharp-tr.html.markdown +++ b/tr-tr/fsharp-tr.html.markdown @@ -5,6 +5,7 @@ contributors: translators: - ["Mustafa Zengin", "http://zengin.github.com/"] filename: learnfsharp-tr.fs +lang: tr-tr --- F# fonksiyonel ve nesne yönelimli, genel amaçlı bir programlama dilidir. Bedava ve açık kaynaklıdır ve Linux, Mac, Windows ve dahasında çalışır. -- cgit v1.2.3 From 2e6c386e9b1e742ac015ab424b3cf0f456c8d550 Mon Sep 17 00:00:00 2001 From: Mustafa Zengin Date: Wed, 27 Apr 2016 23:56:57 -0700 Subject: TypeScript Turkish translation (#2246) --- tr-tr/typescript-tr.html.markdown | 180 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100644 tr-tr/typescript-tr.html.markdown diff --git a/tr-tr/typescript-tr.html.markdown b/tr-tr/typescript-tr.html.markdown new file mode 100644 index 00000000..1bf674c6 --- /dev/null +++ b/tr-tr/typescript-tr.html.markdown @@ -0,0 +1,180 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: + - ["Mustafa Zengin", "http://zengin.github.com"] +filename: learntypescript-tr.ts +lang: tr-tr +--- + +TypeScript, JavaScript'le yazılmış büyük ölçekli uygulamaların geliştirilmesini kolaylaştırmayı hedefleyen bir dildir. +TypeScript, JavaScript'e sınıflar, modüller, arayüzler, jenerik tipler ve (isteğe bağlı) static tipleme gibi genel konseptler ekler. +JavaScript, TypeScript'in bir alt kümesidir: Bütün JavaScript kodları geçerli birer TypeScript kodudur ve sorunsuz herhangi bir projeye eklenebilirler. TypeScript derleyici JavaScript kodu üretir. + +Bu makale sadece TypeScript'e ait ekstra söz dizimini konu alır, JavaScript için bkz: [JavaScript] (../javascript/). + +TypeScript derleyiciyi test etmek için [Playground] (http://www.typescriptlang.org/Playground)'a gidin. Orada otomatik tamamlama ile kod yazabilecek ve üretilen JavaScript'i görebileceksiniz. + +```js +// TypeScript'te üç ana tip vardır. +var bittiMi: boolean = false; +var satırlar: number = 42; +var isim: string = "Anders"; + +// Tipin bilinmediği zamanlar için "Any" tipi +var bilinmiyor: any = 4; +bilinmiyor = "belki de bir string'dir"; +bilinmiyor = false; // tamam, boolean olsun + +// Kolleksiyon olarak, tipli ve jenerik diziler +var liste: number[] = [1, 2, 3]; +// Alternatif olarak jenerik Array tipi +var liste: Array = [1, 2, 3]; + +// 'enum' tipleri: +enum Renk {Kırmızı, Yeşil, Mavi}; +var r: Renk = Renk.Yeşil; + +// Son olarak, "void" hiç bir şey döndürmeyen fonksiyonlarda kullanılan tiptir. +function çokFeciBirUyarı(): void { + alert("Ben biraz sinir bozucuyum!"); +} + +// Fonksiyonlar birinci sınıf vatandaşlardır ve "kalın ok" lambda söz dizimi "=>" +// ve tip çıkarımı kullanırlar. +// Aşağıda listelenenler birbirinin aynısı ve derleyici aynı fonksiyon yapısını +// çıkaracak ve aynı JavaScript kodunu üretecektir +var f1 = function(i: number): number { return i * i; } +// Döndürülen tip tip çıkarımıyla belirlendi +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +// Döndürülen tip tip çıkarımıyla belirlendi +var f4 = (i: number) => { return i * i; } +// Döndürülen tip tip çıkarımıyla belirlendi +// Tek satırlık yazımda "return" anahtar kelimesine ihtiyaç yok. +var f5 = (i: number) => i * i; + +// Arayüzler yapısaldır, listelenen özelliklere sahip her şey arayüzle uyumludur. +interface Kişi { + isim: string; + // İsteğe bağlı özellikler "?" ile işaretlenir + yaş?: number; + // Ve fonksiyonlar... + hareketEt(): void; +} + +// "Kişi" arayüzünü kullanan bir nesne +// isim ve hareketEt özelliklerine sahip olduğu için Kişi olarak kullanılabilir. +var p: Kişi = { isim: "Anders", hareketEt: () => {} }; +// İsteğe bağlı özelliğe sahip bir Kişi +var geçerliKişi: Kişi = { isim: "Anders", yaş: 42, hareketEt: () => {} }; +// Geçersiz bir kişi, çünkü yaş bir sayı (number) tipi değil +var geçersizKişi: Kişi = { isim: "Anders", yaş: true }; + +// Arayüzler bir fonksiyon tipi de ifade edebilirler +interface aramaFonksiyonu { + (kaynak: string, altString: string): boolean; +} + +// Parametrelerin sadece tipleri önemli, isimleri önemli değil +var benimAramam: aramaFonksiyonu; +benimAramam = function(kynk: string, alt: string) { + return kynk.search(alt) != -1; +} + +// Sınıflar - üyeler (members) varsayılan olarak public'tir. +class Nokta { + // Özellikler + x: number; + + // Yapıcı (constructor) - bu bağlamdaki public/private anahtar kelimeleri + // özellikler için gerekli demirbaş kodu oluşturur ve ilk değerlerin + // atanmasını sağlar. + // Bu örnekte, "y" de "x" gibi tanımlanacak is, but with less code + // Default values are also supported + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Fonksiyonlar + mesafe() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Statik üyeler + static orijin = new Nokta(0, 0); +} + +var p1 = new Nokta(10 ,20); +var p2 = new Nokta(25); //y = 0 + +// Kalıtım +class Nokta3Boyutlu extends Nokta { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // süper sınıfın yapıcısını çağırmak zorunlu + } + + // yeniden tanımlama + mesafe() { + var d = super.mesafe(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Modüller, "." alt modülleri ayırmak için kullanılabilir +module Geometri { + export class Kare { + constructor(public kenarUzunluğu: number = 0) { + } + alan() { + return Math.pow(this.kenarUzunluğu, 2); + } + } +} + +var s1 = new Geometri.Kare(5); + +// Modüle atıfta bulunmak için yerel takma ad +import G = Geometri; + +var s2 = new G.Kare(10); + +// Jenerik Tipler +// Sınıflar +class Tuple { + constructor(public item1: T1, public item2: T2) { + } +} + +// Arayüzler +interface Çift { + item1: T; + item2: T; +} + +// Ve fonksiyonlar +var çifttenTupleÜret = function(p: Çift) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = çifttenTupleÜret({ item1:"merhaba", item2:"dünya"}); + +// Tanım dosyasına atıfta bulunma: +/// + +// Şablon Stringleri (ters apostrof kullanan stringler) +// Şablon Stringlerinin kullanımı +var isim = 'Anders'; +var selamlama = `Merhaba ${isim}, nasılsın?` +// Şablon Stringleri ile çok satırlı stringler +var çokSatırlıString = `Bu çok satırlı +bir string örneği`; + +``` + +## Daha fazlası + * [TypeScript Resmi Sitesi] (http://www.typescriptlang.org/) + * [TypeScript dil spesifikasyonu (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Channel 9'da TypeScript'e Giriş] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [GitHub'ta Açık Kaynak Kodu] (https://github.com/Microsoft/TypeScript) + * [Definitely Typed - tip tanımları için kaynak] (http://definitelytyped.org/) -- cgit v1.2.3 From 05af2a80642f7fc68ac828d0f3a92b2799e641dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gerson=20L=C3=A1zaro?= Date: Thu, 28 Apr 2016 01:58:03 -0500 Subject: [asymptotic-notation/es] es-es translation for asymptotic-notation (#1345) * Translation started[es-es]: asymptotic notation * Completed: asymptotic-notation-es * final correction --- es-es/asymptotic-notation-es.html.markdown | 170 +++++++++++++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 es-es/asymptotic-notation-es.html.markdown diff --git a/es-es/asymptotic-notation-es.html.markdown b/es-es/asymptotic-notation-es.html.markdown new file mode 100644 index 00000000..f3fe1614 --- /dev/null +++ b/es-es/asymptotic-notation-es.html.markdown @@ -0,0 +1,170 @@ +--- +category: Algorithms & Data Structures +name: Asymptotic Notation +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] +translators: + - ["Gerson Lázaro", "https://gersonlazaro.com"] +lang: es-es +--- + +# Notaciones asintóticas + +## ¿Qué son? + +Las notaciones asintóticas son lenguajes que nos permitan analizar el tiempo de +ejecución de un algoritmo identificando su comportamiento si el tamaño de +entrada para el algoritmo aumenta. Esto también se conoce como la tasa de +crecimiento de un algoritmo. ¿El algoritmo de repente se vuelve increíblemente +lento cuando el tamaño de entrada crece? ¿Tiende a mantener un rápido tiempo de +ejecución a medida que el tamaño de entrada aumenta? La notación asintótica nos +da la capacidad para responder a estas preguntas. + +## ¿Hay alternativas que respondan a estas preguntas? + +Una manera sería contar el número de operaciones primitivas en diferentes +tamaños de entrada. Aunque esta es una solución válida, la cantidad de trabajo +que esto conlleva, incluso para los algoritmos simples, no justifica su uso. + +Otra manera es medir físicamente la cantidad de tiempo que un algoritmo toma +para completar su ejecución dados diferentes tamaños de entrada. Sin embargo, +la exactitud y la relatividad (los tiempos obtenidos sólo serían relativos a la +máquina sobre la cual se calcularon) de este método está ligado a variables +ambientales tales como especificaciones de hardware, capacidad de procesamiento, +etc. + +## Tipos de Notación Asintótica + +En la primera sección de este documento hemos descrito cómo una notación +asintótica identifica el comportamiento de un algoritmo ante los cambios en el +tamaño de la entrada. Imaginemos un algoritmo como una función f, con tamaño de +entrada n, y f(n) siendo el tiempo de ejecución. Así que para un algoritmo f +dado, con el tamaño de entrada n obtenemos algún tiempo de ejecución resultante +f(n). Esto resulta en un gráfico donde el eje Y es el tiempo de ejecución, el +eje X es el tamaño de la entrada y los puntos en el gráfico son los resultantes +de la cantidad de tiempo para un tamaño de entrada dado. + +Puedes etiquetar una función, o un algoritmo, con una notación asintótica de +muchas maneras diferentes. Algunos ejemplos son describir un algoritmo por su +mejor caso, su peor caso, o el caso promedio. Lo más común es analizar un +algoritmo por su peor caso. Por lo general, no se evalúa el mejor caso, porque +no planeas el algoritmo para estas condiciones. Un muy buen ejemplo de esto son +los algoritmos de ordenamiento; específicamente, añadir elementos a un árbol. +El mejor caso para la mayoría de los algoritmos podría ser tan bajo como una +sola operación. Sin embargo, en la mayoría de los casos, el elemento que está +añadiendo tendrá que ser ordenado adecuadamente a través del árbol, lo que +podría significar examinar toda una rama. Este es el peor de los casos, y +para estos casos es que planeamos el algoritmo. + + +### Tipos de funciones, límites, y simplificación + +``` +Función logarítmica - log n +Función lineal - an + b +Función cuadrática - an^2 + bn + c +Función polinomicas - an^z + . . . + an^2 + a*n^1 + a*n^0, donde z es constante +Función exponencial - a^n, donde a es constante +``` + +Estas son algunas clasificaciones de funciones de crecimiento básicos utilizados +en varias notaciones. La lista comienza en la función de crecimiento menor +(logarítmica, el tiempo de ejecución mas rápido) y pasa a la de mayor +crecimiento (exponencial, el tiempo de ejecución mas lento). Observe como al +crecer 'n', o la entrada, en cada una de estas funciones, el resultado aumenta +claramente mucho más rápido en las cuadráticas, polinómicas y exponenciales, +en comparación con las logarítmicas y lineales. + +Una anotación muy importante es que en las notaciones que se discutirán debes +hacer tu mejor esfuerzo por utilizar los términos más simples. Esto significa +hacer caso omiso de las constantes y terminos de orden inferior, porque a medida +que el tamaño de entrada (o n en f(n)) aumenta hacia el infinito (límites +matemáticos), los términos y constantes de orden inferior se vuelven de poca o +ninguna importancia. Dicho esto, si tienes constantes que son 2^9001, +o alguna otra cantidad ridícula, inimaginable, te daras cuenta de que la +simplificación sesgará la exactitud de la notación. + +Como queremos algo simplificado, vamos a modificarlo un poco... + +``` +Logarítmico - log n +Lineal - n +Cuandrático - n^2 +Polinómico - n^z, donde z es constante +Exponencial - a^n, donde a es constante +``` + +### O-grande (Big-O) +O-grande (Big-O), comúnmente escrito como O, es una notación asintótica para el +peor caso, o el techo de crecimiento para una función determinada. Si `f (n)` +es el tiempo de ejecución del algoritmo, y `g (n)` es un tiempo de complejidad +arbitraria que relacionas con el algoritmo, entonces `f (n)` es O(g(n)), si por +cualquier constante real c (c > 0), `f (n)` <= `c g(n)` para cada tamaño de +entrada n (n > 0 ). + + +*Ejemplo 1* + +``` +f(n) = 3log n + 100 +g(n) = log n +``` + +`f(n)` es O(g(n))? +`3 log n + 100` es O(log n)? +Echemos un vistazo a la definición de O-grande. + +``` +3log n + 100 <= c * log n +``` +¿Hay alguna constante c que satisface esto para todo n? + +``` +3log n + 100 <= 150 * log n, n > 2 (indefinido en n = 1) +``` + +¡Sí! La definición de O-grande se cumple, por lo tanto `f (n)` es O(g(n)). + +*Ejemplo 2* + +``` +f(n) = 3*n^2 +g(n) = n +``` + +`f(n)` es O(g(n))? +`3 * n^2` es O(n)? +Echemos un vistazo a la definición de O-grande. + +``` +3 * n^2 <= c * n +``` + +¿Hay alguna constante c que satisface esto para todo n? +No, no la hay. `f(n)` no es O(g(n)). + +### Big-Omega +Big-Omega, comunmente escrito como Ω, es una notación asintótica para el mejor +caso, o el piso en el crecimiento para una función dada. + +`f(n)` es Ω(g(n)), si para cualquier constante real c (c > 0), +`f(n)` es >= `c g(n)` para cualquier tamaño de entrada n (n > 0). + +No dudes en dirigirte a los recursos adicionales para ejemplos sobre esto. +O-grande es la notación principal utilizada para la complejidad general de +tiempo algoritmico. + +### Notas finales +Es difícil mantener este tipo de tema corto, y sin duda deberias revisar los +libros y recursos en línea en la lista. Entran en mucha mayor profundidad con +definiciones y ejemplos. + +## Libros + +* [Algoritmos (Algorithms)](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X) +* [Diseño de algoritmos (Algorithm Design)](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651) + +## Recursos Online + +* [MIT](http://web.mit.edu/16.070/www/lecture/big_o.pdf) +* [KhanAcademy](https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation) -- cgit v1.2.3 From 1607f05162da5fa0c19bebf79e9ffee197ee7761 Mon Sep 17 00:00:00 2001 From: Bruno Alano Date: Thu, 28 Apr 2016 04:00:16 -0300 Subject: Added Templates to C++ Tutorial (#1576) * Created a simple CMake tutorial * Added resources * Added Templates section to C++ tutorial --- cmake.html.markdown | 176 +++++++++++++++++++++++++++++++++++++++++++++ pt-br/c++-pt.html.markdown | 25 +++++++ 2 files changed, 201 insertions(+) create mode 100644 cmake.html.markdown diff --git a/cmake.html.markdown b/cmake.html.markdown new file mode 100644 index 00000000..e13e7f67 --- /dev/null +++ b/cmake.html.markdown @@ -0,0 +1,176 @@ +--- +language: cmake +contributors: + - ["Bruno Alano", "https://github.com/brunoalano"] +filename: CMake +--- + +CMake it's a cross-platform, open-source build system. This tool will allow you +to test, compile and create packages of your source code. + +The problem that CMake tries to solve it's the problem of Makefiles and +Autoconfigure on cross-platform (different make interpreters have different +command) and the ease-of-use on linking 3rd party libraries. + +CMake is an extensible, open-source system that manages the build process in +an operating system and in a compiler-independent manner. Unlike many +cross-platform systems, CMake is designed to be used in conjunction with the +native build environment. Simple configuration files placed in each source +directory (called CMakeLists.txt files) are used to generate standard build +files (e.g., makefiles on Unix and projects/workspaces in Windows MSVC) which +are used in the usual way. + +```cmake +# In CMake, this is a comment + +# To run our code, we will use these steps: +# - mkdir build && cd build +# - cmake .. +# - make +# +# With those steps, we will follow the best pratice to compile into a subdir +# and the second line will request to CMake to generate a new OS-dependant +# Makefile. Finally, run the native Make command. + +#------------------------------------------------------------------------------ +# Basic +#------------------------------------------------------------------------------ +# +# The CMake file MUST be named as "CMakeLists.txt". + +# Setup the minimum version required of CMake to generate the Makefile +cmake_minimum_required (VERSION 2.8) + +# Raises a FATAL_ERROR if version < 2.8 +cmake_minimum_required (VERSION 2.8 FATAL_ERROR) + +# We setup the name for our project. After we do that, this will change some +# directories naming convention genearted by CMake. We can send the LANG of +# code as second param +project (learncmake C) + +# Set the project source dir (just convention) +set( LEARN_CMAKE_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} ) +set( LEARN_CMAKE_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR} ) + +# It's useful to setup the current version of our code in the build system +# using a `semver` style +set (LEARN_CMAKE_VERSION_MAJOR 1) +set (LEARN_CMAKE_VERSION_MINOR 0) +set (LEARN_CMAKE_VERSION_PATCH 0) + +# Send the variables (version number) to source code header +configure_file ( + "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in" + "${PROJECT_BINARY_DIR}/TutorialConfig.h" +) + +# Include Directories +# In GCC, this will invoke the "-I" command +include_directories( include ) + +# Where are the additional libraries installed? Note: provide includes +# path here, subsequent checks will resolve everything else +set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMake/modules/" ) + +# Conditions +if ( CONDITION ) + # Output! + + # Incidental information + message(STATUS "My message") + + # CMake Warning, continue processing + message(WARNING "My message") + + # CMake Warning (dev), continue processing + message(AUTHOR_WARNING "My message") + + # CMake Error, continue processing, but skip generation + message(SEND_ERROR "My message") + + # CMake Error, stop processing and generation + message(FATAL_ERROR "My message") +endif() + +if( CONDITION ) + +elseif( CONDITION ) + +else( CONDITION ) + +endif( CONDITION ) + +# Loops +foreach(loop_var arg1 arg2 ...) + COMMAND1(ARGS ...) + COMMAND2(ARGS ...) + ... +endforeach(loop_var) + +foreach(loop_var RANGE total) +foreach(loop_var RANGE start stop [step]) + +foreach(loop_var IN [LISTS [list1 [...]]] + [ITEMS [item1 [...]]]) + +while(condition) + COMMAND1(ARGS ...) + COMMAND2(ARGS ...) + ... +endwhile(condition) + + +# Logic Operations +if(FALSE AND (FALSE OR TRUE)) + message("Don't display!") +endif() + +# Set a normal, cache, or environment variable to a given value. +# If the PARENT_SCOPE option is given the variable will be set in the scope +# above the current scope. +# `set( ... [PARENT_SCOPE])` + +# How to reference variables inside quoted and unquoted arguments +# A variable reference is replaced by the value of the variable, or by the +# empty string if the variable is not set +${variable_name} + +# Lists +# Setup the list of source files +set( LEARN_CMAKE_SOURCES + src/main.c + src/imagem.c + src/pather.c +) + +# Calls the compiler +# +# ${PROJECT_NAME} refers to Learn_CMake +add_executable( ${PROJECT_NAME} ${LEARN_CMAKE_SOURCES} ) + +# Link the libraries +target_link_libraries( ${PROJECT_NAME} ${LIBS} m ) + +# Where are the additional libraries installed? Note: provide includes +# path here, subsequent checks will resolve everything else +set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMake/modules/" ) + +# Compiler Condition (gcc ; g++) +if ( "${CMAKE_C_COMPILER_ID}" STREQUAL "GNU" ) + message( STATUS "Setting the flags for ${CMAKE_C_COMPILER_ID} compiler" ) + add_definitions( --std=c99 ) +endif() + +# Check for OS +if( UNIX ) + set( LEARN_CMAKE_DEFINITIONS + "${LEARN_CMAKE_DEFINITIONS} -Wall -Wextra -Werror -Wno-deprecated-declarations -Wno-unused-parameter -Wno-comment" ) +endif() +``` + +### More Resources + ++ [cmake tutorial](https://cmake.org/cmake-tutorial/) ++ [cmake documentation](https://cmake.org/documentation/) ++ [mastering cmake](http://amzn.com/1930934319/) diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown index 61e267f5..31a3110c 100644 --- a/pt-br/c++-pt.html.markdown +++ b/pt-br/c++-pt.html.markdown @@ -581,6 +581,31 @@ void doSomethingWithAFile(const std::string& filename) // vetor (i.e. array de autodimensionamento), mapas hash, e assim por diante // tudo é automaticamente destruído quando eles saem de escopo // - Mutex usa lock_guard e unique_lock + + +///////////////////// +// Templates +///////////////////// + +// Templates em C++ são utilizados para programação genérica, ou seja, +// utilizar um tipo de dado genérico onde possa suportar qualquer entrada. +// Por exemplo, invés de criar uma função que apenas some inteiros, você +// poderá fazer uma função que soma double, float e inteiros em uma única +// definição para reutilizar código. + +// Definimos um função que utiliza um "typename" +template +T soma(T a, T b) { + return A + B; +} + +// E agora para executá-la +int i=5, j=6, k; +double f=2.0, g=0.5, h; +k=sum(i,j); +h=sum(f,g); + +// Deste modo, não precisamos fazer overload nas funções! (: ``` Leitura Adicional: -- cgit v1.2.3 From 8256f12e4647fe9a4cb04aea49801b7b508322ca Mon Sep 17 00:00:00 2001 From: Damaso Sanoja Date: Thu, 28 Apr 2016 02:34:15 -0430 Subject: typescript spanish translation (#1749) --- es-es/typescript-es.html.markdown | 172 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 es-es/typescript-es.html.markdown diff --git a/es-es/typescript-es.html.markdown b/es-es/typescript-es.html.markdown new file mode 100644 index 00000000..c42da4a4 --- /dev/null +++ b/es-es/typescript-es.html.markdown @@ -0,0 +1,172 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +filename: learntypescript-es.ts +translators: + - ["Damaso Sanoja", "https://github.com/damasosanoja"] +lang: es-es +--- + +TypeScript es un lenguaje cuyo objetivo es facilitar el desarrollo de aplicaciones a gran escala escritas en JavaScript. +TypeScript añade conceptos comunes como clases, módulos, interfaces, genéricos y (opcionalmente) tipeo estático a JavaScript. +Es un superset de JavaScript: todo el código JavaScript es código válido en TypeScript de manera que se puede integrar fácilmente a cualquier proyecto . El compilador TypeScript emite JavaScript. + +Este artículo se enfocará solo en la sintáxis extra de TypeScript, y no en [JavaScript] (../javascript/). + +Para probar el compilador de TypeScript, diríjase al [Área de Pruebas] (http://www.typescriptlang.org/Playground) donde podrá tipear código, y ver como se auto-completa al tiempo que ve el código emitido JavaScript. + +```js +// Existen 3 tipos básicos en TypeScript +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Anders"; + +// Cuando es imposible de saber, tenemos el tipo "Any" +var notSure: any = 4; +notSure = "maybe a string instead"; +notSure = false; // okey, definitivamente un boolean + +// Para colecciones, hay matrices de tipos y matrices genéricas +var list: number[] = [1, 2, 3]; +// Alternativamente, usando la matriz genérica +var list: Array = [1, 2, 3]; + +// Para enumeradores: +enum Color {Red, Green, Blue}; +var c: Color = Color.Green; + +// Finalmente, "void" es usado para el caso especial de una función que no retorna nada +function bigHorribleAlert(): void { + alert("I'm a little annoying box!"); +} + +// Las funciones son ciudadanos de primera clase, soportan la sintáxis lambda "fat arrow" y +// usan el tipo inferencia + +// Lo siguiente es equivalante, la misma firma será inferida por el +// compilador, y el mismo JavaScript será emitido +var f1 = function(i: number): number { return i * i; } +// Retorna tipo inferido +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +// Retorna tipo inferido +var f4 = (i: number) => { return i * i; } +// Retorna tipo inferido, one-liner significa que no es necesario que regresen palabras claves +var f5 = (i: number) => i * i; + +// Las interfaces son estructurales, todo lo que tenga las propiedades cumple con +// la interfase +interface Person { + name: string; + // Propiedades opcionales, marcadas con un "?" + age?: number; + // Y por supuesto funciones + move(): void; +} + +// Objeto que implementa la interfase "Persona" +// Puede ser tratada como Persona ya que posee las propiedades name y move +var p: Persona = { name: "Bobby", move: () => {} }; +// Objetos que tienen propiedades opcionales: +var validPersona: Persona = { name: "Bobby", age: 42, move: () => {} }; +// No es una persona porque su edad no es un número +var invalidPersona: Persona = { name: "Bobby", age: true }; + +// Las interfases también pueden describir un tipo de función +interface SearchFunc { + (source: string, subString: string): boolean; +} +// Solo los tipos de parámetros son importantes, los nombres no son importantes. +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// Clases - los miembros son públicos por defecto +class Point { + // Properties + x: number; + + // Constructor - las palabras clave public/private en este contexto generarán + // un código boiler plate para la propiedad y la inicialización en el + // constructor. + // En este ejemplo, "y" debe ser definida al igual que "x" lo es, pero con menos código + // También son soportados valores por defecto + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Funciones + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Miembros estáticos + static origin = new Point(0, 0); +} + +var p1 = new Point(10 ,20); +var p2 = new Point(25); //y será 0 + +// Herencia +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Un llamado explícito al constructor de la super clase es indispensable + } + + // Sobrescribir + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Módulos, los "." pueden ser usados como separadores para los submódulos +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +// Un alias local para referirse a un módulo +import G = Geometry; + +var s2 = new G.Square(10); + +// Genéricos +// Clases +class Tuple { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interfases +interface Pair { + item1: T; + item2: T; +} + +// Y funciones +var pairToTuple = function(p: Pair) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); + +// Incluyendo referencias a un archivo de definición: +/// + +``` + +## Para mayor información + * [Sitio Oficial de TypeScript] (http://www.typescriptlang.org/) + * [Especificaciones del lenguaje TypeScript (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Introduciendo TypeScript en Canal 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Código fuente en GitHub] (https://github.com/Microsoft/TypeScript) + * [Definitely Typed - repositorio para definiciones de tipo] (http://definitelytyped.org/) -- cgit v1.2.3 From 1a52b7663f225a7bfc2b321c5824e12e9764c43c Mon Sep 17 00:00:00 2001 From: Damaso Sanoja Date: Thu, 28 Apr 2016 02:34:52 -0430 Subject: pythonstatcomp spanish translation (#1748) --- es-es/pythonstatcomp-es.html.markdown | 238 ++++++++++++++++++++++++++++++++++ 1 file changed, 238 insertions(+) create mode 100644 es-es/pythonstatcomp-es.html.markdown diff --git a/es-es/pythonstatcomp-es.html.markdown b/es-es/pythonstatcomp-es.html.markdown new file mode 100644 index 00000000..0d39abd5 --- /dev/null +++ b/es-es/pythonstatcomp-es.html.markdown @@ -0,0 +1,238 @@ +--- +language: Statistical computing with Python +contributors: + - ["e99n09", "https://github.com/e99n09"] +filename: pythonstatcomp.py +translators: + - ["Damaso Sanoja", "https://github.com/damasosanoja"] +lang: es-es +--- + +Este es un tutorial de como realizar tareas típicas de programación estadística usando Python. Está destinado a personas con cierta familiaridad con Python y con experiencia en programación estadística en lenguajes como R, Stata, SAS, SPSS, or MATLAB. + +```python + +# 0. Cómo configurar ==== + +""" Configurar con IPython y pip install lo siguiente: numpy, scipy, pandas, + matplotlib, seaborn, requests. + Asegúrese de realizar este tutorial con el IPython notebook para tener fácil + acceso a las ayudas en tiempo real y la documentación respectiva. +""" + +# 1. Captura de datos ==== + +""" Muchos prefieren Python sobre R ya que quieren interactuar mucho + con la web, bien sea haciendo webscraping o solicitando datos mediante + un API. Esto se puede hacer en R, pero en el contexto de un proyecto + que ya usa Python, existen beneficios al mantener un solo lenguaje. +""" + +import requests # para llamados HTTP (webscraping, APIs) +import os + +# webscraping +r = requests.get("https://github.com/adambard/learnxinyminutes-docs") +r.status_code # si es 200, el llamado ha sido exitoso +r.text # código fuente de la página +print(r.text) # formateado y embellecido +# graba el código fuente en un fichero: +os.getcwd() # verifica cual es el directorio de trabajo +f = open("learnxinyminutes.html","wb") +f.write(r.text.encode("UTF-8")) +f.close() + +# descargando un csv +fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/" +fn = "pets.csv" +r = requests.get(fp + fn) +print(r.text) +f = open(fn,"wb") +f.write(r.text.encode("UTF-8")) +f.close() + +""" para saber más del módulo de peticiones, incluyendo APIs, ver + http://docs.python-requests.org/en/latest/user/quickstart/ +""" + +# 2. Leyendo un fichero CSV ==== + +""" El paquete pandas de Wes McKinney brinda objetos 'DataFrame' en Python. Si + has usado R, ya estarás familiarizado con la idea de "data.frame". +""" + +import pandas as pd, numpy as np, scipy as sp +pets = pd.read_csv(fn) +pets +# nombre edad peso especies +# 0 fluffy 3 14 cat +# 1 vesuvius 6 23 fish +# 2 rex 5 34 dog + +""" Usuarios de R: notar que Python, al igual que otros lenguajes de programación + normales, comienza indexando desde 0. R de forma inusual comienza desde 1. +""" + +# dos formas distintas de imprimir una columna +pets.age +pets["age"] + +pets.head(2) # imprime las primeras dos filas +pets.tail(1) # imprime la última fila + +pets.name[1] # 'vesuvius' +pets.species[0] # 'cat' +pets["weight"][2] # 34 + +# en R, puedes esperar obtener 3 filas haciendo esto, pero aquí obtienes 2: +pets.age[0:2] +# 0 3 +# 1 6 + +sum(pets.age)*2 # 28 +max(pets.weight) - min(pets.weight) # 20 + +""" Si estás procesando grandes cantidades de cálculos de álgebra lineal, podrías + querer usar matrices, no DataFrames. Los DataFrames son ideales para combinar + columnas de diferentes tipos. +""" + +# 3. Gráficas ==== + +import matplotlib as mpl, matplotlib.pyplot as plt +%matplotlib inline + +# Para hacer virtualización de datos en Python, usa matplotlib + +plt.hist(pets.age); + +plt.boxplot(pets.weight); + +plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); + +# seaborn está por encima de matplotlib y logra mejores gráficos + +import seaborn as sns + +plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); + +# también hay algunas funciones gráficas específicas de seaborn +# nota como seaborn etiqueta automáticamente el eje x en este gráfico de barras +sns.barplot(pets["age"]) + +# los veteranos de R pueden seguir usando ggplot +from ggplot import * +ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") +# fuente: https://pypi.python.org/pypi/ggplot + +# incluso hay un porteo d3.js: https://github.com/mikedewar/d3py + +# 4. Limpieza simple de datos y análisis exploratorio ==== + +""" Tenemos ahora un ejemplo más complicado que demuestra un flujo básico para + limpieza de datos que lleva a la creación de algunos gráficos exploratorios + y la ejecución de una regresión lineal. + El conjunto de datos fue transcrito de Wikipedia a mano. Contiene + todos los Emperadores Romanos Sagrados y fechas claves en sus vidas + (nacimiento, muerte, coronación, etc.). + El objetivo del análisis es explorar si existe alguna relación + entre el año de nacimiento del Emperador y su tiempo de vida. + fuente de datos: https://en.wikipedia.org/wiki/Holy_Roman_Emperor +""" + +# cargar algunos datos de los Emperadores Romanos Sagrados +url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" +r = requests.get(url) +fp = "hre.csv" +f = open(fp,"wb") +f.write(r.text.encode("UTF-8")) +f.close() + +hre = pd.read_csv(fp) + +hre.head() +""" + Ix Dynasty Name Birth Death Election 1 +0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN +1 NaN Carolingian Louis I 778 20 June 840 NaN +2 NaN Carolingian Lothair I 795 29 September 855 NaN +3 NaN Carolingian Louis II 825 12 August 875 NaN +4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN + + Election 2 Coronation 1 Coronation 2 Ceased to be Emperor +0 NaN 25 December 800 NaN 28 January 814 +1 NaN 11 September 813 5 October 816 20 June 840 +2 NaN 5 April 823 NaN 29 September 855 +3 NaN Easter 850 18 May 872 12 August 875 +4 NaN 29 December 875 NaN 6 October 877 + + Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 +0 NaN NaN NaN NaN +1 Charles I son NaN NaN +2 Louis I son NaN NaN +3 Lothair I son NaN NaN +4 Louis I son NaN NaN +""" + +# limpiar las columnas de Nacimiento y Muerte + +import re # módulo para expresiones regulares + +rx = re.compile(r'\d+$') # coincidencia de últimos dígitos + +""" Esta función aplica una expresión regular a una columna de entrada (Birth, + Death), nivela la lista resultante, la convierte en un objeto Series, y + finalmente convierte el tipo del objeto Series de string a entero. Para + más información sobre que hace cada parte del código, ver: + - https://docs.python.org/2/howto/regex.html + - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list + - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html +""" +def extractYear(v): + return(pd.Series(reduce(lambda x,y: x+y,map(rx.findall,v),[])).astype(int)) + +hre["BirthY"] = extractYear(hre.Birth) +hre["DeathY"] = extractYear(hre.Death) + +# hacer una columna decir la edad estimada +hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int) + +# gráfica de dispersión simple, sin línea de tendencia, el color representa dinastía +sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False); + +# usa scipy para hacer regresiones lineales +from scipy import stats +(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge) +# código fuente: http://wiki.scipy.org/Cookbook/LinearRegression + +# verifica la pendiente (slope) +slope # 0.0057672618839073328 + +# verifica el valor R^2 : +rval**2 # 0.020363950027333586 + +# verifica el valor p +pval # 0.34971812581498452 + +# usa seaborn para hacer un gráfico de dispersión y dibujar una regresión lineal +# de la tendencia +sns.lmplot("BirthY", "EstAge", data=hre); + +""" Para más información sobre seaborn, ver + - http://web.stanford.edu/~mwaskom/software/seaborn/ + - https://github.com/mwaskom/seaborn + Para más información sobre SciPy, ver + - http://wiki.scipy.org/SciPy + - http://wiki.scipy.org/Cookbook/ + Para ver una versión del análisis de los Emperadores Romanos usando R, ver + - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R +""" +``` + +Si quieres aprender más, obtén _Python for Data Analysis_ por Wes McKinney. Es un extraordinario recurso usado como referencia para escribir este tutorial. + +También puedes encontrar gran cantidad de tutoriales interactivos de IPython en temas específicos a tus intereses, como Pilon de Cam Davidson Probabilistic Programming and Bayesian Methods for Hackers. + +Ver más módulos para investigar: + - análisis de texto y procesamiento natural del lenguaje: nltk, http://www.nltk.org + - análisis de redes sociales: igraph, http://igraph.org/python/ -- cgit v1.2.3 From 719e11492e491cdc0263d84bc0717c569f4c8bc9 Mon Sep 17 00:00:00 2001 From: ven Date: Thu, 28 Apr 2016 09:05:15 +0200 Subject: fixup after last PR --- es-es/pythonstatcomp-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/pythonstatcomp-es.html.markdown b/es-es/pythonstatcomp-es.html.markdown index 0d39abd5..0130b72a 100644 --- a/es-es/pythonstatcomp-es.html.markdown +++ b/es-es/pythonstatcomp-es.html.markdown @@ -2,7 +2,7 @@ language: Statistical computing with Python contributors: - ["e99n09", "https://github.com/e99n09"] -filename: pythonstatcomp.py +filename: pythonstatcomp-es.py translators: - ["Damaso Sanoja", "https://github.com/damasosanoja"] lang: es-es -- cgit v1.2.3 From 860fa9ebc732444693568fa9cf007d3c02fe72a2 Mon Sep 17 00:00:00 2001 From: Rodrigo Russo Date: Thu, 28 Apr 2016 09:06:12 +0200 Subject: [yaml/en] Add more resources (#1666) --- yaml.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/yaml.html.markdown b/yaml.html.markdown index 507c4d1f..a1ef0d38 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -164,3 +164,8 @@ set2: item2: null item3: null ``` + +### More Resources + ++ [YAML official website](http://yaml.org/) ++ [Online YAML Validator](http://codebeautify.org/yaml-validator) -- cgit v1.2.3 From bd7a53043f0a45e774ae7167df7ee2de623a9946 Mon Sep 17 00:00:00 2001 From: Radhika Ghosal Date: Thu, 28 Apr 2016 12:36:35 +0530 Subject: Added vim.html.markdown (#1744) --- vim.html.markdown | 235 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 235 insertions(+) create mode 100644 vim.html.markdown diff --git a/vim.html.markdown b/vim.html.markdown new file mode 100644 index 00000000..80c5835a --- /dev/null +++ b/vim.html.markdown @@ -0,0 +1,235 @@ +--- +category: tool +tool: vim +contributors: + - ["RadhikaG", "https://github.com/RadhikaG"] +filename: LearnVim.txt +--- + + +[Vim](www.vim.org) +(Vi IMproved) is a clone of the popular vi editor for Unix. It is a a text +editor designed for speed and increased productivity, and is ubiquitous in most +unix-based systems. It has numerous keybindings for speedy navigation to +specific points in the file, and for fast editing. + +## Basics of navigating Vim + +``` + vim # Open in vim + :q # Quit vim + :w # Save current file + :wq # Save file and quit vim + :q! # Quit vim without saving file + # ! *forces* :q to execute, hence quiting vim without saving + :x # Save file and quit vim, shorter version of :wq + + u # Undo + CTRL+R # Redo + + h # Move left one character + j # Move down one line + k # Move up one line + l # Move right one character + + # Moving within the line + + 0 # Move to beginning of line + $ # Move to end of line + ^ # Move to first non-blank character in line + + # Searching in the text + + /word # Highlights all occurences of word after cursor + ?word # Highlights all occurences of word before cursor + n # Moves cursor to next occurence of word after search + N # Moves cursor to previous occerence of word + + :%s/foo/bar/g # Change 'foo' to 'bar' on every line in the file + :s/foo/bar/g # Change 'foo' to 'bar' on the current line + + # Jumping to characters + + f # Jump forward and land on + t # Jump forward and land right before + + # For example, + f< # Jump forward and land on < + t< # Jump forward and land right before < + + # Moving by word + + w # Move forward by one word + b # Move back by one word + e # Move to end of current word + + # Other characters for moving around + + gg # Go to the top of the file + G # Go to the bottom of the file + :NUM # Go to line number NUM (NUM is any number) + H # Move to the top of the screen + M # Move to the middle of the screen + L # Move to the bottom of the screen +``` + +## Modes: + +Vim is based on the concept on **modes**. + +Command Mode - vim starts up in this mode, used to navigate and write commands +Insert Mode - used to make changes in your file +Visual Mode - used to highlight text and do operations to them +Ex Mode - used to drop down to the bottom with the ':' prompt to enter commands + +``` + i # Puts vim into insert mode, before the cursor position + a # Puts vim into insert mode, after the cursor position + v # Puts vim into visual mode + : # Puts vim into ex mode + # 'Escapes' from whichever mode you're in, into Command mode + + # Copying and pasting text + + y # Yank whatever is selected + yy # Yank the current line + d # Delete whatever is selected + dd # Delete the current line + p # Paste the copied text after the current cursor position + P # Paste the copied text before the current cursor position + x # Deleting character under current cursor position +``` + +## The 'Grammar' of vim + +Vim can be thought of as a set of commands in a +'Verb-Modifier-Noun' format, where: + +Verb - your action +Modifier - how you're doing your action +Noun - the object on which your action acts on + +A few important examples of 'Verbs, 'Modifiers', and 'Nouns': + +``` + # 'Verbs' + + d # Delete + c # Change + y # Yank (copy) + v # Visually select + + # 'Modifiers' + + i # Inside + a # Around + NUM # Number (NUM is any number) + f # Searches for something and lands on it + t # Searches for something and stops before it + / # Finds a string from cursor onwards + ? # Finds a string before cursor + + # 'Nouns' + + w # Word + s # Sentence + p # Paragraph + b # Block + + # Sample 'sentences' or commands + + d2w # Delete 2 words + cis # Change inside sentence + yip # Yank inside paragraph (copy the para you're in) + ct< # Change to open bracket + # Change the text from where you are to the next open bracket + d$ # Delete till end of line +``` + +## Some shortcuts and tricks + + +``` + > # Indent selection by one block + < # Dedent selection by one block + :earlier 15m # Reverts the document back to how it was 15 minutes ago + :later 15m # Reverse above command + ddp # Swap position of consecutive lines, dd then p + . # Repeat previous action +``` + +## Macros + +Macros are basically recordable actions. +When you start recording a macro, it records **every** action and command +you use, until you stop recording. On invoking a macro, it applies the exact +same sequence of actions and commands again on the text selection. + +``` + qa # Start recording a macro named 'a' + q # Stop recording + @a # Play back the macro +``` + +### Configuring ~/.vimrc + +The .vimrc file can be used to configure Vim on startup. + +Here's a sample ~/.vimrc file: + +``` +" Example ~/.vimrc +" 2015.10 + +" Required for vim to be iMproved +set nocompatible + +" Determines filetype from name to allow intelligent auto-indenting, etc. +filetype indent plugin on + +" Enable syntax highlighting +syntax on + +" Better command-line completion +set wildmenu + +" Use case insensitive search except when using capital letters +set ignorecase +set smartcase + +" When opening a new line and no file-specific indenting is enabled, +" keep same indent as the line you're currently on +set autoindent + +" Display line numbers on the left +set number + +" Indentation options, change according to personal preference + +" Number of visual spaces per TAB +set tabstop=4 + +" Number of spaces in TAB when editing +set softtabstop=4 + +" Number of spaces indented when reindent operations (>> and <<) are used +set shiftwidth=4 + +" Convert TABs to spaces +set expandtab + +" Enable intelligent tabbing and spacing for indentation and alignment +set smarttab +``` + +### References + +[Vim | Home](http://www.vim.org/index.php) + +`$ vimtutor` + +[A vim Tutorial and Primer](https://danielmiessler.com/study/vim/) + +[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about) + +[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim) -- cgit v1.2.3 From f18a60dff4f1315001094a2041c6d51edcbb16ec Mon Sep 17 00:00:00 2001 From: Cameron Bernhardt Date: Sun, 1 May 2016 12:44:19 -0400 Subject: Update java.html.markdown --- java.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index ed7e4f53..a025bbba 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -734,7 +734,7 @@ public class EnumTest { // Enum types are much more powerful than we show above. // The enum body can include methods and other fields. -// You can se more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html +// You can see more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html ``` @@ -775,4 +775,4 @@ The links provided here below are just to get an understanding of the topic, fee * [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) -* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) \ No newline at end of file +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) -- cgit v1.2.3 From ef486c21197c30d39399f695bb5414b50ef6c4ac Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Mon, 2 May 2016 15:15:23 -0700 Subject: Clarify inc/dec operators --- csharp.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 7be34fb9..8d185462 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -212,10 +212,10 @@ on a new line! ""Wow!"", the masses cried"; // Incrementations int i = 0; Console.WriteLine("\n->Inc/Dec-rementation"); - Console.WriteLine(i++); //i = 1. Post-Incrementation - Console.WriteLine(++i); //i = 2. Pre-Incrementation - Console.WriteLine(i--); //i = 1. Post-Decrementation - Console.WriteLine(--i); //i = 0. Pre-Decrementation + Console.WriteLine(i++); //Prints "0", i = 1. Post-Incrementation + Console.WriteLine(++i); //Prints "2", i = 2. Pre-Incrementation + Console.WriteLine(i--); //Prints "2", i = 1. Post-Decrementation + Console.WriteLine(--i); //Prints "0", i = 0. Pre-Decrementation /////////////////////////////////////// // Control Structures -- cgit v1.2.3 From ddedb40ef88a8c7b0d26e0aaea0efb4b50ce521f Mon Sep 17 00:00:00 2001 From: Jason Stathopulos Date: Tue, 10 May 2016 10:30:32 -0400 Subject: Add Git Reflog Section To Git.html.markdown --- git.html.markdown | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/git.html.markdown b/git.html.markdown index 6472c462..4d4b2a4e 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Betsy Lorton" , "http://github.com/schbetsy"] - ["Bruno Volcov", "http://github.com/volcov"] - ["Andrew Taylor", "http://github.com/andrewjt71"] + - ["Jason Stathopulos", "http://github.com/SpiritBreaker226"] filename: LearnGit.txt --- @@ -520,6 +521,31 @@ $ git reset 31f2bb1 $ git reset --hard 31f2bb1 ``` +### reflog (caution) + +Reflog will list most of the git commands you have done for a given time period, +default 90 days. + +This give you the a change to reverse any git commands that have gone wrong +for instance if a rebase is has broken your application. + +You can do this: + +1. `git reflog` to list all of the git commands for the rebase +``` +38b323f HEAD@{0}: rebase -i (finish): returning to refs/heads/feature/add_git_reflog +38b323f HEAD@{1}: rebase -i (pick): Clarify inc/dec operators +4fff859 HEAD@{2}: rebase -i (pick): Update java.html.markdown +34ed963 HEAD@{3}: rebase -i (pick): [yaml/en] Add more resources (#1666) +ed8ddf2 HEAD@{4}: rebase -i (pick): pythonstatcomp spanish translation (#1748) +2e6c386 HEAD@{5}: rebase -i (start): checkout 02fb96d +``` +2. Select where to reset to, in our case its `2e6c386`, or `HEAD@{5}` +3. 'git reset --hard HEAD@{5}' this will reset your repo to that head +4. You can start the rebase again or leave it alone. + +[Additional Reading.](https://git-scm.com/docs/git-reflog) + ### revert Revert can be used to undo a commit. It should not be confused with reset which -- cgit v1.2.3 From e0c220a717b0402c4cc3ed22bb7402b62632c13b Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 11 May 2016 10:37:15 -0700 Subject: Update smalltalk.html.markdown Add new resource and fix smalltalk.org link. --- smalltalk.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index 2c17b753..cc7ab84c 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -946,10 +946,11 @@ Utilities openCommandKeyHelp ### Free Online * [GNU Smalltalk User's Guide](https://www.gnu.org/software/smalltalk/manual/html_node/Tutorial.html) -* [smalltalk dot org](http://www.smalltalk.org/smalltalk/learning.html) +* [smalltalk dot org](http://www.smalltalk.org/) * [Computer Programming using GNU Smalltalk](http://www.canol.info/books/computer_programming_using_gnu_smalltalk/) * [Smalltalk Cheatsheet](http://www.angelfire.com/tx4/cus/notes/smalltalk.html) * [Smalltalk-72 Manual](http://www.bitsavers.org/pdf/xerox/parc/techReports/Smalltalk-72_Instruction_Manual_Mar76.pdf) * [BYTE: A Special issue on Smalltalk](https://archive.org/details/byte-magazine-1981-08) * [Smalltalk, Objects, and Design](https://books.google.co.in/books?id=W8_Une9cbbgC&printsec=frontcover&dq=smalltalk&hl=en&sa=X&ved=0CCIQ6AEwAWoVChMIw63Vo6CpyAIV0HGOCh3S2Alf#v=onepage&q=smalltalk&f=false) * [Smalltalk: An Introduction to Application Development Using VisualWorks](https://books.google.co.in/books?id=zalQAAAAMAAJ&q=smalltalk&dq=smalltalk&hl=en&sa=X&ved=0CCgQ6AEwAmoVChMIw63Vo6CpyAIV0HGOCh3S2Alf/) +* [Smalltalk Programming Resources](http://www.whoishostingthis.com/resources/smalltalk/) -- cgit v1.2.3 From 02db6f2bfcb8371a29a708ca425f8785615da969 Mon Sep 17 00:00:00 2001 From: Michal Jurosz Date: Thu, 12 May 2016 10:15:30 +0200 Subject: Fix c - the first character of ILoveC is I not i (#2253) --- c.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 2fad5348..babf0954 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -238,7 +238,7 @@ int main (int argc, char** argv) // Increment and decrement operators: char *s = "ILoveC"; int j = 0; - s[j++]; // => "i". Returns the j-th item of s THEN increments value of j. + s[j++]; // => "I". Returns the j-th item of s THEN increments value of j. j = 0; s[++j]; // => "L". Increments value of j THEN returns j-th value of s. // same with j-- and --j @@ -779,4 +779,4 @@ Readable code is better than clever code and fast code. For a good, sane coding Other than that, Google is your friend. -[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file +[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member -- cgit v1.2.3 From 4e5439c21f5ab5ba33e46926b2fc5e44e25362ae Mon Sep 17 00:00:00 2001 From: Viren Nadkarni Date: Thu, 12 May 2016 16:37:50 +0530 Subject: Fix a mistake in fgrep example (#2254) --- bash.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index f3c9cccc..02d7f31e 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -270,7 +270,7 @@ grep "^foo.*bar$" file.txt grep -c "^foo.*bar$" file.txt # if you literally want to search for the string, # and not the regex, use fgrep (or grep -F) -fgrep "^foo.*bar$" file.txt +fgrep "foobar" file.txt # Read Bash shell builtins documentation with the bash 'help' builtin: -- cgit v1.2.3 From b5def35dab9fc7f370b907106961c570e654c211 Mon Sep 17 00:00:00 2001 From: kberov Date: Fri, 13 May 2016 21:12:19 +0200 Subject: Create bg-bg/perl.html.markdown (#2255) * Create perl.html.markdown * renamed file to match requirments --- bg-bg/perl-bg.html.markdown | 326 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 326 insertions(+) create mode 100644 bg-bg/perl-bg.html.markdown diff --git a/bg-bg/perl-bg.html.markdown b/bg-bg/perl-bg.html.markdown new file mode 100644 index 00000000..babd2d4d --- /dev/null +++ b/bg-bg/perl-bg.html.markdown @@ -0,0 +1,326 @@ +--- +name: perl +category: language +language: perl +filename: learnperl.pl +contributors: + - ["Korjavin Ivan", "http://github.com/korjavin"] + - ["Dan Book", "http://github.com/Grinnz"] +translators: + - ["Красимир Беров", "https://github.com/kberov"] +lang: bg-bg +--- + +Perl 5 е изключително мощен език за програмиране с широка област на приложение +и над 25 годишна история. + +Perl 5 работи на повече от 100 операционни системи от мини до супер-компютри и е +подходящ както за бърза разработка на скриптове така и за огромни приложения. + +```perl +# Едноредовите коментари започват със знака диез. + +#### Стриктен режим и предупреждения + +use strict; +use warnings; + +# Силно препоръчително е всички скриптове и модули да включват тези редове. +# strict спира компилацията в случай на необявени предварително променливи. +# warnings показва предупредителни съобщения в случай на често допускани грешки, +# например използване на променливи без стойност в низове. + +#### Типове променливи в Perl + +# Променливите започват със съответен знак (sigil - от латински sigillum ), +# който представлява символ, указващ типа на променливата. Името на самата +# променлива започва с буква или знак за подчертаване (_), следван от какъвто и +# да е брой букви, цифри или знаци за подчертаване. Забележете, че ако напишете +# 'use utf8;' (без кавичките), можете да използвате всякакви букви за имена на +# променливите, включително и български. + +### Perl има три главни типа променливи: $scalar (скалар), @array (масив), and %hash (хеш). + +## Скалари +# Скаларът представлява единична стойност: +my $animal = "camel"; +my $answer = 42; +use utf8; +my $животно = 'камила'; + +# Стойностите на скаларите могат да бъдат низове, цели числа или числа с +# плаваща запетая (десетични дроби). Perl автоматично ги ползва и превръща от +# един тип стойност в друга, според както е необходимо. + +## Масиви +# Масивът представлява списък от стойности: +my @animals = ("камила", "llama", "owl"); +my @numbers = (23, 42, 69); +my @mixed = ("camel", 42, 1.23); + +# Елементите на масива се достъпват като се използват квадратни скоби и $, +# който указва каква стойност ще бъде върната (скалар). +my $second = $animals[1]; + +## Хешове +# Хешът представлява набор от двойки ключ/стойност: + +my %fruit_color = ("ябълка", "червена", "banana", "yellow"); + +# Може да използвате празно пространство и оператора "=>" (тлъста запетая), +# за да ги изложите по-прегледно: + +%fruit_color = ( + ябълка => "червена", + banana => "yellow", +); + +# Елементите (стойностите) от хеша се достъпват чрез използване на ключовете. +# Ключовете се ограждат с фигурни скоби и се поставя $ пред името на хеша. +my $color = $fruit_color{ябълка}; + +# Скаларите, масивите и хешовете са документирани по-пълно в perldata. +# На командния ред напишете (без кавичките) 'perldoc perldata'. + +#### Указатели (Референции) + +# По-сложни типове данни могат да бъдат създавани чрез използване на указатели, +# които ви позволяват да изграждате масиви и хешове в други масиви и хешове. + +my $array_ref = \@array; +my $hash_ref = \%hash; +my @array_of_arrays = (\@array1, \@array2, \@array3); + +# Също така можете да създавате безименни масиви и хешове, към които сочат само +# указатели. + +my $fruits = ["apple", "banana"]; +my $colors = {apple => "red", banana => "yellow"}; + +# Можете да достигате до безименните структури като поставяте отпред съответния +# знак на структурата, която искате да достъпите (дереферирате). + +my @fruits_array = @$fruits; +my %colors_hash = %$colors; + +# Можете да използвате оператора стрелка (->), за да достигнете до отделна +# скаларна стойност. + +my $first = $array_ref->[0]; +my $value = $hash_ref->{banana}; + +# Вижте perlreftut и perlref, където ще намерите по-задълбочена документация за +# указателите (референциите). + +#### Условни изрази и цикли + +# В Perl ще срещнете повечето от обичайните изрази за условия и обхождане (цикли). + +if ($var) { + ... +} elsif ($var eq 'bar') { + ... +} else { + ... +} + +unless (условие) { + ... +} +# Това е друг, по-четим вариант на "if (!условие)" + +# Perl-овския начин след-условие +print "Yow!" if $zippy; +print "Нямаме банани" unless $bananas; + +# докато +while (условие) { + ... +} + + +# цикли for и повторение +for (my $i = 0; $i < $max; $i++) { + print "index is $i"; +} + +for (my $i = 0; $i < @elements; $i++) { + print "Current element is " . $elements[$i]; +} + +for my $element (@elements) { + print $element; +} + +# мълчаливо - използва се подразбиращата се променлива $_. +for (@elements) { + print; +} + +# Отново Perl-овския начин след- +print for @elements; + +# отпечатване на стойностите чрез обхождане ключовете на указател към хеш +print $hash_ref->{$_} for keys %$hash_ref; + +#### Регулярни (обикновени) изрази + +# Поддръжката на регулярни изрази е залеганала дълбоко в Perl. Задълбочена +# документация ще намерите в perlrequick, perlretut и на други места. +# Но ето накратко: + +# Просто съвпадение +if (/foo/) { ... } # истина ако $_ съдържа "foo" +if ($x =~ /foo/) { ... } # истина ако $x съдържа "foo" + +# Просто заместване + +$x =~ s/foo/bar/; # замества foo с bar в $x +$x =~ s/foo/bar/g; # Замества ВСИЧКИ ПОЯВИ на foo с bar в $x + + +#### Файлове и Вход/Изход (I/O) + +# Можете да отворите файл за въвеждане на данни в него или за извеждане на +# данни от него като използвате функцията "open()". + +open(my $in, "<", "input.txt") or die "Не мога да отворя input.txt: $!"; +open(my $out, ">", "output.txt") or die "Can't open output.txt: $!"; +open(my $log, ">>", "my.log") or die "Can't open my.log: $!"; + +# Можете да четете от отворен файлов манипулатор като използвате оператора +# "<>". В скаларен контекст той чете по един ред от файла наведнъж, а в списъчен +# контекст изчита всички редове от файла наведнъж като присвоява всеки ред на +# масива: + +my $line = <$in>; +my @lines = <$in>; + +#### Подпрограми (функции) + +# Да се пишат подпрограми е лесно: + +sub logger { + my $logmessage = shift; + + open my $logfile, ">>", "my.log" or die "Could not open my.log: $!"; + + print $logfile $logmessage; +} + +# Сега можем да ползваме подпрограмата като всяка друга вградена функция: + +logger("Имаме подпрограма, която пише във файл-отчет!"); + +#### Модули + +# Модулът е набор от програмен код на Perl, обикновено подпрограми, който може +# да бъде използван в друг програмен код на Perl. Обикновено се съхранява във +# файл с разширение .pm, така че perl (програмата) да може лесно да го разпознае. + +# В MyModule.pm +package MyModule; +use strict; +use warnings; + +sub trim { + my $string = shift; + $string =~ s/^\s+//; + $string =~ s/\s+$//; + return $string; +} + +1; + +# От другаде: + +use MyModule; +MyModule::trim($string); + +# Чрез модула Exporter може да направите функциите си износни, така че други +# програми да могат да ги внасят (импортират). +# Такива функции се използват така: + +use MyModule 'trim'; +trim($string); + +# Много Perl-модули могат да се свалят от CPAN (http://www.cpan.org/). Те +# притежават редица полезни свойства, които ще ви помогнат да си свършите работа +# без да откривате колелото. Голям брой известни модули като Exporter са включени +# в дистрибуцията на самия Perl. Вижте perlmod за повече подробности, свързани с +# модулите в Perl. + +#### Обекти + +# Обектите в Perl са просто референции, които знаят на кой клас (пакет) +# принадлежат. По този начин методите (подпрограми), които се извикват срещу +# тях могат да бъдат намерени в съответния клас. За да се случи това, в +# конструкторите (обикновено new) се използва вградената функция +# bless. Ако използвате обаче модули като Moose или Moo, няма да ви се налага +# сами да извиквате bless (ще видите малко по-долу). + +package MyCounter; +use strict; +use warnings; + +sub new { + my $class = shift; + my $self = {count => 0}; + return bless $self, $class; +} + +sub count { + my $self = shift; + return $self->{count}; +} + +sub increment { + my $self = shift; + $self->{count}++; +} + +1; + +# Методите могат да се извикват на клас или на обект като се използва оператора +# стрелка (->). + +use MyCounter; +my $counter = MyCounter->new; +print $counter->count, "\n"; # 0 +$counter->increment; +print $counter->count, "\n"; # 1 + +# Модулите Moose и Moo от CPAN ви помагат леснот да създавате класове. Те +# предоставят готов конструктор (new) и прост синтаксис за деклариране на +# свойства на обектите (attributes). Този клас може да се използва по същия начин +# като предишния по-горе. + +package MyCounter; +use Moo; # внася strict и warnings + +has 'count' => (is => 'rwp', default => 0, init_arg => undef); + +sub increment { + my $self = shift; + $self->_set_count($self->count + 1); +} + +1; + +# Обектно-ориентираното програмиране е разгледано по-задълбочено в perlootut, +# а изпълнението му на ниско ниво в Perl е обяснено в perlobj. +``` + +#### Често задавани въпроси (FAQ) + +# perlfaq съдържа въпроси и отговори, отнасящи се до много общи задачи и предлага +# за ползване добри модлули от CPAN, подходящи за решаване на различни проблеми. + +#### Повече за четене + - [Въведение в Perl](http://www.slideshare.net/kberov/01-intro-bg) + - [PERL - Курс на МГУ "Св.Иван Рилски" (13 ЧАСТИ)](http://www.mgu.bg/drugi/ebooks/belchevski/perl.html) + - [perl-tutorial](http://perl-tutorial.org/) + - [Learn at www.perl.com](http://www.perl.org/learn.html) + - [perldoc](http://perldoc.perl.org/) + - и идващото с perl: `perldoc perlintro` + -- cgit v1.2.3 From 085ddf3aab1bb682da701cf1ab320b78052a3b06 Mon Sep 17 00:00:00 2001 From: clearsense Date: Sat, 14 May 2016 14:35:38 +0300 Subject: fix few mistakes in comments and code delete if-statement in 458 line, because there is not place for it --- uk-ua/javascript-ua.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/uk-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown index 9614f9ca..ff44b656 100644 --- a/uk-ua/javascript-ua.html.markdown +++ b/uk-ua/javascript-ua.html.markdown @@ -350,6 +350,7 @@ myFunc(); // = undefined // Функція може бути присвоєна іншому об’єкту. Тоді вона матиме доступ до // цього об’єкта через this var myOtherFunc = function() { + return this.myString.toUpperCase(); } myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO, WORLD!" @@ -407,7 +408,7 @@ myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 // Аналогічно для функцій -myObj.myFunc(); // = "Hello, world!" +myObj.myFunc(); // = "hello, world!" // Якщо інтерпретатор не знайде властивості в прототипі, то він продовжить пошук // в прототипі прототипа і так далі @@ -432,7 +433,7 @@ myObj.meaningOfLife; // = 43 // Другий спосіб: у конструкторів є властивість з іменем prototype. Це *не* // прототип функції-конструктора, це прототип для нових об’єктів, які будуть створені -// цим конструктором і ключового слова new. +// цим конструктором і ключовим словом new. MyConstructor.prototype = { myNumber: 5, getMyNumber: function() { -- cgit v1.2.3 From 8bda31f05386dcca40400aad34a7c45507c464b7 Mon Sep 17 00:00:00 2001 From: clearsense Date: Sat, 14 May 2016 14:37:54 +0300 Subject: fix some mistakes in comments and code --- uk-ua/javascript-ua.html.markdown | 3 --- 1 file changed, 3 deletions(-) diff --git a/uk-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown index ff44b656..19dc790b 100644 --- a/uk-ua/javascript-ua.html.markdown +++ b/uk-ua/javascript-ua.html.markdown @@ -455,9 +455,6 @@ myNumber == myNumberObj; // = true typeof myNumber; // = 'number' typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false -if (0) { - // Цей код не виконається, тому що 0 - це хиба. -} // Об’єкти-обгортки і вбудовані типи мають спільні прототипи, тому // ви можете розширити функціонал рядків: -- cgit v1.2.3 From 4cfac645fc4d5cb9c78f74f18c01c7a00f7bafba Mon Sep 17 00:00:00 2001 From: clearsense Date: Sat, 14 May 2016 14:45:20 +0300 Subject: fix list of Further Reading --- uk-ua/javascript-ua.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/uk-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown index 19dc790b..11c8db02 100644 --- a/uk-ua/javascript-ua.html.markdown +++ b/uk-ua/javascript-ua.html.markdown @@ -482,12 +482,12 @@ if (Object.create === undefined) { // не перезаписуємо метод ## Що почитати -[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript -[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript -[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core -[4]: http://www.learneroo.com/modules/64/nodes/350 -[5]: http://bonsaiden.github.io/JavaScript-Garden/ -[6]: http://www.amazon.com/gp/product/0596805527/ -[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript -[8]: http://eloquentjavascript.net/ -[9]: http://jstherightway.org/ +* [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript +* [2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +* [3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core +* [4]: http://www.learneroo.com/modules/64/nodes/350 +* [5]: http://bonsaiden.github.io/JavaScript-Garden/ +* [6]: http://www.amazon.com/gp/product/0596805527/ +* [7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +* [8]: http://eloquentjavascript.net/ +* [9]: http://jstherightway.org/ -- cgit v1.2.3 From cc526773bd490520a5a25319cdc971a30f8ff6f9 Mon Sep 17 00:00:00 2001 From: clearsense Date: Sat, 14 May 2016 14:58:16 +0300 Subject: add me to list of contributors --- uk-ua/javascript-ua.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/uk-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown index 11c8db02..a84eba67 100644 --- a/uk-ua/javascript-ua.html.markdown +++ b/uk-ua/javascript-ua.html.markdown @@ -3,6 +3,7 @@ language: javascript contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["clearsense", "https://github.com/clearsense"] filename: javascript-uk.js translators: - ["Ivan", "https://github.com/IvanEh"] -- cgit v1.2.3 From 1c3de94e762953cd863368745f7f1e8071feeb26 Mon Sep 17 00:00:00 2001 From: Danijar Hafner Date: Wed, 18 May 2016 18:05:13 +0200 Subject: Fix git pull --rebase explanation (#2262) --- git.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/git.html.markdown b/git.html.markdown index 4d4b2a4e..47bac3ba 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -396,8 +396,8 @@ $ git pull origin master $ git pull # Merge in changes from remote branch and rebase -# branch commits onto your local repo, like: "git pull , git -# rebase " +# branch commits onto your local repo, like: "git fetch , git +# rebase /" $ git pull origin master --rebase ``` -- cgit v1.2.3 From 056364ff1cf012e9b6a1255a887fa82f4baf8105 Mon Sep 17 00:00:00 2001 From: Bill Panagiotopoulos Date: Thu, 19 May 2016 10:34:53 +0300 Subject: fix some misplaced comments (#2261) --- el-gr/css-gr.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/el-gr/css-gr.html.markdown b/el-gr/css-gr.html.markdown index 327dc1a0..41ddb932 100644 --- a/el-gr/css-gr.html.markdown +++ b/el-gr/css-gr.html.markdown @@ -22,14 +22,15 @@ lang: el-gr ## ΚΑΝΟΝΕΣ #################### */ -/* ένας κανόνας χρησιμοποιείτε για να στοχεύσουμε ένα αντικείμενο (selector). +/* ένας κανόνας χρησιμοποιείτε για να στοχεύσουμε ένα αντικείμενο (selector). */ selector { property: value; /* περισσότερες ιδιότητες...*/ } /* -Αυτό είναι ενα παράδειγμα αντικειμένου¨ +Αυτό είναι ενα παράδειγμα αντικειμένου +*/
-*/ + /* Μπορούμε να το στοχεύσουμε με την χρήση CSS κλάσεων */ .class1 { } -- cgit v1.2.3 From 470893c93ad7aa104345b070a8749aa3edbd5ba8 Mon Sep 17 00:00:00 2001 From: Bill Panagiotopoulos Date: Thu, 19 May 2016 17:16:11 +0300 Subject: Update css-gr.html.markdown (#2263) --- el-gr/css-gr.html.markdown | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/el-gr/css-gr.html.markdown b/el-gr/css-gr.html.markdown index 41ddb932..9404679c 100644 --- a/el-gr/css-gr.html.markdown +++ b/el-gr/css-gr.html.markdown @@ -27,10 +27,8 @@ selector { property: value; /* περισσότερες ιδιότητες...*/ /* Αυτό είναι ενα παράδειγμα αντικειμένου -*/ -
- +*/ /* Μπορούμε να το στοχεύσουμε με την χρήση CSS κλάσεων */ .class1 { } -- cgit v1.2.3 From 88d2e3667761b42ee4d4db6ccab18ad7f29c0a47 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Thu, 19 May 2016 11:11:39 -0700 Subject: Remove nix highlighting (we don't have it) --- nix.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nix.html.markdown b/nix.html.markdown index 2979098f..ef59a135 100644 --- a/nix.html.markdown +++ b/nix.html.markdown @@ -13,7 +13,7 @@ You can evaluate Nix expressions using [nix-instantiate](https://nixos.org/nix/manual/#sec-nix-instantiate) or [`nix-repl`](https://github.com/edolstra/nix-repl). -```nix +``` with builtins; [ # Comments -- cgit v1.2.3 From 2f29565a7bc150f4afd8d6b1f800a019d39e58dd Mon Sep 17 00:00:00 2001 From: Petru Dimitriu Date: Thu, 26 May 2016 22:00:16 +0300 Subject: Fixed typos for latex-ro, added haskell-ro (#2266) --- ro-ro/haskell-ro.html.markdown | 453 +++++++++++++++++++++++++++++++++++++++++ ro-ro/latex-ro.html.markdown | 256 +++++++++++++++++++++++ ro-ro/latex.html.markdown | 258 ----------------------- 3 files changed, 709 insertions(+), 258 deletions(-) create mode 100644 ro-ro/haskell-ro.html.markdown create mode 100644 ro-ro/latex-ro.html.markdown delete mode 100644 ro-ro/latex.html.markdown diff --git a/ro-ro/haskell-ro.html.markdown b/ro-ro/haskell-ro.html.markdown new file mode 100644 index 00000000..98751538 --- /dev/null +++ b/ro-ro/haskell-ro.html.markdown @@ -0,0 +1,453 @@ +--- +language: Haskell +contributors: + - ["Adit Bhargava", "http://adit.io"] +translators: + - ["Petru Dimitriu", "http://petru-dimitriu.github.io"] +--- + +Haskell este un limbaj de programare practic, pur funcțional. + +```haskell +-- Comentariile pe o singura linie incep cu 2 cratime. +{- Comentariile multilinie + se scriu astfel. +-} + +---------------------------------------------------- +-- 1. Tipuri de date primitive si operatori +---------------------------------------------------- + +-- Exista numere +3 -- 3 + +-- Matematica functioneaza ca de obicei +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 +35 / 5 -- 7.0 + +-- Impartirea este cu virgula +35 / 4 -- 8.75 + +-- Impartirea cu rest +35 `div` 4 -- 8 + +-- Valorile booleene sunt primitive +True +False + +-- Operatii logice +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- In exemplele de mai sus, `not` este o functie ce primeste o valoare. +-- In Haskell nu se pun paranteze pentru apelurile de functie. Toate +-- argumentele sunt insirate dupa numele functiei. Sablonul general este: +-- func arg1 arg2 arg3 +-- Vedeti sectiunea despre functii pentru a afla cum sa scrieti propria functie. + +-- Caractere si siruri de caractere +"Acesta este un sir de caractere" +'a' -- un caracter +'Nu se pot folosi apostroafe pentru siruri.' -- eroare! + +-- Sirurile pot fi concatenate +"Hello " ++ "world!" -- "Hello world!" + +-- Un string e de fapt o lista de caractere +['H', 'e', 'l', 'l', 'o'] -- "Hello" +"Acesta este un string" !! 0 -- 'A' + + +---------------------------------------------------- +-- Liste si tupli +---------------------------------------------------- + +-- Fiecare element dintr-o lista trebuie sa aiba acelasi tip. +-- Urmatoarele liste sunt identice. +[1, 2, 3, 4, 5] +[1..5] + +-- Intervalele sunt versatile. +['A'..'F'] -- "ABCDEF" + +-- Se poate specifica un pas pentru intervale. +[0,2..10] -- [0, 2, 4, 6, 8, 10] +[5..1] -- Aceasta nu functioneaza deoarece pasul implicit este incrementarea. +[5,4..1] -- [5, 4, 3, 2, 1] + +-- indexarea intr-o lista este de la zero +[1..10] !! 3 -- se obtine 4 + +-- Se pot crea liste infinite +[1..] -- lista tuturor numerelor naturale + +-- Listele infinite functioneaza pentru ca Haskell foloseste "evaluare lenesa" +-- adica evalueaza lucrurile doar cand este nevoie de ele. Deci se poate +-- cere al 1000-lea element din lista infinita a numerelor naturale astfel: + +[1..] !! 999 -- rezulta 1000 + +-- Haskell a evaluat elementele 1 - 1000 din lista... dar restul elementelor +-- acestei liste "infinite" nu exista inca! Haskell nu le va evalua pana +-- nu va fi nevoie de ele. + +-- concatenarea a doua liste +[1..5] ++ [6..10] + +-- alipirea la capul listei +0:[1..5] -- [0, 1, 2, 3, 4, 5] + +-- operatii cu liste +head [1..5] -- 1 +tail [1..5] -- [2, 3, 4, 5] +init [1..5] -- [1, 2, 3, 4] +last [1..5] -- 5 + +-- intelegerea listelor +[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] + +-- folosind o conditie +[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] + +-- Fiecare element dintr-un tuplu poate fi de un tip diferit +-- dar un tuplu are lungime fixa +-- Un tuplu: +("haskell", 1) + +-- accesarea elementelor unui tuplu pereche +fst ("haskell", 1) -- "haskell" (first) +snd ("haskell", 1) -- 1 (second) + +---------------------------------------------------- +-- 3. Functii +---------------------------------------------------- +-- O functie simpla ce sumeaza doua variabile +add a b = a + b + +-- Aveti in vedere ca daca folositi ghci (interpretorul Haskell) +-- trebuie sa scrieti in fata si `let`, adica +-- let add a b = a + b + +-- Apelarea functiei +add 1 2 -- rezulta 3 + +-- Numele functiei se poate pune si intre argumente +-- folosind apostrof intors: +1 `add` 2 -- 3 + +-- Se pot defini functii fara litere in denumire! Astfel se pot +-- defini noi operatori! De exemplu, iata un operator care realizeaza +-- impartirea intreaga +(//) a b = a `div` b +35 // 4 -- rezulta 8 + +-- Guards: o metoda usoara de a crea ramuri de executie +fib x + | x < 2 = 1 + | otherwise = fib (x - 1) + fib (x - 2) + +-- Potrivirea sirurilor se face similar. Aici am definit 3 definitii +-- pentru fib. Haskell o va alege automat pe prima care se potriveste +-- cu sablonul valorii. +fib 1 = 1 +fib 2 = 2 +fib x = fib (x - 1) + fib (x - 2) + +-- Potrivirea in tupli: +foo (x, y) = (x + 1, y + 2) + +-- Potrivirea in liste. Aici `x` este primul element al listei, +-- iar `xs` este restul litei. Putem scrie propria functie +-- de mapare +myMap func [] = [] +myMap func (x:xs) = func x:(myMap func xs) + +-- Functiile anonime sunt create folosind un backslash urmat +-- de toate argumentele. +myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] + +-- utilizarea fold (denumit `inject` in alte limbaje) cu o functie +-- anonima. foldl1 inseamna pliere la stanga, folosind prima valoare +-- din lista drept valoarea initiala pentru acumulator +foldl1 (\acc x -> acc + x) [1..5] -- 15 + +---------------------------------------------------- +-- 4. Mai multe functii +---------------------------------------------------- + +-- aplicare partiala; daca nu se introduc toate argumentele unei functii, +-- este "aplicata partial", adica returneaza o noua functie ce primeste +-- restul argumentelor, avand deja setate argumentele introduse + +add a b = a + b +foo = add 10 -- foo este o functie ce primeste un numar si ii aduna 10 +foo 5 -- 15 + +-- alta maniera de a scrie acelasi lucru +foo = (10+) +foo 5 -- 15 + +-- compunerea functiilor +-- operatorul `.` inlantuieste functiile. +-- De exeplu, aici foo este o functie care aduna 10 unui numar, il inmul +-- teste cu 4 si returneaza rezultatul calcului +foo = (4*) . (10+) + +-- 4*(10 + 5) = 60 +foo 5 -- 60 + +-- alterarea precedentei +-- Haskell detine un operator numit `$`. Acest operator aplica o functie +-- unui parametru dat. Fata de aplicarea standard a functiilor, care +-- foloseste prioritatea maxim posibila 10 si este asociativa la stanga, +-- operatorul `$` are prioritatea 0 si este asociativ la dreapta. +-- Aceasta inseamna ca expresia de la dreapta este aplicata ca parametru +-- functiei din stanga + +-- inainte +even (fib 7) -- false + +-- echivalent +even $ fib 7 -- false + +-- compunerea functiilor +even . fib $ 7 -- false + + +---------------------------------------------------- +-- 5. Type signatures +---------------------------------------------------- + +-- Haskell are un sistem de tipuri de date foarte puternic; fiecare expresie +-- valida are un tip. + +-- Cateva tipuri de baza: +5 :: Integer +"hello" :: String +True :: Bool + +-- Functiile au tipuri de asemenea. +-- `not` primeste un boolean si returneaza un boolean. +-- not :: Bool -> Bool + +-- Iata o functie ce primeste doi intregi +-- add :: Integer -> Integer -> Integer + +-- Cand se defineste o valoare, este bine sa se precizeze tipul ei deasupra. +double :: Integer -> Integer +double x = x * 2 + +--------------------------------------------------------- +-- 6. Controlul executiei si instructiunile conditionale +--------------------------------------------------------- + +-- expresia conditionala if +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- cand expresiile sunt pe mai multe linii, este importanta indentarea +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- expresiile de tip case; iata cum se verifica argumentele programului +case args of + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + + +-- Haskell nu foloseste cicluri, ci recursie +-- map aplica o functie fiecarui element dintr-o lista + +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +-- se poate face o functie for folosind map +for array func = map func array + +-- si apoi se poate folosi astfel: +for [0..5] $ \i -> show i + +-- se poate scrie si asa: +for [0..5] show + +-- Se poate folosi foldl sau foldr pentru a reduce o lista +-- foldl +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- Acelasi lucru ca a scrie +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- foldl functioneaza spre stanga, foldr spre dreapta +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- Acealsi lucru ca: +(2 * 1 + (2 * 2 + (2 * 3 + 4))) + +---------------------------------------------------- +-- 7. Tipuri de date +---------------------------------------------------- + +-- Iata cum se creeaza un tip de date in Haskell + +data Culoare = Rosu | Albastru | Verde + +-- Acum poate fi folosit in functii + + +spune :: Culoare -> String +spune Rosu = "Esti Rosu!" +spune Albastru = "Esti Albastru!" +spune Verde = "Esti Verde!" + +-- Tipul de date poate avea si parametri. + +data Maybe a = Nothing | Just a + +-- Toate acestea sunt de tipul Maybe +Just "hello" -- de tipul `Maybe String` +Just 1 -- de tipul `Maybe Int` +Nothing -- de tipul `Maybe a` pentru oricare `a` + +---------------------------------------------------- +-- 8. IO in Haskell +---------------------------------------------------- + +-- Desi IO nu se poate explica intru totul fara a explica monadele, +-- nu este atat de greu de explicat pentru o idee de baza. + +-- Cand se executa un program Haskell, se apeleaza `main`. +-- Trebuie sa returneze o valoare de tio `IO a` pentru un anumit tip `a`. +-- De exemplu: + +main :: IO () +main = putStrLn $ "Hello, sky! " ++ (say Blue) +-- putStrLn are tipul String -> IO () + +-- Cel mai usor se lucreaza cu IO daca se implementeaza programul +-- ca o functie de la String la String. Functia +-- interact :: (String -> String) -> IO () +-- citeste un text, executa o functie asupra ei, apoi afiseaza +-- iesirea. + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- O valoare de tipul `IO ()` poate fi privita ca reprezentand +-- o secventa de actiuni pe care care computerul sa le execute, +-- similar cu felul in care un program este scris intr-un limbaj +-- imperativ. Putem folosi notatia `do` pentru a inlantui actiunile. +-- De exemplu: + +sayHello :: IO () +sayHello = do + putStrLn "What is your name?" + name <- getLine -- citeste o linie + putStrLn $ "Hello, " ++ name + +-- Exercise: Scrieti propria functie `interact` care citeste +-- o singura linie de la intrare. + + +-- Codul din `sayHello` nu va fi niciodata executat. Singura actiunile +-- care este executata este valoarea lui `main`. +-- Pentru a rula `sayHello.`, eliminati definitia de mai sus a `main`. +-- si inlocuiti-o cu +-- main = sayHello + +-- Sa intelegem mai bine cum functioneaza functia `getLine`. +-- Tipul ei este: +-- getLine :: IO String +-- Pueti privi o valoare de tipul `IO a` ca fiind un program +-- de computer care va genera o valoare de tipul `a` cand +-- este executata (pe langa orice altceva face). O putem denumi +-- si refolosi utilizand `<-`. De asemenea putem face propriile +-- actiuni te tipul `IO String`: + +action :: IO String +action = do + putStrLn "Aceasta e o linie." + input1 <- getLine + input2 <- getLine + --Tipul instructiunii `do` este cel de pe ultima sa linie. + -- `return` nu este un cuvant cheie, ci o functie + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- Putem folosi aceasta exact cum am folosit `getLine`: + +main'' = do + putStrLn "I will echo two lines!" + result <- action + putStrLn result + putStrLn "This was all, folks!" + +-- Tipul `IO` este un exemplu de "monada". Felul in care Haskell foloseste +-- o monada pentru a realiza opeartii de intrare si iesire il face un limbaj +-- pur functional. Orice functie care interactioneaza cu exteriorul (adica +-- realieaza IO) este marcata ca `IO` in semnatura ei. Aceasta ne permite +-- sa spunem ce functii sunt "pure", adica nu interactioneaza cu exteriorul. + +-- Aceasta este o facilitate foarte puternica, deoarece este usor sa +-- se ruleze functii pure concurent; asadar, concurenta in Haskell se face usor + +---------------------------------------------------- +-- 9. REPL in Haskell +---------------------------------------------------- + +-- Se porneste introducand `ghci`. +-- Dupa aceasta, se poate introduce cod Haskell. +-- Toate valorile noi trebuie precedate de `let`. + +let foo = 5 + +-- Puteti vedea tipul oricarei valori sau expresii cu `:t`. + +> :t foo +foo :: Integer + +-- Operatorii, precum `+`, `:` si `$` sunt functii. +-- Tipul lor poate fi observat punand operatorii intre paranteze. + +> :t (:) +(:) :: a -> [a] -> [a] + +-- Se pot obtine informatii despre fiecare nume folosind `:i` + +> :i (+) +class Num a where + (+) :: a -> a -> a + ... + -- Defined in ‘GHC.Num’ +infixl 6 + + +--De asemenea se poate executa orice actiune de tipul `IO ()` + +> sayHello +What is your name? +Friend! +Hello, Friend! + +``` +Mai sunt multe de spus despre Haskell, printre care typclasses și monade. +Acestea sunt marile idei care fac programarea în Haskell atât de interesantă. +Vă las un exemplu final în Haskell: o variantă de implementare a sortării rapide +(quicksort) în Haskell: + +```haskell +qsort [] = [] +qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater + where lesser = filter (< p) xs + greater = filter (>= p) xs +``` + +Există două maniere populare de a instala Haskell: prin [instalarea bazată pe Cabal](http://www.haskell.org/platform/), și prin mai noul [proces bazat pe Stack](https://www.stackage.org/install). + +Se poate găsi o introducere în Haskell mult mai blândă la adresele +[Learn you a Haskell](http://learnyouahaskell.com/) sau +[Real World Haskell](http://book.realworldhaskell.org/). diff --git a/ro-ro/latex-ro.html.markdown b/ro-ro/latex-ro.html.markdown new file mode 100644 index 00000000..f661db0a --- /dev/null +++ b/ro-ro/latex-ro.html.markdown @@ -0,0 +1,256 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] + - ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"] +translators: + - ["Petru Dimitriu", "http://petru-dimitriu.github.io"] +filename: learn-latex-ro.tex +lang: ro-ro +--- + +```tex +% Toate comentariile încep cu % +% Nu există comentarii multi-linie + +% LaTeX NU este un program software de procesare text de tipul +% "What You See Is What You Get" +% precum MS Word, sau OpenOffice Writer + +% Toate comenzile LaTeX încep cu backslash. (\) + +% Documentele LaTeX încep cu o linie care definește tipul documentului +% care urmează a fi compilat. Alte tipuri de documente sunt book (carte), +% presentation (prezentare), etc. Opțiunile pentru document apar +% între paranteze drepte. În acest caz, specificăm că vrem să folosim +% un corp de text (font) de 12 puncte. +\documentclass[12pt]{article} + +% Mai apoi definim pachetele pe care documentul le folosește. +% Dacă vreți să includeți grafice, text colorat sau +% cod sursă din alt fișier în documentul dumneavoastră, +% trebuie să îmbogățiți capabilitățile LaTeX. Aceasta se realizează +% adăugând pachete. Voi include pachetele float și caption pentru +% imagini. +\usepackage{caption} +\usepackage{float} +% această comandă este necesară atunci când vreți să scrieți codul +% sursă folosind diacrtice! (cum e cazul aici, unde translatorul +% a vrut să scrie neapărat folosind diacriticele românești) +\usepackage[utf8]{inputenc} + +% De asemenea, putem defini și alte proprietăți pentru documente. +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu \\ Traducere de Petru Dimitriu} +\date{\today} +\title{Învățați LaTeX în Y minute!} + +% Suntem gata să începem documentul. +% Tot ce se află înaintea acestei linii se numește "Preambul" +\begin{document} +% dacă am setat autorul, data și titlul, putem cere LaTeX să +% creeze o pagină de titlu +\maketitle + +% Cele mai multe documente științifice au un rezumat; puteți folosi comenzile +% predefinite pentru acesta. Acesta ar trebui să apară, așa cum ar fi logic, +% după titlu, dar înainte de secțiunile principale ale corpului. +% Această comandă este disponibilă în clasele de document article și report. +\begin{abstract} + Documentațue LaTeX scrisă în LaTeX. O idee nicidecum nouă și nicidecum a mea! +\end{abstract} + +% Comenzile pentru secțiuni sunt intuitive. +% Toate titlurile secțiunilor sunt adăugate automat la tabla de materii (cuprins). +\section{Introducere} +Salut, mă numesc Petru. Astăzi vom învăța împreună LaTeX! + +\section{Altă secțiune} +Acesta este textul pentru altă secțiune. Vom face o subsecțiune. + +\subsection{Aceasta este o subsecțiune} +Și încă una. + +\subsubsection{Pitagora} +Mult mai bine. +\label{subsec:pitagora} + +% Folosind asteriscul putem suprima numărătoarea automată a LaTeX. +% Aceasta funcționează și pentru alte comenzi LaTeX. +\section*{Secțiune fără numerotare} +Totuși nu toate secțiunile trebuie să fie nenumerotate! + +\section{Note despre text} +În general LaTeX se pricepe să pună textul unde trebuie. Dacă o linie are \\ +nevoie \\ să \\ fie \\ întreruptă, puteți adăuga două caractere backslash +la codul sursă. + +\section{Liste} +Listele sunt printre cel mai simplu de făcut lucruri în LaTeX! Mâine merg la +cumpărături așa că fac o listă: +\begin{enumerate} % Aceasta creează un mediu "enumerate" + % \item spune mediului "enumerate" să incrementeze + \item salată + \item 27 pepeni + \item un singur iepuroi + % putem suprascrie numărul elementului folosind [] + \item[câte?] conserve de ton + + Nu este un element din listă, dar încă face parte din "enumerate". + +\end{enumerate} % Toate mediile trebuie să aibă o instrucțiune de încheiere. + +\section{Matematică} + +Una dintre principalele întrebuințări ale LaTeX este realizarea +articolelor academice sau a fișelor tehnice, de obicei aflate în +universul matematicii și științelor exacte. Astfel, trebuie să putem +adăuga simboluri speciale în documentul nostru! \\ + +Matematica are multe simboluri, mult mai multe decât se găsesc +pe o tastatură - printre ele, simboluri pentru mulțimi și relații, +săgeți, operatori și litere grecești.\\ + +Mulțimile și relațiile sunt esențiale în lucrările științifce matematice. +Iată cum se scrie: toți y aparținând lui X.\\ +$\forall$ x $\in$ X. \\ + +% Observați cum am avut nevoie să pun semnul $ înainte și după simboluri. +% Aceasta pentru că atunci când scriem, suntem în modul text (text-mode). +% Totuși simbolurile matematice există numai în modul matematic (math-mode). +% Când ne aflăm în text-mode, putem scrie texte în math-mode punând $ înainte +% și după simboluri. La fel și viceversa. Și variabilele pot fi redate +% în math-mode. Putem intra în math-mode și scriind \[\]. + +\[a^2 + b^2 = c^2 \] + +Îmi place litera $\xi$. De asemenea îmi plac $\beta$, $\gamma$ și +$\sigma$. Nu există nicio literă grecească necunoscută pentru LaTeX! + +Operatorii sunt esențiali într-un document matematic! +funcțiile trigonometrice ($\sin$, $\cos$, $\tan$), +logaritmii și exponențialele ($\log$, $\exp$), +limitele ($\lim$), etc. +au comenzi definite în LaTeX pentru fiecare. +Să vedem cum scriem o ecuație: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ + +Fracțiile (numărător - numitor) pot fi scrise astfel: +% 10 / 7 +$^{10}/_{7}$ \\ + +% Fracții relativ complexe pot fi scrie ca +% \frac{numărător}{numitor} +$\frac{n!}{k!(n - k)!}$ \\ + +Putem insera ecuații și într-un "mediu pentru ecuații". + +% Afișează text matematic într-un mediu pentru ecuații. +\begin{equation} % intră în math-mode + c^2 = a^2 + b^2. + \label{eq:pitagora} % pentru referențiere +\end{equation} +% toate instrucțiunile cu \begin trebuie să fie cuplate cu o instrucțiune cu \end + +Putem referenția noua noastră ecuație! +~\ref{eq:pitagora} este cunoscută și ca Teorema lui Pitagora, despre care vorbim și la Sec.~\ref{subsec:pitagora}. Multe lucruri prot fi etichetate: +figuri, ecuații, secțiuni, etc. + +Sumele discrete și integralele se scriu cu comenzile sum și int. + +% Unele compilatoare LaTeX nu acceptă să existe linii goale +% într-un mediu pentru ecuații. +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Figuri} + +Să inserăm o figură. Așezarea figurilor poate fi ușor dificilă. +Eu trebuie să mă uit peste opțiunile de așezare de fiecare dată. + +\begin{figure}[H] % H denumește opțiunle de așezare + \centering % centrează figura pe pagină + % Inserează o figură scalată la 0.8 din lățimea paginii. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Comentat pentru a nu împiedica fișierul să compileze. + \caption{Triunghi dreptunghic cu laturile $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} + +\subsection{Tabel} +Putem insera tabele la fel cum inserăm figuri. + +\begin{table}[H] + \caption{Descriere pentru tabel} + % argumentele {} controlează cum vor fi afișate coloanele + \begin{tabular}{c|cc} + Număr & Nume & Prenume \\ % Numele coloanelor sunt separate prin $ + \hline % a linie orizonală + 1 & Popescu & Ion \\ + 2 & Sima & Felix + \end{tabular} +\end{table} + +% \section{Hyperlinkuri} % În curând + +\section{Cum facem ca LaTeX să nu compileze ceva (de exemplu cod sursă)} +Să zicem că vrem să includem niște cod în documentul nostru LaTeX. +Vom avea nevoie ca LaTeX să nu încerce să interpreteze acel cod, +ci doar să îl redea în document. Vom face asta cu un mediu verbatim. + +% Există și alte pachete (i.e. minty, lstlisting, etc.) +% dar verbatim este pachetul cel mai simplu. +\begin{verbatim} + print("Salut lume!") + a%b; % hei! putem folosi % în verbatim + random = 4; +\end{verbatim} + +\section{Compilarea} +Acum vă întrebați cum se compilează acest document minunat și să vă +minunați de rezultat, un PDF LaTeX. (da, documentul acesta chiar +compilează). \\ +Realizarea documentului cu LaTeX va parcurge următorii pași: + \begin{enumerate} + \item Se scrie documentul în text simplu. (codul sursă) + \item Se compilează documentul pentru a produce un PDF. + Compilarea arată cam așa în Linux:\\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +Anumite editoare pentru LaTeX combină pașii 1 și 2 în același produs software. +Așadar, dacă vreți să vedeți realizați pasul 1 dar nu și pasul 2, el se poate +realiza "în spate". + +Scrieți toate informațiile de formatare în pasul 1. Compilarea din pasul 2 +se ocupă de producerea documentului în formatul definit în pasul 1. + +\section{Final} + +Asta e tot pentru moment! + +% De multe ori veți vrea să aveți o secțiune cu bibliografie în document. +% Cea mai ușoară modalitate este folosind mediul thebibliography. +\begin{thebibliography}{1} + % Similar celorlalte liste, comanda \bibitem e folosită pentru a înșirui + % elemente; fiecare element poate fi citat în interiorul textului + \bibitem{latexwiki} Uimitoarea carte wiki LaTeX: {\em https://en.wikibooks.org/wiki/LaTeX} + \bibitem{latextutorial} Un tutorial propriu-zis: {\em http://www.latex-tutorial.com} +\end{thebibliography} + +% încheie documentul +\end{document} +``` + +## Mai multe despre LaTeX + +* Uimitoarea carte wiki LaTeX: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) +* Un tutorial propriu-zis: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) diff --git a/ro-ro/latex.html.markdown b/ro-ro/latex.html.markdown deleted file mode 100644 index 35651e28..00000000 --- a/ro-ro/latex.html.markdown +++ /dev/null @@ -1,258 +0,0 @@ ---- -language: latex -contributors: - - ["Chaitanya Krishna Ande", "http://icymist.github.io"] - - ["Colton Kohnke", "http://github.com/voltnor"] - - ["Sricharan Chiruvolu", "http://sricharan.xyz"] - - ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"] -translators: - - ["Petru Dimitriu", "http://petru-dimitriu.github.io"] -filename: brainfuck-ro.clj -filename: learn-latex-ro.tex -lang: ro-ro ---- - -```tex -% Toate comentariile încep cu % -% Nu există comentarii multi-linie - -% LaTeX NU este un program software de procesare text de tipul -% "What You See Is What You Get" -% precum MS Word, sau OpenOffice Writer - -% Toate comenzile LaTeX încep cu backslash. (\) - -% Documentele LaTeX încep cu o linie care definește tipul documentului -% care urmează a fi compilat. Alte tipuri de documente sunt book (carte), -% presentation (prezentare), etc. Opțiunile pentru document apar -% între paranteze drepte. În acest caz, specificăm că vrem să folosim -% un corp de text (font) de 12 puncte. -\documentclass[12pt]{article} - -% Mai apoi definim pachetele pe care documentul le folosește. -% Dacă vreți să includeți grafice, text colorat sau -% cod sursă din alt fișier în documentul dumneavoastră, -% trebuie să îmbogățiți capabilitățile LaTeX. Aceasta se realizează -% adăugând pachete. Voi include pachetele float și caption pentru -% imagini. -\usepackage{caption} -\usepackage{float} -% această comandă este necesară atunci când vreți să scrieți codul -% sursă folosind diacrtice! (cum e cazul aici, unde translatorul -% a vrut să scrie neapărat folosind diacriticele românești) -\usepackage[utf8]{inputenc} - -% De asemenea, putem defini și alte proprietăți pentru documente. -% We can define some other document properties too! -\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu \\ Traducere de Petru Dimitriu} -\date{\today} -\title{Învățați LaTeX în Y minute!} - -% Suntem gata să începem documentul. -% Tot ce se află înaintea acestei linii se numește "Preambul" -\begin{document} -% dacă am setat autorul, data și titlul, putem cere LaTeX să -% creeze o pagină de titlu -\maketitle - -% Cele mai multe documente științifice au un abstract; puteți folosi comenzile -% predefinite pentru acesta. Acesta ar trebui să apară, așa cum ar fi logic, -% după titlu, dar înainte de secțiunile principale ale corpului. -% Această comandă este disponibilă în clasele de document article și report. -\begin{abstract} - Documentațue LaTeX scrisă în LaTeX. O idee nicidecum nouă și nicidecum a mea! -\end{abstract} - -% Comenzile pentru secțiuni sunt intuitive. -% Toate titlurile secțiunilor sunt adăugate automat la tabla de materii (cuprins). -\section{Introducere} -Salut, mă numesc Petru. Astăzi vom învăța împreună LaTeX! - -\section{Altă secțiune} -Acesta este textul pentru altă secțiune. Vom face o subsecțiune. - -\subsection{Aceasta este o subsecțiune} % Subsecțiunile sunt și ele intuitive. -Și încă una. - -\subsubsection{Pitagora} -Mult mai bine. -\label{subsec:pitagora} - -% Folosind asteriscul putem suprima numărătoarea automată a LaTeX. -% Aceasta funcționează și pentru alte comenzi LaTeX. -\section*{Secțiune fără numerotare} -Totuși nu toate secțiunile trebuie să fie nenumerotate! - -\section{Note despre text} -În general LaTeX se pricepe să pună textul unde trebuie. Dacă o linie are \\ -nevoie \\ să \\ fie \\ întreruptă, puteți adăuga două caractere backslash -la codul sursă. - -\section{Liste} -Listele sunt printre cel mai simplu de făcut lucruri în LaTeX! Mâine merg la -cumpărături așa că fac o listă: -\begin{enumerate} % Aceasta creează un mediu "enumerate" - % \item spune mediului "enumerate" să incrementeze - \item salată - \item 27 pepeni - \item un singur iepuroi - % putem suprascrie numărul elementului folosind [] - \item[câte?] conserve de ton - - Nu este un element din listă, dar încă face parte din "enumerate". - -\end{enumerate} % All environments must have an end. - -\section{Matematică} - -Una dintre principalele întrebuințări ale LaTeX este realizarea -articolelor academice sau a foilor tehnice, de obicei aflate în -universul matematicii și științelor exacte. Astfel, trebuie să putem -adăuga simboluri speciale în documentului nostru! \\ - -Matematica are multe simboluri, mult mai multe decât se găsesc -pe o tastatură - printre ele, simboluri pentru mulțimi și relații, -săgeți, operatori și litere grecești.\\ - -Mulțimile și relațiile sunt de bază în lucrările științifce matematice. -Iată cum se scrie: toți y aparținând lui X.\\ -$\forall$ x $\in$ X. \\ - -% Observați cum am avut nevoie să pun semnul $ înainte și după simboluri. -% Aceasta pentru că atunci când scriem, suntem în modul text (text-mode). -% Totuși simbolurile matematice există numai în modul matematic (math-mode). -% Când ne aflăm în text-mode, putem scrie texte în math-mode punând $ înainte -% și după simboluri. La fel și viceversa. Și variabilele pot fi redate -% în math-mode. Putem intra în math-mode și scriind \[\]. - -\[a^2 + b^2 = c^2 \] - -Litera mea grecească este $\xi$. De asemenea îmi plac $\beta$, $\gamma$ și -$\sigma$. Nu există nicio literă grecească necunoscută pentru LaTeX! - -Operatorii sunt exențiali într-un document matematic! -funcțiile trigonometrice ($\sin$, $\cos$, $\tan$), -logaritmii și exponențialele ($\log$, $\exp$), -limitele ($\lim$), etc. -au comenzi definite în LaTeX pentru fiecare. -Să vedem cum scriem o ecuație: \\ - -$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ - -Fracțiile (numărător - numitor) pot fi scrise astfel: -% 10 / 7 -$^{10}/_{7}$ \\ - -% Fracții relativ complexe pot fi scrie ca -% \frac{numărător}{numitor} -$\frac{n!}{k!(n - k)!}$ \\ - -Putem insera ecuații și într-un "mediu pentru ecuații". - -% Afișează text matematic într-un mediu pentru ecuații. -\begin{equation} % intră în math-mode - c^2 = a^2 + b^2. - \label{eq:pitagora} % pentru referențiere -\end{equation} -% toate instrucțiunile cu \begin trebuie să fie cuplate cu o instrucțiune cu \end - -Putem referenția noua nosatră ecuație! -~\ref{eq:pitagora} este cunoscută și ca Teorema lui Pitagora, despre care vorbim și la Sec.~\ref{subsec:pitagora}. Multe lucruri prot fi etichetate: -figuri, ecuații, secțiuni, etc. - -Sumele discrete și integralele se scriu cu comenzile sum și int. - -% Unele compilatoare LaTeX nu acceptă să există linii goala -% într-un mediu pentru ecuații. -\begin{equation} - \sum_{i=0}^{5} f_{i} -\end{equation} -\begin{equation} - \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x -\end{equation} - -\section{Figuri} - -Să inserăm o figură. Așezarea figurilor poate fi ușor dificilă. -Eu trebuie să mă uit peste opțiunile de așezare de fiecare dată. - -\begin{figure}[H] % H denumește opțiunle de așezare - \centering % centrează figura pe pagină - % Inserează o figură scalată la 0.8 din lățimea paginii. - %\includegraphics[width=0.8\linewidth]{right-triangle.png} - % Comentat pentru a nu împiedica fișierul să compileze. - \caption{Triunghi dreptunghic cu laturile $a$, $b$, $c$} - \label{fig:right-triangle} -\end{figure} - -\subsection{Tabel} -Putem insera tabele la fel cum inserăm figuri. - -\begin{table}[H] - \caption{Descriere pentru tabel} - % argumentele {} controlează cum vor fi afișate coloanele - \begin{tabular}{c|cc} - Număr & Nume & Prenume \\ % Numele coloanelor sunt separate prin $ - \hline % a linie orizonală - 1 & Popescu & Ion \\ - 2 & Sima & Felix - \end{tabular} -\end{table} - -% \section{Hyperlinkuri} % În curând - -\section{Cum facem ca LaTeX să nu compileze ceva (de exemplu cod sursă)} -Să zicem că vrem să includem niște cod în documentul nostru LaTeX. -Vom avea nevoie ca LaTeX să nu încerce să interpreteze acel cod, -ci doar să îl redea în document. Vom face asta cu un mediu verbatim. - -% Există și alte pachete (i.e. minty, lstlisting, etc.) -% dar verbatim este pachetul cel mai simplu. -\begin{verbatim} - print("Salut lume!") - a%b; % hei! putem folosi % în verbatim - random = 4; -\end{verbatim} - -\section{Compilarea} -Acum vă întrebați cum se compilează acest document minunat și să vă -minunați de rezultatul, un PDF LaTeX. (da, documentul acesta chiar -compilează). \\ -Realizarea documentului cu LaTeX va parcurge următorii pași: - \begin{enumerate} - \item Se scrie documentul în text simplu. (codul sursă) - \item Se compilează documentul pentru a produce un PDF. - Compilarea arată cam așa în Linux:\\ - \begin{verbatim} - $pdflatex learn-latex.tex learn-latex.pdf - \end{verbatim} - \end{enumerate} - -Anumiți editor pentru LaTeX combină pașii 1 și 2 în același produs software. -Așadar, dacă vreți să vedeți realizați pasul 1 dar nu și pasul 2, el se poate -realiza "în spate". - -Scrieți toate informațiile de formatare în pasul 1. Compilarea din pasul 2 -se ocupă de producerea documentului în formatul definit în pasul 1. - -\section{Final} - -Asta e tot pentru moment! - -% De multe ori veți vrea să aveți o secțiune cu bibliografie în document. -% Cea mai ușoară modalitate este folosind mediul thebibliography. -\begin{thebibliography}{1} - % Similar celorlalte liste, comanda \bibitem e folosită pentru a înșirui - % elemente; fiecare element poate fi citat în interiorul textului - \bibitem{latexwiki} Uimitoarea carte wiki LaTeX: {\em https://en.wikibooks.org/wiki/LaTeX} - \bibitem{latextutorial} Un tutorial propriu-zis: {\em http://www.latex-tutorial.com} -\end{thebibliography} - -% încheie documentul -\end{document} -``` - -## Mai multe despre LaTeX - -* Uimitoarea carte wiki LaTeX: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) -* Un tutorial propriu-zis: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) -- cgit v1.2.3 From 828e2ad8aa9ae4f1912010e505d7789b2710f53b Mon Sep 17 00:00:00 2001 From: ven Date: Fri, 27 May 2016 11:22:48 +0200 Subject: Fix haskell-ro headers (#2266) --- ro-ro/haskell-ro.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ro-ro/haskell-ro.html.markdown b/ro-ro/haskell-ro.html.markdown index 98751538..082f138b 100644 --- a/ro-ro/haskell-ro.html.markdown +++ b/ro-ro/haskell-ro.html.markdown @@ -4,6 +4,8 @@ contributors: - ["Adit Bhargava", "http://adit.io"] translators: - ["Petru Dimitriu", "http://petru-dimitriu.github.io"] +lang: ro-ro +filename: haskell-ro.html --- Haskell este un limbaj de programare practic, pur funcțional. -- cgit v1.2.3 From e0a5ad73538cb46637e7d66c88ea96b5ec8c10ff Mon Sep 17 00:00:00 2001 From: MichalMartinek Date: Fri, 27 May 2016 11:24:07 +0200 Subject: Czech translation for CSS (#1771) --- cs-cz/css.html.markdown | 252 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 252 insertions(+) create mode 100644 cs-cz/css.html.markdown diff --git a/cs-cz/css.html.markdown b/cs-cz/css.html.markdown new file mode 100644 index 00000000..a86302f7 --- /dev/null +++ b/cs-cz/css.html.markdown @@ -0,0 +1,252 @@ +--- +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Geoffrey Liu", "https://github.com/g-liu"] + - ["Connor Shea", "https://github.com/connorshea"] + - ["Deepanshu Utkarsh", "https://github.com/duci9y"] +translators: + - ["Michal Martinek", "https://github.com/MichalMartinek"] +filename: learncss.css +--- + +V ranných dobách webu se nevyskytovaly žádné vizuální elementy, pouze čistý text, ale s vývojem webových browserů se staly stránky plné grafických prvků běžné. + +A právě proto vzniklo CSS, aby oddělilo obsah (HTML) od vzhledu webové stránky. + +Pomocí CSS můžete označit různé elementy na HTML stránce a přiřadit jim různé vzhledové vlastnosti. + +Tento návod byl napsán pro CSS 2, avšak CSS 3 se stalo velmi oblíbené a v dnešní době už běžné. + +**POZNÁMKA** Protože CSS produkuje vizuální výsledky, je nutné k jeho naučení všechno zkoušet třeba na [dabbletu](http://dabblet.com/). +Tento článek se zaměřuje hlavně na syntaxi a poskytue také pár obecných tipů. + +```css +/* komentáře jsou ohraničeny lomítkem s hvězdičkou, přesně jako tyto dva + řádky, v CSS není nic jako jednořádkový komentář, pouze tenhle zápis */ + +/* ################ + ## SELEKTORY + ################ */ + +/* Selektor se používá pro vybrání elementu na stránce: +selektor { vlastnost: hodnota; /* více vlastností... }*/ + +/* +Toto je náš element: +
+*/ + +/* Můžeme vybrat tento element třeba podle jeho třídy */ +.trida1 { } + +/* nebo obou tříd! */ +.trida1.trida2 { } + +/* nebo jeho jména */ +div { } + +/* nebo jeho id */ +#nejakeID { } + +/* nebo podle toho, že má atribut! */ +[attr] { font-size:smaller; } + +/* nebo že argument nabývá specifické hodnoty*/ +[attr='hodnota'] { font-size:smaller; } + +/* začíná nějakou hodnotou (CSS 3) */ +[attr^='ho'] { font-size:smaller; } + +/* nebo končí něčím (CSS 3) */ +[attr$='ta'] { font-size:smaller; } + +/* nebo obsahuje nějakou hodnotu, která je v atributu oddělená mezerami */ +[otherAttr~='co'] { } +[otherAttr~='neco'] { } + +/* nebo obsahuje hodnotu oddělenou pomlčkou - "-" (U+002D) */ +[otherAttr|='cs'] { font-size:smaller; } + + +/* Můžeme spojit různé selektory, abychom získali specifičtější selektor. + Pozor, nedávejte mezi ně mezery! */ +div.nejaka-trida[attr$='ta'] { } + +/* Můžeme vybrat element, který je potomek jineho */ +div.vnejsi-element > .jmeno-tridy { } + +/* nebo zanořen ještě hlouběji. Potomci jsou přímo pod vnější třídou, pouze 1 + úroveň pod rodičem. Tento selektor bude fungovat na jakékoliv úrovni pod + rodičem */ +div.rodic .jmeno-tridy { } + +/* Varování: stejný selektor bez mezery má úplně jiný význam + Vzpomínáte si jaký? */ +div.rodic.jmeno-tridy { } + +/* Možná budete chtít vybrat element, který leží přímo vedle */ +.jsem-primo-pred + .timto-elementem { } + +/* nebo kdekoliv na stejné úrovni stromu */ +.jsem-kdekoliv-pred ~ .timto-elementem { } + +/* Existují selektory nazvané pseudo třídy, kterými můžeme vybrat elementy, + když jsou v určitém stavu */ + +/* na příklad, když kurzor najede na element */ +selektor:hover { } + +/* nebo již navštívený odkaz */ +selektor:visited { } + +/* nebo nebyl navštíven */ +selektor:link { } + +/* nebo když je vybrán, např kliknutím do inputu*/ +selektor:focus { } + +/* element, ktery je prvni potomek rodiče */ +selektor:first-child {} + +/* element, který je poslední potomek rodiče */ +selektor:last-child {} + +/* Stejně jako pseudo třídy, umožňují pseudo elementy stylizovat určité + části dokumentu */ + +/* odpovídá virtuálnímu prvnímu potomku */ +selektor::before {} + +/* odpovídá virtuálnímu poslednímu potomku */ +selektor::after {} + +/* Na vhodném místě, může být použitá hvězdička jako žolík, který vybere každý element */ +* { } /* všechny elementy */ +.rodic * { } /* všechny vnořené elementy */ +.rodic > * { } /* všichni potomci */ + +/* #################### + ## VLASTNOSTI + #################### */ + +selektor { + + /* Jednotky délky můžou být relativní nebo absolutní */ + + /* Relativní jednotky */ + width: 50%; /* počet procent šířky rodičovského elementu */ + font-size: 2em; /* násobek puvodní velikosti fontu elementu */ + font-size: 2rem; /* nebo kořenového elementu */ + font-size: 2vw; /* násobek 1% šířky zařízení (viewport) (CSS 3) */ + font-size: 2vh; /* nebo jeho výšky */ + font-size: 2vmin; /* násobek 1% výšky nebo šířky, dle toho, co je menší */ + font-size: 2vmax; /* nebo větší */ + + /* Absolutní jednotky */ + width: 200px; /* pixely */ + font-size: 20pt; /* body */ + width: 5cm; /* centimetry */ + min-width: 50mm; /* milimetry */ + max-width: 5in; /* palce */ + + /* Barvy */ + color: #F6E; /* krátký hexadecimální formát */ + color: #FF66EE; /* dlouhý hexadecimální formát */ + color: tomato; /* pojmenovaná barva */ + color: rgb(255, 255, 255); /* hodnoty rgb */ + color: rgb(10%, 20%, 50%); /* procenta rgb */ + color: rgba(255, 0, 0, 0.3); /* hodnoty rgba (CSS 3) Poznámka: 0 < a < 1 */ + color: transparent; /* ekvivalentní jako nastavení alfy 0 */ + color: hsl(0, 100%, 50%); /* procenta hsl (CSS 3) */ + color: hsla(0, 100%, 50%, 0.3); /* procenta hsl s alfou */ + + /* Obrázky jako pozadí elementu */ + background-image: url(/cesta/k/obrazku.jpg); /* uvozovky jsou dobrovolné */ + + /* Fonty */ + font-family: Arial; + /* když název fontu obsahuje mezeru, tak musí být v uvozovkách */ + font-family: "Courier New"; + /* když se první nenaleze, použije se další atd. */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; +} +``` + +## Použití + +Uložte CSS soubor s příponou `.css`. + +```xml + + + + + + + +
+
+``` + +## Priorita nebo kaskáda + +Element může být vybrán více selektory a jeho vlastnosti můžou být nastaveny více než jednou. V těchto případech, má jedno zadání vlastnosti prioritu před druhým. Obecně platí, že více specifické selektory mají přednost před těmi méně specifickými. + +Tento proces se nazývá kaskáda, proto i název kaskádové styly(Cascading Style Sheets). + +Máme následující CSS + +```css +/* A */ +p.trida1[attr='hodnota'] + +/* B */ +p.trida1 { } + +/* C */ +p.trida2 { } + +/* D */ +p { } + +/* E */ +p { vlastnost: hodnota !important; } +``` + +a tento element +```xml +

+``` +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í. +* `F` je další, kvůli stylu zadanému přimo do elementu +* `A` je další, protože je více specifické, než cokoliv dalšího. Má 3 selektory: jméno elementu `p`, jeho třídu `trida1`, atribut `attr='hodnota'`. +* `C` je další, i když je stejně specifický jako `B`, protože je uveden až po něm. +* `B` je další +* `D` je poslední + +## Kompatibilita + +Většina z možností v CSS 2 (a spousta v CSS 3) je dostupná napříč všemi browsery a zařízeními. Ale pořád je dobrá praxe, zkontrolovat dostupnost, před užitím nové vlastnosti/fičury. + +## Zdroje + +* Přehled dostupnosti [CanIUse](http://caniuse.com). +* CSS hřiště [Dabblet](http://dabblet.com/). +* [Mozilla Developer Network - CSS dokumentace](https://developer.mozilla.org/en-US/docs/Web/CSS) +* [Codrops](http://tympanus.net/codrops/css_reference/) + +## Další čtení + +* [Pochopení priority v CSS: specifičnost, děditelnost a kaskáda](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Vybírání elementů pomocí atributů](https://css-tricks.com/almanac/selectors/a/attribute/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - překrývání obsahu](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) a [LESS](http://lesscss.org/) pro CSS pre-processing +* [CSS-Triky](https://css-tricks.com) -- cgit v1.2.3 From cdc8ff6e6cf1d14ec6cf4efd8820b46e64b8dc16 Mon Sep 17 00:00:00 2001 From: ven Date: Fri, 27 May 2016 11:24:54 +0200 Subject: Fix headers for cs-cz/css (#1771) --- cs-cz/css.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cs-cz/css.html.markdown b/cs-cz/css.html.markdown index a86302f7..54a0a08e 100644 --- a/cs-cz/css.html.markdown +++ b/cs-cz/css.html.markdown @@ -8,7 +8,8 @@ contributors: - ["Deepanshu Utkarsh", "https://github.com/duci9y"] translators: - ["Michal Martinek", "https://github.com/MichalMartinek"] -filename: learncss.css +lang: cs-cz +filename: learncss-cz.css --- V ranných dobách webu se nevyskytovaly žádné vizuální elementy, pouze čistý text, ale s vývojem webových browserů se staly stránky plné grafických prvků běžné. -- cgit v1.2.3 From 2b7eadaa80204deef013afcb6e6793b819dbab30 Mon Sep 17 00:00:00 2001 From: Jacob Ritchie Date: Fri, 27 May 2016 11:25:13 +0200 Subject: Edited tcl.html.markdown to fix a few bugs in the code and formatting error. (#1777) --- tcl.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index b90bd690..4ff1d3cc 100644 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -105,12 +105,14 @@ set greeting $greeting1$greeting2[set greeting3] # Command substitution should really be called script substitution, because an # entire script, not just a command, can be placed between the brackets. The # "incr" command increments the value of a variable and returns its value. + +set i 0 set greeting $greeting[ incr i incr i incr i ] - +# i is now 3 # backslash suppresses the special meaning of characters set amount \$16.42 @@ -149,9 +151,6 @@ set greeting "Hello, [set {first name}]" # To promote the words within a word to individual words of the current # command, use the expansion operator, "{*}". -``` - -```tcl set {*}{name Neo} # is equivalent to @@ -261,10 +260,11 @@ proc greet greeting\ name return\ \"Hello,\ \$name! # When the last parameter is the literal value, "args", it collects all extra # arguments when the command is invoked proc fold {cmd args} { - set res 0 + set res 1 foreach arg $args { set res [$cmd $res $arg] } + return res } fold ::tcl::mathop::* 5 3 3 ;# -> 45 -- cgit v1.2.3 From 9aea9445f2651e8cffb3831f452809e3ef5bb1dd Mon Sep 17 00:00:00 2001 From: MichalMartinek Date: Fri, 27 May 2016 11:26:56 +0200 Subject: Czech translation for JS (#1773) --- cs-cz/javascript.html.markdown | 550 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 550 insertions(+) create mode 100644 cs-cz/javascript.html.markdown diff --git a/cs-cz/javascript.html.markdown b/cs-cz/javascript.html.markdown new file mode 100644 index 00000000..1adc2e89 --- /dev/null +++ b/cs-cz/javascript.html.markdown @@ -0,0 +1,550 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +translators: + - ["Michal Martinek", "https://github.com/MichalMartinek"] +filename: javascript.js +--- + +JavaScript byl vytvořen Brendan Eichem v roce 1995 pro Netscape. Byl původně +zamýšlen jako jednoduchý skriptovací jazyk pro webové stránky, jako doplněk Javy, +která byla zamýšlena pro více komplexní webové aplikace, ale jeho úzké propojení +s webovými stránkami a vestavěná podpora v prohlížečích způsobila, že se stala +více běžná ve webovém frontendu než Java. + + +JavaScript není omezen pouze na webové prohlížeče, např. projekt Node.js, +který zprostředkovává samostatně běžící prostředí V8 JavaScriptového enginu z +Google Chrome se stává více a více oblíbený pro serverovou část webových aplikací. + +Zpětná vazba je velmi ceněná. Autora článku můžete kontaktovat (anglicky) na +[@adambrenecki](https://twitter.com/adambrenecki), nebo +[adam@brenecki.id.au](mailto:adam@brenecki.id.au), nebo mě, jakožto překladatele, +na [martinek@ludis.me](mailto:martinek@ludis.me). + +```js +// Komentáře jsou jako v zayku C. Jednořádkové komentáře začínájí dvojitým lomítkem, +/* a víceřádkové komentáře začínají lomítkem s hvězdičkou + a končí hvězdičkou s lomítkem */ + +// Vyrazu můžou být spuštěny pomocí ; +delejNeco(); + +// ... ale nemusí, středníky jsou automaticky vloženy kdekoliv, +// kde končí řádka, kromě pár speciálních případů +delejNeco() + +// Protože tyto případy můžou způsobit neočekávané výsledky, budeme +// středníky v našem návodu používat. + +///////////////////////////////// +// 1. Čísla, řetězce a operátory + +// JavaScript má jeden číselný typ (čímž je 64-bitový IEEE 754 double). +// Double má 52-bit přesnost, což je dostatečně přesné pro ukládání celých čísel +// do 9✕10¹⁵. +3; // = 3 +1.5; // = 1.5 + +// Základní matematické operace fungují, jak byste očekávali +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// Včetně dělení +5 / 2; // = 2.5 + +// Bitové operace také fungují; když provádíte bitové operace, desetinné číslo +// (float) se převede na celé číslo (int) se znaménkem *do* 32 bitů +1 << 2; // = 4 + +// Přednost se vynucuje závorkami. +(1 + 3) * 2; // = 8 + +// Existují 3 hodnoty mimo obor reálných čísel +Infinity; // + nekonečno; výsledek např. 1/0 +-Infinity; // - nekonečno; výsledek např. -1/0 +NaN; // výsledek např. 0/0, znamená, že výsledek není číslo ('Not a Number') + +// Také existují hodnoty typu bool +true; // pravda +false; // nepravda + +// Řetězce znaků jsou obaleny ' nebo ". +'abc'; +"Ahoj světe!"; + +// Negace se tvoří pomocí ! +!true; // = false +!false; // = true + +// Rovnost se porovnává === +1 === 1; // = true +2 === 1; // = false + +// Nerovnost zase pomocí !== +1 !== 1; // = false +2 !== 1; // = true + +// Další srovnávání +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// Řetězce znaků se spojují pomocí + +"Ahoj " + "světe!"; // = "Ahoj světe!" + +// a porovnávají se pomocí < nebo > +"a" < "b"; // = true + +// Rovnost s převodem typů se dělá pomocí == ... +"5" == 5; // = true +null == undefined; // = true + +// ...dokud nepoužijete === +"5" === 5; // = false +null === undefined; // = false + +// ...což může občas způsobit divné chování... +13 + !0; // 14 +"13" + !0; // '13true' + +// Můžeme přistupovat k jednotlivým znakům v řetězci pomocí charAt` +"Toto je řetězec".charAt(0); // = 'T' + +// ...nebo použít `substring` k získání podřetězce +"Ahoj světe".substring(0, 4); // = "Ahoj" + +// `length` znamená délka a je to vlastnost, takže nepoužívejte () +"Ahoj".length; // = 4 + +// Existují také typy `null` a `undefined`. +null; // značí, že žádnou hodnotu +undefined; // značí, že hodnota nebyla definovaná definovaná (ikdyž + // `undefined` je hodnota sama o sobě) + +// false, null, undefined, NaN, 0 and "" vrací nepravdu (false). Všechno ostatní +// vrací pravdu (true).. +// Všimněte si, že 0 vrací nepravdu, ale "0" vrací pravdu, ikdyž 0 == "0" +// vrací pravdu + +/////////////////////////////////// +// 2. Proměnné, pole a objekty + +// Proměnné jsou deklarovány pomocí slůvka `var`. JavaScript je dynamicky +// typovaný, takže nemusíme specifikovat typ. K přiřazení hodnoty se používá +// znak `=`. +var promenna = 5; + +// když vynecháte slůvko 'var' nedostanete chybovou hlášku... +jinaPromenna = 10; + +// ...ale vaše proměnná bude vytvořena globálně, bude vytvořena v globálním +// oblasti působnosti, ne jenom v lokálním tam, kde jste ji vytvořili + +// Proměnné vytvořené bez přiřazení obsahují hodnotu undefined. +var dalsiPromenna; // = undefined + +// Existuje kratší forma pro matematické operace na proměnné +promenna += 5; // se provede stejně jako promenna = promenna + 5; +// promenna je ted 10 +promenna *= 10; // teď je promenna rovna 100 + +// a tohle je způsob, jak přičítat a odečítat 1 +promenna++; // teď je promenna 101 +promenna--; // zpět na 100 + +// Pole jsou uspořádané seznamy hodnot jakéhokoliv typu +var mojePole = ["Ahoj", 45, true]; + +// Jednotlivé hodnoty jsou přístupné přes hranaté závorky. +// Členové pole se začínají počítat na nule. +myArray[1]; // = 45 + +// Pole je proměnlivé délky a členové se můžou měnit +myArray.push("Světe"); +myArray.length; // = 4 + +// Přidání/změna na specifickém indexu +myArray[3] = "Hello"; + +// JavaScriptové objekty jsou stejné jako asociativní pole v jinných programovacích +// jazycích: je to neuspořádaná množina páru hodnot - klíč:hodnota. +var mujObjekt = {klic1: "Ahoj", klic2: "světe"}; + +// Klíče jsou řetězce, ale nejsou povinné uvozovky, pokud jsou validní +// JavaScriptové identifikátory. Hodnoty můžou být jakéhokoliv typu- +var mujObjekt = {klic: "mojeHodnota", "muj jiny klic": 4}; + +// K hodnotám můžeme přistupovat opět pomocí hranatých závorek +myObj["muj jiny klic"]; // = 4 + +// ... nebo pokud je klíč platným identifikátorem, můžeme přistupovat k +// hodnotám i přes tečku +mujObjekt.klic; // = "mojeHodnota" + +// Objekty jsou měnitelné, můžeme upravit hodnoty, nebo přidat nové klíče. +myObj.mujDalsiKlic = true; + +// Pokud se snažíte přistoupit ke klíči, který není nastaven, dostanete undefined +myObj.dalsiKlic; // = undefined + +/////////////////////////////////// +// 3. Řízení toku programu + +// Syntaxe pro tuto sekci je prakticky stejná jako pro Javu + +// `if` (když) funguje, jak byste čekali. +var pocet = 1; +if (pocet == 3){ + // provede, když se pocet rovná 3 +} else if (pocet == 4){ + // provede, když se pocet rovná 4 +} else { + // provede, když je pocet cokoliv jinného +} + +// Stejně tak cyklus while +while (true){ + // nekonečný cyklus +} + +// Do-while cyklus je stejný jako while, akorát se vždy provede aspoň jednou +var vstup; +do { + vstup = nactiVstup(); +} while (!jeValidni(vstup)) + +// Cyklus for je stejný jako v Javě nebo jazyku C +// inicializace; podmínka pro pokračování; iterace. +for (var i = 0; i < 3; i++){ + // provede třikrát +} + +// Cyklus For-in iteruje přes každo vlastnost prototypu +var popis = ""; +var osoba = {prijmeni:"Paul", jmeno:"Ken", vek:18}; +for (var x in osoba){ + popis += osoba[x] + " "; +} + +//Když chcete iterovat přes vlastnosti, které jsou přímo na objektu a nejsou +//zděněné z prototypů, kontrolujte vlastnosti přes hasOwnProperty() +var popis = ""; +var osoba = {prijmeni:"Jan", jmeno:"Novák", vek:18}; +for (var x in osoba){ + if (osoba.hasOwnProperty(x)){ + popis += osoba[x] + " "; + } +} + +// for-in by neměl být použit pro pole, pokud záleží na pořadí indexů. +// Neexistuje jistota, že for-in je vrátí ve správném pořadí. + +// && je logické a, || je logické nebo +if (dum.velikost == "velký" && dum.barva == "modrá"){ + dum.obsahuje = "medvěd"; +} +if (barva == "červená" || barva == "modrá"){ + // barva je červená nebo modtrá +} + +// && a || jsou praktické i pro nastavení základních hodnot +var jmeno = nejakeJmeno || "default"; + + +// `switch` zkoumá přesnou rovnost (===) +// Používejte 'break;' po každé možnosti, jinak se provede i možnost za ní. +znamka = 'B'; +switch (znamka) { + case 'A': + console.log("Výborná práce"); + break; + case 'B': + console.log("Dobrá práce"); + break; + case 'C': + console.log("Dokážeš to i lépe"); + break; + default: + console.log("Ale ne"); + break; +} + +//////////////////////////////////////////////////////// +// 4. Funckce, Oblast platnosti (scope) a Vnitřní funkce + +// JavaScriptové funkce jsou definovány slůvkem `function`. +function funkce(text){ + return text.toUpperCase(); +} +funkce("něco"); // = "NĚCO" + +// Dávejte si pozor na to, že hodnota k vrácení musí začínat na stejné řádce +// jako slůvko return, jinak se vrátí 'undefined', kvůli automatickému vkládání +// středníků. Platí to zejména pro Allmanův styl zápisu. + +function funkce() +{ + return // <- zde je automaticky vložen středník + { + tohleJe: "vlastnost objektu" + } +} +funkce(); // = undefined + +// JavaScriptové funkce jsou objekty, takže můžou být přiřazeny různým proměnným +// a předány dalším funkcím jako argumenty, na příklad: +function funkce(){ + // tento kód bude zavolán za 5 vteřin +} +setTimeout(funkce, 5000); +// Poznámka: setTimeout není část JS jazyka, ale funkce poskytována +// prohlížeči a NodeJS + +// Objekty funkcí nemusíme ani deklarovat pomocí jména, můžeme je napsat jako +// ananymní funkci přímo vloženou jako argument +setTimeout(function(){ + // tento kód bude zavolán za 5 vteřin +}, 5000); + +// JavaScript má oblast platnosti funkce, funkce ho mají, ale jiné bloky ne +if (true){ + var i = 5; +} +i; // = 5 - ne undefined, jak byste očekávali v jazyku, kde mají bloky svůj +// rámec působnosti + +// Toto je běžný model,který chrání před únikem dočasných proměnných do +//globální oblasti +(function(){ + var docasna = 5; + // Můžeme přistupovat k globálního oblasti přes přiřazování globalním + // objektům. Ve webovém prohlížeči je to vždy 'window`. Globální objekt + // může mít v jiných prostředích jako Node.js jinné jméno. + window.trvala = 10; +})(); +docasna; // způsobí ReferenceError +trvala; // = 10 + +// Jedna z nejvice mocných vlastnosti JavaScriptu je vnitřní funkce. Je to funkce +// definovaná v jinné funkci, vnitřní funkce má přístup ke všem proměnným ve +// vnější funkci, dokonce i poté, co funkce skončí +function ahojPoPetiVterinach(jmeno){ + var prompt = "Ahoj, " + jmeno + "!"; + // Vnitřní funkce je dána do lokální oblasti platnosti, jako kdyby byla + // deklarovaná slůvkem 'var' + function vnitrni(){ + alert(prompt); + } + setTimeout(vnitrni, 5000); + // setTimeout je asynchronní, takže funkce ahojPoPetiVterinach se ukončí + // okamžitě, ale setTimeout zavolá funkci vnitrni až poté. Avšak protože + // vnitrni je definována přes ahojPoPetiVterinach, má pořád přístup k + // proměnné prompt, když je konečně zavolána. +} +ahojPoPetiVterinach("Adam"); // otevře popup s "Ahoj, Adam!" za 5s + +/////////////////////////////////////////////////// +// 5. Více o objektech, konstuktorech a prototypech + +// Objekty můžou obsahovat funkce +var mujObjekt = { + mojeFunkce: function(){ + return "Ahoj světe!"; + } +}; +mujObjekt.mojeFunkce(); // = "Ahoj světe!" + +// Když jsou funkce z objektu zavolány, můžou přistupovat k objektu přes slůvko +// 'this'' +var mujObjekt = { + text: "Ahoj světe!", + mojeFunkce: function(){ + return this.text; + } +}; +mujObjekt.mojeFunkce(); // = "Ahoj světe!" + +// Slůvko this je nastaveno k tomu, kde je voláno, ne k tomu, kde je definováno +// Takže naše funkce nebude fungovat, když nebude v kontextu objektu. +var mojeFunkce = mujObjekt.mojeFunkce; +mojeFunkce(); // = undefined + +// Opačně, funkce může být přiřazena objektu a může přistupovat k objektu přes +// this, i když nebyla přímo v definici- +var mojeDalsiFunkce = function(){ + return this.text.toUpperCase(); +} +mujObjekt.mojeDalsiFunkce = mojeDalsiFunkce; +mujObjekt.mojeDalsiFunkce(); // = "AHOJ SVĚTE!" + +// Můžeme také specifikovat, v jakém kontextu má být funkce volána pomocí +// `call` nebo `apply`. + +var dalsiFunkce = function(s){ + return this.text + s; +} +dalsiFunkce.call(mujObjekt, " A ahoj měsíci!"); // = "Ahoj světe! A ahoj měsíci!" + +// Funkce `apply`je velmi podobná, akorát bere jako druhý argument pole argumentů +dalsiFunkce.apply(mujObjekt, [" A ahoj slunce!"]); // = "Ahoj světe! A ahoj slunce!" + +// To je praktické, když pracujete s funkcí, která bere sekvenci argumentů a +// chcete předat pole. + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// Ale `call` a `apply` jsou pouze dočasné. Pokud je chcete připojit trvale +// použijte `bind`. + +var pripojenaFunkce = dalsiFunkce.bind(mujObjekt); +pripojenaFunkce(" A ahoj Saturne!"); // = "Ahoj světe! A ahoj Saturne!" + +// `bind` může být použito čatečně částečně i k používání + +var nasobeni = function(a, b){ return a * b; } +var zdvojeni = nasobeni.bind(this, 2); +zdvojeni(8); // = 16 + +// Když zavoláte funkci se slůvkem 'new', vytvoří se nový objekt a +// a udělá se dostupný funkcím skrz slůvko 'this'. Funkcím volaným takto se říká +// konstruktory + +var MujKonstruktor = function(){ + this.mojeCislo = 5; +} +mujObjekt = new MujKonstruktor(); // = {mojeCislo: 5} +mujObjekt.mojeCislo; // = 5 + +// Každý JsavaScriptový objekt má prototyp. Když budete přistupovat k vlasnosti +// objektu, který neexistuje na objektu, tak se JS koukne do prototypu. + +// Některé JS implementace vám umožní přistupovat k prototypu přes magickou +// vlastnost '__proto__'. I když je toto užitečné k vysvětlování prototypů, není +// to součást standardu, ke standartní způsobu k používání prototypu se dostaneme +// později. +var mujObjekt = { + mujText: "Ahoj svete!" +}; +var mujPrototyp = { + smyslZivota: 42, + mojeFunkce: function(){ + return this.mujText.toLowerCase() + } +}; + +mujObjekt.__proto__ = mujPrototyp; +mujObjekt.smyslZivota; // = 42 + +// Toto funguje i pro funkce +mujObjekt.mojeFunkce(); // = "Ahoj světe!" + +// Samozřejmě, pokud není vlastnost na vašem prototypu, tak se hledá na +// prototypu od prototypu atd. +mujPrototyp.__proto__ = { + mujBoolean: true +}; +mujObjekt.mujBoolean; // = true + + +// Zde neni žádné kopírování; každý objekt ukládá referenci na svůj prototyp +// Toto znamená, že můžeme měnit prototyp a změny se projeví všude +mujPrototyp.smyslZivota = 43; +mujObjekt.smyslZivota // = 43 + +// Zmínili jsme již předtím, že '__proto__' není ve standardu a není cesta, jak +// měnit prototyp existujícího objektu. Avšak existují možnosti, jak vytvořit +// nový objekt s daným prototypem + +// První je Object.create, což je nedávný přídavek do JS a není dostupný zatím +// ve všech implementacích. +var mujObjekt = Object.create(mujPrototyp); +mujObjekt.smyslZivota // = 43 + +// Druhý způsob, který funguje všude je pomocí konstuktoru. Konstruktor má +// vlastnost jménem prototype. Toto *není* prototyp samotného konstruktoru, ale +// prototyp nového objektu. +MujKonstruktor.prototype = { + mojeCislo: 5, + ziskejMojeCislo: function(){ + return this.mojeCislo; + } +}; +var mujObjekt2 = new MujKonstruktor(); +mujObjekt2.ziskejMojeCislo(); // = 5 +mujObjekt2.mojeCislo = 6 +mujObjekt2.ziskejMojeCislo(); // = 6 + +// Vestavěnné typy jako čísla nebo řetězce mají také konstruktory, které vytváří +// ekvivalentní obalovací objekty (wrappery). +var mojeCislo = 12; +var mojeCisloObj = new Number(12); +mojeCislo == mojeCisloObj; // = true + +// Avšak nejsou úplně přesně stejné +typeof mojeCislo; // = 'number' +typeof mojeCisloObj; // = 'object' +mojeCislo === mojeCisloObj; // = false +if (0){ + // Tento kód se nespustí, protože 0 je nepravdivá (false) +} + +// Avšak, obalovací objekty a normální vestavěnné typy sdílejí prototyp, takže +// můžete přidat funkcionalitu k řetězci +String.prototype.prvniZnak = function(){ + return this.charAt(0); +} +"abc".prvniZnak(); // = "a" + +// Tento fakt je často používán v polyfillech, což je implementace novějších +// vlastností JavaScriptu do starších variant, takže je můžete používat třeba +// ve starých prohlížečích + +// Pro příkklad, zmínili jsme, že Object.create není dostupný ve všech +// implementacích, můžeme si avšak přidat pomocí polyfillu +if (Object.create === undefined){ // nebudeme ho přepisovat, když existuje + Object.create = function(proto){ + // vytvoříme dočasný konstruktor + var Constructor = function(){}; + Constructor.prototype = proto; + // ten použijeme k vytvoření nového s prototypem + return new Constructor(); + } +} +``` + +## Kam dál + +[Mozilla Developer +Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) obsahuje +perfektní dokumentaci pro JavaScript, který je používaný v prohlížečích. Navíc +je to i wiki, takže jakmile se naučíte více, můžete pomoci ostatním, tím, že +přispějete svými znalostmi. + +MDN's [A re-introduction to +JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +pojednává o konceptech vysvětlených zde v mnohem větší hloubce. Tento návod +pokrývá hlavně JavaScript sám o sobě. Pokud se chcete naučit více, jak se používá +na webových stránkách, začněte tím, že se kouknete na [DOM](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) + +[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) je varianta tohoto +návodu i s úkoly- + +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) je sbírka +příkladů těch nejvíce nepředvídatelných částí tohoto jazyka. + +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) +je klasická výuková kniha. + +Jako dodatek k přímým autorům tohoto článku, některý obsah byl přizpůsoben z +Pythoního tutoriálu od Louie Dinh na této stráce, a z [JS +Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +z Mozilla Developer Network. -- cgit v1.2.3 From 1288ddaac3e8ed928deee7cc73694503e34191c5 Mon Sep 17 00:00:00 2001 From: ven Date: Fri, 27 May 2016 11:27:36 +0200 Subject: Fix cs-cz/javascript headers (#1773) --- cs-cz/javascript.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cs-cz/javascript.html.markdown b/cs-cz/javascript.html.markdown index 1adc2e89..0b053595 100644 --- a/cs-cz/javascript.html.markdown +++ b/cs-cz/javascript.html.markdown @@ -5,7 +5,8 @@ contributors: - ["Ariel Krakowski", "http://www.learneroo.com"] translators: - ["Michal Martinek", "https://github.com/MichalMartinek"] -filename: javascript.js +lang: cs-cz +filename: javascript-cz.js --- JavaScript byl vytvořen Brendan Eichem v roce 1995 pro Netscape. Byl původně -- cgit v1.2.3 From 4ba201c541fb00029be1b6d245be7b4204dccf6c Mon Sep 17 00:00:00 2001 From: Jhoon Saravia Date: Fri, 27 May 2016 02:30:17 -0700 Subject: [groovy/es] Groovy translated to Spanish (#1791) * Fix extra character on Groovy documentation * Translate Groovy to Spanish --- es-es/groovy-es.html.markdown | 433 ++++++++++++++++++++++++++++++++++++++++++ groovy.html.markdown | 2 +- 2 files changed, 434 insertions(+), 1 deletion(-) create mode 100644 es-es/groovy-es.html.markdown diff --git a/es-es/groovy-es.html.markdown b/es-es/groovy-es.html.markdown new file mode 100644 index 00000000..8018fba7 --- /dev/null +++ b/es-es/groovy-es.html.markdown @@ -0,0 +1,433 @@ +--- +language: Groovy +contributors: + - ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"] +translators: + - ["Jhoon Saravia", "https://github.com/jhoon"] +lang: es-es +--- + +Groovy - Un lenguaje dinámico para la plataforma Java [Leer más aquí.](http://www.groovy-lang.org/) + +```groovy + +/* + Hora de configurar: + + 1) Instala GVM - http://gvmtool.net/ + 2) Instala Groovy: gvm install groovy + 3) Inicia la consola de groovy escribiendo: groovyConsole + +*/ + +// Los comentarios de una sola línea inician con dos barras inclinadas +/* +Los comentarios multilínea se ven así. +*/ + +// Hola Mundo +println "Hola mundo!" + +/* + Variables: + + Puedes asignar valores a variables para usarlas después +*/ + +def x = 1 +println x + +x = new java.util.Date() +println x + +x = -3.1499392 +println x + +x = false +println x + +x = "Groovy!" +println x + +/* + Mapas y Colecciones +*/ + +// Creando una lista vacía +def technologies = [] + +/*** Agregando elementos a la lista ***/ + +// Como si fuera Java +technologies.add("Grails") + +// Doble símbolo de menor agrega un elemento y, además, retorna la lista +technologies << "Groovy" + +// Agregando múltiples elementos +technologies.addAll(["Gradle","Griffon"]) + +/*** Quitando elementos de la lista ***/ + +// Como si fuera Java +technologies.remove("Griffon") + +// La resta también funciona +technologies = technologies - 'Grails' + +/*** Iterando Listas ***/ + +// Para iterar sobre los elementos de una Lista +technologies.each { println "Technology: $it"} +technologies.eachWithIndex { it, i -> println "$i: $it"} + +/*** Revisando los contenidos de una Lista ***/ + +// Evaluar si la lista contiene elemento(s) (boolean) +contained = technologies.contains( 'Groovy' ) + +// O +contained = 'Groovy' in technologies + +// Evaluar por múltiples contenidos +technologies.containsAll(['Groovy','Grails']) + +/*** Ordenando Listas ***/ + +// Para ordenar una Lista (modifica la lista original) +technologies.sort() + +// Para ordenarla sin modificar la original, se puede hacer: +sortedTechnologies = technologies.sort( false ) + +/*** Manipulando Listas ***/ + +// Reemplazar todos los elementos en la lista +Collections.replaceAll(technologies, 'Gradle', 'gradle') + +// Mezclar una lista +Collections.shuffle(technologies, new Random()) + +// Limpiar una lista +technologies.clear() + +// Creando un mapa vacío +def devMap = [:] + +// Agregando valores +devMap = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] +devMap.put('lastName','Perez') + +// Iterar sobre los elementos del mapa +devMap.each { println "$it.key: $it.value" } +devMap.eachWithIndex { it, i -> println "$i: $it"} + +// Evaluar si el mapa contiene una llave +assert devMap.containsKey('name') + +// Evaluar si el mapa contiene un valor +assert devMap.containsValue('Roberto') + +// Para obtener las llaves del mapa +println devMap.keySet() + +// Para obtener los valores del mapa +println devMap.values() + +/* + Groovy Beans + + GroovyBeans son JavaBeans pero usando una sintaxis mucho más simple + + Cuando Groovy es compilado a código de bytes, las siguientes reglas son usadas: + + * Si el nombre es declarado con un modificador de acceso (public, private o + protected), entonces se genera un campo. + + * Un nombre declarado sin modificador de acceso genera un campo privado con + un getter y un setter públicos (ej: una propiedad) + + * Si una propiedad es declarada como final, entonces el campo privado es creado + como final y no se genera un setter. + + * Puedes declarar una propiedad y también sus propios getter y setter. + + * Puedes declarar una propiedad y un campo del mismo nombre, en ese caso, la + propiedad usará ese campo. + + * Si quieres una propiedad private o proteceted, tienes que proveer tus propios + getter y setter, los cuales deben ser declarados private o protected. + + * Si accedes a una propiedad desde dentro de la clase, la propiedad es definida + en tiempo de compilación con this implícito o explícito (por ejemplo, this.foo + o simplemente foo), Groovy accederá al campo directamente en vez de usar el + getter y setter. + + * Si accedes a una propiedad que no existe usando foo explícito o implícito, entonces + Groovy accederá a la propiedad a través de la clase meta, que puede fallar en + tiempo de ejecución. + +*/ + +class Foo { + // propiedad de solo lectura + final String name = "Roberto" + + // propiedad de solo lectura, con getter público y setter como protected + String language + protected void setLanguage(String language) { this.language = language } + + // propiedad de tipo dinámico + def lastName +} + +/* + Derivación Lógica e Iteraciones +*/ + +// Groovy soporta la clásica sintaxis de if - else +def x = 3 + +if(x==1) { + println "One" +} else if(x==2) { + println "Two" +} else { + println "X greater than Two" +} + +// Groovy también soporta el uso del operador ternario: +def y = 10 +def x = (y > 1) ? "worked" : "failed" +assert x == "worked" + +// ¡Groovy también soporta 'El Operador Elvis'! +// En lugar de usar el operador ternario: + +displayName = user.name ? user.name : 'Anonymous' + +// Podemos escribirlo así: +displayName = user.name ?: 'Anonymous' + +// Iteración con For +// Iterando en un rango numérico +def x = 0 +for (i in 0 .. 30) { + x += i +} + +// Iterando sobre una lista +x = 0 +for( i in [5,3,2,1] ) { + x += i +} + +// Iterando sobre un arreglo +array = (0..20).toArray() +x = 0 +for (i in array) { + x += i +} + +// Iterando sobre un mapa +def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] +x = 0 +for ( e in map ) { + x += e.value +} + +/* + Operadores + + Para la lista de los operadores que Groovy soporta, visita: + http://www.groovy-lang.org/operators.html#Operator-Overloading + + Operadores Groovy útiles +*/ +// Operador de propagación: invocar una acción en todos los elementos de un objeto agregado. +def technologies = ['Groovy','Grails','Gradle'] +technologies*.toUpperCase() // equivale a: technologies.collect { it?.toUpperCase() } + +// Operador de navegación segura: usado para evitar un NullPointerException. +def user = User.get(1) +def username = user?.username + + +/* + Closures + Un Closure en Groovy es como un "bloque de código" o un puntero a un método. Es una + porci´øn de código que es definida y ejecutada en un punto futuro en el tiempo. + + Más información en: http://www.groovy-lang.org/closures.html +*/ +// Ejemplo: +def clos = { println "Hello World!" } + +println "Executing the Closure:" +clos() + +// Pasando parámetros a un closure +def sum = { a, b -> println a+b } +sum(2,4) + +// Los Closures pueden referir a variables no listadas en sus listas de parámetros +def x = 5 +def multiplyBy = { num -> num * x } +println multiplyBy(10) + +// Si tienes un Closure que toma un solo argumento, puedes omitir la +// definición del parámetro en el Closure +def clos = { print it } +clos( "hi" ) + +/* + Groovy puede memorizar los resultados de un Closure [1][2][3] +*/ +def cl = {a, b -> + sleep(3000) // simula algún proceso que consume tiempo + a + b +} + +mem = cl.memoize() + +def callClosure(a, b) { + def start = System.currentTimeMillis() + mem(a, b) + println "Inputs(a = $a, b = $b) - took ${System.currentTimeMillis() - start} msecs." +} + +callClosure(1, 2) +callClosure(1, 2) +callClosure(2, 3) +callClosure(2, 3) +callClosure(3, 4) +callClosure(3, 4) +callClosure(1, 2) +callClosure(2, 3) +callClosure(3, 4) + +/* + Expando + + La clase Expando es un bean dinámico para que podamos agregar propiedades y closures + como métodos a una instancia de esta clase + + http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html +*/ + def user = new Expando(name:"Roberto") + assert 'Roberto' == user.name + + user.lastName = 'Pérez' + assert 'Pérez' == user.lastName + + user.showInfo = { out -> + out << "Name: $name" + out << ", Last name: $lastName" + } + + def sw = new StringWriter() + println user.showInfo(sw) + + +/* + Metaprogramación (MOP) +*/ + +// Usando ExpandoMetaClass para agregar comportamiento +String.metaClass.testAdd = { + println "we added this" +} + +String x = "test" +x?.testAdd() + +// Interceptando llamadas a métodos +class Test implements GroovyInterceptable { + def sum(Integer x, Integer y) { x + y } + + def invokeMethod(String name, args) { + System.out.println "Invoke method $name with args: $args" + } +} + +def test = new Test() +test?.sum(2,3) +test?.multiply(2,3) + +// Groovy soporta propertyMissing para lidiar con intentos de resolución de propiedades. +class Foo { + def propertyMissing(String name) { name } +} +def f = new Foo() + +assertEquals "boo", f.boo + +/* + TypeChecked y CompileStatic + Groovy, por naturaleza, es y siempre será un lenguaje dinámico pero soporta + typechecked y compilestatic + + Más información: http://www.infoq.com/articles/new-groovy-20 +*/ +// TypeChecked +import groovy.transform.TypeChecked + +void testMethod() {} + +@TypeChecked +void test() { + testMeethod() + + def name = "Roberto" + + println naameee + +} + +// Otro ejemplo: +import groovy.transform.TypeChecked + +@TypeChecked +Integer test() { + Integer num = "1" + + Integer[] numbers = [1,2,3,4] + + Date date = numbers[1] + + return "Test" + +} + +// ejemplo de CompileStatic: +import groovy.transform.CompileStatic + +@CompileStatic +int sum(int x, int y) { + x + y +} + +assert sum(2,5) == 7 + + +``` + +## Más recursos + +[Documentación de Groovy](http://www.groovy-lang.org/documentation.html) + +[Consola Web de Groovy](http://groovyconsole.appspot.com/) + +Únete a un [Groovy user group](http://www.groovy-lang.org/usergroups.html) + +## Libros + +* [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook) + +* [Groovy in Action] (http://manning.com/koenig2/) + +* [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do) + +[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ +[2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize +[3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html diff --git a/groovy.html.markdown b/groovy.html.markdown index 94678c39..a3a45757 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -99,7 +99,7 @@ technologies.sort() // To sort without mutating original, you can do: sortedTechnologies = technologies.sort( false ) -/*** Manipulating Lists ***/e +/*** Manipulating Lists ***/ //Replace all elements in the list Collections.replaceAll(technologies, 'Gradle', 'gradle') -- cgit v1.2.3 From bd07416a0e57e595a8368ed9c7287a06f7549e55 Mon Sep 17 00:00:00 2001 From: ven Date: Fri, 27 May 2016 11:30:43 +0200 Subject: Fix es-es/groovy headers (#1791) --- es-es/groovy-es.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/es-es/groovy-es.html.markdown b/es-es/groovy-es.html.markdown index 8018fba7..799fc609 100644 --- a/es-es/groovy-es.html.markdown +++ b/es-es/groovy-es.html.markdown @@ -5,6 +5,7 @@ contributors: translators: - ["Jhoon Saravia", "https://github.com/jhoon"] lang: es-es +filename: groovy-es.html --- Groovy - Un lenguaje dinámico para la plataforma Java [Leer más aquí.](http://www.groovy-lang.org/) -- cgit v1.2.3 From 964273453ae062423acbb8dc391120519218278d Mon Sep 17 00:00:00 2001 From: Christian Albrecht Date: Fri, 27 May 2016 11:31:23 +0200 Subject: added rust in german (#1794) --- de-de/rust-de.html.markdown | 352 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 352 insertions(+) create mode 100644 de-de/rust-de.html.markdown diff --git a/de-de/rust-de.html.markdown b/de-de/rust-de.html.markdown new file mode 100644 index 00000000..2b1471a8 --- /dev/null +++ b/de-de/rust-de.html.markdown @@ -0,0 +1,352 @@ +--- +language: rust +contributors: + - ["P1start", "http://p1start.github.io/"] +translators: + - ["Christian Albrecht", "https://github.com/coastalchief"] +lang: de-de +filename: lernerust-de.rs +--- + +Rust ist eine Programmiersprache von Mozilla Research. +Rust vereint Sicherheit, Nebenläufigkeit und eine hohe Praxistauglichkeit. + +Sicherheit bedeuted, dass Programmierfehler ausgeschlossen werden, die zu +Speicherzugriffsfehlern führen könnten. Das funktioniert u.a. dadurch, dass +es keinen Garbage Collector gibt, sondern ein besonderes Typsystem. + +Das erste Release von Rust, 0.1, wurde im Januar 2012 veröffentlicht. +In den nächsten drei Jahren wurde die Sprache so schnell und aktiv weiter- +entwickelt, dass es einfach keine stabile gab und geraten wurde den +nightly build zu nutzen. + +Am 15. Mai 2015 wurde Rust 1.0 freigegeben, und zwar mit der Garantie einer +Abwärtskompatabilität. Verbesserungen der Kompilierzeit und andere Compiler +verbesserungen finden im Moment im nightly build statt. Von Rust gibt es im +Moment ungefähr alle sechs Wochen ein Release. Rust 1.1 beta wurde zusammen +mit dem 1.0 Release zur Verfügung gestellt. + +Obwohl Rust eine ziemlich low-level Sprache ist, vereint sie Ansätze aus +der Welt der funktionalen, der objektorientierten und der nebenläufigen +Programmierung. Dadurch kann in Rust nicht nur schnell, sondern auch sehr +effizient entwickelt werden. + + +```rust +// Dies ist ein Kommentar. Ein einzeiliger... +/* ...und multi-zeilen Kommentare sehe so aus */ + +///////////////////// +// 0. Installation // +///////////////////// +// Stabile binaries gibt es unter https://www.rust-lang.org/downloads.html + +// Programme werden in .rs Dateien geschrieben also zum Beispiel +// "main.rs" und dann kompiliert "rustc main.rs" +// Herauskommt eine ausführbare Datei "main" +// Für dieses Tutorial reicht das vollkommen aus. Für größere Projekte +// sollte das unten beschriebene Cargo angeschaut werden. + +// Cargo +// Ein gängiges Tool um Rust Projekte zu verwalten ist Cargo. Es macht im +// wesentlichen drei Dinge: Code bauen, Dependencies laden und +// Dependencies bauen. +// Um ein vorhandenes Projekt zu cargo-ifyen müssen drei Dinge gemacht werden +// * Erstelle eine Cargo.toml Konfigurationsdatei +// * Verschiebe Source Code in ein src Verzeichnis +// * Lösche das alte Executable +// +// 'cargo build' baut den Code +// 'cargo run' baut und führt das Programm aus + +/////////////// +// 1. Basics // +/////////////// + +// Funktionen +// `i32` ist der Typ für einen 32-bit signed Integer +fn add2(x: i32, y: i32) -> i32 { + // Impliziter return (kein Semikolon) + x + y +} + +// Main Funktion +fn main() { + // Zahlen // + + // Unveränderliche Variable + let x: i32 = 1; + + // Integer/float Suffixe + let y: i32 = 13i32; + let f: f64 = 1.3f64; + + // Type inference + Meistens kann der Rust Compiler selbst schlussfolgern, von welchem + Typ eine Variable ist, so dass man den Typ nicht explizit angeben muss. + In diesem Tutorial werden Typen explizit angegeben, um zu demonstrieren, + welche Möglichkeiten es gibt. Wenn man damit vertraut ist, kann man die + Typen auch weglassen und die Type Inference hilft dann im Hintergrund. + + let implicit_x = 1; + let implicit_f = 1.3; + + // Arithmetik + let sum = x + y + 13; + + // Veränderliche Variable + let mut mutable = 1; + mutable = 4; + mutable += 2; + + // Strings // + // Strings gibt es in zwei Typen: &str und String + + // Zunächst &str + let x: &str = "hello world!"; + + // Ausgabe + println!("{} {}", f, x); // 1.3 hello world + + // Ein `String` – heap-allokierter String + let s: String = "hello world".to_string(); + + // Ein string slice – ist eigentlich ein unveränderlicher Pointer + // auf einen String – er enthält nicht den Inhalt den String, sondern + // eben nur den Pointer auf etwas, dass den Inhalt kennt: + // (In diesem Fall, `s`) + let s_slice: &str = &s; + + // Ausgabe + println!("{} {}", s, s_slice); // hello world hello world + + // Vektoren/Arrays // + + // Ein Array mit fester Größe + let vier_ints: [i32; 4] = [1, 2, 3, 4]; + + // Ein dynamisches Array (Vektorentor) + let mut vector: Vec = vec![1, 2, 3, 4]; + vector.push(5); + + // Ein slice – eine unveränderliche Ansicht, oder Pointer auf einen + // Vektor oder ein Array. Wie bei Strings, nur eben bei Vektoren + let slice: &[i32] = &vector; + + // Benutze `{:?}` um eine debug Ausgabe zu erzeugen + println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + + // Tuples // + + // Ein Tuple ist eine Liste mit fester Größe und kann Werte + // von unterschiedlichen Typen enthalten + let x: (i32, &str, f64) = (1, "hello", 3.4); + + // Werte aus Vektor mit `let` destrukturieren + let (a, b, c) = x; + println!("{} {} {}", a, b, c); // 1 hello 3.4 + + // Vektor Indizes + println!("{}", x.1); // hello + + ////////////// + // 2. Typen // + ////////////// + + // Struct + struct Punkt { + x: i32, + y: i32, + } + + let anfang: Punkt = Punkt { x: 0, y: 0 }; + + // Ein struct mit unbenannten Felder heisst ‘tuple struct’ + struct Punkt2(i32, i32); + + let anfang2 = Punkt2(0, 0); + + // Einfache enum, so ähnlich wie in C + enum Richtung { + Links, + Rechts, + Hoch, + Runter, + } + + let hoch = Richtung::Hoch; + + // Enum mit Feldern + enum OptionalI32 { + EinI32(i32), + Nix, + } + + let zwei: OptionalI32 = OptionalI32::EinI32(2); + let nix = OptionalI32::Nix; + + // Generics // + + struct Foo { bar: T } + + // In der Standard Bibliothek heisst das hier `Option` + enum Optional { + EinWert(T), + KeinWert, + } + + // Methoden // + + impl Foo { + // Methoden erwarten einen `self` Parameter + fn get_bar(self) -> T { + self.bar + } + } + + let a_foo = Foo { bar: 1 }; + println!("{}", a_foo.get_bar()); // 1 + + // Traits (vergleichbar mit Interfaces oder Typklassen in anderen Sprachen) + // In Traits werden nur Method Signaturen erstellt. + // Die Implementierung findet im impl statt. + + trait MacheIrgendwas { + fn macheIrgendwas(self) -> Option; + } + + impl MacheIrgendwas for Foo { + fn macheIrgendwas(self) -> Option { + mache(self.bar) + } + } + + let anderes_foo = Foo { bar: 1 }; + println!("{:?}", anderes_foo.macheIrgendwas()); // mache(1) + + ///////////////////////// + // 3. Pattern matching // + ///////////////////////// + + let foo = OptionalI32::AnI32(1); + match foo { + OptionalI32::EinI32(n) => println!("hier ist ein i32: {}", n), + OptionalI32::Nix => println!("hier ist nix!"), + } + + // Advanced pattern matching + struct FooBar { x: i32, y: OptionalI32 } + let bar = FooBar { x: 15, y: OptionalI32::EinI32(32) }; + + match bar { + FooBar { x: 0, y: OptionalI32::EinI32(0) } => + println!("Beide Zahlen sind 0!"), + FooBar { x: n, y: OptionalI32::EinI32(m) } if n == m => + println!("Beide Zahlen sind gleich"), + FooBar { x: n, y: OptionalI32::EinI32(m) } => + println!("Zahlen sind unterschiedlich: {} {}", n, m), + FooBar { x: _, y: OptionalI32::Nix } => + println!("Die zweite Zahl ist leer!"), + } + + ///////////////////// + // 4. Control // + ///////////////////// + + // `for` Schleife/Iterationen + let array = [1, 2, 3]; + for i in array.iter() { + println!("{}", i); + } + + // Ranges + for i in 0u32..10 { + print!("{} ", i); + } + println!(""); + // gibt aus: `0 1 2 3 4 5 6 7 8 9 ` + + // `if` + if 1 == 1 { + println!("Mathe ist klappt!"); + } else { + println!("Oh nein..."); + } + + // `if` als Ausdruck + let wert = if true { + "gut" + } else { + "schlecht" + }; + + // `while` Schleife + while 1 == 1 { + println!("Läuft..."); + } + + // Unendliche Schleifen + loop { + println!("Hello!"); + } + + ///////////////////////////////////// + // 5. Speichersicherheit & Pointer // + ///////////////////////////////////// + + // Owned pointer – nur eine Sache kann einen Pointer 'besitzen'. + // Das heisst, wenn das Objekt `Box` seinen scope verlässt oder verliert, + // wird es automatisch im Speicher de-allokiert. + let mut mine: Box = Box::new(3); + // Jetzt wird die Box dereferenziert + *mine = 5; + // Jetzt geht `mine` in den Besitz von `now_its_mine` über. + // `mine` wird verschoben. + let mut now_its_mine = mine; + *now_its_mine += 2; + + println!("{}", now_its_mine); // ergibt 7 + + // Das würde nicht kompilieren, da `now_its_mine` jetzt den Pointer besitzt + // println!("{}", mine); + + // Reference – ein unveränderlicher Pointer der fremde Daten referenziert + // Wenn eine Referenz auf einen Wert gesetzt wird, heisst das, dass man den + // Wert ausleiht (‘borrowed’). + // Ein ausgeliehener Wert ist unveränderlich und lebt solange wie der + // Scope existiert, in dem er erstellt wurde. + let mut var = 4; + var = 3; + let ref_var: &i32 = &var; + + println!("{}", var); // Anders als `box`, `var` kann hier weiter verwendet werden + println!("{}", *ref_var); + // var = 5; // das kompiliert nicht, da `var` ausgeliehen ist + // *ref_var = 6; // das kompiliert auch nicht, da `ref_var` eine unveränderliche Referenz ist + + // Veränderliche Referenzen + // Solange ein Wert veränderlich geliehen wurde, kann man nicht darauf zugreifen + let mut var2 = 4; + let ref_var2: &mut i32 = &mut var2; + *ref_var2 += 2; // '*' wird benutzt um auf den veränderlich geliehenen Wert var2 zu zeigen + + println!("{}", *ref_var2); // 6 , //var2 würde nicht kompilieren. //ref_var2 ist vom Typ &mut i32, also //stores a reference to an i32 not the value. + // var2 = 2; // würde das nicht kompilieren, da `var2` geliehen wurde. +} +``` + +## Weitere Informationen + +Es gibt eine ganze Reihe mehr über Rust zu sagen. Dieser Text gibt nur einen +Einblick in die wichtigsten Sprachmerkmale. +Um mehr über Rust zu erfahren, sollte man mit den folgenden Stellen starten: + +1. Englisch: + * [Die offizielle Rust Webseite](http://rust-lang.org) + * [The Rust Programming Language](https://doc.rust-lang.org/stable/book/README.html) + * [/r/rust](http://reddit.com/r/rust) + * the #rust channel on irc.mozilla.org + +2. Deutsch + * [Rust Wikipedia](https://de.wikipedia.org/wiki/Rust_(Programmiersprache)) + * [Artikel im LinuxMagazin](http://www.linux-magazin.de/Ausgaben/2015/08/Rust) -- cgit v1.2.3 From e1dc35b3501ba25780a34a1f9c14d3b165ab0ead Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Antonio=20Chio?= Date: Fri, 27 May 2016 09:12:43 -0500 Subject: Update javascript-es.html.markdown (#2267) --- es-es/javascript-es.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index 34428f42..31512dc4 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -16,7 +16,7 @@ con Java para aplicaciones más complejas. Debido a su integracion estrecha con web y soporte por defecto de los navegadores modernos se ha vuelto mucho más común para front-end que Java. -Aunque JavaScript no sólo se limita a los navegadores web: Node.js, Un proyecto que proporciona un entorno de ejecución independiente para el motor V8 de Google Chrome, se está volviendo más y más popular. +Sin embargo, JavaScript no sólo se limita a los navegadores web: Node.js, un proyecto que proporciona un entorno de ejecución independiente para el motor V8 de Google Chrome, se está volviendo más y más popular. ¡La retroalimentación es bienvenida! Puedes encontrarme en: [@adambrenecki](https://twitter.com/adambrenecki), o @@ -82,13 +82,13 @@ false; !true; // = false !false; // = true -// Para comprobar una igualdad se usa == -1 == 1; // = true -2 == 1; // = false +// Para comprobar una igualdad se usa === +1 === 1; // = true +2 === 1; // = false -// Para comprobar una desigualdad se usa != -1 != 1; // = false -2 != 1; // = true +// Para comprobar una desigualdad se usa !== +1 !== 1; // = false +2 !== 1; // = true // Más comparaciones 1 < 10; // = true -- cgit v1.2.3 From 08c653ad62e0e21cf7873aa6a8e5195d25f15240 Mon Sep 17 00:00:00 2001 From: Carlo Milanesi Date: Sat, 28 May 2016 15:22:22 +0200 Subject: Corrected definition of "slice" concept --- rust.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/rust.html.markdown b/rust.html.markdown index d0c56b4a..f82f7785 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -81,9 +81,10 @@ fn main() { let s: String = "hello world".to_string(); // A string slice – an immutable view into another string - // This is basically an immutable pointer to a string – it doesn’t + // This is basically an immutable pair of pointers to a string – it doesn’t // actually contain the contents of a string, just a pointer to - // something that does (in this case, `s`) + // the begin and a pointer to the end of a string buffer, + // statically allocated or contained in another object (in this case, `s`) let s_slice: &str = &s; println!("{} {}", s, s_slice); // hello world hello world -- cgit v1.2.3 From 39b02cf5ab38bc6ccbd66e03740a89fabc41952f Mon Sep 17 00:00:00 2001 From: Carlo Milanesi Date: Sat, 28 May 2016 17:23:14 +0200 Subject: Translated into Italian --- it-it/rust-it.html.markdown | 321 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 321 insertions(+) create mode 100644 it-it/rust-it.html.markdown diff --git a/it-it/rust-it.html.markdown b/it-it/rust-it.html.markdown new file mode 100644 index 00000000..39dbb944 --- /dev/null +++ b/it-it/rust-it.html.markdown @@ -0,0 +1,321 @@ +--- +language: rust +contributors: + - ["Carlo Milanesi", "http://github.com/carlomilanesi"] +filename: rust-it.html.markdown +--- + +Rust è un linguaggio di programmazione sviluppato da Mozilla Research. +Rust combina il controllo a basso livello sulle prestazioni con alcune comodità +ad alto livello e stringenti garanzie di sicurezza. + +Rust raggiunge questi obiettivi senza richiedere la garbage collection né una grossa +libreria di supporto run-time, rendendo così possibile l'uso di librerie scritte in Rust +come rimpiazzo di librerie scritte in C. + +La prima versione pubblica di Rust, la 0.1, è stata rilasciata nel gennaio 2012, e per 3 anni +lo sviluppo è proceduto così rapidamente che l'utilizzo delle versioni +stabili veniva scoraggiato, e piuttosto si consigliava di utilizzare le versioni notturne +(nightly build). + +Il 15 maggio 2015, la versione 1.0 di Rust è stata rilasciata con la garanzia +che nelle successive versioni 1.x non ci sarebbero state modifiche che avrebbero reso +incompatibile il codice scritto per tale versione. +Nelle nightly build sono attualmente disponibili migliorie al tempo di compilazione +e ad altri aspetti del compilatore. Rust ha adottato un modello di rilascio a scaglioni +con rilasci regolari ogni sei settimane. Per esempio, la versione 1.1 beta è stata resa +disponibile contestualmente al rilascio della versione stabile 1.0. + +Sebbene Rust sia un linguaggio di livello relativamente basso, Rust ha alcuni concetti +di programmazione funzionale che solitamente si trovano solo nei linguaggi di livello più alto. +Ciò rende Rust non solo veloce, ma anche facile ed comodo da usare. + +```rust +// I commenti che stanno su una sola riga sono fatti così... +/* ...mentre così sono fatti +i commenti che richiedono +più righe */ + +/////////////////// +// 1. Fondamenti // +/////////////////// + +// Funzioni +// `i32` è il tipo per gli interi a 32-bit con segno +fn add2(x: i32, y: i32) -> i32 { + // return implicito (senza punto-e-virgola) + x + y +} + +// Funzione "main" +fn main() { + // Numeri // + + // Binding (ossia "variabili") immutabili + let x: i32 = 1; + + // Suffissi intero/virgola mobile + let y: i32 = 13i32; + let f: f64 = 1.3f64; + + // Inferenza di tipo + // La maggior parte delle volte, il compilatore Rust può inferire + // di quale tipo sia l'espressione usata per inizializzare un binding, + // e quindi non è necessario specificare esplicitamente il tipo. + // In tutto questo tutorial, i tipi vengono specificati esplicitamente in molti posti, + // ma solo a scopo dimostrativo. La maggior parte delle volte se ne potrebbe + // fare a meno, grazie all'inferenza di tipo. + let implicito_x = 1; + let implicito_f = 1.3; + + // Aritmetica + let somma = x + y + 13; + + // Variabile mutevole + let mut mutevole = 1; + mutevole = 4; + mutevole += 2; + + // Stringhe // + + // Letterali di stringa + let x: &str = "Ciao mondo!"; + + // Stampa + println!("{} {}", f, x); // 1.3 Ciao mondo! + + // Una `String` – una stringa allocata nello heap + let s: String = "Ciao mondo".to_string(); + + // Uno slice (fetta) di stringa – una vista immutabile + // all'interno di un'altra stringa. + // Uno slice è una coppia immutabile di puntatori al buffer contenuto + // nella stringa - non contiene dei caratteri, solo dei puntatori a + // un buffer statico o a un buffer contenuto in un altro oggetto (in questo caso, `s`) + let s_slice: &str = &s; + + println!("{} - {}", s, s_slice); // Ciao mondo - Ciao mondo + + // Vettori/array // + + // Un array di lunghezza fissa + let quattro_int: [i32; 4] = [1, 2, 3, 4]; + + // Un array dinamico (vettore) + let mut vettore: Vec = vec![1, 2, 3, 4]; + vettore.push(5); + + // Uno slice – una vista immutabile all'interno di un vettore o di un array + // E' molto simile a uno slice di stringa, ma per i vettori + let slice: &[i32] = &vettore; + + // Usa `{:?}` per stampare qualcosa a scopo di debugging + println!("{:?} {:?}", vettore, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + + // Tuple // + + // Una tupla è un insieme ordinato di dimensione fissa di valori aventi tipi eventualmente diversi + let x: (i32, &str, f64) = (1, "ciao", 3.4); + + // Il `let` che destruttura + let (a, b, c) = x; + println!("{} {} {}", a, b, c); // 1 ciao 3.4 + + // Indicizzazione + println!("{}", x.1); // ciao + + ///////////// + // 2. Tipi // + ///////////// + + // Strutture + struct Point { + x: i32, + y: i32, + } + + let origine: Punto = Punto { x: 0, y: 0 }; + + // Ana struct con campi senza nome, chiamata ‘tuple struct’ + struct Punto2(i32, i32); + + let origine2 = Punto2(0, 0); + + // Enum basilare, analoga a quelle del linguaggio C + enum Direzione { + Sinistra, + Destra, + Su, + Giu, + } + + let su = Direzione::Su; + + // Enum con campi + enum OpzionaleI32 { + UnI32(i32), + Niente, + } + + let due: OpzionaleI32 = OpzionaleI32::UnI32(2); + let niente = OpzionaleI32::Niente; + + // Generici // + + struct Foo { bar: T } + + // Questo è definito nella libreria standard come `Option` + enum Opzionale { + QualcheValore(T), + NessunValore, + } + + // Metodi // + + impl Foo { + // I metodi di oggetto prendono un parametro `self` esplicito + fn get_bar(self) -> T { + self.bar + } + } + + let a_foo = Foo { bar: 1 }; + println!("{}", a_foo.get_bar()); // 1 + + // I trait (tratti), noti come "interfacce" o "mixin" in altri linguaggi + + trait Maneggiamento { + fn maneggia(self) -> Option; + } + + impl Maneggiamento for Foo { + fn maneggia(self) -> Option { + Some(self.bar) + } + } + + let altro_foo = Foo { bar: 1 }; + println!("{:?}", altro_foo.maneggia()); // Some(1) + + ///////////////////////// + // 3. Pattern matching // + ///////////////////////// + + let foo = OpzionaleI32::UnI32(1); + match foo { + OpzionaleI32::UnI32(n) => println!("E' un i32: {}", n), + OpzionaleI32::Niente => println!("Non vale niente!"), + } + + // Pattern matching avanzato + struct FooBar { x: i32, y: OpzionaleI32 } + let bar = FooBar { x: 15, y: OpzionaleI32::UnI32(32) }; + + match bar { + FooBar { x: 0, y: OpzionaleI32::UnI32(0) } => + println!("I numeri valgono zero!"), + FooBar { x: n, y: OpzionaleI32::UnI32(m) } if n == m => + println!("I numeri sono identici"), + FooBar { x: n, y: OpzionaleI32::UnI32(m) } => + println!("Numeri diversi: {} {}", n, m), + FooBar { x: _, y: OpzionaleI32::Niente } => + println!("Il secondo numbero non vale niente!"), + } + + /////////////////////////////////////////// + // 4. Flusso di controllo (Control flow) // + /////////////////////////////////////////// + + // cicli/iterazione con `for` + let array = [1, 2, 3]; + for i in array.iter() { + println!("{}", i); + } + + // Range + for i in 0u32..10 { + print!("{} ", i); + } + println!(""); + // prints `0 1 2 3 4 5 6 7 8 9 ` + + // `if` + if 1 == 1 { + println!("La matematica funziona!"); + } else { + println!("Oh no..."); + } + + // `if` come espressione + let value = if true { + "bene" + } else { + "male" + }; + + // ciclo `while` + while 1 == 1 { + println!("L'universo sta funzionando regolarmente."); + } + + // Ciclo infinito + loop { + println!("Ciao!"); + } + + ///////////////////////////////////////////////// + // 5. La sicurezza della memoria e i puntatori // + ///////////////////////////////////////////////// + + // Puntatore posseduto (owned) – solamente una cosa sola per volta può ‘possedere’ questo puntatore + // Ciò significa che quando il `Box` abbandona il suo scope, verrà automaticamente deallocato in sicurezza. + let mut mio: Box = Box::new(3); + *mio = 5; // dereference + // Qui, `adesso_e_mio` acquisisce la proprietà di `mio`. In altre parole, `mio` viene spostato. + let mut adesso_e_mio = mio; + *adesso_e_mio += 2; + + println!("{}", adesso_e_mio); // 7 + // println!("{}", mio); // questo non compilerebbe perché `adesso_e_mio` adesso possiede il puntatore + + // Riferimento (reference) – un puntatore immutabile che si riferisce ad altri dati + // Quando un riferimento viene preso a un valore, diciamo che quel valore + // è stato ‘preso in prestito’ (borrowed). + // Mentre un valore è preso in prestito immutabilmente, non può venire mutato né spostato. + // Un prestito dura fino alla fine dello scope in cui è stato creato. + let mut var = 4; + var = 3; + let ref_var: &i32 = &var; + + println!("{}", var); // Diversamente da `box`, `var` può ancora essere usato + println!("{}", *ref_var); + // var = 5; // questo non compilerebbe, perché `var` è stato preso in prestito + // *ref_var = 6; // neanche questo, perché `ref_var` è un riferimento immutabile + + // Riferimento immutabile + // Mentre un valore è preso in presto mutevolmente, non può essere acceduto in nessun modo. + let mut var2 = 4; + let ref_var2: &mut i32 = &mut var2; + *ref_var2 += 2; // '*' serve a puntare al binding var2, preso in presto mutevolmente + + println!("{}", *ref_var2); // 6 + // var2 non compilerebbe. ref_var2 è di tipo &mut i32, e quindi + // immagazzina un riferimento a un i32, e non il valore stesso. + // var2 = 2; // questo non compilerebbe, perché `var2` è stato preso in prestito +} +``` + +## Ulteriori letture + +C'è molto di più in Rust — questi sono solo i fondamenti di Rust, che servono a capire +le cose più importanti. + +Purtroppo c'è pochissima documentazione in italiano, tra cui: +(https://www.mozillaitalia.org/home/2015/05/30/primi-passi-con-rust/) + +Però ce n'è parecchia in inglese. Per saperne di più, leggi [The Rust Programming +Language](http://doc.rust-lang.org/book/index.html) e tieni d'occhio l'area di interesse di Reddit (subreddit) +[/r/rust](http://reddit.com/r/rust). + +Puoi anche provare a programmare in varie versioni di Rust usando il compilatore online al sito ufficiale +[Rust playpen](http://play.rust-lang.org). -- cgit v1.2.3 From b891d0d7e11fba89cad7ee22ec0d2f82b1eb4f64 Mon Sep 17 00:00:00 2001 From: ven Date: Mon, 30 May 2016 15:54:45 +0200 Subject: fix minor typo --- cmake.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake.html.markdown b/cmake.html.markdown index e13e7f67..fb14ab22 100644 --- a/cmake.html.markdown +++ b/cmake.html.markdown @@ -5,7 +5,7 @@ contributors: filename: CMake --- -CMake it's a cross-platform, open-source build system. This tool will allow you +CMake is a cross-platform, open-source build system. This tool will allow you to test, compile and create packages of your source code. The problem that CMake tries to solve it's the problem of Makefiles and -- cgit v1.2.3 From 4e118150a2ba76129389d6f57ff86f942fc50863 Mon Sep 17 00:00:00 2001 From: ven Date: Mon, 30 May 2016 15:55:57 +0200 Subject: tiny fixes to cmake --- cmake.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cmake.html.markdown b/cmake.html.markdown index fb14ab22..a2c8cc8a 100644 --- a/cmake.html.markdown +++ b/cmake.html.markdown @@ -8,12 +8,12 @@ filename: CMake CMake is a cross-platform, open-source build system. This tool will allow you to test, compile and create packages of your source code. -The problem that CMake tries to solve it's the problem of Makefiles and -Autoconfigure on cross-platform (different make interpreters have different +The problem that CMake tries to solve is the problem of Makefiles and +Autoconfigure on cross-platforms (different make interpreters have different command) and the ease-of-use on linking 3rd party libraries. CMake is an extensible, open-source system that manages the build process in -an operating system and in a compiler-independent manner. Unlike many +an operating system and compiler-independent manner. Unlike many cross-platform systems, CMake is designed to be used in conjunction with the native build environment. Simple configuration files placed in each source directory (called CMakeLists.txt files) are used to generate standard build -- cgit v1.2.3 From 427f87c65588374352c6a85e52758a9609baa9bc Mon Sep 17 00:00:00 2001 From: Carl Date: Sat, 4 Jun 2016 00:26:18 -0700 Subject: Updated closure Corrected closure example that referenced assigning x to e^10, which does not happen in this iteration. Set x to a value large enough to make the comments hold true. --- go.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index dc684227..7b007bab 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -221,7 +221,8 @@ func learnFlowControl() { xBig := func() bool { return x > 10000 // References x declared above switch statement. } - fmt.Println("xBig:", xBig()) // true (we last assigned e^10 to x). + x = 99999 + fmt.Println("xBig:", xBig()) // true x = 1.3e3 // This makes x == 1300 fmt.Println("xBig:", xBig()) // false now. -- cgit v1.2.3 From c450701b46fdbed9f51d2776cab2462021c13d87 Mon Sep 17 00:00:00 2001 From: Felipe Pontes Date: Sat, 4 Jun 2016 10:02:37 -0300 Subject: [c++/pt-br] Fix some typos --- pt-br/c++-pt.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown index 31a3110c..e2e95268 100644 --- a/pt-br/c++-pt.html.markdown +++ b/pt-br/c++-pt.html.markdown @@ -490,7 +490,7 @@ bool doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); // Abra o arquivo em modo de leitura if (fh == nullptr) // O ponteiro retornado é nulo em caso de falha. - reuturn false; // Relate o fracasso para o chamador. + return false; // Relate o fracasso para o chamador. // Suponha cada função retorne false, se falhar if (!doSomethingWithTheFile(fh)) { @@ -511,7 +511,7 @@ bool doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); if (fh == nullptr) - reuturn false; + return false; if (!doSomethingWithTheFile(fh)) goto failure; -- cgit v1.2.3 From 4207b753bc31f1050b394a87cbe1e3c0a3fa1914 Mon Sep 17 00:00:00 2001 From: Carlo Milanesi Date: Mon, 6 Jun 2016 01:43:39 +0200 Subject: Small corrections to translation --- it-it/rust-it.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/it-it/rust-it.html.markdown b/it-it/rust-it.html.markdown index 39dbb944..dd5005f2 100644 --- a/it-it/rust-it.html.markdown +++ b/it-it/rust-it.html.markdown @@ -226,7 +226,7 @@ fn main() { // 4. Flusso di controllo (Control flow) // /////////////////////////////////////////// - // cicli/iterazione con `for` + // Ciclo/iterazione con `for` let array = [1, 2, 3]; for i in array.iter() { println!("{}", i); @@ -237,7 +237,7 @@ fn main() { print!("{} ", i); } println!(""); - // prints `0 1 2 3 4 5 6 7 8 9 ` + // Stampa `0 1 2 3 4 5 6 7 8 9 ` // `if` if 1 == 1 { @@ -253,7 +253,7 @@ fn main() { "male" }; - // ciclo `while` + // Ciclo `while` while 1 == 1 { println!("L'universo sta funzionando regolarmente."); } -- cgit v1.2.3 From 3684cae8c7632a7519eaf13b0a59141e4f068888 Mon Sep 17 00:00:00 2001 From: Peter Wu Date: Mon, 6 Jun 2016 11:47:47 +0200 Subject: tcl: fix error in no-braces example (#2274) --- tcl.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index 4ff1d3cc..9118081d 100644 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -253,7 +253,7 @@ proc greet {greeting name} { # As noted earlier, braces do not construct a code block. Every value, even # the third argument of the "proc" command, is a string. The previous command # rewritten to not use braces at all: -proc greet greeting\ name return\ \"Hello,\ \$name! +proc greet greeting\ name return\ \"\$greeting,\ \$name!\" -- cgit v1.2.3 From 8b2eff3f0bf3622faeb2e0346a22470a7131bed2 Mon Sep 17 00:00:00 2001 From: kedaio Date: Tue, 7 Jun 2016 00:16:38 -0400 Subject: start translation for zfs - lang zh-cn first para translated. commit to see if this mess up the format. --- zh-cn/zfs-cn.html.markdown | 400 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 400 insertions(+) create mode 100644 zh-cn/zfs-cn.html.markdown diff --git a/zh-cn/zfs-cn.html.markdown b/zh-cn/zfs-cn.html.markdown new file mode 100644 index 00000000..bb80e369 --- /dev/null +++ b/zh-cn/zfs-cn.html.markdown @@ -0,0 +1,400 @@ +--- +category: tool +tool: zfs +contributors: + - ["sarlalian", "http://github.com/sarlalian"] +translators: + - ["Alan Cheng", "https://github.com/kedaio"] +filename: LearnZfs-cn.txt +lang: zh-cn +--- + +[ZFS](http://open-zfs.org/wiki/Main_Page) +是对存储相关技术重新思考的结果,它把传统的文件系统和卷管理器集成到一个工具当中. +ZFS有一些特有的术语,这把它和传统的存储系统区分开来。但它有很多功能聚焦于可用性。 + + +## ZFS概念 + +### 虚拟设备(Virtual Devices) + +A VDEV is similar to a raid device presented by a RAID card, there are several different +types of VDEV's that offer various advantages, including redundancy and speed. In general +VDEV's offer better reliability and safety than a RAID card. It is discouraged to use a +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) + * raidz2 (2-disk parity, similar to RAID 6) + * raidz3 (3-disk parity, no RAID analog) +* disk +* file (not recommended for production due to another filesystem adding unnecessary layering) + +Your data is striped across all the VDEV's present in your Storage Pool, so more VDEV's will +increase your IOPS. + +### Storage Pools + +ZFS uses Storage Pools as an abstraction over the lower level storage provider (VDEV), allow +you to separate the user visible file system from the physical layout. + +### ZFS Dataset + +ZFS datasets are analogous to traditional filesystems but with many more features. They +provide many of ZFS's advantages. Datasets support [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write) +snapshots, quota's, compression and de-duplication. + + +### Limits + +One directory may contain up to 2^48 files, up to 16 exabytes each. A single storage pool +can contain up to 256 zettabytes (2^78) of space, and can be striped across 2^64 devices. A +single host can have 2^64 storage pools. The limits are huge. + + +## Commands + +### Storage Pools + +Actions: +* List +* Status +* Destroy +* Get/Set properties + +List zpools + +```bash +# Create a raidz zpool +$ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 + +# List ZPools +$ zpool list +NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT +zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - + +# List detailed information about a specific zpool +$ 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% +``` + +Status of zpools + +```bash +# Get status information about zpools +$ 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 + +# Scrubbing a zpool to correct any 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 +``` + +Properties of zpools + +```bash + +# Getting properties from the pool properties can be user set or system provided. +$ zpool get all zroot +NAME PROPERTY VALUE SOURCE +zroot size 141G - +zroot capacity 75% - +zroot altroot - default +zroot health ONLINE - +... + +# Setting a zpool property +$ 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 +``` + +Remove zpool + +```bash +$ zpool destroy test +``` + + +### Datasets + +Actions: +* Create +* List +* Rename +* Delete +* Get/Set properties + +Create datasets + +```bash +# Create dataset +$ zfs create tank/root/data +$ mount | grep data +tank/root/data on /data (zfs, local, nfsv4acls) + +# Create child dataset +$ zfs create tank/root/data/stuff +$ mount | grep data +tank/root/data on /data (zfs, local, nfsv4acls) +tank/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 - +``` + +List datasets + +```bash +# List all datasets +$ 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 +... + +# List a specific dataset +$ zfs list zroot/home +NAME USED AVAIL REFER MOUNTPOINT +zroot/home 288K 30.8G 144K none + +# List snapshots +$ 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 - +``` + +Rename datasets + +```bash +$ zfs rename tank/root/home tank/root/old_home +$ zfs rename tank/root/new_home tank/root/home +``` + +Delete dataset + +```bash +# Datasets cannot be deleted if they have any snapshots +zfs destroy tank/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 +zroot/home mounted yes - +... + +# Get property from dataset +$ zfs get compression zroot/usr/home +NAME PROPERTY VALUE SOURCE +zroot/home compression off default + +# Set property on dataset +$ zfs set compression=gzip-9 mypool/lamb + +# Get a set of properties from all datasets +$ 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 +... +``` + + +### Snapshots + +ZFS snapshots are one of the things about zfs that are a really big deal + +* The space they take up is equal to the difference in data between the filesystem and its snapshot +* Creation time is only seconds +* Recovery is as fast as you can write data. +* They are easy to automate. + +Actions: +* Create +* Delete +* Rename +* Access snapshots +* Send / Receive +* Clone + + +Create snapshots + +```bash +# Create a snapshot of a single dataset +zfs snapshot tank/home/sarlalian@now + +# Create a snapshot of a dataset and its children +$ zfs snapshot -r tank/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 - +... + +Destroy snapshots + +```bash +# How to destroy a snapshot +$ zfs destroy tank/home/sarlalian@now + +# Delete a snapshot on a parent dataset and its children +$ zfs destroy -r tank/home/sarlalian@now + +``` + +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 -r tank/home@now @yesterday +``` + +Accessing snapshots + +```bash +# CD Into a snapshot directory +$ cd /home/.zfs/snapshot/ +``` + +Sending and Receiving + +```bash +# Backup a snapshot to a file +$ zfs send tank/home/sarlalian@now | gzip > backup_file.gz + +# Send a snapshot to another dataset +$ zfs send tank/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' + +# Send full dataset with snapshos to new host +$ zfs send -v -R tank/home@now | ssh root@backup_server 'zfs recv tank/home' +``` + +Cloneing Snapshots + +```bash +# Clone a snapshot +$ zfs clone tank/home/sarlalian@now tank/home/sarlalian_new + +# Promoting the clone so it is no longer dependent on the snapshot +$ zfs promote tank/home/sarlalian_new +``` + +### Putting it all together + +This following a script utilizing FreeBSD, jails and ZFS to automate +provisioning a clean copy of a mysql staging database from a live replication +slave. + +```bash +#!/bin/sh + +echo "==== Stopping the staging database server ====" +jail -r staging + +echo "==== Cleaning up existing staging server and snapshot ====" +zfs destroy -r zroot/jails/staging +zfs destroy zroot/jails/slave@staging + +echo "==== Quiescing the slave database ====" +echo "FLUSH TABLES WITH READ LOCK;" | /usr/local/bin/mysql -u root -pmyrootpassword -h slave + +echo "==== Snapshotting the slave db filesystem as zroot/jails/slave@staging ====" +zfs snapshot zroot/jails/slave@staging + +echo "==== Starting the slave database server ====" +jail -c slave + +echo "==== Cloning the slave snapshot to the staging server ====" +zfs clone zroot/jails/slave@staging zroot/jails/staging + +echo "==== Installing the staging mysql config ====" +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 "==== Setting up the staging rc.conf file ====" +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 "==== Starting the staging db server ====" +jail -c staging + +echo "==== Makes the staging database not pull from the master ====" +echo "STOP SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging +echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging +``` + + +### Additional Reading + +* [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) -- cgit v1.2.3 From c4077317b378547902e88d5a9dab4ee1f5417a99 Mon Sep 17 00:00:00 2001 From: kedaio Date: Tue, 7 Jun 2016 03:38:55 -0400 Subject: Update zfs-cn.html.markdown completed translation --- zh-cn/zfs-cn.html.markdown | 194 ++++++++++++++++++++++----------------------- 1 file changed, 96 insertions(+), 98 deletions(-) diff --git a/zh-cn/zfs-cn.html.markdown b/zh-cn/zfs-cn.html.markdown index bb80e369..2e9321a4 100644 --- a/zh-cn/zfs-cn.html.markdown +++ b/zh-cn/zfs-cn.html.markdown @@ -16,59 +16,57 @@ ZFS有一些特有的术语,这把它和传统的存储系统区分开来。 ## ZFS概念 -### 虚拟设备(Virtual Devices) +### 虚拟设备(Virtual Devices,VDEV) -A VDEV is similar to a raid device presented by a RAID card, there are several different -types of VDEV's that offer various advantages, including redundancy and speed. In general -VDEV's offer better reliability and safety than a RAID card. It is discouraged to use a -RAID setup with ZFS, as ZFS expects to directly manage the underlying disks. +对于操作系统来说,VDEA和传统的RAID阵列卡所呈现的rai设备类似。VDEV有几种不同的类型,每种类型 +都有自己的优势,包括冗余和速度。一般来说,VDEV的可靠性和安全性比阵列卡要好。因此使用ZFS时不 +建议使用阵列卡。让ZFS直接管理磁盘。 -Types of VDEV's -* stripe (a single disk, no redundancy) -* mirror (n-way mirrors supported) +VDEV的类型 +* stripe (条带。单个磁盘,没有冗余) +* mirror (镜像。支持n-wa镜像) * raidz - * raidz1 (1-disk parity, similar to RAID 5) - * raidz2 (2-disk parity, similar to RAID 6) - * raidz3 (3-disk parity, no RAID analog) -* disk -* file (not recommended for production due to another filesystem adding unnecessary layering) + * raidz1 (一个奇偶校验磁盘, 类似于RAID 5) + * raidz2 (两个奇偶校验磁盘, 类似于RAID 6) + * raidz3 (三个奇偶校验磁盘, 没有类似RAID等级) +* disk (磁盘) +* file (文件。不推荐在生产环境中使用,因为中间又多了一层不必要的文件系统) -Your data is striped across all the VDEV's present in your Storage Pool, so more VDEV's will -increase your IOPS. +数据会以条带方式存储于存储池中的所有VDE上。因此一个存储池中的VDEV越多,IOPS就越高。 -### Storage Pools +### storage pool (存储池) -ZFS uses Storage Pools as an abstraction over the lower level storage provider (VDEV), allow -you to separate the user visible file system from the physical layout. +ZFS 使用存储池来作为底层存储提供者(VDEV)的抽象。这样可以把用户可见的文件系统和底层的物理磁盘 +布局分离开来。 -### ZFS Dataset +### ZFS 数据集(Dataset) -ZFS datasets are analogous to traditional filesystems but with many more features. They -provide many of ZFS's advantages. Datasets support [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write) -snapshots, quota's, compression and de-duplication. +ZFS 数据集类似于传统的文件系统(译者注:或者说是目录),但是提供了更多的功能。ZFS的很多优势也是 +在这一层体现出来的。数据集支持 [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write) +快照, 配额, 压缩和重复消除(de-duplication). -### Limits +### 限制 -One directory may contain up to 2^48 files, up to 16 exabytes each. A single storage pool -can contain up to 256 zettabytes (2^78) of space, and can be striped across 2^64 devices. A -single host can have 2^64 storage pools. The limits are huge. +一个目录最多可包含 2^48个文件, 每个文件最大可以是16 exabytes. 一个存储池最大可包含256 zettabytes 、 +(2^78) 的空间, 可以条带化地分布于2^64 设备上. 单一主机最多可以创建2^64个存储池。这些限制可以说是相 +当大。 -## Commands +## 命令 -### Storage Pools +### 存储池 -Actions: -* List -* Status -* Destroy -* Get/Set properties +Actions: (存储池操作) +* List (列举) +* Status (查看状态) +* Destroy (删除) +* Get/Set properties (获取/设置属性) -List zpools +List zpools (列举存储池(也叫zpool)) ```bash -# Create a raidz zpool +# Create a raidz zpool (创建一个raidz类型的存储池) $ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 # List ZPools @@ -76,17 +74,17 @@ $ zpool list NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - -# List detailed information about a specific zpool +# List detailed information about a specific zpool (列出某一存储池的详细信息) $ 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% ``` -Status of zpools +Status of zpools (存储池状态) ```bash -# Get status information about zpools +# Get status information about zpools (获取全部zpool信息) $ zpool status pool: zroot state: ONLINE @@ -99,7 +97,7 @@ config: errors: No known data errors -# Scrubbing a zpool to correct any errors +# Scrubbing a zpool to correct any errors (用scrub来更正存储池错误信息) $ zpool scrub zroot $ zpool status -v zroot pool: zroot @@ -116,11 +114,12 @@ config: errors: No known data errors ``` -Properties of zpools +Properties of zpools (存储池属性) ```bash # Getting properties from the pool properties can be user set or system provided. +# (获取zroot存储池的全部属性) $ zpool get all zroot NAME PROPERTY VALUE SOURCE zroot size 141G - @@ -129,7 +128,7 @@ zroot altroot - default zroot health ONLINE - ... -# Setting a zpool property +# Setting a zpool property (设置存储池属性,下例蛇这的是commen备注属性) $ zpool set comment="Storage of mah stuff" zroot $ zpool get comment NAME PROPERTY VALUE SOURCE @@ -137,48 +136,48 @@ tank comment - default zroot comment Storage of mah stuff local ``` -Remove zpool +Remove zpool (删除存储池) ```bash $ zpool destroy test ``` -### Datasets +### Datasets (数据集) -Actions: -* Create -* List -* Rename -* Delete -* Get/Set properties +Actions: (数据集相关操作) +* Create (创建) +* List (列举) +* Rename (重命名) +* Delete (删除) +* Get/Set properties (获取/设置属性) Create datasets ```bash -# Create dataset +# Create dataset (创建数据集) $ zfs create tank/root/data $ mount | grep data tank/root/data on /data (zfs, local, nfsv4acls) -# Create child dataset +# Create child dataset (创建子数据集) $ zfs create tank/root/data/stuff $ mount | grep data tank/root/data on /data (zfs, local, nfsv4acls) tank/root/data/stuff on /data/stuff (zfs, local, nfsv4acls) -# Create Volume +# 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 - ``` -List datasets +List datasets (列举数据集) ```bash -# List all datasets +# List all datasets (列举所有数据集) $ zfs list NAME USED AVAIL REFER MOUNTPOINT zroot 106G 30.8G 144K none @@ -189,12 +188,12 @@ zroot/backup 5.23G zroot/home 288K 30.8G 144K none ... -# List a specific dataset +# List a specific dataset (列举某一数据集) $ zfs list zroot/home NAME USED AVAIL REFER MOUNTPOINT zroot/home 288K 30.8G 144K none -# List snapshots +# List snapshots (列举快照) $ zfs list -t snapshot zroot@daily-2015-10-15 0 - 144K - zroot/ROOT@daily-2015-10-15 0 - 144K - @@ -207,24 +206,24 @@ zroot/var/log@daily-2015-10-15 zroot/var/tmp@daily-2015-10-15 0 - 152K - ``` -Rename datasets +Rename datasets (重命名数据集) ```bash $ zfs rename tank/root/home tank/root/old_home $ zfs rename tank/root/new_home tank/root/home ``` -Delete dataset +Delete dataset (删除数据集) ```bash -# Datasets cannot be deleted if they have any snapshots +# Datasets cannot be deleted if they have any snapshots (数据集如果有快照则无法删除) zfs destroy tank/root/home ``` -Get / set properties of a dataset +Get / set properties of a dataset (获取/设置数据集属性) ```bash -# Get all properties +# 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 @@ -235,15 +234,15 @@ zroot/home referenced 11.9G - zroot/home mounted yes - ... -# Get property from dataset +# Get property from dataset (获取数据集属性) $ zfs get compression zroot/usr/home NAME PROPERTY VALUE SOURCE zroot/home compression off default -# Set property on dataset +# Set property on dataset (设置压缩属性compressio) $ zfs set compression=gzip-9 mypool/lamb -# Get a set of properties from all datasets +# Get a set of properties from all datasets (列举所有数据集的名称,配额和预留属性) $ zfs list -o name,quota,reservation NAME QUOTA RESERV zroot none none @@ -257,31 +256,31 @@ zroot/var none none ``` -### Snapshots +### Snapshots (快照) -ZFS snapshots are one of the things about zfs that are a really big deal +快照是ZFS 的一个非常重要的功能 -* The space they take up is equal to the difference in data between the filesystem and its snapshot -* Creation time is only seconds -* Recovery is as fast as you can write data. -* They are easy to automate. +* 快照占用的空间等于它和原始数据的差异量 +* 创建时间以秒计 +* 恢复时间和写入速度相同 +* 易于自动化 -Actions: -* Create -* Delete -* Rename -* Access snapshots -* Send / Receive -* Clone +Actions: (快照相关操作) +* Create (创建) +* Delete (删除) +* Rename (重命名) +* Access snapshots (访问) +* Send / Receive (发送/接收) +* Clone (克隆) -Create snapshots +Create snapshots (创建快照) ```bash -# Create a snapshot of a single dataset +# Create a snapshot of a single dataset (为单一数据集创建快照) zfs snapshot tank/home/sarlalian@now -# Create a snapshot of a dataset and its children +# Create a snapshot of a dataset and its children (为数据集及其子集创建快照) $ zfs snapshot -r tank/home@now $ zfs list -t snapshot NAME USED AVAIL REFER MOUNTPOINT @@ -291,65 +290,64 @@ tank/home/alice@now 0 - 156M - tank/home/bob@now 0 - 156M - ... -Destroy snapshots +Destroy snapshots (删除快照) ```bash -# How to destroy a snapshot +# How to destroy a snapshot (如何删除) $ zfs destroy tank/home/sarlalian@now -# Delete a snapshot on a parent dataset and its children +# Delete a snapshot on a parent dataset and its children (删除某一数据集及其子集的快照) $ zfs destroy -r tank/home/sarlalian@now ``` -Renaming Snapshots +Renaming Snapshots (重命名) ```bash -# Rename a snapshot +# Rename a snapshot (重命名快照,示例) $ zfs rename tank/home/sarlalian@now tank/home/sarlalian@today $ zfs rename tank/home/sarlalian@now today # zfs rename -r tank/home@now @yesterday ``` -Accessing snapshots +Accessing snapshots (访问快照) ```bash -# CD Into a snapshot directory +# CD Into a snapshot directory (cd进入一个快照目录) $ cd /home/.zfs/snapshot/ ``` Sending and Receiving ```bash -# Backup a snapshot to a file +# Backup a snapshot to a file (备份快照到一个文件) $ zfs send tank/home/sarlalian@now | gzip > backup_file.gz -# Send a snapshot to another dataset +# Send a snapshot to another dataset (发送快照到另一个数据集) $ zfs send tank/home/sarlalian@now | zfs recv backups/home/sarlalian -# Send a snapshot to a remote host +# Send a snapshot to a remote host (发送快照到一个远程主机) $ zfs send tank/home/sarlalian@now | ssh root@backup_server 'zfs recv tank/home/sarlalian' -# Send full dataset with snapshos to new host +# Send full dataset with snapshos to new host (发送数据集及其快照到一个新主机) $ zfs send -v -R tank/home@now | ssh root@backup_server 'zfs recv tank/home' ``` -Cloneing Snapshots +Cloneing Snapshots (克隆快照) ```bash # Clone a snapshot $ zfs clone tank/home/sarlalian@now tank/home/sarlalian_new -# Promoting the clone so it is no longer dependent on the snapshot +# Promoting the clone so it is no longer dependent on the snapshot(提升克隆,让它不再依赖原始数据) $ zfs promote tank/home/sarlalian_new ``` -### Putting it all together +### Putting it all together (汇总) -This following a script utilizing FreeBSD, jails and ZFS to automate -provisioning a clean copy of a mysql staging database from a live replication -slave. +下面这个脚本使用了FreeBSD, jails和ZFS,来自动在一个mysql群集的热备主机上为一个mysq staging数据库 +创建一份纯净的拷贝。 ```bash #!/bin/sh @@ -390,7 +388,7 @@ echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging ``` -### Additional Reading +### Additional Reading (延伸阅读) * [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) -- cgit v1.2.3 From 18a78a7aae5c8a6172777c92f5470a00258cbe36 Mon Sep 17 00:00:00 2001 From: kedaio Date: Tue, 7 Jun 2016 03:44:37 -0400 Subject: Update zfs-cn.html.markdown added remark on what is zfs clone --- zh-cn/zfs-cn.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zh-cn/zfs-cn.html.markdown b/zh-cn/zfs-cn.html.markdown index 2e9321a4..3680678e 100644 --- a/zh-cn/zfs-cn.html.markdown +++ b/zh-cn/zfs-cn.html.markdown @@ -128,7 +128,7 @@ zroot altroot - default zroot health ONLINE - ... -# Setting a zpool property (设置存储池属性,下例蛇这的是commen备注属性) +# Setting a zpool property (设置存储池属性,下例这是设置commen备注属性) $ zpool set comment="Storage of mah stuff" zroot $ zpool get comment NAME PROPERTY VALUE SOURCE @@ -239,7 +239,7 @@ $ zfs get compression zroot/usr/home NAME PROPERTY VALUE SOURCE zroot/home compression off default -# Set property on dataset (设置压缩属性compressio) +# Set property on dataset (设置压缩属性compression) $ zfs set compression=gzip-9 mypool/lamb # Get a set of properties from all datasets (列举所有数据集的名称,配额和预留属性) @@ -271,7 +271,7 @@ Actions: (快照相关操作) * Rename (重命名) * Access snapshots (访问) * Send / Receive (发送/接收) -* Clone (克隆) +* Clone (克隆。译者注:关于clone和快照的区别可参看[这里](http://docs.oracle.com/cd/E19253-01/819-5461/gbcxz/index.html)) Create snapshots (创建快照) -- cgit v1.2.3 From 0a93da20009c51e28b2d12a142f06aaa680a231f Mon Sep 17 00:00:00 2001 From: kedaio Date: Tue, 7 Jun 2016 09:57:17 -0400 Subject: update according to reviewer feedback updated translation according to reviewer's feedback --- zh-cn/zfs-cn.html.markdown | 75 +++++++++++++++++++++++----------------------- 1 file changed, 37 insertions(+), 38 deletions(-) diff --git a/zh-cn/zfs-cn.html.markdown b/zh-cn/zfs-cn.html.markdown index 3680678e..fdf5277e 100644 --- a/zh-cn/zfs-cn.html.markdown +++ b/zh-cn/zfs-cn.html.markdown @@ -10,21 +10,21 @@ lang: zh-cn --- [ZFS](http://open-zfs.org/wiki/Main_Page) -是对存储相关技术重新思考的结果,它把传统的文件系统和卷管理器集成到一个工具当中. -ZFS有一些特有的术语,这把它和传统的存储系统区分开来。但它有很多功能聚焦于可用性。 +是重新思考与储存相关技术的结果,它把传统的文件系统和卷管理器集成到一个工具当中. +ZFS不但有把它和传统存储系统分开来的特有术语,也有很多聚焦于可用性的功能。 ## ZFS概念 ### 虚拟设备(Virtual Devices,VDEV) -对于操作系统来说,VDEA和传统的RAID阵列卡所呈现的rai设备类似。VDEV有几种不同的类型,每种类型 +对于操作系统来说,VDEV和传统的RAID阵列卡所呈现的raid设备类似。VDEV有几种不同的类型,每种类型 都有自己的优势,包括冗余和速度。一般来说,VDEV的可靠性和安全性比阵列卡要好。因此使用ZFS时不 建议使用阵列卡。让ZFS直接管理磁盘。 VDEV的类型 * stripe (条带。单个磁盘,没有冗余) -* mirror (镜像。支持n-wa镜像) +* mirror (镜像。支持n-way镜像) * raidz * raidz1 (一个奇偶校验磁盘, 类似于RAID 5) * raidz2 (两个奇偶校验磁盘, 类似于RAID 6) @@ -32,7 +32,7 @@ VDEV的类型 * disk (磁盘) * file (文件。不推荐在生产环境中使用,因为中间又多了一层不必要的文件系统) -数据会以条带方式存储于存储池中的所有VDE上。因此一个存储池中的VDEV越多,IOPS就越高。 +数据会以条带方式存储于存储池中的所有VDEV上。因此一个存储池中的VDEV越多,IOPS就越高。 ### storage pool (存储池) @@ -66,15 +66,15 @@ Actions: (存储池操作) List zpools (列举存储池(也叫zpool)) ```bash -# Create a raidz zpool (创建一个raidz类型的存储池) +# 创建一个raidz类型的存储池(名称为bucket) $ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 -# List ZPools +# 列出所有存储池 $ zpool list NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - -# List detailed information about a specific zpool (列出某一存储池的详细信息) +# 列出某一存储池的详细信息 $ zpool list -v zroot NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - @@ -84,7 +84,7 @@ zroot 141G 106G 35.2G - 43% Status of zpools (存储池状态) ```bash -# Get status information about zpools (获取全部zpool信息) +# 获取全部zpool状态信息 $ zpool status pool: zroot state: ONLINE @@ -97,7 +97,7 @@ config: errors: No known data errors -# Scrubbing a zpool to correct any errors (用scrub来更正存储池错误信息) +# 用scrub来更正存储池错误信息 $ zpool scrub zroot $ zpool status -v zroot pool: zroot @@ -118,8 +118,7 @@ Properties of zpools (存储池属性) ```bash -# Getting properties from the pool properties can be user set or system provided. -# (获取zroot存储池的全部属性) +# 获取某一存储池的全部属性。属性可能是系统提供,也可能是用户设置 $ zpool get all zroot NAME PROPERTY VALUE SOURCE zroot size 141G - @@ -128,7 +127,7 @@ zroot altroot - default zroot health ONLINE - ... -# Setting a zpool property (设置存储池属性,下例这是设置commen备注属性) +# 设置存储池属性,下例这是设置comment(备注)属性 $ zpool set comment="Storage of mah stuff" zroot $ zpool get comment NAME PROPERTY VALUE SOURCE @@ -155,19 +154,19 @@ Actions: (数据集相关操作) Create datasets ```bash -# Create dataset (创建数据集) +# 创建数据集 $ zfs create tank/root/data $ mount | grep data tank/root/data on /data (zfs, local, nfsv4acls) -# Create child dataset (创建子数据集) +# 创建子数据集 $ zfs create tank/root/data/stuff $ mount | grep data tank/root/data on /data (zfs, local, nfsv4acls) tank/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 @@ -177,7 +176,7 @@ tank/win_vm 4.13G 17.9G 64K - List datasets (列举数据集) ```bash -# List all datasets (列举所有数据集) +# 列出所有数据集 $ zfs list NAME USED AVAIL REFER MOUNTPOINT zroot 106G 30.8G 144K none @@ -188,12 +187,12 @@ zroot/backup 5.23G zroot/home 288K 30.8G 144K none ... -# List a specific dataset (列举某一数据集) +# 列举某一数据集的信息 $ zfs list zroot/home NAME USED AVAIL REFER MOUNTPOINT zroot/home 288K 30.8G 144K none -# List snapshots (列举快照) +# 列出快照 $ zfs list -t snapshot zroot@daily-2015-10-15 0 - 144K - zroot/ROOT@daily-2015-10-15 0 - 144K - @@ -216,14 +215,14 @@ $ zfs rename tank/root/new_home tank/root/home Delete dataset (删除数据集) ```bash -# Datasets cannot be deleted if they have any snapshots (数据集如果有快照则无法删除) +# 数据集如果有快照则无法删除 zfs destroy tank/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 @@ -234,15 +233,15 @@ zroot/home referenced 11.9G - zroot/home mounted yes - ... -# Get property from dataset (获取数据集属性) +# 获取数据集属性 $ zfs get compression zroot/usr/home NAME PROPERTY VALUE SOURCE zroot/home compression off default -# Set property on dataset (设置压缩属性compression) +# 设置数据集属性(下例为设置压缩属性compression) $ zfs set compression=gzip-9 mypool/lamb -# Get a set of properties from all datasets (列举所有数据集的名称,配额和预留属性) +# 列举所有数据集的名称、配额和预留属性 $ zfs list -o name,quota,reservation NAME QUOTA RESERV zroot none none @@ -277,10 +276,10 @@ Actions: (快照相关操作) Create snapshots (创建快照) ```bash -# Create a snapshot of a single dataset (为单一数据集创建快照) +# 为单一数据集创建快照 zfs snapshot tank/home/sarlalian@now -# Create a snapshot of a dataset and its children (为数据集及其子集创建快照) +# 为数据集及其子集创建快照 $ zfs snapshot -r tank/home@now $ zfs list -t snapshot NAME USED AVAIL REFER MOUNTPOINT @@ -293,10 +292,10 @@ tank/home/bob@now 0 - 156M - Destroy snapshots (删除快照) ```bash -# How to destroy a snapshot (如何删除) +# 如何删除快照 $ zfs destroy tank/home/sarlalian@now -# Delete a snapshot on a parent dataset and its children (删除某一数据集及其子集的快照) +# 删除某一数据集及其子集的快照 $ zfs destroy -r tank/home/sarlalian@now ``` @@ -304,7 +303,7 @@ $ zfs destroy -r tank/home/sarlalian@now Renaming Snapshots (重命名) ```bash -# Rename a snapshot (重命名快照,示例) +# 重命名快照 $ zfs rename tank/home/sarlalian@now tank/home/sarlalian@today $ zfs rename tank/home/sarlalian@now today @@ -314,37 +313,37 @@ $ zfs rename tank/home/sarlalian@now today Accessing snapshots (访问快照) ```bash -# CD Into a snapshot directory (cd进入一个快照目录) +# cd进入一个快照目录 $ cd /home/.zfs/snapshot/ ``` Sending and Receiving ```bash -# Backup a snapshot to a file (备份快照到一个文件) +# 备份快照到一个文件 $ zfs send tank/home/sarlalian@now | gzip > backup_file.gz -# Send a snapshot to another dataset (发送快照到另一个数据集) +# 发送快照到另一个数据集 $ zfs send tank/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' -# Send full dataset with snapshos to new host (发送数据集及其快照到一个新主机) +# 发送完整数据集及其快照到一个新主机 $ zfs send -v -R tank/home@now | ssh root@backup_server 'zfs recv tank/home' ``` Cloneing Snapshots (克隆快照) ```bash -# Clone a snapshot +# 克隆一个快照 $ zfs clone tank/home/sarlalian@now tank/home/sarlalian_new -# Promoting the clone so it is no longer dependent on the snapshot(提升克隆,让它不再依赖原始数据) +# 提升克隆,让它不再依赖原始快照 $ zfs promote tank/home/sarlalian_new ``` -### Putting it all together (汇总) +### 汇总 下面这个脚本使用了FreeBSD, jails和ZFS,来自动在一个mysql群集的热备主机上为一个mysq staging数据库 创建一份纯净的拷贝。 @@ -388,7 +387,7 @@ echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging ``` -### Additional Reading (延伸阅读) +### 延伸阅读 * [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) -- cgit v1.2.3 From cc9d2ca4a1691fd1af9527774dc72f441582d661 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juraj=20Kostolansk=C3=BD?= Date: Thu, 16 Jun 2016 15:03:19 +0200 Subject: [coffeescript/sk] Slovak translation for CoffeeScript (#1811) --- sk-sk/coffeescript.html.markdown | 108 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 sk-sk/coffeescript.html.markdown diff --git a/sk-sk/coffeescript.html.markdown b/sk-sk/coffeescript.html.markdown new file mode 100644 index 00000000..e716abed --- /dev/null +++ b/sk-sk/coffeescript.html.markdown @@ -0,0 +1,108 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Juraj Kostolanský", "http://www.kostolansky.sk"] +lang: sk-sk +filename: coffeescript.coffee +--- + +CoffeeScript je jazyk, ktorý sa kompiluje do ekvivalentného JavaScriptu, +neexistuje peňho interpretácia počas behu programu (runtime). +CoffeeScript sa snaží vytvárať čitateľný, pekne formátovaný a optimalizovaný +JavaScriptový kód pracujúci pod každým JavaScriptovým prostredím. + +Pozri tiež [stránku CoffeeScript](http://coffeescript.org/), ktoré obsahuje kompletný tutoriál o CoffeeScripte. + +```coffeescript +# CoffeeScript je jazyk hipsterov. +# Ide s trendom mnohých moderných jazykov. +# Komentáre sú podobné tým v Ruby a Pythone, používajú symbol #. + +### +Blokové komentáre vyzerajú takto, prekladajú sa priamo do '/ * ... * /' +pre výsledný kód JavaScriptu. + +Predtým, než budeš pokračovať, mal by si rozumieť sémantike JavaScriptu. +### + +# Priradenia: +cislo = 42 #=> var cislo = 42; +opak = true #=> var opak = true; + +# Podmienky: +cislo = -42 if opak #=> if(opak) { cislo = -42; } + +# Funkcie: +stvorec = (x) -> x * x #=> var stvorec = function(x) { return x * x; } + +vypln = (nadoba, tekutina = "káva") -> + "#{nadoba} sa napĺňa tekutinou #{tekutina}..." +#=>var vypln; +# +#vypln = function(nadoba, tekutina) { +# if (tekutina == null) { +# tekutina = "káva"; +# } +# return nadoba + " sa napĺňa tekutinou " + tekutina + "..."; +#}; + +# Rozsahy: +zoznam = [1..5] #=> var zoznam = [1, 2, 3, 4, 5]; + +# Objekty: +matika = + zaklad: Math.sqrt + stvorec: square + kocka: (x) -> x * square x +#=> var matika = { +# "zaklad": Math.sqrt, +# "stvorec": square, +# "kocka": function(x) { return x * square(x); } +#} + +# Splat operátor: +zavod = (vitaz, bezci...) -> + print vitaz, bezci +#=>zavod = function() { +# var vitaz, bezci; +# vitaz = arguments[0], +# bezci = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(vitaz, bezci); +#}; + +# Existencia: +alert "Vedel som to!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) +# { alert("Vedel som to!"); } + +# Pole: +kocky = (matika.kocka cislo for cislo in zoznam) +#=>kocky = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = zoznam.length; _i < _len; _i++) { +# cislo = zoznam[_i]; +# _results.push(matika.kocka(cislo)); +# } +# return _results; +# })(); + +jedla = ['brokolica', 'špenát', 'čokoláda'] +zjedz jedlo for jedlo in jedla when jedlo isnt 'čokoláda' +#=>jedla = ['brokolica', 'špenát', 'čokoláda']; +# +#for (_k = 0, _len2 = jedla.length; _k < _len2; _k++) { +# jedlo = jedla[_k]; +# if (jedlo !== 'čokoláda') { +# zjedz(jedlo); +# } +#} +``` + +## Ďalšie zdroje + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) -- cgit v1.2.3 From 84260a4cda5e15cf79da08b74831767fb4cca51c Mon Sep 17 00:00:00 2001 From: ven Date: Thu, 16 Jun 2016 15:03:46 +0200 Subject: Add filename to fix #1811 --- sk-sk/coffeescript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sk-sk/coffeescript.html.markdown b/sk-sk/coffeescript.html.markdown index e716abed..30bbceec 100644 --- a/sk-sk/coffeescript.html.markdown +++ b/sk-sk/coffeescript.html.markdown @@ -6,7 +6,7 @@ contributors: translators: - ["Juraj Kostolanský", "http://www.kostolansky.sk"] lang: sk-sk -filename: coffeescript.coffee +filename: coffeescript-fr.coffee --- CoffeeScript je jazyk, ktorý sa kompiluje do ekvivalentného JavaScriptu, -- cgit v1.2.3 From 367f1477f956044e5926c58639e64be68ca70494 Mon Sep 17 00:00:00 2001 From: Ryan Date: Thu, 16 Jun 2016 09:04:40 -0400 Subject: Change curly braces statement (#1804) The '$$' before the braces was a bit confusing. I added a couple lines that show that you have options on where the '$' goes when it comes to curly braces in strings. --- php.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/php.html.markdown b/php.html.markdown index 6c2b38c8..24d656fa 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -88,6 +88,8 @@ $escaped = "This contains a \t tab character."; $unescaped = 'This just contains a slash and a t: \t'; // Enclose a variable in curly braces if needed +$apples = "I have {$number} apples to eat."; +$oranges = "I have ${number} oranges to eat."; $money = "I have $${number} in the bank."; // Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners -- cgit v1.2.3 From 114387de05f459d558b05580b893fb45b8ccf89a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juraj=20Kostolansk=C3=BD?= Date: Thu, 16 Jun 2016 15:09:07 +0200 Subject: [json/sk] Slovak translation for JSON (#1812) --- sk-sk/json.html.markdown | 61 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 sk-sk/json.html.markdown diff --git a/sk-sk/json.html.markdown b/sk-sk/json.html.markdown new file mode 100644 index 00000000..b5cee796 --- /dev/null +++ b/sk-sk/json.html.markdown @@ -0,0 +1,61 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Juraj Kostolanský", "http://www.kostolansky.sk"] +lang: sk-sk +--- + +Nakoľko je JSON extrémne jednoduchý formát na výmenu dát, toto bude +pravdepodobne najjednoduchšie "Learn X in Y Minutes". + +JSON v jeho základnej forme nemá komentáre, ale veľa parserov akceptuje +komentáre v štýle C (`//`, `/* */`). V tomto návode však bude všetko +100% valídny JSON. + +```json +{ + "kľúč": "hodnota", + + "kľúč": "musí byť vždy uzavretý v dvojitých uvodzovkách", + "čísla": 0, + "reťazce": "Ahøj, svet. Unicode je povolený pri použití \"únikovej sekvencie (escaping)\".", + "boolean?": true, + "nič": null, + + "veľké číslo": 1.2e+100, + + "objekty": { + "komentár": "Väčšina štruktúry bude pochádzať z objektov.", + + "pole": [0, 1, 2, 3, "Pole môže obsahovať čokoľvek.", 5], + + "iný objekt": { + "komentár": "Môžu byť vhniezdené, čo môže byť užitočné." + } + }, + + "nezmysly": [ + { + "zdroje draslíka": ["banány"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternatívny štýl": { + "komentár": "sleduj toto!" + , "pozícia čiarky": "nezáleží na nej - pokiaľ je pred hodnotou, všetko je ok" + , "iný komentár": "pekné, že?" + }, + + "to bolo rýchle": "A už sme aj na konci. Teraz ovládš všetko, čo ti JSON môže ponúknuť." +} +``` -- cgit v1.2.3 From d82da8357c526a738b7bfda3d44f2e34c423ea7d Mon Sep 17 00:00:00 2001 From: ven Date: Thu, 16 Jun 2016 15:09:37 +0200 Subject: Fix filename for #1812 --- sk-sk/json.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sk-sk/json.html.markdown b/sk-sk/json.html.markdown index b5cee796..2b1fbb58 100644 --- a/sk-sk/json.html.markdown +++ b/sk-sk/json.html.markdown @@ -1,6 +1,6 @@ --- language: json -filename: learnjson.json +filename: learnjson-sk.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] -- cgit v1.2.3 From b3b5ece63ce00ed5983374b91d150515c5a90f69 Mon Sep 17 00:00:00 2001 From: ven Date: Thu, 16 Jun 2016 15:18:30 +0200 Subject: String length by @thesourabh --- python.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index 28b0a7ae..fa604455 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -126,6 +126,9 @@ not False # => True # A string can be treated like a list of characters "This is a string"[0] # => 'T' +# You can find the length of a string +len("This is a string") # => 16 + #String formatting with % #Even though the % string operator will be deprecated on Python 3.1 and removed #later at some time, it may still be good to know how it works. -- cgit v1.2.3 From 5affe64801a241c2307a3b2ec6950d1dc41f531b Mon Sep 17 00:00:00 2001 From: ven Date: Thu, 16 Jun 2016 15:19:43 +0200 Subject: String length by #1742 --- python3.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/python3.html.markdown b/python3.html.markdown index 2e37fccb..0f5da8f1 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -119,6 +119,9 @@ b == a # => True, a's and b's objects are equal # A string can be treated like a list of characters "This is a string"[0] # => 'T' +# You can find the length of a string +len("This is a string") # => 16 + # .format can be used to format strings, like this: "{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" -- cgit v1.2.3 From 02eec229227fa6c8fa5d3cfff77bf3905d0fbfd9 Mon Sep 17 00:00:00 2001 From: Jeroen Deviaene Date: Thu, 16 Jun 2016 15:21:35 +0200 Subject: Translated Markdown to dutch (#1815) * Translated Markdown to dutch * Translated Bash to dutch --- nl-nl/bash-nl.html.markdown | 235 ++++++++++++++++++++++++++++++++++++++ nl-nl/markdown-nl.html.markdown | 242 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 477 insertions(+) create mode 100644 nl-nl/bash-nl.html.markdown create mode 100644 nl-nl/markdown-nl.html.markdown diff --git a/nl-nl/bash-nl.html.markdown b/nl-nl/bash-nl.html.markdown new file mode 100644 index 00000000..31c110db --- /dev/null +++ b/nl-nl/bash-nl.html.markdown @@ -0,0 +1,235 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] +translators: + - ["Jeroen Deviaene", "https://www.github.com/jerodev"] +lang: nl-nl +filename: LearnBash.sh +--- + +Bash is de naam van den unix shell, deze wordt gebruikt voor het GNU operating system en is de standaard shell op Linux en Mac OS X. +Bijna alle voorbeelden hier onder kunnen deel uitmaken van een shell script of kunnen uitgevoerd worden in de shell. + +[Lees er meer over hier.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# De eerste lijn in het schript is shebang, deze laat het systeem weten hoe +# het script uitgevoerd moet worden: http://en.wikipedia.org/wiki/Shebang_(Unix) +# Zoals je kan zien wordt # gebruikt om een commentaar lijn te starten. + +# Simpel hello world voorbeeld: +echo Hello world! + +# Elke command start op een nieuwe lijn, of achter een puntkomma (;): +echo 'Dit is de eerste lijn'; echo 'Dit is de tweede lijn' + +# Een varialbe declareren gebeurt op volgende manier: +Variabele="Een string" + +# Maar niet op deze manier: +Variabele = "Een string" +# Bash ziet variable als een commando en zal een error geven omdat dit commando +# niet bestaat. + +# Of op deze manier: +Variabele= 'Een string' +# Bash zal 'Een string' zien als een commanda en een error geven omdat het niet +# gevonden kan worden. + +# Variabelen gebruiken: +echo $Variabele +echo "$Variabele" +echo '$Variabele' +# Wanneer je een variable wil toekennen, exporteren of nog anders gebruik je +# de naam zonder '$'. Als je de waarde van de variabele wilt, gebruik je een +# '$' voor de naam. + +# Strings vervangen in variables +echo ${Variabele/Een/De} +# Dit zal 'Een' vervangen door 'De' in de string + +# Substring +Length=7 +echo ${Variabele:0:Length} +# Dit zal de eerste 7 tekens van de string weergeven. + +# Standaard waarde voor variabele +echo ${Foo:-"StandaardwaardeAlsFooLeegIsOfNietBestaat"} +# Dit werkt voor null en lege strings (Foo=""). Dit werkt niet voor 0 (Foo=0). +# Merk op dat dit enkel de waarde retourneerd en de variable niet aanpast. + + +# Ingebouwde variabelen: +# Er zijn enkele zeer handige ingebouwde variabelen, zoals: +echo "Return waarde van laatste programma: $?" +echo "PID van dit script: $$" +echo "Aantal argumenten voor dit script: $#" +echo "Alle argumenten voor dit script: $@" +echo "Argumenten voor dit script in apparte variabelen: $1 $2..." + +# Een waarde lezen via input: +echo "Wat is uw naam?" +read Naam # Merk op dat we geen variabele gedeclareerd hebben +echo Hallo, $Naam! + +# We hebben ook if structuren +# Gebruik 'man test' voor meer informatie over condities. +if [ $Naam -ne $USER ] +then + echo "Uw naam is niet gelijk aan de gebruikersnaam" +else + echo "Uw naam is de gebruikersnaam" +fi + +# MERK OP: als $Naam leeg is ziet bash het bovenstaande als volgt: +if [ -ne $USER ] +# dit is ongeldige syntax +# Dus de beter manier om dit te schrijven is +if [ "$Naam" -ne $USER ] ... +# Als naam nu leeg is, ziet bash nu nog steeds +if [ "" -ne $USER ] ... +# Dit werkt wel zoals het hoort + +# Er is ook conditionele executie +echo "Altijd uitvoeren" || echo "Enkel uitvoeren als vorige command mislukt" +echo "Altijd uitvoeren" && echo "Enkel uitvoeren als vorige command NIET mislukt" + +# Om && en || te gebruiken in if structuren moeten vierkante haken gebruikt worden: +if [ "$Naam" == "Steve" ] && [ "$Leeftijd" -eq 15 ] +then + echo "Dit wordt uitgevoerd als $Naam Steve is en $Leeftijd 15 is." +fi + +# Expressies worden gemaakt met volgende syntax: +echo $(( 10 + 5 )) + +# Bash werkt steeds in de context van een huidige map in het bestandssysteem. +# Bestanden en mappen in de huidige map kunnen weergegeven worden met het ls +# commando. +ls + +# Commandos hebben opties die de uitvoer beinvloeden +ls -l # Lijst elk bestand en map op een nieuwe lijn. + +# Resultaten van een vorig commando kunnen doorgegeven worden aan een volgend +# commando als input. +# Het grep commando filter de input met een bepaald patroon. Op deze manier kunnen +# we alle .txt bestanden weergeven in de huidige map. +ls -l | grep "\.txt" + +# Commando's kunnen gekoppeld worden met andere commando's door gebruik te maken van +# $( ): +# Het volgende commando geeft het aantal bestanden weer in de huidige map +echo "Er zijn hier $(ls | wc -l) bestanden." + +# Het zelfde kan gedaan worden met `, maar die kunnen niet genest worden. De methode +# bij voorkeur is om $( ) te gebruiken. +echo "Er zijn hier `ls | wc -l` bestanden." + +# Bash heeft een case statement dat werkt zoals in Java en C++ +case "$Variabele" in + 0) echo "Er is een 0";; + 1) echo "Er is een 1";; + *) echo "Er is iets";; +esac + +# For lussen itereren over de gegeven argumenten +# De waarde van $Variabele wordt hier drie keer afgeprint +for Variable in {1..3} +do + echo "$Variabele" +done + +# Of schrijf een traditionele for loop op deze manier +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Lussen kunnen ook gebruikt worden met bestanden +# Deze lus voert het cat commando uit op file1 en file2 +for Variable in file1 file2 +do + cat "$Variable" +done + +# Of met het output commando +for Output in $(ls) +do + cat "$Output" +done + +# while lus: +while [ true ] +do + echo "body van de lus..." + break +done + +# Je kan ook functies aanmaken +# Defenitie: +function foo () +{ + echo "Alle argumenten: $@" + echo "Apparte argumenten: $1 $2..." + echo "Dit is een functie" + return 0 +} + +# Of simpeler +bar () +{ + echo "Dit is een andere manier om functies te maken." + return 0 +} + +# Functies oproepen +foo "Mijn naam is" $Naam + +# Enkele zeer handige commando's die je moet kennen +# print de laatste 10 lijnen van file.txt +tail -n 10 file.txt +# print de eerste 10 lijnen van file.txt +head -n 10 file.txt +# Sorteer de lijnen in file.txt +sort file.txt +# Vind dubbele lijnen in file.txt +uniq -d file.txt +# Print de eerste kolom voor het ',' karakter +cut -d ',' -f 1 file.txt +# Vervang elke 'okay' met 'great' in file.txt (werkt ook met regex) +sed -i 's/okay/great/g' file.txt +# Print alle lijnen die voldoen aan de regex naar stdout +grep "^foo.*bar$" file.txt + + +# Gebruik de ingebouwde help functies door het help commando te gebruiken: +help +help help +help for +help return +help source +help . + +# Lees de bash documentatie met het man commando: +apropos bash +man 1 bash +man bash + +# Lees bash info documentatie: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` diff --git a/nl-nl/markdown-nl.html.markdown b/nl-nl/markdown-nl.html.markdown new file mode 100644 index 00000000..3dcfd4c8 --- /dev/null +++ b/nl-nl/markdown-nl.html.markdown @@ -0,0 +1,242 @@ +--- +language: markdown +filename: markdown.md +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Jeroen Deviaene", "https://www.github.com/jerodev"] +lang: nl-nl +--- + +Markdown is gecreëerd door John Gruber in 2004. Het is bedoeld om met een gemakkelijke te lezen en +schrijven syntax te zijn die gemakkelijk omgevormd kan worden naar HTML (en op heden verschillende +andere formaten) + +```markdown + + + + + + +Dit is een h1 +============= + +Dit is een h2 +------------- + + + + +*Deze tekst is cursief* +_Deze tekst ook_ + +**Deze tekst is vet gedrukt** +__En deze tekst ook!__ + +***Deze tekst is zowel bold als schuin gedrukt*** +**_Deze ook!_** +*__En zelfs deze!__* + + + +~~Deze tekst wordt doorstreept.~~ + + + +Dit is een paragraaf. + +Dit is paragraaf 2. +Dit is nog steeds paragraaf 2! + + +Hallo, ik ben paragraaf 3. + + + +> Dit is een citaat. Je kan alle lijnen manueel starten met een '>'. +> Of je kan de lijn heel heel, heel, lang laten worden zodat de parser deze automatisch zal afbreken en op een nieuwe lijn plaatsen. +> Het maakt niet uit, zolang je start met een '>'. + +> Je kan ook in niveaus werken +>> Niveau 2 +> Hoe leuk is dat? + + + + +* Item +* Item +* Nog een item + +of + ++ Item ++ Item ++ Nog een item + +of + +- Item +- Item +- Een laatste item + + + +1. Item een +2. Item twee +3. Item drie + + + +1. Item een +1. Item twe +1. Item drie + + + + +1. Item een +2. Item twee +3. Item drie + * Sub-item + * Sub-item +4. Item vier + + + +Boxen zonder een 'x' zijn niet aangevinkt +- [ ] Eerste to-do item. +- [ ] Tweede to-do item +Dit item zal aangevinkt zijn in de gerenderde html. +- [x] Deze taak is uitgevoerd + + + + + Dit is code + En dit ook + + + + my_array.each do |item| + puts item + end + + + +John wist zelfs niet dat de `go_to()` functie bestond! + + + +\`\`\`ruby +def foobar + puts "Hello world!" +end +\`\`\` + + + + +*** +--- +- - - +**************** + + + + +[Klik mij!](http://test.com/) + + + +[Klik mij!](http://test.com/ "Titel voor de link") + + + +[Naar de muziek](/music/). + + + +[Klik deze link][link1] voor meer info! +[Beijk ook dit][foobar] als je echt wil. + +[link1]: http://test.com/ "Cool!" +[foobar]: http://foobar.biz/ "Tof!" + + + + + +![Dit is de alt waarde van een afbeelding](http://imgur.com/myimage.jpg "Optionele titel") + + + +![Dit is de alt waarde][myimage] + +[myimage]: relative/urls/cool/image.jpg "als een titel nodig is, staat deze hier" + + + + + is gelijk aan +[http://testwebsite.com/](http://testwebsite.com/) + + + + + + + +Als je sterretjes wil gebruiken in je tekst zoals *dit* dan zal dit schuingedrukt weergegeven +worden. +Dit kan je oplossen met backslashes: \*dit\* staat tussen sterretjes + + + + +Loopt je computer vast? Probeer volgende toetsen combinatie: +Ctrl+Alt+Del + + + + +| Col1 | Col2 | Col3 | +| :--------------- | :---------: | ----------------: | +| Links uitgelijnt | Gecentreerd | Rechts uitgelijnt | +| blah | blah | blah | + + + +Col 1 | Col2 | Col3 +:-- | :-: | --: +Zeer | Lelijke | Code! + + + +``` + +Voor meer info, bekijk de officiële post van John Gruber [hier](http://daringfireball.net/projects/markdown/syntax) en de handige cheatsheet van Adam Pritchard [hier](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From 1e117c111fab6c1db9532bdd5d72569547d396c8 Mon Sep 17 00:00:00 2001 From: ven Date: Thu, 16 Jun 2016 15:22:06 +0200 Subject: fix yaml in #1815 --- nl-nl/bash-nl.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nl-nl/bash-nl.html.markdown b/nl-nl/bash-nl.html.markdown index 31c110db..da47e2a9 100644 --- a/nl-nl/bash-nl.html.markdown +++ b/nl-nl/bash-nl.html.markdown @@ -12,9 +12,9 @@ contributors: - ["Gregrory Kielian", "https://github.com/gskielian"] - ["Etan Reisner", "https://github.com/deryni"] translators: - - ["Jeroen Deviaene", "https://www.github.com/jerodev"] + - ["Jeroen Deviaene", "https://www.github.com/jerodev"] lang: nl-nl -filename: LearnBash.sh +filename: LearnBash-nl.sh --- Bash is de naam van den unix shell, deze wordt gebruikt voor het GNU operating system en is de standaard shell op Linux en Mac OS X. -- cgit v1.2.3 From 0484537a1cf42a9ac2adea31d63d5d9286546a91 Mon Sep 17 00:00:00 2001 From: ven Date: Thu, 16 Jun 2016 15:22:17 +0200 Subject: Fix yaml in #1815 --- nl-nl/markdown-nl.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-nl/markdown-nl.html.markdown b/nl-nl/markdown-nl.html.markdown index 3dcfd4c8..35cc67c5 100644 --- a/nl-nl/markdown-nl.html.markdown +++ b/nl-nl/markdown-nl.html.markdown @@ -1,6 +1,6 @@ --- language: markdown -filename: markdown.md +filename: markdown-nl.md contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: -- cgit v1.2.3 From bf32d58d75f640666d67ff3c07b618a5dd83a493 Mon Sep 17 00:00:00 2001 From: Keith Miyake Date: Sun, 19 Jun 2016 09:59:26 -0400 Subject: [SASS] Add control directives, and misc. fixes (#1805) * [SASS] Add control directives, other selector uses, and variables in selector names * sass: add contributor credit --- sass.html.markdown | 153 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 149 insertions(+), 4 deletions(-) diff --git a/sass.html.markdown b/sass.html.markdown index 4d4ece71..802b40f4 100644 --- a/sass.html.markdown +++ b/sass.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Laura Kyle", "https://github.com/LauraNK"] - ["Sean Corrales", "https://github.com/droidenator"] - ["Kyle Mendes", "https://github.com/pink401k"] + - ["Keith Miyake", "https://github.com/kaymmm"] --- Sass is a CSS extension language that adds features such as variables, nesting, mixins and more. @@ -52,16 +53,161 @@ body { font-family: 'Roboto', sans-serif; } - /* This is much more maintainable than having to change the color each time it appears throughout your stylesheet. */ -/* Mixins +/* Control Directives ============================== */ +/* Sass lets you use @if, @else, @for, @while, and @each to control the + compilation of your code to CSS. */ + +/* @if/@else blocks behave exactly as you might expect */ + +$debug: true !default; + +@mixin debugmode { + @if $debug { + @debug "Debug mode enabled"; + + display: inline-block; + } + @else { + display: none; + } +} + +.info { + @include debugmode; +} + +/* If $debug is set to true, .info is displayed; if it's set to false then +.info is not displayed. + +Note: @debug will output debugging information to the command line. +Useful for checking variables while debugging your SCSS. */ + +.info { + display: inline-block; +} + +/* @for is a control loop that iterates through a range of values. +Particularly useful for setting styles on a collection of items. +There are two forms, "through" and "to." The former includes the last value, +the latter stops at the last value. */ + +@for $c from 1 to 4 { + div:nth-of-type(#{$c}) { + left: ($c - 1) * 900 / 3; + } +} + +@for $c from 1 through 3 { + .myclass-#{$c} { + color: rgb($c * 255 / 3, $c * 255 / 3, $c * 255 / 3); + } +} + +/* Will compile to: */ +div:nth-of-type(1) { + left: 0; +} + +div:nth-of-type(2) { + left: 300; +} + +div:nth-of-type(3) { + left: 600; +} + +.myclass-1 { + color: #555555; +} + +.myclass-2 { + color: #aaaaaa; +} + +.myclass-3 { + color: white; +// SASS automatically converts #FFFFFF to white +} + +/* @while is very straightforward: */ + +$columns: 4; +$column-width: 80px; + +@while $columns > 0 { + .col-#{$columns} { + width: $column-width; + left: $column-width * ($columns - 1); + } + + $columns: $columns - 1; +} + +/* Will output the following CSS: */ + +.col-4 { + width: 80px; + left: 240px; +} + +.col-3 { + width: 80px; + left: 160px; +} + +.col-2 { + width: 80px; + left: 80px; +} + +.col-1 { + width: 80px; + left: 0px; +} + +/* @each functions like @for, except using a list instead of ordinal values +Note: you specify lists just like other variables, with spaces as +delimiters. */ + +$social-links: facebook twitter linkedin reddit; + +.social-links { + @each $sm in $social-links { + .icon-#{$sm} { + background-image: url("images/#{$sm}.png"); + } + } +} + +/* Which will output: */ + +.social-links .icon-facebook { + background-image: url("images/facebook.png"); +} + +.social-links .icon-twitter { + background-image: url("images/twitter.png"); +} + +.social-links .icon-linkedin { + background-image: url("images/linkedin.png"); +} + +.social-links .icon-reddit { + background-image: url("images/reddit.png"); +} + + +/*Mixins +==============================*/ /* If you find you are writing the same code for more than one element, you might want to store that code in a mixin. @@ -93,7 +239,6 @@ div { background-color: #A3A4FF; } - /* You can use mixins to create a shorthand property. */ @mixin size($width, $height) { @@ -139,7 +284,7 @@ body { } .footer { - background-color: fade_out(#000000, 0.25) + background-color: fade_out(#000000, 0.25); } /* Compiles to: */ -- cgit v1.2.3 From eaf0307775733fddebe308a5a98b7b386f3820cf Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 20 Jun 2016 14:56:44 -0400 Subject: Security additions + edits (#2281) * Edits with a focus on security risks * Modified example * Flip sign - example of the risk of Solidity code when published to an append only ledger * Fixed formatting --- solidity.html.markdown | 133 ++++++++++++++++++++++++++++++++++++------------- 1 file changed, 97 insertions(+), 36 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index a511bbb3..9bf5bf4d 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -8,7 +8,7 @@ contributors: Solidity lets you program on [Ethereum](https://www.ethereum.org/), a blockchain-based virtual machine that allows the creation and -execution of smart contracts, without needing centralized or trusted parties. +execution of smart contracts, without requiring centralized or trusted parties. Solidity is a statically typed, contract programming language that has similarities to Javascript and C. Like objects in OOP, each contract contains @@ -18,8 +18,17 @@ global variables. Some Ethereum contract examples include crowdfunding, voting, and blind auctions. +There is a high risk and high cost of errors in Solidity code, so you must be very careful to test +and slowly rollout. WITH THE RAPID CHANGES IN ETHEREUM, THIS DOCUMENT IS UNLIKELY TO STAY UP TO +DATE, SO YOU SHOULD FOLLOW THE SOLIDITY CHAT ROOM AND ETHEREUM BLOG FOR THE LATEST. ALL CODE HERE IS +PROVIDED AS IS, WITH SUBSTANTIAL RISK OF ERRORS OR DEPRECATED CODE PATTERNS. + +Unlike other code, you may also need to add in design patterns like pausing, deprecation, and +throttling usage to reduce risk. This document primarily discusses syntax, and so excludes many +popular design patterns. + As Solidity and Ethereum are under active development, experimental or beta -features are explicitly marked, and subject to change. Pull requests welcome. +features are typically marked, and subject to change. Pull requests welcome. ```javascript // First, a simple Bank contract @@ -40,6 +49,7 @@ contract SimpleBank { // CamelCase // Declare state variables outside function, persist through life of contract // dictionary that maps addresses to balances + // always be careful about overflow attacks with numbers mapping (address => uint) private balances; // "private" means that other contracts can't directly query balances @@ -49,7 +59,7 @@ contract SimpleBank { // CamelCase // 'public' makes externally readable (not writeable) by users or contracts // Events - publicize actions to external listeners - event DepositMade(address accountAddress, uint amount); + event LogDepositMade(address accountAddress, uint amount); // Constructor, can receive one or many variables here; only one allowed function AcmeBank() { @@ -65,7 +75,7 @@ contract SimpleBank { // CamelCase // no "this." or "self." required with state variable // all values set to data type's initial value by default - DepositMade(msg.sender, msg.value); // fire event + LogDepositMade(msg.sender, msg.value); // fire event return balances[msg.sender]; } @@ -76,11 +86,14 @@ contract SimpleBank { // CamelCase /// @return The balance remaining for the user function withdraw(uint withdrawAmount) public returns (uint remainingBal) { if(balances[msg.sender] >= withdrawAmount) { + // Note the way we deduct the balance right away, before sending - due to + // the risk of a recursive call that allows the caller to request an amount greater + // than their balance balances[msg.sender] -= withdrawAmount; if (!msg.sender.send(withdrawAmount)) { - // to be safe, may be sending to contract that - // has overridden 'send' which may then fail + // increment back only on fail, as may be sending to contract that + // has overridden 'send' on the receipt end balances[msg.sender] += withdrawAmount; } } @@ -150,8 +163,10 @@ address public owner; // All addresses can be sent ether owner.send(SOME_BALANCE); // returns false on failure -if (owner.send) {} // typically wrap in 'if', as contract addresses have -// functions have executed on send and can fail +if (owner.send) {} // REMEMBER: wrap in 'if', as contract addresses have +// functions executed on send and these can fail +// Also, make sure to deduct balances BEFORE attempting a send, as there is a risk of a recursive +// call that can drain the contract // can override send by defining your own @@ -351,8 +366,11 @@ function b() { // access events from outside blockchain (with lightweight clients) // typically declare after contract parameters +// Typically, capitalized - and add Log in front to be explicit and prevent confusion +// with a function call + // Declare -event Sent(address from, address to, uint amount); // note capital first letter +event LogSent(address indexed from, address indexed to, uint amount); // note capital first letter // Call Sent(from, to, amount); @@ -396,7 +414,10 @@ onlyIfState(State.A) modifier checkValue(uint amount) { _ if (msg.value > amount) { - msg.sender.send(amount - msg.value); + uint amountToRefund = amount - msg.value; + if (!msg.sender.send(amountToRefund)) { + throw; + } } } @@ -409,6 +430,21 @@ modifier checkValue(uint amount) { // Syntax same as javascript, but no type conversion from non-boolean // to boolean (comparison operators must be used to get the boolean val) +// For loops that are determined by user behavior, be careful - as contracts have a maximal +// amount of gas for a block of code - and will fail if that is exceeded +// For example: +for(uint x = 0; x < refundAddressList.length; x++) { + if (!refundAddressList[x].send(SOME_AMOUNT)) { + throw; + } +} + +// Two errors above: +// 1. A failure on send stops the loop from completing, tying up money +// 2. This loop could be arbitrarily long (based on the amount of users who need refunds), and +// therefore may always fail as it exceeds the max gas for a block +// Instead, you should let people withdraw individually from their subaccount, and mark withdrawn + // 7. OBJECTS/CONTRACTS @@ -587,13 +623,13 @@ contract CrowdFunder { address public fundRecipient; // creator may be different than recipient uint public minimumToRaise; // required to tip, else everyone gets refund string campaignUrl; + byte constant version = 1; // Data structures enum State { Fundraising, - ExpiredRefundPending, - Successful, - ExpiredRefundComplete + ExpiredRefund, + Successful } struct Contribution { uint amount; @@ -604,11 +640,11 @@ contract CrowdFunder { State public state = State.Fundraising; // initialize on create uint public totalRaised; uint public raiseBy; + uint public completeAt; Contribution[] contributions; - event fundingReceived(address addr, uint amount, uint currentTotal); - event allRefundsSent(); - event winnerPaid(address winnerAddress); + event LogFundingReceived(address addr, uint amount, uint currentTotal); + event LogWinnerPaid(address winnerAddress); modifier inState(State _state) { if (state != _state) throw; @@ -620,10 +656,13 @@ contract CrowdFunder { _ } + // Wait 6 months after final contract state before allowing contract destruction modifier atEndOfLifecycle() { - if(state != State.ExpiredRefundComplete && state != State.Successful) { + if(!((state == State.ExpiredRefund || state == State.Successful) && + completeAt + 6 months < now)) { throw; } + _ } function CrowdFunder( @@ -651,9 +690,10 @@ contract CrowdFunder { ); totalRaised += msg.value; - fundingReceived(msg.sender, msg.value, totalRaised); + LogFundingReceived(msg.sender, msg.value, totalRaised); checkIfFundingCompleteOrExpired(); + return contributions.length - 1; // return id } function checkIfFundingCompleteOrExpired() { @@ -663,9 +703,9 @@ contract CrowdFunder { // could incentivize sender who initiated state change here } else if ( now > raiseBy ) { - state = State.ExpiredRefundPending; - refundAll(); + state = State.ExpiredRefund; // backers can now collect refunds by calling getRefund(id) } + completeAt = now; } function payOut() @@ -676,22 +716,27 @@ contract CrowdFunder { throw; } - winnerPaid(fundRecipient); + + LogWinnerPaid(fundRecipient); } - function refundAll() + function getRefund(id) public - inState(State.ExpiredRefundPending) + inState(State.ExpiredRefund) { - uint length = contributions.length; - for (uint i = 0; i < length; i++) { - if(!contributions[i].contributor.send(contributions[i].amount)) { - throw; - } + if (contributions.length <= id || id < 0 || contributions[id].amount == 0 ) { + throw; + } + + uint amountToRefund = contributions[id].amount; + contributions[id].amount = 0; + + if(!contributions[id].contributor.send(amountToSend)) { + contributions[id].amount = amountToSend; + return false; } - allRefundsSent(); - state = State.ExpiredRefundComplete; + return true; } function removeContract() @@ -700,13 +745,13 @@ contract CrowdFunder { atEndOfLifecycle() { selfdestruct(msg.sender); + // creator gets all money that hasn't be claimed } function () { throw; } } // ** END EXAMPLE ** - // 10. OTHER NATIVE FUNCTIONS // Currency units @@ -732,8 +777,14 @@ sha3("ab", "cd"); ripemd160("abc"); sha256("def"); +// 11. SECURITY + +// Bugs can be disastrous in Ethereum contracts - and even popular patterns in Solidity, +// may be found to be antipatterns -// 11. LOW LEVEL FUNCTIONS +// See security links at the end of this doc + +// 12. LOW LEVEL FUNCTIONS // call - low level, not often used, does not provide type safety successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2'); @@ -742,7 +793,7 @@ successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2'); someContractAddress.callcode('function_name'); -// 12. STYLE NOTES +// 13. STYLE NOTES // Based on Python's PEP8 style guide // Quick summary: @@ -753,7 +804,7 @@ someContractAddress.callcode('function_name'); // else should be placed on own line -// 13. NATSPEC COMENTS +// 14. NATSPEC COMENTS // used for documentation, commenting, and external UIs // Contract natspec - always above contract definition @@ -773,9 +824,8 @@ someContractAddress.callcode('function_name'); - [Solidity Docs](https://solidity.readthedocs.org/en/latest/) - [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. - [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) -- [Gitter Chat room](https://gitter.im/ethereum/solidity) +- [Gitter Solidity Chat room](https://gitter.im/ethereum/solidity) - [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/) -- Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc)) ## Sample contracts - [Dapp Bin](https://github.com/ethereum/dapp-bin) @@ -783,13 +833,24 @@ someContractAddress.callcode('function_name'); - [ConsenSys Contracts](https://github.com/ConsenSys/dapp-store-contracts) - [State of Dapps](http://dapps.ethercasts.com/) +## Security +- [Thinking About Smart Contract Security](https://blog.ethereum.org/2016/06/19/thinking-smart-contract-security/) +- [Smart Contract Security](https://blog.ethereum.org/2016/06/10/smart-contract-security/) +- [Hacking Distributed Blog](http://hackingdistributed.com/) + ## Information purposefully excluded - Libraries ## Style - Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy +## Editors +- [Vim Solidity](https://github.com/tomlion/vim-solidity) +- Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc)) + ## Future To Dos - New keywords: protected, inheritable +- List of common design patterns (throttling, RNG, version upgrade) +- Common security anti patterns Feel free to send a pull request with any edits - or email nemild -/at-/ gmail -- cgit v1.2.3 From 7895dcc6043d9229b593516ebf17cca08a515227 Mon Sep 17 00:00:00 2001 From: Felipe Martins Date: Tue, 21 Jun 2016 18:20:59 -0300 Subject: Add example of an int is divided by a double (#2284) --- scala.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/scala.html.markdown b/scala.html.markdown index 745605ed..7f5f0ec3 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -88,6 +88,7 @@ true == false // false 6 / 2 // 3 6 / 4 // 1 6.0 / 4 // 1.5 +6 / 4.0 // 1.5 // Evaluating an expression in the REPL gives you the type and value of the result -- cgit v1.2.3 From 83eb5dd94eabe8f3309beacdbe5efa7ef719fefe Mon Sep 17 00:00:00 2001 From: WeizhongTu Date: Thu, 23 Jun 2016 13:50:44 +0800 Subject: fix spelling mistake --- zh-cn/r-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/r-cn.html.markdown b/zh-cn/r-cn.html.markdown index 0c46bc22..55a29b11 100644 --- a/zh-cn/r-cn.html.markdown +++ b/zh-cn/r-cn.html.markdown @@ -285,7 +285,7 @@ while (a > 4) { } # 记住,在 R 语言中 for / while 循环都很慢 -# 建议使用 apply()(我们一会介绍)来错做一串数据(比如一列或者一行数据) +# 建议使用 apply()(我们一会介绍)来操作一串数据(比如一列或者一行数据) # IF/ELSE -- cgit v1.2.3 From 912d546dc7e6c83cbac4800aff6116dd77101b5d Mon Sep 17 00:00:00 2001 From: Devin Soni Date: Sun, 26 Jun 2016 08:30:39 -0400 Subject: add dict.items() (#2290) --- python.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index fa604455..2105748c 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -301,6 +301,9 @@ filled_dict.keys() # => ["three", "two", "one"] filled_dict.values() # => [3, 2, 1] # Note - Same as above regarding key ordering. +# Get all key-value pairs as a list of tuples with "items()" +filled_dicts.items() # => [("one", 1), ("two", 2), ("three", 3)] + # Check for existence of keys in a dictionary with "in" "one" in filled_dict # => True 1 in filled_dict # => False -- cgit v1.2.3 From cdda9936e9385198e338cd6e5b6fb4a3ec69c7cd Mon Sep 17 00:00:00 2001 From: Vipul Sharma Date: Sun, 26 Jun 2016 18:02:15 +0530 Subject: Added Hindi amd (#1673) * Added Hindi amd.html.maarkdown * Added D.html.markdown * removed * Added D.html.markdown * Fixing.. * Added D.html.markup finally --- hd-hd/amd.html.markdown | 206 ++++++++++++++++++++++++++++++++++++++ hd-hd/d.html.markdown | 256 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 462 insertions(+) create mode 100644 hd-hd/amd.html.markdown create mode 100644 hd-hd/d.html.markdown diff --git a/hd-hd/amd.html.markdown b/hd-hd/amd.html.markdown new file mode 100644 index 00000000..ac8400ad --- /dev/null +++ b/hd-hd/amd.html.markdown @@ -0,0 +1,206 @@ +--- +category: tool +tool: amd +contributors: + - ["Frederik Ring", "https://github.com/m90"] +filename: learnamd.js +--- +## एएमडी के साथ प्रारंभ करना + +एपीआई को परिभाषित करने के लिए एक तंत्र को निर्दिष्ट ** ** अतुल्यकालिक मॉड्यूल परिभाषा +जावास्क्रिप्ट मॉड्यूल ऐसे मॉड्यूल और इसकी अतुल्यकालिक निर्भरता से भरा हुआ है। यह ब्राउज़र पर्यावरण जहां के लिए विशेष रूप से अच्छी तरह से अनुकूल है, और प्रदर्शन , प्रयोज्य, डीबगिंग, और क्रॉस-डोमेन जैसे मॉड्यूल्स को जल्दी सिंक्रनाइज़ लोडिंग करता hai। + +### मूल अवधारणा +```javascript +// बुनियादी एएमडी एपीआई दो तरीकों लेकिन कुछ भी नहीं होते : ` define` और` require` +// और सभी मॉड्यूल परिभाषा और खपत के बारे में है : +// `define` एक मॉड्यूल को परिभाषित करता है +// ` require` निर्भरता का एक सेट का आयात करता है और +// पारित कर दिया कॉलबैक में उन्हें सेवन करती है + +// एक नया नाम देकर हम मॉड्यूल को परिभाषित करने का उपयोग करके शुरू करते हैं +// जिसकी कोई निर्भरता है । हम एक नाम से गुजर रहा है ऐसा करेंगे +// और एक कारखाने समारोह को परिभाषित करने के लिए : +define('awesomeAMD', function(){ + var isAMDAwesome = function(){ + return true; + }; +// एक मॉड्यूल के कारखाने समारोह की मान है + // जब प्राप्त होगा क्या अन्य मॉड्यूल या आवश्यकता कॉल + // हमारे ` awesomeAMD` मॉड्यूल की आवश्यकता होती है । + // निर्यात मूल्य कुछ भी हो सकता है, (निर्माता ) काम करता है, + // वस्तुओं, पुरातन, (जो कि बहुत ज्यादा मदद नहीं करेगा , हालांकि) भी अपरिभाषित । + return isAMDAwesome; +}); + +// अब, हमारे ` awesomeAMD` मॉड्यूल पर निर्भर करता है कि किसी अन्य मॉड्यूल परिभाषित करते हैं। +// हमारे परिभाषित करने के लिए एक अतिरिक्त तर्क है कि नोटिस +अब // मॉड्यूल की निर्भरता : +define('loudmouth', ['awesomeAMD'], function(awesomeAMD){ +// निर्भरता कारखाने के तर्कों को पारित हो जाएगा + // क्रम में वे निर्दिष्ट कर रहे हैं + var tellEveryone = function(){ + if (awesomeAMD()){ + alert('This is sOoOo rad!'); + } else { + alert('Pretty dull, isn\'t it?'); + } + }; + return tellEveryone; +}); + +// हम अब परिभाषित का उपयोग करने के लिए कैसे जानते हैं के रूप में, के लिए ` require` का उपयोग करते हैं +// हमारे कार्यक्रम बंद किक । ` require` के हस्ताक्षर है :(arrayOfDependencies, callback)`. +require(['loudmouth'], function(loudmouth){ + loudmouth(); +}); + +// इस ट्यूटोरियल रन कोड बनाने के लिए है, चलो एक बहुत ही बुनियादी लागू करते हैं +// (गैर अतुल्यकालिक ) की मौके पर यहीं एएमडी के संस्करण: +function define(name, deps, factory){ +// निर्भरता के बिना मॉड्यूल नियंत्रित किया जाता है कैसे नोटिस + define[name] = require(factory ? deps : [], factory || deps); +} + +function require(deps, callback){ + var args = []; + // पहले की जरूरत है सभी निर्भरता पुनः प्राप्त करते हैं + // आवश्यकता कॉल द्वारा + for (var i = 0; i < deps.length; i++){ + args[i] = define[deps[i]]; + } +// सभी कॉलबैक की निर्भरता को संतुष्ट + return callback.apply(null, args); +} +// आप यहाँ कार्रवाई में इस कोड को देख सकते हैं: http://jsfiddle.net/qap949pd/ +``` + +### Require.js के साथ वास्तविक दुनिया के उपयोग + +परिचयात्मक उदाहरण के विपरीत, ` require.js` (सबसे लोकप्रिय एएमडी पुस्तकालय ) वास्तव में लागू करता है ** ** Amd ** में *A * **, आप XHR के माध्यम से मॉड्यूल और उनकी निर्भरता लोड करने के लिए सक्षम करने के लिए : +```javascript +/* file: app/main.js */ +require(['modules/someClass'], function(SomeClass){ + // निर्भरता लोड होने तक कॉलबैक टाल दिया गया है + var thing = new SomeClass(); +}); +console.log('So here we are, waiting!'); // this will run first +``` + +परंपरा के अनुसार , आप आमतौर पर एक फाइल में एक मॉड्यूल में ही रखते है । ` require.js` फ़ाइल पथ पर आधारित मॉड्यूल नाम को हल कर सकते हैं , तो आप अपने मॉड्यूल के नाम करने की जरूरत नहीं है , लेकिन बस उनके स्थान का उपयोग कर उन्हें संदर्भित कर सकते हैं । उदाहरण के `में someClass` आपके विन्यास की ` baseUrl` के सापेक्ष ` modules` फ़ोल्डर में माना गया है : + +* app/ + * main.js + * modules/ + * someClass.js + * someHelpers.js + * ... + * daos/ + * things.js + * ... + +इसका मतलब यह है कि हम एक मॉड्यूल आईडी निर्दिष्ट किए बिना ` someClass` परिभाषित कर सकते हैं : + +```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; +}); +``` +अपने ` main.js` में डिफ़ॉल्ट पथ मानचित्रण व्यवहार का उपयोग ` requirejs.config ( configObj ) ` में परिवर्तन करने के लिए: + +```javascript +/* file: main.js */ +requirejs.config({ + baseUrl : 'app', + paths : { + // आप भी अन्य स्थानों से मॉड्यूल लोड कर सकते हैं + 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){ + //एक ` main` फ़ाइल में कम से कम एक बार की आवश्यकता को फोन करने की जरूरत है, + // अन्यथा कोई कोड कभी चलेंगे + coolLib.doFancyStuffWith(helpers.transform($('#foo'))); +}); +``` +` require.js` आधारित क्षुधा आमतौर पर एक डाटा विशेषता के रूप में ` require.js` स्क्रिप्ट टैग को पारित कर दिया है कि एक एकल प्रवेश बिंदु (` main.js` ) होगा। यह स्वचालित रूप से भरी हुई है और pageload पर क्रियान्वित किया जाएगा : + +```html + + + + A hundred script tags? Never again! + + + + + +``` + +### R.js का उपयोग कर एक पूरी परियोजना का अनुकूलन + +कई लोगों को विकास के दौरान समझदार कोड संगठन के लिए एएमडी का उपयोग कर पसंद करते हैं, लेकिन अभी भी पेज लोड पर XHRs के सैकड़ों करने के बजाय उत्पादन में एक भी स्क्रिप्ट फ़ाइल जहाज करने के लिए चाहते हैं। + +(राइनो भी समर्थन किया है, तो आप शायद 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 */ +({ + name : 'main', // प्रवेश बिंदु के नाम + out : 'main-built.js', // फ़ाइल का नाम करने के लिए उत्पादन में लिखने के लिए + baseUrl : 'app', + paths : { + // ` empty :` का उपयोग कर , यह अभी भी समन्वय से लोड किया जाना चाहिए कि r.js बताता है + // main.js में निर्दिष्ट स्थान + jquery : 'empty:', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}) +``` + +उत्पादन में बनाया फ़ाइल का उपयोग करने के लिए, बस ` Data-main` स्वैप: +```html + +``` + +एक अविश्वसनीय रूप से विस्तृत [निर्माण विकल्पों में से अवलोकन] (https://github.com/jrburke/r.js/blob/master/build/example.build.js) GitHub रेपो में उपलब्ध है। + +### विषय इस ट्यूटोरियल में शामिल नहीं +* [लोडर प्लगइन्स / रूपांतरण] (http://requirejs.org/docs/plugins.html) +* [CommonJS शैली लोड हो रहा है और निर्यात] (http://requirejs.org/docs/commonjs.html) +* [उन्नत विन्यास] (http://requirejs.org/docs/api.html#config) +* [शिम विन्यास (गैर एएमडी मॉड्यूल लोडिंग)] (http://requirejs.org/docs/api.html#config-shim) +* [सीएसएस लदान और require.js साथ अनुकूलन] (http://requirejs.org/docs/optimization.html#onecss) +* (Https://github.com/jrburke/almond) [बनाता है के लिए almond.js का प्रयोग] + +### अग्रिम पठन: + +* [सरकारी कल्पना] (https://github.com/amdjs/amdjs-api/wiki/AMD) +* [क्यों एएमडी?] (Http://requirejs.org/docs/whyamd.html) +* [यूनिवर्सल मॉड्यूल परिभाषा] (https://github.com/umdjs/umd) + +### कार्यान्वयन: + +* [Require.js] (http://requirejs.org) +* [डोजो टूलकिट] (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) +* [एमडी] (https://github.com/alexlawrence/mmd) diff --git a/hd-hd/d.html.markdown b/hd-hd/d.html.markdown new file mode 100644 index 00000000..80cf3bed --- /dev/null +++ b/hd-hd/d.html.markdown @@ -0,0 +1,256 @@ +--- +language: D +filename: learnd.d +contributors: + - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] +lang: en +--- + +```c +//क्या आ रहा है पता है ... +module hello; + +import std.stdio; + +void main(string[] args) { + writeln("Hello, World!"); +} +``` + +अगर आप मेरे जैसे हैं और इंटरनेट पर समय बहुत अधिक समय खर्च करते हैं, तो आप बाधाओं के बारे में सुना है +के बारे में [डी ] ( http://dlang.org/ )। डी प्रोग्रामिंग भाषा में एक आधुनिक, सामान्य प्रयोजन है , +सब कुछ के लिए समर्थन कम स्तर की सुविधाओं से करने के साथ बहु - प्रतिमान भाषा +अर्थपूर्ण उच्च स्तरीय चीजें । + +D सक्रिय रूप से सुपर स्मार्ट लोगों का एक बड़ा समूह द्वारा विकसित की है और नेतृत्व द्वारा किया जाता है +[ वाल्टर ब्राइट ] ( https://en.wikipedia.org/wiki/Walter_Bright ) और +[ आंद्रेई Alexandrescu ] ( https://en.wikipedia.org/wiki/Andrei_Alexandrescu )। +जिस तरह की है कि सभी के साथ बाहर, चलो कुछ उदाहरणों पर गौर करते हैं! + + +```c +import std.stdio; + +void main() { + + for(int i = 0; i < 10000; i++) { + writeln(i); + } + + // 'auto' can be used for inferring types. + auto n = 1; + + // संख्यात्मक literals स्पष्टता के लिए एक अंकों विभाजक के रूप में '_' का उपयोग कर सकते हैं। + while(n < 10_000) { + n += n; + } + + do { + n -= (n / 2); + } while(n > 0); +    // लिए और जब तक अच्छा कर रहे हैं, लेकिन D में हम 'foreach' छोरों पसंद करते हैं। +    // '..' पहला मान सहित एक सतत श्रृंखला बनाता है, +    // लेकिन पिछले छोड़कर। + foreach(i; 1..1_000_000) { + if(n % 2 == 0) + writeln(i); + } + + // वहाँ भी 'foreach_reverse' आप पीछे की ओर पाश करना चाहते हैं। + foreach_reverse(i; 1..int.max) { + if(n % 2 == 1) { + writeln(i); + } else { + writeln("No!"); + } + } +} +``` + +हम ' struct`, `class`,` union`, और `` enum` साथ नए प्रकार परिभाषित कर सकते हैं। Structs और unions +मूल्य से कार्य करने के लिए पारित कर रहे हैं (यानी नकल) और वर्गों के संदर्भ द्वारा पारित कर रहे हैं। इसके अलावा, +हम प्रकारों और मानों दोनों पर करने के लिए टेम्पलेट का उपयोग कर सकते हैं! + +```c +// इधर, 'T' एक प्रकार पैरामीटर है। लगता है कि '<+T>' C++ / C/ Java से। +struct LinkedList(T) { + T data = null; + + // '!'का प्रयोग करें , एक पैरामिट्रीकृत प्रकार इन्स्तांत । फिर, '' लगता है। + LinkedList!(T)* next; +} + +class BinTree(T) { + T data = null; + +// केवल एक टेम्पलेट पैरामीटर नहीं है, तो , हम कोष्ठकों छोड़ सकते हैं। + BinTree!T left; + BinTree!T right; +} + +enum Day { + Sunday, + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, +} + +// उपयोग उर्फ प्रकार (alias) के लिए संक्षिप्त बनाने के लिए। +alias IntList = LinkedList!int; +alias NumTree = BinTree!double; + +//हम के रूप में अच्छी तरह से कार्य टेम्पलेट्स बना सकते हैं! +T max(T)(T a, T b) { + if(a < b) + return b; + + return a; +} + +// संदर्भ द्वारा पारित सुनिश्चित करने के लिए रेफरी कीवर्ड का प्रयोग करें । यही कारण है कि यहां तक ​​कि 'A' और 'B' , तो है +//मान प्रकार वे हमेशा ' swap()' के संदर्भ द्वारा पारित हो जाएगा हैं । +void swap(T)(ref T a, ref T b) { + auto temp = a; + + a = b; + b = temp; +} + +// टेम्पलेट्स के साथ, हम भी मूल्यों पर परमेटेराइज़ कर सकते हैं , न सिर्फ types.With टेम्पलेट्स, हम भी नहीं है, बस प्रकार , मूल्यों पर parameterize कर सकते हैं। +class Matrix(uint m, uint n, T = int) { + T[m] rows; + T[n] columns; +} + +auto mat = new Matrix!(3, 3); + +``` + +Classes की बात हो रही है , एक दूसरे के लिए गुणों के बारे में बात करते हैं। एक संपत्ति +एक value की तरह कार्य कर सकते हैं कि एक समारोह में मोटे तौर पर है, इसलिए हम कर सकते हैं +के शब्दों के साथ पॉड संरचनाओं की वाक्य रचना (` structure.x = 7` ) है +मनुष्य और सेटर तरीकों ( ` object.setX (7) `) ! + +```c +// Consider a class parameterized on types 'T' & 'U'. +class MyClass(T, U) { + T _data; + U _other; +} + +// And "getter" and "setter" methods like so: +class MyClass(T, U) { + T _data; + U _other; + + // भवन निर्माताओं हमेशा नामित कर रहे हैं 'this'. + this(T t, U u) { + //यह नीचे सेटर तरीकों से मुलाकात करेंगे। + data = t; + other = u; + } + + // getters + @property T data() { + return _data; + } + + @property U other() { + return _other; + } + + // setters + @property void data(T t) { + _data = t; + } + + @property void other(U u) { + _other = u; + } +} + +//और हम इस तरह से उन का उपयोग करें : +void main() { + auto mc = new MyClass!(int, string)(7, "seven"); + + करने के लिए लिखने के लिए मानक पुस्तकालय से + // आयात ' stdio ' मॉड्यूल + // सांत्वना (आयात एक गुंजाइश के लिए स्थानीय हो सकता है) । + import std.stdio; + + // Call the getters to fetch the values. + writefln("Earlier: data = %d, str = %s", mc.data, mc.other); + + // Call the setters to assign new values. + mc.data = 8; + mc.other = "eight"; + + // Call the getters again to fetch the new values. + writefln("Later: data = %d, str = %s", mc.data, mc.other); +} +``` + +गुणों के साथ, हम तर्क की किसी भी राशि को जोड़ सकते हैं +हमारे मनुष्य और सेटर तरीकों, और की साफ वाक्य रचना रखना +सीधे सदस्यों तक पहुँचने ! + +हमारे निपटान पर अन्य वस्तु उन्मुख उपहार +` interface`s , ` सार class`es शामिल +और ` तरीकों override`ing । डी सिर्फ जावा की तरह विरासत करता है: +आप कृपया के रूप में कई इंटरफेस को लागू करने, एक वर्ग का विस्तार । + +हम डी एस OOP सुविधाओं देखा , लेकिन स्विच गियर छोड़ दिया । डी प्रस्तावों +प्रथम श्रेणी के कार्यों के साथ कार्यात्मक प्रोग्रामिंग, ` pure` +काम करता है, और अपरिवर्तनीय डेटा । इसके अलावा, अपने पसंदीदा के सभी +कार्यात्मक एल्गोरिदम ( नक्शा, फिल्टर , कम करने और मित्र हो सकते हैं) +अद्भुत ` std.algorithm` मॉड्यूल में पाया! + +```c +import std.algorithm : map, filter, reduce; +import std.range : iota; // builds an end-exclusive range + +void main() { + // हम भी ints के वर्गों की एक सूची का योग मुद्रित करना चाहते हैं + // 1 से 100 के लिए आसान करने के लिए! + + // बस टेम्पलेट पैरामीटर के रूप में लैम्ब्डा भाव के पास! + // आप आप की तरह किसी भी पुराने समारोह पारित कर सकते हैं , लेकिन lambdas यहाँ सुविधाजनक हैं। + auto num = iota(1, 101).filter!(x => x % 2 == 0) + .map!(y => y ^^ 2) + .reduce!((a, b) => a + b); + + writeln(num); +} +``` + +हम NUM गणना करने के लिए एक अच्छा Haskellian पाइपलाइन का निर्माण करने के लिए मिला सूचना कैसे ? +यही कारण है कि एक डी नवाचार करने के लिए धन्यवाद वर्दी समारोह कॉल सिंटेक्स के रूप में जानते हैं। +UFCS के साथ, हम एक विधि के रूप में एक समारोह कॉल लिखने के लिए चुन सकते हैं +या मुफ्त समारोह कॉल ! वाल्टर इस पर एक अच्छा लेख लिखा था +[यहाँ ।] ( http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394 ) +संक्षेप में, आप जिनकी पहली पैरामीटर कार्यों कॉल कर सकते हैं +एक विधि के रूप में ग्रुप ए की किसी भी अभिव्यक्ति पर कुछ प्रकार एक की है । + +मैं समानता चाहते । समानता की तरह कोई और? ज़रूर तुम करना। चलो कुछ करते हैं! +```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); + } +} + + +``` -- cgit v1.2.3 From b76ab9f2b56298d8f4d9c7ddf861db2f0692a9b3 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 14:32:48 +0200 Subject: Fixup metadata for #1673 --- hd-hd/d.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hd-hd/d.html.markdown b/hd-hd/d.html.markdown index 80cf3bed..96274e2b 100644 --- a/hd-hd/d.html.markdown +++ b/hd-hd/d.html.markdown @@ -1,9 +1,9 @@ --- language: D -filename: learnd.d +filename: learnd-hd.d contributors: - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] -lang: en +lang: hd --- ```c -- cgit v1.2.3 From b46e577526dc05d188950f3e4d85d027035a1bf3 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 14:33:01 +0200 Subject: Metadata fixups for #1673 --- hd-hd/amd.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/hd-hd/amd.html.markdown b/hd-hd/amd.html.markdown index ac8400ad..0a6581d6 100644 --- a/hd-hd/amd.html.markdown +++ b/hd-hd/amd.html.markdown @@ -3,7 +3,8 @@ category: tool tool: amd contributors: - ["Frederik Ring", "https://github.com/m90"] -filename: learnamd.js +filename: learnamd-hd.js +lang: hd --- ## एएमडी के साथ प्रारंभ करना -- cgit v1.2.3 From d4aa031d55e03a08f92fd2e3c407655eaf3ef4f2 Mon Sep 17 00:00:00 2001 From: Carolina Knoll Date: Sun, 26 Jun 2016 09:34:35 -0300 Subject: Create asymptoticnotation-pt.html.markdown (#1820) --- pt-br/asymptoticnotation-pt.html.markdown | 161 ++++++++++++++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 pt-br/asymptoticnotation-pt.html.markdown diff --git a/pt-br/asymptoticnotation-pt.html.markdown b/pt-br/asymptoticnotation-pt.html.markdown new file mode 100644 index 00000000..c5299a11 --- /dev/null +++ b/pt-br/asymptoticnotation-pt.html.markdown @@ -0,0 +1,161 @@ +--- +category: Algorithms & Data Structures +name: Asymptotic Notation +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] +translators: + - ["Carolina Knoll", "http://github.com/carolinaknoll"] +lang: pt-br +--- + +# Aprenda X em Y minutos +## Onde X=Notação Assintótica + +# Notações Assintóticas +## O que são? + +Notações assintóticas são notações matemáticas que nos permitem analisar tempo de execução +de um algoritmo, identificando o seu comportamento de acordo como o tamanho de entrada para +o algoritmo aumenta. Também é conhecido como taxa de "crescimento" de um algoritmo. O algoritmo +simplesmente se torna incrivelmente lento conforme o seu tamanho aumenta? Será que pode-se na +maior parte manter o seu tempo de execução rápido mesmo quando o tamanho de entrada aumenta? +A notação assintótica nos dá a capacidade de responder a essas perguntas. + +## Além desta, existem outras alternativas para responder a essas perguntas? + +Uma forma seria a de contar o número de operações primitivas em diferentes tamanhos de entrada. +Embora esta seja uma solução válida, a quantidade de trabalho necessário, mesmo para algoritmos +simples, não justifica a sua utilização. + +Outra maneira é a de medir fisicamente a quantidade de tempo que leva para se executar um algoritmo +de diferentes tamanhos. No entanto, a precisão e a relatividade (já que tempos obtidos só teriam +relação à máquina em que eles foram testados) deste método estão ligadas a variáveis ambientais, +tais como especificações de hardware, poder de processamento, etc. + +## Tipos de Notação Assintótica + +Na primeira seção deste documento nós descrevemos como uma notação assintótica identifica o comportamento +de um algoritmo como as alterações de tamanho de entrada (input). Imaginemos um algoritmo como uma função +f, n como o tamanho da entrada, e f (n) sendo o tempo de execução. Assim, para um determinado algoritmo f, +com tamanho de entrada n você obtenha algum tempo de execução resultante f (n). Isto resulta num gráfico, +em que o eixo Y representa o tempo de execução, o eixo X é o tamanho da entrada, e os pontos marcados são +os resultantes da quantidade de tempo para um dado tamanho de entrada. + +Pode-se rotular uma função ou algoritmo com uma notação assintótica de diversas maneiras diferentes. +Dentre seus exemplos, está descrever um algoritmo pelo seu melhor caso, pior caso, ou caso equivalente. +O mais comum é o de analisar um algoritmo pelo seu pior caso. Isso porque você normalmente não avaliaria +pelo melhor caso, já que essas condições não são as que você está planejando. Um bom exemplo disto é o de +algoritmos de ordenação; especificamente, a adição de elementos a uma estrutura de tipo árvore. O melhor +caso para a maioria dos algoritmos pode ser tão simples como uma única operação. No entanto, na maioria +dos casos, o elemento que você está adicionando terá de ser ordenado de forma adequada através da árvore, +o que poderia significar a análise de um ramo inteiro. Este é o pior caso, e é por ele que precisamos seguir. + +### Tipos de funções, limites, e simplificação + +``` +Função Logaritmica - log n +Função Linear - an + b +Função Quadrática - an^2 + bn + c +Função Polinomial - an^z + . . . + an^2 + a*n^1 + a*n^0, onde z é uma constante +Função Exponencial - a^n, onde a é uma constante +``` + +Estas são algumas classificações básicas de crescimento de função usados em várias notações. A lista +começa com a função crescimento mais lento (logarítmica, com tempo de execução mais rápido) e vai até +a mais rápida (exponencial, com tempo de execução mais lento). Observe que 'n', ou nossa entrada, +cresce em cada uma dessas funções, e o resultado claramente aumenta muito mais rapidamente em função +quadrática, polinomial e exponencial, em comparação com a logarítmica e a linear. + +Uma observação de boa importância é que, para as notações a serem discutidas, deve-se fazer o melhor +para utilizar termos mais simples. Isto significa desrespeitar constantes, e simplificar termos de +ordem, porque, como o tamanho da entrada (ou n no nosso f (n) exemplo) aumenta infinitamente (limites +matemáticos), os termos em ordens mais baixas e constantes são de pouca ou nenhuma importância. Dito +isto, se você possui constantes com valor 2^9001, ou alguma outra quantidade ridícula, inimaginável, +perceberá que a simplificação distorcerá a precisão de sua notação. + +Já que nós queremos a forma mais simples, vamos modificar nossas funções um pouco. + +``` +Logaritmica - log n +Linear - n +Quadrática - n^2 +Polinomial - n^z, onde z é uma constante +Exponencial - a^n, onde a é uma constante +``` + +### O Grande-O + +Grande-O, geralmente escrita como O, é uma Notação Assintótica para o pior caso para uma dada função. Digamos +que `f(n)` é o tempo de execução de seu algoritmo, e `g(n)` é uma complexidade de tempo arbitrário que você está +tentando se relacionar com o seu algoritmo. `f(n)` será O(g(n)), se, por qualquer constante real c (c > 0), +`f(n)` <= `c g(n)` para cada tamanho de entrada n (n > 0). + +*Exemplo 1* + +``` +f(n) = 3log n + 100 +g(n) = log n +``` + +É `f(n)` um O(g(n))? +É 3 `log n + 100` igual a O(log n)? +Vamos checar na definição de Grande-O. + +``` +3log n + 100 <= c * log n +``` + +Existe alguma constante c que satisfaça isso para todo n? + +``` +3log n + 100 <= 150 * log n, n > 2 (indefinido em n = 1) +``` + +Sim! A definição de Grande-O foi satisfeita. Sendo assim, `f(n)` é O(g(n)). + +*Exemplo 2* + +``` +f(n) = 3 * n^2 +g(n) = n +``` + +É `f(n)` um O(g(n))? +É `3 * n^2` um O(n)? +Vamos ver na definição de Grande-O. + +``` +3 * n^2 <= c * n +``` + +Existe alguma constante que satisfaça isso para todo n? +Não, não existe. `f(n)` NÃO É O(g(n)). + +### Grande-Omega + +Grande-Omega, comumente escrito como Ω, é uma Notação Assintótica para o melhor caso, ou +uma taxa de crescimento padrão para uma determinada função. + +`f(n)` é Ω(g(n)), se, por qualquer constante c real (c > 0), `f(n)` é >= `c g(n)` para cada +tamanho de entrada n (n > 0). + +Sinta-se livre para pesquisar recursos adicionais e obter mais exemplos sobre este assunto! +Grande-O é a notação primária utilizada para tempo de execução de algoritmos, de modo geral. + +### Notas de Finalização + +É complicado exibir este tipo de assunto de forma tão curta, então é definitivamente recomendado +pesquisar além dos livros e recursos on-line listados. Eles serão capazes de analisar o assunto com +uma profundidade muito maior, além de ter definições e exemplos. Mais sobre onde X="Algoritmos e +Estruturas de Dados" está a caminho: Haverá conteúdo focado na análise de exemplos de códigos reais +em breve. + +## Livros + +* [Algorithms] (http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X) +* [Algorithm Design] (http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651) + +## Recursos Online + +* [MIT] (http://web.mit.edu/16.070/www/lecture/big_o.pdf) +* [KhanAcademy] (https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation) -- cgit v1.2.3 From d1216a4253c1b03641c10b171030d04227ad8408 Mon Sep 17 00:00:00 2001 From: Sachin Divekar Date: Sun, 26 Jun 2016 18:08:05 +0530 Subject: Add an example of trap command (#1826) * Begin writing document for PCRE Started writing learnxinyminutes document for PCRE to cover general purpose regular expressions. Added introduction and a couple of details. * Change introductory example for regex The old example was incorrect. It's replaced with a simple one. * Add some more introductory text * Add first example * Added more example and a table for proper formatting * Add few more examples * Formatting * Improve example * Edit description of character classes * Add a way to test regex Add https://regex101.com/ web application to test the regex provided in example. * Add example of trap command trap is a very important command to intercept a fatal signal, perform cleanup, and then exit gracefully. It needs an entry in this document. Here a simple and most common example of using trap command i.e. cleanup upon receiving signal is added. * Revert "Add example of trap command" * Add an example of trap command `trap` is a very important command to intercept a fatal signal, perform cleanup, and then exit gracefully. It needs an entry in this document. Here a simple and most common example of using `trap` command i.e. cleanup upon receiving signal is added. --- bash.html.markdown | 3 ++ pcre.html.markdown | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 pcre.html.markdown diff --git a/bash.html.markdown b/bash.html.markdown index 02d7f31e..c2c3e3f1 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -272,6 +272,9 @@ grep -c "^foo.*bar$" file.txt # and not the regex, use fgrep (or grep -F) fgrep "foobar" file.txt +# trap command allows you to execute a command when a signal is received by your script. +# Here trap command will execute rm if any one of the three listed signals is received. +trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM # Read Bash shell builtins documentation with the bash 'help' builtin: help diff --git a/pcre.html.markdown b/pcre.html.markdown new file mode 100644 index 00000000..0b61653d --- /dev/null +++ b/pcre.html.markdown @@ -0,0 +1,82 @@ +--- +language: PCRE +filename: pcre.txt +contributors: + - ["Sachin Divekar", "http://github.com/ssd532"] + +--- + +A regular expression (regex or regexp for short) is a special text string for describing a search pattern. e.g. to extract domain name from a string we can say `/^[a-z]+:/` and it will match `http:` from `http://github.com/`. + +PCRE (Perl Compatible Regular Expressions) is a C library implementing regex. It was written in 1997 when Perl was the de-facto choice for complex text processing tasks. The syntax for patterns used in PCRE closely resembles Perl. PCRE syntax is being used in many big projects including PHP, Apache, R to name a few. + + +There are two different sets of metacharacters: +* Those that are recognized anywhere in the pattern except within square brackets +``` + \ general escape character with several uses + ^ assert start of string (or line, in multiline mode) + $ assert end of string (or line, in multiline mode) + . match any character except newline (by default) + [ start character class definition + | start of alternative branch + ( start subpattern + ) end subpattern + ? extends the meaning of ( + also 0 or 1 quantifier + also quantifier minimizer + * 0 or more quantifier + + 1 or more quantifier + also "possessive quantifier" + { start min/max quantifier +``` + +* Those that are recognized within square brackets. Outside square brackets. They are also called as character classes. + +``` + + \ general escape character + ^ negate the class, but only if the first character + - indicates character range + [ POSIX character class (only if followed by POSIX syntax) + ] terminates the character class + +``` + +PCRE provides some generic character types, also called as character classes. +``` + \d any decimal digit + \D any character that is not a decimal digit + \h any horizontal white space character + \H any character that is not a horizontal white space character + \s any white space character + \S any character that is not a white space character + \v any vertical white space character + \V any character that is not a vertical white space character + \w any "word" character + \W any "non-word" character +``` + +## Examples + +We will test our examples on following string `66.249.64.13 - - [18/Sep/2004:11:07:48 +1000] "GET /robots.txt HTTP/1.0" 200 468 "-" "Googlebot/2.1"`. It is a standard Apache access log. + +| Regex | Result | Comment | +| :---- | :-------------- | :------ | +| GET | GET | GET matches the characters GET literally (case sensitive) | +| \d+.\d+.\d+.\d+ | 66.249.64.13 | `\d+` match a digit [0-9] one or more times defined by `+` quantifier, `\.` matches `.` literally | +| (\d+\.){3}\d+ | 66.249.64.13 | `(\d+\.){3}` is trying to match group (`\d+\.`) exactly three times. | +| \[.+\] | [18/Sep/2004:11:07:48 +1000] | `.+` matches any character (except newline), `.` is any character | +| ^\S+ | 66.249.64.13 | `^` means start of the line, `\S+` matches any number of non-space characters | +| \+[0-9]+ | +1000 | `\+` matches the character `+` literally. `[0-9]` character class means single number. Same can be achieved using `\+\d+` | + +All these examples can be tried at https://regex101.com/ + +1. Copy the example string in `TEST STRING` section +2. Copy regex code in `Regular Expression` section +3. The web application will show the matching result + + +## Further Reading + + -- cgit v1.2.3 From 243ef338ab06a030ae9461a4162ae53f8f9603a3 Mon Sep 17 00:00:00 2001 From: julianaortga Date: Sun, 26 Jun 2016 07:38:29 -0500 Subject: update further reading [c/es] (#1829) --- es-es/c-es.html.markdown | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/es-es/c-es.html.markdown b/es-es/c-es.html.markdown index 5d3aae0c..8bc1eabb 100644 --- a/es-es/c-es.html.markdown +++ b/es-es/c-es.html.markdown @@ -418,8 +418,18 @@ typedef void (*my_fnp_type)(char *); ## Otras lecturas -Lo mejor que puedes en contrar es una copia de [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language) +Lo mejor que puedes encontrar es una copia de [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language). Es *el* +libro de C, escrito por Dennis Ritchie, creador de C y Brian Kernighan. Aún así, +se cuidadoso, es antiguo, contiene algunas inexactitudes, y algunas prácticas +han cambiado. -Otro buen recurso es [Learn C the hard way](http://c.learncodethehardway.org/book/) +Otro buen recurso es [Learn C the hard way](http://c.learncodethehardway.org/book/). + +Si tienes una pregunta, lee [compl.lang.c Frequently Asked Questions](http://c-faq.com). + +Es muy importante utilizar el espaciado y la sangría apropiados y ser coherente +con su estilo de codificación en general. El código legible es mejor que el +código rápido. Para adoptar un buen estilo de codificación, vea el +[Estilo de codificación del kernel Linux] (https://www.kernel.org/doc/Documentation/CodingStyle). Aparte de eso, Google es tu amigo. -- cgit v1.2.3 From 9592b8fc431708a5ddbcf0c18aef4e3b8c978cd3 Mon Sep 17 00:00:00 2001 From: julianaortga Date: Sun, 26 Jun 2016 07:39:14 -0500 Subject: [css/es] Updated translation (#1830) * updated resources and further reading [css/es] * minor fix and spellchecking --- es-es/css-es.html.markdown | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/es-es/css-es.html.markdown b/es-es/css-es.html.markdown index 31000785..6395f5fd 100644 --- a/es-es/css-es.html.markdown +++ b/es-es/css-es.html.markdown @@ -233,12 +233,21 @@ en todos los navegadores y dispositivos. Pero siempre es vital tener en mente la compatibilidad y disponibilidad del CSS que uses con respecto a los navegadores y dispositivos para los que desarrolles. - [QuirksMode CSS](http://www.quirksmode.org/css/) es una excelente referencia para esto. -## Referencias +## Recursos + +* Para ejecutar un test de compatibilidad, revisa [CanIUse](http://caniuse.com). +* CSS Playground [Dabblet](http://dabblet.com/). +* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS). +* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/). + +## Otras lecturas -* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) -* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/). +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/). +* [QuirksMode CSS](http://www.quirksmode.org/css/). * [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) y [LESS](http://lesscss.org/) para preprocesamiento CSS. +* [CSS-Tricks](https://css-tricks.com). -- cgit v1.2.3 From a24bafe5cbb26c4da8629439e19bb210ca1c9ee2 Mon Sep 17 00:00:00 2001 From: julianaortga Date: Sun, 26 Jun 2016 07:39:28 -0500 Subject: [git/es] updated further information (#1831) --- es-es/git-es.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown index 4e1e68ba..1a8e275a 100644 --- a/es-es/git-es.html.markdown +++ b/es-es/git-es.html.markdown @@ -398,6 +398,10 @@ $ git rm /directorio/del/archivo/FooBar.c * [tryGit - Una forma entretenida y rapida de aprender Git.](http://try.github.io/levels/1/challenges/1) +* [Udemy tutorial de Git: Una guía completa](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) + +* [Inmersión Git - Una visita guiada caminando a través de los fundamentos de git](http://gitimmersion.com/) + * [git-scm - Video-tutoriales](http://git-scm.com/videos) * [git-scm - Documentacion](http://git-scm.com/book/es) @@ -407,3 +411,9 @@ $ git rm /directorio/del/archivo/FooBar.c * [SalesForce Chuleta](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) * [GitGuys](http://www.gitguys.com/) + +* [Git - La guía simple](http://rogerdudler.github.io/git-guide/index.html) + +* [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) -- cgit v1.2.3 From 1311f4dbb29085167248e8a746b27a5e1bee7459 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 14:41:30 +0200 Subject: manually merge #1838 --- objective-c.html.markdown | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 0dbb3ae3..e41e71c3 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -20,7 +20,7 @@ Multi-line comments look like this */ // XCode supports pragma mark directive that improve jump bar readability -#pragma mark Navigation Functions // New tag on jump bar named 'Navigation Functions' +#pragma mark Navigation Functions // New tag o@"Third number = %@", thirdNumber); // prin jump bar named 'Navigation Functions' #pragma mark - Navigation Functions // Same tag, now with a separator // Imports the Foundation headers with #import @@ -133,6 +133,8 @@ int main (int argc, const char * argv[]) NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; NSLog(@"Third number = %@", thirdNumber); // prints => "Third number = 3" + // Since Xcode 7, NSArray objects can be typed (Generics) + NSArray *stringArray = @[@"hello", @"world"]; // NSMutableArray is a mutable version of NSArray, allowing you to change // the items in the array and to extend or shrink the array object. // Convenient, but not as efficient as NSArray. @@ -146,6 +148,8 @@ int main (int argc, const char * argv[]) NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; NSObject *valueObject = aDictionary[@"A Key"]; NSLog(@"Object = %@", valueObject); // prints => "Object = (null)" + // Since Xcode 7, NSDictionary objects can be typed (Generics) + NSDictionary *numberDictionary = @{@"a": @1, @"b": @2}; // NSMutableDictionary also available as a mutable dictionary object NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; [mutableDictionary setObject:@"value1" forKey:@"key1"]; @@ -161,6 +165,8 @@ int main (int argc, const char * argv[]) // Set object NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order) + // Since Xcode 7, NSSet objects can be typed (Generics) + NSSet *stringSet = [NSSet setWithObjects:@"hello", @"world", nil]; // NSMutableSet also available as a mutable set object NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2]; [mutableSet addObject:@"Hello"]; -- cgit v1.2.3 From d7af1e0b709a19506c4a6158537b1d1a14e79207 Mon Sep 17 00:00:00 2001 From: Sam van Kampen Date: Sun, 26 Jun 2016 14:43:53 +0200 Subject: Clarify sentences and fix spelling and space usage in nl-nl/yaml (#1822) --- nl-nl/yaml-nl.html.markdown | 53 +++++++++++++++++++++++---------------------- 1 file changed, 27 insertions(+), 26 deletions(-) diff --git a/nl-nl/yaml-nl.html.markdown b/nl-nl/yaml-nl.html.markdown index a4a9d5fc..11af784f 100644 --- a/nl-nl/yaml-nl.html.markdown +++ b/nl-nl/yaml-nl.html.markdown @@ -5,21 +5,22 @@ contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] translators: - ["Niels van Velzen", "https://nielsvanvelzen.me"] + - ["Sam van Kampen", "http://tehsvk.net"] lang: nl-nl --- -YAML is een data serialisatie taal ontworpen om snel te kunnen worden begrepen door mensen. +YAML is een dataserialisatietaal ontworpen om snel te kunnen worden begrepen door mensen. -Het is een strikte superset van JSON en bevat nieuwe regels en een stricte manier van inspringen, zoals bij Python. In tegenstelling tot Python kan je alleen geen tab tekens gebruiken. +Het is een strikte superset van JSON en bevat nieuwe regels en een strikte manier van inspringen die lijkt op de manier van Python. In tegenstelling tot Python kan je alleen geen tabtekens gebruiken. ```yaml # Commentaar in YAML ziet er zo uit -################ -# SCALAR TYPES # -################ +################## +# SCALAIRE TYPES # +################## -# Ons hoofd object (Wat in het hele document gebruikt wordt) is een map, +# Ons hoofdobject (Wat in het hele document gebruikt wordt) is een map; # dit staat gelijk aan een dictionary, hash of object in andere talen. sleutel: waarde nog_een_sleutel: Een andere waarde @@ -35,10 +36,10 @@ quote_waarde: "Een string in quotes" # Tekst over meerdere lijnen kan je schrijven als een 'letterlijk blok' (met |) # Of een 'gevouwen blok' (met >) letterlijk_blok: | - Dit hele blok met tekst is de waarde van de 'letterlijk_blok' sleutel, + Dit hele blok met tekst is de waarde van de 'letterlijk_blok'-sleutel, met nieuwe lijnen behouden. - Het blok blijft door gaan tot het geeindigd wordt door korter te inspringen. + Het blok blijft door gaan tot het geeindigd wordt door korter in te springen. Lijnen die groter zijn ingesprongen behouden dit. gevouwen_stijl: > @@ -50,9 +51,9 @@ gevouwen_stijl: > Meer ingesprongen lijnen zullen hun nieuwe lijnen ook behouden, deze tekst zal over 2 lijnen te zien zijn. -#################### -# COLLECTION TYPES # -#################### +################## +# COLLECTIETYPES # +################## # Nesten wordt bereikt met inspringen. geneste_map: @@ -61,7 +62,7 @@ geneste_map: andere_geneste_map: hallo: wereld -# In een map is een sleutel niet verplicht om een string te gebruiken +# In een map hoeft de sleutel geen string te zijn. 0.25: een float als sleutel # Sleutels kunnen ook meerdere lijnen gebruiken met behulp van het vraagteken @@ -70,14 +71,14 @@ geneste_map: met meerdere lijnen : en dit is de waarde -# YAML staat ook collection types toe in sleutels, maar veel programmeertalen +# YAML staat ook collectietypes toe in sleutels, maar veel programmeertalen # zullen hierover klagen. # Sequences (gelijk aan lijsten of arrays) zien er zo uit: een_sequence: - Item 1 - Item 2 - - 0.5 # sequences kunnen meerdere type waardes bevatten. + - 0.5 # sequences kunnen meerdere typen waardes bevatten. - Item 4 - sleutel: waarde andere_sleutel: andere waarde @@ -85,13 +86,13 @@ een_sequence: - Dit is een sequence - in een andere sequence -# Doordat YAML een superset van JSON is kan je ook JSON-stijl mappen en -# sequences maken: +# Doordat YAML een superset van JSON is kan je ook mappen en +# sequences volgens de JSON-stijl maken: json_map: {"sleutel": "waarde"} json_seq: [3, 2, 1, "takeoff"] ####################### -# EXTRA YAML FUNCTIES # +# EXTRA YAML-FUNCTIES # ####################### # YAML heeft ook een handige functie genaamd 'anchors' (ankers), deze laten je @@ -102,16 +103,16 @@ andere_anker: *anker_naam # YAML heeft ook tags, deze gebruik je om een expliciet type te verklaren expliciete_string: !!str 0.5 -# Sommige parsers gebruiken taal specifieke tags, zoals deze voor Python's -# complexe nummer type: +# Sommige parsers gebruiken taalspecifieke tags, zoals deze voor Python's +# complexe nummertype: python_complex_nummer: !!python/complex 1+2j -#################### -# EXTRA YAML TYPES # -#################### +####################### +# EXTRA TYPES IN YAML # +####################### -# Strings en nummer zijn niet de enige types die YAML begrijpt. -# ISO opgemaakte datum en datumtijd notaties werken ook: +# Strings en nummers zijn niet de enige types die YAML begrijpt. +# ISO opgemaakte datum- en datumtijdnotaties werken ook: datumtijd: 2001-12-15T02:59:43.1Z datumtijd_met_spaties: 2001-12-14 21:59:43.10 -5 datum: 2002-12-14 @@ -124,13 +125,13 @@ gif_bestand: !!binary | +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= -# YAML heeft ook een set type, dat ziet er zo uit: +# YAML heeft ook een settype, dat ziet er zo uit: set: ? item1 ? item2 ? item3 -# Zoals in Python zijn sets gewoon mappen met null waardes; +# Zoals in Python zijn sets gewoon mappen met nulwaarden; # bovenstaand is gelijk aan: set2: item1: null -- cgit v1.2.3 From efec1d63ee081781e3009286b3df24b1dbea0ac6 Mon Sep 17 00:00:00 2001 From: Caio Mariano Date: Sun, 26 Jun 2016 09:45:07 -0300 Subject: correcoes ortograficas e adicao de alguns exemplos (#1849) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * correcoes ortogrÃaficas e adicao de alguns exemplos * mais explicacoes no documento * somente explicacoes mais detalhadas --- pt-br/php-pt.html.markdown | 66 ++++++++++++++++++++++++---------------------- 1 file changed, 35 insertions(+), 31 deletions(-) diff --git a/pt-br/php-pt.html.markdown b/pt-br/php-pt.html.markdown index 0e710742..8a1c956e 100644 --- a/pt-br/php-pt.html.markdown +++ b/pt-br/php-pt.html.markdown @@ -7,7 +7,7 @@ translators: - ["Abdala Cerqueira", "http://abda.la"] - ["Raquel Diniz", "http://twitter.com/raquelrdiniz"] lang: pt-br -filename: learnphp-pt.php +filename: php-pt.html.markdown --- Este documento descreve PHP 5+. @@ -20,21 +20,23 @@ Este documento descreve PHP 5+. // Duas barras iniciam o comentário de uma linha. -# O hash (aka pound symbol) também inicia, mas // é mais comum +# O hash (aka pound symbol) também inicia, mas // é mais comum. /* O texto envolto por barra-asterisco e asterisco-barra - faz um comentário de múltiplas linhas + faz um comentário de múltiplas linhas. */ -// Utilize "echo" ou "print" para imprimir a saída -print('Olá '); // Imprime "Olá " sem quebra de linha +// Utilize "echo" ou "print" para imprimir a saída. +print('Olá '); // Imprime "Olá " sem quebra de linha. +print 'Olá '; // Não tem a necessidade de utilizar as chaves. // () são opcionais para print e echo -echo "Mundo\n"; // Imprime "Mundo" com quebra de linha -// (Todas as declarações devem terminar com um ponto e vírgula) +echo "Mundo\n"; // Imprime "Mundo" com quebra de linha. +echo ("Mundo\n"); // Podemos tambem utilizar com chaves no echo. +// (Todas as declarações devem terminar com um ponto e vírgula.) -// Qualquer coisa fora da tag Olá mundo novamente! '$String' // Evite o uso de aspas duplas, exceto para incorporar outras variáveis $dbl_quotes = "Esta é uma $sgl_quotes."; // => 'Esta é uma $String.' -// Os caracteres especiais só são escapados entre aspas duplas -$escapado = "Este contém um \t caractere tab."; -$naoescapado = 'Este contém somente a barra e o t: \t'; +// Os caracteres especiais só são escapados entre aspas duplas. +$escapado = "Este contém um \t caractere tab."; +echo $escapado; //Imprime: Este contém um caractere tab. +$naoescapado = 'Este contém somente a barra e o t: \t'; +echo $naoescapado; //Imprime: Este contém somente a barra e o t: \t -// Coloque uma variável entre chaves se necessário +// Coloque uma variável entre chaves se necessário. $dinheiro = "Eu tenho $${numero} no banco."; // Desde o PHP 5.3, nowdocs podem ser usados para múltiplas linhas sem análise @@ -105,7 +109,7 @@ $sgl_quotes FIM; // Concatenação de string é feita com . -echo 'Esta string ' . 'é concatenada'; +echo 'Esta string ' . 'é concatenada'; //Imprime: 'Esta string é concatenada' /******************************** @@ -120,7 +124,7 @@ echo 'Esta string ' . 'é concatenada'; define("FOO", "alguma coisa"); // Acesso a uma constante é possível usando diretamente o nome escolhido -echo 'Isto sairá '.FOO; +echo 'Isto sairá '.FOO; //Imprime: Isto sairá alguma coisa /******************************** @@ -135,16 +139,16 @@ $associativo = array('Um' => 1, 'Dois' => 2, 'Tres' => 3); // PHP 5.4 introduziu uma nova sintaxe $associativo = ['Um' => 1, 'Dois' => 2, 'Tres' => 3]; -echo $associativo['Um']; // imprime 1 +echo $associativo['Um']; // Imprime 1. // Uma lista de literais atribui chaves inteiras implicitamente $array = ['Um', 'Dois', 'Tres']; -echo $array[0]; // => "Um" +echo $array[0]; // Imprime => "Um" // Adiciona um elemento no final do array $array[] = 'Quatro'; -// Remove um elemento do array +// Remove um elemento do array. unset($array[3]); /******************************** @@ -155,12 +159,12 @@ echo('Olá Mundo!'); // Imprime Olá Mundo! para stdout. // Stdout é uma página web se executado em um navegador. -print('Olá Mundo!'); // O mesmo que o echo +print('Olá Mundo!'); // O mesmo que o echo. // echo é atualmente um construtor de linguagem, então você pode // remover os parênteses. -echo 'Olá Mundo!'; -print 'Olá Mundo!'; // O print também é +echo 'Olá Mundo!'; // Imprime: Olá Mundo! +print 'Olá Mundo!'; // O print também é - Imprime: Olá Mundo! $paragrafo = 'parágrafo'; @@ -181,11 +185,11 @@ $z = &$y; // $z irá mudar o valor de $y também, e vice-versa. // $x irá permanecer inalterado com o valor original de $y -echo $x; // => 2 -echo $z; // => 2 +echo $x; // Imprime => 2 +echo $z; // Imprime => 2 $y = 0; -echo $x; // => 2 -echo $z; // => 0 +echo $x; // Imprime => 2 +echo $z; // Imprime => 0 // Despeja tipos e valores de variável para o stdout var_dump($z); // imprime int(0) @@ -222,13 +226,13 @@ assert(1 !== '1'); // As variáveis podem ser convertidas entre tipos, dependendo da sua utilização. $inteiro = 1; -echo $inteiro + $inteiro; // => 2 +echo $inteiro + $inteiro; // Imprime => 2 $string = '1'; -echo $string + $string; // => 2 (strings são coagidas para inteiros) +echo $string + $string; // Imprime => 2 (strings são coagidas para inteiros) $string = 'one'; -echo $string + $string; // => 0 +echo $string + $string; // Imprime => 0 // Imprime 0 porque o operador + não pode fundir a string 'um' para um número // Tipo de fundição pode ser utilizado para tratar uma variável -- cgit v1.2.3 From ebd74da99a73d9cbdba23285afc745a740a87e28 Mon Sep 17 00:00:00 2001 From: Harry Date: Sun, 26 Jun 2016 13:45:20 +0100 Subject: Added main attributes of javadocs. (#1850) --- java.html.markdown | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index a025bbba..fb0913f1 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -23,8 +23,17 @@ Multi-line comments look like this. */ /** -JavaDoc comments look like this. Used to describe the Class or various -attributes of a Class. + * JavaDoc comments look like this. Used to describe the Class or various + * attributes of a Class. + * Main attributes: + * + * @author Name (and contact information such as email) of author(s). + * @version Current version of the program. + * @since When this part of the program was first added. + * @param For describing the different parameters for a method. + * @return For describing what the method returns. + * @deprecated For showing the code is outdated or shouldn't be used. + * @see Links to another part of documentation. */ // Import ArrayList class inside of the java.util package -- cgit v1.2.3 From 9d17f8bc578c96bda52bd2611625bacb8b518afb Mon Sep 17 00:00:00 2001 From: Yi Hong Ang Date: Sun, 26 Jun 2016 20:45:45 +0800 Subject: Add a section on code sections/cells (#1855) --- matlab.html.markdown | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/matlab.html.markdown b/matlab.html.markdown index ddc0cb40..51b7bd4e 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -25,6 +25,23 @@ like this %} +% Two percent signs denote the start of a new code section +% Individual code sections can be run by moving the cursor to the section followed by +% either clicking the "Run Section" button +% or using Ctrl+Shift+Enter (Windows) or Cmd+Shift+Return (OS X) + +%% This is the start of a code section +% One way of using sections is to separate expensive but unchanging start-up code like loading data +load myFile.mat y + +%% This is another code section +% This section can be edited and run repeatedly on its own, and is helpful for exploratory programming and demos +A = A * 2; +plot(A); + +%% Code sections are also known as code cells or cell mode (not to be confused with cell arrays) + + % commands can span multiple lines, using '...': a = 1 + 2 + ... + 4 -- cgit v1.2.3 From e9ce4e2e6e401b9bb1f495d35c57141b4cffba22 Mon Sep 17 00:00:00 2001 From: Shawn McGuire Date: Sun, 26 Jun 2016 07:47:36 -0500 Subject: [csharp/en] Add string interpolation (#1864) Added example of using string interpolation --- csharp.html.markdown | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index 8d185462..69aef257 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -8,6 +8,7 @@ contributors: - ["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"] filename: LearnCSharp.cs --- @@ -947,6 +948,24 @@ on a new line! ""Wow!"", the masses cried"; A.A2(); } } + + // String interpolation by prefixing the string with $ + // and wrapping the expression you want to interpolate with { braces } + 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}"); + } + } + } // End Namespace ``` -- cgit v1.2.3 From 0387bd30fc91f82b19e8e60c8969391a5c04fc28 Mon Sep 17 00:00:00 2001 From: Prashant Khanduri Date: Sun, 26 Jun 2016 05:50:05 -0700 Subject: Generator explanation for python (#1870) More details and code on the same example as before. --- python.html.markdown | 51 ++++++++++++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 17 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 2105748c..6c9da9a9 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -678,29 +678,46 @@ dir(math) ## 7. Advanced #################################################### -# Generators help you make lazy code +# Generators +# A generator "generates" values as they are requested instead of storing +# everything up front + +# The following method (*NOT* a generator) will double all values and store it +# in `double_arr`. For large size of iterables, that might get huge! def double_numbers(iterable): + double_arr = [] + for i in iterable: + double_arr.append(i + i) + +# Running the following would mean we'll double all values first and return all +# of them back to be checked by our condition +for value in double_numbers(range(1000000)): # `test_non_generator` + print value + if value > 5: + break + +# We could instead use a generator to "generate" the doubled value as the item +# is being requested +def double_numbers_generator(iterable): for i in iterable: yield i + i -# A generator creates values on the fly. -# Instead of generating and returning all values at once it creates one in each -# iteration. This means values bigger than 15 wont be processed in -# double_numbers. -# Note xrange is a generator that does the same thing range does. -# Creating a list 1-900000000 would take lot of time and space to be made. -# xrange creates an xrange generator object instead of creating the entire list -# like range does. -# We use a trailing underscore in variable names when we want to use a name that -# would normally collide with a python keyword -xrange_ = xrange(1, 900000000) - -# will double all numbers until a result >=30 found -for i in double_numbers(xrange_): - print i - if i >= 30: +# Running the same code as before, but with a generator, now allows us to iterate +# over the values and doubling them one by one as they are being consumed by +# our logic. Hence as soon as we see a value > 5, we stop break out of the +# loop and don't need to double most of the values sent in (MUCH FASTER!) +for value in double_numbers_generator(xrange(1000000)): # `test_generator` + print value + if value > 5: break +# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`? +# Just as `double_numbers_generator` is the generator version of `double_numbers` +# We have `xrange` as the generator version of `range` +# `range` would return back and array with 1000000 values for us to use +# `xrange` would generate 1000000 values for us as we request / iterate over those items + + # Decorators # in this example beg wraps say -- cgit v1.2.3 From 8e19b8ebba863acd3f140320649cd472d1928564 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Costa?= Date: Sun, 26 Jun 2016 13:50:52 +0100 Subject: [swift/pt-pt] Add Swift Portuguese translation (#1740) * Start swift pt-pt translation * Start swift pt-pt translation * Finish Collections Section * Finish Control Flow Section * Finish Functions Section * Finish Structures Section * Finish Classes Section * Finish translating Enums Section * Finish Protocols Sections translation * Finish Other Section translation --- pt-pt/swift.html.markdown | 608 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 608 insertions(+) create mode 100644 pt-pt/swift.html.markdown diff --git a/pt-pt/swift.html.markdown b/pt-pt/swift.html.markdown new file mode 100644 index 00000000..f27c3043 --- /dev/null +++ b/pt-pt/swift.html.markdown @@ -0,0 +1,608 @@ +--- +language: swift +filename: learnswift-pt.swift +contributors: + - ["Grant Timmerman", "http://github.com/grant"] + - ["Christopher Bess", "http://github.com/cbess"] + - ["Joey Huang", "http://github.com/kamidox"] + - ["Anthony Nguyen", "http://github.com/anthonyn60"] + - ["Clayton Walker", "https://github.com/cwalk"] + - ["João Costa", "https://github.com/joaofcosta"] +lang: pt-pt +--- + +Swift é uma linguagem de programação criada pela Apple para o desenvolvimento em iOS e OS X. +Desenhada de forma a coexistir com Objective-C e ser mais resiliente contra código errôneo, a linguagem Swift foi introduzida em 2014 na conferência para desenvolvedores WWDC da Apple. +Swift usa o compilador LLVM incluido no XCode 6+. + +O livro oficial [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) da Apple está agora disponivel via iBooks. + +Consulta também o [guia de iniciação](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/) da Apple, que contêm um tutorial completo em Swift. + +```swift +// importar um módulo +import UIKit + +// +// MARK: Básico +// + +// O Xcode suporta landmarks para anotação de código e lista-as na jump bar +// MARK: Marco de secção (MARK) +// TODO: Algo a fazer em breve +// FIXME: Reparar este código + +// Em Swift 2, println e print foram unidos num só método print. O print automaticamente acrescenta uma nova linha. +print("Hello, world") // println mudou para print +print("Hello, world", appendNewLine: false) // imprimir sem acrescentar uma nova linha + +// variáveis (var) podem ser modificadas depois de inicializadas +// constantes (let) NÂO podem ser modificadas depois de inicializadas + +var myVariable = 42 +let øπΩ = "value" // nomes de variáveis em unicode +let π = 3.1415926 +let convenience = "keyword" // nome de variável contextual +let weak = "keyword"; let override = "another keyword" // expressões podem ser separadas com ';' +let `class` = "keyword" // plicals permitem que keywords sejam usadas como nomes de vartiáveis +let explicitDouble: Double = 70 +let intValue = 0007 // 7 +let largeIntValue = 77_000 // 77000 +let label = "some text " + String(myVariable) // Casting +let piText = "Pi = \(π), Pi 2 = \(π * 2)" // interpolação de Strings + +// Valores especificos à build +// usam a configuração de build -D +#if false + print("Not printed") + let buildValue = 3 +#else + let buildValue = 7 +#endif +print("Build value: \(buildValue)") // Build value: 7 + +/* + Optionals são um dos recursos de Swift, Optionals tanto podem conter + um valor ou conter nil (sem valor) que indica que não existe um valor. + Adicionar um ponto de exclamção (?) após definir o tipo declara + esse valor como um Optional. + + Como Swift requere que todas as propriedades tenham um valor, até nil + tem que ser explicitamente guardado como um valor Optional. + + Optional é uma enumeração. +*/ +var someOptionalString: String? = "optional" // Pode assumir o valor nil +// Igual ao de cima, mas ? é um operando pósfixo (açúcar sintático) +var someOptionalString2: Optional = "optional" + +if someOptionalString != nil { + // Não sou nil + if someOptionalString!.hasPrefix("opt") { + print("has the prefix") + } + + let empty = someOptionalString?.isEmpty +} +someOptionalString = nil + +/* + Tentar usar ! para aceder a Optional com valor não existente, ou seja, nil, + causa em erro de execução. + É necessário ter sempre a certeza que um Optional não tem valor nil + antes de usar ! para fazer 'force-unwrap' ao seu valor. +*/ + +// Optional implicitamente desembrulhado +var unwrappedString: String! = "Value is expected." +// O mesmo de cima, mas ! é um operando pósfixo (mais açúcar sintático) +var unwrappedString2: ImplicitlyUnwrappedOptional = "Value is expected." + +if let someOptionalStringConstant = someOptionalString { + // Tem um valor diferente de nil + if !someOptionalStringConstant.hasPrefix("ok") { + // Não tem o prefixo + } +} + +// Swift tem suporte para guardar valores de qualquer tipo. +// AnyObject == id +// Ao contrátio do `id` de Objective-C, AnyObject funciona com qualquer valor (Class, Int, struct, etc.) +var anyObjectVar: AnyObject = 7 +anyObjectVar = "Changed value to a string, not good practice, but possible." + +/* + Comentar aqui + + /* + Também é possível fazer comentários aninhados + */ +*/ + +// +// MARK: Coleções (Collections) +// + +/* + Os tipos Array e Dictionary são structs e, portanto, `let` e `var` + também indicam se eles são mutáveis (var) or imutáveis (let) + na altura em que se declaram estes tipos. +*/ + +// Array +var shoppingList = ["catfish", "water", "lemons"] +shoppingList[1] = "bottle of water" +let emptyArray = [String]() // let == imutável +let emptyArray2 = Array() // mesmo de cima +var emptyMutableArray = [String]() // var == mutável + + +// Dictionary +var occupations = [ + "Malcolm": "Captain", + "kaylee": "Mechanic" +] +occupations["Jayne"] = "Public Relations" +let emptyDictionary = [String: Float]() // let == imutável +let emptyDictionary2 = Dictionary() // mesmo de cima +var emptyMutableDictionary = [String: Float]() // var == mutável + + +// +// MARK: Controlo de Fluxo (Control Flow) +// + +// for loop (array) +let myArray = [1, 1, 2, 3, 5] +for value in myArray { + if value == 1 { + print("One!") + } else { + print("Not one!") + } +} + +// for loop (dictionary) +var dict = ["one": 1, "two": 2] +for (key, value) in dict { + print("\(key): \(value)") +} + +// ciclo for (limite) +for i in -1...shoppingList.count { + print(i) +} +shoppingList[1...2] = ["steak", "peacons"] +// usar ..< para excluir o último número + +// ciclo while +var i = 1 +while i < 1000 { + i *= 2 +} + +// ciclo do-whie +do { + print("hello") +} while 1 == 2 + +// Switch +// Muito poderoso, imagine `if`s com açúcar sintático +// Funciona para String, instâncias de objectos e primitivas (Int, Double, etc.) +let vegetable = "red pepper" +switch vegetable { +case "celery": + let vegetableComment = "Add some raisins and make ants on a log." +case "cucumber", "watercress": + let vegetableComment = "That would make a good tea sandwich." +case let localScopeValue where localScopeValue.hasSuffix("pepper"): + let vegetableComment = "Is it a spicy \(localScopeValue)?" +default: // obrigatório (de forma a cobrir todos os possíveis inputs) + let vegetableComment = "Everything tastes good in soup." +} + + +// +// MARK: Funções (Functions) +// + +// Funções são tipos de primeira classe, o que significa que podem ser +// aninhadas dentro de outras funções e passadas como argumento + +// Função em Swift com documentação no header + +/** + Função de cumprimento. + + - Um ponto em documentação + - Outro ponto na documentação + + :param: nome Um nome + :param: dia Um dia + :returns: Uma string com um cumprimento contendo o nome e o dia. +*/ +func greet(nome: String, dia: String) -> String { + return "Hello \(nome), today is \(dia)." +} +greet("Bob", "Tuesday") + +// Semelhante ao método de cima excepto ao comportamento dos argumentos +func greet2(#nomeObrigatório: String, nomeArgumentoExterno nomeArgumentoLocal: String) -> String { + return "Hello \(nomeObrigatório), the day is \(nomeArgumentoLocal)" +} +greet2(nomeObrigatório:"John", nomeArgumentoExterno: "Sunday") + +// Função que devolve vários itens num tuplo +func getGasPrices() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} +let pricesTuple = getGasPrices() +let price = pricesTuple.2 // 3.79 +// Ignorar tuplos ou outros valores usando _ (underscore) +let (_, price1, _) = pricesTuple // price1 == 3.69 +print(price1 == pricesTuple.1) // true +print("Gas price: \(price)") + +// Argumentos variáveis +func setup(numbers: Int...) { + // é um array + let number = numbers[0] + let argCount = numbers.count +} + +// Passar e devolver funções +func makeIncrementer() -> (Int -> Int) { + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne +} +var increment = makeIncrementer() +increment(7) + +// Passar por referência (inout) +func swapTwoInts(inout a: Int, inout b: Int) { + let tempA = a + a = b + b = tempA +} +var someIntA = 7 +var someIntB = 3 +swapTwoInts(&someIntA, &someIntB) +print(someIntB) // 7 + + +// +// MARK: Closures +// +var numbers = [1, 2, 6] + +// Funções são casos especiais de closures ({}) + +// Exemplo de um Closure. +// `->` separa o argumento e o tipo de retorno. +// `in` separa o cabeçalho do closure do corpo do closure. +numbers.map({ + (number: Int) -> Int in + let result = 3 * number + return result +}) + +// Quando o tipo é conhecido, como em cima, podemos fazer o seguinte +numbers = numbers.map({ number in 3 * number }) +// Ou até mesmo isto +//numbers = numbers.map({ $0 * 3 }) + +print(numbers) // [3, 6, 18] + +// Closure à direita (Trailing closure) +numbers = sorted(numbers) { $0 > $1 } + +print(numbers) // [18, 6, 3] + +// Super curto, pois o operador < consegue inferir o tipo + +numbers = sorted(numbers, < ) + +print(numbers) // [3, 6, 18] + +// +// MARK: Estruturas (Structures) +// + +// Estruturas (struct) e classes (class) têm capacidades muito semelhantes +struct NamesTable { + let names = [String]() + + // Custom subscript + subscript(index: Int) -> String { + return names[index] + } +} + +// Estruturas têm um inicializador implicito que é automaticamente gerado +let namesTable = NamesTable(names: ["Me", "Them"]) +let name = namesTable[1] +print("Name is \(name)") // Name is Them + +// +// MARK: Classes +// + +// Classes, estruturas e os seus membros têm três níveis de controlo de acesso +// Nomeadamente: interno (predefinição)(internal) , público (public), privado (private) + +public class Shape { + public func getArea() -> Int { + return 0; + } +} + +// Todos os métodos e propriedades de uma classe são públicos. +// Se só for necessário guarda dados num +// objecto estruturado, então é melhor usar uma `struct` + +internal class Rect: Shape { + var sideLength: Int = 1 + + // Propriedade getter e setter personalizado + private var perimeter: Int { + get { + return 4 * sideLength + } + set { + // `newValue` é uma variável implicita disponível aos setters + sideLength = newValue / 4 + } + } + + // Carregar preguiçosamente uma propriedade + // subShape permanece a nil (unintialized) até o getter ser invocado + lazy var subShape = Rect(sideLength: 4) + + // Se não for necessário um getter e setter personalizado, + // mas se quiser correr o código antes e depois de modificar ou aceder + // uma propriedade, é possível usar `willSet` e `didSet` + var identifier: String = "defaultID" { + // o argumento de `willSet` é o nome da variável para o novo valor + willSet(someIdentifier) { + print(someIdentifier) + } + } + + init(sideLength: Int) { + self.sideLength = sideLength + // invocar super.init no final do método de inicialização + super.init() + } + + func shrink() { + if sideLength > 0 { + --sideLength + } + } + + override func getArea() -> Int { + return sideLength * sideLength + } +} + +// A class `Square` estende (extends) a classe `Rect` (hierarquia) +class Square: Rect { + convenience init() { + self.init(sideLength: 5) + } +} + +var mySquare = Square() +print(mySquare.getArea()) // 25 +mySquare.shrink() +print(mySquare.sideLength) // 4 + +// Cast de uma instância de `Square` para `Shape` +let aShape = mySquare as Shape + +// Compara instâncias, não é igual a == , visto que == compara objects (igual a) +if mySquare === mySquare { + print("Yep, it's mySquare") +} + +// Inicializador (init) com Optional +class Circle: Shape { + var radius: Int + override func getArea() -> Int { + return 3 * radius * radius + } + + // Colocar um ponto de interrpgação depois de `init` cria um inicializador + // Optional, o qual pode retornar nil + init?(radius: Int) { + self.radius = radius + super.init() + + if radius <= 0 { + return nil + } + } +} + +var myCircle = Circle(radius: 1) +print(myCircle?.getArea()) // Optional(3) +print(myCircle!.getArea()) // 3 +var myEmptyCircle = Circle(radius: -1) +print(myEmptyCircle?.getArea()) // "nil" +if let circle = myEmptyCircle { + // Não vai executar pois a variável myEmptyCircle é igual a nil + print("circle is not nil") +} + + +// +// MARK: Enumerações (Enums) +// + +// Enums pode opcionalmente ser um tipo especifico ou não. +// Enums podem conter métodos tal como as classes. + +enum Suit { + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } + } +} + +// Os valores de Enum permitem syntax reduzida, não é preciso escrever o tipo do enum +// quando a variável é explicitamente definida. +var suitValue: Suit = .Hearts + +// Enums que não sejam inteiros obrigam a atribuições valor bruto (raw value) diretas +enum BookName: String { + case John = "John" + case Luke = "Luke" +} +print("Name: \(BookName.John.rawValue)") + +// Enum com valores associados +enum Furniture { + // Associar com um inteiro (Int) + case Desk(height: Int) + // Associar com uma String e um Int + case Chair(String, Int) + + func description() -> String { + switch self { + case .Desk(let height): + return "Desk with \(height) cm" + case .Chair(let brand, let height): + return "Chair of \(brand) with \(height) cm" + } + } +} + +var desk: Furniture = .Desk(height: 80) +print(desk.description()) // "Desk with 80 cm" +var chair = Furniture.Chair("Foo", 40) +print(chair.description()) // "Chair of Foo with 40 cm" + + +// +// MARK: Protocolos (Protocols) +// + +// Protocolos (`protcol`s) obrigam a que os tipos tenham +// propriedades de instância, métodos de instância, métodos de tipo, +// operadores e subscripts específicos. + +protocol ShapeGenerator { + var enabled: Bool { get set } + func buildShape() -> Shape +} + +// Protocolos definidos com @objc permitem funções com optional +// que permitem verificar se existem conformidade +@objc protocol TransformShape { + optional func reshaped() + optional func canReshape() -> Bool +} + +class MyShape: Rect { + var delegate: TransformShape? + + func grow() { + sideLength += 2 + + // Coloca um ponto de interrogação após uma propriedade opcional, método + // ou subscript para graciosamente ignorar um valor nil e retornar nil + // em vez de provoar um erro em tempo de execução ("optional chaining"). + if let allow = self.delegate?.canReshape?() { + // testar o delegate e depois o método + self.delegate?.reshaped?() + } + } +} + + +// +// MARK: Outro +// + +// extensões (`extension`s): Adiciona funcionalidade extra a um tipo já existente. + +// Square agora "conforma" com o protocolo `Printable` +extension Square: Printable { + var description: String { + return "Area: \(self.getArea()) - ID: \(self.identifier)" + } +} + +print("Square: \(mySquare)") + +// Também é possível extender tipos já embutidos +extension Int { + var customProperty: String { + return "This is \(self)" + } + + func multiplyBy(num: Int) -> Int { + return num * self + } +} + +print(7.customProperty) // "This is 7" +print(14.multiplyBy(3)) // 42 + +// Generics: Semelhante a Java e C#. Usa a palavra-chave `where` para +// especificar requisitos do `generics`. + +func findIndex(array: [T], valueToFind: T) -> Int? { + for (index, value) in enumerate(array) { + if value == valueToFind { + return index + } + } + return nil +} +let foundAtIndex = findIndex([1, 2, 3, 4], 3) +print(foundAtIndex == 2) // true + +// Operadores: +// Operadores personalizados podem começar com caracteres: +// / = - + * % < > ! & | ^ . ~ +// ou +// Caracteres Unicode matemáticos, símbolos, setas, dingbat e +// caracteres de desenho linha/caixa. +operador prefixo !!! {} + +// Um operador prefixo que triplica o comprimento do lado quando usado +prefix func !!! (inout shape: Square) -> Square { + shape.sideLength *= 3 + return shape +} + +// valor atual +print(mySquare.sideLength) // 4 + +// muda o comprimento deste lado usando o operador personalizado !!!, aumenta +// o comprimento 3x +!!!mySquare +print(mySquare.sideLength) // 12 + +// Operadores também podem ser generics +infix operator <-> {} +func <-> (inout a: T, inout b: T) { + let c = a + a = b + b = c +} + +var foo: Float = 10 +var bar: Float = 20 + +foo <-> bar +print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0" +``` -- cgit v1.2.3 From e65c618e29d971509a30d9395bd8341a1c52bce2 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 14:51:06 +0200 Subject: Update swift.html.markdown --- pt-pt/swift.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/pt-pt/swift.html.markdown b/pt-pt/swift.html.markdown index f27c3043..2a964bde 100644 --- a/pt-pt/swift.html.markdown +++ b/pt-pt/swift.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Joey Huang", "http://github.com/kamidox"] - ["Anthony Nguyen", "http://github.com/anthonyn60"] - ["Clayton Walker", "https://github.com/cwalk"] +translators: - ["João Costa", "https://github.com/joaofcosta"] lang: pt-pt --- -- cgit v1.2.3 From 75a5764000b53faf4a49e4e456591ef0cfd93b77 Mon Sep 17 00:00:00 2001 From: ditam Date: Sun, 26 Jun 2016 14:51:24 +0200 Subject: add Hungarian translation (#1874) --- hu-hu/typescript-hu.html.markdown | 174 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 hu-hu/typescript-hu.html.markdown diff --git a/hu-hu/typescript-hu.html.markdown b/hu-hu/typescript-hu.html.markdown new file mode 100644 index 00000000..88d13a9c --- /dev/null +++ b/hu-hu/typescript-hu.html.markdown @@ -0,0 +1,174 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: + - ["Tamás Diószegi", "https://github.com/ditam"] +filename: learntypescript-hu.ts +--- + +A TypeScript nyelv a JavaScript nyelven írt nagy méretű alkalmazások fejlesztését kívánja megkönnyíteni. +A TypeScript olyan, más nyelvekből ismert gyakori fogalmakat ad hozzá a JavaScripthez, mint például osztályok, interfészek, generikusság, és (opcionális) statikus típusosság. +A JavaScript egy befoglaló halmazát képzi: minden JavaScript kód érvényes TypeScript kód, így könnyen hozzáadható meglévő projektekhez. A TypeScript fordító kimenetként JavaScript kódot állít elő. + +Ez a dokumentum a TypeScript által hozzáadott új szintaxissal foglalkozik, nem pedig a [Javascripttel](../javascript/). + +Hogy kipróbáld a TypeScript fordítót, látogass el a [Játszótérre avagy Playground-ra](http://www.typescriptlang.org/Playground) ahol kódot írhatsz automatikus kódkiegészítéssel, és közvetlenül láthatod az előállított JavaScript kódot. + +```js +// 3 alapvető típus létezik TypeScriptben +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Anders"; + +// Amikor nem lehet a típust előre tudni, használható az "Any" típus +var notSure: any = 4; +notSure = "talán mégis sztring lesz"; +notSure = false; // tévedtem, mégis boolean + +// Kollekciókból létezik típusos és generikus tömb +var list: number[] = [1, 2, 3]; +// ugyanez a generikus típus használatával +var list: Array = [1, 2, 3]; + +// Enumerált típusok: +enum Color {Red, Green, Blue}; +var c: Color = Color.Green; + +// Végül, "void" használható a visszatérési értékkel nem bíró függvényeknél +function bigHorribleAlert(): void { + alert("Kis idegesítő doboz vagyok!"); +} + +// A függvények elsőrangú (first-class) típusok, használható a vastag nyilas +// lambda szintaxis, +// a compiler pedig kikövetkezteti a típusokat (inferred types) + +// A következők egyenértékűek, ugyanaz a szignatúra kerül kikövetkeztetésre, és +// így ugyanaz a JavaScript kód lesz előállítva +var f1 = function(i: number): number { return i * i; } +// Következtetett visszatérési értékkel +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +// Következtetett visszatérési értékkel +var f4 = (i: number) => { return i * i; } +// Következtetett visszatérési értékkel, +// ebben az egysoros formában nem szükséges a return kulcsszó +var f5 = (i: number) => i * i; + +// Az interfészek szerkezeti alapon működnek, vagyis minden objektum, ahol +// jelen vannak a megfelelő mezők kompatibilis az interfésszel +interface Person { + name: string; + // Az opcionális tagokat "?" jelöli + age?: number; + // És persze függvények is: + move(): void; +} + +// Egy objektum, ami megvalósítja a "Person" interfészt +// Tekinthető Personnek, hiszen van name és move mezője +var p: Person = { name: "Bobby", move: () => {} }; +// Egy objektum, ahol az opcionális mező is jelen van: +var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; +// Ez viszont nem Person, mert az age mező típusa nem szám! +var invalidPerson: Person = { name: "Bobby", age: true }; + +// Az interfészekkel függvény típusok is leírhatóak: +interface SearchFunc { + (source: string, subString: string): boolean; +} +// Csak a paraméterek típusai számítanak, a neveik nem. +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// Osztályok - a mezők alapértelmezésben publikusak +class Point { + // Mezők + x: number; + + // Konstruktor - a public/private kulcsszavak ebben a kontextusban + // legenerálják a mezőkhöz szükséges kódot a konstruktorban. + // Ebben a példában az "y" ugyanúgy definiálva lesz, mint az "x", csak + // kevesebb kóddal. + // Alapértelmezett (default) értékek is megadhatóak. + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Metódusok + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Statikus mezők + static origin = new Point(0, 0); +} + +var p1 = new Point(10 ,20); +var p2 = new Point(25); //y itt 0 lesz + +// Öröklés +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Szükséges az ősosztály konstruktorának explicit hívása + } + + // Felülírás + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Modulok +// ("." használható az almodulok számára) +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +// Új lokális név definiálása a module számára +import G = Geometry; + +var s2 = new G.Square(10); + +// Generikus típusok +// Osztályok +class Tuple { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interfészek +interface Pair { + item1: T; + item2: T; +} + +// és függvények +var pairToTuple = function(p: Pair) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); + +// definíciós fájl hivatkozása: +/// + +``` + +## További források + * [TypeScript hivatalos weboldala] (http://www.typescriptlang.org/) + * [TypeScript nyelv specifikációja (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Forráskód GitHubon] (https://github.com/Microsoft/TypeScript) + * [Definitely Typed - típusdefiníciók gyűjteménye] (http://definitelytyped.org/) \ No newline at end of file -- cgit v1.2.3 From 49bc5c8f11cd2717e0dff524ca936bd18c9de11d Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 14:51:54 +0200 Subject: metadata fixup for #1874 --- hu-hu/typescript-hu.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/hu-hu/typescript-hu.html.markdown b/hu-hu/typescript-hu.html.markdown index 88d13a9c..aedd5a64 100644 --- a/hu-hu/typescript-hu.html.markdown +++ b/hu-hu/typescript-hu.html.markdown @@ -5,6 +5,7 @@ contributors: translators: - ["Tamás Diószegi", "https://github.com/ditam"] filename: learntypescript-hu.ts +lang: hu-hu --- A TypeScript nyelv a JavaScript nyelven írt nagy méretű alkalmazások fejlesztését kívánja megkönnyíteni. @@ -171,4 +172,4 @@ var tuple = pairToTuple({ item1:"hello", item2:"world"}); * [TypeScript nyelv specifikációja (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) * [Forráskód GitHubon] (https://github.com/Microsoft/TypeScript) - * [Definitely Typed - típusdefiníciók gyűjteménye] (http://definitelytyped.org/) \ No newline at end of file + * [Definitely Typed - típusdefiníciók gyűjteménye] (http://definitelytyped.org/) -- cgit v1.2.3 From 59adb3cca3447c8099fb5b5dab5dd22630232094 Mon Sep 17 00:00:00 2001 From: Abhishek Jaisingh Date: Sun, 26 Jun 2016 18:22:17 +0530 Subject: Ds (#1879) * created binary search doc started contributing * Updated binary search * Added new info --- binary-search.html | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 binary-search.html diff --git a/binary-search.html b/binary-search.html new file mode 100644 index 00000000..68a54c2a --- /dev/null +++ b/binary-search.html @@ -0,0 +1,63 @@ +--- +category: Algorithms & Data Structures +name: Binary Search +contributors: + - ["Abhishek Jaisingh", "http://github.com/abhishekjiitr"] +--- + +# Binary Search + +## Why Binary Search? + +Searching is one of the prime problems in the domain of Computer Science.Today there are more than 1 trillion searches per year, and we need algorithms that can do that very fastly. Binary search is one of the fundamental algorithms in computer science. In order to explore it, we’ll first build up a theoretical backbone, then use that to implement the algorithm properly. + +## Introduction + +A simple approach to implement search is to do a linear search, but this approach takes a lot of time and this time grows linearly with the amount or number of data points. i.e., start from the leftmost element of arr[] and one by one compare x with each element of arr[], if x matches with an element, return the index. If x doesn’t match with any of elements, return -1. + +``` +Linear Search: O (n) Linear Time + +Binary Search: O ( log(n) ) Logarithmic Time + +``` +``` +def search(arr, x): + + for i in range(len(arr)): + + if arr[i] == x: + return i + + return -1 + +``` +## Binary Search Algorithm + +The basic requirement for binary search to work is that the data to search should be sorted (in any order). +### Algo + +``` +The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Logn). We basically ignore half of the elements just after one comparison. +1) Compare x with the middle element. +2) If x matches with middle element, we return the mid index. +3) Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half. +4) Else (x is smaller) recur for the left half. +Following is Recursive implementation of Binary Search. + +``` + +### Ending Notes + +There is another form of binary search that is very useful. + +## Books + +* [CLRS](https://mitpress.mit.edu/books/introduction-algorithms) +* [Algorithms](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X) +* [Algorithm Design](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651) + +## Online Resources + +* [GeeksforGeeks](http://www.geeksforgeeks.org/the-ubiquitous-binary-search-set-1/) +* [Topcoder Tutorial](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/) \ No newline at end of file -- cgit v1.2.3 From b76e66ed9be842c573deedbf6835f8e28685ac50 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 14:52:42 +0200 Subject: fixup filename for #1879 --- binary-search.html | 63 --------------------------------------------- binary-search.html.markdown | 63 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 63 deletions(-) delete mode 100644 binary-search.html create mode 100644 binary-search.html.markdown diff --git a/binary-search.html b/binary-search.html deleted file mode 100644 index 68a54c2a..00000000 --- a/binary-search.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -category: Algorithms & Data Structures -name: Binary Search -contributors: - - ["Abhishek Jaisingh", "http://github.com/abhishekjiitr"] ---- - -# Binary Search - -## Why Binary Search? - -Searching is one of the prime problems in the domain of Computer Science.Today there are more than 1 trillion searches per year, and we need algorithms that can do that very fastly. Binary search is one of the fundamental algorithms in computer science. In order to explore it, we’ll first build up a theoretical backbone, then use that to implement the algorithm properly. - -## Introduction - -A simple approach to implement search is to do a linear search, but this approach takes a lot of time and this time grows linearly with the amount or number of data points. i.e., start from the leftmost element of arr[] and one by one compare x with each element of arr[], if x matches with an element, return the index. If x doesn’t match with any of elements, return -1. - -``` -Linear Search: O (n) Linear Time - -Binary Search: O ( log(n) ) Logarithmic Time - -``` -``` -def search(arr, x): - - for i in range(len(arr)): - - if arr[i] == x: - return i - - return -1 - -``` -## Binary Search Algorithm - -The basic requirement for binary search to work is that the data to search should be sorted (in any order). -### Algo - -``` -The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Logn). We basically ignore half of the elements just after one comparison. -1) Compare x with the middle element. -2) If x matches with middle element, we return the mid index. -3) Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half. -4) Else (x is smaller) recur for the left half. -Following is Recursive implementation of Binary Search. - -``` - -### Ending Notes - -There is another form of binary search that is very useful. - -## Books - -* [CLRS](https://mitpress.mit.edu/books/introduction-algorithms) -* [Algorithms](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X) -* [Algorithm Design](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651) - -## Online Resources - -* [GeeksforGeeks](http://www.geeksforgeeks.org/the-ubiquitous-binary-search-set-1/) -* [Topcoder Tutorial](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/) \ No newline at end of file diff --git a/binary-search.html.markdown b/binary-search.html.markdown new file mode 100644 index 00000000..92df4875 --- /dev/null +++ b/binary-search.html.markdown @@ -0,0 +1,63 @@ +--- +category: Algorithms & Data Structures +name: Binary Search +contributors: + - ["Abhishek Jaisingh", "http://github.com/abhishekjiitr"] +--- + +# Binary Search + +## Why Binary Search? + +Searching is one of the prime problems in the domain of Computer Science.Today there are more than 1 trillion searches per year, and we need algorithms that can do that very fastly. Binary search is one of the fundamental algorithms in computer science. In order to explore it, we’ll first build up a theoretical backbone, then use that to implement the algorithm properly. + +## Introduction + +A simple approach to implement search is to do a linear search, but this approach takes a lot of time and this time grows linearly with the amount or number of data points. i.e., start from the leftmost element of arr[] and one by one compare x with each element of arr[], if x matches with an element, return the index. If x doesn’t match with any of elements, return -1. + +``` +Linear Search: O (n) Linear Time + +Binary Search: O ( log(n) ) Logarithmic Time + +``` +``` +def search(arr, x): + + for i in range(len(arr)): + + if arr[i] == x: + return i + + return -1 + +``` +## Binary Search Algorithm + +The basic requirement for binary search to work is that the data to search should be sorted (in any order). +### Algo + +``` +The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Logn). We basically ignore half of the elements just after one comparison. +1) Compare x with the middle element. +2) If x matches with middle element, we return the mid index. +3) Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half. +4) Else (x is smaller) recur for the left half. +Following is Recursive implementation of Binary Search. + +``` + +### Ending Notes + +There is another form of binary search that is very useful. + +## Books + +* [CLRS](https://mitpress.mit.edu/books/introduction-algorithms) +* [Algorithms](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X) +* [Algorithm Design](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651) + +## Online Resources + +* [GeeksforGeeks](http://www.geeksforgeeks.org/the-ubiquitous-binary-search-set-1/) +* [Topcoder Tutorial](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/) -- cgit v1.2.3 From eda92c01650f21ed43fea92b7e4535647defd3bd Mon Sep 17 00:00:00 2001 From: Paulo Henrique Rodrigues Pinheiro Date: Sun, 26 Jun 2016 09:55:40 -0300 Subject: Output example had a value more (#1876) * Output example had a value more * Added pt-br translation for python3 --- pt-br/python3-pt.html.markdown | 747 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 747 insertions(+) create mode 100644 pt-br/python3-pt.html.markdown diff --git a/pt-br/python3-pt.html.markdown b/pt-br/python3-pt.html.markdown new file mode 100644 index 00000000..0fef2528 --- /dev/null +++ b/pt-br/python3-pt.html.markdown @@ -0,0 +1,747 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] +filename: learnpython3.py +translators: + - ["Paulo Henrique Rodrigues Pinheiro", "http://www.sysincloud.it"] +language: pt-br +filename: learnpython3-pt-br.py +--- + +Python foi criado por Guido Van Rossum nos anos 1990. Ele é atualmente uma +das mais populares linguagens em existência. Eu fiquei morrendo de amor +pelo Python por sua clareza sintática. É praticamente pseudocódigo executável. + +Suas opiniões são grandemente apreciadas. Você pode encontrar-me em +[@louiedinh](http://twitter.com/louiedinh) ou louiedinh [em] +[serviço de e-mail do google]. + +Observação: Este artigo trata de Python 3 especificamente. Verifique +[aqui](http://learnxinyminutes.com/docs/pt-br/python-pt/) se você pretende +aprender o velho Python 2.7. + +```python + +# Comentários em uma única linha começam com uma cerquilha (também conhecido por sustenido). + +""" Strings de várias linhas podem ser escritas + usando três ", e são comumente usadas + como comentários. +""" + +#################################################### +## 1. Tipos de dados primitivos e operadores +#################################################### + +# Você usa números normalmente +3 # => 3 + +# Matemática é como você espera que seja +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Números inteiros por padrão, exceto na divisão, que retorna número +# de ponto flutuante (float). +35 / 5 # => 7.0 + +# O resultado da divisão inteira arredonda para baixo tanto para números +# positivos como para negativos. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # funciona em float também +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Quando você usa um float, o resultado é float. +3 * 2.0 # => 6.0 + +# operador módulo +7 % 3 # => 1 + +# Exponenciação (x**y, x elevado à potência y) +2**4 # => 16 + +# Determine a precedência usando parêntesis +(1 + 3) * 2 # => 8 + +# Valores lógicos são primitivos (Atenção à primeira letra maiúscula) +True +False + +# negação lógica com not +not True # => False +not False # => True + +# Operadores lógicos +# Observe que "and" e "or" são sensíveis a maiúsculas e minúsculas +True and False # => False +False or True # => True + +# Observe a utilização de operadores lógicos com números inteiros +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# Igualdade é == +1 == 1 # => True +2 == 1 # => False + +# Diferença é != +1 != 1 # => False +2 != 1 # => True + +# Mais comparações +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Comparações podem ser agrupadas +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (operador 'is' e operador '==') is verifica se duas referenciam um +# mesmo objeto, mas == verifica se as variáveis apontam para o +# mesmo valor. +a = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4] +b = a # b referencia o que está referenciado por a +b is a # => True, a e b referenciam o mesmo objeto +b == a # => True, objetos a e b tem o mesmo conteúdo +b = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4] +b is a # => False, a e b não referenciam o mesmo objeto +b == a # => True, objetos a e b tem o mesmo conteúdo + +# Strings são criadas com " ou ' +"Isto é uma string." +'Isto também é uma string.' + +# Strings também podem ser somadas! Mas tente não fazer isso. +"Olá " + "mundo!" # => "Olá mundo!" +# Strings podem ser somadas sem usar o '+' +"Olá " "mundo!" # => "Olá mundo!" + +# Uma string pode ser manipulada como se fosse uma lista de caracteres +"Isso é uma string"[0] # => 'I' + +# .format pode ser usado para formatar strings, dessa forma: +"{} podem ser {}".format("Strings", "interpoladas") # => "Strings podem ser interpoladas" + +# Você pode repetir os argumentos para digitar menos. +"Seja ágil {0}, seja rápido {0}, salte sobre o {1} {0}".format("Jack", "castiçal") +# => "Seja ágil Jack, seja rápido Jack, salte sobre o castiçal Jack." + +# Você pode usar palavras-chave se quiser contar. +"{nome} quer comer {comida}".format(nome="Beto", comida="lasanha") # => "Beto quer comer lasanha" + +# Se você precisa executar seu código Python3 com um interpretador Python 2.5 ou acima, você pode usar a velha forma para formatação de texto: +"%s podem ser %s da forma %s" % ("Strings", "interpoladas", "antiga") # => "Strings podem ser interpoladas da forma antiga" + + +# None é um objeto +None # => None + +# Não use o operador de igualdade "==" para comparar objetos com None +# Use "is" para isso. Ele checará pela identidade dos objetos. +"etc" is None # => False +None is None # => True + +# None, 0, e strings/listas/dicionários vazios todos retornam False. +# Qualquer outra coisa retorna True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False + + +#################################################### +## 2. Variáveis e coleções +#################################################### + +# Python tem uma função print +print("Eu sou o Python. Prazer em conhecer!") # => Eu sou o Python. Prazer em conhecer! + +# Por padrão a função print também imprime o caractere de nova linha ao final. +# Use o argumento opcional end para mudar o caractere final. +print("Olá, Mundo", end="!") # => Olá, Mundo! + +# Forma simples para capturar dados de entrada via console +input_string_var = input("Digite alguma coisa: ") # Retorna o que foi digitado em uma string +# Observação: Em versões antigas do Python, o método input() era chamado raw_input() + +# Não é necessário declarar variáveis antes de iniciá-las +# È uma convenção usar letras_minúsculas_com_sublinhados +alguma_variavel = 5 +alguma_variavel # => 5 + +# Acessar uma variável que não tenha sido inicializada gera uma exceção. +# Veja Controle de Fluxo para aprender mais sobre tratamento de exceções. +alguma_variavel_nao_inicializada # Gera a exceção NameError + +# Listas armazenam sequencias +li = [] +# Você pode iniciar com uma lista com alguns valores +outra_li = [4, 5, 6] + +# Adicionar conteúdo ao fim da lista com append +li.append(1) # li agora é [1] +li.append(2) # li agora é [1, 2] +li.append(4) # li agora é [1, 2, 4] +li.append(3) # li agora é [1, 2, 4, 3] +# Remover do final da lista com pop +li.pop() # => 3 e agora li é [1, 2, 4] +# Vamos colocá-lo lá novamente! +li.append(3) # li agora é [1, 2, 4, 3] novamente. + +# Acessar uma lista da mesma forma que você faz com um array +li[0] # => 1 +# Acessa o último elemento +li[-1] # => 3 + +# Acessando além dos limites gera um IndexError +li[4] # Gera o IndexError + +# Você pode acessar vários elementos com a sintaxe de limites +# (É um limite fechado, aberto pra você que gosta de matemática.) +li[1:3] # => [2, 4] +# Omitindo o final +li[2:] # => [4, 3] +# Omitindo o início +li[:3] # => [1, 2, 4] +# Selecione cada segunda entrada +li[::2] # => [1, 4] +# Tenha uma cópia em ordem invertida da lista +li[::-1] # => [3, 4, 2, 1] +# Use qualquer combinação dessas para indicar limites complexos +# li[inicio:fim:passo] + +# Faça uma cópia profunda de um nível usando limites +li2 = li[:] # => li2 = [1, 2, 4, 3] mas (li2 is li) resultará em False. + +# Apague elementos específicos da lista com "del" +del li[2] # li agora é [1, 2, 3] + +# Você pode somar listas +# Observação: valores em li e other_li não são modificados. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concatene listas com "extend()" +li.extend(other_li) # Agora li é [1, 2, 3, 4, 5, 6] + +# Verifique se algo existe na lista com "in" +1 in li # => True + +# Examine tamanho com "len()" +len(li) # => 6 + + +# Tuplas são como l istas, mas imutáveis. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Gera um TypeError + +# Observe que uma tupla de tamanho um precisa ter uma vírgula depois do +# último elemento mas tuplas de outros tamanhos, mesmo vazias, não precisa,. +type((1)) # => +type((1,)) # => +type(()) # => + +# Você pode realizar com tuplas a maior parte das operações que faz com listas +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Você pode desmembrar tuplas (ou listas) em variáveis. +a, b, c = (1, 2, 3) # a é 1, b é 2 e c é 3 +# Por padrão, tuplas são criadas se você não coloca parêntesis. +d, e, f = 4, 5, 6 +# Veja como é fácil permutar dois valores +e, d = d, e # d é 5, e é 4 + +# Dicionários armazenam mapeamentos +empty_dict = {} +# Aqui está um dicionário preenchido na definição da referência +filled_dict = {"um": 1, "dois": 2, "três": 3} + +# Observe que chaves para dicionários devem ser tipos imutáveis. Isto é para +# assegurar que a chave pode ser convertida para uma valor hash constante para +# buscas rápidas. +# Tipos imutáveis incluem inteiros, flotas, strings e tuplas. +invalid_dict = {[1,2,3]: "123"} # => Gera um TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Já os valores, podem ser de qualquer tipo. + +# Acesse valores com [] +filled_dict["um"] # => 1 + +# Acesse todas as chaves como um iterável com "keys()". É necessário encapsular +# a chamada com um list() para transformá-las em uma lista. Falaremos sobre isso +# mais adiante. Observe que a ordem de uma chave de dicionário não é garantida. +# Por isso, os resultados aqui apresentados podem não ser exatamente como os +# aqui apresentados. +list(filled_dict.keys()) # => ["três", "dois", "um"] + + +# Acesse todos os valores de um iterável com "values()". Novamente, é +# necessário encapsular ele com list() para não termos um iterável, e sim os +# valores. Observe que, como foi dito acima, a ordem dos elementos não é +# garantida. +list(filled_dict.values()) # => [3, 2, 1] + + +# Verifique a existência de chaves em um dicionário com "in" +"um" in filled_dict # => True +1 in filled_dict # => False + +# Acessar uma chave inexistente gera um KeyError +filled_dict["quatro"] # KeyError + +# Use o método "get()" para evitar um KeyError +filled_dict.get("um") # => 1 +filled_dict.get("quatro") # => None +# O método get permite um parâmetro padrão para quando não existir a chave +filled_dict.get("um", 4) # => 1 +filled_dict.get("quatro", 4) # => 4 + +# "setdefault()" insere em dicionário apenas se a dada chave não existir +filled_dict.setdefault("cinco", 5) # filled_dict["cinco"] tem valor 5 +filled_dict.setdefault("cinco", 6) # filled_dict["cinco"] continua 5 + +# Inserindo em um dicionário +filled_dict.update({"quatro":4}) # => {"um": 1, "dois": 2, "três": 3, "quatro": 4} +#filled_dict["quatro"] = 4 #outra forma de inserir em um dicionário + +# Remova chaves de um dicionário com del +del filled_dict["um"] # Remove a chave "um" de filled_dict + + +# Armazenamento em sets... bem, são conjuntos +empty_set = set() +# Inicializa um set com alguns valores. Sim, ele parece um dicionário. Desculpe. +some_set = {1, 1, 2, 2, 3, 4} # some_set agora é {1, 2, 3, 4} + +# Da mesma forma que chaves em um dicionário, elementos de um set devem ser +# imutáveis. +invalid_set = {[1], 1} # => Gera um TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# Pode definir novas variáveis para um conjunto +filled_set = some_set + +# Inclua mais um item no set +filled_set.add(5) # filled_set agora é {1, 2, 3, 4, 5} + +# Faça interseção de conjuntos com & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Faça união de conjuntos com | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Faça a diferença entre conjuntos com - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Verifique a existência em um conjunto com in +2 in filled_set # => True +10 in filled_set # => False + + + +#################################################### +## 3. Controle de fluxo e iteráveis +#################################################### + +# Iniciemos um variável +some_var = 5 + +# Aqui está uma expressão if. Indentação é significante em python! +# imprime "somevar é menor que10" +if some_var > 10: + print("some_var é absolutamente maior que 10.") +elif some_var < 10: # Esta cláusula elif é opcional. + print("some_var é menor que 10.") +else: # Isto também é opcional. + print("some_var é, de fato, 10.") + + +""" +Laços for iteram sobre listas +imprime: + cachorro é um mamífero + gato é um mamífero + rato é um mamífero +""" +for animal in ["cachorro", "gato", "rato"]: + # Você pode usar format() para interpolar strings formatadas + print("{} é um mamífero".format(animal)) + +""" +"range(número)" retorna um iterável de números +de zero até o número escolhido +imprime: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(menor, maior)" gera um iterável de números +começando pelo menor até o maior +imprime: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(menor, maior, passo)" retorna um iterável de números +começando pelo menor número até o maior númeno, pulando de +passo em passo. Se o passo não for indicado, o valor padrão é um. +imprime: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) +""" + +Laços while executam até que a condição não seja mais válida. +imprime: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Maneira mais curta para for x = x + 1 + +# Lide com exceções com um bloco try/except +try: + # Use "raise" para gerar um erro + raise IndexError("Isto é um erro de índice") +except IndexError as e: + pass # Pass é um não-operador. Normalmente você usa algum código de recuperação aqui. +except (TypeError, NameError): + pass # Varias exceções podem ser gerenciadas, se necessário. +else: # Cláusula opcional para o bloco try/except. Deve estar após todos os blocos de exceção. + print("Tudo certo!") # Executa apenas se o código em try não gera exceção +finally: # Sempre é executado + print("Nós podemos fazer o código de limpeza aqui.") + +# Ao invés de try/finally para limpeza você pode usar a cláusula with +with open("myfile.txt") as f: + for line in f: + print(line) + +# Python provê uma abstração fundamental chamada Iterável. +# Um iterável é um objeto que pode ser tratado como uma sequência. +# O objeto retornou a função range, um iterável. + +filled_dict = {"um": 1, "dois": 2, "três": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => range(1,10). Esse é um objeto que implementa nossa interface iterável. + +# Nós podemos percorrê-la. +for i in our_iterable: + print(i) # Imprime um, dois, três + +# Mas não podemos acessar os elementos pelo seu índice. +our_iterable[1] # Gera um TypeError + +# Um iterável é um objeto que sabe como criar um iterador. +our_iterator = iter(our_iterable) + +# Nosso iterador é um objeto que pode lembrar o estado enquanto nós o percorremos. +# Nós acessamos o próximo objeto com "next()". +next(our_iterator) # => "um" + +# Ele mantém o estado enquanto nós o percorremos. +next(our_iterator) # => "dois" +next(our_iterator) # => "três" + +# Após o iterador retornar todos os seus dados, ele gera a exceção StopIterator +next(our_iterator) # Gera StopIteration + +# Você pode capturar todos os elementos de um iterador aplicando list() nele. +list(filled_dict.keys()) # => Retorna ["um", "dois", "três"] + + +#################################################### +## 4. Funções +#################################################### + +# Use "def" para criar novas funções. +def add(x, y): + print("x é {} e y é {}".format(x, y)) + return x + y # Retorne valores com a cláusula return + +# Chamando funções com parâmetros +add(5, 6) # => imprime "x é 5 e y é 6" e retorna 11 + +# Outro meio de chamar funções é com argumentos nomeados +add(y=6, x=5) # Argumentos nomeados podem aparecer em qualquer ordem. + +# Você pode definir funções que pegam um número variável de argumentos +# posicionais +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# Você pode definir funções que pegam um número variável de argumentos nomeados +# também +def keyword_args(**kwargs): + return kwargs + +# Vamos chamá-lo para ver o que acontece +keyword_args(peh="grande", lago="ness") # => {"peh": "grande", "lago": "ness"} + + +# Você pode fazer ambos simultaneamente, se você quiser +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) imprime: + (1, 2) + {"a": 3, "b": 4} +""" + +# Quando chamar funções, você pode fazer o oposto de args/kwargs! +# Use * para expandir tuplas e use ** para expandir dicionários! +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalente a foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalente a foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4) + +# Retornando múltiplos valores (com atribuição de tuplas) +def swap(x, y): + return y, x # Retorna múltiplos valores como uma tupla sem os parêntesis. + # (Observação: os parêntesis foram excluídos mas podem estar + # presentes) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Novamente, os parêntesis foram excluídos mas podem estar presentes. + +# Escopo de função +x = 5 + +def setX(num): + # A variável local x não é a mesma variável global x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # variável global x agora é 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python tem funções de primeira classe +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Também existem as funções anônimas +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# TODO - Fix for iterables +# Existem funções internas de alta ordem +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Nós podemos usar compreensão de lista para interessantes mapas e filtros +# Compreensão de lista armazena a saída como uma lista que pode ser uma lista +# aninhada +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. Classes +#################################################### + + +# Nós usamos o operador "class" para ter uma classe +class Human: + + # Um atributo de classe. Ele é compartilhado por todas as instâncias dessa + # classe. + species = "H. sapiens" + + # Construtor básico, é chamado quando esta classe é instanciada. + # Note que dois sublinhados no início e no final de uma identificados + # significa objetos ou atributos que são usados pelo python mas vivem em + # um namespace controlado pelo usuário. Métodos (ou objetos ou atributos) + # como: __init__, __str__, __repr__, etc. são chamados métodos mágicos (ou + # algumas vezes chamados métodos dunder - "double underscore") + # Você não deve usar nomes assim por sua vontade. + def __init__(self, name): + @ Atribui o argumento ao atributo da instância + self.name = name + + # Um método de instância. Todos os métodos tem "self" como primeiro + # argumento + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Um método de classe é compartilhado por todas as instâncias + # Eles são chamados com a classe requisitante como primeiro argumento + @classmethod + def get_species(cls): + return cls.species + + # Um método estático é chamado sem uma referência a classe ou instância + @staticmethod + def grunt(): + return "*grunt*" + + +# Instancie uma classe +i = Human(name="Ian") +print(i.say("oi")) # imprime "Ian: oi" + +j = Human("Joel") +print(j.say("olá")) # imprime "Joel: olá" + +# Chama nosso método de classe +i.get_species() # => "H. sapiens" + +# Altera um atributo compartilhado +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Chama o método estático +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. Módulos +#################################################### + +# Você pode importar módulos +import math +print(math.sqrt(16)) # => 4 + +# Você pode importar apenas funções específicas de um módulo +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Você pode importar todas as funções de um módulo para o namespace atual +# Atenção: isso não é recomendado +from math import * + +# Você pode encurtar o nome dos módulos +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Módulos python são apenas arquivos python comuns. Você +# pode escrever os seus, e importá-los. O nome do +# módulo é o mesmo nome do arquivo. + +# Você pode procurar que atributos e funções definem um módulo. +import math +dir(math) + + +#################################################### +## 7. Avançado +#################################################### + +# Geradores podem ajudar você a escrever código "preguiçoso" +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Um gerador cria valores conforme necessário. +# Ao invés de gerar e retornar todos os valores de uma só vez ele cria um em +# cada interação. Isto significa que valores maiores que 15 não serão +# processados em double_numbers. +# Nós usamos um sublinhado ao final do nome das variáveis quando queremos usar +# um nome que normalmente colide com uma palavra reservada do python. +range_ = range(1, 900000000) +# Multiplica por 2 todos os números até encontrar um resultado >= 30 +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Decoradores +# Neste exemplo beg encapsula say +# beg irá chamar say. Se say_please é verdade então ele irá mudar a mensagem +# retornada +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Por favor! Eu sou pobre :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Você me paga uma cerveja?" + return msg, say_please + + +print(say()) # Você me paga uma cerveja? +print(say(say_please=True)) # Você me paga uma cerveja? Por favor! Eu sou pobre :( +``` + +## Pronto para mais? + +### Free Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) + +### Dead Tree + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From f6c68bdd0055b7c066cd707ec6f1227608fe26d8 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 14:56:03 +0200 Subject: Update python3-pt.html.markdown --- pt-br/python3-pt.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pt-br/python3-pt.html.markdown b/pt-br/python3-pt.html.markdown index 0fef2528..c5a3c020 100644 --- a/pt-br/python3-pt.html.markdown +++ b/pt-br/python3-pt.html.markdown @@ -5,11 +5,10 @@ contributors: - ["Steven Basart", "http://github.com/xksteven"] - ["Andre Polykanine", "https://github.com/Oire"] - ["Zachary Ferguson", "http://github.com/zfergus2"] -filename: learnpython3.py translators: - ["Paulo Henrique Rodrigues Pinheiro", "http://www.sysincloud.it"] language: pt-br -filename: learnpython3-pt-br.py +filename: learnpython3-pt.py --- Python foi criado por Guido Van Rossum nos anos 1990. Ele é atualmente uma -- cgit v1.2.3 From 41cf3e7421fe7547ee55ac551438c0645281de33 Mon Sep 17 00:00:00 2001 From: Akashdeep Goel Date: Sun, 26 Jun 2016 18:28:40 +0530 Subject: Feature: adds Dynamic Programming tutorial (#1885) --- dynamic-programming.html.markdown | 50 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 dynamic-programming.html.markdown diff --git a/dynamic-programming.html.markdown b/dynamic-programming.html.markdown new file mode 100644 index 00000000..95f774bf --- /dev/null +++ b/dynamic-programming.html.markdown @@ -0,0 +1,50 @@ +--- +category: Algorithms & Data Structures +name: Dynamic Programming +contributors: + - ["Akashdeep Goel", "http://github.com/akashdeepgoel"] +--- + +# Dynamic Programming + +## Introduction + +Dynamic Programming is a powerful technique used for solving a particular class of problems as we will see.The idea is very simple, If you have solved a problem with the given input, then save the result for future reference, so as to avoid solving the same problem again. + +Always remember!! +"Those who can't remember the past are condemned to repeat it" + +## Ways of solving such Problems + +1.) Top-Down : Start solving the given problem by breaking it down. If you see that the problem has been solved already, then just return the saved answer. If it has not been solved, solve it and save the answer. This is usually easy to think of and very intuitive. This is referred to as Memoization. + +2.) Bottom-Up : Analyze the problem and see the order in which the sub-problems are solved and start solving from the trivial subproblem, up towards the given problem. In this process, it is guaranteed that the subproblems are solved before solving the problem. This is referred to as Dynamic Programming. + +## Example of Dynamic Programming + +The Longest Increasing Subsequence problem is to find the longest increasing subsequence of a given sequence. Given a sequence S= {a1 , a2 , a3, a4, ............., an-1, an } we have to find a longest subset such that for all j and i, j a[j] and LS[i] Date: Sun, 26 Jun 2016 10:03:09 -0300 Subject: Added typescript-pt.html.markdown (#1699) * link for learning of javascript adjusted * Added typescript-pt.html.markdown --- pt-br/typescript-pt.html.markdown | 179 ++++++++++++++++++++++++++++++++++++++ typescript.html.markdown | 2 +- 2 files changed, 180 insertions(+), 1 deletion(-) create mode 100644 pt-br/typescript-pt.html.markdown diff --git a/pt-br/typescript-pt.html.markdown b/pt-br/typescript-pt.html.markdown new file mode 100644 index 00000000..f072b257 --- /dev/null +++ b/pt-br/typescript-pt.html.markdown @@ -0,0 +1,179 @@ +--- +language: TypeScript +filename: learntypescript-pt.ts +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: + - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"] +lang: pt-br +--- + +TypeScript is a language that aims at easing development of large scale applications written in JavaScript. +TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. +It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emits JavaScript. + +This article will focus only on TypeScript extra syntax, as opposed to [JavaScript] (../javascript/). + + +Typescript é uma linguagem que visa facilitar o desenvolvimento de aplicações em grande escala escritos em JavaScript. +Typescript acrescenta conceitos comuns como classes, módulos, interfaces, genéricos e (opcional) tipagem estática para JavaScript. +É um super conjunto de JavaScript: todo o código JavaScript é o código do texto dactilografado válido para que possa ser adicionados diretamente a qualquer projeto. O compilador emite typescript JavaScript. + +Este artigo irá se concentrar apenas em texto datilografado sintaxe extra, ao contrário de [JavaScript](javascript-pt.html.markdown). + +Para testar compilador do texto datilografado, de cabeça para o [Parque](http://www.typescriptlang.org/Playground), onde você vai ser capaz de escrever código, ter auto conclusão e ver diretamente o JavaScript emitida. + +```js +// Existem 3 tipos básicos no TypeScript +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Anders"; + +// Quando é impossível saber, há o "Qualquer" tipo +var notSure: any = 4; +notSure = "maybe a string instead"; +notSure = false; // Ok, definitivamente um boolean + +// Para coleções, não são matrizes e matrizes genéricas digitado +var list: number[] = [1, 2, 3]; +// Como alternativa, usando o tipo de matriz genérica +var list: Array = [1, 2, 3]; + +// Para enumerações: +enum Color {Red, Green, Blue}; +var c: Color = Color.Green; + +// Por último, "vazio" é utilizado no caso especial de uma função que não retorna nada +function bigHorribleAlert(): void { + alert("I'm a little annoying box!"); +} + +// Funções são cidadãos de primeira classe, apoiar a sintaxe lambda "seta gordura" e +// Tipo de uso inferência + +// A seguir são equivalentes, a mesma assinatura será inferido pelo +// Compilador, e mesmo JavaScript será emitido +var f1 = function(i: number): number { return i * i; } +// Tipo de retorno inferida +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +// Tipo de retorno inferida +var f4 = (i: number) => { return i * i; } +// Tipo de retorno inferido, one-liner significa nenhuma palavra-chave retorno necessário +var f5 = (i: number) => i * i; + +// Interfaces são estruturais, qualquer coisa que tenha as propriedades é compatível com +// A interface +interface Person { + name: string; + // Propriedades opcionais, marcado com um "?" + age?: number; + // E de funções curso + move(): void; +} + +// Objeto que implementa a "Pessoa" Interface +// Pode ser tratado como uma pessoa desde que tem o nome e mover propriedades +var p: Person = { name: "Bobby", move: () => {} }; +// Os objetos que têm a propriedade opcional: +var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; +// Não é uma pessoa porque a idade não é um número +var invalidPerson: Person = { name: "Bobby", age: true }; + +// Interfaces também pode descrever um tipo de função +interface SearchFunc { + (source: string, subString: string): boolean; +} +// Somente tipos dos parâmetros são importantes, os nomes não são importantes. +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// Classes - membros são públicos por padrão +class Point { + // Propriedades + x: number; + + // Construtor - the public/private keywords in this context will generate + // o código clichê para a propriedade e a inicialização no + // construtor. + // Neste exemplo, "y" será definida como "X" é, mas com menos código + // Os valores padrão também são suportados. + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Funções + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Membros Estáticos + static origin = new Point(0, 0); +} + +var p1 = new Point(10 ,20); +var p2 = new Point(25); //y será 0 + +// Herança +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Chamada explícita para o construtor da super classe é obrigatória + } + + // Sobrescrever + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Módulos, "." pode ser utilizado como separador de sub módulos +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +// Alias no local para fazer referência a um módulo +import G = Geometry; + +var s2 = new G.Square(10); + +// Genericos +// Classes +class Tuple { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interfaces +interface Pair { + item1: T; + item2: T; +} + +// e funções +var pairToTuple = function(p: Pair) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); + +// Incluindo referências a um arquivo de definição: +/// + +``` + +## Leitura adicional + * [TypeScript site oficial](http://www.typescriptlang.org/) + * [TypeScript especificações de idioma (pdf)](http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Apresentando texto datilografado no Canal 9](http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Código fonte no GitHub](https://github.com/Microsoft/TypeScript) + * [Definitivamente datilografado - repositório de definições de tipo](http://definitelytyped.org/) diff --git a/typescript.html.markdown b/typescript.html.markdown index 21f1ce7d..1d712369 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -9,7 +9,7 @@ TypeScript is a language that aims at easing development of large scale applicat TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emits JavaScript. -This article will focus only on TypeScript extra syntax, as opposed to [JavaScript] (../javascript/). +This article will focus only on TypeScript extra syntax, as opposed to [JavaScript](javascript.html.markdown). To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the emitted JavaScript. -- cgit v1.2.3 From 8cd7c230aaa708dffb544887baa85de8f3377251 Mon Sep 17 00:00:00 2001 From: Jonathan Wang Date: Sun, 26 Jun 2016 09:04:11 -0400 Subject: [bash/en] basic parameter expansion, and brace expansion (#1533) * Added brace expansion as well as basic parameter expansion * frogot my name * Update bash.html.markdown Added to parameter expansion --- bash.html.markdown | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index c2c3e3f1..a62bd167 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -11,6 +11,7 @@ contributors: - ["Rahil Momin", "https://github.com/iamrahil"] - ["Gregrory Kielian", "https://github.com/gskielian"] - ["Etan Reisner", "https://github.com/deryni"] + - ["Jonathan Wang", "https://github.com/Jonathansw" ] filename: LearnBash.sh --- @@ -54,6 +55,13 @@ echo '$Variable' # its name without $. If you want to use the variable's value, you should use $. # Note that ' (single quote) won't expand the variables! +# Parameter expansion ${ }: +echo ${Variable} +# This is a simple usage of parameter expansion +# Parameter Expansion gets a value from a variable. It "expands" or prints the value +# During the expansion time the value or parameter are able to be modified +# Below are other modifications that add onto this expansion + # String substitution in variables echo ${Variable/Some/A} # This will substitute the first occurrence of "Some" with "A" @@ -68,6 +76,12 @@ echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} # This works for null (Foo=) and empty string (Foo=""); zero (Foo=0) returns 0. # Note that it only returns default value and doesn't change variable value. +# Brace Expansion { } +# Used to generate arbitrary strings +echo {1..10} +echo {a..z} +# This will output the range from the start value to the end value + # Builtin variables: # There are some useful builtin variables, like echo "Last program's return value: $?" -- cgit v1.2.3 From 57a0ce5acc898792ea5c577fa41f5376a30c28d0 Mon Sep 17 00:00:00 2001 From: Lucas Moreira Date: Sun, 26 Jun 2016 10:05:04 -0300 Subject: =?UTF-8?q?[ruby/pt-br]=20Erros=20ortogr=C3=A1ficos.=20(#1609)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Alguns erros ortográficos foram corrigidos. * Correcting some words. --- pt-br/git-pt.html.markdown | 12 ++++++------ pt-br/ruby-pt.html.markdown | 10 +++++----- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown index ea3570d6..907892b1 100644 --- a/pt-br/git-pt.html.markdown +++ b/pt-br/git-pt.html.markdown @@ -32,7 +32,7 @@ a um arquivo ou conjunto de arquivos ao longo do tempo. de arquivos. * Controle de versão distribuído foca em compartilhar alterações. Cada alteração é associada a um *id* único. -* Sistemas distribuídos não tem estrutura definida. É possivel ter um sistema +* Sistemas distribuídos não têm estrutura definida. É possivel ter um sistema centralizado ao estilo SVN usando git. [Informação adicional (EN)](http://git-scm.com/book/en/Getting-Started-About-Version-Control) @@ -56,7 +56,7 @@ referências. Pode ser descrito como uma estrutura de dados de código fonte com a particularidade de cada elemento do código fonte permitir acesso ao histórico das suas alterações, entre outras coisas. -Um repositório git é constituido pelo diretório .git e a *working tree* +Um repositório git é constituído pelo diretório .git e a *working tree* ### Diretório .git (componente do repositório) @@ -140,10 +140,10 @@ Para visualizar rapidamente o detalhamento de cada comando ou apenas lembrar da # Ver rapidamente os comandos disponiveis $ git help -# Ver todos os comandos disponiveis +# Ver todos os comandos disponíveis $ git help -a -# Usar o *help* para um comando especifico +# Usar o *help* para um comando específico # git help $ git help add $ git help commit @@ -158,7 +158,7 @@ do repositório) e o *commit* da *HEAD* atual. ```bash # Apresenta o *branch*, arquivos não monitorados, alterações e outras -# difereças +# diferenças $ git status # Para aprender mais detalhes sobre git *status* @@ -400,7 +400,7 @@ perigoso quando não há certeza do que se está fazendo. ```bash # Restabelece a camada intermediária de registo para o último -# commit (o directório fica sem alterações) +# commit (o diretório fica sem alterações) $ git reset # Restabelece a camada intermediária de registo para o último commit, e diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown index 668cd25f..eeb51bec 100644 --- a/pt-br/ruby-pt.html.markdown +++ b/pt-br/ruby-pt.html.markdown @@ -101,7 +101,7 @@ caminho_para_a_raiz_do_projeto = '/bom/nome/' caminho = '/nome/ruim/' # Símbolos (são objetos) -# Símbolos são imutáveis, são constantes reutilizáveis representadadas +# Símbolos são imutáveis, são constantes reutilizáveis representados # internamente por um valor inteiro. Eles são frequentemente usados no # lugar de strings para transmitir com eficiência os valores específicos # e significativos @@ -260,7 +260,7 @@ somar 3, 4 #=> 7 somar(3,4), 5 #=> 12 # yield -# Todos os métodos possuem implicitamente um paramêntro opcional que é um bloco +# Todos os métodos possuem implicitamente um paramêtro opcional que é um bloco # ele pode ser chamado com a palavra chave 'yield' def ao_redor @@ -285,7 +285,7 @@ class Humano # Inicialização básica (contructor) def initialize(nome, idade=0) - # Atribui o argumento para a variável de instancia "nome" do objeto + # Atribui o argumento para a variável de instância "nome" do objeto @nome = nome # Se a idade não for passada, nós definimos um valor padrão na lista de argumentos @idade = idade @@ -301,7 +301,7 @@ class Humano @nome end - # Um método de classe usa a palavra chave self para se defenciar dos métodos de instância. + # Um método de classe usa a palavra chave self para se diferenciar dos métodos de instância. # Ele só pode ser chamado na classe, não na instancia def self.diz(msg) puts "#{msg}" @@ -362,7 +362,7 @@ Trabalhador.foo # 0 Humano.foo = 2 # 2 Trabalhador.foo # 2 -# Uma variável de instância não é compartilhada por suas classes decendentes. +# Uma variável de instância não é compartilhada por suas classes descendentes. class Humano @bar = 0 -- cgit v1.2.3 From b54e0f4da89f04e635d40958d74c71effea762cf Mon Sep 17 00:00:00 2001 From: Matthias Kern Date: Sun, 26 Jun 2016 16:06:36 +0300 Subject: Add german translation for python3 (#1287) --- de-de/python3-de.html.markdown | 655 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 655 insertions(+) create mode 100644 de-de/python3-de.html.markdown diff --git a/de-de/python3-de.html.markdown b/de-de/python3-de.html.markdown new file mode 100644 index 00000000..ef1786c8 --- /dev/null +++ b/de-de/python3-de.html.markdown @@ -0,0 +1,655 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["kultprok", "http:/www.kulturproktologie.de"] + - ["matthiaskern", "https://github.com/matthiaskern"] +filename: learnpython3-de.py +lang: de-de +--- + +Anmerkungen des ursprünglichen Autors: +Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen Übersichtlichkeit verliebt. Eigentlich ist es ausführbarer Pseudocode. + +Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service]. + +Hinweis: Dieser Beitrag bezieht sich insplizit auf Python 3. Falls du lieber Python 2.7 lernen möchtest, schau [hier](http://learnxinyminutes.com/docs/python/) weiter. + +```python + +# Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz) + +""" Mehrzeilige Strings werden mit + drei '-Zeichen geschrieben und werden + oft als Kommentare genutzt. +""" + +#################################################### +## 1. Primitive Datentypen und Operatoren +#################################################### + +# Die Zahlen +3 #=> 3 + +# Mathematik funktioniert so, wie man das erwartet +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 + +# Außer Division, welche automatisch Gleitkommazahlen zurückgibt +35 / 5 # => 7.0 + +# Eine Division kann mit "//" für positive sowie negative Werte abgerundet werden. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Benutzt man eine Gleitkommazahl, ist auch das Ergebnis eine solche +3 * 2.0 # => 6.0 + +# Der Rest einer Division +7 % 3 # => 1 + +# Potenz +2**4 # => 16 + +# Rangfolge wird mit Klammern erzwungen +(1 + 3) * 2 #=> 8 + +# Boolesche Ausdrücke sind primitive Datentypen +True +False + +# Mit not wird negiert +not True #=> False +not False #=> True + +# Boolesche Operatoren +# Hinweis: "and" und "or" müssen klein geschrieben werden +True and False #=> False +False or True #=> True + +# Für die Benutzung von Booleschen Operatoren und ganzen Zahlen +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# Gleichheit ist == +1 == 1 #=> True +2 == 1 #=> False + +# Ungleichheit ist != +1 != 1 #=> False +2 != 1 #=> True + +# Ein paar weitere Vergleiche +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Vergleiche können verknüpft werden! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Strings werden mit " oder ' gebildet +"Das ist ein String." +'Das ist auch ein String.' + +# Strings können auch addiert werden! Vermeide dies aber lieber. +"Hallo " + "Welt!" #=> "Hallo Welt!" +# Strings können ohne "+" addiert werden +"Hallo " "welt!" # => "Hallo Welt!" + +# Ein String kann wie eine Liste von Zeichen verwendet werden +"Das ist ein String"[0] #=> 'D' + +# .format kann Strings formatieren +"{} können {} werden".format("Strings", "formatiert") + +# Schneller geht das mit Wiederholungen +"{0} mag Spagetthi, {0} liebt es zu Schwimmen und ganz besonders mag {0} {1}".format("Hans", "Blattsalat") +#=> "Hans mag Spagetthi, Hans liebt es zu Schwimmen und ganz besonders mag Hans Blattsalat" + +# Wir können Schlüsselwörter verwenden, wenn wir nicht abzählen wollen. +"{name} will {food} essen".format(name="Bob", food="Lasagne") +#=> "Bob will Lasagne kochen" + +#Falls dein Python 3 Code auch unter Python 2.5 oder darunter laufen soll, kann das alte Format benutzt werden: +"%s können %s werden" % ("Strings", "interpoliert") + + +# None ist ein Objekt +None #=> None + +# Verwendet nicht das Symbol für Gleichheit `==`, um Objekte mit None zu vergleichen +# Benutzt stattdessen `is`. Dieser Operator testet Objektidentität +"etc" is None #=> False +None is None #=> True + + + +# None, 0, und leere Strings/Listen werden alle als False bewertet. +# Alle anderen Werte sind True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Variablen und Collections +#################################################### + +# Textausgabe ist sehr einfach +print "Ich bin Python. Schön, dich kennenzulernen!" + +# Es gibt keinen Grund, Variablen vor der Zuweisung zu deklarieren. +some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm +some_var #=> 5 + +# Das Ansprechen einer noch nicht deklarierte Variable löst eine Exception aus. +# Unter "Kontrollstruktur" kann noch mehr über +# Ausnahmebehandlung erfahren werden. +some_unknown_var # Löst einen NameError aus + +# Listen speichern Sequenzen +li = [] +# Wir können mit einer bereits gefüllten Liste anfangen +other_li = [4, 5, 6] + +# append fügt Daten am Ende der Liste ein +li.append(1) #li ist jetzt [1] +li.append(2) #li ist jetzt [1, 2] +li.append(4) #li ist jetzt [1, 2, 4] +li.append(3) #li ist jetzt [1, 2, 4, 3] +# Vom Ende der Liste mit pop entfernen +li.pop() #=> 3 und li ist jetzt [1, 2, 4] +# und dann wieder hinzufügen +li.append(3) # li ist jetzt wieder [1, 2, 4, 3]. + +# Greife auf Listen wie auf Arrays zu +li[0] #=> 1 +# Das letzte Element ansehen +li[-1] #=> 3 + +# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError +li[4] # Verursacht einen IndexError + +# Wir können uns Ranges mit Slice-Syntax ansehen +li[1:3] #=> [2, 4] +# Den Anfang auslassen +li[2:] #=> [4, 3] +# Das Ende auslassen +li[:3] #=> [1, 2, 4] +# Jeden Zweiten Eintrag auswählen +li[::2] # =>[1, 4] +# Eine umgekehrte Kopie zurückgeben +li[::-1] # => [3, 4, 2, 1] +# Jegliche Kombination dieser Syntax machen fortgeschrittene Slices möglich +# li[Start:Ende:Schritt] + +# Ein bestimmtes Element mit del aus der Liste entfernen +del li[2] # li ist jetzt [1, 2, 3] + +# Listen können addiert werden +li + other_li #=> [1, 2, 3, 4, 5, 6] - Hinweis: li und other_li werden in Ruhe gelassen + +# Listen mit extend verknüpfen +li.extend(other_li) # Jetzt ist li [1, 2, 3, 4, 5, 6] + +# Mit in auf Existenz eines Elements prüfen +1 in li #=> True + +# Die Länge der Liste mit len ermitteln +len(li) #=> 6 + + +# Tupel sind wie Listen, nur unveränderlich. +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Löst einen TypeError aus + +# Wir können all diese Listen-Dinge auch mit Tupeln anstellen +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Wir können Tupel (oder Listen) in Variablen entpacken +a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3 +# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen +d, e, f = 4, 5, 6 +# Es ist kinderleicht zwei Werte zu tauschen +e, d = d, e # d is now 5 and e is now 4 + + +# Dictionarys (Wörterbucher) speichern Schlüssel-Werte-Paare +empty_dict = {} +# Hier ein gefülltes Wörterbuch +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Wir können Einträge mit [] nachschlagen +filled_dict["one"] #=> 1 + +# So holen wir alle Keys (Schlüssel) als Liste +list(filled_dict.keys()) #=> ["three", "two", "one"] +# Hinweis - Die Reihenfolge von Schlüsseln in der Liste ist nicht garantiert. +# Einzelne Resultate können anders angeordnet sein. + +# Alle Values (Werte) als Liste +list(filled_dict.values()) #=> [3, 2, 1] +# Hinweis - Hier gelten dieselben Einschränkungen für die Reihenfolge wie bei Schlüsseln. + +# Das Vorhandensein eines Schlüssels im Wörterbuch mit "in" prüfen +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Einen nicht vorhandenenen Schlüssel zu suchen, löst einen KeyError aus +filled_dict["four"] # KeyError + +# Mit der get-Methode verhindern wir das +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# Die get-Methode unterstützt auch ein Standardargument, falls der Wert fehlt +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# Die setdefault-Methode ist ein sicherer Weg, ein neues Schlüssel-Wert-Paar anzulegen +filled_dict.setdefault("five", 5) #filled_dict["five"] wird auf 5 gesetzt +filled_dict.setdefault("five", 6) #filled_dict["five"] ist noch immer 5 + +# Einträge zu einem Wörterbuch hinzufügen +filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 # noch ein Weg, Werte hinzuzufügen + +# Schlüssel von einem Wörterbuch entfernen +del filled_dict["one"] # Entfert den Schlüssel "one" + + +# Sets speichern Mengen +empty_set = set() +# Initialisieren wir ein Set mit ein paar Werten +some_set = {1, 1, 2, 2, 3, 4} # some_set ist jetzt {1, 2, 3, 4} + +# Neue Variablen können einer Menge gleichgesetzt werden +filled_set = some_set + +# Mehr Elemente hinzufügen +filled_set.add(5) # filled_set ist jetzt {1, 2, 3, 4, 5} + +# Schnittmengen werden mit & gebildet +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# Mengen werden mit | vereinigt +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# Die Differenz einer Menge mit - bilden +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Auf Vorhandensein von Elementen mit in prüfen +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. Kontrollstruktur und Iteratoren +#################################################### + +# Erstellen wir mal eine Variable +some_var = 5 + +# Hier eine if-Anweisung. Die Einrückung ist in Python wichtig! +# gibt "some_var ist kleiner als 10" aus +if some_var > 10: + print "some_var ist viel größer als 10." +elif some_var < 10: # Dieser elif-Absatz ist optional. + print "some_var ist kleiner als 10." +else: # Das hier ist auch optional. + print "some_var ist tatsächlich 10." + + +""" +For-Schleifen iterieren über Listen +Ausgabe: + hund ist ein Säugetier + katze ist ein Säugetier + maus ist ein Säugetier +""" +for animal in ["hund", "katze", "maus"]: + # Wir können Strings mit format() formatieren + print("{} ist ein Säugetier".format(animal)) + +""" +`range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder +Ausgabe: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +"range(unten, oben)" gibt eine Liste von der unteren Zahl bis zur oberen Zahl aus +Ausgabe: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +While-Schleifen laufen, bis eine Bedingung erfüllt ist. +Ausgabe: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Kurzform für x = x + 1 + +# Ausnahmebehandlung mit einem try/except-Block +try: + # Mit raise wird ein Fehler ausgegeben + raise IndexError("Das hier ist ein Index-Fehler") +except IndexError as e: + pass # Pass ist nur eine no-op. Normalerweise würden wir hier den Fehler klären. +except (TypeError, NameError): + pass # Mehrere Fehler können zusammen geklärt werden, falls erforderlich. +else: # Optional, hinter allen except-Blöcken + print("Keine Probleme!") # Wird nur ausgeführt, wenn keine Ausnahmen aufgetreten sind +finally: # Wird immer ausgeführt + print("Hier können wir Ressourcen aufräumen") + +# alternativ zu einem try/finally Block um Aufzuräumen: +with open("meineDatei.txt") as f: + for line in f: + print(line) + +# Python bietet ein fundamentales Konzept der Iteration. +# Das Objekt, auf das die Interation, also die Wiederholung einer Methode angewandt wird heißt auf Englisch "iterable". +# Die range Method gibt ein solches Objekt aus. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) #=> range(1,10). Dies ist ein "iterable" Objekt. + +# Über dieses können wir auch iterieren +for i in our_iterable: + print(i) # Gibt one, two, three aus + +# Allerdings können wir die einzelnen Elemente nicht mit ihrem index ausgeben +our_iterable[1] # TypeError + +# Ein iterable ist ein Objekt, das weiß wie es einen Iteratoren erschafft. +our_iterator = iter(our_iterable) + +# Unser Iterator ist ein Objekt, das sich merkt, welchen Status es geraden hat während wir durch es gehen. +# Das jeweeils nächste Objekt bekommen wir mit "next()" +next(our_iterator) #=> "one" + +# Es hält den vorherigen Status +next(our_iterator) #=> "two" +next(our_iterator) #=> "three" + +# Nachdem alle Daten ausgegeben worden sind, kommt eine StopIterator Ausnahme zurück +next(our_iterator) # Gibt StopIteration aus + +# Alle Elemente können mit "list()" ausgegeben werden +list(filled_dict.keys()) #=> ["one", "two", "three"] + + + +#################################################### +## 4. Funktionen +#################################################### + +# Mit def neue Funktionen erstellen +def add(x, y): + print "x ist %s und y ist %s" % (x, y) + return x + y # Werte werden mit return zurückgegeben + +# Funktionen mit Parametern aufrufen +add(5, 6) #=> Ausgabe ist "x ist 5 und y ist 6" und gibt 11 zurück + +# Ein anderer Weg des Funktionsaufrufs sind Schlüsselwort-Argumente +add(y=6, x=5) # Schlüsselwörter können in beliebiger Reihenfolge übergeben werden. + +# Wir können Funktionen mit beliebiger Anzahl von # Positionsargumenten definieren +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Wir können auch Funktionen mit beliebiger Anzahl +# Schlüsselwort-Argumenten definieren +def keyword_args(**kwargs): + return kwargs + +# Rufen wir es mal auf, um zu sehen, was passiert +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Wir können beides gleichzeitig machem, wenn wir wollen +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) Ausgabe: + (1, 2) + {"a": 3, "b": 4} +""" + +# Beim Aufruf von Funktionen können wir das Gegenteil von varargs/kwargs machen! +# Wir benutzen dann *, um Tupel auszuweiten, und ** für kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # äquivalent zu foo(1, 2, 3, 4) +all_the_args(**kwargs) # äquivalent zu foo(a=3, b=4) +all_the_args(*args, **kwargs) # äquivalent zu foo(1, 2, 3, 4, a=3, b=4) + + +# Anwendungsbereich von Funktionen +x = 5 + +def setX(num): + # lokale Variable x ist nicht die globale Variable x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # globale Variable x ist jetzt 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python hat First-Class-Funktionen +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Es gibt auch anonyme Funktionen +(lambda x: x > 2)(3) #=> True + +# Es gibt auch Funktionen höherer Ordnung als Built-Ins +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Wir können bei map- und filter-Funktionen auch List Comprehensions einsetzen +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + +#################################################### +## 5. Klassen +#################################################### + +# Wir bilden die Unterklasse eines Objekts, um Klassen zu erhalten. +class Human(object): + + # Ein Klassenattribut. Es wird von allen Instanzen einer Klasse geteilt + species = "H. sapiens" + + # Ein simpler Konstruktor + def __init__(self, name): + # Wir weisen das Argument name dem name-Attribut der Instanz zu + self.name = name + + # Eine Instanzmethode. Alle Methoden erhalten self als erstes Argument. + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Eine Klassenmethode wird von allen Instanzen geteilt. + # Sie werden mit der aufrufenden Klasse als erstem Argument aufgerufen + @classmethod + def get_species(cls): + return cls.species + + # Eine statische Methode wird ohne Klasse oder Instanz aufgerufen + @staticmethod + def grunt(): + return "*grunt*" + + +# Eine Instanz einer Klasse erstellen +i = Human(name="Ian") +print i.say("hi") # gibt "Ian: hi" aus + +j = Human("Joel") +print j.say("hello") #gibt "Joel: hello" aus + +# Rufen wir mal unsere Klassenmethode auf +i.get_species() #=> "H. sapiens" + +# Ändern wir mal das gemeinsame Attribut +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Aufruf der statischen Methode +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Module +#################################################### + +# Wir können Module importieren +import math +print math.sqrt(16) #=> 4 + +# Wir können auch nur spezielle Funktionen eines Moduls importieren +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Wir können auch alle Funktionen eines Moduls importieren +# Warnung: Dies wird nicht empfohlen +from math import * + +# Wir können Modulnamen abkürzen +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Module sind in Python nur gewöhnliche Dateien. Wir +# können unsere eigenen schreiben und importieren. Der Name des +# Moduls ist der Dateiname. + +# Wir können auch die Funktionen und Attribute eines +# Moduls herausfinden. +import math +dir(math) + + +#################################################### +## 7. Fortgeschritten +#################################################### + +# Generatoren helfen um Code schnell und einfach zu schreiben +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Ein Generator erschafft Werte spontan +# Statt alle Werte auf einmal, wird bei jeder Iteration einer erschaffen. +# iteration. Das heißt, Werte größer als 15 werden nicht behandelt. +# Die range-Methode ist auch ein Generator. Im Fall einer Liste von 1-900000000 +# würde das sehr viel Zeit in Anspruch nehmen. +# Wenn wir eine variable mit einem Namen erschaffen wollen, das +# normalerweise mit einem Python - Schlüsselwort kollidieren würde, +# benutzen wir einen Unterstrich nach dem Wort. +range_ = range(1, 900000000) +# Alle Nummern bis zu einem Ergebnis von >=30 werden verdoppelt +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Dekoratoren +# In diesem Beispiel die Methode beg umwickelt say +# Beim Aufruf von beg, say wird aufgerufen +# Falls say_please true ist, ändert sich die ausgegebene Nachricht +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( + +``` + +## Lust auf mehr? + +### Kostenlos online (Englisch) + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) + +### Totholz (Englisch) + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From 25f954e90ac0fc87fa24a1c018fb891544870dd6 Mon Sep 17 00:00:00 2001 From: Niels van Velzen Date: Sun, 26 Jun 2016 15:06:53 +0200 Subject: Add dutch translation of markdown (#1724) Add dutch translation of markdown --- nl-nl/markdown-nl-html.markdown | 256 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 256 insertions(+) create mode 100644 nl-nl/markdown-nl-html.markdown diff --git a/nl-nl/markdown-nl-html.markdown b/nl-nl/markdown-nl-html.markdown new file mode 100644 index 00000000..0f954715 --- /dev/null +++ b/nl-nl/markdown-nl-html.markdown @@ -0,0 +1,256 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +filename: learnmarkdown-nl.md +translators: + - ["Niels van Velzen", "https://nielsvanvelzen.me"] +lang: nl-nl +--- + +Markdown is gemaakt door John Gruber in 2004. De bedoeling was om een simpel te +lezen en schrijven syntax te creëren wat makkelijk om te zetten is naar +HTML (en tegenwoordig ook vele andere formaten). + +```markdown + + + + + + +# Dit is een

+## Dit is een

+### Dit is een

+#### Dit is een

+##### Dit is een

+###### Dit is een
+ + +Dit is een h1 +============= + +Dit is een h2 +------------- + + + + +*Deze tekst staat schuin.* +_Net als deze tekst._ + +**Deze tekst is dikgedrukt.** +__Net als deze tekst.__ + +***En deze tekst is dik en schuin.*** +**_Net als dit!_** +*__En dit!__* + + + +~~Deze tekst is doorgehaald.~~ + + + + +Dit is een paragraaf. Ik typ in een paragraaf, is dat niet leuk? + +Nu ben ik in paragraaf 2. +Nog steeds in paragraaf 2! + +Dit is paragraaf drie! + + + +Ik eindig met twee spaties (selecteer mij om het te zien). + +Er is een nieuwe regel boven mij! + + + +> Dit is een citaat. Je kan +> handmatig je lijnen laten vormen of je kan je lijnen lang laten worden en vanzelf op nieuwe regels verder laten gaan. +> Het maakt niet uit zolang je maar begint met een `>`. + +> Je kunt ook meer dan 1 level +>> uitlijning gebruiken. +> Hoe handig is dat? + + + + +* Item +* Item +* Nog een item + +of + ++ Item ++ Item ++ Nog een item + +of + +- Item +- Item +- Nog een item + + + +1. Item een +2. Item twee +3. Item drie + + + +1. Item een +1. Item twee +1. Item drie + + + + + +1. Item een +2. Item twee +3. Item drie + * Sub-item een + * Sub-item twee +4. Item vier + + + +Checkboxes hieronder zonder de 'x' zijn leeg. +- [ ] Eerste taak. +- [ ] Tweede taak +Checkboxes met een 'x' zijn klaar. +- [x] Deze taak is klaar. + + + + + Dit is code + net als dit + + + + mijn_array.each do |item| + puts item + end + + + +John wist niet eens wat de `go_to()` functie deed! + + + +\`\`\`ruby +def foobar + puts "Hallo wereld!" +end +\`\`\` + + + + + + +*** +--- +- - - +**************** + + + + +[Klik op mij!](http://test.com/) + + + +[Klik op mij!](http://test.com/ "Link naar Test.com") + + + +[Ga naar de muziek](/music/). + + + +[Klik op deze link][link1] vor meer informatie erover! +[Bekijk deze ook eens][foobar] als je wilt. + +[link1]: http://test.com/ "Cool!" +[foobar]: http://foobar.biz/ "In orde!" + + + + + +[Dit][] is een link. + +[dit]: http://ditiseenlink.nl/ + + + + + + +![Dit is de alt attribuut van het plaatje](http://imgur.com/myimage.jpg "Een optionele titel") + + + +![Dit is de alt attribuut.][mijnplaatje] + +[mijnplaatje]: relative/urls/cool/image.jpg "Hier is de titel" + + + + + is hetzelfde als +[http://testwebsite.com/](http://testwebsite.com/) + + + + + + + +Ik wil *deze tekst met sterretjes typen* maar ik wil het niet schuin, dus ik doe dit: \*deze tekst met sterretjes typen\*. + + + + +Computer gecrashed? Gebruik eens +Ctrl+Alt+Del + + + + +| kolom1 | kolom2 |kolom3 | +| :--------------- | :---------: | ----------------: | +| Links-uitgelijnd | Gecentreerd | Rechts-uitgelijnd | +| blah | blah | blah | + + + +Kolom 1 | Kolom 2 | Kolom 3 +:-- | :-: | --: +Dit is zo lelijk | stop | er mee + + + +``` + +Voor meer informatie, bekijk Josn Gruber's officiele post over de syntax [hier](http://daringfireball.net/projects/markdown/syntax). Of bekijk Adam Pritchard's grote cheatsheet [hier](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) (beide Engels). -- cgit v1.2.3 From eaee51effeaa9a6ec85f64e4cf69e79ac1b507d6 Mon Sep 17 00:00:00 2001 From: Jorge Antonio Atempa Camacho Date: Sun, 26 Jun 2016 06:07:31 -0700 Subject: [haskell/es] Spanish translation (#1309) * Add comments section * Add Strings and Characters Section * Added list and tuples Section * Add More Functions Section * Add translation of Types Signature Section * Add Haskell links * Add translation * Haskell's spanish translation, finished --- es-es/haskell-es.html.markdown | 436 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 436 insertions(+) create mode 100644 es-es/haskell-es.html.markdown diff --git a/es-es/haskell-es.html.markdown b/es-es/haskell-es.html.markdown new file mode 100644 index 00000000..a6900a2b --- /dev/null +++ b/es-es/haskell-es.html.markdown @@ -0,0 +1,436 @@ +--- +language: Haskell +contributors: + - ["Adit Bhargava", "http://adit.io"] +translators: + - ["Jorge Antonio Atempa", "http://www.twitter.com/atempa09"] +lang: es-es +--- + +Haskell fue diseñado como lenguaje de programación funcional práctico y puro. Es famoso por sus mónadas y su sistema de tipos, pero siempre regreso a él debido a su elegancia. Haskell hace la codificación una verdadera alegría para mí. + +```haskell +-- Para comentar una sola línea utiliza dos guiones. +{- Para comentar múltiples líneas puedes encerrarlas +en un bloque como este. +-} + +---------------------------------------------------- +-- 1. Tipos de datos primitivos y Operadores +---------------------------------------------------- + +-- Tienes números a tu disposición +3 -- 3 + +-- Matématicas, es lo que esperas +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 +35 / 5 -- 7.0 + +-- Por defecto la división no devuelve un entero +35 / 4 -- 8.75 + +-- Para la división entera utiliza +35 `div` 4 -- 8 + +-- Valores booleanos +True +False + +-- Operaciones booleanas +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- En los ejemplos superiores, `not` es una función que toma un valor. +-- Haskell no necesita paréntisis para las llamadas a funciones...todos los argumentos +-- son enlistados después de la función. Entonces el patrón general es: +-- func arg1 arg2 arg3... +-- Observa la sección de funciones para obtener información de como escribir tu propia función. + +-- Cadenas y caracteres +"Esto es una cadena." +'a' -- caracter +'No puedes utilizar comillas simples para cadenas.' -- ¡error! + +-- Concatenación de cadenas +"¡Hola " ++ "mundo!" -- "¡Hola mundo!" + +-- Una cadena es una lista de caracteres +['H', 'o', 'l', 'a'] -- "Hola" +"Esto es una cadena" !! 0 -- 'E' + + +---------------------------------------------------- +-- Listas y Tuplas +---------------------------------------------------- + +-- Cada elemento en una lista debe ser del mismo tipo. +-- Estas dos listas son iguales: +[1, 2, 3, 4, 5] +[1..5] + +-- Los rangos son versátiles. +['A'..'F'] -- "ABCDEF" + +-- Puedes crear un paso en un rango. +[0,2..10] -- [0, 2, 4, 6, 8, 10] +[5..1] -- Esto no funciona debido a que Haskell incrementa por defecto. +[5,4..1] -- [5, 4, 3, 2, 1] + +-- indexación en una lista +[0..] !! 5 -- 5 + +-- También tienes listas infinitas en Haskell! +[1..] -- una lista de todos los números naturales + +-- Las listas infinitas funcionan porque Haskell tiene "lazy evaluation". Esto significa +-- que Haskell solo evalúa las cosas cuando lo necesita. Así que puedes pedir +-- el elemento 1000 de tú lista y Haskell te devolverá: + +[1..] !! 999 -- 1000 + +-- Y ahora Haskell ha evaluado elementos 1 - 1000 de esta lista...pero el +-- resto de los elementos de esta lista "infinita" ¡no existen todavía! Haskell no lo hará +-- en realidad los evalúa hasta que los necesita. + +-- uniendo dos listas +[1..5] ++ [6..10] + +-- añadiendo a la cabeza de la lista +0:[1..5] -- [0, 1, 2, 3, 4, 5] + +-- más operaciones con listas +head [1..5] -- 1 +tail [1..5] -- [2, 3, 4, 5] +init [1..5] -- [1, 2, 3, 4] +last [1..5] -- 5 + +-- Listas por comprensión +[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] + +-- Listas por comprensión utilizando condicionales +[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] + +-- Cada elemento en una tupla puede ser de diferente tipo, pero una tupla tiene +-- longitud fija. +-- Ejemplo de una tupla: +("haskell", 1) + +-- acceder a los elementos (por ejemplo una tupla de longitud 2) +fst ("haskell", 1) -- "haskell" +snd ("haskell", 1) -- 1 + +---------------------------------------------------- +-- 3. Funciones +---------------------------------------------------- +-- Una función simple que recibe dos variables +add a b = a + b + +-- Nota: Si estas utilizando ghci (el interprete de Haskell) +-- Necesitas utilizar `let`, por ejemplo +-- let add a b = a + b + +-- Utilizando la función +add 1 2 -- 3 + +-- También puedes llamar a la función enmedio de dos argumentos +-- con acentos abiertos: +1 `add` 2 -- 3 + +-- ¡También puedes definir funciones sin tener que utilizar letras! De este modo +-- ¡Tú defines tus propios operadores! Aquí esta un operador que realiza +-- una división entera +(//) a b = a `div` b +35 // 4 -- 8 + +-- Guardas: son una manera fácil para ramificar funciones +fib x + | x < 2 = 1 + | otherwise = fib (x - 1) + fib (x - 2) + +-- La coincidencia de patrones es similar. Aquí hemos dado tres diferentes +-- definiciones para fib. Haskell llamará automáticamente la primer +-- función que coincide con el patrón del valor. +fib 1 = 1 +fib 2 = 2 +fib x = fib (x - 1) + fib (x - 2) + +-- Coincidencia de patrones en tuplas: +foo (x, y) = (x + 1, y + 2) + +-- Coincidencia de patrones en listas. Aquí `x` es el primer elemento +-- en una lista, y `xs` es el resto de la lista. Podemos escribir +-- nuestra propia función map: +myMap func [] = [] +myMap func (x:xs) = func x:(myMap func xs) + +-- Funciones anónimas son creadas con una diagonal invertida seguido de +-- todos los argumentos. +myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] + +-- utilizando pliegues (llamado `inject` en algunos lenguajes) con una función +-- anónima. foldl1 significa pliegue por la izquierda, y usa el primer valor +-- en la lista como el valor inicial para el acumulador. +foldl1 (\acc x -> acc + x) [1..5] -- 15 + +---------------------------------------------------- +-- 4. Más funciones +---------------------------------------------------- + +-- aplicación parcial: si no quieres pasar todos los argumentos a una función, +-- esta es "parcialmente aplicada". Esto significa que retorna una función que toma +-- el resto de los argumentos. + +add a b = a + b +foo = add 10 -- foo es actualmente una función que toma un número y suma 10 a esta +foo 5 -- 15 + +-- Otra manera de escribir los mismo +foo = (+10) +foo 5 -- 15 + +-- composición de funciones +-- el (.) encadena funciones. +-- Por ejemplo, aquí foo es una función que toma un valor. Y se le suma 10, +-- posteriormente multiplica el resultado por 5, y devuelve el resultado final. +foo = (*5) . (+10) + +-- (5 + 10) * 5 = 75 +foo 5 -- 75 + +-- fijación de precedencia +-- Haskell tiene otro operador llamado `$`. Este operador aplica a una función +-- para un parámetro dado. En contraste a la aplicación de función estándar, +-- la cúal tiene prioridad más alta posible de 10 y es asociativa por la izquierda, +-- el operador `$` tiene prioridad de 0 y es asociativa por la derecha. Tal que +-- una baja prioridad significa que la expresión a su derecha es aplicada como parámetro a la función a su izquierda. + +-- antes +even (fib 7) -- false + +-- equivalentemente +even $ fib 7 -- false + +-- composición de funciones +even . fib $ 7 -- false + + +---------------------------------------------------- +-- 5. Firma de tipos +---------------------------------------------------- + +-- Haskell tiene un fuerte sistema de tipado, y cada cosa tiene una firma de tipo. + +-- Algunos tipos básicos: +5 :: Integer +"hola" :: String +True :: Bool + +-- Las funciones tienen muchos tipos. +-- `not` toma un booleano y devuelve un booleano: +-- not :: Bool -> Bool + +-- Aquí, esta función toma dos argumentos: +-- add :: Integer -> Integer -> Integer + +-- Cuando defines un valor, es una buena práctica escribir su tipo en una línea superior: +double :: Integer -> Integer +double x = x * 2 + +---------------------------------------------------- +-- 6. Control de flujo y Expresiones If +---------------------------------------------------- + +-- expressiones if en una sola línea +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- expressiones if en múltiples líneas, la identación es importante +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- expressiones case: Aquí se muestra como analizar los argumentos +-- desde línea de comandos +case args of + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + +-- Haskell no tiene ciclos; en lugar de esto utiliza recursión. +-- map aplica una función sobre cada elemento en un arreglo + +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +-- tú puedes crear una función utilizando map +for array func = map func array + +-- y entonces utilizarla +for [0..5] $ \i -> show i + +-- también podríamos haberlo escrito de esta manera: +for [0..5] show + +-- Puedes utilizar foldl o foldr para reducir una lista +-- foldl +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- Esto es lo mismo que +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- foldl es izquierda, foldr es derecha +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- Esto es los mismo que +(2 * 1 + (2 * 2 + (2 * 3 + 4))) + +---------------------------------------------------- +-- 7. Tipos de datos +---------------------------------------------------- + +-- Por ejemplo, para crear tu propio tipo de dato en Haskell + +data Color = Rojo | Azul | Verde + +-- Ahora puedes utilizarlo en una función: + + +say :: Color -> String +say Rojo = "¡Es Rojo!" +say Azul = "¡Es Azul!" +say Verde = "¡Es Verde!" + +-- Tus tipos de datos pueden tener parámetros también: + +data Maybe a = Nothing | Just a + +-- Estos son todos de tipo Maybe +Just "hello" -- de tipo `Maybe String` +Just 1 -- de tipo `Maybe Int` +Nothing -- de tipo `Maybe a` para cualquier `a` + +---------------------------------------------------- +-- 8. Haskell IO +---------------------------------------------------- + +-- Mientras que IO no puede ser explicado plenamente sin explicar las mónadas, +-- no es difícil explicar lo suficiente para ponerse en marcha. + +-- Cuando un programa en Haskell se ejecuta, `main` es +-- llamado. Este debe devolver un valor de tipo `IO ()`. Por ejemplo: + +main :: IO () +main = putStrLn $ "¡Hola, cielo! " ++ (say Blue) +-- putStrLn tiene tipo String -> IO () + +-- Es más fácil de hacer IO si puedes implementar tu programa como +-- una función de String a String. La función +-- interact :: (String -> String) -> IO () +-- recibe como entrada un texto, ejecuta una función e imprime +-- una salida. + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- Puedes pensar en el valor de tipo `IO ()` como la representación +-- de una secuencia de acciones que la computadora hace, al igual que +-- un programa escrito en un lenguaje imperativo. Podemos utilizar +-- la notación `do` para encadenar acciones. Por ejemplo: + +sayHello :: IO () +sayHello = do + putStrLn "¿Cual es tu nombre?" + name <- getLine -- obtenemos un valor y lo proporcionamos a "name" + putStrLn $ "Hola, " ++ name + +-- Ejercicio: escribe tu propia version de `interact` que solo lea +-- una linea como entrada. + +-- Nunca se ejecuta el código en `sayHello`, sin embargo. La única +-- acción que siempre se ejecuta es el valor de `main`. +-- Para ejecutar `sayHello` comenta la definición anterior de `main` +-- y sustituyela por: +-- main = sayHello + +-- Vamos a entender mejor como funciona la función `getLine` cuando +-- la utilizamos. Su tipo es: +-- getLine :: IO String +-- Puedes pensar en el valor de tipo `IO a` como la representación +-- programa que generará un valor de tipo `a` +-- cuando es ejecutado (además de cualquier otra cosa que haga). Podemos +-- almacenar y reutilizar el valor usando `<-`. También podemos +-- crear nuestra propia acción de tipo `IO String`: + +action :: IO String +action = do + putStrLn "Esta es una linea." + input1 <- getLine + input2 <- getLine + -- El tipo de la sentencia `do` es la de su última línea. + -- `return` no es una palabra clave, sino simplemente una función + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- Podemos usar esto sólo como usabamos `getLine`: + +main'' = do + putStrLn "¡Volveré a repetir dos líneas!" + result <- action + putStrLn result + putStrLn "Esto es todo, ¡amigos!" + +-- El tipo `IO` es un ejemplo de una "mónada". La forma en que Haskell utiliza una monada +-- permite que sea un lenguaje puramente funcional. Cualquier función que +-- interactue con el mundo exterior (por ejemplo usar IO) obtiene una marca `IO` +-- como su firma de tipo. Esto nos permite pensar qué funciones son "puras" +-- (que no interactuan con el mundo exterior o modifican el estado) y que funciones no lo son. + +-- Esta es una poderosa característica, porque es una manera fácil de ejecutar funciones puras +-- concurrentemente; entonces, la concurrencia en Haskell es muy fácil. + + +---------------------------------------------------- +-- 9. El interprete de comandos de Haskell +---------------------------------------------------- + +-- Para comenzar escribe desde la terminal `ghci`. +-- Ahora puede escribir código en Haskell. Para cualquier valor nuevo +-- que necesites crear utiliza `let`: + +let foo = 5 + +-- Puedes inspeccionar el tipo de cualquier valor con `:t`: + +>:t foo +foo :: Integer + +-- Puedes ejecutar acciones de tipo `IO ()` + +> sayHello +¿Cual es tu nombre? +Amigo +Hola, Amigo + +``` + +Existe mucho más de Haskell, incluyendo clases de tipos y mónadas. Estas son +las grandes ideas que hacen a Haskell divertido. Te dejamos un ejemplo final +de Haskell: una implementación del algoritmo QuickSort: + +```haskell +qsort [] = [] +qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater + where lesser = filter (< p) xs + greater = filter (>= p) xs +``` + +Haskell es fácil de instalar. Obtenlo [aquí](http://www.haskell.org/platform/). + +Usted puede encontrar más información en: +[Learn you a Haskell](http://learnyouahaskell.com/) o +[Real World Haskell](http://book.realworldhaskell.org/) o +[Aprende Haskell por el bien de todos](http://aprendehaskell.es/) -- cgit v1.2.3 From eb15a9272f151e50397e3fdfc0cd4bced4faec53 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 15:08:10 +0200 Subject: #1672 metadata --- es-es/haskell-es.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/es-es/haskell-es.html.markdown b/es-es/haskell-es.html.markdown index a6900a2b..babb1060 100644 --- a/es-es/haskell-es.html.markdown +++ b/es-es/haskell-es.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Adit Bhargava", "http://adit.io"] translators: - ["Jorge Antonio Atempa", "http://www.twitter.com/atempa09"] +filename: haskell-es.md lang: es-es --- -- cgit v1.2.3 From 810178c3cc3e83d37efc8b73772b1a468f6117a9 Mon Sep 17 00:00:00 2001 From: Xuan-thi N Date: Sun, 26 Jun 2016 15:10:26 +0200 Subject: [Git/fr] Added translation for Git article (#1949) * Added translation for Git article * Took into account suggestions for modification * Forgot a fix --- fr-fr/git-fr.html.markdown | 583 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 583 insertions(+) create mode 100644 fr-fr/git-fr.html.markdown diff --git a/fr-fr/git-fr.html.markdown b/fr-fr/git-fr.html.markdown new file mode 100644 index 00000000..7a83704d --- /dev/null +++ b/fr-fr/git-fr.html.markdown @@ -0,0 +1,583 @@ +--- +category: tool +tool: git +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Leo Rudberg" , "http://github.com/LOZORD"] + - ["Betsy Lorton" , "http://github.com/schbetsy"] + - ["Bruno Volcov", "http://github.com/volcov"] +translators: + - ["Xuan-thi Nguyen", "http://github.com/mellenguyen"] +filename: LearnGit-fr-.txt +lang: fr-fr +--- + +Git est un logiciel de contrôle de versions distribué et un système de gestion +du code source. + +Il effectue sa tâche via des séries d'instantanés (snapshots) du projet, et +travaille avec ces instantanés afin de fournir les fonctionnalités de gestion +de version et de code source. + +## Concepts du versionnage + +### Qu'est ce que le contrôle de version ? + +Le contrôle de version est un système qui enregistre les changements faits sur +un ou plusieurs fichiers au fil du temps. + +### Versionnage centralisé VS Versionnage distribué + +* Le contrôle de version centralisé se concentre sur la synchronisation, le +suivi et la sauvegarde des fichiers. +* Le contrôle de version distribué se focalise sur l'échange des changements. +Chaque changement a un identifiant unique. +* Les systèmes distribués n'ont pas de structure définie. Vous pouvez aisément +avoir un système centralisé de type SVN, avec Git. + +[Informations additionnelles](http://git-scm.com/book/fr/v1/D%C3%A9marrage-rapide-%C3%80-propos-de-la-gestion-de-version) + +### Pourquoi utiliser Git ? + +* Fonctionne hors ligne. +* Travailler avec les autres devient facile ! +* Ramifier le travail (créer des branches différentes) est facile ! +* Fusionner le travail est facile ! +* Git est rapide. +* Git est flexible. + +## Architecture Git + + +### Dépôt ("repository") + +Un ensemble de fichiers, dossiers, historiques de modifications, commits +(validations de changements) et de heads (état courant, "tête"). +Représentez-vous ceci comme une structure de données de code source, avec la +particularité que chaque "élement" vous donne, entre autres, accès à son +historique des révisions. + +Un dépôt Git comprend un répertoire .git et "l'arbre de travail" (working tree). + +### Répertoire .git (composant du dépôt) + +Le répertoire .git contient toutes les configurations, logs (journaux), +branches, HEAD et plus. +[Liste détaillée (EN)](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) + +### Arbre de travail (composant du dépôt) + +Il s'agit de l'ensemble des répertoires et fichiers de votre dépôt. Il est +souvent qualifié de répertoire de travail ("working directory"). + +### Index (composant du répertoire .git) + +L'index est la zone de transit ("staging area") dans Git. Il s'agit d'une couche +séparant votre arbre de travail de votre dépôt Git. Ceci donne aux développeurs +plus de pouvoir sur ce qu'ils envoient au dépôt. + +### Commit + +Un "commit" (validation de changements) est un instantané d'un ensemble de +modifications de votre arbre de travail. Par exemple, si vous avez rajouté 5 +fichiers et enlevé 2 autres, ces changements seront contenus dans un commit +(ou "snapshot", instantané). Ce commit peut ensuite être poussé ("pushed") dans +d'autres dépôts, ou non ! + +### Branches + +Une branche consiste essentiellement en un pointeur vers le dernier commit que +vous avez fait. Au fur et à mesure de vos commits, ce pointeur se mettra +automatiquement à jour pour pointer vers le dernier commit. + +### Etiquette ("tag") + +Une étiquette est une marque sur un point spécifique de l'historique. +Typiquement, on utilise cette fonctionnalité pour marquer les états de +publication (v1.0, et ainsi de suite). + +### HEAD and head (composant du répertoire .git) + +HEAD est un pointeur pointant vers la branche courante. Un dépôt ne peut avoir +qu'un seul HEAD *actif*. +head est un pointeur pouvant pointer sur n'importe quel commit. Un dépôt peut +avoir un nombre illimité de heads. + +### Les états dans Git +* Modifié - Des changements on été faits à un fichier mais ce dernier n'a pas +encore été rajouté à l'ensemble des fichiers Git +* Indexé ("staged") - Indique qu'un fichier modifié ira dans le prochain commit +* Validé ("committed") - Les fichiers ont été validés dans l'ensemble de +fichiers + +### Ressources conceptuelles + +* [Git pour les informaticiens (EN)](http://eagain.net/articles/git-for-computer-scientists/) +* [Git pour les designers (EN)](http://hoth.entp.com/output/git_for_designers.html) + + +## Commandes + + +### init + +Créé un dépôt Git vide. Les paramètres du dépôt Git, les informations stockées +et plus sont dans un répertoire (un dossier) nommé ".git". + +```bash +$ git init +``` + +### config + +Configuration des paramètres. Que ce soit pour le dépôt, le système lui-même, +ou la configuration globale (le fichier de configuration globale +est `~/.gitconfig`). + + +```bash +# Lit et assigne quelques variables (globales) de configuration de base +$ git config --global user.email "monEmail@foo.com" +$ git config --global user.name "Mon nom" +``` + +[Apprenez-en plus à propos de git config.](https://git-scm.com/book/fr/v1/Personnalisation-de-Git-Configuration-de-Git) + +### help + +Vous donne un accès rapide à un guide extrêmement détaillé de chaque commande. +Ou juste vous donner un rappel rapide de la sémantique. + +```bash +# Vérifie rapidement les commandes disponibles +$ git help + +# Vérifie toutes les commandes disponibles +$ git help -a + +# Aide pour une commande spécifique - manuel utilisateur +# git help +$ git help add +$ git help commit +$ git help init +# ou git --help +$ git add --help +$ git commit --help +$ git init --help +``` + +### ignorer des fichiers + +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 +``` + +### status + +Montre les différences entre le fichier indexé (typiquement votre copie/dépôt +de travail) et le HEAD actuel. + + +```bash +# Affiche la branche, les fichiers non suivis, les changements et autres +différences +$ git status + +# Pour en apprendre plus sur git status +$ git help status +``` + +### add + +Rajoute des fichiers à la zone d'index. Si vous ne faites pas `git add` sur les +nouveaux fichiers, ils ne seront pas inclus dans les commits ! + +```bash +# rajoute un fichier dans votre répertoire de travail actuel +$ git add HelloWorld.java + +# rajoute un fichier dans un répertoire imbriqué +$ git add /path/to/file/HelloWorld.c + +# Gestion des expressions régulières ! +$ git add ./*.java +``` + +On ne fait que rajouter des fichiers dans la zone d'index, on ne valide pas +les changements au répertoire/dépôt de travail. + +### branch + +Gère vos branches. Vous pouvez voir, éditer, créer et supprimer des branches en +utilisant cette commande. + +```bash +# Liste les branches existantes et distantes +$ git branch -a + +# Créé une nouvelle branche +$ git branch maNouvelleBranche + +# Supprime une branche +$ git branch -d maBranche + +# Renomme une branche +# git branch -m +$ git branch -m nomDeMaBranche nouveauNomDeMaBranche + +# Edite la description d'une branche +$ git branch nomDeMaBranche --edit-description +``` + +### tag + +Gère vos étiquettes + +```bash +# Liste les étiquettes +$ git tag + +# Créé une étiquette annotée +# L'option -m spécifie un message qui sera stockée dans l'étiquette. +# Si vous ne spécifiez pas de message pour une étiquette annotée, +# Git lance votre éditeur pour que vous puissiez le saisir. +$ git tag -a v2.0 -m 'ma version 2.0' + +# Affiche des informations à propos de l'étiquette +# comprenant des informations sur l'auteur, la date du commit correspondant, +# et le message d'annotation avant d'afficher les informations du commit. +$ git show v2.0 + +# Pousse une seule étiquette dans le dépôt distant +$ git push origin v2.0 + +# Pousse beaucoup d'étiquettes dans le dépôt distant +$ git push origin --tags +``` + +### checkout + +Met à jour tous les fichiers dans l'arbre de travail afin de correspondre à la +version de la zone d'index ou de l'arbre spécifié. + +```bash +# Obtenir une copie de travail du dépôt - par défaut on prend la branche master +$ git checkout + +# Bascule vers une branche spéficiée +$ git checkout nomDeLaBranche + +# Créé une nouvelle branche et bascule sur celle-ci +# Revient à faire "git branch ; git checkout " +$ git checkout -b nouvelleBranche +``` + +### clone + +Clone (ou copie) un dépôt existant dans un nouveau répertoire. Rajoute +également les branches distantes pour chaque branche du dépôt clôné, ce qui +vous permet de pousser vers une branche distante. + +```bash +# Clone learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git + +# Clone superficiel ("shallow clone") - clone plus rapide qui récupère +seulement le dernier instantané ("snapshot") +$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git + +# Clone seulement une branche spécifique +$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch +``` + +### commit + +Conserve le contenu actuel de la zone d'index dans un nouveau "commit." Ce +commit contient les changements faits, accompagnés d'un message écrit par son +auteur. + +```bash +# Commit avec un message +$ git commit -m "Ajout de la fonction multiplierNombres() dans HelloWorld.c" + +# Rajoute automatiquement dans l'index les fichiers modifiés ou supprimés, +# à l'exception des nouveaux fichiers, puis commit +$ git commit -a -m "Modification de foo.php et suppression de bar.php" + +# Change le dernier commit (ceci supprime le commit précédent avec un +# nouveau commit) +$ git commit --amend -m "Message corrigé" +``` + +### diff + +Montre les différences entre un fichier dans le répertoire de travail, la zone +d'index and les commits. + +```bash +# Affiche les différences entre votre répertoire de travail et l'index +$ git diff + +# Affiche les différences entre l'index et le plus récent commit. +$ git diff --cached + +# Affiche les différences entre votre répertoire de travail et le plus récent +# commit +$ git diff HEAD +``` + +### grep + +Permet de faire une recherche rapide dans le dépôt. + +Configurations optionnelles : + +```bash +# Merci à Travis Jeffery pour ce qui suit +# Affiche les numéros des lignes dans les résultats de la recherche grep +$ git config --global grep.lineNumber true + +# Rend les résultats de recherche plus lisibles, en incluant les groupements +$ git config --global alias.g "grep --break --heading --line-number" +``` + +```bash +# Recherche de "nomDeVariable" dans tous les fichiers java +$ git grep 'nomDeVariable' -- '*.java' + +# Recherche une ligne contenant "nomDeTableau", et "rajouter" ou "enlever" +$ git grep -e 'nomDeTableau' --and \( -e rajouter -e enlever \) +``` + +Google est votre ami; pour plus d'exemples : +[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) + +### log + +Affiche les commits d'un dépôt. + +```bash +# Montre tous les commits +$ git log + +# Montre seulement les messages de commits et leur référence +$ git log --oneline + +# Montre seulement les commits commits des merges (fusions) +$ git log --merges +``` + +### merge + +Fusionne les changements provenant de commits externes dans la branche +courante. + +```bash +# Fusionne la branche spécifiée dans la branche courante. +$ git merge nomDeBranche + +# Génère toujours un commit quand on fusionne +$ git merge --no-ff branchName +``` + +### mv + +Renomme ou déplace un fichier + +```bash +# Renomme un fichier +$ git mv HelloWorld.c HelloNewWorld.c + +# Déplace un fichier +$ git mv HelloWorld.c ./new/path/HelloWorld.c + +# Force le renommage ou le déplacement +# Si "fichierExistant" existe déjà dans le répertoire, il sera écrasé +$ git mv -f monFichier fichierExistant +``` + +### pull + +Récupère la version d'un dépôt et la fusionne avec une autre branche. + +```bash +# Met à jour votre dépôt local en y intégrant les changements +# depuis la branche "master" du dépôt distant "origin". +# git pull +$ git pull origin master + +# Par défaut, git pull mettra à jour votre branche actuelle +# en y intégrant les nouveaux changements venant de sa branche distante suivie +$ git pull + +# Intègre les changements de la branche distante et "rebase" +# les commits de la branche dans votre dépôt local, comme ceci: +#"git pull , git rebase " +$ git pull origin master --rebase +``` + +### push + +Pousse et fusionne les changements d'une dépôt local vers une branche distante. + +```bash +# Pousse et fusionne les changements d'un dépôt local vers la branche +# appelée "master" du dépôt distant "master". +# git push +$ git push origin master + +# Par défaut, git push poussera et fusionnera les changements de la branche +# courante vers sa branche distante suivie. +$ git push + +# Pour faire le lien entre la branche locale courante et sa branche distante, +# rajouter l'option -u : +$ git push -u origin master +# Dorénavant, à chaque fois que vous voulez pousser depuis cette même branche +# locale, utilisez ce raccourci : +$ git push +``` + +### stash + +Sauvegarde ("stash") l'état actuel de votre espace de travail et le garde dans +pile de changements non finis que vous pouvez réappliquer n'importe quand. + +Supposons que vous avez effectué du travail dans votre dépôt git, mais que vous +voulez récupérer la version de la branche distante. Depuis que vous avez des +changements "malpropres" (non commités) à quelques fichiers, vous ne pouvez pas +faire de `git pull`. A la place, vous pouvez utiliser `git stash` afin de +sauvegarder votre travail dans la pile ! + +```bash +$ git stash +Saved working directory and index state \ + "WIP on master: 049d078 added the index file" + HEAD is now at 049d078 added the index file + (To restore them type "git stash apply") +``` + +Vous pouvez maintenant pull ! + +```bash +git pull +``` +`...changes apply...` + +Vérifiez maintenant que tout est OK + +```bash +$ git status +# On branch master +nothing to commit, working directory clean +``` + +Vous pouvez constater quels "morceaux" vous avez stash jusque là en +utilisant `git stash list`. +Puisque les changements sont gardés dans une pile Last-In-First-Out, notre +changement le plus récent sera en premier. + +```bash +$ git stash list +stash@{0}: WIP on master: 049d078 rajout du fichier index +stash@{1}: WIP on master: c264051 annulation de "rajout de la taille_fichier" +stash@{2}: WIP on master: 21d80a5 ajout des chiffres aux logs +``` + +Appliquons maintenant les changements en les enlevant de notre pile. + +```bash +$ git stash pop +# On branch master +# Changes not staged for commit: +# (use "git add ..." to update what will be committed) +# +# modified: index.html +# modified: lib/simplegit.rb +# +``` + +`git stash apply` effectue le même travail + +Vous êtes maintenant prêt à retourner sur vos tâches de travail ! + +[Lecture additionelle.](https://git-scm.com/book/fr/v1/Utilitaires-Git-Le-remisage) + +### rebase (attention) + +Prend tous les changements qui ont été commités sur une branche, et les +ré-applique sur une autre branche. +*Ne rebasez pas les commits que vous avez poussés sur un dépôt publique*. + +```bash +# Expérimentation d'un rebase dans la branche "master" +# git rebase +$ git rebase master brancheExperience +``` + +[Lecture additionelle.](https://git-scm.com/book/fr/v1/Les-branches-avec-Git-Rebaser) + +### reset (attention) + +Réinitialise le pointeur HEAD courant à l'état spécifié. Ceci vous permet +d'annuler des fusions, des pulls, commits, ajouts et autres. C'est une commande +puissante mais également dangereuse si vous ne savez pas ce que vous faites. + +```bash +# Réinitialise la zone d'index afin de correspondre au dernier commit (laisse +# le répertoire inchangé). +$ git reset + +# Réinitialise la zone d'index afin de correspondre au dernier commit et +# réécrit le répertoire de travail. +$ git reset --hard + +# Déplace le pointeur de la branche courante au commit spécifié (laisse +# le répertoire inchangé). Tous les changements existents toujours dans +# le répertoire. +$ git reset 31f2bb1 + +# Déplace le pointeur de la branche courante en arrière, au commit spécifié +# et fait correspondre le répertoire de travail (supprime les changements +# non commités et tous les commits après le commit spécifié). +$ git reset --hard 31f2bb1 +``` + +### rm + +Le contraire de git add, git rm supprime les fichiers de l'arbre de travail +courant. + +```bash +# Supprime HelloWorld.c +$ git rm HelloWorld.c + +# Enlève un fichier d'un répertoire imbriqué. +$ git rm /chemin/vers/le/fichier/HelloWorld.c +``` + +## Informations complémentaires + +* [tryGit - A fun interactive way to learn Git (EN)](http://try.github.io/levels/1/challenges/1) + +* [Udemy Git Tutorial: A Comprehensive Guide (EN)](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) + +* [git-scm - Tutoriaux vidéos](http://git-scm.com/videos) + +* [git-scm - Documentation](http://git-scm.com/docs) + +* [Atlassian Git - Tutoriaux et Workflows](https://www.atlassian.com/git/) + +* [SalesForce Cheat Sheet (EN)](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) + +* [GitGuys (EN)](http://www.gitguys.com/) + +* [Git - the simple guide (EN)](http://rogerdudler.github.io/git-guide/index.html) + +* [Livre Pro Git](http://www.git-scm.com/book/fr/v1) + +* [Une introduction à Git et GitHub pour les débutants (tutoriel) (EN)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) -- cgit v1.2.3 From cf309475adf6e26ec3977c81d58d033551361e18 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 15:10:59 +0200 Subject: #1949 metadata fix --- fr-fr/git-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/git-fr.html.markdown b/fr-fr/git-fr.html.markdown index 7a83704d..510459fe 100644 --- a/fr-fr/git-fr.html.markdown +++ b/fr-fr/git-fr.html.markdown @@ -8,7 +8,7 @@ contributors: - ["Bruno Volcov", "http://github.com/volcov"] translators: - ["Xuan-thi Nguyen", "http://github.com/mellenguyen"] -filename: LearnGit-fr-.txt +filename: LearnGit-fr.txt lang: fr-fr --- -- cgit v1.2.3 From b7e57907b97582c5adc4f4cbf4c0fbee6e56a6ef Mon Sep 17 00:00:00 2001 From: Jacopo Andrea Giola Date: Sun, 26 Jun 2016 15:11:52 +0200 Subject: Add Italian translation for Markdown (#1663) --- it-it/markdown.html.markdown | 244 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 244 insertions(+) create mode 100644 it-it/markdown.html.markdown diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown new file mode 100644 index 00000000..2560c5b1 --- /dev/null +++ b/it-it/markdown.html.markdown @@ -0,0 +1,244 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Jacopo Andrea Giola", "http://geekpanda.net"] +filename: markdown.md +lang: it-it +--- + +Markdown è stato creato da John Gruber nel 2004. Il suo scopo è quello di essere una sintassi facile da leggere e scrivere, e che può essere convertita in HTML (ad oggi anche in molti altri formati). + +Mandate tutto il feedback che volete! / Sentitevi liberi di forkare o di mandare pull request! + + +```markdown + + + + + + +# Questo è un

+## Questo è un

+### Questo è un

+#### Questo è un

+##### Questo è un

+###### Questo è un
+ + +Questo è un h1 +============== + +Questo è un h2 +-------------- + + + + +*Questo testo è in corsivo.* +_Come pure questo._ + +**Questo testo è in grassetto.** +__Come pure questo.__ + +***Questo testo è stilizzato in entrabmi i modi.*** +**_Come questo!_** +*__E questo!__* + + + +~~Questo testo è barrato.~~ + + + +Qeusto è un paragrafo. Sto scrivendo in un paragrafo, non è divertente? + +Ora sono nel paragrafo 2. +Anche questa linea è nel paragrafo 2! + + +Qui siamo nel paragrafo 3! + + + +Questa frase finisce con due spazi (evidenziatemi per vederli). + +C'è un
sopra di me! + + + +> Questa è una citazione. Potete +> mandare a capo manualmente le linee e inserire un `>` prima di ognuna, oppure potete usare una sola linea e lasciare che vada a capo automaticamente. +> Non c'è alcuna differenza, basta che iniziate ogni riga con `>`. + +> Potete utilizzare anche più di un livello +>> di indentazione! +> Quanto è comodo? + + + + +* Oggetto +* Oggetto +* Altro oggetto + +oppure + ++ Oggetto ++ Oggetto ++ Un altro oggetto + +oppure + +- Oggetto +- Oggetto +- Un ultimo oggetto + + + +1. Primo oggetto +2. Secondo oggetto +3. Terzo oggetto + + + +1. Primo oggetto +1. Secondo oggetto +1. Terzo oggetto + + + + +1. Primo oggetto +2. Secondo oggetto +3. Terzo oggetto + * Sotto-oggetto + * Sotto-oggetto +4. Quarto oggetto + + + +I box senza la 'x' sono checkbox HTML ancora da completare. +- [ ] Primo task da completare. +- [ ] Secondo task che deve essere completato. +Il box subito sotto è una checkbox HTML spuntata. +- [x] Questo task è stato completato. + + + + + Questa è una linea di codice + Come questa + + + + my_array.each do |item| + puts item + end + + + +Giovanni non sapeva neppure a cosa servisse la funzione `go_to()`! + + + +\`\`\`ruby +def foobar + puts "Hello world!" +end +\`\`\` + + + + + + +*** +--- +- - - +**************** + + + + +[Cliccami!](http://test.com/) + + + +[Cliccami!](http://test.com/ "Link a Test.com") + + + +[Vai a musica](/music/). + + + +[Apri questo link][link1] per più informazioni! +[Guarda anche questo link][foobar] se ti va. + +[link1]: http://test.com/ "Bello!" +[foobar]: http://foobar.biz/ "Va bene!" + + + + + +[Questo][] è un link. + +[Questo]: http://thisisalink.com/ + + + + + + +![Qeusto è il testo alternativo per l'immagine](http://imgur.com/myimage.jpg "Il titolo opzionale") + + + +![Questo è il testo alternativo.][myimage] + +[myimage]: relative/urls/cool/image.jpg "Se vi serve un titolo, lo mettete qui" + + + + + è equivalente ad +[http://testwebsite.com/](http://testwebsite.com/) + + + + + + + +Voglio inserire *questo testo circondato da asterischi* ma non voglio che venga renderizzato in corsivo, quindi lo inserirò così: \*questo testo è circondato da asterischi\*. + + + + +Il tuo computer è crashato? Prova a premere +Ctrl+Alt+Canc + + + + +| Col1 | Col2 | Col3 | +| :------------------- | :------: | -----------------: | +| Allineato a sinistra | Centrato | Allineato a destra | +| blah | blah | blah | + + + +Col 1 | Col2 | Col3 +:-- | :-: | --: +È una cosa orrenda | fatela | finire in fretta + + + +``` + +Per altre informazioni, leggete il post ufficiale di John Gruber sulla sintassi [qui](http://daringfireball.net/projects/markdown/syntax) e il magnifico cheatsheet di Adam Pritchard [qui](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From 4604870dc36e9603c563826224d13af881c7e132 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 15:12:36 +0200 Subject: metadata fix --- it-it/markdown.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown index 2560c5b1..b006dbb4 100644 --- a/it-it/markdown.html.markdown +++ b/it-it/markdown.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - ["Jacopo Andrea Giola", "http://geekpanda.net"] -filename: markdown.md +filename: markdown-it.md lang: it-it --- -- cgit v1.2.3 From 19ac1e8eeb92115b1af90ea1aa9181a8f6d48211 Mon Sep 17 00:00:00 2001 From: s-webber Date: Sun, 26 Jun 2016 14:20:28 +0100 Subject: [kotlin/en] Add examples of sequences (#2214) * minor capitalization and punctuation changes * examples of sequences * corrected comment --- kotlin.html.markdown | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/kotlin.html.markdown b/kotlin.html.markdown index 7b1475a8..605b1a63 100644 --- a/kotlin.html.markdown +++ b/kotlin.html.markdown @@ -5,7 +5,7 @@ contributors: filename: LearnKotlin.kt --- -Kotlin is a Statically typed programming language for the JVM, Android and the +Kotlin is a statically typed programming language for the JVM, Android and the browser. It is 100% interoperable with Java. [Read more here.](https://kotlinlang.org/) @@ -72,7 +72,7 @@ fun helloWorld(val name : String) { A variable can be specified as nullable by appending a ? to its type. We can access a nullable variable by using the ?. operator. We can use the ?: operator to specify an alternative value to use - if a variable is null + if a variable is null. */ var fooNullable: String? = "abc" println(fooNullable?.length) // => 3 @@ -137,7 +137,7 @@ fun helloWorld(val name : String) { println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}") } - //The "class" keyword is used to declare classes. + // The "class" keyword is used to declare classes. class ExampleClass(val x: Int) { fun memberFunction(y: Int) : Int { return x + y @@ -194,7 +194,7 @@ fun helloWorld(val name : String) { println(fooList.size) // => 3 println(fooList.first()) // => a println(fooList.last()) // => c - // elements can be accessed by index + // Elements of a list can be accessed by their index. println(fooList[1]) // => b // A mutable list can be created using the "mutableListOf" function. @@ -213,12 +213,37 @@ fun helloWorld(val name : String) { // Map values can be accessed by their key. println(fooMap["a"]) // => 8 + /* + Sequences represent lazily-evaluated collections. + We can create a sequence using the "generateSequence" function. + */ + val fooSequence = generateSequence(1, {it + 1}) + val x = fooSequence.take(10).toList() + println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + + // An example of using a sequence to generate Fibonacci numbers: + fun fibonacciSequence() : Sequence { + var a = 0L + var b = 1L + + fun next() : Long { + val result = a + b + a = b + b = result + return a + } + + return generateSequence(::next) + } + val y = fibonacciSequence().take(10).toList() + println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] + // Kotlin provides higher-order functions for working with collections. - val x = (1..9).map {it * 3} + val z = (1..9).map {it * 3} .filter {it < 20} .groupBy {it % 2 == 0} .mapKeys {if (it.key) "even" else "odd"} - println(x) // => {odd=[3, 9, 15], even=[6, 12, 18]} + println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]} // A "for" loop can be used with anything that provides an iterator. for (c in "hello") { -- cgit v1.2.3 From 273fa8606b662dbec5b3b0b2fd0d3dfd648e00ab Mon Sep 17 00:00:00 2001 From: Geoffrey Liu Date: Sun, 26 Jun 2016 21:21:13 +0800 Subject: [racket/en] Add more details about Racket (#2278) * Add let* and letrec reference * More elaboration on structs * Add code about predefined car, cdr functions * Mention explicit typing, int to real conversion --- racket.html.markdown | 34 ++++++++++++++++++++++++++++++++++ standard-ml.html.markdown | 8 ++++++++ 2 files changed, 42 insertions(+) diff --git a/racket.html.markdown b/racket.html.markdown index 0fe3f030..96dcaf25 100644 --- a/racket.html.markdown +++ b/racket.html.markdown @@ -114,18 +114,42 @@ some-var ; => 5 "Alice" me) ; => "Bob" +;; let* is like let, but allows you to use previous bindings in creating later bindings +(let* ([x 1] + [y (+ x 1)]) + (* x y)) + +;; finally, letrec allows you to define recursive and mutually recursive functions +(letrec ([is-even? (lambda (n) + (or (zero? n) + (is-odd? (sub1 n))))] + [is-odd? (lambda (n) + (and (not (zero? n)) + (is-even? (sub1 n))))]) + (is-odd? 11)) + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 3. Structs and Collections ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Structs +; By default, structs are immutable (struct dog (name breed age)) (define my-pet (dog "lassie" "collie" 5)) my-pet ; => # +; returns whether the variable was constructed with the dog constructor (dog? my-pet) ; => #t +; accesses the name field of the variable constructed with the dog constructor (dog-name my-pet) ; => "lassie" +; You can explicitly declare a struct to be mutable with the #:mutable option +(struct rgba-color (red green blue alpha) #:mutable) +(define burgundy + (rgba-color 144 0 32 1.0)) +(set-color-green! burgundy 10) +(color-green burgundy) ; => 10 + ;;; Pairs (immutable) ;; `cons' constructs pairs, `car' and `cdr' extract the first ;; and second elements @@ -143,6 +167,16 @@ my-pet ; => # ;; and a quote can also be used for a literal list value '(1 2 3) ; => '(1 2 3) +;; Racket has predefined functions on top of car and cdr, to extract parts of a list +(cadr (list 1 2 3)) ; => 2 +(car (cdr (list 1 2 3))) ; => 2 + +(cddr (list 1 2 3)) ; => '(3) +(cdr (cdr (list 1 2 3))) ; => '(3) + +(caddr (list 1 2 3)) ; => 3 +(car (cdr (cdr (list 1 2 3)))) ; => 3 + ;; Can still use `cons' to add an item to the beginning of a list (cons 4 '(1 2 3)) ; => '(4 1 2 3) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index 143980e7..133e4f54 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -24,6 +24,12 @@ val phone_no = 5551337 val pi = 3.14159 val negative_number = ~15 (* Yeah, unary minus uses the 'tilde' symbol *) +(* Optionally, you can explicitly declare types. This is not necessary as + ML will automatically figure out the types of your values. *) +val diameter = 7926 : int +val e = 2.718 : real +val name = "Bobby" : string + (* And just as importantly, functions: *) fun is_large(x : int) = if x > 37 then true else false @@ -31,6 +37,8 @@ fun is_large(x : int) = if x > 37 then true else false val tau = 2.0 * pi (* You can multiply two reals *) val twice_rent = 2 * rent (* You can multiply two ints *) (* val meh = 1.25 * 10 *) (* But you can't multiply an int and a real *) +val yeh = 1.25 * (Real.fromInt 10) (* ...unless you explicitly convert + one or the other *) (* +, - and * are overloaded so they work for both int and real. *) (* The same cannot be said for division which has separate operators: *) -- cgit v1.2.3 From a7015a0f8592d49f62bbafae1dcffcf1619ec92d Mon Sep 17 00:00:00 2001 From: Adam Heins Date: Sun, 26 Jun 2016 06:21:27 -0700 Subject: Minor formatting and wording change in rust doc. (#2277) --- rust.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/rust.html.markdown b/rust.html.markdown index d0c56b4a..440cd9eb 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -281,7 +281,7 @@ fn main() { println!("{}", var); // Unlike `box`, `var` can still be used println!("{}", *ref_var); // var = 5; // this would not compile because `var` is borrowed - // *ref_var = 6; // this would not too, because `ref_var` is an immutable reference + // *ref_var = 6; // this would not either, because `ref_var` is an immutable reference // Mutable reference // While a value is mutably borrowed, it cannot be accessed at all. @@ -289,8 +289,9 @@ fn main() { let ref_var2: &mut i32 = &mut var2; *ref_var2 += 2; // '*' is used to point to the mutably borrowed var2 - println!("{}", *ref_var2); // 6 , //var2 would not compile. //ref_var2 is of type &mut i32, so //stores a reference to an i32 not the value. - // var2 = 2; // this would not compile because `var2` is borrowed + println!("{}", *ref_var2); // 6 , // var2 would not compile. + // ref_var2 is of type &mut i32, so stores a reference to an i32, not the value. + // var2 = 2; // this would not compile because `var2` is borrowed. } ``` -- cgit v1.2.3 From 6069ef6dc36baa14eda997591031c1eaf78b6481 Mon Sep 17 00:00:00 2001 From: Arlindo Pereira Date: Sun, 26 Jun 2016 10:22:21 -0300 Subject: fixing typos (#2228) --- pt-br/bash-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/bash-pt.html.markdown b/pt-br/bash-pt.html.markdown index a604e7b8..ae18435a 100644 --- a/pt-br/bash-pt.html.markdown +++ b/pt-br/bash-pt.html.markdown @@ -161,11 +161,11 @@ echo "#helloworld" > output.out echo "#helloworld" | cat > output.out echo "#helloworld" | tee output.out > /dev/null -# Limpa os arquivos temporarios detalhando quais foram deletados (use '-i' para confirmar exlusão) +# Limpa os arquivos temporários detalhando quais foram deletados (use '-i' para confirmar exclusão) rm -v output.out error.err output-and-error.log -# Comando podem ser substituidos por outros comandos usando $( ): -# O comand oa seguir mostra o número de arquivos e diretórios no diretorio atual +# Comando podem ser substituídos por outros comandos usando $( ): +# O comando a seguir mostra o número de arquivos e diretórios no diretorio atual echo "Existem $(ls | wc -l) itens aqui." # O mesmo pode ser feito usando crase `` mas elas não podem ser aninhadas - dá se -- cgit v1.2.3 From ec15a36de7bcc56708d7e6d52fabe0296b8cc466 Mon Sep 17 00:00:00 2001 From: Arlindo Pereira Date: Sun, 26 Jun 2016 10:22:34 -0300 Subject: Removing untranslated duplicated text (#2227) --- pt-br/javascript-pt.html.markdown | 4 ---- 1 file changed, 4 deletions(-) diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index 59c6890e..e337f4bc 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -197,7 +197,6 @@ myObj.myFourthKey; // = undefined // A sintaxe para essa seção é quase idêntica a maioria das linguagens. -// The `if` structure works as you'd expect. // A estrutura `if` funciona como deveria ser. var count = 1 if (count == 3){ @@ -219,9 +218,6 @@ do { input = getInput(); } while (!isValid(input)) -// The `for` loop is the same as C and Java: -// initialisation; continue condition; iteration. - // O loop `for` é o mesmo de C e Java: // inicialização, condição para continuar; iteração for (var i = 0; i < 5; i++){ -- cgit v1.2.3 From e72c849556dd7ae9cd1333229b4c007a7229225f Mon Sep 17 00:00:00 2001 From: Alexandre Constantino Date: Sun, 26 Jun 2016 14:22:47 +0100 Subject: Python3/en: multiple inheritance (#2217) * Add __name__ check to make testing easier * Update say to call print. Add more usage examples * Move Modules section before Classes Makes more sense for when explaining inheritance * Add multiple inheritance example * Add examples for multiple inheritance * Add instance check examples * Fix multiple inheritance example * Add note on the __name__ variable --- python3.html.markdown | 197 +++++++++++++++++++++++++++++++++++++------------- 1 file changed, 147 insertions(+), 50 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 0f5da8f1..7f3702e6 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -601,10 +601,47 @@ list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + #################################################### -## 5. Classes +## 5. Modules #################################################### +# You can import modules +import math +print(math.sqrt(16)) # => 4.0 + +# You can get specific functions from a module +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# You can import all functions from a module. +# Warning: this is not recommended +from math import * + +# You can shorten module names +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Python modules are just ordinary python files. You +# can write your own, and import them. The name of the +# module is the same as the name of the file. + +# You can find out which functions and attributes +# defines a module. +import math +dir(math) + +# If you have a Python script named math.py in the same +# folder as your current script, the file math.py will +# be loaded instead of the built-in Python module. +# This happens because the local folder has priority +# over Python's built-in libraries. + + +#################################################### +## 6. Classes +#################################################### # We use the "class" operator to get a class class Human: @@ -627,7 +664,11 @@ class Human: # An instance method. All methods take "self" as the first argument def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) + print ("{name}: {message}".format(name=self.name, message=msg)) + + # Another instance method + def sing(self): + return 'yo... yo... microphone check... one two... one two...' # A class method is shared among all instances # They are called with the calling class as the first argument @@ -658,71 +699,127 @@ class Human: del self._age -# Instantiate a class -i = Human(name="Ian") -print(i.say("hi")) # prints out "Ian: hi" +# When a Python interpreter reads a source file it executes all its code. +# This __name__ check makes sure this code block is only executed when this +# module is the main program. +if __name__ == '__main__': + # Instantiate a class + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # i and j are instances of type Human, or in other words: they are Human objects + + # Call our class method + i.say(i.get_species()) # "Ian: H. sapiens" + # Change the shared attribute + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # Call the static method + print(Human.grunt()) # => "*grunt*" + print(i.grunt()) # => "*grunt*" + + # Update the property for this instance + i.age = 42 + # Get the property + i.say(i.age) # => 42 + j.say(j.age) # => 0 + # Delete the property + del i.age + # i.age # => this would raise an AttributeError -j = Human("Joel") -print(j.say("hello")) # prints out "Joel: hello" -# Call our class method -i.get_species() # => "H. sapiens" +#################################################### +## 6.1 Multiple Inheritance +#################################################### -# Change the shared attribute -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" +# Another class definition +class Bat: -# Call the static method -Human.grunt() # => "*grunt*" + species = 'Baty' -# Update the property -i.age = 42 + def __init__(self, can_fly=True): + self.fly = can_fly -# Get the property -i.age # => 42 + # This class also has a say method + def say(self, msg): + msg = '... ... ...' + return msg -# Delete the property -del i.age -i.age # => raises an AttributeError + # And its own method as well + def sonar(self): + return '))) ... (((' +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) -#################################################### -## 6. Modules -#################################################### +# from "filename-without-extension" import "function-or-class" +from human import Human +from bat import Bat -# You can import modules -import math -print(math.sqrt(16)) # => 4.0 +# Batman inherits from both Human and Bat +class Batman(Human, Bat): -# You can get specific functions from a module -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 + # Batman has its own value for the species class attribute + species = 'Superhero' -# You can import all functions from a module. -# Warning: this is not recommended -from math import * + def __init__(self, *args, **kwargs): + # Typically to inherit attributes you have to call super: + #super(Batman, self).__init__(*args, **kwargs) + # However we are dealing with multiple inheritance here, and super() + # only works with the next base class in the MRO list. + # So instead we explicitly call __init__ for all ancestors. + # The use of *args and **kwargs allows for a clean way to pass arguments, + # with each parent "peeling a layer of the onion". + Human.__init__(self, 'anonymous', *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # override the value for the name attribute + self.name = 'Sad Affleck' -# You can shorten module names -import math as m -math.sqrt(16) == m.sqrt(16) # => True + def sing(self): + return 'nan nan nan nan nan batman!' -# Python modules are just ordinary python files. You -# can write your own, and import them. The name of the -# module is the same as the name of the file. -# You can find out which functions and attributes -# defines a module. -import math -dir(math) +if __name__ == '__main__': + sup = Batman() + + # Instance type checks + if isinstance(sup, Human): + print('I am human') + if isinstance(sup, Bat): + print('I am bat') + if type(sup) is Batman: + print('I am Batman') + + # Get the Method Resolution search Order used by both getattr() and super(). + # This attribute is dynamic and can be updated + print(Batman.__mro__) # => (, , , ) + + # Calls parent method but uses its own class attribute + print(sup.get_species()) # => Superhero + + # Calls overloaded method + print(sup.sing()) # => nan nan nan nan nan batman! + + # Calls method from Human, because inheritance order matters + sup.say('I agree') # => Sad Affleck: I agree + + # Call method that exists only in 2nd ancestor + print(sup.sonar()) # => ))) ... ((( + + # Inherited class attribute + sup.age = 100 + print(sup.age) + + # Inherited attribute from 2nd ancestor whose default value was overriden + print('Can I fly? ' + str(sup.fly)) + -# If you have a Python script named math.py in the same -# folder as your current script, the file math.py will -# be loaded instead of the built-in Python module. -# This happens because the local folder has priority -# over Python's built-in libraries. #################################################### ## 7. Advanced -- cgit v1.2.3 From 5068509640591a47a47169687757fc996c88d60a Mon Sep 17 00:00:00 2001 From: Voltinus Date: Sun, 26 Jun 2016 16:24:58 +0300 Subject: [json/pl] Translated JSON tutorial (#2079) * Create json-pl.html.markdown * Update json-pl.html.markdown * Added -pl to file name --- pl-pl/json-pl.html.markdown | 85 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 pl-pl/json-pl.html.markdown diff --git a/pl-pl/json-pl.html.markdown b/pl-pl/json-pl.html.markdown new file mode 100644 index 00000000..872455de --- /dev/null +++ b/pl-pl/json-pl.html.markdown @@ -0,0 +1,85 @@ +--- +language: json +filename: learnjson-pl.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] + - ["Michael Neth", "https://github.com/infernocloud"] +translators: + - ["Michał Mitrosz", "https://github.com/Voltinus"] +lang: pl-pl +--- + +JSON to bardzo prosty format wymiany danych. Jak jest napisane na [json.org](http://json.org), jest łatwy do pisania i czytania dla ludzi i do parsowania i generowania dla maszyn. + +Kod JSON musi zawierać któreś z poniższych: +* Zbiór par nazwa/wartość (`{ }`). W różnych językach jest to obiekt, rekord, struktura, słownik, tablica mieszająca, lista z kluczami, lub tablica asocjacyjna. +* Uporządkowana lista wartości (`[ ]`). W różnych językach jest to tablica, wektor, lista, lub sekwencja. + tablica/lista/sekwencja (`[ ]`) lub słownik/obiekt/tablica asocjacyjna (`{ }`). + +JSON w swojej czystej postaci nie ma komentarzy, ale większość parserów akceptuje komentarze w stylu C (`//`, `/* */`). Niektóre parsery pozwalają także na końcowy przecinek (np. przecinek po ostatnim elemencie w tablicy lub po ostatiej własności obiektu), ale powinien on być omijany dla lepszej kompatybilności. + +Dla celów tego poradnika wszystko będzie 100% kodem JSON. Na szczęście, to samo mówi za siebie. + +Wspierane typy danych: + +* Łańcuchy znaków: `"witaj"`, `"\"Cytat.\""`, `"\u0abe"`, `"Nowa linia.\n"` +* Liczby: `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4` +* Obiekty: `{ "klucz": "wartość" }` +* Tablice: `["Wartości"]` +* Inne: `true`, `false`, `null` + +```json +{ + "klucz": "wartość", + + "klucze": "muszą być zawsze zamknięte w podwójnych cudzysłowach", + "liczby": 0, + "łańcuchy": "Hellø, wørld. Wszystkie znaki unicode są dozwolone, razem z \"sekwencjami escape\".", + "wartości logiczne?": true, + "nic": null, + + "duża liczba": 1.2e+100, + + "obiekty": { + "komentarz": "Większość twojej struktury będzie zbudowana z obiektów.", + + "tablica": [0, 1, 2, 3, "Tablice mogą mieć wewnątrz cokolwiek", 5], + + "inny obiekt": { + "komentarz": "Elementy mogą się w sobie zawierać, bardzo użyteczne" + } + }, + + "głupota": [ + { + "źródła potasu": ["banany"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "styl alternatywny": { + "komentarz": "sprawdź to!" + , "pozycja przecinka": "nie ma znaczenia, o ile jest przed następnym kluczem, jest poprawnie" + , "następny komentarz": "jak ładnie" + }, + + + + "znaki białe": "nie mają znaczenia", + + + + "to było krótkie": "I gotowe. Wiesz już wszystko o formacie JSON." +} +``` + +## Dalsza lektura + +* [JSON.org](http://json.org) Cały JSON pięknie wytłumaczony na podstawie grafik przypominających schematy blokowe. -- cgit v1.2.3 From 0bb3ed5f870025a14e07cd9ff7eb00277cd14e19 Mon Sep 17 00:00:00 2001 From: Tasya Aditya Rukmana Date: Sun, 26 Jun 2016 21:29:20 +0800 Subject: Added id-id translation for markdown (#1476) --- id-id/markdown.html.markdown | 263 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 263 insertions(+) create mode 100644 id-id/markdown.html.markdown diff --git a/id-id/markdown.html.markdown b/id-id/markdown.html.markdown new file mode 100644 index 00000000..5e28aba9 --- /dev/null +++ b/id-id/markdown.html.markdown @@ -0,0 +1,263 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Tasya Aditya Rukmana", "http://github.com/tadityar"] +filename: markdown.md +--- + +Markdown dibuat oleh John Gruber pada tahun 2004. Tujuannya untuk menjadi syntax yang mudah dibaca dan ditulis yang dapat berubah menjadi HTML (dan sekarang berbagai format lainnya) dengan mudah. + +Beri masukan sebanyak-banyaknya! / Jangan sungkan untuk melakukan fork dan pull request! + + +```markdown + + + + + + +# Ini adalah

+## Ini adalah

+### Ini adalah

+#### Ini adalah

+##### Ini adalah

+###### Ini adalah
+ + +Ini adalah h1 +============= + +Ini adalah h2 +------------- + + + + +*Ini adalah teks miring.* +_Dan juga teks ini._ + +**Ini adalah teks tebal.** +__Dan juga teks ini.__ + +***Ini adalah teks dengan keduanya.*** +**_Dan juga ini!_** +*__Dan ini!__* + + + +~~Teks ini dirender dengan coretan.~~ + + + +Ini adalah paragraf. Saya mengetik dalam paragraf, bukankah ini menyenangkan? + +Sekarang saya ada di paragraf 2. +Saya juga masih ada dalam paragraf 2! + + +Saya ada di paragraf 3! + + + +Aku diakhiri dua spasi (soroti aku untuk melihatnya). + +Ada sebuah
diatasku! + + + +> Ini adalah kutipan. Anda dapat +> membungkusnya secara manual dan meletakkan `>` sebelum tiap baris atau Anda dapat membuat baris yang sangat panjang dan membuatnya membungkus secara otomatis. +> Tidak ada masalah selama ia diawali dengan `>`. + +> Anda juga dapat menggunakan lebih dari satu level +>> indentasi! +> Sangat rapi bukan? + + + + +* Item +* Item +* Item lainnya + +atau + ++ Item ++ Item ++ Satu lagi item + +or + +- Item +- Item +- Item terakhir + + + +1. Item satu +2. Item dua +3. Item tiga + + + +1. Item satu +1. Item dua +1. Item tida + + + + +1. Item satu +2. Item dua +3. Item tiga + * Sub-item + * Sub-item +4. Item empat + + + +Kotak di bawah tanpa 'x' adalah kotak centang HTML yang belum diisi. +- [ ] Tugas pertama selesai. +- [ ] Tugas kedua yang harus diselesaikan +Kotak centang HTML berikut telah diisi. +- [x] Tugas ini telah diselesaikan + + + + + Ini adalah kode + Dan ini juga + + + + array_ku.each do |item| + puts item + end + + + +John bahkan tidak tahu apa fungsi dari `go_to()` ! + + + +\`\`\`ruby +def foobar + puts "Halo Dunia!" +end +\`\`\` + + + + + + +*** +--- +- - - +**************** + + + + +[Klik aku!](http://test.com/) + + + +[Klik aku!](http://test.com/ "Link to Test.com") + + + +[Pergi ke musik](/music/). + + + +[Klik link ini][link1] untuk info lebih banyak! +[Juga cek link ini][foobar] jika Anda mau. + +[link1]: http://test.com/ "Keren!" +[foobar]: http://foobar.biz/ "OK!" + + + + + +[Ini][] adalah tautan. + +[ini]: http://thisisalink.com/ + + + + + + +![Ini adalah atribut alt dari gambar saya](http://imgur.com/myimage.jpg "Judul opsional") + + + +![Ini adalah atribut alt.][myimage] + +[myimage]: relative/urls/cool/image.jpg "jika Anda membutuhkan judul, disini" + + + + + sama dengan +[http://testwebsite.com/](http://testwebsite.com/) + + + + + + + +Saya ingin mengetik *teks ini dikelilingi tanda bintang* tapi saya tidak mau teksnya menjadi +miring, jadi saya melakukan: \*teks ini dikelilingi tanda bintang\*. + + + + +Komputer Anda hang? Coba kirim sebuah +Ctrl+Alt+Del + + + + +| Kol1 | Kol2 | Kol3 | +| :----------- | :------: | ------------: | +| Rata-kiri | Tengah | Rata-Kanan | +| blah | blah | blah | + + + +Kol 1 | Kol2 | Kol3 +:-- | :-: | --: +Ugh ini sangat jelek | buat ia | berhenti + + + +``` + +Untuk info lebih lanjut, cek post syntax resmi John Gruber [di sini](http://daringfireball.net/projects/markdown/syntax) dan contekan hebat Adam Pritchard's [di sini](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From c6ba8c1f3f9401907236da73a3eddcf77b05bf2e Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 15:29:40 +0200 Subject: #1476 metadata --- id-id/markdown.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/id-id/markdown.html.markdown b/id-id/markdown.html.markdown index 5e28aba9..9a7c18cc 100644 --- a/id-id/markdown.html.markdown +++ b/id-id/markdown.html.markdown @@ -3,8 +3,8 @@ language: markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - - ["Tasya Aditya Rukmana", "http://github.com/tadityar"] -filename: markdown.md + - ["Tasya Aditya Rukmana", "http://github.com/tadityar"] +filename: markdown-id.md --- Markdown dibuat oleh John Gruber pada tahun 2004. Tujuannya untuk menjadi syntax yang mudah dibaca dan ditulis yang dapat berubah menjadi HTML (dan sekarang berbagai format lainnya) dengan mudah. -- cgit v1.2.3 From d9c2b9a9c26ecb387b50660e71855691c0995e1d Mon Sep 17 00:00:00 2001 From: fontealpina Date: Sun, 26 Jun 2016 15:30:05 +0200 Subject: Add matlab italian translation (#1454) --- it-it/matlab-it.html.markdown | 525 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 525 insertions(+) create mode 100644 it-it/matlab-it.html.markdown diff --git a/it-it/matlab-it.html.markdown b/it-it/matlab-it.html.markdown new file mode 100644 index 00000000..b1e8777b --- /dev/null +++ b/it-it/matlab-it.html.markdown @@ -0,0 +1,525 @@ +--- +language: Matlab +contributors: + - ["mendozao", "http://github.com/mendozao"] + - ["jamesscottbrown", "http://jamesscottbrown.com"] + - ["Colton Kohnke", "http://github.com/voltnor"] +translators: + - ["Samuele Gallerani", "http://github.com/fontealpina"] +lang: it-it +--- + +MATLAB sta per MATrix LABoratory ed è un potente linguaggio per il calcolo numerico comunemente usato in ingegneria e matematica. + +```matlab +% I commenti iniziano con il segno percentuale. + +%{ +I commenti multilinea +assomigliano a +qualcosa +del genere +%} + +% i comandi possono essere spezzati su più linee, usando '...': + a = 1 + 2 + ... + + 4 + +% i comandi possono essere passati al sistema operativo +!ping google.com + +who % Mostra tutte le variabili in memoria +whos % Mostra tutte le variabili in memoria, con i loro tipi +clear % Cancella tutte le tue variabili dalla memoria +clear('A') % Cancella una particolare variabile +openvar('A') % Apre la variabile in un editor di variabile + +clc % Cancella il contenuto della Command Window +diary % Attiva il log della Command Window su file +ctrl-c % Interrompe il calcolo corrente + +edit('myfunction.m') % Apre la funzione/script nell'editor +type('myfunction.m') % Stampa il codice della funzione/script sulla Command Window + +profile on % Attiva la profilazione del codice +profile off % Disattiva la profilazione del codice +profile viewer % Apre il profilatore + +help comando % Mostra la documentazione di comando sulla Command Window +doc comando % Mostra la documentazione di comando sulla Help Window +lookfor comando % Cerca comando nella prima linea di commento di tutte le funzioni +lookfor comando -all % Cerca comando in tutte le funzioni + + +% Formattazione dell'output +format short % 4 decimali in un numero float +format long % 15 decimali +format bank % Solo due cifre decimali - per calcoli finaziari +fprintf('text') % Stampa "text" a terminale +disp('text') % Stampa "text" a terminale + +% Variabili ed espressioni +miaVariabile = 4 % Il pannello Workspace mostra la nuova variabile creata +miaVariabile = 4; % Il punto e virgola evita che l'output venga stampato sulla Command Window +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 + +% La chiamata di funzioni può essere fatta in due modi differenti: +% Sintassi standard di una funzione: +load('myFile.mat', 'y') % argomenti tra parentesi, separati da virgole +% Sintassi di tipo comando: +load myFile.mat y % Non ci sono parentesi e gli argometi sono separati da spazi +% Notare la mancanza di apici nella sintassi di tipo comando: gli input sono sempre passati come +% testo letterale - non è possibile passare valori di variabili. Inoltre non può ricevere output: +[V,D] = eig(A); % Questa non ha una forma equivalente con una sintassi di tipo comando +[~,D] = eig(A); % Se si vuole solo D e non V + + + +% Operatori logici +1 > 5 % ans = 0 +10 >= 10 % ans = 1 +3 ~= 4 % Not equal to -> ans = 1 +3 == 3 % equal to -> ans = 1 +3 > 1 && 4 > 1 % AND -> ans = 1 +3 > 1 || 4 > 1 % OR -> ans = 1 +~1 % NOT -> ans = 0 + +% Gli operatori logici possono essere applicati alle matrici: +A > 5 +% Per ogni elemento, se la condizione è vera, quell'elemento vale 1 nella matrice risultante +A( A > 5 ) +% Restituisce un vettore contenente gli elementi in A per cui la condizione è vera + +% Stringhe +a = 'MyString' +length(a) % ans = 8 +a(2) % ans = y +[a,a] % ans = MyStringMyString + + +% Celle +a = {'one', 'two', 'three'} +a(1) % ans = 'one' - ritorna una cella +char(a(1)) % ans = one - ritorna una stringa + +% Strutture +A.b = {'one','two'}; +A.c = [1 2]; +A.d.e = false; + +% Vettori +x = [4 32 53 7 1] +x(2) % ans = 32, gli indici in Matlab iniziano da 1, non da 0 +x(2:3) % ans = 32 53 +x(2:end) % ans = 32 53 7 1 + +x = [4; 32; 53; 7; 1] % Vettore colonna + +x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 + +% Matrici +A = [1 2 3; 4 5 6; 7 8 9] +% Le righe sono separate da punto e virgola, mentre gli elementi sono separati da spazi +% A = + +% 1 2 3 +% 4 5 6 +% 7 8 9 + +A(2,3) % ans = 6, A(row, column) +A(6) % ans = 8 +% (implicitamente concatena le colonne in un vettore, e quindi gli indici sono riferiti al vettore) + + +A(2,3) = 42 % Aggiorna riga 2 colonna 3 con 42 +% A = + +% 1 2 3 +% 4 5 42 +% 7 8 9 + +A(2:3,2:3) % Crea una nuova matrice a partire da quella precedente +%ans = + +% 5 42 +% 8 9 + +A(:,1) % Tutte le righe nella colonna 1 +%ans = + +% 1 +% 4 +% 7 + +A(1,:) % Tutte le colonne in riga 1 +%ans = + +% 1 2 3 + +[A ; A] % Concatenazione di matrici (verticalmente) +%ans = + +% 1 2 3 +% 4 5 42 +% 7 8 9 +% 1 2 3 +% 4 5 42 +% 7 8 9 + +% è equivalente a +vertcat(A,A); + + +[A , A] % Concatenazione di matrici (orrizontalmente) + +%ans = + +% 1 2 3 1 2 3 +% 4 5 42 4 5 42 +% 7 8 9 7 8 9 + +% è equivalente a +horzcat(A,A); + + +A(:, [3 1 2]) % Ripristina le colonne della matrice originale +%ans = + +% 3 1 2 +% 42 4 5 +% 9 7 8 + +size(A) % ans = 3 3 + +A(1, :) =[] % Rimuove la prima riga della matrice +A(:, 1) =[] % Rimuove la prima colonna della matrice + +transpose(A) % Traspone la matrice, equivale a: +A one +ctranspose(A) % Trasposizione hermitiana della matrice +% (ovvero il complesso coniugato di ogni elemento della matrice trasposta) + + + + +% Aritmetica Elemento per Elemento vs. Artimetica Matriciale +% Gli operatori aritmetici da soli agliscono sull'intera matrice. Quando sono preceduti +% da un punto, allora agiscono su ogni elemento. Per esempio: +A * B % Moltiplicazione matriciale +A .* B % Moltiplica ogni elemento di A per il corrispondente elemento di B + +% Ci sono diverse coppie di funzioni, in cui una agisce su ogni elemento, e +% l'altra (il cui nome termina con m) agisce sull'intera matrice. +exp(A) % Calcola l'esponenziale di ogni elemento +expm(A) % Calcola la matrice esponenziale +sqrt(A) % Calcola la radice quadrata di ogni elementotake the square root of each element +sqrtm(A) % Trova la matrice di cui A nè è la matrice quadrata + + +% Plot di grafici +x = 0:.10:2*pi; % Crea un vettore che inizia a 0 e termina 2*pi con incrementi di .1 +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 range da 0 a 2*pi, y range da -1 a 1 + +plot(x,y1,'-',x,y2,'--',x,y3,':') % Per stampare più funzioni in unico plot +legend('Line 1 label', 'Line 2 label') % Aggiunge un etichetta con il nome delle curve + +% Metodo alternativo per stampare funzioni multiple in un unico plot. +% mentre 'hold' è on, i comandi sono aggiunti al grafico esistene invece di sostituirlo +plot(x, y) +hold on +plot(x, z) +hold off + +loglog(x, y) % Un plot di tipo log-log +semilogx(x, y) % Un plot con asse x logaritmico +semilogy(x, y) % Un plot con asse y logaritmico + +fplot (@(x) x^2, [2,5]) % Stampa la funzione x^2 da x=2 a x=5 + +grid on % Mostra la griglia, disattivare con 'grid off' +axis square % Rende quadrata la regione individuata dagli assi +axis equal % Iposta l'aspetto del grafico in modo che le unità degli assi siano le stesse + +scatter(x, y); % Scatter-plot +hist(x); % Istogramma + +z = sin(x); +plot3(x,y,z); % Stampa una linea 3D + +pcolor(A) % Heat-map di una matrice: stampa una griglia di rettangoli, colorati in base al valore +contour(A) % Contour plot di una matrice +mesh(A) % Stampa come una superfice di mesh + +h = figure % Crea un nuovo oggetto figura, con handle f +figure(h) % Rende la figura corrispondente al handle h la figura corrente +close(h) % Chiude la figura con handle h +close all % Chiude tutte le figure +close % Chiude la figura corrente + +shg % Riutilizza una finestra grafica già esistente, o se necessario ne crea una nuova +clf clear % Pulisce la figura corrente, e resetta le proprietà della figura + +% Le proprietà possono essere impostate e modificate attraverso l'handle della figura. +% Si può salvare l'handle della figura quando viene creata. +% La funzione gcf restituisce un handle alla figura attuale. +h = plot(x, y); % Si può salvare un handle della figura quando viene creata +set(h, 'Color', 'r') +% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black +set(h, 'LineStyle', '--') + % '--' linea continua, '---' tratteggiata, ':' puntini, '-.' trattino-punto, 'none' nessuna linea +get(h, 'LineStyle') + + +% La funzione gca restituisce un handle degli assi della figura corrente +set(gca, 'XDir', 'reverse'); % Inverte la direzione dell'asse x + +% Per creare una figura che contiene diverse sottofigure, usare subplot +subplot(2,3,1); % Seleziona la prima posizione in una griglia 2 per 3 di sottofigure +plot(x1); title('First Plot') % Stampa qualcosa in questa posizione +subplot(2,3,2); % Seleziona la seconda posizione nella griglia +plot(x2); title('Second Plot') % Stampa qualcosa in questa posizione + + +% Per usare funzioni o script, devono essere nel tuo path o nella directory corrente +path % Mostra il path corrente +addpath /path/to/dir % Aggiunge al path +rmpath /path/to/dir % Rimuove dal path +cd /path/to/move/into % Cambia directory + + +% Le variabili possono essere salvate in file .mat +save('myFileName.mat') % Salva le variabili nel tuo Workspace +load('myFileName.mat') % Carica variabili salvate nel tuo Workspace + +% M-file Scripts +% I file di script sono file esterni che contengono una sequenza di istruzioni. +% Permettono di evitare di scrivere ripetutamente lo stesso codice nella Command Window +% Hanno estensione .m + +% M-file Functions +% Come gli script, hanno la stessa estensione .m +% Ma possono accettare argomenti di input e restituire un output. +% Inoltre, hanno un proprio workspace (differente scope delle variabili). +% Il nome della funzione dovrebbe coincidere con il nome del file (quindi salva questo esempio come double_input.m). +% 'help double_input.m' restituisce i commenti sotto alla linea iniziale della funzione +function output = double_input(x) + %double_input(x) restituisce il doppio del valore di x + output = 2*x; +end +double_input(6) % ans = 12 + + +% Si possono anche avere sottofunzioni e funzioni annidate. +% Le sottofunzioni sono nello stesso file della funzione primaria, e possono solo essere +% chiamate da funzioni nello stesso file. Le funzioni annidate sono definite dentro ad altre +% funzioni, e hanno accesso ad entrambi i workspace. + +% Se si vuole creare una funzione senza creare un nuovo file si può usare una +% funzione anonima. Utile quando si vuole definire rapidamente una funzione da passare ad +% un'altra funzione (es. stampa con fplot, valutare un integrale indefinito +% con quad, trovare le radici con fzenzro, o trovare il minimo con fminsearch). +% Esempio che restituisce il quadrato del proprio input, assegnato all'handle sqr: +sqr = @(x) x.^2; +sqr(10) % ans = 100 +doc function_handle % scopri di più + +% Input dell'utente +a = input('Enter the value: ') + +% Ferma l'esecuzione del file e cede il controllo alla tastiera: l'utente può esaminare +% o cambiare variabili. Digita 'return' per continuare l'esecuzione, o 'dbquit' per uscire +keyboard + +% Importarare dati (anche xlsread/importdata/imread per excel/CSV/image file) +fopen(filename) + +% Output +disp(a) % Stampa il valore della variabile a +disp('Hello World') % Stampa una stringa +fprintf % Stampa sulla Command Window con più controllo + +% Istruzioni condizionali (le parentesi sono opzionali, ma un buon stile) +if (a > 15) + disp('Maggiore di 15') +elseif (a == 23) + disp('a è 23') +else + disp('nessuna condizione verificata') +end + +% Cicli +% NB. Ciclare su elementi di vettori/matrici è lento! +% Dove possibile, usa funzioni che agiscono sull'intero vettore/matrice +for k = 1:5 + disp(k) +end + +k = 0; +while (k < 5) + k = k + 1; +end + +% Misurare la durata dell'esecuzione del codice: 'toc' stampa il tempo trascorso da quando 'tic' è stato chiamato +tic +A = rand(1000); +A*A*A*A*A*A*A; +toc + +% Connessione a un Database 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 dipende dalla versione, download disponibile all'indirizzo http://dev.mysql.com/downloads/connector/j/ +conn = database(dbname, username, password, driver, dburl); +sql = ['SELECT * from table_name where id = 22'] % Esempio istruzione sql +a = fetch(conn, sql) % conterra i tuoi dati + + +% Funzioni matematiche comuni +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 % Numeri pseudocasuali uniformemente distribuiti +randi % Numeri interi pseudocasuali uniformemente distrubuiti +randn % Numeri pseudocasuali distrbuiti normalmente + +% Costanti comuni +pi +NaN +inf + +% Risolvere equazioni matriciali +% Gli operatori \ e / sono equivalenti alle funzioni mldivide e mrdivide +x=A\b % Risolve Ax=b. Più veloce e più accurato numericamente rispetto ad usare inv(A)*b. +x=b/A % Risolve xA=b + +inv(A) % Calcola la matrice inversa +pinv(A) % Calcola la matrice pseudo-inversa + +% Funzioni comuni su matrici +zeros(m,n) % Matrice m x n di zeri +ones(m,n) % Matrice m x n di uni +diag(A) % Estrae gli elementi della diagonale della matrice A +diag(x) % Costruisce una matrice con elementi diagonali uguali agli elementi di x, e zero negli altri elementi +eye(m,n) % Matrice identità +linspace(x1, x2, n) % Ritorna n punti equamente distanziati, con minimo x1 e massimo x2 +inv(A) % Matrice inversa di A +det(A) % Determinante di A +eig(A) % Autovalori e autovettori di A +trace(A) % Traccia della matrice - equivalente a sum(diag(A)) +isempty(A) % Verifica se l'array è vuoto +all(A) % Verifica se tutti gli elementi sono nonzero o veri +any(A) % Verifica se almento un elemento è nonzero o vero +isequal(A, B) % Verifica l'uguaglianza di due array +numel(A) % Numero di elementi nella matrice +triu(x) % Ritorna la parte triangolare superiore di x +tril(x) % Ritorna la parte triangolare inferiore di x +cross(A,B) % Ritorna il prodotto vettoriale dei vettori A e B +dot(A,B) % Ritorna il prodotto scalare di due vettori (devono avere la stessa lunghezza) +transpose(A) % Ritorna la trasposta di A +fliplr(A) % Capovolge la matrice da sinistra a destra +flipud(A) % Capovolge la matrice da sopra a sotto + +% Fattorizzazione delle matrici +[L, U, P] = lu(A) % Decomposizione LU: PA = LU, L è il triangolo inferiore, U è il triangolo superiore, P è la matrice di permutazione +[P, D] = eig(A) % Auto-decomposizione: AP = PD, le colonne di P sono autovettori e gli elementi sulle diagonali di D sono autovalori +[U,S,V] = svd(X) % SVD: XV = US, U e V sono matrici unitarie, S ha gli elementi della diagonale non negativi in ordine decrescente + +% Funzioni comuni su vettori +max % elemento più grande +min % elemento più piccolo +length % lunghezza del vettore +sort % ordina in modo crescente +sum % somma degli elementi +prod % prodotto degli elementi +mode % valore moda +median % valore mediano +mean % valore medio +std % deviazione standard +perms(x) % lista tutte le permutazioni di elementi di x + + +% Classi +% Matlab supporta la programmazione orientata agli oggetti. +% La classe deve essere messa in un file con lo stesso nome della classe e estensione .m +% Per iniziare, creiamo una semplice classe per memorizzare waypoint GPS +% Inizio WaypointClass.m +classdef WaypointClass % Il nome della classe. + properties % Le proprietà della classe funzionano come Strutture + latitude + longitude + end + methods + % Questo metodo che ha lo stesso nome della classe è il costruttore + function obj = WaypointClass(lat, lon) + obj.latitude = lat; + obj.longitude = lon; + end + + % Altre funzioni che usano l'oggetto Waypoint + function r = multiplyLatBy(obj, n) + r = n*[obj.latitude]; + end + + % Se si vuole aggiungere due oggetti Waypoint insieme senza chiamare + % una funzione speciale si può sovradefinire una funzione aritmetica di Matlab come questa: + function r = plus(o1,o2) + r = WaypointClass([o1.latitude] +[o2.latitude], ... + [o1.longitude]+[o2.longitude]); + end + end +end +% End WaypointClass.m + +% Si può creare un oggetto della classe usando un costruttore +a = WaypointClass(45.0, 45.0) + +% Le proprietà della classe si comportano esattamente come una Struttura Matlab. +a.latitude = 70.0 +a.longitude = 25.0 + +% I metodi possono essere chiamati allo stesso modo delle funzioni +ans = multiplyLatBy(a,3) + +% Il metodo può anche essere chiamato usando una notazione con punto. In questo caso, l'oggetto +% non necessita di essere passato al metodo. +ans = a.multiplyLatBy(a,1/3) + +% Le funzioni Matlab possono essere sovradefinite per gestire oggetti. +% Nel metodo sopra, è stato sovradefinito come Matlab gestisce +% l'addizione di due oggetti Waypoint. +b = WaypointClass(15.0, 32.0) +c = a + b + +``` + +## Di più su Matlab + +* Sito ufficiale [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) +* Forum ufficiale di MATLAB: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) -- cgit v1.2.3 From 9b51e703c57c77bfe29c390d9d1dbe398e1ce5b8 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 15:30:19 +0200 Subject: Update matlab-it.html.markdown --- it-it/matlab-it.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/it-it/matlab-it.html.markdown b/it-it/matlab-it.html.markdown index b1e8777b..aeb42658 100644 --- a/it-it/matlab-it.html.markdown +++ b/it-it/matlab-it.html.markdown @@ -7,6 +7,7 @@ contributors: translators: - ["Samuele Gallerani", "http://github.com/fontealpina"] lang: it-it +filename: matlab-it.md --- MATLAB sta per MATrix LABoratory ed è un potente linguaggio per il calcolo numerico comunemente usato in ingegneria e matematica. -- cgit v1.2.3 From 13bddecbe44f424436f5c9c838c5c9c633b6c5b4 Mon Sep 17 00:00:00 2001 From: Rodrigo Muniz Date: Sun, 26 Jun 2016 10:31:09 -0300 Subject: =?UTF-8?q?Tradu=C3=A7=C3=A3o=20do=20Elixir=20para=20pt=5Fbr=20(#1?= =?UTF-8?q?421)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pt-br/elixir.html.markdown | 411 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 411 insertions(+) create mode 100644 pt-br/elixir.html.markdown diff --git a/pt-br/elixir.html.markdown b/pt-br/elixir.html.markdown new file mode 100644 index 00000000..55a8df86 --- /dev/null +++ b/pt-br/elixir.html.markdown @@ -0,0 +1,411 @@ +--- +language: elixir +contributors: + - ["Joao Marques", "http://github.com/mrshankly"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] +translators: + - ["Rodrigo Muniz", "http://github.com/muniz95"] +filename: learnelixir.ex +--- + +Elixir é uma linguagem funcional moderna construída no topo da Erlang VM. +É totalmente compatível com Erlang, porém conta com uma sintaxe mais padronizada +e muitos outros recursos. + +```elixir + +# Comentários de linha única começam com um símbolo de número. + +# 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`. +# Compile seus módulos com o comando `elixirc`. + +# Ambos devem estar em seu path se você instalou o Elixir corretamente. + +## --------------------------- +## -- Tipos Básicos +## --------------------------- + +# Há números +3 # integer +0x1F # integer +3.0 # float + +# Atoms, que são literais, uma constante com nome. Elas começam com `:`. +:hello # atom + +# Tuplas que são guardadas contiguamente em memória. +{1,2,3} # tupla + +# Podemos acessar um elemento de uma tupla om a função `elem`: +elem({1, 2, 3}, 0) #=> 1 + +# Listas que são implementadas como listas ligadas. +[1,2,3] # lista + +# Podemos acessar a primeira posição (head) e o resto (tail) de uma lista como a seguir: +[head | tail] = [1,2,3] +head #=> 1 +tail #=> [2,3] + +# 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 +# estiver à direita. +# +# É assim que o exemplo acima de acesso à head e tail de uma lista funciona. + +# Um pattern match retornará erro quando os lados não conferem, como neste exemplo +# onde as tuplas tem diferentes tamanhos. +# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} + +# Também há binários +<<1,2,3>> # binary + +# Strings e char lists +"hello" # string +'hello' # char list + +# Strings de múltiplas linhas +""" +Strings +de múltiplas +linhas. +""" +#=> "Strings\nde múltiplas\nlinhas" + +# Strings são sempre codificadas em UTF-8: +"héllò" #=> "héllò" + +# Strings são de fato apenas binários, e char lists apenas listas. +<> #=> "abc" +[?a, ?b, ?c] #=> 'abc' + +# `?a` em elixir retorna o valor ASCII para a letra `a` +?a #=> 97 + +# Para concatenar listas use `++`, para binários use `<>` +[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" + +# Ranges são representados como `início..fim` (ambos inclusivos) +1..10 #=> 1..10 +menor..maior = 1..10 # Pattern matching pode ser usada em ranges também +[lower, upper] #=> [1, 10] + +## --------------------------- +## -- Operadores +## --------------------------- + +# Matemática básica +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 + +# Em elixir o operador `/` sempre retorna um float. + +# Para divisão de inteiros use `div` +div(10, 2) #=> 5 + +# Para obter o resto da divisão use `rem` +rem(10, 3) #=> 1 + +# Há também operadores booleanos: `or`, `and` e `not`. +# Estes operadores esperam um booleano como primeiro argumento. +true and true #=> true +false or true #=> true +# 1 and true #=> ** (ArgumentError) argument error + +# Elixir também fornece `||`, `&&` e `!` que aceitam argumentos de qualquer tipo. +# Todos os valores exceto `false` e `nil` serão avaliados como true. +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil +!true #=> false + +# Para comparações temos: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` e `>` +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true + +# `===` e `!==` são mais estritos ao comparar integers e floats: +1 == 1.0 #=> true +1 === 1.0 #=> false + +# Podemos comparar também dois tipos de dados diferentes: +1 < :hello #=> true + +# A regra de ordenação no geral é definida abaixo: +# number < atom < reference < functions < port < pid < tuple < list < bit string + +# Ao citar Joe Armstrong nisto: "A ordem de fato não é importante, +# mas que uma ordem total esteja bem definida é importante." + +## --------------------------- +## -- Fluxo de Controle +## --------------------------- + +# expressão `if` +if false do + "Isso nunca será visto" +else + "Isso será" +end + +# Também há `unless` +unless true do + "Isso nunca será visto" +else + "Isso será" +end + +# Lembra do patter 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 + {:quatro, :cinco} -> + "Isso não corresponde" + {:um, x} -> + "Isso corresponde e vincula `x` a `:dois`" + _ -> + "Isso corresponde a qualquer valor" +end + +# É comum vincular o valor a `_` se não precisamos dele. +# Por exemplo, se apenas a head de uma lista nos interessa: +[head | _] = [1,2,3] +head #=> 1 + +# Para melhor legibilidade podemos fazer o seguinte: +[head | _tail] = [:a, :b, :c] +head #=> :a + +# `cond` nos permite verificar várias condições ao mesmo tempo. +# Use `cond` em vez de aninhar vários `if`'s. +cond do + 1 + 1 == 3 -> + "Nunca serei visto" + 2 * 5 == 12 -> + "Nem eu" + 1 + 2 == 3 -> + "Mas eu serei" +end + +# É comum definir a última condição igual a `true`, que sempre irá corresponder. +cond do + 1 + 1 == 3 -> + "Nunca serei visto" + 2 * 5 == 12 -> + "Nem eu" + true -> + "Mas eu serei (isso é essencialmente um else)" +end + +# `try/catch` é usado para capturar valores que são lançados, também suporta uma +# cláusula `after` que é invocada havendo um valor capturado ou não. +try do + throw(:hello) +catch + message -> "Deu #{mensagem}." +after + IO.puts("Sou o after.") +end +#=> Sou o after +# "Deu :hello" + +## --------------------------- +## -- Módulos e Funções +## --------------------------- + +# Funções Anônimas (repare o ponto) +square = fn(x) -> x * x end +square.(5) #=> 25 + +# Elas também aceitam várias cláusulas e guards. +# Guards permitem ajustes finos de pattern matching, +# sendo indicados pela palavra `when`: +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# Elixir também fornece várias funções embutidas. +# Estas estão disponíveis no escopo atual. +is_number(10) #=> true +is_list("ola") #=> false +elem({1,2,3}, 0) #=> 1 + +# Você pode agrupar algumas funções em um módulo. Dentro de um módulo use `def` +# para definir suas funções. +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 + +# Para compilar o módulo Math salve-o como `math.ex` e use `elixirc` +# em seu terminal: elixirc math.ex + +# Dentro de um módulo podemos definir funções com `def` e funções privadas com `defp`. +# Uma função definida com `def` pode ser invocada por outros módulos, +# já uma função privada pode ser invocada apenas localmente. +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) + +# Declarações de funções também suportam guards cláusulas múltiplas: +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 + +# Devido à imutabilidade, recursão é uma grande parte do 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 + +# Módulos do elixir suportam atributos, hpa atributos embutidos e você +# pode também adicionar os seus próprios. +defmodule MyMod do + @moduledoc """ + Este é um atributo embutido em um módulo de exemplo. + """ + + @my_data 100 # Este é um atributo customizado. + IO.inspect(@my_data) #=> 100 +end + +## --------------------------- +## -- Structs e Exceptions +## --------------------------- + +# Structs são extensões no topo de mapas que trazem valores padrão, +# garantias em tempo de compilação e polimorfismo para o Elixir. +defmodule Pessoa do + defstruct nome: nil, idade: 0, peso: 0 +end + +joe_info = %Pessoa{ nome: "Joe", idade: 30, peso: 180 } +#=> %Pessoa{idade: 30, peso: 180, nome: "Joe"} + +# Acessa o valor de nome +joe_info.name #=> "Joe" + +# Atualiza o valor de idade +older_joe_info = %{ joe_info | idade: 31 } +#=> %Pessoa{idade: 31, peso: 180, nome: "Joe"} + +# O bloco `try` com a palavra `rescue` é usado para manipular exceções +try do + raise "algum erro" +rescue + RuntimeError -> "resgatado um erro em tempo de execução" + _error -> "isso resgatará qualquer erro" +end + +# Toda exceção possui uma mensagem +try do + raise "algum erro" +rescue + x in [RuntimeError] -> + x.message +end + +## --------------------------- +## -- Concorrência +## --------------------------- + +# 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, +# sending messages e receiving messages. + +# Para iniciar um novo processo usamos a função `spawn`, a qual leva uma função +# como argumento. +f = fn -> 2 * 2 end #=> #Function +spawn(f) #=> #PID<0.40.0> + +# `spawn` retorna um pid (process identifier), você pode usar esse pid para enviar +# mensagens ao processo. Para envio de mensagens usamos o operador `send`. +# Para tudo isso ser útil precisamos estar aptos a receber mensagens. Isto é +# realizado com o mecanismo `receive`: +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 + +# Compile o módulo e crie um processo que avalie `area_loop` no shell +pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> + +# Envia uma mensagem ao `pid` correspondente a um pattern na declaração de recebimento +send pid, {:rectangle, 2, 3} +#=> Area = 6 +# {:rectangle,2,3} + +send pid, {:circle, 2} +#=> Area = 12.56000000000000049738 +# {:circle,2} + +# O shell também é um processo, você pode usar `self` para obter o pid atual +self() #=> #PID<0.27.0> +``` + +## Referências + +* [Getting started guide](http://elixir-lang.org/getting_started/1.html) da [página do elixir](http://elixir-lang.org) +* [Elixir Documentation](http://elixir-lang.org/docs/master/) +* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) por Dave Thomas +* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) +* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) por Fred Hebert +* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) por Joe Armstrong -- cgit v1.2.3 From 0827434afa6e0f9ac7371a7b51a6a055a794aaf3 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 15:31:27 +0200 Subject: #1421 --- pt-br/elixir.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/elixir.html.markdown b/pt-br/elixir.html.markdown index 55a8df86..b4ca8a52 100644 --- a/pt-br/elixir.html.markdown +++ b/pt-br/elixir.html.markdown @@ -5,7 +5,7 @@ contributors: - ["Dzianis Dashkevich", "https://github.com/dskecse"] translators: - ["Rodrigo Muniz", "http://github.com/muniz95"] -filename: learnelixir.ex +filename: learnelixir-pt.ex --- Elixir é uma linguagem funcional moderna construída no topo da Erlang VM. -- cgit v1.2.3 From 6419fa49074df3b24e8225f457cb462aededcc01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juraj=20Kostolansk=C3=BD?= Date: Sun, 26 Jun 2016 15:32:29 +0200 Subject: [bash/sk] Slovak translation for Bash (#1517) --- sk-sk/bash.html.markdown | 286 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 286 insertions(+) create mode 100644 sk-sk/bash.html.markdown diff --git a/sk-sk/bash.html.markdown b/sk-sk/bash.html.markdown new file mode 100644 index 00000000..ba67b699 --- /dev/null +++ b/sk-sk/bash.html.markdown @@ -0,0 +1,286 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] +translators: + - ["Juraj Kostolanský", "http://www.kostolansky.sk"] +lang: sk-sk +filename: LearnBash.sh +--- + +Bash je pomenovanie pre unix shell (príkazový interpreter), ktorý bol +tiež distribuovaný ako shell pre GNU operačné systémy a ako predvolený +shell pre Linux a Mac OS X. +Takmer všetky príklady uvedené nižšie môžu byť súčasťou shell skriptu alebo +vykonané priamo v shelli. + +[Viac informácií tu.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# Prvý riadok skriptu je tzv. shebang, ktorý systému povie ako skript vykonať: +# http://en.wikipedia.org/wiki/Shebang_(Unix) +# Komentáre začínajú znakom #. Shebang je tiež komentár. + +# Jednoduchý príklad: +echo Ahoj svet! + +# Každý príkaz začína na novom riadku alebo za bodkočiarkou: +echo 'Toto je prvý riadok'; echo 'Toto je druhý riadok' + +# Deklarácia premenných vyzerá takto: +Premenna="Nejaky retazec" + +# Ale nie takto: +Premenna = "Nejaky retazec" +# Bash si bude myslieť, že Premenna je príkaz, ktorý musí vykonať. +# Výsledkom bude chyba, pretože taký príkaz nenájde. + +# Alebo takto: +Premenna= 'Nejaky retazec' +# Bash zistí, že 'Nejaky retazec' je príkaz, ktorý musí vykonať. +# Výsledkom je opäť chyba, lebo taký príkaz neexistuje. + +# Používanie premenných: +echo $Premenna +echo "$Premenna" +echo '$Premenna' +# Keď je premenná použitá samostatne - priradenie, exportovanie a pod. - jej +# meno sa píše bez znaku $. Keď sa používa hodnota premennej, pred názov sa +# dáva znak $. Pozor však pri použití ' (apostrof), ktorý nenahradí premennú +# hodnotou! + +# Nahradenie reťazca v premennej +echo ${Premenna/Nieco/A} +# Toto nahradí prvý výskyt reťazca "Nieco" za "A" + +# Podreťazec z premennej +Dlzka=7 +echo ${Premenna:0:Dlzka} +# Toto vráti iba prvých 7 znakov z hodnoty premennej + +# Predvolená hodnota premennej +echo ${Foo:-"PredvolenaHodnotaAkFooChybaAleboJePrazdna"} +# Toto funguje pre null (Foo=) a prázdny reťazec (Foo=""); +# nula (Foo=0) vráti 0. Všimni si, že toto iba vráti predvolenú hodnotu, +# ale nezmení hodnotu premennej. + +# Štandardné premenné: +# Existujú aj užitočné "vstavané" premenné, ako +echo "Hodnota vrátená posledným programom: $?" +echo "PID skriptu: $$" +echo "Počet argumentov: $#" +echo "Argumeny skriptu: $@" +echo "Argumeny skriptu oddelené do rôznych premenných: $1 $2..." + +# Čítanie hodnoty zo vstupu: +echo "Ako sa voláš?" +read Meno # Premenná nemusí byť deklarovaná skôr +echo Ahoj, $Meno! + +# Klasická if štruktúra: +# použi 'man test' Pre viac informácií o podmienkach +if [ $Meno -ne $USER ] +then + echo "Meno nie je tvoje používateľské meno" +else + echo "Meno je tvoje používateľské meno" +fi + +# Existuje aj podmienené vykonanie +echo "Vykonané vždy" || echo "Vykonané iba ak prvý príkaz zlyhá" +echo "Vykonané vždy" && echo "Vykonané iba ak prvý príkaz uspeje" + +# Pre použitie && a || s if-podmienkou je potrebné použiť zátvorky: +if [ $Meno == "Steve" ] && [ $Vek -eq 15 ] +then + echo "Toto sa spustí ak $Meno je Steve a $Vek je 15." +fi + +if [ $Meno == "Daniya" ] || [ $Meno == "Zach" ] +then + echo "Toto sa spustí ak $Meno je Daniya alebo Zach." +fi + +# Pre výrazy sa používa nasledovný formát: +echo $(( 10 + 5 )) + +# Na rozdiel od programovacích jazykov shell pracuje v kontexte aktuálneho +# adresára. Môžeš si prehliadať súbory a adresáre v aktuálnom adresári pomocou +# príkazu ls: +ls + +# Tieto príkazy majú aj argumenty pre úpravu ich správania: +ls -l # Vypíše zoznam súborov a priečinkov, každý na samostatnom riadku + +# Výsledok predchádzajúceho príkazu môže byť využitý priamo ako vstup pre +# ďalší príkaz. +# Príkaz grep filtruje vstupvyužitím poskytnutého vzoru. Takto môžeme vypísať +# iba .txt súbory: +ls -l | grep "\.txt" + +# Vstup a výstup príkazu (stdin, stdout, stderr) môžu byť presmerované. +# Toto číta stdin až po ^EOF$ a prepíše hello.py riadkami medzi "EOF": +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ import print_function +import sys +print("#stdout", file=sys.stdout) +print("#stderr", file=sys.stderr) +for line in sys.stdin: + print(line, file=sys.stdout) +EOF + +# Spustí hello.py s rôznymi presmerovaniami pre stdin, stdout a stderr: +python hello.py < "vstup.in" +python hello.py > "vystup.out" +python hello.py 2> "chyby.err" +python hello.py > "vystup-a-chyby.log" 2>&1 +python hello.py > /dev/null 2>&1 +# Chybový výstup prepíše uvedený súbor, ak už existuje. +# Ak chceš výstup pridať za existujúci obsah, použi ">>": +python hello.py >> "vystup.out" 2>> "chyby.err" + +# Prepíše vystup.out, pripojí k chyby.err a spočíta riadky: +info bash 'Basic Shell Features' 'Redirections' > vystup.out 2>> chyby.err +wc -l vystup.out chyby.err + +# Spustí príkaz a vypíše deskriptor súboru (napr. /dev/fd/123) +# pozri: man fd +echo <(echo "#ahojsvet") + +# Prepíše vystup.out s "#ahojsvet": +cat > vystup.out <(echo "#ahojsvet") +echo "#ahojsvet" > vystup.out +echo "#ahojsvet" | cat > vystup.out +echo "#ahojsvet" | tee vystup.out >/dev/null + +# Potichu odstráni dočasné súbory (pridaj '-i' pre interaktivitu) +rm -v vystup.out chyby.err vystup-a-chyby.log + +# Príkazy môžu byť nahradené v iných príkazoch použitím $( ): +# Nasledujúci príkaz vypíše počet súborov a adresárov v aktuálnom adresári +echo "Je tu $(ls | wc -l) súborov a priečinkov." + +# To isté sa dá spraviť pomocou spätného apostrofu ``, tie však nemôžu byť +# vhniezdené - preferovaný spôsob je preto $( ). +echo "Je tu `ls | wc -l` súborov a priečinkov." + +# Bash používa case, ktorý funguje podobne ako switch v Jave a C++: +case "$Premenna" in + #Zoznam vzorov pre podmienky + 0) echo "Je to nula.";; + 1) echo "Je to jednotka.";; + *) echo "Nie je to null.";; +esac + +# for-cyklus iteruje cez všetky argumenty: +# Obsah premennej $Premenna sa vypíše trikrát. +for Premenna in {1..3} +do + echo "$Premenna" +done + +# Alebo "tradičným" spôsobom: +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Môžu sa použiť aj na súbory.. +# Toto spustí príkaz 'cat' na subor1 a subor2 +for Premenna in subor1 subor2 +do + cat "$Premenna" +done + +# ..alebo na výstup príkazu. +# Toto použije príkaz cat na výstup z ls. +for Vystup in $(ls) +do + cat "$Vystup" +done + +# while-cykklus: +while [ true ] +do + echo "telo cyklu..." + break +done + +# Môžeš tiež definovať funkice +# Definícia: +function foo () +{ + echo "Argumenty fungujú rovnako ako pri skriptoch: $@" + echo "A: $1 $2..." + echo "Toto je funkcia" + return 0 +} + +# alebo jednoducho +bar () +{ + echo "Iný spôsob definície funkcií" + return 0 +} + +# Volanie funkcie +foo "Moje meno je" $Meno + +# Existuje veľa užitočných príkazov, ktoré sa oplatí naučiť: +# vypíše posledných 10 riadkov zo subor.txt +tail -n 10 subor.txt +# vypíše prvých 10 riadkov zo subor.txt +head -n 10 subor.txt +# zotriedi riadky zo subor.txt +sort subor.txt +# vypíše alebo vynechá opakované riadky, použitím -d ich vypíše +uniq -d subor.txt +# vypíše iba prvý stĺpecpred znakom ',' +cut -d ',' -f 1 subor.txt +# nahradí každý výskyt 'oukej' za 'super' v subor.txt (možnosť použiť regex) +sed -i 's/oukej/super/g' subor.txt +# vypíše všetky riadky zo subor.txt ktoré vyhovujú regexu +# ukážka vypíše riadky ktoré začínajú s "foo" a končia s "bar" +grep "^foo.*bar$" subor.txt +# pre výpis počtu riadkov vyhovujúcich regexu slúži "-c" +grep -c "^foo.*bar$" subor.txt +# pre vyhľadávanie reťazca bez regexu slúži fgrep (alebo grep -F) +fgrep "^foo.*bar$" subor.txt + + +# Prečítaj si dokumentáciu k Bash shellu použitím príkazu 'help': +help +help help +help for +help return +help source +help . + +# Prečítaj si Bash manpage dokumentáciu príkazom 'man' +apropos bash +man 1 bash +man bash + +# Prečítaj si info dokumentáciu pomocou 'info' (? pre help) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# Prečítaj si bash info dokumentáciu: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` -- cgit v1.2.3 From 095d2e2405ced6a6e42b5f270d44a6ec6e9e3cb4 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 15:32:45 +0200 Subject: #1517 --- sk-sk/bash.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sk-sk/bash.html.markdown b/sk-sk/bash.html.markdown index ba67b699..e9d1490c 100644 --- a/sk-sk/bash.html.markdown +++ b/sk-sk/bash.html.markdown @@ -14,7 +14,7 @@ contributors: translators: - ["Juraj Kostolanský", "http://www.kostolansky.sk"] lang: sk-sk -filename: LearnBash.sh +filename: LearnBash-sk.sh --- Bash je pomenovanie pre unix shell (príkazový interpreter), ktorý bol -- cgit v1.2.3 From be12f2009759514fdcf6bfc70cc62f4cc60c651b Mon Sep 17 00:00:00 2001 From: Martin Damien Date: Sun, 26 Jun 2016 15:34:16 +0200 Subject: [en/RST] Add RST introduction (#1723) * [en/RST] Add RST introduction * Fix @ in username --- rst.html.markdown | 107 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 rst.html.markdown diff --git a/rst.html.markdown b/rst.html.markdown new file mode 100644 index 00000000..161a0610 --- /dev/null +++ b/rst.html.markdown @@ -0,0 +1,107 @@ +--- +language: restructured text +contributors: + - ["DamienVGN", "https://github.com/martin-damien"] +filename: restructuredtext.rst +--- + +RST is file format formely created by Python community to write documentation (and so, is part of Docutils). + +RST files are simple text files with lightweight syntaxe (comparing to HTML). + + +## Installation + +To use Restructured Text, you will have to install [Python](http://www.python.org) and the `docutils` package. + +`docutils` can be installed using the commandline: + +```bash +$ easy_install docutils +``` + +If your system have `pip`, you can use it too: + +```bash +$ pip install docutils +``` + + +## File syntaxe + +A simple example of the file syntax: + +```rst +.. Line with two dotes are special commands. But if no command can be found, the line is considered as a comment + +========================================================= +Main titles are written using equals signs over and under +========================================================= + +Note that theire must be as many equals signs as title characters. + +Title are underlined with equals signs too +========================================== + +Subtitles with dashes +--------------------- + +And sub-subtitles with tilde +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can put text in *italic* or in **bold**, you can "mark" text as code with double backquote ``: ``print()``. + +Lists are as simple as markdown: + +- First item +- Second item + - Sub item + +or + +* First item +* Second item + * Sub item + +Tables are really easy to write: + +=========== ======== +Country Capital +=========== ======== +France Paris +Japan Tokyo +=========== ======== + +More complexe tabless can be done easily (merged columns and/or rows) but I suggest you to read the complete doc for this :) + +Their is multiple ways to make links: + +- By adding an underscore after a word : Github_ and by adding the target after the text (this have the advantage to not insert un-necessary URL inside the readed text). +- By typing a full comprehensible URL : https://github.com/ (will be automatically converted in link) +- By making a more "markdown" link: `Github `_ . + +.. _Github https://github.com/ + +``` + + +## How to use it + +RST comes with docutils in which you have `rst2html` for exemple: + +```bash +$ rst2html myfile.rst output.html +``` + +*Note : On some systems the command could be rst2html.py* + +But their is more complexe applications that uses RST file format: + +- [Pelican](http://blog.getpelican.com/), a static site generator +- [Sphinx](http://sphinx-doc.org/), a documentation generator +- and many others + + +## Readings + +- [Official quick reference](http://docutils.sourceforge.net/docs/user/rst/quickref.html) -- cgit v1.2.3 From 6b3f99a4131665670c58a2ad5ab90254f365f83c Mon Sep 17 00:00:00 2001 From: Tommaso Date: Sun, 26 Jun 2016 15:35:10 +0200 Subject: [go/it] Add first italian translation of go language (#1630) --- it-it/go-it.html.markdown | 454 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 454 insertions(+) create mode 100644 it-it/go-it.html.markdown diff --git a/it-it/go-it.html.markdown b/it-it/go-it.html.markdown new file mode 100644 index 00000000..3f17fe1f --- /dev/null +++ b/it-it/go-it.html.markdown @@ -0,0 +1,454 @@ +--- +name: Go +category: language +language: Go +filename: learngo-it.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] + - ["Christopher Bess", "https://github.com/cbess"] + - ["Jesse Johnson", "https://github.com/holocronweaver"] + - ["Quint Guvernator", "https://github.com/qguv"] + - ["Jose Donizetti", "https://github.com/josedonizetti"] + - ["Alexej Friesen", "https://github.com/heyalexej"] + - ["Clayton Walker", "https://github.com/cwalk"] +translators: + - ["Tommaso Pifferi","http://github.com/neslinesli93"] +lang: it-it +--- + +Go è stato creato per avere tra le mani uno strumento in grado di arrivare +al punto, nel modo più veloce ed efficiente possibile. Non è all'ultima +moda tra i linguaggi di programmazione, ma è una delle migliori soluzioni +per risolvere in maniera efficace i problemi di tutti i giorni. + +Go presenta alcuni concetti già presenti nei linguaggi imperativi con +tipizzazione statica. Compila velocemente ed esegue altrettanto veloce. +Aggiunge la concorrenza in maniera diretta e semplice da capire, per far +forza sulle CPU multi-core di oggigiorno. Presenta caratteristiche utili +per la programmazione in larga scala. + +Go comes with a great standard library and an enthusiastic community. + +```go +// Commento su riga singola +/* Commento + su riga multipla */ + +// In cima a ogni file è necessario specificare il package. +// Main è un package speciale che identifica un eseguibile anziché una libreria. +package main + +// Con import sono dichiarate tutte le librerie a cui si fa riferimento +// all'interno del file. +import ( + "fmt" // Un package nella libreria standard di Go. + "io/ioutil" // Implementa alcune funzioni di utility per l'I/O. + m "math" // Libreria matematica, con alias locale m + "net/http" // Sì, un web server! + "strconv" // Package per la conversione di stringhe. +) + +// Una definizione di funzione. Il main è speciale: è il punto di ingresso +// per il programma. Amalo o odialo, ma Go usa le parentesi graffe. +func main() { + // Println stampa una riga a schermo. + // Questa funzione è all'interno del package fmt. + fmt.Println("Ciao mondo!") + + // Chiama un'altra funzione all'interno di questo package. + oltreIlCiaoMondo() +} + +// Le funzioni ricevono i parametri all'interno di parentesi tonde. +// Se la funzione non riceve parametri, vanno comunque messe le parentesi (vuote). +func oltreIlCiaoMondo() { + var x int // Dichiarazione di una variabile. Ricordati di dichiarare sempre le variabili prima di usarle! + x = 3 // Assegnazione di una variabile. + // E' possibile la dichiarazione "rapida" := per inferire il tipo, dichiarare e assegnare contemporaneamente. + y := 4 + // Una funzione che ritorna due valori. + somma, prod := imparaMoltepliciValoriDiRitorno(x, y) + fmt.Println("somma:", somma, "prodotto:", prod) // Semplice output. + imparaTipi() // < y minuti, devi imparare ancora! +} + +/* <- commento su righe multiple +Le funzioni possono avere parametri e ritornare (molteplici!) valori. +Qua, x e y sono gli argomenti, mentre somma e prod sono i valori ritornati. +Da notare il fatto che x e somma vengono dichiarati come interi. +*/ +func imparaMoltepliciValoriDiRitorno(x, y int) (somma, prod int) { + return x + y, x * y // Ritorna due valori. +} + +// Ecco alcuni tipi presenti in Go +func imparaTipi() { + // La dichiarazione rapida di solito fa il suo lavoro. + str := "Impara il Go!" // Tipo stringa. + + s2 := `Una stringa letterale +puo' includere andata a capo.` // Sempre di tipo stringa. + + // Stringa letterale non ASCII. I sorgenti Go sono in UTF-8. + g := 'Σ' // Il tipo runa, alias per int32, è costituito da un code point unicode. + + f := 3.14195 // float64, un numero in virgola mobile a 64-bit (IEEE-754) + + c := 3 + 4i // complex128, rappresentato internamente con due float64. + + // Inizializzare le variabili con var. + var u uint = 7 // Senza segno, ma la dimensione dipende dall'implementazione (come l'int) + var pi float32 = 22. / 7 + + // Sintassi per la conversione. + n := byte('\n') // Il tipo byte è un alias per uint8. + + // I vettori hanno dimensione fissa, stabilita durante la compilazione. + var a4 [4]int // Un vettore di 4 interi, tutti inizializzati a 0. + a3 := [...]int{3, 1, 5} // Un vettore inizializzato con una dimensione fissa pari a 3, i cui elementi sono 3, 1 e 5. + + // Gli slice hanno dimensione variabile. Vettori e slice hanno pro e contro, + // ma generalmente si tende a usare più spesso gli slice. + s3 := []int{4, 5, 9} // La differenza con a3 è che qua non ci sono i 3 punti all'interno delle parentesi quadre. + s4 := make([]int, 4) // Alloca uno slice di 4 interi, tutti inizializzati a 0. + var d2 [][]float64 // Semplice dichiarazione, non vengono fatte allocazioni. + bs := []byte("uno slice") // Sintassi per la conversione. + + // Poiché gli slice sono dinamici, è possibile aggiungere elementi + // quando è necessario. Per farlo, si usa la funzione append(). Il primo + // argomento è lo slice a cui stiamo aggiungendo elementi. Di solito + // lo slice viene aggiornato, senza fare una copia, come nell'esempio: + s := []int{1, 2, 3} // Il risultato è uno slice di dimensione 3. + s = append(s, 4, 5, 6) // Aggiunge 3 elementi: lo slice ha dimensione 6. + fmt.Println(s) // Lo slice aggiornato è [1 2 3 4 5 6] + // Per aggiungere un altro slice, invece che elencare gli elementi uno ad + // uno, è possibile passare alla funzione append un riferimento ad uno + // slice, oppure uno slice letterale: in questo caso si usano i tre punti, + // dopo lo slice, a significare "prendi ciascun elemento dello slice": + s = append(s, []int{7, 8, 9}...) // Il secondo argomento è uno slice letterale. + fmt.Println(s) // Lo slice aggiornato è [1 2 3 4 5 6 7 8 9] + + p, q := imparaLaMemoria() // Dichiara due puntatori a intero: p e q. + fmt.Println(*p, *q) // * dereferenzia un puntatore. Questo stampa due interi. + + // Una variabile di tipo map è un vettore associativo di dimensione variabile, + // e funzionano come le tabelle di hash o i dizionari in altri linguaggi. + m := map[string]int{"tre": 3, "quattro": 4} + m["uno"] = 1 + + // Le variabili dichiarate e non usate sono un errore in Go. + // L'underscore permette di "usare" una variabile, scartandone il valore. + _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs + // Stampare a schermo ovviamente significa usare una variabile. + fmt.Println(s, c, a4, s3, d2, m) + + imparaControlloDiFlusso() // Torniamo in carreggiata. +} + +// In Go è possibile associare dei nomi ai valori di ritorno di una funzione. +// Assegnare un nome al tipo di dato ritornato permette di fare return in vari +// punti all'interno del corpo della funzione, ma anche di usare return senza +// specificare in modo esplicito che cosa ritornare. +func imparaValoriDiRitornoConNome(x, y int) (z int) { + z = x * y + return // z è implicito, perchè compare nella definizione di funzione. +} + +// Go è dotato di garbage collection. Ha i puntatori, ma non l'aritmetica dei +// puntatori. Puoi fare errori coi puntatori a nil, ma non puoi direttamente +// incrementare un puntatore. +func imparaLaMemoria() (p, q *int) { + // I valori di ritorno (con nome) p e q sono puntatori a int. + p = new(int) // La funzione new si occupa di allocare memoria. + // L'int allocato viene inizializzato a 0, dunque p non è più nil. + s := make([]int, 20) // Alloca 20 int come un singolo blocco di memoria. + s[3] = 7 // Ne assegna uno. + r := -2 // Dichiara un'altra variabile locale + return &s[3], &r // & "prende" l'indirizzo di un oggetto. +} + +func calcoloCostoso() float64 { + return m.Exp(10) +} + +func imparaControlloDiFlusso() { + // L'istruzione if richiede parentesi graffe per il corpo, mentre non ha + // bisogno di parentesi tonde per la condizione. + if true { + fmt.Println("te l'ho detto") + } + // Eseguendo "go fmt" da riga di comando, il codice viene formattato + // in maniera standard. + if false { + // :( + } else { + // :D + } + // L'istruzione switch serve ad evitare tanti if messi in cascata. + x := 42.0 + switch x { + case 0: + case 1: + case 42: + // Quando è soddisfatta la condizione all'interno di un case, il + // programma esce dal switch senza che siano specificate istruzioni + // di tipo "break". In Go infatti di default non è presente il + // cosiddetto "fall through" all'interno dell'istruzione switch. + // Tuttavia, il linguaggio mette a disposizione la parola chiave + // fallthrough per permettere, in casi particolari, questo comportamento. + case 43: + // Non si arriva qua. + default: + // Il caso di default è opzionale. + } + // Come l'if, anche il for non usa parentesi tonde per la condizione. + // Le variabili dichiarate all'interno di if/for sono locali al loro scope. + for x := 0; x < 3; x++ { // ++ è un'istruzione! + fmt.Println("ciclo numero", x) + } + // x == 42 qua. + + // Il for è l'unica istruzione per ciclare in Go, ma ha varie forme. + for { // Ciclo infinito. + break // Scherzavo. + continue // Non si arriva qua. + } + + // Puoi usare range per ciclare su un vettore, slice, stringa, mappa o canale. + // range ritorna uno (per i canali) o due valori (vettore, slice, stringa, mappa). + for chiave, valore := range map[string]int{"uno": 1, "due": 2, "tre": 3} { + // per ogni coppia dentro la mappa, stampa chiave e valore + fmt.Printf("chiave=%s, valore=%d\n", chiave, valore) + } + + // Come nel for, := dentro la condizione dell'if è usato per dichiarare + // e assegnare y, poi testare se y > x. + if y := calcoloCostoso(); y > x { + x = y + } + // Le funzioni letterali sono closure. + xGrande := func() bool { + return x > 10000 // Si riferisce a x dichiarata sopra al switch (vedi sopra). + } + fmt.Println("xGrande:", xGrande()) // true (abbiamo assegnato e^10 a x). + x = 1.3e3 // Adesso x == 1300 + fmt.Println("xGrande:", xGrande()) // false ora. + + // Inoltre le funzioni letterali possono essere definite e chiamate + // inline, col ruolo di parametri di funzione, a patto che: + // a) la funzione letterale venga chiamata subito (), + // b) il valore ritornato è in accordo con il tipo dell'argomento. + fmt.Println("Somma e raddoppia due numeri: ", + func(a, b int) int { + return (a + b) * 2 + }(10, 2)) // Chiamata con argomenti 10 e 2 + // => Somma e raddoppia due numeri: 24 + + // Quando ti servirà, lo amerai. + goto amore +amore: + + imparaFabbricaDiFunzioni() // Una funzione che ritorna un'altra funzione è divertente! + imparaDefer() // Un tour veloce di una parola chiave importante. + imparaInterfacce() // Arriva la roba buona! +} + +func imparaFabbricaDiFunzioni() { + // Questi due blocchi di istruzioni sono equivalenti, ma il secondo è più semplice da capire. + fmt.Println(fabbricaDiFrasi("estate")("Una bella giornata", "giornata!")) + + d := fabbricaDiFrasi("estate") + fmt.Println(d("Una bella", "giornata!")) + fmt.Println(d("Un pigro", "pomeriggio!")) +} + +// I decoratori sono comuni in alcuni linguaggi. Si può fare lo stesso in Go +// con le funzioni letterali che accettano argomenti. +func fabbricaDiFrasi(miaStringa string) func(prima, dopo string) string { + return func(prima, dopo string) string { + return fmt.Sprintf("%s %s %s", prima, miaStringa, dopo) // Nuova stringa + } +} + +func imparaDefer() (ok bool) { + // Le istruzioni dette "deferred" (rinviate) sono eseguite + // appena prima che la funzione ritorni. + defer fmt.Println("le istruzioni 'deferred' sono eseguite in ordine inverso (LIFO).") + defer fmt.Println("\nQuesta riga viene stampata per prima perché") + // defer viene usato di solito per chiudere un file, così la funzione che + // chiude il file viene messa vicino a quella che lo apre. + return true +} + +// Definisce Stringer come un'interfaccia con un metodo, String. +type Stringer interface { + String() string +} + +// Definisce coppia come una struct con due campi interi, chiamati x e y. +type coppia struct { + x, y int +} + +// Definisce un metodo sul tipo coppia, che adesso implementa Stringer. +func (p coppia) String() string { // p viene definito "ricevente" + // Sprintf è un'altra funzione del package ftm. + // La notazione con il punto serve per richiamare i campi di p. + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func imparaInterfacce() { + // Brace syntax is a "struct literal". It evaluates to an initialized + // struct. The := syntax declares and initializes p to this struct. + // Le parentesi graffe sono usate per le cosiddette "struct letterali". + // Con :=, p viene dichiarata e inizializzata a questa struct. + p := coppia{3, 4} + fmt.Println(p.String()) // Chiama il metodo String di p, che è di tipo coppia. + var i Stringer // Dichiara i come interfaccia Stringer. + i = p // Valido perchè coppia implementa Stringer. + // Chiama il metodo String di i, che è di tipo Stringer. Output uguale a sopra. + fmt.Println(i.String()) + + // Functions in the fmt package call the String method to ask an object + // for a printable representation of itself. + // Le funzioni dentro al package fmt chiamano il metodo String per + // chiedere ad un oggetto una rappresentazione in stringhe di sé stesso. + fmt.Println(p) // Output uguale a sopra. Println chiama il metodo String. + fmt.Println(i) // Output uguale a sopra. + + imparaParametriVariadici("grande", "imparando", "qua!") +} + +// Le funzioni possono avere parametri variadici (ovvero di lunghezza variabile). +func imparaParametriVariadici(mieStringhe ...interface{}) { + // Cicla su ogni valore variadico. + // L'underscore serve a ignorare l'indice del vettore. + for _, param := range mieStringhe { + fmt.Println("parametro:", param) + } + + // Passa un valore variadico come parametro variadico. + fmt.Println("parametri:", fmt.Sprintln(mieStringhe...)) + + imparaGestioneErrori() +} + +func imparaGestioneErrori() { + // La sintassi ", ok" è usata per indicare se qualcosa ha funzionato o no. + m := map[int]string{3: "tre", 4: "quattro"} + if x, ok := m[1]; !ok { // ok sarà false perchè 1 non è dentro la mappa. + fmt.Println("qua non c'è nessuno!") + } else { + fmt.Print(x) // x sarebbe il valore che corrisponde alla chiave 1, se fosse nella mappa. + } + // Un errore non riporta soltanto "ok" ma è più specifico riguardo al problema. + if _, err := strconv.Atoi("non_intero"); err != nil { // _ scarta il valore + // stampa 'strconv.ParseInt: parsing "non_intero": invalid syntax' + fmt.Println(err) + } + // Approfondiremo le interfacce un'altra volta. Nel frattempo, + imparaConcorrenza() +} + +// c è un canale, un oggetto per comunicare in modo concorrente e sicuro. +func inc(i int, c chan int) { + c <- i + 1 // <- è l'operatore di "invio" quando un canale sta a sinistra. +} + +// Useremo inc per incrementare alcuni numeri in modo concorrente. +func imparaConcorrenza() { + // Stessa funzione usata prima per creare uno slice. Make alloca e + // inizializza slice, mappe e canali. + c := make(chan int) + // Lancia tre goroutine. I numeri saranno incrementati in modo concorrente, + // forse in parallelo se la macchina lo supporta. Tutti e tre inviano dati + // sullo stesso canale. + go inc(0, c) // go è un'istruzione che avvia una goroutine. + go inc(10, c) + go inc(-805, c) + // Legge tre risultati dal canale e li stampa a schermo. + // Non si conosce a priori l'ordine in cui i risultati arriveranno! + fmt.Println(<-c, <-c, <-c) // <- è l'operatore di "ricevuta" quando + // un canale sta a destra. + + cs := make(chan string) // Un altro canale, gestisce le stringhe. + ccs := make(chan chan string) // Un canale che gestisce canali di stringhe. + go func() { c <- 84 }() // Lancia una goroutine, solo per inviare un valore. + go func() { cs <- "parolina" }() // Stessa cosa ma per cs. + // select è simile a switch, ma ogni case riguarda un'operazione su un + // canale. Seleziona, in modo random, uno tra i canali che sono pronti + // a comunicare. + select { + case i := <-c: // Il valore ricevuto può essere assegnato a una variabile, + fmt.Printf("E' un %T", i) + case <-cs: // oppure il valore ricevuto può essere scartato. + fmt.Println("E' una stringa.") + case <-ccs: // Canale vuoto, non pronto per comunicare. + fmt.Println("Non succede niente.") + } + // A questo punto un valore è stato preso da c o cs. Una delle tue goroutine + // cominciate sopra ha completato l'esecuzione, l'altra rimarrà bloccata. + + imparaProgrammazioneWeb() // Se lo fa Go, lo puoi fare anche tu. +} + +// Una funzione all'interno del package http avvia un webserver. +func imparaProgrammazioneWeb() { + + // Il primo parametro di ListenAndServe è l'indirizzo TCP su cui ascoltare. + // Il secondo parametro è un'interfaccia, precisamente http.Handler. + go func() { + err := http.ListenAndServe(":8080", coppia{}) + fmt.Println(err) // Non ignorare gli errori. + }() + + richiediServer() +} + +// Per rendere coppia un http.Handler basta implementare il metodo ServeHTTP. +func (p coppia) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Il server fornisce dati con un metodo di http.ResponseWriter. + w.Write([]byte("Hai imparato Go in Y minuti!")) +} + +func richiediServer() { + risposta, err := http.Get("http://localhost:8080") + fmt.Println(err) + defer risposta.Body.Close() + corpo, err := ioutil.ReadAll(risposta.Body) + fmt.Printf("\nIl webserver dice: `%s`", string(corpo)) +} +``` + +## Letture consigliate + +La risorsa più importante per imparare il Go è il [sito ufficiale di Go](http://golang.org/). +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 +come scrivere ottimo codice in Go, documentazione sui package e sui comandi, e +la cronologia delle release. + +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). +Prova a cambiarlo e ad eseguirlo dal browser! +Osserva che puoi usare [https://play.golang.org](https://play.golang.org) 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 è +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 +codice sorgente! + +Un'altra ottima risorsa per imparare è [Go by example](https://gobyexample.com/). + +Go Mobile aggiunge il supporto per lo sviluppo mobile (Android e iOS). +In questo modo è possibile scrivere un'app mobile nativa in Go, oppure +una libreria che contiene binding da un package scritto in Go, e che può +essere richiamata da Java(Android) e Objective-C(iOS). Visita la pagina di +[Go Mobile](https://github.com/golang/go/wiki/Mobile) per maggiori informazioni. \ No newline at end of file -- cgit v1.2.3 From 80e4a8375dcaa89ddbe2b40840f968d6e632185a Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 15:35:51 +0200 Subject: #1630 --- it-it/go-it.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/it-it/go-it.html.markdown b/it-it/go-it.html.markdown index 3f17fe1f..e005f2dc 100644 --- a/it-it/go-it.html.markdown +++ b/it-it/go-it.html.markdown @@ -1,6 +1,5 @@ --- name: Go -category: language language: Go filename: learngo-it.go contributors: @@ -451,4 +450,4 @@ Go Mobile aggiunge il supporto per lo sviluppo mobile (Android e iOS). In questo modo è possibile scrivere un'app mobile nativa in Go, oppure una libreria che contiene binding da un package scritto in Go, e che può essere richiamata da Java(Android) e Objective-C(iOS). Visita la pagina di -[Go Mobile](https://github.com/golang/go/wiki/Mobile) per maggiori informazioni. \ No newline at end of file +[Go Mobile](https://github.com/golang/go/wiki/Mobile) per maggiori informazioni. -- cgit v1.2.3 From 8eac984e808014de68082b125b98091f3d50901e Mon Sep 17 00:00:00 2001 From: phbo85 Date: Sun, 26 Jun 2016 17:11:24 +0200 Subject: Added suffix to filename and changed minor content errors (#2291) --- de-de/sass-de.html.markdown | 450 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 450 insertions(+) create mode 100644 de-de/sass-de.html.markdown diff --git a/de-de/sass-de.html.markdown b/de-de/sass-de.html.markdown new file mode 100644 index 00000000..20266d17 --- /dev/null +++ b/de-de/sass-de.html.markdown @@ -0,0 +1,450 @@ +--- +language: sass +filename: learnsass.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] + - ["Sean Corrales", "https://github.com/droidenator"] + - ["Kyle Mendes", "https://github.com/pink401k"] +translators: + - ["Philipp Bochmann", "https://github.com/phbo85"] +lang: de-de +--- +Sass ist eine CSS-erweiternde Sprache, welche Features wie Variablen, Verschachtelung, Mixins und mehr hinzufügt. +Sass (und andere Präprozessoren wie [Less](http://lesscss.org/)) helfen Entwicklern dabei ihren Code wartbar und DRY (Don't Repeat Yourself - wiederhole dich nicht) zu schreiben. + +Sass hat zwei verschiedene Syntax-Optionen. SCSS, mit der gleichen Syntax wie CSS aber mit den zusätzlichen Features von Sass. Oder Sass (die originale Syntax), welche Einrückung statt geschweiften Klammern und Semikolons benutzt. +Dieses Tutorial wurde mit SCSS geschrieben. + +Wenn du bereits mit CSS3 vertraut bist, wirst du dir Sass relativ schnell aneignen. Es bietet keine neuen Styling-Eigenschaft, sondern Werkzeuge mit denen du dein CSS effizienter schreiben kannst und die Wartung viel einfacher machst. + + +```scss + + +//Einzeilige Kommentare werden entfernt, wenn Sass zu CSS kompiliert wird. + +/* Mehrzeilige Kommentare bleiben bestehen. */ + + + +/* Variablen +============================== */ + + + +/* Du kannst einen CSS-Wert (wie eine Farbe) in einer Variable speichern. +Benutze das '$'-Zeichen um eine Variable zu erstellen. */ + +$primary-color: #A3A4FF; +$secondary-color: #51527F; +$body-font: 'Roboto', sans-serif; + +/* Du kannst die Variablen überall in deinem Stylesheet verwenden. +Wenn du nun eine Farbe ändern willst, musst du das nur einmal tun. */ + +body { + background-color: $primary-color; + color: $secondary-color; + font-family: $body-font; +} + +/* Das wird kompiliert zu: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/* Dies ist viel besser wartbar als die Farbe +an jeder Stelle im Stylesheet einzeln ändern zu müssen. */ + + + +/* Mixins +============================== */ + + + +/* Wenn du merkst, dass du den gleichen Code für mehr als ein +Element schreiben musst, kannst du ihn in einem mixin speichern. + +Dazu benutzt du '@mixin' plus einem Namen für dein mixin. */ + +@mixin center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Du kannst das mixin mit '@include' und dem Namen des mixin benutzen. */ + +div { + @include center; + background-color: $primary-color; +} + +/* Das kompiliert zu: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + + +/* Du kannst Mixins benutzen, um shorthand Eigenschaften zu erstellen. */ + +@mixin size($width, $height) { + width: $width; + height: $height; +} + +/* Diese kannst du aufrufen und width und height als Parameter übergeben. */ + +.rectangle { + @include size(100px, 60px); +} + +.square { + @include size(40px, 40px); +} + +/* Compiles to: */ +.rectangle { + width: 100px; + height: 60px; +} + +.square { + width: 40px; + height: 40px; +} + + + +/* Funktionen +============================== */ + + + +/* Sass bietet Funktionen, welche benutzt werden können um eine Reihe + von Aufgaben zu bewältigen. Berücksichtige das Folgende: */ + +/* Funktionen können aufgerufen werden indem du ihren Namen benutzt + und die benötigten Parameter übergibst. */ +body { + width: round(10.25px); +} + +.footer { + background-color: fade_out(#000000, 0.25) +} + +/* Kompiliert: */ + +body { + width: 10px; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* Du kannst auch deine eigenen Funktionen definieren. Funktionen ähneln + Mixins. Wenn du zwischen Funktionen und Mixins auswählen musst, denke + daran, dass Mixins am besten zur Generierung von CSS eignen, während + Funktionen besser für Logik in deinem Sass Code genutzt werden. Die + Beispiele mit in der Sektion "Mathematische Operatoren" sind ideale + Kandidaten für wiederverwendbare Funktionen. */ + +/* Diese Funktion errechnet den Prozentwert aus target-size und parent-size + und gibt diesen zurück. */ + +@function calculate-percentage($target-size, $parent-size) { + @return $target-size / $parent-size * 100%; +} + +$main-content: calculate-percentage(600px, 960px); + +.main-content { + width: $main-content; +} + +.sidebar { + width: calculate-percentage(300px, 960px); +} + +/* Kompiliert: */ + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + + + +/* Extend (Vererbung) +============================== */ + + + +/* Extend ist ein Weg um Eigenschaften eines Selektoren mit einem anderem + zu teilen. */ + +.display { + @include size(5em, 5em); + border: 5px solid $secondary-color; +} + +.display-success { + @extend .display; + border-color: #22df56; +} + +/* Kompiliert: */ +.display, .display-success { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.display-success { + border-color: #22df56; +} + +/* Aufgrund der Art wie Sass die Klassen zusammen gruppiert, welche + alle das gleiche Grund-Styling haben, ist Extend der Erstellung + eines Mixins vorzuziehen. Wenn dies mit einem Mixin gemacht worden + wäre, würden width, height und border für jedes Element dupliziert + werden, welches das Mixin aufruft. Dies beeinflusst zwar nicht + deinen Workflow, bläht aber die vom Sass-Compiler erzeugten Dateien + unnötige auf. */ + + + +/* Nesting (Verschachtelung) +============================== */ + + + +/* Sass erlaubt es Selektoren in Selektoren zu verschachteln. */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* '&' wird durch den übergeordneten Selektor ersetzt. */ +/* Du kannst auch Pseudo-Klassen verschachteln. */ +/* Denk daran, dass zu viel Verschachtelung deinen Code schlechter + wartbar macht. + Die Best Practices empfehlen nicht mehr als 3 Ebenen zu verschachteln. + Zum Beispiel: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Kompiliert: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/* Partials und Imports +============================== */ + + + +/* Sass erlaubt dir das Erstellen partieller Dateien (partials). + Das hilft dir modularisierten Sass Code zu schreiben. + Partielle Dateien fangen mit einem '_' an, z.B. _reset.css. + Partielle Dateien werden nicht zu CSS generiert. */ + +/* Schau dir folgendes CSS an, was wir in einer Datei namens _reset.css haben */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Mit @import kannst du in Sass partielle Dateien importieren. + Dies unterscheidet sich vom traditionellen CSS @import Statement + welches einen neuen HTTP Request macht, um die zu importierende Datei + zu holen. Sass nimmt die importierte Datei und kombiniert sie mit + dem kompilierten Code. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Kompiliert: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/* Platzhalter Selektoren +============================== */ + + + +/* Platzhalter sind nützlich, um ein CSS Statement zum Erweitern zu + erstellen. Wenn du ein CSS Statement erstellst, welches du ausschließlich + zur Verwendung mit @extend nutzen willst, kannst du das mit einem + Platzhalter tun. Platzhalter fangen mit einem '%' statt einem '.' + oder '#' an und erscheinen nicht im kompilierten CSS. */ + +%content-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + @extend %content-window; + background-color: #0000ff; +} + +/* Kompiliert: */ + +.message-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + background-color: #0000ff; +} + + + +/* Mathematische Operationen +============================== */ + + + +/* Sass bietet die folgenden Operatoren: +, -, *, /, und %. Diese können + nützlich sein, wenn du Werte direkt in Sass berechnen willst, anstatt + vorher manuell errechnete Werte zu verwenden. Unten folgt ein Beispiel + für ein einfaches zweispaltiges Design. */ + +$content-area: 960px; +$main-content: 600px; +$sidebar-content: 300px; + +$main-size: $main-content / $content-area * 100%; +$sidebar-size: $sidebar-content / $content-area * 100%; +$gutter: 100% - ($main-size + $sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: $main-size; +} + +.sidebar { + width: $sidebar-size; +} + +.gutter { + width: $gutter; +} + +/* Compiles to: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + +``` + +## SASS oder Sass? +Hast du dich jemals gefragt, ob Sass ein Akronym ist oder nicht? Hast du wahrscheinlich nicht, aber ich sage es dir trotzdem. Der Name der Sprache ist ein Wort, "Sass", und kein Akronym. +Da die Leute durchgehend "SASS" geschrieben haben, hat der Ersteller der Sprache es scherzhaft "Syntactically Awesome StyleSheets" genannt. + +## Sass üben +Wenn du mit Sass in deinem Browser spielen willst, schau dir [SassMeister](http://sassmeister.com/) an. +Du kannst beide Syntax-Optionen benutzen, gehe einfach in die Einstellungen und wähle entweder Sass oder SCSS. + +## Kompatibilität +Sass kann in jedem Projekt verwendet werden, solange du ein Programm hast, um es in CSS zu kompilieren. +Du solltest verifizieren, dass das CSS, was du verwendest, mit deinen Ziel-Browsern kompatibel ist. + +[QuirksMode CSS](http://www.quirksmode.org/css/) und [CanIUse](http://caniuse.com) sind gute Resourcen um die Kompatibilät zu überpüfen. + + +## Literaturhinweise +* [Offizielle Dokumentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) bietet Tutorials (Anfänger bis Fortgeschritten) und Artikel. -- cgit v1.2.3 From 5ec0aba7783f7900bc97dda4a0ce68814442b6e4 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 17:11:50 +0200 Subject: fix #2291 metadata --- de-de/sass-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/sass-de.html.markdown b/de-de/sass-de.html.markdown index 20266d17..0c14e249 100644 --- a/de-de/sass-de.html.markdown +++ b/de-de/sass-de.html.markdown @@ -1,6 +1,6 @@ --- language: sass -filename: learnsass.scss +filename: learnsass-de.scss contributors: - ["Laura Kyle", "https://github.com/LauraNK"] - ["Sean Corrales", "https://github.com/droidenator"] -- cgit v1.2.3 From 5d39704b57bc3e163df6f9ac510ea7e56439db0e Mon Sep 17 00:00:00 2001 From: Kyle Mendes Date: Sun, 26 Jun 2016 15:46:16 -0400 Subject: [rust/en] Updating comment examples (#1883) --- rust.html.markdown | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/rust.html.markdown b/rust.html.markdown index 440cd9eb..cce91683 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -2,6 +2,7 @@ language: rust contributors: - ["P1start", "http://p1start.github.io/"] + - ["Pink401k", "http://github.com/Pink401k"] filename: learnrust.rs --- @@ -27,8 +28,15 @@ concepts that are generally found in higher-level languages. This makes Rust not only fast, but also easy and efficient to code in. ```rust -// This is a comment. Single-line look like this... -/* ...and multi-line comment look like this */ +// This is a comment. Line comments look like this... +// and extend multiple lines like this. + +/// Documentation comments look like this and support markdown notation. +/// # Examples +/// +/// ``` +/// let five = 5 +/// ``` /////////////// // 1. Basics // -- cgit v1.2.3 From 5977df5be45c0f3468abf402921cf925c996a472 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 21:46:57 +0200 Subject: Update rust.html.markdown --- rust.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/rust.html.markdown b/rust.html.markdown index cce91683..4aa9ca7c 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -2,7 +2,6 @@ language: rust contributors: - ["P1start", "http://p1start.github.io/"] - - ["Pink401k", "http://github.com/Pink401k"] filename: learnrust.rs --- -- cgit v1.2.3 From 281ba5b37a9e4e42d33442b0d3a062d99c964a95 Mon Sep 17 00:00:00 2001 From: Ankush goyal Date: Mon, 27 Jun 2016 02:19:51 +0530 Subject: Containers Added (#1942) * Containers Added * Text Formatting Added required spaces between text and // --- c++.html.markdown | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/c++.html.markdown b/c++.html.markdown index a02e7e5b..6b81f95f 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Matt Kline", "https://github.com/mrkline"] - ["Geoff Liu", "http://geoffliu.me"] - ["Connor Waters", "http://github.com/connorwaters"] + - ["Ankush Goyal", "http://github.com/ankushg07"] lang: en --- @@ -985,6 +986,99 @@ cout << get<0>(concatenated_tuple) << "\n"; // prints: 10 cout << get<3>(concatenated_tuple) << "\n"; // prints: 15 cout << get<5>(concatenated_tuple) << "\n"; // prints: 'A' + +///////////////////// +// CONTAINERS +///////////////////// + +// Containers or the Standard Template Library are some predefined templates +// They manages the storage space for its elements and provide +// member functions to access and manipulate them + +// Few containers are as follows:- + +// Vectors (Dynamic arrays) +// Allow us to Define the Array or list of objects at run time +#include // will include the header file for vector +vector< Data_Type > Vector_name; // used to initialize the vector +cin>>val; +Vector_name.push_back(val); // will push the value of variable into array + +// To iterate through vector, we have 2 choices +// using normal looping +for(int i=0; i::iterator it; // initialize the iteartor for vector +for(it=vector_name.begin(); it!=vector_name.end();++it) + +// For accessing the element of the vector +// Operator [] +var= vector_name[index]; //will assign value at that index to var + + +// Set +// Sets are containers that store unique elements following a specific order +// Very useful container to store unique values in sorted order +// without any other functions or code + +#include // Will include the header file for sets +set< int > ST; // Will initialize the set of int data type +ST.insert(30); // Will insert the value 30 in set ST +ST.insert(10); // Will insert the value 10 in set ST +ST.insert(20); // Will insert the value 20 in set ST +ST.insert(30); // Will insert the value 30 in set ST +// Now elements of sets are as follows +// 10 20 30 + +// To erase an element +ST.erase(20); // Will erase element with value 20 +// Set ST: 10 30 +// To iterate through Set we use iterators +set< int >::iterator it; +for(it=ST.begin();it // Will include the header file for map +map< char, int >mymap; // Will initalize the map with key as char and value as int + +mymap.insert ( pair('A',1) ); +// Will insert value 1 for key A +mymap.insert ( pair('Z',26) ); +// Will insert value 26 for key Z + +// To iterate +map::iterator it; +for (it=mymap.begin(); it!=mymap.end(); ++it) + std::cout << it->first << "->" << it->second <<'\n'; +// Output: +// A->1 +// Z->26 + +// To find the value correponsing to a key +it = mymap.find('Z'); +cout<second; + +// OUTPUT: 26 + + ``` Further Reading: -- cgit v1.2.3 From f98cbd3653bd0b83bdfb4cb8afae529afd3bc8bc Mon Sep 17 00:00:00 2001 From: Oleksii Kholovchuk Date: Mon, 27 Jun 2016 00:10:37 +0300 Subject: Added document about Qt framework (#1444) * Added document about Qt framework * Removed qt.cpp file and made some corrections in the markdown file --- qt.html.markdown | 157 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 qt.html.markdown diff --git a/qt.html.markdown b/qt.html.markdown new file mode 100644 index 00000000..71d12909 --- /dev/null +++ b/qt.html.markdown @@ -0,0 +1,157 @@ +--- +category: tool +tool: Qt Framework +language: c++ +filename: learnqt.cpp +contributors: + - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"] +lang: en +--- + +**Qt** is a widely-known framework for developing cross-platform software that can be run on various software and hardware platforms with little or no change in the code, while having the power and speed of native applications. Though **Qt** was originally written in *C++*, there are its ports to other languages: *PyQt*, *QtRuby*, *PHP-Qt*, etc. + +**Qt** is beautiful for creating applications with graphical user interface (GUI). This tutorial is how to do it in *C++*. + +```c++ +/* + * Let's start clasically + */ + +// all headers from Qt framework start with capital letter 'Q' +#include +#include + +int main(int argc, char *argv[]) { + // create an object to manage application-wide resources + QApplication app(argc, argv); + + // create line edit widget and show it on screen + QLineEdit lineEdit("Hello world!"); + lineEdit.show(); + + // start the application's event loop + return app.exec(); +} +``` + +GUI-related part of **Qt** is all about *widgets* and *connections* between them. + +[READ MORE ABOUT WIDGETS](http://doc.qt.io/qt-5/qtwidgets-index.html) + +```c++ +/* + * Let's create a label and a button. + * A label should appear when a button is pressed. + * + * Qt code is speaking for itself. + */ + +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + + QDialog dialogWindow; + dialogWindow.show(); + + // add vertical layout + QVBoxLayout layout; + dialogWindow.setLayout(&layout); + + QLabel textLabel("Thanks for pressing that button"); + layout.addWidget(&textLabel); + textLabel.hide(); + + QPushButton button("Press me"); + layout.addWidget(&button); + + // show hidden label when the button is pressed + QObject::connect(&button, &QPushButton::pressed, + &textLabel, &QLabel::show); + + return app.exec(); +} +``` + +Notice that *QObject::connect* part. This method is used to connect *SIGNALS* of one objects to *SLOTS* of another. + +**Signals** are being emited when certain things happen with objects, like *pressed* signal is emited when user presses on QPushButton object. + +**Slots** are *actions* that might be performed in response to received signals. + +[READ MORE ABOUT SLOTS AND SIGNALS](http://doc.qt.io/qt-4.8/signalsandslots.html) + + +Next, let's learn that we can not only use standard widgets but also extend their behaviour using inheritance. Let's create a button and count how many times it was pressed. For this purpose we define our own class *CounterLabel*. It must be declared in separate file because of specific Qt architecture. + +```c++ +// counterlabel.hpp + +#ifndef COUNTERLABEL +#define COUNTERLABEL + +#include + +class CounterLabel : public QLabel { + Q_OBJECT // Qt-defined macros that must be present in every custom widget + +public: + CounterLabel() : counter(0) { + setText("Counter has not been increased yet"); // method of QLabel + } + +public slots: + // action that will be called in response to button press + void increaseCounter() { + setText(QString("Counter value: %1").arg(QString::number(++counter))); + } + +private: + int counter; +}; + +#endif // COUNTERLABEL +``` + +```c++ +// main.cpp +// Almost the same as in previous example + +#include +#include +#include +#include +#include +#include "counterlabel.hpp" + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + + QDialog dialogWindow; + dialogWindow.show(); + + QVBoxLayout layout; + dialogWindow.setLayout(&layout); + + CounterLabel counterLabel; + layout.addWidget(&counterLabel); + + QPushButton button("Push me once more"); + layout.addWidget(&button); + QObject::connect(&button, &QPushButton::pressed, + &counterLabel, &CounterLabel::increaseCounter); + + return app.exec(); +} +``` + +## Furter reading +That's it! Of course Qt framework is much much larger than the part that was covered in this tutorial, so be ready to read and practice. + +[READ MORE ABOUT QT](http://doc.qt.io/qt-4.8/tutorials.html) + +Good luck and have fun -- cgit v1.2.3 From 95870a3aa2a05542ef2e9356127bafe2eeeb535f Mon Sep 17 00:00:00 2001 From: WinChris Date: Mon, 27 Jun 2016 10:00:38 +0200 Subject: Create HTML-fr.html.markdown (#1843) * Create HTML-fr.html.markdown What is HTML ? Tutorial to understand HTML * Update HTML-fr.html.markdown * Update HTML-fr.html.markdown * Update HTML-fr.html.markdown Corrections de divers points * Update HTML-fr.html.markdown Corrections * Update HTML-fr.html.markdown Corrections d'un commentaire * Update HTML-fr.html.markdown * Update HTML-fr.html.markdown * Update HTML-fr.html.markdown --- HTML-fr.html.markdown | 115 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 HTML-fr.html.markdown diff --git a/HTML-fr.html.markdown b/HTML-fr.html.markdown new file mode 100644 index 00000000..fdde9107 --- /dev/null +++ b/HTML-fr.html.markdown @@ -0,0 +1,115 @@ +--- +language: html +filename: learnhtml-fr.html +contributors: + - ["Christophe THOMAS", "https://github.com/WinChris"] +lang: fr-fr +--- +HTML signifie HyperText Markup Language. +C'est un langage (format de fichiers) qui permet d'écrire des pages internet. +C’est un langage de balisage, il nous permet d'écrire des pages HTML au moyen de balises (Markup, en anglais). +Les fichiers HTML sont en réalité de simple fichier texte. +Qu'est-ce que le balisage ? C'est une façon de hiérarchiser ses données en les entourant par une balise ouvrante et une balise fermante. +Ce balisage sert à donner une signification au texte ainsi entouré. +Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parlons de HTML5. + +**NOTE :** Vous pouvez tester les différentes balises que nous allons voir au fur et à mesure du tutoriel sur des sites comme [codepen](http://codepen.io/pen/) afin de voir les résultats, comprendre, et vous familiariser avec le langage. +Cet article porte principalement sur la syntaxe et quelques astuces. + + +```HTML + + + + + + + + + + + Mon Site + + +

Hello, world!

+ Venez voir ce que ça donne +

Ceci est un paragraphe

+

Ceci est un autre paragraphe

+
    +
  • Ceci est un item d'une liste non ordonnée (liste à puces)
  • +
  • Ceci est un autre item
  • +
  • Et ceci est le dernier item de la liste
  • +
+ + + + + + + + + + + + + + + + + + + + Mon Site + + + + + + + +

Hello, world!

+ + Venez voir ce que ça donne +

Ceci est un paragraphe

+

Ceci est un autre paragraphe

+
    + +
  • Ceci est un item d'une liste non ordonnée (liste à puces)
  • +
  • Ceci est un autre item
  • +
  • Et ceci est le dernier item de la liste
  • +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
First Header Second Header
Première ligne, première cellule Première ligne, deuxième cellule
Deuxième ligne, première celluleDeuxième ligne, deuxième cellule
+ +## Utilisation + +Le HTML s'écrit dans des fichiers `.html`. + +## En savoir plus + +* [Tutoriel HTML](http://slaout.linux62.org/html_css/html.html) +* [W3School](http://www.w3schools.com/html/html_intro.asp) -- cgit v1.2.3 From 46844f8e8e9b55148910256e149f510ae43cf757 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20D=C3=A4hnert?= Date: Mon, 27 Jun 2016 10:09:58 +0200 Subject: [java/de] Initial translation added. (#1391) * DE-Translation for Java added. * Handled hints from vendethiel. --- de-de/java-de.html.markdown | 497 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 497 insertions(+) create mode 100644 de-de/java-de.html.markdown diff --git a/de-de/java-de.html.markdown b/de-de/java-de.html.markdown new file mode 100644 index 00000000..001c6888 --- /dev/null +++ b/de-de/java-de.html.markdown @@ -0,0 +1,497 @@ +--- +language: java +filename: LearnJavaDe.java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Jakukyo Friel", "http://weakish.github.io"] + - ["Madison Dickson", "http://github.com/mix3d"] + - ["Simon Morgan", "http://sjm.io/"] +translators: + - ["Michael Dähnert", "http://github.com/JaXt0r"] +lang: de-de +--- + +Java ist eine Programmiersprache für vielfältige Aufgaben. Sie ist imperative und objektorientiert. +Oftmals wird sie für Desktop- Webapplikationen sowie als Programmiersprache im Betriebssystem Android verwendet. +[Weitere Informationen \(Englisch\](http://docs.oracle.com/javase/tutorial/java/) + +```java +// Einzeilige Kommentare starten mit // +/* +Mehrzeilige Kommentare sehen so aus. +*/ +/** +JavaDoc Kommentare haben dieses Format. Sie werden verwendet um Klassen, Attribute sowie Methoden zu beschreiben. +*/ + +// Importieren der Klasse ArrayList aus dem Paket java.util +import java.util.ArrayList; +// Importieren aller Klassen innerhalb des Paketes java.security +import java.security.*; + +// Jede .java Datei besteht aus einer äußeren öffentlichen (public) Klasse. +// Der Name der Klasse muss identisch des Dateinamens sein. +public class LearnJavaDe { + + // Ein Programm muss eine main Methode als Eintrittspunkt besitzen. + public static void main (String[] args) { + + // System.out.println() wird zum Schreiben von zeilenweisen Ausgaben verwendet. + System.out.println("Hello World!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Zum Schreiben von Ausgaben ohne Zeilenumbruch wird System.out.print() verwendet. + System.out.print("Hello "); + System.out.print("World"); + + + /////////////////////////////////////// + // Typen & Variablen + /////////////////////////////////////// + + // Zum Deklarieren einer Variable nutze + // Byte - 8-bit vorzeichenbehaftete (signed), binäre Ganzzahl + // (-128 <= byte <= 127) + byte fooByte = 100; + + // Short - 16-bit vorzeichenbehaftete (signed), binäre Ganzzahl + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Integer - 32-bit vorzeichenbehaftete (signed), binäre Ganzzahl + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Long - 64-bit vorzeichenbehaftete (signed), binäre Ganzzahl + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L wird verwendet um zu kennzeichnen, dass ein Variablenwert vom Typ long ist. + // Ohne diesen Buchstaben wird die Zahl automatisch als Integer behandelt. + + // Hinweis: Java besitzt keine vorzeichenlosen (unsigned) Typen. + + // Float - Typ mit einfacher Genauigkeit (Single-precision), 32-bit IEEE 754 Fließkommazahl + float fooFloat = 234.5f; + // f wird verwendet um zu kennzeichnen, dass ein Variablenwert vom Typ float ist; + // Ohne diesen Buchstaben wird die Zahl automatisch als Integer behandelt. + + // Double - Typ mit doppelter Genauigkeit (Double-precision), 64-bit IEEE 754 Fließkommazahl + double fooDouble = 123.4; + + // Boolean - Wahr & Falsch (true & false) + boolean fooBoolean = true; + boolean barBoolean = false; + + // Char - Ein einfacher 16-bit Unicode Buchstabe + char fooChar = 'A'; + + // final Variablen können von einem anderen Objekt nicht erneut zugeordnet werden. + final int HOURS_I_WORK_PER_WEEK = 9001; + + // Zeichenketten (Strings) + String fooString = "My String Is Here!"; + + // \n ist ein Escape Zeichen welcher eine neue Zeile startet. + String barString = "Schreiben auf einer neuen Zeile?\nKein Problem!"; + // \t ist ein Escape Zeichen welcher einen Tab-Zeichen anhängt. + String bazString = "Möchtest du einen Tabulator anhängen?\tKein Problem!"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // Arrays + // Die Arraygröße muss bei Instanziierung entschieden werden. + // Das folgende Format funktioniert bei Deklaration eines Arrays + // [] = new []; + // [] = new []; + int[] intArray = new int[10]; + String[] stringArray = new String[1]; + boolean boolArray[] = new boolean[100]; + + // Eine weitere Möglichkeit ein Array zu deklarieren & initialisieren. + int[] y = {9000, 1000, 1337}; + String names[] = {"Bob", "John", "Fred", "Juan Pedro"}; + boolean bools[] = new boolean[] {true, false, false}; + + // Indexierung eines Arrays - Zugriff auf ein Element + System.out.println("intArray @ 0: " + intArray[0]); + + // Arrays sind 0-indexiert und veränderbar. + intArray[1] = 1; + System.out.println("intArray @ 1: " + intArray[1]); // => 1 + + // Weitere nennenswerte Typen + // ArrayLists - Ähnlich Arrays, allerdings werden mehr Funktionen geboten, + // ebenso ist die Arraygröße verwänderbar + // LinkedLists - Implementierung einer doppelt verlinkten Liste. + // Alle Operationen funktioneren so, wie es von einer doppelt verlinkten Liste erwartet wird. + // Weitere Informationen: https://de.wikipedia.org/wiki/Liste_(Datenstruktur)#Doppelt_.28mehrfach.29_verkettete_Liste + // Maps - Eine Sammlung von Objekten, welche eine Verknüpfung von Schlüsseln zu Werten (key => value) vornimmt. + // Eine Map kann keine Duplikate enthalten; Jeder Schlüssel kann genau einen Wert beinhalten. + // HashMaps - Diese Klasse nutzt eine Hashtabelle zur Implementierung eines Map Interfaces. + // Dies erlaubt es zur Laufzeit Standardoperationen wie gib (get) und einfügen (insert) + // selbst für große Mengen in einer konstanten Zeit auszuführen (Laufzeitverhalten O(n)). + + /////////////////////////////////////// + // Operatoren + /////////////////////////////////////// + System.out.println("\n->Operatoren"); + + int i1 = 1, i2 = 2; // Kurform zur Deklaration mehrerer Variablen. + + // Arithmetische Operationen sind einfach nutzbar. + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 Nachkommazahl abgeschnitten) + + // Modulo + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Vergleichsoperationen + System.out.println("3 == 2? " + (3 == 2)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // Bitwise Operatoren! + /* + ~ Unäres (unary) bitweise Komplement + << Vorzeichenbehaftete (signed) linke Verschiebung + >> Vorzeichenbehaftete (signed) rechte Verschiebung + >>> Vorzeichenlose (unsigned) linke Verschiebung + & Bitweise UND (AND) + ^ Bitweise exklusive ODER (OR) + | Bitweise inklusive ODER (OR) + */ + + // Inkrementierungen + int i = 0; + System.out.println("\n->Inc/Dec-rementierung"); + // Die ++ und -- operatoren inkrementieren und dekrementieren jeweils um 1. + // Werden sie vor die Variable gesetzt, ink-/dekrementieren sie und geben anschließend ihren Wert zurück. + // Hinter der Variable geben sie ihren Wert zurück und ändern ihn anschließend. + System.out.println(i++); // i = 1, schreibt 0 (post-increment) + System.out.println(++i); // i = 2, schreibt 2 (pre-increment) + System.out.println(i--); // i = 1, schreibt 2 (post-decrement) + System.out.println(--i); // i = 0, schreibt 0 (pre-decrement) + + /////////////////////////////////////// + // Kontrollstrukturen + /////////////////////////////////////// + System.out.println("\n->Kontrollstrukturen"); + + // If Bedingungen sind wie in den C-Sprachen aufgebaut + int j = 10; + if (j == 10){ + System.out.println("Ich wurde geprinted"); + } else if (j > 10) { + System.out.println("Ich nicht"); + } else { + System.out.println("Ich auch nicht"); + } + + // While Schleife + int fooWhile = 0; + while(fooWhile < 100) { + System.out.println(fooWhile); + // Den Zähler inkrementieren + // 100x iterieren, fooWhile 0,1,2...99 + fooWhile++; + } + System.out.println("fooWhile Wert: " + fooWhile); + + // Do While Schleife + int fooDoWhile = 0; + do { + System.out.println(fooDoWhile); + // Den Zähler inkrementieren + // 99x iterieren, fooDoWhile 0->99 + fooDoWhile++; + } while(fooDoWhile < 100); + System.out.println("fooDoWhile Wert: " + fooDoWhile); + + // For Schleife + int fooFor; + // for Schleifenstruktur => for(; ; ) + for (fooFor = 0; fooFor < 10; fooFor++) { + System.out.println(fooFor); + // 10x iterieren, fooFor 0->9 + } + System.out.println("fooFor Wert: " + fooFor); + + // For Each Schleife + // The for Schleife kann verwendet werden um über Arrays ebenso wie Objekte, + // welche das Interface Iterable implementieren zu iterieren. + int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + // for each Schleifenstruktur => for ( : ) + // Wird gelesen als: Iteriere für jedes Element im Iterable + // Hinweis: Der Objekttyp muss dem Elementtyp des Iterable entsprechen. + + for (int bar : fooList) { + System.out.println(bar); + //9x iterieren und die Werte 1-9 auf jeweils einer neuen Zeile schreiben + } + + // Switch Case + // A Schalter (switch) funktioniert mit den Datentypen byte, short, char und int. + // Ebenso kann er für Aufzählungen (Enums) verwendet werden (Enum Typen folgen weiter unten) + // der String Klasse (ab Java SE7) und ein paar spezielle Klassen, welche die primitiven Typen ummanteln (wrap): + // Character, Byte, Short, and Integer. + int monat = 3; + String monatsString; + switch (monat) { + case 1: monatsString = "Januar"; + break; + case 2: monatsString = "Februar"; + break; + case 3: monatsString = "März"; + break; + default: monatsString = "Ein anderer Monat"; + break; + } + System.out.println("Switch Case Ergebnis: " + monatsString); + + // Bedingungsoperator (Conditional Shorthand) + // Der Operator '?' kann für schnelle Zuweisungen oder logische Verzweigungen genutzt werden. + // Er ist wie folgt zu lesen: Wenn die Bedingung wahr ist, nutze + // ansonsten nutze + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println(bar); // Schreibt A, denn die Bedingung ist wahr. + + + //////////////////////////////////////// + // Typkonvertierung und Type-Casting + //////////////////////////////////////// + + // Konvertierung von Daten + + // Konvertiere String nach Integer + Integer.parseInt("123");// Gibt die Integer Repräsentation von "123" zurück + + // Konvertiere String nach Integer + Integer.toString(123);// Gibt die String Repräsentation von 123 zurück + + // Für andere Konvertierungen sind die folgenden Klassen zu betrachten: + // Double + // Long + // String + + // Tpe-Casting + // Java Objekte können benfalls konvertiert werden, hierbei gibt es vielfältige Konzepte. + // Weitere Informationen finden sich hier (englisch): + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Klassen und Funktionen + /////////////////////////////////////// + + System.out.println("\n->Klassen & Funktionen"); + + // (Die Definition der Klasse Fahrrad folgt) + + // Verwendung einer neuen Klasseninstanz + Fahrrad trek = new Fahrrad(); + + // Aufruf von Methoden des Objektes + trek.erhöheGeschwindigkeit(3); // Es sollten immer getter- und setter- Methoden verwendet werden + trek.setTrittfrequenz(100); + + // toString gibt die StringRepräsentation des Objektes zurück. + System.out.println("trek info: " + trek.toString()); + + } // Ende der Main Methode +} // Ende der LearnJavaDe Klasse + + +// In einer .java-Datei können zusätzliche nicht öffentliche (non-public) äüßere Klassen vorhanden sein. + + +// Syntax der Klassendeklaration: +// class { +// // Es folgen Datenfelder, Konstruktoren, Funktionen. +// // Funktionen werden in Java Methoden genannt. +// } + +class Fahrrad { + + // Felder/Variablen der Klasse Fahrrad + public int trittfrequenz; // Public: Kann von überall her angesprochen werden + private int geschwindigkeit; // Private: Nur innerhalb der Klasse sichtbar + protected int gang; // Protected: Erreichbar innerhalb der Klasse oder Subklassen (sub classes) + String name; // default: Nur innerhalb des Paketes verwendbar + + // Eine Klasse kann mittelst Konstruktoren erstellt werden. + // Das ist ein Konstruktor + public Fahrrad() { + gang = 1; + trittfrequenz = 50; + geschwindigkeit = 5; + name = "Bontrager"; + } + + // Das ist ein Konstruktor mit Argumenten + public Bicycle(int initialTrittfrequenz, int initialGeschwindigkeit, int initialGang, + String name) { + this.gang = initialGang; + this.trittfrequenz = initialTrittfrequenz; + this.geschwindigkeit = initialGeschwindigkeit; + this.name = name; + } + + // Syntax von Methoden (Funktionen): + // () + + // Java Klassen implementieren oftmals getter- und setter-Methoden ihrer Felder + + // Syntax von Methodendeklarationen: + // () + public int getTrittfrequenz() { + return tri; + } + + // void Methoden benötigen kein return Statement. + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void erhöheGeschwindigkeit(int increment) { + speed += increment; + } + + public void verringereGeschwindigkeit(int decrement) { + speed -= decrement; + } + + public void setName(String newName) { + name = newName; + } + + public String getName() { + return name; + } + + //Methode zur Darstellung der Attributwerte des Objektes. + @Override + public String toString() { + return "Gang: " + gang + " Trittfrequenz: " + trittfrequenz + " Geschwindigkeit: " + geschwindigkeit + + " name: " + name; + } +} // Ende der Klasse Fahrrad + +// Hochrad ist eine Subklasse von Fahrrad +class Hochrad extends Fahrrad { + // (Hochräder sind Fahrräder mit einem extrem großen Vorderrad. + // Sie haben keine Gänge.) + + public Hochrad(int initialTrittfrequenz, int initialGeschwindigkeit){ + // Aufruf des Vater-Konstruktors (parent constructor) mit dem Wort super. + super(initialTrittfrequenz, initialGeschwindigkeit, 0, "Hochrad"); + } + + // Überschriebene Methoden sollten die Annotation @Override besitzen. + // Mehr zu Annotationen und deren Verwendungszwecken kann hier nachgelesen werden: + // (englisch) http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setGang(int gang) { + gang = 0; + } +} + +// Schnittstellen (Interfaces) +// Interface Deklaration +// interface extends { +// // Konstanten +// // Methodendeklarationen +// } + +// Beispiel - Nahrung: +public interface Essbar { + public void essen(); // Jede Klasse, die dieses Interface implementiert + // muss auch diese Methode implementieren. +} + + +public interface Verdaulich { + public void verdauen(); +} + + +// Nun können wir eine Klasse erstellen, die beide Interfaces implementiert. +public class Frucht implements Essbar, Verdaulich { + @Override + public void essen() { + // ... + } + + @Override + public void verdauen() { + // ... + } +} + +// Mit Java kann man nur eine Klasse erweitern (extends) jedoch mehrere Interfaces implementieren. +// z.B.: +public class BeispielKlasse extends ParentBeispielKlasse implements InterfaceEins, + InterfaceZwei { + @Override + public void methodeInterfaceEins() { + } + + @Override + public void methodeInterfaceZwei() { + } +} +``` + +## Weitere Informationen (in englisch) + +Die folgenden Links dienen lediglich dazu Verständnis für die Kapitel aufzubauen. +Für tiefergreifende Fragen ist Google der beste Startpunkt. + +**Offizielle Oracle Guides**: + +* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) + +**Online Tutorials** + +* [Learneroo.com - Learn Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Bücher**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Thinking in Java](http://www.mindview.net/Books/TIJ/) + +* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) -- cgit v1.2.3 From c50ff9299651ba3c856ee23cbdabeda2784b864c Mon Sep 17 00:00:00 2001 From: Jatin Dhankhar Date: Mon, 27 Jun 2016 19:00:07 +0530 Subject: Added the Logical and bitwise operators section, fixes merge issue with #1817 (#2292) * Added the Logical and bitwise operators section * Added a note for Short Circuit evaluation Excerpt from https://en.wikipedia.org/wiki/Short-circuit_evaluation C++ uses minimal evaluation, or McCarthy evaluation (after John McCarthy (computer scientist)) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true. In some programming languages (Lisp), the usual Boolean operators are short-circuit. --- c++.html.markdown | 57 +++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 51 insertions(+), 6 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 6b81f95f..290633f3 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Geoff Liu", "http://geoffliu.me"] - ["Connor Waters", "http://github.com/connorwaters"] - ["Ankush Goyal", "http://github.com/ankushg07"] + - ["Jatin Dhankhar", "https://github.com/jatindhankhar"] lang: en --- @@ -1005,7 +1006,7 @@ cin>>val; Vector_name.push_back(val); // will push the value of variable into array // To iterate through vector, we have 2 choices -// using normal looping +// using normal looping for(int i=0; i // Will include the header file for sets @@ -1031,7 +1032,7 @@ ST.insert(20); // Will insert the value 20 in set ST ST.insert(30); // Will insert the value 30 in set ST // Now elements of sets are as follows // 10 20 30 - + // To erase an element ST.erase(20); // Will erase element with value 20 // Set ST: 10 30 @@ -1041,7 +1042,7 @@ for(it=ST.begin();it('A',1) ); mymap.insert ( pair('Z',26) ); // Will insert value 26 for key Z -// To iterate +// To iterate map::iterator it; for (it=mymap.begin(); it!=mymap.end(); ++it) std::cout << it->first << "->" << it->second <<'\n'; -// Output: +// Output: // A->1 // Z->26 @@ -1078,6 +1079,50 @@ cout<second; // OUTPUT: 26 +/////////////////////////////////// +// Logical and Bitwise operators +////////////////////////////////// + +// Most of the operators in C++ are same as in other languages + +// Logical operators + +// C++ uses Short - circuit evaluation for boolean expressions, i.e, the second argument is executed or +// evaluated only if the first argument does not suffice to determine the value of the expression + +true && false // Performs **logical and** to yield false +true || false // Performs **logical or** to yield true +! true // Performs **logcical not** to yield + +// Instead of using symbols equivalent keywords can be used +true and false // Performs **logical and** to yield false +true or false // Performs **logical or** to yield true +not true // Performs **logcical not** to yield + +// Bitwise operators + +// **<<** Left Shift Operator +// << shifts bits to the left +4 << 1 // Shifts bits of 4 to left by 1 to give 8 +// x << n can be thought as x * 2^n + + +// **>>** Right Shift Operator +// << shifts bits to the right +4 >> 1 // Shifts bits of 4 to right by 1 to give 2 +// x << n can be thought as x / 2^n + +~4 // Performs a bitwise not +4 | 3 // Performs bitwise or +4 & 3 // Performs bitwise and +4 ^ 3 // Performs bitwise xor + +// Equivalent keywords are +compl 4 // Performs a bitwise not +4 bitor 3 // Performs bitwise or +4 bitand 3 // Performs bitwise and +4 xor 3 // Performs bitwise xor + ``` Further Reading: -- cgit v1.2.3 From c0577fece6b2862a7198b61ec1855b504cf43d47 Mon Sep 17 00:00:00 2001 From: Durant Schoon Date: Mon, 27 Jun 2016 23:53:25 -0700 Subject: Correct "Bycles" to "Bicycles"" (#2293) "DidWeCreateEnoughBycles" -> "DidWeCreateEnoughBicycles" --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 69aef257..4c9e8411 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -826,7 +826,7 @@ on a new line! ""Wow!"", the masses cried"; } // Methods can also be static. It can be useful for helper methods - public static bool DidWeCreateEnoughBycles() + public static bool DidWeCreateEnoughBicycles() { // Within a static method, we only can reference static class members return BicyclesCreated > 9000; -- cgit v1.2.3 From d3a31e9a7d2752e67e452a28f318710448444ba8 Mon Sep 17 00:00:00 2001 From: Adam Heins Date: Mon, 27 Jun 2016 23:54:00 -0700 Subject: Remove obsolete utf-8 options. (#2294) These options are no longer valid in recent versions of tmux. See https://github.com/tmux/tmux/issues/230. --- tmux.html.markdown | 4 ---- 1 file changed, 4 deletions(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index c9e3db6b..ae73d912 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -122,10 +122,6 @@ like how .vimrc or init.el are used. ### General ########################################################################### -# Enable UTF-8 -setw -g utf8 on -set-option -g status-utf8 on - # Scrollback/History limit set -g history-limit 2048 -- cgit v1.2.3 From 7812b99ff8f649595a57ef86577c7567cd1c8166 Mon Sep 17 00:00:00 2001 From: ven Date: Tue, 28 Jun 2016 18:06:06 +0200 Subject: Manually merge #1780 fixes #1780 --- java.html.markdown | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index fb0913f1..f65c484e 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -8,6 +8,7 @@ contributors: - ["Zachary Ferguson", "http://github.com/zfergus2"] - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] - ["Rachel Stiyer", "https://github.com/rstiyer"] + - ["Michael Dähnert", "http://github.com/JaXt0r"] filename: LearnJava.java --- @@ -171,6 +172,29 @@ public class LearnJava { System.out.println(barString); System.out.println(bazString); + // String Building + // #1 - with plus operator + // That's the basic way to do it (optimized under the hood) + String plusConcatenated = "Strings can " + "be concatenated " + "via + operator."; + System.out.println(plusConcatenated); + // Output: Strings can be concatenated via + operator. + + // #2 - with StringBuilder + // This way doesn't create any intermediate strings. It just stores the string pieces, and ties them together + // when toString() is called. + // Hint: This class is not thread safe. A thread-safe alternative (with some impact on performance) is StringBuffer. + StringBuilder builderConcatenated = new StringBuilder(); + builderConcatenated.append("You "); + builderConcatenated.append("can use "); + builderConcatenated.append("the StringBuilder class."); + System.out.println(builderConcatenated.toString()); // only now is the string built + // Output: You can use the StringBuilder class. + + // #3 - with String formatter + // Another alternative way to create strings. Fast and readable. + String.format("%s may prefer %s.", "Or you", "String.format()"); + // Output: Or you may prefer String.format(). + // Arrays // The array size must be decided upon instantiation // The following formats work for declaring an array -- cgit v1.2.3 From e07de13721a6f434473839454fe161ed2cff3a6e Mon Sep 17 00:00:00 2001 From: Xuan-thi N Date: Wed, 29 Jun 2016 11:26:11 +0200 Subject: [fr/tmux] Tmux translated in French (#1861) * tmux article translated in French * Small typos * Added change suggestions --- fr-fr/tmux-fr.html.markdown | 261 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 fr-fr/tmux-fr.html.markdown diff --git a/fr-fr/tmux-fr.html.markdown b/fr-fr/tmux-fr.html.markdown new file mode 100644 index 00000000..d353af3b --- /dev/null +++ b/fr-fr/tmux-fr.html.markdown @@ -0,0 +1,261 @@ +--- +category: tool +tool: tmux +contributors: + - ["mdln", "https://github.com/mdln"] +translators: + - ["Xuan-thi Nguyen", "https://github.com/mellenguyen"] +filename: LearnTmux-fr.txt +lang: fr-fr +--- + + +[Tmux](http://tmux.sourceforge.net) est un multiplexeur de terminal: il permet +de créer plusieurs terminaux, accédés et contrôlés depuis un seul écran. Tmux +peut être détaché de l'écran tout en continuant de fonctionner en tâche de +fond, puis rattaché de nouveau. + + +``` + + tmux [command] # Exécute une commande + # 'tmux' sans commande créé une nouvelle session + + new # Créé une nouvelle session + -s "Session" # Créé une session nommée "Session" + -n "Window" # Créé une fenêtre nommée "Window" + -c "/dir" # Démarre dans le dossier cible "/dir" + + attach # S'attache à la dernière session ou la session disponible + -t "#" # S'attache à la session cible + -d # Détache la session des autres instances + + ls # Liste les sessions ouvertes + -a # Liste toutes les sessions ouvertes + + lsw # Liste les fenêtres de la session courante + -a # Liste toutes les fenêtres + -s # Liste toutes les fenêtres en session + + lsp # Liste les panels + -a # Liste tous les panels + -s # Liste tous les panels en session + -t # Liste tous les panels dans la cible + + kill-window # Tue la fenêtre courante + -t "#" # Tue la fenêtre cible + -a # Tue toutes les fenêtres + -a -t "#" # Tue toutes les fenêtres sauf la cible + + kill-session # Tue la session courante + -t "#" # Tue la session cible + -a # Tue toutes les sessions + -a -t "#" # Tue toutes les sessions sauf la cible + +``` + + +### Raccourcis clavier + +Afin de contrôler une session tmux attachée, on utilise une combinaison de +touches appelées 'Préfixe'. Elle doit être pressée afin d'utiliser les +raccourcis. + +``` +-------------------------------------------------------------------------------- + (C-b) = Ctrl + b # Combinaison 'Préfixe' requise pour utiliser les raccourcis + + (M-1) = Meta + 1 -ou- Alt + 1 +-------------------------------------------------------------------------------- + + ? # Liste tous les raccourcis + : # Entre dans l'invite de commande de tmux + r # Force la redéfinition du client attaché + c # Créé une nouvelle fenêtre + + ! # Sépare le panel courant de sa fenêtre + % # Sépare le panel courant en deux, gauche et droite + " # Sépare le panel courant en deux, haut et bas + + n # Changer vers la fenêtre suivante + p # Changer vers la fenêtre précédente + { # Echange le panel courant avec le panel précédent + } # Echange le panel courant avec le panel suivant + + s # Sélectionne une nouvelle session pour le client attaché + # de manière interactive + w # Choisi la fenêtre courante de manière interactive + 0 to 9 # Sélectionne la fenêtre de 0 à 9 + + d # Détache le client courant + D # Choisi un client à détacher + + & # Tue la fenêtre courante + x # Tue le panel courant + + Up, Down # Change vers le panel au dessus, en dessous, à gauche + Left, Right # ou à droite + + M-1 to M-5 # Arrange les panels: + # 1) égaliser sur l'horizontale + # 2) égaliser sur la verticale + # 3) panel principal en haut et le reste en bas + # de gauche à droite + # 4) panel principal à gauche et le reste à droite + # de haut en bas + # 5) "tiled" : égalise les panels + # sur la hauteur et la largeur + + C-Up, C-Down # Redimensionne le panel courant par pas de une cellule + C-Left, C-Right + + M-Up, M-Down # Redimensionne le panel courant par pas de cinq cellules + M-Left, M-Right + +``` + + +### Configuration de ~/.tmux.conf + +tmux.conf peut être utilisé pour fixer les options automatiquement au +démarrage, comme .vimrc ou init.el. + +``` +# Exemple de tmux.conf +# 2014.10 + + +### Général +########################################################################### + +# Active UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Limite de l'historique +set -g history-limit 2048 + +# Indice de début du nombre de panels +set -g base-index 1 + +# Souris +set-option -g mouse-select-pane on + +# Force le rechargement du fichier de configuration +unbind r +bind r source-file ~/.tmux.conf + + +### Raccourcis clavier +########################################################################### + +# Annule C-b en tant que préfixe par défaut +unbind C-b + +# Définit un nouveau préfixe par défaut +set-option -g prefix ` + +# Retourne à la fenêtre précédente quand le préfixe est pressé deux fois +bind C-a last-window +bind ` last-window + +# Permet d'échanger C-a et ` en utilisant F11/F12 +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` + +# Préférences de raccourcis clavier +setw -g mode-keys vi +set-option -g status-keys vi + +# Navigue entre les panels avec les raccourcis clavier de vim +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R + +# Navigation entre les fenêtres +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +# Commandes simples de séparation des panels +bind = split-window -h +bind - split-window -v +unbind '"' +unbind % + +# Active la session la plus imbriquée (en faisant de l'imbrication sous tmux) +# pour envoyer des commandes +bind a send-prefix + + +### Thème +########################################################################### + +# Palette de couleurs pour la barre de statuts +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +# Palette de couleurs pour les bordures des panels +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +# Palette de couleurs pour les messages +set-option -g message-fg black +set-option -g message-bg green + +# Palette de couleurs pour les fenêtres +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +# Notification +setw -g monitor-activity on +set -g visual-activity on +set-option -g bell-action any +set-option -g visual-bell off + +# Définir automatiquement des titres de fenêtres +set-option -g set-titles on +# Numéro de fenêtre, nom du programme, actif (ou non) +set-option -g set-titles-string '#H:#S.#I.#P #W #T' + +# Réglages de la barre de statuts +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" + +# Présente des indicateurs de performance dans la barre de statuts +# Recquiert https://github.com/thewtex/tmux-mem-cpu-load/ +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + + +### Références + +[Tmux | Home](http://tmux.sourceforge.net) + +[Page du manuel Tmux](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) + +[Montrer le pourcentage CPU/MEM dans la barre de statuts](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) + +[tmuxinator - Gère des sessions tmux complexes](https://github.com/tmuxinator/tmuxinator) -- cgit v1.2.3 From df4dbee36f5a3b9b63292a2346327f8b7d282a28 Mon Sep 17 00:00:00 2001 From: Xuan-thi N Date: Wed, 29 Jun 2016 11:26:53 +0200 Subject: [fr/ruby-ecosytem] Translated ruby-ecosytem article in French (#1857) * Translated ruby-ecosytem article in French * Added change suggestions --- fr-fr/ruby-ecosystem-fr.html.markdown | 154 ++++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 fr-fr/ruby-ecosystem-fr.html.markdown diff --git a/fr-fr/ruby-ecosystem-fr.html.markdown b/fr-fr/ruby-ecosystem-fr.html.markdown new file mode 100644 index 00000000..9b52069a --- /dev/null +++ b/fr-fr/ruby-ecosystem-fr.html.markdown @@ -0,0 +1,154 @@ +--- +category: tool +tool: ruby ecosystem +contributors: + - ["Jon Smock", "http://github.com/jonsmock"] + - ["Rafal Chmiel", "http://github.com/rafalchmiel"] +translators: + - ["Xuan-thi Nguyen", "http://github.com/mellenguyen"] +lang: fr-fr + +--- + +Les gens utilisant Ruby adoptent généralement un gestionnaire pour installer +différentes versions de Ruby, gérer leurs paquets (ou gems), et gérer les +dépendances des gems. + +## Ruby Managers + +Quelques plateformes possèdent Ruby pré-installé ou disponible en tant que +paquet. La plupart des rubyists ne les utilisent pas, ou si c'est le cas, ne +les utilise que pour faire démarrer un autre installateur ou implémentation de +Ruby. Les rubyists tendent plutôt à installer un manager Ruby pour installer +et changer entre les différentes et nombreuses versions de Ruby et les +environnements de leurs projets Ruby. + +Les gestionnaires d'environnement Ruby les plus populaires sont : + +* [RVM](https://rvm.io/) - Installe et navigue entre les rubies. RVM possède + églement le concept des gemsets pour isoler les environnements de projets + complètement. +* [ruby-build](https://github.com/sstephenson/ruby-build) - Installe seulement + les rubies. Utilisez-le pour un contrôle plus fin des installations des + rubies. +* [rbenv](https://github.com/sstephenson/rbenv) - Navigue seulement entre les + rubies. Utilisé avec ruby-build. Utilisez-le pour un contrôle plus fin des + chargements des rubies. +* [chruby](https://github.com/postmodern/chruby) - Navigue seulement entre les + rubies. Similaire à rbenv. Neutre sur comment les rubies sont installés. + +## Versions de Ruby + +Ruby a été créé par Yukihiro "Matz" Matsumoto, qui reste quelque peu un +[BDFL](https://fr.wikipedia.org/wiki/Benevolent_Dictator_for_Life), bien que +cela soit récemment en changement. Jusqu'à la standardisation du langage en +2011, l'implémentation de référence de Ruby était appelé MRI (Matz' Reference +Implementation). + +Les trois versions majeures de Ruby actuellement utilisées sont : + +* 2.0.0 - Sortie en février 2013. La plupart des librairies et frameworks + gèrent la versions 2.0.0. +* 1.9.3 - Sortie en octobre 2011. Il s'agit de la version que la majorité des + rubyists utilisent actuellement. [Fin de vie](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) +* 1.8.7 - Sortie en juin 2006. [Fin de vie](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). + +Les changements entre 1.8.7 à 1.9.x sont bien plus grands qu'entre 1.9.3 +jusqu'à 2.0.0. Par exemple, les versions 1.9 ont introduit le support des +encodages et d'une VM bytecode ([YARV](https://fr.wikipedia.org/wiki/YARV)). +Il y a toujours des projets sur 1.8.7, mais ils deviennent minoritaires, étant +donné que la majorité de la communauté a migré vers au moins 1.9.2 ou 1.9.3. + +## Implémentations Ruby + +L'écosystème Ruby comprend de nombreuses implémentations de Ruby, chacune avec +des points forts uniques et différents degrés de compatibilité. Les différentes +implémentations sont écrites dans différents languages. +Chaque implémentation a des "hooks" et des fonctionnalités spécifiques, elles +exécutent cependant très bien des fichiers Ruby classiques. +Par exemple, JRuby est écrit en Java, mais vous n'avez pas besoin de connaître +le Java pour l'utiliser. + +Très mature/compatible: + +* [MRI](https://github.com/ruby/ruby) - Ecrite en C, c'est l'implémentation de + référence de Ruby. Elle est par définition 100% compatible (avec elle-même). + Tous les autres rubies maintiennent la compatibilité avec MRI + (voir [RubySpec](#rubyspec) à la suite). +* [JRuby](http://jruby.org/) - Écrite en Java et Ruby, cette robuste + implémentation est assez rapide. + La force de JRuby réside surtout sur l'interopérabilité JVM/Java, faisant + levier sur des outils JVM, des projets et des langages existants. +* [Rubinius](http://rubini.us/) - Ecrite principalement en Ruby avec une VM + bytecode en C++. Egalement mature et rapide. Etant donné qu'elle est + implémentée en Ruby, elle couvre beaucoup de fonctionnalités de la + VM dans Ruby. + +Mpyennement mature/compatible: + +* [Maglev](http://maglev.github.io/) - Basée sur Gemstone, une VM Smalltalk. + Smalltalk possède quelques outils impressionnants, et ce projet tente + de les apporter dans le développement Ruby. +* [RubyMotion](http://www.rubymotion.com/) - Ruby pour développement iOS. +* [Opal](http://opalrb.org/) - Compile le Ruby en Javascript + +Les implémentations de Ruby peuvent avoir leurs propres numéros de versions, +mais elles ciblent toujours une versions spéficique de MRI pour la +compatibilité. +Beaucoup d'implémentations ont la capacité d'entrer dans différents modes +(par exemple, la version 1.8 ou 1.9) afin de spécifier quelle version de MRI +cibler. + +Une liste non exhaustive d'implémentations peut être trouvée [ici (EN)](https://github.com/cogitator/ruby-implementations/wiki/List-of-Ruby-implementations). + +## RubySpec + +La plupart des implémentations Ruby s'appuient fortement sur [RubySpec](http://rubyspec.org/). +Ruby n'a pas de spécification officielle, c'est pourquoi la commaunité a écrit +des spécifications exécutables en Ruby pour tester la compatibilité de leur +implémentation avec MRI. + +## RubyGems + +[RubyGems](http://rubygems.org/) est un gestionnaire de paquets communautaire +pour Ruby. +RubyGems est livré avec Ruby, il n'y a donc pas besoin de le télécharger +séparément. + +Les paquets Ruby sont appelés des "gems", et peuvent être hébergés par la +communauté à RubyGems.org. Chaque gem contient son code source et quelques +métadatas, includant des choses comme la version, les dépendances, +l(es) auteur(s) et la/les licence(s). + +## Bundler + +[Bundler](http://bundler.io/) est un résolveur de dépendances des gems. Il +utilise le Gemfile d'un projet ppur trouver les dépendances, et récupère +ensuite les dépendances de ces dépendances récursivement. Il déroule cet +algorithme jusqu'à ce que toutes les dépendances soient résolues et +téléchargées, ou s'arrête si un conflit est trouvé. + +Bundler lèvera une erreur s'il trouve des conflits de dépendances. Par exemple, +si la gem A recquiert la version 3 ou plus de gem Z, mais que gem B recquiert +seulement la version 2, Bundler vous notifiera ce conflict. Cela devient +extrêmement utile, étant donné que beaucoup de gems font référence à d'autres +gems (qui se réfèrent à d'autres gems), ce qui peut former un large graphe de +dépendance à résoudre. + +# Les tests + +Tester fait partie intégrante de la culture Ruby. Ruby fournit son propre +framework de tests unitaires appelé minitest (ou TestUnit pour Ruby +version 1.8.x). Il existe beaucoup de librairies de tests avec des buts +différents. + +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - Framework de tests intégré de Ruby version 1.8 style "Unit" +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - Framework de tests intégré de Ruby version 1.9/2.0 +* [RSpec](http://rspec.info/) - Un framework de tests qui se focalise sur l'expressivité +* [Cucumber](http://cukes.info/) - Un framework de tests BDD ([behaviour-driven development](https://fr.wikipedia.org/wiki/Behavior_driven_development)) qui parse les tests formatés de Gherkin. + +## Soyez gentil + +La communauté Ruby est fière d'être une communauté ouverte, riche et +accueillante. Matz lui-même est extrêmement sociable, et la générosité des +rubyists est généralement remarquable. -- cgit v1.2.3 From a7eed36c1da2a16c7ced96e4d5fb0fb03bd94716 Mon Sep 17 00:00:00 2001 From: ven Date: Sat, 2 Jul 2016 12:43:15 +0200 Subject: fix #2295 --- elm.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/elm.html.markdown b/elm.html.markdown index fa10671f..dab2ab34 100644 --- a/elm.html.markdown +++ b/elm.html.markdown @@ -156,6 +156,7 @@ List.map (\a -> a * 2) [1..4] -- [2, 4, 6, 8] -- You can pattern match in function definitions when there's only one case. -- This function takes one tuple rather than two arguments. +-- This is the way you'll usually unpack/extract values from tuples. area (width, height) = width * height -- cgit v1.2.3 From 5dee671bfef8c4ab253a1992f03176b72948f226 Mon Sep 17 00:00:00 2001 From: Edmilson Lima Date: Sat, 2 Jul 2016 11:02:38 -0300 Subject: Update Dict and Set Syntax (#2296) --- julia.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 23d834f4..5b3f6fd8 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -255,7 +255,7 @@ e, d = d, e # => (5,4) # d is now 5 and e is now 4 empty_dict = Dict() # => Dict{Any,Any}() # You can create a dictionary using a literal -filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] +filled_dict = Dict("one"=> 1, "two"=> 2, "three"=> 3) # => Dict{ASCIIString,Int64} # Look up values with [] @@ -305,7 +305,7 @@ in(10, filled_set) # => false other_set = Set([3, 4, 5, 6]) # => Set{Int64}(6,4,5,3) intersect(filled_set, other_set) # => Set{Int64}(3,4,5) union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6) -setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) +setdiff(Set([1,2,3,4]),Set([2,3,5])) # => Set{Int64}(1,4) #################################################### @@ -346,7 +346,7 @@ end # cat is a mammal # mouse is a mammal -for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] +for a in Dict("dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal") println("$(a[1]) is a $(a[2])") end # prints: @@ -354,7 +354,7 @@ end # cat is a mammal # mouse is a mammal -for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] +for (k,v) in Dict("dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal") println("$k is a $v") end # prints: @@ -445,7 +445,7 @@ end # You can define functions that take keyword arguments function keyword_args(;k1=4,name2="hello") # note the ; - return ["k1"=>k1,"name2"=>name2] + return Dict("k1"=>k1,"name2"=>name2) end keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] -- cgit v1.2.3 From e053806775d18e14bb5de2adcdf8369d6566ce45 Mon Sep 17 00:00:00 2001 From: "J. Ryan Rembert" Date: Sun, 3 Jul 2016 01:47:57 -0700 Subject: [python/en] Set, dict, and generator comprehensions (#2298) * Add set and dict comprehensions for python 2 and 3 * Clean up formatting and generator explanation * Include documentation for generator comprehensions --- python.html.markdown | 50 ++++++++++++++++++++++++++++++++------------------ python3.html.markdown | 38 ++++++++++++++++++++++++-------------- 2 files changed, 56 insertions(+), 32 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 6c9da9a9..55f56071 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -8,21 +8,21 @@ contributors: filename: learnpython.py --- -Python was created by Guido Van Rossum in the early 90s. It is now one of the -most popular languages in existence. I fell in love with Python for its +Python was created by Guido Van Rossum in the early 90s. It is now one of the +most popular languages in existence. I fell in love with Python for its syntactic clarity. It's basically executable pseudocode. -Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) +Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] -Note: This article applies to Python 2.7 specifically, but should be applicable -to Python 2.x. Python 2.7 is reaching end of life and will stop being -maintained in 2020, it is though recommended to start learning Python with +Note: This article applies to Python 2.7 specifically, but should be applicable +to Python 2.x. Python 2.7 is reaching end of life and will stop being +maintained in 2020, it is though recommended to start learning Python with Python 3. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). -It is also possible to write Python code which is compatible with Python 2.7 +It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same time, using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports -allow you to write Python 3 code that will run on Python 2, so check out the +allow you to write Python 3 code that will run on Python 2, so check out the Python 3 tutorial. ```python @@ -549,6 +549,10 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] +# You can construct set and dict comprehensions as well. +{x for x in 'abcddeef' if x in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + #################################################### ## 5. Classes @@ -668,10 +672,10 @@ import math dir(math) # If you have a Python script named math.py in the same -# folder as your current script, the file math.py will -# be loaded instead of the built-in Python module. +# folder as your current script, the file math.py will +# be loaded instead of the built-in Python module. # This happens because the local folder has priority -# over Python's built-in libraries. +# over Python's built-in libraries. #################################################### @@ -679,44 +683,54 @@ dir(math) #################################################### # Generators -# A generator "generates" values as they are requested instead of storing +# A generator "generates" values as they are requested instead of storing # everything up front -# The following method (*NOT* a generator) will double all values and store it +# The following method (*NOT* a generator) will double all values and store it # in `double_arr`. For large size of iterables, that might get huge! def double_numbers(iterable): double_arr = [] for i in iterable: double_arr.append(i + i) -# Running the following would mean we'll double all values first and return all +# Running the following would mean we'll double all values first and return all # of them back to be checked by our condition for value in double_numbers(range(1000000)): # `test_non_generator` print value if value > 5: break -# We could instead use a generator to "generate" the doubled value as the item +# We could instead use a generator to "generate" the doubled value as the item # is being requested def double_numbers_generator(iterable): for i in iterable: yield i + i # Running the same code as before, but with a generator, now allows us to iterate -# over the values and doubling them one by one as they are being consumed by -# our logic. Hence as soon as we see a value > 5, we stop break out of the +# over the values and doubling them one by one as they are being consumed by +# our logic. Hence as soon as we see a value > 5, we break out of the # loop and don't need to double most of the values sent in (MUCH FASTER!) for value in double_numbers_generator(xrange(1000000)): # `test_generator` print value if value > 5: break -# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`? +# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`? # Just as `double_numbers_generator` is the generator version of `double_numbers` # We have `xrange` as the generator version of `range` # `range` would return back and array with 1000000 values for us to use # `xrange` would generate 1000000 values for us as we request / iterate over those items +# Just as you can create a list comprehension, you can create generator +# comprehensions as well. +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 to console/terminal + +# You can also cast a generator comprehension directly to a list. +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] # Decorators diff --git a/python3.html.markdown b/python3.html.markdown index 7f3702e6..6b3486a6 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -601,6 +601,10 @@ list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] +# You can construct set and dict comprehensions as well. +{x for x in 'abcddeef' if x in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + #################################################### ## 5. Modules @@ -816,7 +820,7 @@ if __name__ == '__main__': sup.age = 100 print(sup.age) - # Inherited attribute from 2nd ancestor whose default value was overriden + # Inherited attribute from 2nd ancestor whose default value was overridden. print('Can I fly? ' + str(sup.fly)) @@ -825,29 +829,35 @@ if __name__ == '__main__': ## 7. Advanced #################################################### -# Generators help you make lazy code +# Generators help you make lazy code. def double_numbers(iterable): for i in iterable: yield i + i -# A generator creates values on the fly. -# Instead of generating and returning all values at once it creates one in each -# iteration. This means values bigger than 15 wont be processed in -# double_numbers. -# We use a trailing underscore in variable names when we want to use a name that -# would normally collide with a python keyword -range_ = range(1, 900000000) -# will double all numbers until a result >=30 found -for i in double_numbers(range_): +# Generators are memory-efficient because they only load the data needed to +# process the next value in the iterable. This allows them to perform +# operations on otherwise prohibitively large value ranges. +# NOTE: `range` replaces `xrange` in Python 3. +for i in double_numbers(range(1, 900000000)): # `range` is a generator. print(i) if i >= 30: break +# Just as you can create a list comprehension, you can create generator +# comprehensions as well. +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 to console/terminal + +# You can also cast a generator comprehension directly to a list. +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + # Decorators -# in this example beg wraps say -# Beg will call say. If say_please is True then it will change the returned -# message +# In this example `beg` wraps `say`. If say_please is True then it +# will change the returned message. from functools import wraps -- cgit v1.2.3 From 1cab710b058b9a84bf13913263c26968098d3b10 Mon Sep 17 00:00:00 2001 From: ven Date: Wed, 6 Jul 2016 12:09:20 +0200 Subject: Attempt at #2299 --- ro-ro/bf-ro.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ro-ro/bf-ro.html.markdown b/ro-ro/bf-ro.html.markdown index 61b555ed..686dd39d 100644 --- a/ro-ro/bf-ro.html.markdown +++ b/ro-ro/bf-ro.html.markdown @@ -1,10 +1,11 @@ --- -language: brainfuck +language: bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] translators: - ["Petru Dimitriu", "http://petru-dimitriu.github.io"] +filename: bf-ro.html lang: ro-ro --- @@ -87,4 +88,4 @@ Așadar acesta este limbajul brainfuck. Nu e atât de greu, nu? Pentru amuzament, puteți să scrieți propriile dumneavoastră limbaje, sau puteți scrie un interpretor pentru brainfuck într-un alt limbaj. Interpretorul este destul de ușor de implementat, dar dacă sunteți masochist, încercați -să implementați un interpretor de brainfuck… în brainfuck. \ No newline at end of file +să implementați un interpretor de brainfuck… în brainfuck. -- cgit v1.2.3 From b8e496eba15314e581c1280b1f55cd6e56740956 Mon Sep 17 00:00:00 2001 From: Nimit Shah Date: Fri, 8 Jul 2016 15:03:11 +0530 Subject: [Java/en] Adding a reference for treemap (#2300) * Adding a reference for treemap Adding reference for a treemap * Removing my name from the contributors list Removing my name from the contributors list as it requires a significant contribution to add my name to it. --- java.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index f65c484e..1f7d4115 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -232,6 +232,9 @@ public class LearnJava { // interface. This allows the execution time of basic // operations, such as get and insert element, to remain // constant even for large sets. + // TreeMap - This class is a sorted tree structure. It implements a red + // black tree and sorts the entries based on the key value or + // the comparator provided while creating the object /////////////////////////////////////// // Operators -- cgit v1.2.3 From 36ab227827c371721066ebfbc954ce3eaeaf2aa3 Mon Sep 17 00:00:00 2001 From: Nimit Shah Date: Fri, 8 Jul 2016 23:42:03 +0530 Subject: [CSS/en] Adding border related styleguides (#2301) * Adding border related styleguides Adding border related styleguides. Most of the modern designs have borders for their elements. * Spacing the comments like the rest of the file --- css.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/css.html.markdown b/css.html.markdown index 5dae06ca..fc07fce4 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -169,6 +169,13 @@ selector { color: transparent; /* equivalent to setting the alpha to 0 */ color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */ color: hsla(0, 100%, 50%, 0.3); /* as hsl percentages with alpha */ + + /* Borders */ + border-width:5px; + border-style:solid; + border-color:red; /* similar to how background-color is set */ + border: 5px solid red; /* this is a short hand approach for the same */ + border-radius:20px; /* this is a CSS3 property */ /* Images as backgrounds of elements */ background-image: url(/img-path/img.jpg); /* quotes inside url() optional */ -- cgit v1.2.3 From f1ac2a78aeca0c26f190dc2f79f4b3d29fe74b9f Mon Sep 17 00:00:00 2001 From: Ahmad Zafrullah Date: Sun, 10 Jul 2016 02:00:47 +0800 Subject: [java/id-id] ID translation (#2304) --- id-id/java-id.html.markdown | 801 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 801 insertions(+) create mode 100644 id-id/java-id.html.markdown diff --git a/id-id/java-id.html.markdown b/id-id/java-id.html.markdown new file mode 100644 index 00000000..a5455952 --- /dev/null +++ b/id-id/java-id.html.markdown @@ -0,0 +1,801 @@ +--- +language: java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Jakukyo Friel", "http://weakish.github.io"] + - ["Madison Dickson", "http://github.com/mix3d"] + - ["Simon Morgan", "http://sjm.io/"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] + - ["Rachel Stiyer", "https://github.com/rstiyer"] +filename: LearnJava-id.java +translators: + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] +lang: id-id +--- + +Java adalah bahasa pemrograman yang memiliki tujuan umum dan berorientasi kelas dan objek. +[Baca lebih lanjut.](http://docs.oracle.com/javase/tutorial/java/) + +```java +// Komentar satu baris diawali dengan // (dua garis miring) +/* +Ini adalah contoh komentar banyak-baris. +*/ +/** +Ini adalah contoh komentar JavaDoc. Digunakan untuk mendeskripsikan sebuah kelas, +atau beberapa sifat dari kelas tersebut. +*/ + +// Menyertakan kelas ArrayList dalam paket java.util +import java.util.ArrayList; +// Menyertakan semua kelas yang ada dalam paket java.security +import java.security.*; + +// Setiap dokumen .java sebuah kelas publik dengan nama yang sama dengan nama kelas. +public class BelajarJava { + + // Untuk menjalankan program java, program harus memiliki sebuah method utama (main) sebagai awalan. + public static void main (String[] args) { + + // System.out.println() digunakan untuk menampilkan satu baris teks. + System.out.println("Halo Dunia!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // System.out.print() hanya menampilkan teks tanpa baris baru. + System.out.print("Halo "); + System.out.print("Dunia"); + + // System.out.printf() memudahkan dalam mengatur format penampilan. + System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159 + + /////////////////////////////////////// + // Variabel + /////////////////////////////////////// + + /* + * Deklarasi Variabel + */ + // Deklarasi variabel menggunakan format + int nilai; + // Deklarasi banyak variabel menggunakan format yang sama , , + int nilai1, nilai2, nilai3; + + /* + * Inisialisasi Variabel + */ + + // Inisialisasi sebuah variabel menggunakan = + int nilai = 1; + // Inisialisasi banyak variabel menggunakan format yang sama , , = + int nilai1, nilai2, nilai3; + nilai1 = nilai2 = nilai3 = 1; + + /* + * Tipe Variabel + */ + // Byte - 8 bit signed untuk bilangan bulat komplemen 2 + // (-128 <= byte <= 127) + byte nilaiByte = 100; + + // Short - 8 bit signed untuk bilangan bulat komplemen 2 + // (-32,768 <= short <= 32,767) + short nilaiShort = 10000; + + // Integer - 32 bit signed untuk bilangan bulat komplemen 2 + // (-2,147,483,648 <= int <= 2,147,483,647) + int nilaiInt = 1; + + // Long - 64 bit signed untuk bilangan bulat komplemen 2 + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long nilaiLong = 100000L; + // Karakter "L" pada akhir nilai menyatakan tipe Long; + // selainnya akan dianggap sebagai nilai bilangan bulat. + + // Catatan: Java tidak memiliki tipe unsigned. + + // Float - Presisi-satu 32-bit standar IEEE 754 untuk Floating Point + // 2^-149 <= float <= (2-2^-23) * 2^127 + float nilaiFloat = 234.5f; + // Karakter "f" atau "F" pada akhir nilai menyatakan tipe Float; + // selainnya akan dianggap sebagai nilai double. + + // Double - Presisi-dua 64-bit standar IEEE 754 untuk Floating Point + // 2^-1074 <= x <= (2-2^-52) * 2^1023 + double nilaiDouble = 123.4; + + // Boolean - true & false + boolean nilaiBoolean = true; + boolean nilaiBoolean = false; + + // Char - Sebuah karakter Unicode 16-bit + char nilaiChar = 'A'; + + // Variabel "final" tidak dapat di-set kembali nilainya pada objek lain, + final int WAKTU_SAYA_BEKERJA_TIAP_MINGGU = 9001; + // tapi dapat dilakukan inisialisasi diwaktu yang lain. + final double E; + E = 2.71828; + + + // BigInteger - Bilangan bulat yang memiliki presisi dinamis + // + // BigInteger adalah tipe data yang memungkinkan pembuat program untuk memanipulasi + // bilangan bulat lebih panjang dari 64-bit. Bilangan bulat tersebut tersimpan dalam + // bentuk kumpulan byte (array) dan dimanipulasi menggunakan fungsi yang sudah tersedia + // pada BigInteger + // + // BigInteger dapat diinisialisasi menggunakan kumpulan byte atau teks. + + BigInteger nilaiBigInteger = new BigInteger(kumpulanByte); + + + // BigDecimal - Bilangan signed desimal yang memiliki presisi dinamis + // + // Tipe BigDecimal memiliki dua bagian: sebuah bilangan bulat dengan nilai presisi + // dinamis tanpa skala dan sebuah bilangan bulat skala 32-bit. + + // BigDecimal memungkinkan pembuat program untuk memegang kontrol penuh + // terhadap batas desimal. BigDecimal baik digunakan untuk nilai tukar mata uang + // dimana sangat mementingkan presisi nilai desimal. + // + // BigDecimal dapat diinisialisasi dengan int, long, double, String, + // atau dengan melakukan inisialisasi nilai tanpa skala (BigInteger) + // dan nilai dengan skala (int). + + BigDecimal nilaiBigDecimal = new BigDecimal(nilaiBigInteger, nilaiInt); + + // Perlu diperhatikan konstruktor yang digunakan apakah float atau double + // karena dapat mengakibatkan ketidak-akurasian float/double yang akan digunakan + // dalam BigDecimal. Sebaiknya gunakan nilai String pada konstruktor + // jika membutuhkan nilai pasti. + + BigDecimal sepuluhSen = new BigDecimal("0.1"); + + + // Strings + String nilaiString1 = "Ini adalah contoh String!"; + + // Karakter \n berfungsi untuk membuat baris baru + String nilaiString2 = "Menampilkan baris baru?\nTidak masalah!"; + // Karakter \t berfungsi untuk membuat tab antar karakter + String nilaiString3 = "Ingin menambahkan sebuah tab?\tTidak masalah!"; + System.out.println(nilaiString1); + System.out.println(nilaiString2); + System.out.println(nilaiString3); + + // Larik (array) + // Ukuran array harus ditentukan ketika instansiasi + // Format berikut adalah beberapa cara deklarasi array + // [] = new []; + // [] = new []; + int[] barisAngka = new int[10]; + String[] barisString = new String[1]; + boolean barisBoolean[] = new boolean[100]; + + // Cara lain untuk mendeklarasikan dan menginisialisasi sebuah array + int[] y = {9000, 1000, 1337}; + String nama[] = {"Andi", "Budi", "Agus"}; + boolean bools[] = new boolean[] {true, false, false}; + + // Indeks sebuah array - Mengakses sebuah elemen + System.out.println("barisAngka @ 0: " + barisAngka[0]); + + // Array menggunakan indeks 0 yang tetap. + barisAngka[1] = 1; + System.out.println("barisAngka @ 1: " + barisAngka[1]); // => 1 + + // Lainnya yang perlu diketahui + // ArrayLists - Sama seperti array biasa, namum penggunaannya sudah ditentukan, + // dan ukurannya dapat berubah-ubah. + // LinkedLists - Implementasi dari doubly-linked list. Semua operasi yang digunakan + // hampir sama dengan operasi yang dimiliki oleh sebuah doubly-linked list. + // Maps - Sebuah kumpulan objek yang menyatakan hubungan antara kunci dan nilai. Map merupakan + // sebuah interface sehingga tidak dapat diinstansiasi. Jenis kunci dan nilai yang digunakan + // pada Map harus spesifik pada saat instansiasi ketika diimplementasikan pada sebuah kelas. + // Setiap kunci hanya memiliki sebuah nilai, dan hanya muncul sekali. + // HashMaps - Kelas ini menggunakan tabel-hash untuk mengimplementasikan interface Map. + // Hal ini memungkinkan waktu eksekusi ketika melakukan operasi dasar (mengakses + // dan menambahkan elemen) menjadi konstan, meskipun memiliki banyak set data. + + /////////////////////////////////////// + // Operator + /////////////////////////////////////// + System.out.println("\n->Operator"); + + int i1 = 1, i2 = 2; // Cara singkat untuk deklarasi banyak nilai + + // Kemudahan dalam artimatika + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int menghasilkan int juga) + System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 + + // Modulus + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Operator Perbandingan + System.out.println("3 == 2? " + (3 == 2)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // Operator Boolean + System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false + System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true + System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true + + // Operator Bitwise + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed/Arithmetic right shift + >>> Unsigned/Logical right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR + */ + + // Peningkatan + int i = 0; + System.out.println("\n->Pengurangan/Peningkatan"); + // Operator ++ dan -- masing-masing melakukan peningkatan dan penurunan 1 nilai. + // Jika diletakkan sebelum variabel, maka akan di tambah/kurang 1 sebelum dilakukan perintah lainnya; + // jika setelah variabel, maka akan ditambah/kurang 1 setelah dilakukan perintah lainnya; + System.out.println(i++); // i = 1, prints 0 (peningkatan setelahnya) + System.out.println(++i); // i = 2, prints 2 (peningkatan sebelumnya) + System.out.println(i--); // i = 1, prints 2 (pengurangan setelahnya) + System.out.println(--i); // i = 0, prints 0 (pengurangan sebelumnya) + + /////////////////////////////////////// + // Struktur Kontrol + /////////////////////////////////////// + System.out.println("\n->Struktur Kontrol"); + + // Perintah "if" hampir sama dengan bahasa C + int j = 10; + if (j == 10) { + System.out.println("Saya ditampilkan"); + } else if (j > 10) { + System.out.println("Saya tidak ditampilkan"); + } else { + System.out.println("Saya juga tidak ditampilkan"); + } + + // Perulangan "while" + int fooWhile = 0; + while(fooWhile < 100) { + System.out.println(fooWhile); + // Tingkatkan penghitung + // 100 kali iterasi, fooWhile 0,1,3,...,99 + fooWhile++; + } + System.out.println("Nilai fooWhile: " + fooWhile); + + // Perulangan "do...while" + int fooDoWhile = 0; + do { + System.out.println(fooDoWhile); + // Tingkatkan penghitung + // 99 kali iterasi, fooDoWhile 0->99 + fooDoWhile++; + } while(fooDoWhile < 100); + System.out.println("Nilai fooDoWhile: " + fooDoWhile); + + // Perulangan "for" + // Struktur perulangan "for" => for(; ; ) + for (int fooFor = 0; fooFor < 10; fooFor++) { + System.out.println(fooFor); + // 10 kali iterasi, foofor 0-9 + } + System.out.println("Nilai fooFor: " + fooFor); + + // Perulangan "for" bertingkat dengan label "exit" + outer: + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // Menghentikan semua perulangan, tidak hanya perulangan bagian dalam saja + } + } + } + + // Perulangan "for each" + // Perulangan "for" juga dapat melakukan iterasi terhadap larik (array) dari objek + // yang mana mengimplementasikan interface Ieterable. + int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + // Struktur perulangan "for each" => for ( : ) + // dibaca: setiap elemen dalam iterable + // catatan: tipe objek harus sama dengan tipe iterable + + for (int bar : fooList) { + System.out.println(bar); + // Melakukan interasi sebanyak 9 kali dan menampilkan 1-9 tiap baris + } + + // "switch case" + // "switch" dapat digunakan pada byte, short, char, dan tipe data bilangan bulat (int). + // "switch" juga dapat digunakan pada tipe "enum" (dijelaskan nanti), kelas String, + // dan beberapa kelas khusus yang mengandung tipe data primitif: + // Character, Byte, Short, dan Integer. + int bulan = 3; + String bulanString; + switch (bulan) { + case 1: bulanString = "Januari"; + break; + case 2: bulanString = "Februari"; + break; + case 3: bulanString = "Maret"; + break; + default: bulanString = "Bulan lainnya"; + break; + } + System.out.println("Hasil switch case: " + bulanString); + + // Mulai dari Java 7 keatas, "switch" memiliki format: + String jawabanSaya = "mungkin"; + switch(jawabanSaya) { + case "ya": + System.out.println("Anda menjawab ya."); + break; + case "tidak": + System.out.println("Anda menjawab tidak."); + break; + case "mungkin": + System.out.println("Anda menjawab mungkin."); + break; + default: + System.out.println("Anda menjawab " + jawabanSaya); + break; + } + + // Pengkondisian dengan cara singkat + // Karakter '?' dapat digunakan untuk penilaian atau logika secara cepat antara dua pernyataan. + // Dibaca "Jika (pernyataan) adalah benar, gunakan , sisanya gunakan + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println(bar); // Menampilkan A, karena pernyataannya benar + + + //////////////////////////////////////// + // Konversi Data dan Tipe Data (Typecasting) + //////////////////////////////////////// + + // Konversi Data + + // Konversi String ke Integer + Integer.parseInt("123"); // menghasilkan nilai versi Integer dari "123" + + // Konversi Integer ke String + Integer.toString(123); // menghasilkan nilai versi String dari 123 + + // Untuk konversi lainnya silakan coba kelas berikut: + // Double + // Long + // String + + // Typecasting + // Objek dalam Java juga dapat dikonversi, banyak penjelasan dan aturan + // dengan beberapa konsep sederhana. Silakan cek di alamat berikut: + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Kelas dan Fungsi + /////////////////////////////////////// + + System.out.println("\n->Kelas & Fungsi"); + + // (penjelasan mengenai kelas "Sepeda" ada dibawah) + + // Gunakan "new" untuk melakukan instansiasi pada kelas + Sepeda laju = new Sepeda(); + + // Memanggil method objek + laju.tambahKecepatan(3); // Dapat juga digunakan "setter" dan "getter" method + laju.setIrama(100); + + // Method "toString()" menghasilkan representasi string dari objek. + System.out.println("informasi jalur: " + laju.toString()); + + // Dua Pasang Inisialisasi + // Bahasa Java tidak memiliki sintaks untuk membuat koleksi dari "static" sekaligus + // dengan mudah, kecuali dengan cara berikut: + + private static final Set NEGARA = new HashSet(); + static { + validCodes.add("INDONESIA"); + validCodes.add("MALAYSIA"); + validCodes.add("SINGAPURA"); + } + + // Terdapat cara yang baik untuk menulis skrip dengan mudah, + // dengan menggunakan Dua-Kurung Kurawal Inisialisasi (Double Brace Initialization) + + private static final Set NEGARA = new HashSet() {{ + add("INDONESIA"); + add("MALAYSIA"); + add("SINGAPURA"); + }} + + // Kurung kurawal yang pertama membuat sebuah AnonymousInnerClas + // dan kurung kurawal yang kedua mendeklarasikan instance dari blok + // inisialisasi. Blok ini kemudian dipanggil ketika InnerClass dibentuk. + // Cara ini tidak hanya berfungsi pada koleksi data, juga dapat digunakan + // pada semua kelas bukan-"final". + + } // Akhir dari method utama +} // Akhir dari kelas BelajarJava + + +// Kelas bukan-"public" lainnya dapat dimasukkan kedalam satu dokumen .java, +// namun tidak dianjurkan, sebaiknya memisahkan menjadi beberapa dokumen terpisah. + +// Sintaks pendeklarasian kelas: +// class { +// // isi data, konstruktor, dan fungsi. +// // dalam Java, fungsi biasa disebut juga "method" +// } + +class Sepeda { + + // Variabel dari kelas Sepeda + public int irama; // Public: dapat diakses dari manapun + private int kecepatan; // Private: hanya dapat diakses dari dalam kelas + protected int rodaGigi; // Protected: dapat diakses dari dalam kelas dan turunan kelas + String nama; // Default: hanya dapat diakses kelas yang berada dalam paket yang sama + + static String namaKelas; // Variabel "static" + + // Blok Static + // Java tidak memiliki implementasi untuk konstruktor "static", namun + // memiliki blok status yang dapat digunakan untuk inisialisasi variabel + // dalam kelas (variabel "static"). + // Blok ini akan dipanggil secara otomatis ketika kelas dijalankan. + static { + namaKelas = "Sepeda"; + } + + // Konstruktor adalah salah satu cara untuk membuat kelas + // Ini adalah bagian konstruktor + public Sepeda() { + // Dapat juga dipanggil konstruktor lainnya: + // this(1, 50, 5, "Bontrager"); + rodaGigi = 1; + irama = 50; + kecepatan = 5; + nama = "Bontrager"; + } + + // Ini adalah bagian konstruktor yang menggunakan argumen (parameter) + public Sepeda(int iramaAwal, int kecepatanAwal, int rodaGigiAwal, + String nama) { + this.rodaGigi = rodaGigiAwal; + this.irama = iramaAwal; + this.kecepatan = kecepatanAwal; + this.nama = nama; + } + + // Sintaks untuk method: + // () + + // Kelas Java terkadang mengimplementasikan "getters" dan "setters" untuk data. + + // Sintaks untuk deklarasi method: + // () + public int getIrama() { + return irama; + } + + // Tipe "void" tidak memiliki kembalian (return) nilai + public void setIrama(int nilaiBaru) { + irama = nilaiBaru; + } + + public void setRodaGigi(int nilaiBaru) { + rodaGigi = nilaiBaru; + } + + public void tambahKecepatan(int nilaiTambahan) { + kecepatan += nilaiTambahan; + } + + public void kurangiKecepatan(int nilaiPengurangan) { + kecepatan -= nilaiPengurangan; + } + + public void setNama(String namaBaru) { + nama = namaBaru; + } + + public String getNama() { + return nama; + } + + // Method untuk menampilkan nilai dari tiap atribut yang dimiliki objek Sepeda. + @Override // Diturunkan dari kelas "Object" (Pustaka Java). + public String toString() { + return "roda gigi: " + rodaGigi + " irama: " + irama + " kecepatan: " + kecepatan + + " nama: " + nama; + } +} // akhir dari kelas Sepeda + +// PennyFarthing adalah kelas turunan dari Sepeda +class PennyFarthing extends Sepeda { + // (Penny Farthings adalah sepeda dengan roda depan yang besar, + // dan tidak memiliki roda gigi.) + // (Penny Farthings are those bicycles with the big front wheel. + // They have no gears.) + + public PennyFarthing(int startCadence, int startSpeed) { + // Call the parent constructor with super + super(startCadence, startSpeed, 0, "PennyFarthing"); + } + + // You should mark a method you're overriding with an @annotation. + // To learn more about what annotations are and their purpose check this + // out: http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setRodaGigi(int rodaGigi) { + roda rodaGigi = 0; + } +} + +// Interfaces +// Sintaks untuk deklarasi Interface +// interface extends { +// // Konstan +// // Deklarasi method +// } + +// Contoh - Makanan: +public interface dapatDimakan { + public void makan(); // Setiap kelas yang menggunakan interface "dapatDimakan", + // harus mengimplementasikan method "makan". +} + +public interface dapatDicerna { + public void cerna(); +} + + +// Membuat kelas dengan mengimplementasikan dua interface dalam satu waktu. +public class Buah implements dapatDimakan, dapatDicerna { + + @Override + public void makan() { + // ... + } + + @Override + public void cerna() { + // ... + } +} + +// Dalam Java, kelas hanya dapat diturunkan sekali, tapi dapat mengimplementasikan +// banyak interface. Contoh: +public class ContohKelas extends ContohKelasInduk implements InterfaceSatu, + InterfaceDua { + + @Override + public void MethodInterfaceSatu() { + } + + @Override + public void MethodInterfaceDua() { + } + +} + +// Kelas Abstrak (Abstract) +// Sintaks untuk deklarasi kelas abstrak +// Abstract Class declaration syntax +// abstract extends { +// // Konstan dan variabel +// // Deklarasi method + +// Menjadikan kelas sebagai abstrak adalah memungkinkan kelas berisi method abstrak +// yang harus didefinisikan pada kelas turunannya. Mirip dengan Interface, kelas abstrak +// tidak dapat dilakukan instansiasi, namun harus diturunkan pada kelas lain dan method abstrak +// harus didefinisikan. Perbedaannya dengan Interface ialah kelas abstrak dapat berisi method +// kongkrit dan method abstrak. Pada Interface method tidak dapat memiliki isi, artinya hanya +// method statis, dan variabel langsung ditentukan menjadi final, tidak seperti kelas abstrak. +// Kelas abstrak juga dapat memiliki method "main". + +public abstract class Hewan +{ + public abstract void bersuara(); + + // Method biasa dapat memiliki isi + public void makan() + { + System.out.println("Saya adalah hewan dan Saya makan."); + // Catatan: Kita dapat mengakses variabel private yang ada disini. + umur = 30; + } + + // Tidak perlu dilakukan inisialisasi, berbeda dengan Interface + // sebuah variabel adalah final dan harus dilakukan inisialisasi. + protected int umur; + + public void tampilkanUmur() + { + System.out.println(umur); + } + + // Kelas abstrak dapat memiliki fungsi utama (main). + public static void main(String[] args) + { + System.out.println("Saya adalah kelas abstrak!"); + } +} + +class Kucing extends Hewan +{ + // Catatan: kelas ini harus melakukan override method abstrak + // yang ada pada kelas abstrak (induk). + @Override + public void bersuara() + { + System.out.println("Moe"); + // umur = 30; ==> ERROR! umur merupakan variabel private pada abstrak Hewan + } + + // CATATAN: Akan muncul error jika menggunakan + // keterangan @Override pada method utama (main), + // Java tidak mengizinkan hal tersebut. + // Kejadian ini sering disebut sebagai METHOD HIDING. + // Pertanyaan-jawaban yang menarik dapat dilihat: http://stackoverflow.com/questions/16313649/ + public static void main(String[] args) + { + Kucing moe = new Kucing(); + noe.bersuara(); + moe.makan(); + moe.tampilkanUmur(); + } +} + +// Kelas Final + +// Sintaks untuk deklarasi kelas Final +// final { +// // Konstann dan variabel +// // Deklarasi method +// } + +// Kelas Final merupakan kelas yang tidak dapat diturunkan sehingga menjadikan +// method tersebut turunan method terakhir. Disisi lain, kelas final merupakan +// lawan dari kelas abstrak karena kelas abstrak dapat diturunkan lagi, sedangkan +// kelas final tidak dapat diturunkan lagi. +public final class Serigala extends Hewan +{ + // Catatan: method abstrak harus di-override pada kelas abstrak. + @Override + public void bersuara() + { + System.out.println("Auuww"); + } +} + +// Method Final +public abstract class Mamalia() +{ + // Sintaks untuk method final: + // final () + + // Method final, seperti kelas final tidak dapat di-override oleh kelas turunan, + // sehingga menjadikannya implementasi terakhir dari method. + public final boolean apakahBerdarahDingin() + { + return true; + } +} + + +// Tipe Enum +// +// Tipe Enum merupakan tipe data spesial yang memungkinkan sebuah nilai dijadikan +// konstan awal (predefined). Variabel setidaknya harus memiliki nilai yang sama +// dengan salah satu dari enum-enum yang telah ditentukan. Karena nilainya merupakan +// konstan, untuk itu penamaannya menggunakan huruf kapital (uppercase). Dalam Java, +// Enum didefinisikan dengan kata kunci "enum". Contohnya nama-nama hari dalam semunggu: + +public enum Hari { + SENIN, SELASA, RABU, KAMIS, + JUMAT, SABTU, MUNGGU +} + +// Cara menggunakan Enum: +public class CobaEnum { + + // Variabel Enum + Hari hari; + + // Konstruktor + public CobaEnum(Hari hari) { + this.hari = hari; + } + + public void tampilkanKeterangan() { + switch (day) { + case SENIN: + System.out.println("Senin adalah hari yang menyebalkan."); + break; + + case JUMAT: + System.out.println("Jumat adalah hari yang singkat."); + break; + + case SABTU: + case MINGGU: + System.out.println("Akhir pekan adalah hari yang menyenangkan."); + break; + + default: + System.out.println("Hari kerja yang biasa saja."); + break; + } + } + + public static void main(String[] args) { + CobaEnum hariPertama = new CobaEnum(Hari.SENIN); + hariPertama.tampilkanKeterangan(); // Senin adalah hari yang menyebalkan. + CobaEnum hariKetiga = new CobaEnum(Hari.RABU); + hariPertama.tampilkanKeterangan(); // Hari kerja yang biasa saja. + } +} + +// Tipe enum memiliki banyak kegunaan selain yang dicontohkan diatas. +// Tipe enum dapat memiliki isi seperti method dan variabel. +// Penjelasan lebih detail di https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html + +``` + +## Referensi Lainnya + +Link-link berikut hanya menyediakan pemahaman lebih lanjut mengenai topik diatas. +Tip, trik, dan contoh lainnya dapat melakukan pencarian melalui Google atau mesin pencari yang lain. + +**Panduan resmi Oracle** + +* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) + +**Tutorial dan Praktik Online** + +* [Learneroo.com - Learn Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Buku**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Thinking in Java](http://www.mindview.net/Books/TIJ/) + +* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) -- cgit v1.2.3 From 56b3d98321eb4f48ffd06077d07e5208d8481ea2 Mon Sep 17 00:00:00 2001 From: Ahmad Zafrullah Date: Sun, 10 Jul 2016 02:39:03 +0800 Subject: [json/id-id] update changes for ID translation (#2305) * [json/id-id] update changes for ID translation * [json/id-id] update reference info --- id-id/json-id.html.markdown | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/id-id/json-id.html.markdown b/id-id/json-id.html.markdown index ca346f6c..eef48c63 100644 --- a/id-id/json-id.html.markdown +++ b/id-id/json-id.html.markdown @@ -1,20 +1,32 @@ --- language: json -filename: learnjson-id.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] -translators: +filename: learnjson-id.json +translators - ["Rizky Luthfianto", "https://github.com/rilut"] + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] lang: id-id --- -JSON adalah format pertukaran data yang sangat simpel, kemungkinan besar, -ini adalah "Learn X in Y Minutes" yang paling singkat. +JSON adalah format pertukaran data yang sangat sederhana. Sebagaimana dikutip dari [json.org](http://json.org), JSON mudah untuk dibaca atau ditulis oleh manusia, dan mudah diuraikan dan diproses oleh mesin. + +Sebuah format JSON setidaknya memiliki: +* Sebuah pasangan nama atau nilai dinyatakan dengan karakter (`{ }`). Dibeberapa bahasa pemrograman, karakter ini sering digunakan sebagai object, record, struct, dictionary, hash table, keyed list, atau associative array. +* Daftar nilai dinyatakan dengan karakter (`[ ]`). Dibeberapa bahasa pemrograman, karakter ini sering digunakan sebagai array, vector, list, atau sequence. + +Format JSON murni tidak memiliki komentar, namun beberapa pengurai (parser) dapat mengenali komentar seperti yang digunakan oleh bahasa C (`//`, `/**/`). Beberapa pengurai lainnya juga memiliki toleransi terhadap akhiran sisa koma (seperti koma yang terdapat pada akhir elemen dari larik atau properti terakhir dari objek), tapi koma tersebut memang seharusnya diabaikan untuk dukungan yang lebih baik. -Murninya, JSON tidak mempunyai fitur komentar, tapi kebanyakan parser akan -menerima komentar bergaya bahasa C (`//`, `/* */`). Namun, pada halaman ini, -hanya dicontohkan JSON yang 100% valid. +Dalam tutorial ini, semuanya menggunakan format JSON murni. + +Tipe data yang didukung oleh JSON: + +* Teks: `"halo"`, `"\"tanda petik.\""`, `"\u0abe"`, `"baris baru.\n"` +* Angka: `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4` +* Objek: `{ "kunci": "nilai" }` +* Larik: `["nilai"]` +* Lainnya: `true`, `false`, `null` ```json { @@ -59,3 +71,7 @@ hanya dicontohkan JSON yang 100% valid. "singkat": "Dan Anda selesai! Sekarang Anda tahu apa saja yang disediakan oleh JSON." } ``` + +## Referensi lebih labjut + +* [JSON.org](http://json.org/json-id.html) semua keindahan JSON dijelaskan dalam bentuk alur-grafis (bahasa indonesia). -- cgit v1.2.3 From b16c7ee2d8b41b5db4f713360280c284ca9b1a80 Mon Sep 17 00:00:00 2001 From: Leo Rudberg Date: Sun, 10 Jul 2016 02:04:08 -0500 Subject: [bash/en] Addition to bash (#2302) * Added bash intro edits * Fixed page header * Finalizing updates Implemented my changes in the main bash code chunk instead of as an out-of-code prologue * Final touches * Added citation for John and mkdir content * Added removed original intro back in * Update bash.html.markdown Moved "hard way" link to top of article Fixed spacing Grouped `rm` commands * Fixed typos --- bash.html.markdown | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index a62bd167..b1a14bdb 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -11,7 +11,10 @@ contributors: - ["Rahil Momin", "https://github.com/iamrahil"] - ["Gregrory Kielian", "https://github.com/gskielian"] - ["Etan Reisner", "https://github.com/deryni"] - - ["Jonathan Wang", "https://github.com/Jonathansw" ] + - ["Jonathan Wang", "https://github.com/Jonathansw"] + - ["Leo Rudberg", "https://github.com/LOZORD"] + - ["Betsy Lorton", "https://github.com/schbetsy"] + - ["John Detter", "https://github.com/jdetter"] filename: LearnBash.sh --- @@ -20,6 +23,8 @@ Nearly all examples below can be a part of a shell script or executed directly i [Read more here.](http://www.gnu.org/software/bash/manual/bashref.html) +Another recommened link: [The Command Line Crash Course](http://cli.learncodethehardway.org/book/) + ```bash #!/bin/bash # First line of the script is shebang which tells the system how to execute @@ -90,6 +95,21 @@ echo "Number of arguments passed to script: $#" echo "All arguments passed to script: $@" echo "Script's arguments separated into different variables: $1 $2..." +# Now that we know how to echo and use variables, +# let's learn some of the other basics of bash! + +# Getting our current directory is available through the command `pwd`. +# `pwd` stands for "print working directory". +# We can also use the builtin variable `$PWD`. +# Observer that the following are equivalent: +echo "I'm in $(pwd)" # execs `pwd` and interpolates output +echo "I'm in $PWD" # interpolates the variable + +# If you get too much output in your terminal, or from a script, the command +# `clear` clears your screen +clear +# Ctrl-L also works for clearing output + # Reading a value from input: echo "What's your name?" read Name # Note that we didn't need to declare a new variable @@ -138,12 +158,37 @@ ls # These commands have options that control their execution: ls -l # Lists every file and directory on a separate line +ls -t # Sort the directory contents by last-modified date (descending) +ls -R # Recursively `ls` this directory and all of its subdirectories # Results of the previous command can be passed to the next command as input. # grep command filters the input with provided patterns. That's how we can list # .txt files in the current directory: ls -l | grep "\.txt" +# Use `cat` to print files to stdout: +cat file.txt + +# We can also read the file using `cat`: +Contents=$(cat file.txt) +echo "START OF FILE\n$Contents\nEND OF FILE" + +# Use `cp` to copy files or directories from one place to another. +# `cp` creates NEW versions of the sources, +# so editing the copy won't affect the original (and vice versa). +# Note that it will overwrite the destination if it already exists. +cp srcFile.txt clone.txt +cp -r srcDirectory/ dst/ # recursively copy + +# Look into `scp` or `sftp` if you plan on exchanging files between computers. +# `scp` behaves very similarly to `cp`. +# `sftp` is more interactive. + +# Use `mv` to move files or directories from one place to another. +# `mv` is similar to `cp`, but it deletes the source. +# `mv` is also useful for renaming files! +mv s0urc3.txt dst.txt # sorry, l33t hackers... + # Since bash works in the context of a current directory, you might want to # run your command in some other directory. We have cd for changing location: cd ~ # change to home directory @@ -152,6 +197,14 @@ cd .. # go up one directory cd /home/username/Documents # change to specified directory cd ~/Documents/.. # still in home directory..isn't it?? +# Use subshells to work across directories +(echo "First, I'm here: $PWD") && (cd someDir; echo "Then, I'm here: $PWD") +pwd # still in first directory + +# Use `mkdir` to create new directories. +mkdir myNewDir +# The `-p` flag causes new intermediate directories to be created as necessary. +mkdir -p myNewDir/with/intermediate/directories # You can redirect command input and output (stdin, stdout, and stderr). # Read from stdin until ^EOF$ and overwrite hello.py with the lines @@ -191,7 +244,9 @@ echo "#helloworld" | cat > output.out echo "#helloworld" | tee output.out >/dev/null # Cleanup temporary files verbosely (add '-i' for interactive) +# WARNING: `rm` commands cannot be undone rm -v output.out error.err output-and-error.log +rm -r tempDir/ # recursively delete # Commands can be substituted within other commands using $( ): # The following command displays the number of files and directories in the @@ -282,6 +337,13 @@ sed -i 's/okay/great/g' file.txt grep "^foo.*bar$" file.txt # pass the option "-c" to instead print the number of lines matching the regex grep -c "^foo.*bar$" file.txt +# Other useful options are: +grep -r "^foo.*bar$" someDir/ # recursively `grep` +grep -n "^foo.*bar$" file.txt # give line numbers +grep -rI "^foo.*bar$" someDir/ # recursively `grep`, but ignore binary files +# perform the same initial search, but filter out the lines containing "baz" +grep "^foo.*bar$" file.txt | grep -v "baz" + # if you literally want to search for the string, # and not the regex, use fgrep (or grep -F) fgrep "foobar" file.txt @@ -290,6 +352,11 @@ fgrep "foobar" file.txt # Here trap command will execute rm if any one of the three listed signals is received. trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM +# `sudo` is used to perform commands as the superuser +$NAME1=$(whoami) +$NAME2=$(sudo whoami) +echo "Was $NAME1, then became more powerful $NAME2" + # Read Bash shell builtins documentation with the bash 'help' builtin: help help help -- cgit v1.2.3 From e249d12ee6fdc9366e6d13b869f2ca2ccff6ee56 Mon Sep 17 00:00:00 2001 From: Ryan Plant Date: Tue, 12 Jul 2016 18:07:38 +1000 Subject: Elixir agents/maps, Ruby conventions/docs (#2116) * Add name to contributors list * Fix typo * Note convention on curly-braced blocks * Replace hardcoded link to 2.1.1 documentation with generic current link * Add notes on Elixir agents * Add explanation of maps * Add name to contributors list * Fix code fence that was obscuring markdown * Fix syntax error * Remove disputed comment * Remove from contributors list --- elixir.html.markdown | 26 ++++++++++++++++++++++++++ ruby.html.markdown | 4 ++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index eb708576..26a547c3 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -3,6 +3,7 @@ language: elixir contributors: - ["Joao Marques", "http://github.com/mrshankly"] - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Ryan Plant", "https://github.com/ryanplant-au"] filename: learnelixir.ex --- @@ -96,6 +97,14 @@ string. lower..upper = 1..10 # Can use pattern matching on ranges as well [lower, upper] #=> [1, 10] +# Maps are key-value pairs +genders = %{"david" => "male", "gillian" => "female"} +genders["david"] #=> "male" + +# Maps with atom keys can be used like this +genders = %{david: "male", gillian: "female"} +genders.gillian #=> "female" + ## --------------------------- ## -- Operators ## --------------------------- @@ -407,6 +416,23 @@ send pid, {:circle, 2} # The shell is also a process, you can use `self` to get the current pid self() #=> #PID<0.27.0> + +## --------------------------- +## -- Agents +## --------------------------- + +# An agent is a process that keeps track of some changing value + +# Create an agent with `Agent.start_link`, passing in a function +# The initial state of the agent will be whatever that function returns +{ok, my_agent} = Agent.start_link(fn -> ["red, green"] end) + +# `Agent.get` takes an agent name and a `fn` that gets passed the current state +# Whatever that `fn` returns is what you'll get back +Agent.get(my_agent, fn colors -> colors end) #=> ["red, "green"] + +# Update the agent's state the same way +Agent.update(my_agent, fn colors -> ["blue" | colors] end) ``` ## References diff --git a/ruby.html.markdown b/ruby.html.markdown index adf5ce81..a1532855 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -210,7 +210,7 @@ array.push(6) #=> [1, 2, 3, 4, 5, 6] # Check if an item exists in an array array.include?(1) #=> true -# Hashes are Ruby's primary dictionary with keys/value pairs. +# Hashes are Ruby's primary dictionary with key/value pairs. # Hashes are denoted with curly braces: hash = { 'color' => 'green', 'number' => 5 } @@ -612,7 +612,7 @@ Something.new.qux # => 'qux' - [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. - [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Learn Ruby through a series of interactive tutorials. -- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) +- [Official Documentation](http://ruby-doc.org/core) - [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) - [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. - [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. -- cgit v1.2.3 From 8f99c7ab7ef071979d6143ad0cf53576c1a970e0 Mon Sep 17 00:00:00 2001 From: ven Date: Tue, 12 Jul 2016 19:14:38 +0200 Subject: fix #2308 --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index e41e71c3..2b599378 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -20,7 +20,7 @@ Multi-line comments look like this */ // XCode supports pragma mark directive that improve jump bar readability -#pragma mark Navigation Functions // New tag o@"Third number = %@", thirdNumber); // prin jump bar named 'Navigation Functions' +#pragma mark Navigation Functions // New tag on jump bar named 'Navigation Functions' #pragma mark - Navigation Functions // Same tag, now with a separator // Imports the Foundation headers with #import -- cgit v1.2.3 From c1a258ba9f64f648f529b8ab4ac3f5560675d322 Mon Sep 17 00:00:00 2001 From: Chris Warren-Smith Date: Sat, 16 Jul 2016 20:59:31 +1000 Subject: [smallbasic/en] New article about SmallBASIC (#2311) * [smallbasic/en] new article * [smallbasic/en] new article --- smallbasic.html.markdown | 124 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 smallbasic.html.markdown diff --git a/smallbasic.html.markdown b/smallbasic.html.markdown new file mode 100644 index 00000000..007f9591 --- /dev/null +++ b/smallbasic.html.markdown @@ -0,0 +1,124 @@ +--- +language: SmallBASIC +filename: learnsmallbasic.bas +contributors: + - ["Chris Warren-Smith", "http://smallbasic.sourceforge.net"] +--- + +## About + +SmallBASIC is a fast and easy to learn BASIC language interpreter ideal for everyday calculations, scripts and prototypes. SmallBASIC includes trigonometric, matrices and algebra functions, a built in IDE, a powerful string library, system, sound, and graphic commands along with structured programming syntax. + +## Development + +SmallBASIC was originally developed by Nicholas Christopoulos in late 1999 for the Palm Pilot. Project development has been continued by Chris Warren-Smith since around 2005. + +Versions of SmallBASIC have been made for a number of early hand held devices including Franklin eBookman and the Nokia 770. Also various desktop releases have been released based on a variety of GUI tool-kits, some of which have become defunct. The current supported platforms are Linux and Windows based on SDL2 and Android based on NDK. + +In late 2000's a large corporation released a BASIC like programming environment with a similar sounding name. SmallBASIC is not related to this other project. + +``` +REM This is a comment +' and this is also a comment + +REM print text +print "hello" +? "? is short for PRINT" + +REM Control structures +FOR index = 0 TO 10 STEP 2 + ? "This is line number "; index +NEXT +J=0 +REPEAT + J++ +UNTIL J=10 +WHILE J>0 + J-- +WEND + +REM Select case statement +Select Case "Cool" + Case "null", 1,2,3,4,5,6,7,8,"Cool","blah" + Case "Not cool" + PRINT "Epic fail" + Case Else + PRINT "Fail" +End Select + +REM catching errors with TRY/CATCH +Try + fn = Freefile + Open filename For Input As #fn +Catch err + Print "failed to open" +End Try + +REM User defined subs and functions +func add2(x,y) + ' variables may be declared as local within the scope of a SUB or FUNC + local K + k = "k will cease to exist when this FUNC returns" + add2=x+y +end +Print add2(5,5) +sub print_it(it) + print it +end +print_it "IT...." + +REM Display lines and pixels +At 0,ymax/2+txth("Q") +Color 1: ? "sin(x)": +Color 8: ? "cos(x)": +Color 12: ? "tan(x)" +Line 0,ymax/2,xmax,ymax/2 +For i=0 to xmax + Pset i,ymax/2-sin(i*2*pi/ymax)*ymax/4 color 1 + Pset i,ymax/2-cos(i*2*pi/ymax)*ymax/4 color 8 + Pset i,ymax/2-tan(i*2*pi/ymax)*ymax/4 color 12 +Next +showpage + +REM SmallBASIC is great for experimenting with fractals and other interesting effects +Delay 3000 +Randomize +ff = 440.03 +For j = 0 to 20 + r = rnd * 1000 % 255 + b = rnd * 1000 % 255 + g = rnd * 1000 % 255 + c = rgb(r,b,g) + ff += 9.444 + for i=0 to 25000 + f += ff + x = min(xmax, -x + cos(f*i)) + y = min(ymax, -y + sin(f*i)) + pset x, y color c + if (i%1000==0) then + showpage + fi + next +Next j + +REM For computer historians, SmallBASIC can run programs +REM found in early computer books and magazines, for example: +10 LET A=9 +20 LET B=7 +30 PRINT A*B +40 PRINT A/B + +PAUSE + +``` + +## Articles + +* [Getting started](http://smallbasic.sourceforge.net/?q=node/1573) +* [Welcome to SmallBASIC](http://smallbasic.sourceforge.net/?q=node/838) + +## GitHub + +* [Source code](https://github.com/smallbasic/SmallBASIC) +* [Reference snapshot](http://smallbasic.github.io/) + -- cgit v1.2.3 From a4db2f20120aa1efcbccc42ec78f95948f56fbde Mon Sep 17 00:00:00 2001 From: Chris Warren-Smith Date: Sun, 17 Jul 2016 09:51:57 +1000 Subject: [smallbasic/en] minor fact check fix (#2312) --- smallbasic.html.markdown | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/smallbasic.html.markdown b/smallbasic.html.markdown index 007f9591..9244525e 100644 --- a/smallbasic.html.markdown +++ b/smallbasic.html.markdown @@ -13,9 +13,9 @@ SmallBASIC is a fast and easy to learn BASIC language interpreter ideal for ever SmallBASIC was originally developed by Nicholas Christopoulos in late 1999 for the Palm Pilot. Project development has been continued by Chris Warren-Smith since around 2005. -Versions of SmallBASIC have been made for a number of early hand held devices including Franklin eBookman and the Nokia 770. Also various desktop releases have been released based on a variety of GUI tool-kits, some of which have become defunct. The current supported platforms are Linux and Windows based on SDL2 and Android based on NDK. +Versions of SmallBASIC have been made for a number of early hand held devices including Franklin eBookman and the Nokia 770. Also various desktop versions have been released based on a variety of GUI tool-kits, some of which have become defunct. The current supported platforms are Linux and Windows based on SDL2 and Android based on NDK. A desktop command line version is also available, although not typically released in binary form. -In late 2000's a large corporation released a BASIC like programming environment with a similar sounding name. SmallBASIC is not related to this other project. +In around 2008 a large corporation released a BASIC like programming environment with a similar sounding name. SmallBASIC is not related to this other project. ``` REM This is a comment @@ -108,6 +108,13 @@ REM found in early computer books and magazines, for example: 30 PRINT A*B 40 PRINT A/B +REM SmallBASIC also has support for a few modern concepts such as JSON +aa = array("{\"cat\":{\"name\":\"harry\"},\"pet\":\"true\"}") +If (ismap(aa) == false) Then + throw "not an map" +End If +Print aa + PAUSE ``` -- cgit v1.2.3 From 50c8f7b4dd78df0e4db95ab2cad42373d25f3021 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohan Date: Sat, 30 Jul 2016 21:58:27 +0530 Subject: Fix typo (#2317) --- lua.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua.html.markdown b/lua.html.markdown index 2cd4d7bb..1e2d4366 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -190,7 +190,7 @@ end -------------------------------------------------------------------------------- -- A table can have a metatable that gives the table operator-overloadish --- behaviour. Later we'll see how metatables support js-prototypey behaviour. +-- behaviour. Later we'll see how metatables support js-prototype behaviour. f1 = {a = 1, b = 2} -- Represents the fraction a/b. f2 = {a = 2, b = 3} -- cgit v1.2.3 From a186508d6f4c57dba8f1f573b476741a45f7895f Mon Sep 17 00:00:00 2001 From: LuJimin Date: Sun, 31 Jul 2016 13:04:45 +0800 Subject: =?UTF-8?q?=E5=88=9B=E5=BB=BAKotlin=E7=9A=84=E4=B8=AD=E6=96=87?= =?UTF-8?q?=E7=BF=BB=E8=AF=91=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 创建Kotlin的中文翻译版本 --- zh-cn/kotlin-cn.html.markdown | 346 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 346 insertions(+) create mode 100644 zh-cn/kotlin-cn.html.markdown diff --git a/zh-cn/kotlin-cn.html.markdown b/zh-cn/kotlin-cn.html.markdown new file mode 100644 index 00000000..ac15c564 --- /dev/null +++ b/zh-cn/kotlin-cn.html.markdown @@ -0,0 +1,346 @@ +--- +language: kotlin +contributors: + - ["S Webber", "https://github.com/s-webber"] +translators: + - ["Jimin Lu", "https://github.com/lujimin"] +filename: LearnKotlin-cn.kt +--- + +Kotlin是一门适用于JVM、Android和浏览器的静态类型编程语言。它100%兼容Java。 +[了解更多。](https://kotlinlang.org/) + +```java +// 单行注释从 // 开始 +/* +多行注释看起来像这样。 +*/ + +// "package" 关键字的工作方式与Java相同。 +package com.learnxinyminutes.kotlin + +/* +Kotlin程序的入口点是一个"main"函数 +该函数传递一个包含任何命令行参数的数组。 +*/ +fun main(args: Array) { + /* + 使用"var"或"val"来声明一个值。 + "val"声明的值不能被重新赋值,而"vars"声明的值可以。 + */ + val fooVal = 10 // 以后我们不能再次给fooVal赋值 + var fooVar = 10 + fooVar = 20 // fooVar可以被再次赋值 + + /* + 在大多数情况下,Kotlin可以确定变量的类型是什么, + 所以我们不必要每次都去明确指定它。 + 我们可以像这样明确地声明一个变量的类型: + */ + val foo : Int = 7 + + /* + 可以采取和Java类似的方法来表示一个字符串。 + 用反斜杠来转义字符。 + */ + val fooString = "My String Is Here!"; + val barString = "Printing on a new line?\nNo Problem!"; + val bazString = "Do you want to add a tab?\tNo Problem!"; + println(fooString); + println(barString); + println(bazString); + + /* + 原始字符串用三重引号(""")来定义。 + 原始字符串可以包含新的行以及其他任何字符。 + */ + val fooRawString = """ +fun helloWorld(val name : String) { + println("Hello, world!") +} +""" + println(fooRawString) + + /* + 字符串可以包含模板表达式。 + 模板表达式从一个美元符号($)开始。 + */ + val fooTemplateString = "$fooString has ${fooString.length} characters" + println(fooTemplateString) + + /* + 当某个变量的值可以为 null 的时候,我们必须被明确指定它是可为空的。 + 在变量声明处的类型后面加上?来标识它是可为空的。 + 我们可以用?.操作符来访问可为空的变量。 + 我们可以用?:操作符来指定一个替代值在变量为空的时候使用。 + */ + var fooNullable: String? = "abc" + println(fooNullable?.length) // => 3 + println(fooNullable?.length ?: -1) // => 3 + fooNullable = null + println(fooNullable?.length) // => null + println(fooNullable?.length ?: -1) // => -1 + + /* + 使用"fun"关键字来声明一个函数。 + 函数的参数在函数名后面的括号内指定。 + 函数的参数可以设定一个默认值。 + 如果需要的话,函数的返回值类型可以在参数后面指定。 + */ + fun hello(name: String = "world") : String { + return "Hello, $name!" + } + println(hello("foo")) // => Hello, foo! + println(hello(name = "bar")) // => Hello, bar! + println(hello()) // => Hello, world! + + /* + 用"vararg"关键字来修饰一个函数的参数 + 来允许可变参数传递给该函数 + */ + fun varargExample(vararg names: Int) { + println("Argument has ${names.size} elements") + } + varargExample() // => Argument has 0 elements + varargExample(1) // => Argument has 1 elements + varargExample(1, 2, 3) // => Argument has 3 elements + + /* + 当函数只包含一个单独的表达式时,大括号可以被省略。 + 函数体可以被指定在一个=符号后面。 + */ + fun odd(x: Int): Boolean = x % 2 == 1 + println(odd(6)) // => false + println(odd(7)) // => true + + // 如果返回值类型可以被推断,那么我们不需要指定它。 + fun even(x: Int) = x % 2 == 0 + println(even(6)) // => true + println(even(7)) // => false + + // 函数可以用函数作为参数并且可以返回函数。 + fun not(f: (Int) -> Boolean) : (Int) -> Boolean { + return {n -> !f.invoke(n)} + } + // 命名函数可以被指定为参数使用::操作符。 + val notOdd = not(::odd) + val notEven = not(::even) + // 匿名函数可以被指定为参数。 + val notZero = not {n -> n == 0} + /* + 如果一个匿名函数只有一个参数 + 那么它的声明可以被省略(连同->)。 + 这个参数的名字是"it"。 + */ + val notPositive = not {it > 0} + for (i in 0..4) { + println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}") + } + + // "class"关键字用来声明类。 + class ExampleClass(val x: Int) { + fun memberFunction(y: Int) : Int { + return x + y + } + + infix fun infixMemberFunction(y: Int) : Int { + return x * y + } + } + /* + 我们调用构造方法来创建一个新的实例。 + 注意,Kotlin没有"new"关键字。 + */ + val fooExampleClass = ExampleClass(7) + // 可以使用一个点号来调用成员函数。 + println(fooExampleClass.memberFunction(4)) // => 11 + /* + 如果使用"infix"关键字来标记一个函数 + 那么可以使用中缀表示法来调用该函数。 + */ + println(fooExampleClass infixMemberFunction 4) // => 28 + + /* + 数据类是创建只包含数据的类的一个简洁的方法。 + "hashCode"、"equals"和"toString"方法将被自动生成。 + */ + data class DataClassExample (val x: Int, val y: Int, val z: Int) + val fooData = DataClassExample(1, 2, 4) + println(fooData) // => DataClassExample(x=1, y=2, z=4) + + // 数据类有一个"copy"函数 + val fooCopy = fooData.copy(y = 100) + println(fooCopy) // => DataClassExample(x=1, y=100, z=4) + + // 对象可以被解构成为多个变量 + val (a, b, c) = fooCopy + println("$a $b $c") // => 1 100 4 + + // "with"函数类似于JavaScript中的"with"用法。 + data class MutableDataClassExample (var x: Int, var y: Int, var z: Int) + val fooMutableDate = MutableDataClassExample(7, 4, 9) + with (fooMutableDate) { + x -= 2 + y += 2 + z-- + } + println(fooMutableDate) // => MutableDataClassExample(x=5, y=6, z=8) + + /* + 我们可以使用"listOf"函数来创建一个list。 + 这个list是不可变的 - 元素不可以被添加或删除。 + */ + val fooList = listOf("a", "b", "c") + println(fooList.size) // => 3 + println(fooList.first()) // => a + println(fooList.last()) // => c + // 可以通过索引来访问list中的元素。 + println(fooList[1]) // => b + + // 可以使用"mutableListOf"函数来创建一个可变的list。 + val fooMutableList = mutableListOf("a", "b", "c") + fooMutableList.add("d") + println(fooMutableList.last()) // => d + println(fooMutableList.size) // => 4 + + // 我们可以使用"setOf"函数来创建一个set。 + val fooSet = setOf("a", "b", "c") + println(fooSet.contains("a")) // => true + println(fooSet.contains("z")) // => false + + // 我们可以使用"mapOf"函数来创建一个map。 + val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9) + // 可以通过键来访问map中的值。 + println(fooMap["a"]) // => 8 + + /* + 序列表示惰性求值集合。 + 我们可以使用"generateSequence"函数来创建一个序列。 + */ + val fooSequence = generateSequence(1, {it + 1}) + val x = fooSequence.take(10).toList() + println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + + // 一个用序列来生成斐波那契数列的例子。 + fun fibonacciSequence() : Sequence { + var a = 0L + var b = 1L + + fun next() : Long { + val result = a + b + a = b + b = result + return a + } + + return generateSequence(::next) + } + val y = fibonacciSequence().take(10).toList() + println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] + + // Kotlin为集合提供高阶函数。 + val z = (1..9).map {it * 3} + .filter {it < 20} + .groupBy {it % 2 == 0} + .mapKeys {if (it.key) "even" else "odd"} + println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]} + + // 任何提供迭代器的都可以使用"for"循环。 + for (c in "hello") { + println(c) + } + + // "while"循环的用法和其他语言一样。 + var ctr = 0 + while (ctr < 5) { + println(ctr) + ctr++ + } + do { + println(ctr) + ctr++ + } while (ctr < 10) + + // "when"可以用来替代"if-else if"链。 + val i = 10 + when { + i < 7 -> println("first block") + fooString.startsWith("hello") -> println("second block") + else -> println("else block") + } + + // "when"可以带参数。 + when (i) { + 0, 21 -> println("0 or 21") + in 1..20 -> println("in the range 1 to 20") + else -> println("none of the above") + } + + // "when"可以作为一个函数,提供返回值。 + var result = when (i) { + 0, 21 -> "0 or 21" + in 1..20 -> "in the range 1 to 20" + else -> "none of the above" + } + println(result) + + /* + 我们可以通过使用"is"操作符来检查一个对象是否是特定类型的。 + 如果对象通过了类型检查那么它可以作为该类型使用而不需要强制转换它。 + */ + fun smartCastExample(x: Any) : Boolean { + if (x is Boolean) { + // x自动转换为Boolean + return x + } else if (x is Int) { + // x自动转换为Int + return x > 0 + } else if (x is String) { + // x自动转换为String + return x.isNotEmpty() + } else { + return false + } + } + println(smartCastExample("Hello, world!")) // => true + println(smartCastExample("")) // => false + println(smartCastExample(5)) // => true + println(smartCastExample(0)) // => false + println(smartCastExample(true)) // => true + + /* + 扩展是用来添加新的功能到一个类的。 + 它类似于C#的扩展方法。 + */ + fun String.remove(c: Char): String { + return this.filter {it != c} + } + println("Hello, world!".remove('l')) // => Heo, word! + + println(EnumExample.A) // => A + println(ObjectExample.hello()) // => hello +} + +// 枚举类和Java的枚举类型类似。 +enum class EnumExample { + A, B, C +} + +/* +"object"关键字用来创建单例对象。 +我们不能把它赋给一个变量,但我们可以通过它的名字引用它。 +这类似于Scala的单例对象。 +*/ +object ObjectExample { + fun hello() : String { + return "hello" + } +} + +``` + +### 进一步阅读 + +* [Kotlin教程](https://kotlinlang.org/docs/tutorials/) +* [在您的浏览器中使用Kotlin](http://try.kotlinlang.org/) +* [Kotlin资源列表](http://kotlin.link/) -- cgit v1.2.3 From 7645f54e5eb3be229ed05bc99f1fc0c5db4c90fb Mon Sep 17 00:00:00 2001 From: LuJimin Date: Sun, 31 Jul 2016 13:13:44 +0800 Subject: fix bug MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改bug --- zh-cn/kotlin-cn.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/zh-cn/kotlin-cn.html.markdown b/zh-cn/kotlin-cn.html.markdown index ac15c564..5998f33f 100644 --- a/zh-cn/kotlin-cn.html.markdown +++ b/zh-cn/kotlin-cn.html.markdown @@ -5,6 +5,7 @@ contributors: translators: - ["Jimin Lu", "https://github.com/lujimin"] filename: LearnKotlin-cn.kt +lang: zh-cn --- Kotlin是一门适用于JVM、Android和浏览器的静态类型编程语言。它100%兼容Java。 -- cgit v1.2.3 From 83bca498968c24262780de32e5b5e2d2ac0318bc Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Sun, 31 Jul 2016 13:37:09 +0800 Subject: [bash/zh-tw] add zh-tw translation --- zh-tw/bash-tw.html.markdown | 376 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 376 insertions(+) create mode 100644 zh-tw/bash-tw.html.markdown diff --git a/zh-tw/bash-tw.html.markdown b/zh-tw/bash-tw.html.markdown new file mode 100644 index 00000000..f195d273 --- /dev/null +++ b/zh-tw/bash-tw.html.markdown @@ -0,0 +1,376 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] + - ["Jonathan Wang", "https://github.com/Jonathansw"] + - ["Leo Rudberg", "https://github.com/LOZORD"] + - ["Betsy Lorton", "https://github.com/schbetsy"] + - ["John Detter", "https://github.com/jdetter"] +translators: + - ["Jinchang Ye", "https://github.com/Alwayswithme"] + - ["Chunyang Xu", "https://github.com/XuChunyang"] + - ["Weihang Lo", "https://github.com/weihanglo"] +filename: LearnBash-tw.sh +lang: zh-tw +--- + +Bash 是一個爲 GNU 計劃編寫的 Unix shell,是 Linux 和 Mac OS X 下預設的 shell。 +以下大多數例子可以作爲腳本的一部分運行,也可直接在 shell 下互動執行。 + +[更多資訊](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# 腳本的第一行叫 shebang,用來告知系統如何執行該腳本: +# 參見: http://en.wikipedia.org/wiki/Shebang_(Unix) +# 如你所見,註釋以 # 開頭,shebang 也是註釋。 + +# 顯示 “Hello world!” +echo Hello world! + +# 每一句指令以換行或分號隔開: +echo 'This is the first line'; echo 'This is the second line' + +# 宣告一個變數: +Variable="Some string" + +# 下面是錯誤的做法: +Variable = "Some string" +# Bash 會把 Variable 當做一個指令,由於找不到該指令,因此這裡會報錯。 + +# 也不可以這樣: +Variable= 'Some string' +# Bash 會認爲 'Some string' 是一條指令,由於找不到該指令,這裡會再次報錯。 +# (這個例子中 'Variable=' 這部分會被當作僅對 'Some string' 起作用的賦值。) + +# 使用變數: +echo $Variable +echo "$Variable" +echo '$Variable' +# 當你賦值 (assign) 、匯出 (export),或者以其他方式使用變數時,變數名前不加 $。 +# 如果要使用變數的值, 則要加 $。 +# 注意: ' (單引號) 不會展開變數。 + +# 參數展開式 ${}: +echo ${Variable} +# 這是一個參數展開的簡單用法 +# 使用參數展開會得到該變數的值,也就是會「展開」或印出該值。 +# 在展開期間,可以修改該值或該參數。 +# 以下是修改參數展開式的範例: + +# 在變數內部進行字串代換 +echo ${Variable/Some/A} +# 會把 Variable 中首次出現的 "some" 替換成 “A”。 + +# 變數的截取 +Length=7 +echo ${Variable:0:Length} +# 這樣僅會返回變數值的前7個字元 + +# 變數的預設值 +echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} +# 對 null (Foo=) 和空字串 (Foo="") 起作用; 零(Foo=0)時返回0 +# 注意這僅返回預設值而不是改變變數的值 + +# 括號展開 { } +# 用以產生任意的字串 +echo {1..10} +echo {a..z} +# 這將會輸出該範圍內的起始值到最終值。 + +# 內建變數: +# 下面的內建變數很有用 +echo "Last program's return value: $?" +echo "Script's PID: $$" +echo "Number of arguments: $#" +echo "Scripts arguments: $@" +echo "Scripts arguments separated in different variables: $1 $2..." + +# 現在,我們知道變數如何使用與印出 +# 讓我們開始學習其他Bash基礎吧! + +# 使用 `pwd` 指令,可以得知當前工作目錄 +# `pwd` 意指 「印出工作目錄」(print working directory)。 +# 我們也可使用內建變數 `$PWD`。 +# 下列兩行指令等價: +echo "I'm in $(pwd)" # 執行 `pwd` 且將該值內插至輸出中 +echo "I'm in $PWD" # 直接內插 `$PWD` 變數 + +# 如果終端機上有太多輸出,`clear` 指令可以清除螢幕先前的輸出 +clear +# Ctrl-L 也有相同的效果 + +# 讀取輸入: +echo "What's your name?" +read Name # 這裡不需要宣告新變數 +echo Hello, $Name! + +# 一般 if 結構看起來像這樣: +# 'man test' 可查看更多的信息 +if [ $Name != $USER ] +then + echo "Your name isn't your username" +else + echo "Your name is your username" +fi + +# 注意: 如果 $Name 為空,bash會將該條件式解讀成: +if [ != USER ] +# 這是一個錯誤的語法 +# 所以,安全避免空變數的方法如下: +if [ "$Name" != $USER ] ... +# 如果 $Name 為空,該條件式將被視為: +if [ "" != $USER] +# 此條件式可正常運作 + + +# 根據上一個指令執行結果決定是否執行下一個指令 +echo "Always executed" || echo "Only executed if first command fails" +echo "Always executed" && echo "Only executed if first command does NOT fail" + +# 在 if 語句中使用 && 和 || 需要多對方括號 +if [ $Name == "Steve" ] && [ $Age -eq 15 ] +then + echo "This will run if $Name is Steve AND $Age is 15." +fi + +if [ $Name == "Daniya" ] || [ $Name == "Zach" ] +then + echo "This will run if $Name is Daniya OR Zach." +fi + +# 表達式的格式如下: +echo $(( 10 + 5 )) + +# 與其他程式語言不同的是,bash 運行時依賴上下文。比如,使用 ls 時,列出當前目錄。 +ls + +# 指令可以帶有選項: +ls -l # 列出文件和目錄的詳細信息 +ls -t # 以最後修改時間,對文件與目錄排序 +ls -R # 遞迴列出目錄與次目錄的內容 + +# 前一個指令的輸出可以當作後一個指令的輸入。grep 用來匹配字串。 +# 用下面的指令列出當前目錄下所有的 txt 文件: +ls -l | grep "\.txt" + +# 使用 `cat` 將檔案印出在標準輸出中: +cat file.txt + +# 使用 `cat` 讀取檔案 +Contents=$(cat file.txt) +echo "START OF FILE\n$Contents\nEND OF FILE" + +# 使用 `cp` 複製檔案或目錄,`cp` 會創建新版本的來源檔案/目錄 +# 所以,編輯副本不會影響到初始來源(反之亦然)。 +# 注意,如果目的地已存在該檔案/目錄,該檔案/目錄將會被覆寫 +cp srcFile.txt clone.txt +cp -r srcDirectory/ dst/ # 遞迴複製 + +# `scp` or `sftp` if you plan on exchanging files between computers. +# 如需在兩台電腦間交換檔案,請查看 `scp` 或 `sftp`。 +# `scp` 與 `cp` 相似。 +# `sftp` 則有更高的互動性(與 `ftp` 相似)。 + +# 使用 `mv` 來移動目錄與檔案。 +# `mv` 與 `cp` 相似,但會刪除來源。 +# `mv` 也可以用來重新命名檔案/目錄! +mv s0urc3.txt dst.txt + +# 由於 bash 運行時依賴當前目錄的上下文, +# 需要在其他目錄執行指令時,可使用 `cd` 改變當前目錄: +cd ~ # 到家目錄 +cd .. # 到上一層目錄 + # (^^例如, 從 /home/username/Downloads 到 /home/username) +cd /home/username/Documents # 到指定目錄 +cd ~/Documents/.. # 仍位於家目錄,不是嗎? + +# 使用子殼程式 (subshells) 在不同目錄間工作 +(echo "First, I'm here: $PWD") && (cd someDir; echo "Then, I'm here: $PWD") +pwd # 仍在第一個目錄 + +# 使用 `mkdir` 來建立新的目錄 +mkdir myNewDir +# 使用 `-p` 選項參數,將會自動創建路徑中不存在的目錄 +mkdir -p myNewDir/with/intermediate/directories + +# 將指令的輸出輸入重新導向(標準輸入、標準輸出、標準錯誤輸出)。 +# 從標準輸入讀取資料,直到 ^EOF$ (End-of-file),且將讀取的資料覆寫至hello.py +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ import print_function +import sys +print("#stdout", file=sys.stdout) +print("#stderr", file=sys.stderr) +for line in sys.stdin: + print(line, file=sys.stdout) +EOF + +# 重新導向可以到標準輸出(stdout),標準輸入(stdin)和標準錯誤輸出(stderr)。 +python hello.py < "input.in" +python hello.py > "output.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# `>` 會覆蓋已存在的文件, `>>` 會以累加的方式輸出文件中。 +python hello.py >> "output.out" 2>> "error.err" + +# 覆蓋 output.out , 追加 error.err 並統計行數 +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# 運行指令並印出文件描述 (比如 /dev/fd/123) +# 具體可查看: man fd +echo <(echo "#helloworld") + +# 以 "#helloworld" 覆蓋 output.out: +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# 清理臨時文件並顯示詳情(增加 '-i' 選項啓用互動模式) +rm -v output.out error.err output-and-error.log + +# 一個指令可用 $( ) 嵌套在另一個指令內部: +# 以下的指令會印出當前目錄下的目錄和文件總數 +echo "There are $(ls | wc -l) items here." + +# 反引號 `` 起相同作用,但不允許嵌套 +# 優先使用 $( ). +echo "There are `ls | wc -l` items here." + +# Bash 的 case 語句與 Java 和 C++ 中的 switch 語句類似: +case "$Variable" in + # 列出需要匹配的字串 + 0) echo "There is a zero.";; + 1) echo "There is a one.";; + *) echo "It is not null.";; +esac + +# 循環遍歷給定的參數序列: +# 變數$Variable 的值會被印出 3 次。 +for Variable in {1..3} +do + echo "$Variable" +done + +# 或傳統的 “for循環” : +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# 也可以用於文件 +# 用 cat 輸出 file1 和 file2 內容 +for Variable in file1 file2 +do + cat "$Variable" +done + +# 或作用於其他命令的輸出 +# 對 ls 輸出的文件執行 cat 指令。 +for Output in $(ls) +do + cat "$Output" +done + +# while 循環: +while [ true ] +do + echo "loop body here..." + break +done + +# 你也可以使用函數 +# 定義函數: +function foo () +{ + echo "Arguments work just like script arguments: $@" + echo "And: $1 $2..." + echo "This is a function" + return 0 +} + +# 更簡單的方法 +bar () +{ + echo "Another way to declare functions!" + return 0 +} + +# 呼叫函數 +foo "My name is" $Name + +# 有很多有用的指令需要學習: +# 打印 file.txt 的最後 10 行 +tail -n 10 file.txt +# 印出 file.txt 的前 10 行 +head -n 10 file.txt +# 將 file.txt 按行排序 +sort file.txt +# 報告或忽略重複的行,用選項 -d 印出重複的行 +uniq -d file.txt +# 打印每行中 ',' 之前內容 +cut -d ',' -f 1 file.txt +# 將 file.txt 文件所有 'okay' 替換爲 'great', (兼容正規表達式) +sed -i 's/okay/great/g' file.txt +# 將 file.txt 中匹配正則的行打印到標準輸出 +# 這裡印出以 "foo" 開頭, "bar" 結尾的行 +grep "^foo.*bar$" file.txt +# 使用選項 "-c" 統計行數 +grep -c "^foo.*bar$" file.txt +# 其他實用的選項參數 +grep -r "^foo.*bar$" someDir/ # 遞迴的 `grep` +grep -n "^foo.*bar$" file.txt # 顯示行數 +grep -rI "^foo.*bar$" someDir/ # 遞迴的 `grep`, 但忽略二進位檔案 +# 同樣的搜尋,再過濾包含「baz」的行 +grep "^foo.*bar$" file.txt | grep -v "baz" + +# 如果要搜尋字面上的字串而不是用正規表達式,使用 `fgrep` 或 `grep -F` +fgrep "foobar" file.txt + +# trap command allows you to execute a command when a signal is received by your script. +# `trap` 可以在一個script運行,接收到特定信號時,執行對應的指令 +# `trap` 接收到 `SIGHUP`、`SIGINT`、`SIGTERM` 信號時,會移除 $TEMP_FILE +trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM + +# `sudo` 可用於以superuser的身分執行指令 +$NAME1=$(whoami) +$NAME2=$(sudo whoami) +echo "Was $NAME1, then became more powerful $NAME2" + +# 以 bash 內建的 'help' 指令閱讀 Bash 內建文件: +help +help help +help for +help return +help source +help . + +# 用 man 指令閱讀相關的 Bash 手冊 +apropos bash +man 1 bash +man bash + +# 用 info 指令查閱命令的 info 文件 (info 中按 ? 顯示幫助信息) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# 閱讀 Bash 的 info 文件: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` -- cgit v1.2.3 From dce4fefd20c025d1dd7b05781e587a6c7997da91 Mon Sep 17 00:00:00 2001 From: tiaan Date: Sun, 31 Jul 2016 14:52:41 +0200 Subject: Fix inconsistencies and add resource links --- less.html.markdown | 150 ++++++++++++++++++++++++++++------------------------- 1 file changed, 80 insertions(+), 70 deletions(-) diff --git a/less.html.markdown b/less.html.markdown index a1018ca3..f4887947 100644 --- a/less.html.markdown +++ b/less.html.markdown @@ -3,6 +3,7 @@ language: less filename: learnless.less contributors: - ["Saravanan Ganesh", "http://srrvnn.me"] + - ["Tiaan du Plessis", "https://github.com/tidupls"] --- Less is a CSS pre-processor, that adds features such as variables, nesting, mixins and more. @@ -24,8 +25,8 @@ Less (and other preprocessors, such as [Sass](http://sass-lang.com/) help develo /* You can store a CSS value (such as a color) in a variable. Use the '@' symbol to create a variable. */ -@primary-color: #A3A4FF; -@secondary-color: #51527F; +@primary-color: #a3a4ff; +@secondary-color: #51527f; @body-font: 'Roboto', sans-serif; /* You can use the variables throughout your stylesheet. @@ -39,7 +40,7 @@ body { /* This would compile to: */ body { - background-color: #A3A4FF; + background-color: #a3a4ff; color: #51527F; font-family: 'Roboto', sans-serif; } @@ -86,7 +87,7 @@ div { margin-right: auto; left: 0; right: 0; - background-color: #A3A4FF; + background-color: #a3a4ff; } /* You can omit the mixin code from being compiled by adding parenthesis @@ -112,7 +113,66 @@ div { margin-right: auto; left: 0; right: 0; - background-color: #A3A4FF; + background-color: #a3a4ff; +} + + +/*Nesting +==============================*/ + + + +/*Less allows you to nest selectors within selectors */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #f00; + } +} + +/* '&' will be replaced by the parent selector. */ +/* You can also nest pseudo-classes. */ +/* Keep in mind that over-nesting will make your code less maintainable. +Best practices recommend going no more than 3 levels deep when nesting. +For example: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Compiles to: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; } @@ -130,8 +190,12 @@ body { width: round(10.25px); } +.header { + background-color: lighten(#000, 0.5); +} + .footer { - background-color: fadeout(#000000, 0.25) + background-color: fadeout(#000, 0.25) } /* Compiles to: */ @@ -140,6 +204,10 @@ body { width: 10px; } +.header { + background-color: #010101; +} + .footer { background-color: rgba(0, 0, 0, 0.75); } @@ -155,12 +223,12 @@ body { and return the percentage */ .average(@x, @y) { - @average_result: ((@x + @y) / 2); + @average-result: ((@x + @y) / 2); } div { .average(16px, 50px); // "call" the mixin - padding: @average_result; // use its "return" value + padding: @average-result; // use its "return" value } /* Compiles to: */ @@ -202,67 +270,6 @@ div { add unnecessary bloat to the files created by the Less compiler. */ - -/*Nesting -==============================*/ - - - -/*Less allows you to nest selectors within selectors */ - -ul { - list-style-type: none; - margin-top: 2em; - - li { - background-color: #FF0000; - } -} - -/* '&' will be replaced by the parent selector. */ -/* You can also nest pseudo-classes. */ -/* Keep in mind that over-nesting will make your code less maintainable. -Best practices recommend going no more than 3 levels deep when nesting. -For example: */ - -ul { - list-style-type: none; - margin-top: 2em; - - li { - background-color: red; - - &:hover { - background-color: blue; - } - - a { - color: white; - } - } -} - -/* Compiles to: */ - -ul { - list-style-type: none; - margin-top: 2em; -} - -ul li { - background-color: red; -} - -ul li:hover { - background-color: blue; -} - -ul li a { - color: white; -} - - - /*Partials and Imports ==============================*/ @@ -365,7 +372,9 @@ body { ## Practice Less -If you want to play with Less in your browser, check out [LESS2CSS](http://lesscss.org/less-preview/). +If you want to play with Less in your browser, check out: +* [Codepen](http://codepen.io/) +* [LESS2CSS](http://lesscss.org/less-preview/) ## Compatibility @@ -377,3 +386,4 @@ with your target browsers. ## Further reading * [Official Documentation](http://lesscss.org/features/) +* [Less CSS - Beginner's Guide](http://www.hongkiat.com/blog/less-basic/) -- cgit v1.2.3 From 47679dfcbe82811b7042a5994baab448adc15dd4 Mon Sep 17 00:00:00 2001 From: Valery Cherepanov Date: Tue, 2 Aug 2016 16:32:38 +0300 Subject: Some minor (mostly stylistic) fixes in C++ --- c++.html.markdown | 98 +++++++++++++++++++++++++++---------------------------- 1 file changed, 49 insertions(+), 49 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 290633f3..5dc1af59 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -808,8 +808,8 @@ void doSomethingWithAFile(const std::string& filename) // have default comparators, but you can override it. class Foo { public: - int j; - Foo(int a) : j(a) {} + int j; + Foo(int a) : j(a) {} }; struct compareFunction { bool operator()(const Foo& a, const Foo& b) const { @@ -948,7 +948,7 @@ f1 = f2; #include -// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members , +// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members, // its elements are accessed by their order in the tuple. // We start with constructing a tuple. @@ -958,10 +958,10 @@ const int maxN = 1e9; const int maxL = 15; auto second = make_tuple(maxN, maxL); -// printing elements of 'first' tuple +// Printing elements of 'first' tuple cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A -// printing elements of 'second' tuple +// Printing elements of 'second' tuple cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 15 // Unpacking tuple into variables @@ -989,43 +989,43 @@ cout << get<5>(concatenated_tuple) << "\n"; // prints: 'A' ///////////////////// -// CONTAINERS +// Containers ///////////////////// -// Containers or the Standard Template Library are some predefined templates -// They manages the storage space for its elements and provide -// member functions to access and manipulate them +// Containers or the Standard Template Library are some predefined templates. +// They manage the storage space for its elements and provide +// member functions to access and manipulate them. -// Few containers are as follows:- +// Few containers are as follows: -// Vectors (Dynamic arrays) +// Vector (Dynamic array) // Allow us to Define the Array or list of objects at run time -#include // will include the header file for vector -vector< Data_Type > Vector_name; // used to initialize the vector -cin>>val; +#include +vector Vector_name; // used to initialize the vector +cin >> val; Vector_name.push_back(val); // will push the value of variable into array -// To iterate through vector, we have 2 choices -// using normal looping +// To iterate through vector, we have 2 choices: +// Normal looping for(int i=0; i::iterator it; // initialize the iteartor for vector for(it=vector_name.begin(); it!=vector_name.end();++it) // For accessing the element of the vector // Operator [] -var= vector_name[index]; //will assign value at that index to var +var = vector_name[index]; // Will assign value at that index to var // Set -// Sets are containers that store unique elements following a specific order -// Very useful container to store unique values in sorted order -// without any other functions or code +// Sets are containers that store unique elements following a specific order. +// Set is a very useful container to store unique values in sorted order +// without any other functions or code. -#include // Will include the header file for sets -set< int > ST; // Will initialize the set of int data type +#include +set ST; // Will initialize the set of int data type ST.insert(30); // Will insert the value 30 in set ST ST.insert(10); // Will insert the value 10 in set ST ST.insert(20); // Will insert the value 20 in set ST @@ -1037,47 +1037,47 @@ ST.insert(30); // Will insert the value 30 in set ST ST.erase(20); // Will erase element with value 20 // Set ST: 10 30 // To iterate through Set we use iterators -set< int >::iterator it; -for(it=ST.begin();it::iterator it; +for(it=ST.begin();it // Will include the header file for map -map< char, int >mymap; // Will initalize the map with key as char and value as int +#include +map mymap; // Will initalize the map with key as char and value as int -mymap.insert ( pair('A',1) ); +mymap.insert(pair('A',1)); // Will insert value 1 for key A -mymap.insert ( pair('Z',26) ); +mymap.insert(pair('Z',26)); // Will insert value 26 for key Z // To iterate map::iterator it; for (it=mymap.begin(); it!=mymap.end(); ++it) - std::cout << it->first << "->" << it->second <<'\n'; + std::cout << it->first << "->" << it->second << '\n'; // Output: // A->1 // Z->26 // To find the value correponsing to a key it = mymap.find('Z'); -cout<second; +cout << it->second; + +// Output: 26 -// OUTPUT: 26 /////////////////////////////////// // Logical and Bitwise operators @@ -1087,17 +1087,17 @@ cout<second; // Logical operators -// C++ uses Short - circuit evaluation for boolean expressions, i.e, the second argument is executed or +// C++ uses Short-circuit evaluation for boolean expressions, i.e, the second argument is executed or // evaluated only if the first argument does not suffice to determine the value of the expression true && false // Performs **logical and** to yield false true || false // Performs **logical or** to yield true -! true // Performs **logcical not** to yield +! true // Performs **logical not** to yield false // Instead of using symbols equivalent keywords can be used true and false // Performs **logical and** to yield false -true or false // Performs **logical or** to yield true -not true // Performs **logcical not** to yield +true or false // Performs **logical or** to yield true +not true // Performs **logical not** to yield false // Bitwise operators @@ -1108,20 +1108,20 @@ not true // Performs **logcical not** to yield // **>>** Right Shift Operator -// << shifts bits to the right +// >> shifts bits to the right 4 >> 1 // Shifts bits of 4 to right by 1 to give 2 -// x << n can be thought as x / 2^n +// x >> n can be thought as x / 2^n -~4 // Performs a bitwise not +~4 // Performs a bitwise not 4 | 3 // Performs bitwise or 4 & 3 // Performs bitwise and 4 ^ 3 // Performs bitwise xor // Equivalent keywords are -compl 4 // Performs a bitwise not -4 bitor 3 // Performs bitwise or +compl 4 // Performs a bitwise not +4 bitor 3 // Performs bitwise or 4 bitand 3 // Performs bitwise and -4 xor 3 // Performs bitwise xor +4 xor 3 // Performs bitwise xor ``` -- cgit v1.2.3 From bc158cba137307ff34f4ef4b6b3e7fde1afb9179 Mon Sep 17 00:00:00 2001 From: LuJimin Date: Tue, 2 Aug 2016 23:51:15 +0800 Subject: fix bug MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改一些小问题。 --- zh-cn/kotlin-cn.html.markdown | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/zh-cn/kotlin-cn.html.markdown b/zh-cn/kotlin-cn.html.markdown index 5998f33f..1fd12f5b 100644 --- a/zh-cn/kotlin-cn.html.markdown +++ b/zh-cn/kotlin-cn.html.markdown @@ -27,7 +27,7 @@ Kotlin程序的入口点是一个"main"函数 fun main(args: Array) { /* 使用"var"或"val"来声明一个值。 - "val"声明的值不能被重新赋值,而"vars"声明的值可以。 + "val"声明的值不能被重新赋值,而"var"声明的值可以。 */ val fooVal = 10 // 以后我们不能再次给fooVal赋值 var fooVar = 10 @@ -53,7 +53,7 @@ fun main(args: Array) { /* 原始字符串用三重引号(""")来定义。 - 原始字符串可以包含新的行以及其他任何字符。 + 原始字符串可以包含换行符以及其他任何字符。 */ val fooRawString = """ fun helloWorld(val name : String) { @@ -73,7 +73,7 @@ fun helloWorld(val name : String) { 当某个变量的值可以为 null 的时候,我们必须被明确指定它是可为空的。 在变量声明处的类型后面加上?来标识它是可为空的。 我们可以用?.操作符来访问可为空的变量。 - 我们可以用?:操作符来指定一个替代值在变量为空的时候使用。 + 我们可以用?:操作符来指定一个在变量为空时使用的替代值。 */ var fooNullable: String? = "abc" println(fooNullable?.length) // => 3 @@ -96,8 +96,7 @@ fun helloWorld(val name : String) { println(hello()) // => Hello, world! /* - 用"vararg"关键字来修饰一个函数的参数 - 来允许可变参数传递给该函数 + 用"vararg"关键字来修饰一个函数的参数来允许可变参数传递给该函数 */ fun varargExample(vararg names: Int) { println("Argument has ${names.size} elements") @@ -123,7 +122,7 @@ fun helloWorld(val name : String) { fun not(f: (Int) -> Boolean) : (Int) -> Boolean { return {n -> !f.invoke(n)} } - // 命名函数可以被指定为参数使用::操作符。 + // 命名函数可以用::运算符被指定为参数。 val notOdd = not(::odd) val notEven = not(::even) // 匿名函数可以被指定为参数。 @@ -286,7 +285,7 @@ fun helloWorld(val name : String) { println(result) /* - 我们可以通过使用"is"操作符来检查一个对象是否是特定类型的。 + 我们可以通过使用"is"操作符来检查一个对象是否是某个类型的。 如果对象通过了类型检查那么它可以作为该类型使用而不需要强制转换它。 */ fun smartCastExample(x: Any) : Boolean { @@ -310,7 +309,7 @@ fun helloWorld(val name : String) { println(smartCastExample(true)) // => true /* - 扩展是用来添加新的功能到一个类的。 + 扩展是用来给一个类添加新的功能的。 它类似于C#的扩展方法。 */ fun String.remove(c: Char): String { -- cgit v1.2.3 From fdc1cf944dbafd7ee89c421c871e70f57e5aacb5 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Wed, 3 Aug 2016 01:45:22 +0800 Subject: [bash/zh-tw] add missing line for rm command --- zh-tw/bash-tw.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/zh-tw/bash-tw.html.markdown b/zh-tw/bash-tw.html.markdown index f195d273..3210f001 100644 --- a/zh-tw/bash-tw.html.markdown +++ b/zh-tw/bash-tw.html.markdown @@ -239,7 +239,9 @@ echo "#helloworld" | cat > output.out echo "#helloworld" | tee output.out >/dev/null # 清理臨時文件並顯示詳情(增加 '-i' 選項啓用互動模式) +# 警告: `rm` 指令無法復原 rm -v output.out error.err output-and-error.log +rm -r tempDir/ # 遞迴刪除 # 一個指令可用 $( ) 嵌套在另一個指令內部: # 以下的指令會印出當前目錄下的目錄和文件總數 -- cgit v1.2.3 From 7d585f8174d4abbe9dd3f4707f937c23ad8c5d51 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Wed, 3 Aug 2016 02:05:09 +0800 Subject: [bash/zh-tw] delete extra line --- zh-tw/bash-tw.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/zh-tw/bash-tw.html.markdown b/zh-tw/bash-tw.html.markdown index 3210f001..78b39f2d 100644 --- a/zh-tw/bash-tw.html.markdown +++ b/zh-tw/bash-tw.html.markdown @@ -176,7 +176,6 @@ echo "START OF FILE\n$Contents\nEND OF FILE" cp srcFile.txt clone.txt cp -r srcDirectory/ dst/ # 遞迴複製 -# `scp` or `sftp` if you plan on exchanging files between computers. # 如需在兩台電腦間交換檔案,請查看 `scp` 或 `sftp`。 # `scp` 與 `cp` 相似。 # `sftp` 則有更高的互動性(與 `ftp` 相似)。 -- cgit v1.2.3 From 959d95dd78ffa939f876bd559d0331f29b64e075 Mon Sep 17 00:00:00 2001 From: Joakim Lahtinen Date: Thu, 4 Aug 2016 09:10:00 +0200 Subject: [json/sv-se] Synced with english version. (#2324) * [json/sv-se] Synced with english version. * [json/sv-se] Added swedish link. --- sv-se/json-sv.html.markdown | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/sv-se/json-sv.html.markdown b/sv-se/json-sv.html.markdown index c2ee36dd..002aec2e 100644 --- a/sv-se/json-sv.html.markdown +++ b/sv-se/json-sv.html.markdown @@ -4,18 +4,30 @@ filename: learnjson-sv.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] + - ["Michael Neth", "https://github.com/infernocloud"] translators: - ["Lari Kovanen", "https://github.com/larkov"] + - ["Joakim Lahtinen", "https://github.com/VibyJocke"] lang: sv-se --- -Eftersom JSON är ett extremt lätt data-utbytes format så kommer detta -förmodligen att vara den lättaste "Learn X in Y Minutes" någonsin. +JSON är ett extremt enkelt datautbytesformat. Som [json.org](http://json.org) beskriver så är det lätt för människor att läsa och skriva, och för datorer att tolka och generera. -JSON i dess renaste form har inga kommentarer, men de flesta tolkarna accepterar -C-stils (`//`, `/* */`) kommentarer. Detta dokument kommer dock att tillämpa -100% giltigt JSON. Lyckligtvis så är resten av dokumentet självförklarande. +En bit av JSON måste representera antingen: +* En samling av namn/värde-par (`{ }`). I olika språk kan denna realiseras som ett objekt, struct, dictionary, hash-tabell, nyckellista eller en associativ array. +* En ordnad lista av värden (`[ ]`). I olika språk kan denna realiseras som en array, vektor, lista eller sekvens. +JSON i dess renaste form har inga kommentarer, men de flesta tolkarna accepterar C-stils (`//`, `/* */`) kommentarer. Vissa tolkar tolererar även komman efter sista elementet i en array, eller det sista attributet av ett objekt, men dessa bör undvikas för bättre kompabilitet. + +Detta dokument kommer dock att tillämpa 100% giltigt JSON. Lyckligtvis så är resten av dokumentet självförklarande. + +Följande datatyper stöds: +* Strängar: `"hello"`, `"\"A quote.\""`, `"\u0abe"`, `"Newline.\n"` +* Nummer: `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4` +* Objekt: `{ "key": "value" }` +* Arrayer: `["Values"]` +* Övriga: `true`, `false`, `null` ```json { @@ -57,6 +69,16 @@ C-stils (`//`, `/* */`) kommentarer. Detta dokument kommer dock att tillämpa , "en kommentar till": "vad fint" }, + + + "blanksteg": "Spelar ingen roll.", + + + "det var kort": "Nu är du klar och kan allt vad JSON har att erbjuda." } ``` + +## Fortsatt läsning + +* [JSON.org](http://json.org/json-sv.html) Allt du kan tänkas vilja veta om JSON, och lite därtill. -- cgit v1.2.3 From 25aa41467a13fbc98de3a0a058bd5ecc2f03b5c3 Mon Sep 17 00:00:00 2001 From: robochat Date: Thu, 4 Aug 2016 10:33:58 +0200 Subject: [fortran/en] Adding a Fortran (95) Tutorial (#2318) * adding fortran tutorial * [fortran/en] fixing some typos * [fortran/en] changed a word * [fortran/en] changed another word * [fortran/en] typos and improvements. * [fortran/en] moving comments around * [fortran/en] moving print statement introduction to appropriate section * [fortran/en] changing exit code to generic error code * [fortran/en] changing bessel_j0 (available from fortran 2008) to log10 (available since fortran 77). * [fortran/en] being explicit about using cleaner Fortran 2003 notation * [fortran/en] code whitespace consistency * [fortran/en] adding examples on implied-DO loops. * [fortran/en] small adjustment to implied-DO loop example to make it more idiomatic --- fortran95.html.markdown | 452 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 452 insertions(+) create mode 100644 fortran95.html.markdown diff --git a/fortran95.html.markdown b/fortran95.html.markdown new file mode 100644 index 00000000..8479fef8 --- /dev/null +++ b/fortran95.html.markdown @@ -0,0 +1,452 @@ +--- +language: Fortran +contributors: + - ["Robert Steed", "https://github.com/robochat"] +filename: learnfortran.f95 +--- + +Fortran is one of the oldest computer languages. It was developed in the 1950s +by IBM for numeric calculations (Fortran is an abreviation of "Formula +Translation"). Despite its age, it is still used for high-performance computing +such as weather prediction. However, the language has changed considerably over +the years, although mostly maintaining backwards compatibility; well known +versions are FORTRAN 77, Fortran 90, Fortran 95, Fortran 2003, Fortran 2008 and +Fortran 2015. + +This overview will discuss the features of Fortran 95 since it is the most +widely implemented of the more recent specifications and the later versions are +largely similar (by comparison FORTRAN 77 is a very different language). + +```fortran + +! This is a comment. + + +program example !declare a program called example. + + ! Code can only exist inside programs, functions, subroutines or modules. + ! Using indentation is not required but it is recommended. + + + ! Declaring Variables + ! =================== + + ! All declarations must come before statements and expressions. + + implicit none !prevents dynamic declaration of variables (recommended!) + ! Implicit none must be redeclared in every function/program/module... + + ! IMPORTANT - Fortran is case insensitive. + real z + REAL Z2 + + real :: v,x ! WARNING: default initial values are compiler dependent! + real :: a = 3, b=2E12, c = 0.01 + integer :: i, j, k=1, m + real, parameter :: PI = 3.1415926535897931 !declare a constant. + logical :: y = .TRUE. , n = .FALSE. !boolean type. + complex :: w = (0,1) !sqrt(-1) + character (len=3) :: month !string of 3 characters. + + real :: array(6) !declare an array of 6 reals. + real, dimension(4) :: arrayb !another way to declare an array. + integer :: arrayc(-10:10) !an array with a custom index. + real :: array2d(3,2) !multidimensional array. + + ! The '::' separators are not always necessary but are recommended. + + ! many other variable attributes also exist: + real, pointer :: p !declare a pointer. + + integer, parameter :: LP = selected_real_kind(20) + real (kind = LP) :: d !long precision variable. + + ! WARNING: initialising variables during declaration causes problems + ! in functions since this automatically implies the 'save' attribute + ! whereby values are saved between function calls. In general, separate + ! declaration and initialisation code except for constants! + + + ! Strings + ! ======= + + character :: a_char = 'i' + character (len = 6) :: a_str = "qwerty" + character (len = 30) :: str_b + character (len = *), parameter :: a_long_str = "This is a long string." + !can have automatic counting of length using (len=*) but only for constants. + + str_b = a_str // " keyboard" !concatenate strings using // operator. + + + ! Assignment & Arithmetic + ! ======================= + + Z = 1 !assign to variable z declared above (case insensitive). + j = 10 + 2 - 3 + a = 11.54 / (2.3 * 3.1) + b = 2**3 !exponentiation + + + ! Control Flow Statements & Operators + ! =================================== + + ! Single-line if statement + if (z == a) b = 4 !condition always need surrounding parentheses. + + if (z /= a) then !z not equal to a + ! Other symbolic comparisons are < > <= >= == /= + b = 4 + else if (z .GT. a) then !z greater than a + ! Text equivalents to symbol operators are .LT. .GT. .LE. .GE. .EQ. .NE. + b = 6 + else if (z < a) then !'then' must be on this line. + b = 5 !execution block must be on a new line. + else + b = 10 + end if !end statement needs the 'if' (or can use 'endif'). + + + if (.NOT. (x < c .AND. v >= a .OR. z == z)) then !boolean operators. + inner: if (.TRUE.) then !can name if-construct. + b = 1 + endif inner !then must name endif statement. + endif + + + i = 20 + select case (i) + case (0) !case i == 0 + j=0 + case (1:10) !cases i is 1 to 10 inclusive. + j=1 + case (11:) !all cases where i>=11 + j=2 + case default + j=3 + end select + + + month = 'jan' + ! Condition can be integer, logical or character type. + ! Select constructions can also be named. + monthly: select case (month) + case ("jan") + j = 0 + case default + j = -1 + end select monthly + + + do i=2,10,2 !loops from 2 to 10 (inclusive) in increments of 2. + innerloop: do j=1,3 !loops can be named too. + exit !quits the loop. + end do innerloop + cycle !jump to next loop iteration. + enddo + + + ! Goto statement exists but it is heavily discouraged though. + goto 10 + stop 1 !stops code immediately (returning specified condition code). +10 j = 201 !this line is labeled as line 10 + + + ! Arrays + ! ====== + array = (/1,2,3,4,5,6/) + array = [1,2,3,4,5,6] !using Fortran 2003 notation. + arrayb = [10.2,3e3,0.41,4e-5] + array2d = reshape([1.0,2.0,3.0,4.0,5.0,6.0], [3,2]) + + ! Fortran array indexing starts from 1. + ! (by default but can be defined differently for specific arrays). + v = array(1) !take first element of array. + v = array2d(2,2) + + print *, array(3:5) !print all elements from 3rd to 5th (inclusive). + print *, array2d(1,:) !print first column of 2d array. + + array = array*3 + 2 !can apply mathematical expressions to arrays. + array = array*array !array operations occur element-wise. + !array = array*array2d !these arrays would not be compatible. + + ! There are many built-in functions that operate on arrays. + c = dot_product(array,array) !this is the dot product. + ! Use matmul() for matrix maths. + c = sum(array) + c = maxval(array) + print *, minloc(array) + c = size(array) + print *, shape(array) + m = count(array > 0) + + ! Loop over an array (could have used Product() function normally). + v = 1 + do i = 1, size(array) + v = v*array(i) + end do + + ! Conditionally execute element-wise assignments. + array = [1,2,3,4,5,6] + where (array > 3) + array = array + 1 + elsewhere (array == 2) + array = 1 + elsewhere + array = 0 + end where + + ! Implied-DO loops are a compact way to create arrays. + array = [ (i, i = 1,6) ] !creates an array of [1,2,3,4,5,6] + array = [ (i, i = 1,12,2) ] !creates an array of [1,3,5,7,9,11] + array = [ (i**2, i = 1,6) ] !creates an array of [1,4,9,16,25,36] + array = [ (4,5, i = 1,3) ] !creates an array of [4,5,4,5,4,5] + + + ! Input/Output + ! ============ + + print *, b !print the variable 'b' to the command line + + ! We can format our printed output. + print "(I6)", 320 !prints ' 320' + print "(I6.4)", 3 !prints ' 0003' + print "(F6.3)", 4.32 !prints ' 4.320' + + ! The letter indicates the expected type and the number afterwards gives + ! the number of characters to use for printing the value. + ! Letters can be I (integer), F (real), E (engineering format), + ! L (logical), A (characters) ... + print "(I3)", 3200 !print '***' since the number doesn't fit. + + ! we can have multiple format specifications. + print "(I5,F6.2,E6.2)", 120, 43.41, 43.41 + print "(3I5)", 10, 20, 30 !3 repeats of integers (field width = 5). + print "(2(I5,F6.2))", 120, 43.42, 340, 65.3 !repeated grouping of formats. + + ! We can also read input from the terminal. + read *, v + read "(2F6.2)", v, x !read two numbers + + ! To read a file. + open(unit=11, file="records.txt", status="old") + ! The file is referred to by a 'unit number', an integer that you pick in + ! the range 9:99. Status can be one of {'old','replace','new'}. + read(unit=11, fmt="(3F10.2)") a, b, c + close(11) + + ! To write a file. + open(unit=12, file="records.txt", status="replace") + write(12, "(F10.2,F10.2,F10.2)") c, b, a + close(12) + + ! There are more features available than discussed here and alternative + ! variants due to backwards compatability with older Fortran versions. + + + ! Built-in Functions + ! ================== + + ! Fortran has around 200 functions/subroutines intrinsic to the language. + ! Examples - + call cpu_time(v) !sets 'v' to a time in seconds. + k = ior(i,j) !bitwise OR of 2 integers. + v = log10(x) !log base 10. + i = floor(b) !returns the closest integer less than or equal to x. + v = aimag(w) !imaginary part of a complex number. + + + ! Functions & Subroutines + ! ======================= + + ! A subroutine runs some code on some input values and can cause + ! side-effects or modify the input values. + + call routine(a,c,v) !subroutine call. + + ! A function takes a list of input parameters and returns a single value. + ! However the input parameters may still be modified and side effects + ! executed. + + m = func(3,2,k) !function call. + + ! Function calls can also be evoked within expressions. + Print *, func2(3,2,k) + + ! A pure function is a function that doesn't modify its input parameters + ! or cause any side-effects. + m = func3(3,2,k) + + +contains ! Zone for defining sub-programs internal to the program. + + ! Fortran has a couple of slightly different ways to define functions. + + integer function func(a,b,c) !a function returning an integer value. + implicit none !best to use implicit none in function definitions too. + integer :: a,b,c !type of input parameters defined inside the function. + if (a >= 2) then + func = a + b + c !the return variable defaults to the function name. + return !can return the current value from the function at any time. + endif + func = a + c + ! Don't need a return statement at the end of a function. + end function func + + + function func2(a,b,c) result(f) !return variable declared to be 'f'. + implicit none + integer, intent(in) :: a,b !can declare and enforce that variables + !are not modified by the function. + integer, intent(inout) :: c + integer :: f !function return type declared inside the function. + integer :: cnt = 0 !GOTCHA - initialisation implies variable is + !saved between function calls. + f = a + b - c + c = 4 !altering the value of an input variable. + cnt = cnt + 1 !count number of function calls. + end function func2 + + + pure function func3(a,b,c) !a pure function can have no side-effects. + implicit none + integer, intent(in) :: a,b,c + integer :: func3 + func3 = a*b*c + end function func3 + + + subroutine routine(d,e,f) + implicit none + real, intent(inout) :: f + real, intent(in) :: d,e + f = 2*d + 3*e + f + end subroutine routine + + +end program example ! End of Program Definition ----------------------- + + +! Functions and Subroutines declared externally to the program listing need +! to be declared to the program using an Interface declaration (even if they +! are in the same source file!) (see below). It is easier to define them within +! the 'contains' section of a module or program. + +elemental real function func4(a) result(res) +! An elemental function is a Pure function that takes a scalar input variable +! but can also be used on an array where it will be separately applied to all +! of the elements of an array and return a new array. + real, intent(in) :: a + res = a**2 + 1.0 +end function func4 + + +! Modules +! ======= + +! A module is a useful way to collect related declarations, functions and +! subroutines together for reusability. + +module fruit + real :: apple + real :: pear + real :: orange +end module fruit + + +module fruity + ! Declarations must be in the order: modules, interfaces, variables. + ! (can declare modules and interfaces in programs too). + + use fruit, only: apple, pear ! use apple and pear from fruit module. + implicit none !comes after module imports. + + private !make things private to the module (default is public). + ! Declare some variables/functions explicitly public. + public :: apple,mycar,create_mycar + ! Declare some variables/functions private to the module (redundant here). + private :: func4 + + ! Interfaces + ! ========== + ! Explicitly declare an external function/procedure within the module + ! (better in general to put functions/procedures in the 'contains' section). + interface + elemental real function func4(a) result(res) + real, intent(in) :: a + end function func4 + end interface + + ! Overloaded functions can be defined using named interfaces. + interface myabs + ! Can use 'module procedure' keyword to include functions already + ! defined within the module. + module procedure real_abs, complex_abs + end interface + + ! Derived Data Types + ! ================== + ! Can create custom structured data collections. + type car + character (len=100) :: model + real :: weight !(kg) + real :: dimensions(3) !i.e. length-width-height (metres). + character :: colour + end type car + + type(car) :: mycar !declare a variable of your custom type. + ! See create_mycar() routine for usage. + + ! Note: There are no executable statements in modules. + +contains + + subroutine create_mycar(mycar) + ! Demonstrates usage of a derived data type. + implicit none + type(car),intent(out) :: mycar + + ! Access type elements using '%' operator. + mycar%model = "Ford Prefect" + mycar%colour = 'r' + mycar%weight = 1400 + mycar%dimensions(1) = 5.0 !default indexing starts from 1! + mycar%dimensions(2) = 3.0 + mycar%dimensions(3) = 1.5 + + end subroutine + + real function real_abs(x) + real :: x + if (x<0) then + real_abs = -x + else + real_abs = x + end if + end function real_abs + + real function complex_abs(z) + complex :: z + ! long lines can be continued using the continuation character '&' + complex_abs = sqrt(real(z)**2 + & + aimag(z)**2) + end function complex_abs + + +end module fruity + +``` + +### More Resources + +For more information on Fortran: + ++ [wikipedia](https://en.wikipedia.org/wiki/Fortran) ++ [Fortran_95_language_features](https://en.wikipedia.org/wiki/Fortran_95_language_features) ++ [fortranwiki.org](http://fortranwiki.org) ++ [www.fortran90.org/](http://www.fortran90.org) ++ [list of Fortran 95 tutorials](http://www.dmoz.org/Computers/Programming/Languages/Fortran/FAQs%2C_Help%2C_and_Tutorials/Fortran_90_and_95/) ++ [Fortran wikibook](https://en.wikibooks.org/wiki/Fortran) ++ [Fortran resources](http://www.fortranplus.co.uk/resources/fortran_resources.pdf) ++ [Mistakes in Fortran 90 Programs That Might Surprise You](http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html) -- cgit v1.2.3 From 2f28300d10505c294ae1d805514c7d01636925f2 Mon Sep 17 00:00:00 2001 From: Wim Date: Thu, 4 Aug 2016 14:41:16 +0200 Subject: [fsharp/en] Explain the cons pattern, and introduce recursion keyword (#2310) * [fsharp/en] Explain the cons pattern, and introduce recursion keyword Was confused when reading the sieve function and thought it could be explained a little more. I got some help from http://hestia.typepad.com/flatlander/2010/07/f-pattern-matching-for-beginners-part-4-lists-and-recursion.html * Forgot the word 'notation' --- fsharp.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/fsharp.html.markdown b/fsharp.html.markdown index e345201d..69f4eb60 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -175,7 +175,12 @@ module ListExamples = // list comprehensions (aka generators) let squares = [for i in 1..10 do yield i * i] - // prime number generator + // A prime number generator + // - this is using a short notation for the pattern matching syntax + // - (p::xs) is 'first :: tail' of the list, could also be written as p :: xs + // this means this matches 'p' (the first item in the list), and xs is the rest of the list + // this is called the 'cons pattern' + // - uses 'rec' keyword, which is necessary when using recursion let rec sieve = function | (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ] | [] -> [] -- cgit v1.2.3 From f6c353eb37b553ae18e659eb5b6eb883e43e4b00 Mon Sep 17 00:00:00 2001 From: tiaan Date: Thu, 4 Aug 2016 23:05:29 +0200 Subject: Remove name from contributors list. --- less.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/less.html.markdown b/less.html.markdown index f4887947..d88b6ee9 100644 --- a/less.html.markdown +++ b/less.html.markdown @@ -3,7 +3,6 @@ language: less filename: learnless.less contributors: - ["Saravanan Ganesh", "http://srrvnn.me"] - - ["Tiaan du Plessis", "https://github.com/tidupls"] --- Less is a CSS pre-processor, that adds features such as variables, nesting, mixins and more. @@ -26,7 +25,7 @@ Less (and other preprocessors, such as [Sass](http://sass-lang.com/) help develo Use the '@' symbol to create a variable. */ @primary-color: #a3a4ff; -@secondary-color: #51527f; +@secondary-color: #51527f; @body-font: 'Roboto', sans-serif; /* You can use the variables throughout your stylesheet. -- cgit v1.2.3 From 804261b9e5d6c0686d7cbc236b239afe853db57f Mon Sep 17 00:00:00 2001 From: Alexander Salamanca Date: Sun, 7 Aug 2016 02:32:44 -0500 Subject: [ps/es] Added initial version of powershell Spanish guide (based on the latest English version) (#2325) * progress in translating to spanish the powershell guide * traducido todo * fixed reported issues in powershell spanish file --- es-es/powershell-es.html.markdown | 329 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 329 insertions(+) create mode 100644 es-es/powershell-es.html.markdown diff --git a/es-es/powershell-es.html.markdown b/es-es/powershell-es.html.markdown new file mode 100644 index 00000000..dd92eb97 --- /dev/null +++ b/es-es/powershell-es.html.markdown @@ -0,0 +1,329 @@ +--- +category: tool +tool: powershell +contributors: + - ["Wouter Van Schandevijl", "https://github.com/laoujin"] +translators: + - ["Alexander Salamanca", "https://github.com/alexitosrv"] +filename: LearnPowershell-es.ps1 +lang: es-es +--- + +PowerShell es el lenguaje de automatización y gestión de configuraciones de Windows hecho por Microsoft basado en .NET Framework. Desde Windows 7 en adelante, esos sistemas operativos incluyen un intérprete de PowerShell. +Casi todos los ejemplos a continuación pueden ser parte de un script o ejecutados directamente en la consola de PowerShell. + +Una diferencia clave con respecto a Bash es que en PowerShell casi todo son manipulaciones de objetos en vez de análisis sobre flujos de texto plano. + +[Leer más acá.](https://technet.microsoft.com/en-us/library/bb978526.aspx) (EN) + +Si no está seguro sobre el ambiente de ejecución en su sistema: + +``` +Get-ExecutionPolicy -List +Set-ExecutionPolicy AllSigned +# Otras opciones de políticas de ejecución son: +# - Restricted: Los scripts no correrán. +# - RemoteSigned: Los scripts que se hayan descargado sólo correrán si han sido firmados por un editor de confianza. +# - AllSigned: Los scripts requieren ser firmados por un editor de confianza. +# - Unrestricted: Ejecuta cualquier script. +help about_Execution_Policies # para obtener más ayuda sobre políticas de ejecución. + +# Versión instalada de PowerShell: +$PSVersionTable +``` + +Para obtener ayuda: + +``` +# 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' +Get-Alias ps +Get-Alias -Definition Get-Process + +Get-Help ps | less # alias: help +ps | Get-Member # alias: gm + +Show-Command Get-EventLog # Muestra un formulario para llenar los parámetros del comando Get-EventLog + +Update-Help # Actualiza la ayuda (debe ser ejecutado en una consola elevada como admin) +``` + +Acá inicia el tutorial: + +``` +# Como ya lo notó, los comentarios empiezan con # + +# Ejemplo de un simple hola mundo: +echo Hola mundo! +# echo es el alias del comando Write-Output (a los comandos también se les dice cmdlets) +# La mayoría de los cmdlets y funciones siguen la convención de llamarse de la forma: Verbo-Sustantivo + +# Cada comando inicia en una nueva línea, o después de un punto y coma: +echo 'Esta es la primer línea'; echo 'Esta es la segunda' + +# La declaración de una variable se ve así: +$unaCadena ="Algún texto" +# O así: +$unNumero = 5 -as [double] +$unaLista = 1,2,3,4,5 +$unaCadena = $unaLista -join '--' # también existe el parámetro -split +$unaTablaHash = @{nom1='val1'; nom2='val2'} + +# Uso de variables: +echo $unaCadena +echo "Interpolación: $unaCadena" +echo "`$unaCadena tiene longitud de $($unaCadena.Length)" +echo '$unaCadena' +echo @" +Esta es una Here-String +$otraVariable +"@ +# Note que una ' (comilla simple) no expande las variables! +# Las Here-Strings también funcionan con comilla simple + +# Variables Automáticas: +# Hay algunas variables previamente definidas en el ambiente que le pueden servir, tales como +echo "Booleanos: $TRUE y $FALSE" +echo "Valor vacío: $NULL" +echo "Valor de retorno del último programa: $?" +echo "Código de salida del último programa en Windows: $LastExitCode" +echo "El último token en la última línea de la sesión activa: $$" +echo "El primer token: $^" +echo "PID del script: $PID" +echo "Ruta completa del directorio dónde está el script actual: $PSScriptRoot" +echo 'Ruta completa de script actual: ' + $MyInvocation.MyCommand.Path +echo "Ruta completa de directorio actual: $Pwd" +echo "Argumentos pasados a la invocación de una función, script o bloque de código: $PSBoundParameters" +echo "Argumentos no predefinidos: $($Args -join ', ')." +# Para saber más sobre variables automáticas: `help about_Automatic_Variables` + +# Para enlazar otro archivo (operador punto) +. .\otroNombreDeScript.ps1 + + +### Control de Flujo +# Tenemos la estructura de if como es usual: +if ($Edad -is [string]) { + echo 'Pero... si $Edad no puede ser una cadena de texto!' +} elseif ($Edad -lt 12 -and $Edad -gt 0) { + echo 'Niño (Menor de 12. Mayor que 0)' +} else { + echo 'Adulto' +} + +# Sentencias switch de PS son más poderosas comparadas con otros lenguajes +$val = "20" +switch($val) { + { $_ -eq 42 } { "La respuesta es 42"; break } + '20' { "Exactamente 20"; break } + { $_ -like 's*' } { "No distingue entre mayúsculas/minúsculas"; break } + { $_ -clike 's*'} { "clike, ceq, cne para ser diferenciar el caso entre mayúsculas/minúsculas"; break } + { $_ -notmatch '^.*$'} { "Emparejamiento de expresiones regulares. cnotmatch, cnotlike, ..."; break } + { 'x' -contains 'x'} { "FALSO! -contains es para listas!"; break } + default { "Otros" } +} + +# El for clásico +for($i = 1; $i -le 10; $i++) { + "Número de ciclo $i" +} +# O más corto +1..10 | % { "Número de ciclo $_" } + +# PowerShell también incluye +foreach ($var in 'valor1','valor2','valor3') { echo $var } +# while () {} +# do {} while () +# do {} until () + +# Manejo de excepciones +try {} catch {} finally {} +try {} catch [System.NullReferenceException] { + echo $_.Exception | Format-List -Force +} + + +### Proveedores +# Lista de archivos y directorios en la ubicación actual +ls # o el alias `dir` +cd ~ # ir al directorio principal del usuario + +Get-Alias ls # -> Get-ChildItem +# ¿¡Eh!? Estos cmdlets tienen nombres genéricos porque a diferencia de otros lenguajes de scripting, +# PowerShell no opera únicamente en el directorio actual. +cd HKCU: # se dirige a la rama HKEY_CURRENT_USER del registro de Windows + +# Para hacer un listado de todos los proveedores disponibles +Get-PSProvider + + +### Tuberías +# Los Cmdlets tienen parámetros que controlan su ejecución: +Get-ChildItem -Filter *.txt -Name # Se obtiene sólo el nombre de todos los archivos txt +# Sólo se necesita escribir caracteres de un parámetro hasta que deja de ser ambiguo +ls -fi *.txt -n # -f no se puede porque también existe -Force +# Use `Get-Help Get-ChildItem -Full` para un tratado más completo + +# Los results del cmdlet anterior se le pueden pasar como entrada al siguiente. +# `$_` representa el objeto actual en el objeto de tubería. +ls | Where-Object { $_.Name -match 'c' } | Export-CSV exportado.txt +ls | ? { $_.Name -match 'c' } | ConvertTo-HTML | Out-File exportado.html + +# Si se confunde con la tubería use `Get-Member` para revisar +# los métodos y propiedades de los objetos de la tubería: +ls | Get-Member +Get-Date | gm + +# ` es el caracter de continuación de línea. O termine la línea con un | +Get-Process | Sort-Object ID -Descending | Select-Object -First 10 Name,ID,VM ` + | Stop-Process -WhatIf + +Get-EventLog Application -After (Get-Date).AddHours(-2) | Format-List + +# Use % como una abreviación de ForEach-Object +(a,b,c) | ForEach-Object ` + -Begin { "Iniciando"; $counter = 0 } ` + -Process { "Procesando $_"; $counter++ } ` + -End { "Terminando: $counter" } + +# El siguiente comando ps (alias de Get-Process) devuelve una tabla con 3 columnas +# La tercera columan es el valor de memoria virtual en MB y usando 2 dígitos decimales +# Las columnas calculadas pueden escribirse más extensamente como: +# `@{name='lbl';expression={$_}` +ps | Format-Table ID,Name,@{n='VM(MB)';e={'{0:n2}' -f ($_.VM / 1MB)}} -autoSize + + +### Funciones +# El atributo [string] es opcional. +function foo([string]$nombre) { + echo "Hey $nombre, aquí tiene una función" +} + +# Llamando una función +foo "Diga mi nombre" + +# Funciones con parámetros nombrados, atributos de parámetros y documentación analizable +<# +.SYNOPSIS +Establecer un nuevo sitio web +.DESCRIPTION +Crea todo lo que su sitio necesite +.PARAMETER siteName +El nombre para el nuevo sitio web +.EXAMPLE +Crear-SitioWeb -Nombre SitioBonito -Po 5000 +Crear-SitioWeb SiteWithDefaultPort +Crear-SitioWeb nombreSitio 2000 # ERROR! No se pudo validar arguemento de puerto +('nombre1','nombre2') | Crear-SitioWeb -Verbose +#> +function Crear-SitioWeb() { + [CmdletBinding()] + param ( + [Parameter(ValueFromPipeline=$true, Mandatory=$true)] + [Alias('nombre')] + [string]$nombreSitio, + [ValidateSet(3000,5000,8000)] + [int]$puerto = 3000 + ) + BEGIN { Write-Verbose 'Creando nuevo(s) sitio(s) web' } + PROCESS { echo "nombre: $nombreSitio, puerto: $puerto" } + END { Write-Verbose 'Sitio(s) web creado(s)' } +} + + +### Todo es .NET +# Una cadena PS es, de hecho, una cadena tipo System.String de .NET +# Todos los métodos y propiedades de .NET están disponibles +'cadena'.ToUpper().Replace('E', 'eee') +# O más powershellezco +'cadena'.ToUpper() -replace 'E', 'eee' + +# ¿No recuerda cómo es que se llama cierto método .NET? +'cadena' | gm + +# Sintaxis para ejecutar métodos .NET estáticos +[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') + +# Nótese que cualquier función que proviene de .NET Framework REQUIERE paréntesis para ser invocada +# al contrario de las funciones definidas desde PS, las cuales NO PUEDEN ser invocadas con paréntesis. +# Si se invoca una función/cmdlet de PS usando paréntesis, +# es equivalente a que le estuviera pasando un parámetro de tipo lista +$writer = New-Object System.IO.StreamWriter($ruta, $true) +$writer.Write([Environment]::NewLine) +$writer.Dispose() + +### Entrada/Salida +# Leyendo una variable +$Nombre = Read-Host "¿Cómo se llama?" +echo "¡Hola $Nombre!" +[int]$Edad = Read-Host "¿Cuál es su edad?" + +# Test-Path, Split-Path, Join-Path, Resolve-Path +# Get-Content filename # devuelve un string[] +# Set-Content, Add-Content, Clear-Content +Get-Command ConvertTo-*,ConvertFrom-* + + +### Material útil +# Actualizar la ruta de ejecuciones (PATH) +$env:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User") + +# Encontrar Python en el path +$env:PATH.Split(";") | Where-Object { $_ -like "*python*"} + +# Cambiar el directorio de trabajo sin tener que memorizar la ruta anterior +Push-Location c:\temp # se cambia el directorio de trabajo a c:\temp +Pop-Location # revierte el cambio y se devuelve a donde estaba al principio +# Los aliases son : pushd y popd + +# Desbloquear un archivo después de descargarlo de Internet +Get-ChildItem -Recurse | Unblock-File + +# Abre Windows Explorer en la ruta actual (usando el alias ii de Invoke-Item) +ii . + +# Pulse cualquier tecla para salir +$host.UI.RawUI.ReadKey() +return + +# Para crear un acceso directo +$WshShell = New-Object -comObject WScript.Shell +$Shortcut = $WshShell.CreateShortcut($link) +$Shortcut.TargetPath = $file +$Shortcut.WorkingDirectory = Split-Path $file +$Shortcut.Save() +``` + + +Configurando el shell + +``` +# $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)) { + New-Item -Type file -Path $Profile -Force + notepad $Profile +} +# Más información en: `help about_profiles` +# Para un shell más productivo, asegúrese de verifivar el proyecto PSReadLine descrito abajo +``` + +Proyectos interesantes (EN) + +* [Channel9](https://channel9.msdn.com/Search?term=powershell%20pipeline#ch9Search&lang-en=en) Tutoriales de PowerShell +* [PSGet](https://github.com/psget/psget) NuGet para PowerShell +* [PSReadLine](https://github.com/lzybkr/PSReadLine/) Una implementación inspirada en bash para PowerShell (¡Es tan buena que ahora viene con Windows10 por defecto!) +* [Posh-Git](https://github.com/dahlbyk/posh-git/) Un intérprete bonito de Git (¡Recomendado!) +* [PSake](https://github.com/psake/psake) Herramienta de automatización de compilaciones +* [Pester](https://github.com/pester/Pester) Framework de pruebas BDD +* [Jump-Location](https://github.com/tkellogg/Jump-Location) Powershell `cd` que lee su mente + + +Material no cubierto en esta guía + +* WMI: Windows Management Intrumentation (Get-CimInstance) +* Multitarea: Start-Job -scriptBlock {...}, +* Firmas de código +* Remoting (Enter-PSSession/Exit-PSSession; Invoke-Command) -- cgit v1.2.3 From c0183a42cd8e52e5ee8d46645a41ab7c86f7a134 Mon Sep 17 00:00:00 2001 From: freesoftwareneedsfreetools Date: Sun, 7 Aug 2016 16:21:54 -0500 Subject: [elisp/en] Fix tiny typo (#2327) --- elisp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/elisp.html.markdown b/elisp.html.markdown index da86cab3..c88d97f0 100644 --- a/elisp.html.markdown +++ b/elisp.html.markdown @@ -194,7 +194,7 @@ filename: learn-emacs-lisp.el ;; And evaluate it: (greeting "you") -;; Some function are interactive: +;; Some functions are interactive: (read-from-minibuffer "Enter your name: ") ;; Evaluating this function returns what you entered at the prompt. -- cgit v1.2.3 From a0b6af45345b957c749dd2cd2e54117006af08be Mon Sep 17 00:00:00 2001 From: "J. Ryan Rembert" Date: Tue, 16 Aug 2016 03:42:20 -0700 Subject: [rust/fr] - French translation for Rust tutorial (#2297) * Initial pass at a fr translation of Rust tutorial * Clean up formatting * Add GFM rust modifer to code black * Final pre-PR fixes * Edit YAML front-matter * Grammar and typo fixes --- fr-fr/rust-fr.html.markdown | 319 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 319 insertions(+) create mode 100644 fr-fr/rust-fr.html.markdown diff --git a/fr-fr/rust-fr.html.markdown b/fr-fr/rust-fr.html.markdown new file mode 100644 index 00000000..0fa16075 --- /dev/null +++ b/fr-fr/rust-fr.html.markdown @@ -0,0 +1,319 @@ +--- +language: rust +contributors: + - ["P1start", "http://p1start.github.io/"] +translators: + - ["Ryan Rembert", "http://jrrembert.github.io"] +filename: learnrust-fr.rs +lang: fr-fr +--- + +Rust est un langage de programmation développé par Mozilla Research. Rust combine le contrôle de bas niveau sur la performance avec la commodité et la sécurité garanties de haut niveau. + +Il atteint ces objectifs sans avoir besoin d'un ramasse-miettes ou environnement d'exécution, ce qui rend possible l'utilisation de bibliothèques Rust comme une substitution directe pour C. + +La première version de Rust, 0.1, est sortie en janvier 2012 et a tellement évolué rapidement que jusqu'à récemment, l'utilisation de versions stables était déconseillée - à la place ce était conseillé d'utiliser les nightly builds. + +Le 15 mai 2015, Rust 1.0 a été libéré avec une garantie complète de compatibilité ascendante. Améliorations aux temps de compilation et d'autres aspects du compilateur sont actuellement disponibles dans la nightly builds. Rust a adopté un modèle de libération à bord du train avec les versions régulières toutes les six semaines. Rust 1.1 beta a été mis à la disposition dans le même temps de la libération de Rust 1.0. + +Bien que Rust soit un langage relativement bas niveau, Rust a quelques concepts fonctionnels qui se trouvent généralement dans les langues de niveau supérieur. Cela rend Rust non seulement rapide, mais aussi efficace et facile à coder. + +```rust +// Ceci est un commentaire. commentaires de ligne ressemblent à ceci ... +// Et prolonger plusieurs lignes comme celle-ci. + +/// Les commentaires de documentation ressemblent à ceci et à soutenir +/// la notation de démarques. +/// # Exemples +/// +/// ``` +/// let cinq = 5 +/// ``` + +/////////////// +// 1. Basics // +/////////////// + +// Les fonctions +// `I32` est le type 32 bits entiers signés +fn add2(x: i32, y: i32) -> i32 { +    // Retour implicite (pas virgule) +    x + y +} + +// Fonction principale +fn main() { +    // Nombres // + +    // Reliures immutable +    let x: i32 = 1; + +    // Entier suffixes/float +    let y: I32 = 13i32; +    let f: f64 = 1.3f64; + +    // Type Inférence +    // La plupart du temps, le compilateur Rust peut déduire le type de variable + // est, donc vous ne devez pas écrire une annotation de type explicite. +    // Tout au long de ce tutoriel, les types sont explicitement annotées dans + // de nombreux endroits, mais seulement à des fins de démonstration. + // L'inférence de type peut gérer cela pour vous la plupart du temps. +    let implicit_x = 1; +    let implicit_f = 1,3; + +    // Arithmétique +    let somme = x + y + 13; + +    // Variable Mutable +    let mut mutable = 1; +    let mutable = 4; +    let mutable += 2; + +    // Chaînes // + +    // Littéraux chaîne +    let x: &str = "Bonjour tout le monde!"; + +    // Impression +    println!("{} {}", f, x); // 1.3 Bonjour tout le monde + +    // A `Chaîne` - une chaîne de tas alloué +    let s: String = "Bonjour tout le monde".to_string(); + +    // Une tranche de chaîne - une vue immutable dans une else chaîne. +    // Ceci est essentiellement un pointeur immutable à une chaîne - il n'a pas +    // contient effectivement le contenu d'une chaîne, juste un pointeur vers +    // quelque chose qui fait(dans ce cas, `s`). +    let s_slice: &str = &s; + +    println!("{} {}", s, s_slice); // Bonjour monde Bonjour tout le monde + +    // Vecteurs/tableau // + +    // Un tableau de taille fixe +    let four_ints: [i32; 4] = [1, 2, 3, 4]; + +    // Un tableau dynamique(vecteur) +    let mut vecteur: Vec = vec![1, 2, 3, 4]; +    vecteur.push(5); + +    // Une tranche - une vue immutable dans un vecteur ou un tableau. +    // Ceci est un peu comme une tranche de chaîne, mais pour les vecteurs. +    let tranche: &[i32] = &vecteur; + +    // Utiliser `{:?}` pour imprimer quelque chose de débogage de style +    println!("{:?} {:?}", vecteur, tranche); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + +    // Tuples // + +    // Un tuple est un ensemble de valeurs de peut-être différents types. + // de taille fixe +    let x:(i32, &str, f64) = (1, "bonjour", 3.4); + +    // Déstructurante `let` +    let (a, b, c) = x; +    println!("{} {} {}", a, b, c); // 1 bonjour 3.4 + +    // indexation +    println!("{}", x.1); // Bonjour + +    ////////////// +    // 2. Types // +    ////////////// + +    // Struct +    struct Point { +        x: i32, +        y: i32, +    } + +    let origine: Point = Point { x: 0, y: 0 }; + +    // Un struct avec des champs sans nom, appelé 'tuple struct'. +    struct Point2(i32, i32); + +    let origine2 = Point2(0, 0); + +    // Basic C-like enum +    enum Direction { +        Àgauche, +        Droite, +        En_Haut, +        Vers_Le_Bas, +    } + +    let en_haut = Direction::En_Haut; + +    // Enum avec des champs +    enum OptionnelI32 { +        AnI32(I32), +        Rien, +    } + +    let deux: OptionnelI32 = OptionnelI32::AnI32(2); +    let rien = OptionnelI32::Rien; + +    // Generics // + +    struct Foo { bar: T } + +    // Ceci est défini dans la bibliothèque standard comme `Option`. +    enum Optionnel { +        SomeVal(T), +        NoVal, +    } + +    // Méthodes // + +    impl Foo { +        // Méthodes prennent un paramètre explicite `de self`. +        fn get_bar(self) -> T { +            self.bar +        } +    } + +    let a_foo = Foo { bar: 1 }; +    println!("{}", a_foo.get_bar()); // 1 + +    // Traits (connu sous le nom des interfaces ou des classes de types dans + // d'elses langues). + +    trait Frobnicate { +        fn frobnicate(self) -> Option; +    } + +    impl Frobnicate for Foo { +        fn frobnicate(self) -> Option { +            Some(self.bar) +        } +    } + +    let another_foo = Foo { bar: 1 }; +    println!("{:?}", another_foo.frobnicate()); // Some(1) + +    ///////////////////////// +    // 3. Motif correspondant // +    ///////////////////////// + +    let foo = OptionnelI32::AnI32(1); +    match foo { +        OptionnelI32::AnI32(n) => println!("Il est un i32: {}", n), +        OptionnelI32::Rien => println!("Il n'y a rien!"), +    } + +    // Motif avancé correspondant +    struct FooBar { x: i32, y: OptionnelI32 } +    let bar = FooBar { x: 15, y: OptionnelI32::AnI32(32) }; + +    match bar { +        FooBar { x: 0, y: OptionnelI32 :: AnI32(0)} => +            println!("Les chiffres sont nuls!"), +        FooBar { x: n, y: OptionnelI32 :: AnI32(m)} if n == m => +            println!("Les chiffres sont les mêmes"), +        FooBar { x: n, y: OptionnelI32 :: AnI32(m)} => +            println!("Différents numéros: {} {}", n, m)!, +        FooBar { x: _, y: OptionnelI32 :: Rien} => +            println!("Le deuxième numéro est rien!"), +    } + +    ///////////////////// +    // 4. Flux de contrôle // +    ///////////////////// + +    // `for` boucles / itération +    let array = [1, 2, 3]; +    for i in array.iter() { +        println!("{}", i); +    } + +    // Ranges +    for i in 0u32..10 { +        print!("{}", i); +    } +    println!(""); +    // imprime `0 1 2 3 4 5 6 7 8 9` + +    // `if` +    if 1 == 1 { +        println!("Maths est travaille!"); +    } else { +        println!("Oh non ...!"); +    } + +    // `if` comme expression +    let valeur = if true { +        "bien" +    } else { +        "mal" +    }; + +    // `while` boucle +    while 1 == 1 { +        println!("L'univers fonctionne normalement."); +    } + +    // Boucle infinie +    loop { +        println!("Bonjour!"); +    } + +    ///////////////////////////////// +    // 5. Sécurité & pointeurs mémoire // +    ///////////////////////////////// + + // Pointeur occasion - une seule chose peut "posséder" pointeur à un moment. +    // Cela signifie que lorsque le `Box` laisse son champ d'application, il + // peut être automatiquement libérée en toute sécurité. +    let mut mien: Box = Box::new(3); +    *mien = 5; // déréférencer +    // Ici, `now_its_mine` prend possession de` mine`. En d'elses termes, + // `mien` est déplacé. +    let mut now_its_mine = mien; +    *now_its_mine += 2; + +    println!("{}", now_its_mine); // 7 +    // println!("{}", de la mine); // Cela ne compile pas parce + // que `now_its_mine` possède maintenant le pointeur + +    // Référence - un pointeur immutable qui fait référence à d'elses données. +    // Quand une référence est prise à une valeur, nous disons que la valeur + // a été "emprunté". +    // Même si une valeur est emprunté immutablement, il ne peut pas être + // muté ou déplacé. +    // Un emprunt dure jusqu'à la fin de la portée, il a été créé. +    let mut var = 4; +    var = 3; +    let ref_var: &i32 = &var; + +    println!("{}", var); // Contrairement `box`, `var` peut encore être utilisé +    println!("{}", *ref_var); +    // Var = 5; // Cela ne compile pas parce que `var` est emprunté. +    // *ref_var = 6; // Ce ne serait pas non plus, parce que `ref_var` est une + // référence immutable. + +    // Référence Mutable +    // Même si une valeur est mutably emprunté, il ne peut pas être + // accessible à tous. +    let mut var2 = 4; +    let ref_var2: &mut i32 = &mut var2; + // '*' est utilisé pour pointer vers le var2 mutably emprunté. + *ref_var2 += 2; + + println!("{}", * ref_var2); // 6, // var2 ne serait pas compiler. +    // ref_var2 est de type &mut i32 donc stocke il référence à i32, + // pas la valeur. +    // var2 = 2; // Cela ne compile pas parce que `var2` est emprunté. +} +``` + +## Autres lectures + +Il y a beaucoup plus à Rust -- ce est juste l'essentiel de Rust afin que vous puissiez comprendre +les choses les plus importantes. Pour en savoir plus sur Rust, lire [La Programmation Rust +Langue](http://doc.rust-lang.org/book/index.html) et etudier la +[/r/rust](http://reddit.com/r/rust) subreddit. Les gens sur le canal de #rust sur +irc.mozilla.org sont aussi toujours prêts à aider les nouveaux arrivants. + +Vous pouvez également essayer caractéristiques de Rust avec un compilateur en ligne sur le fonctionnaire +[Rust parc](http://play.rust-lang.org) ou sur la principale +[Site Rust](http://rust-lang.org). -- cgit v1.2.3 From 21c4be47790c230cf5a321aeabb5c07ad57f0522 Mon Sep 17 00:00:00 2001 From: Ryan Date: Wed, 17 Aug 2016 13:25:32 -0600 Subject: Remove undefined behavior (#2332) --- c.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index babf0954..92f07fe2 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -449,7 +449,8 @@ int main (int argc, char** argv) int size = 10; int *my_arr = malloc(sizeof(int) * size); // Add an element to the array - my_arr = realloc(my_arr, ++size); + size++; + my_arr = realloc(my_arr, sizeof(int) * size); my_arr[10] = 5; // Dereferencing memory that you haven't allocated gives -- cgit v1.2.3 From 12e1739706da8ead292f1c21c4cf54afbd4f4087 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Sun, 21 Aug 2016 15:51:29 +0800 Subject: go: [zh-cn] fix a typo. --- zh-cn/go-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index 49224085..fa4540a2 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -129,7 +129,7 @@ func learnFlowControl() { fmt.Println("told ya") } // 用go fmt 命令可以帮你格式化代码,所以不用怕被人吐槽代码风格了, - // 也不用容忍被人的代码风格。 + // 也不用容忍别人的代码风格。 if false { // pout } else { -- cgit v1.2.3 From 6f20dea30740479fd0f0d7e2221490eaffb9a0d5 Mon Sep 17 00:00:00 2001 From: Chris Martin Date: Sun, 21 Aug 2016 15:55:49 -0400 Subject: Added info on Java generics in Spanish. (#2213) --- es-es/java-es.html.markdown | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/es-es/java-es.html.markdown b/es-es/java-es.html.markdown index b34dca8d..e48a3b73 100644 --- a/es-es/java-es.html.markdown +++ b/es-es/java-es.html.markdown @@ -279,6 +279,19 @@ public class AprendeJava { // 'toString' es una convención para mostrar los valores de este objeto. System.out.println("informacion de la excursion: " + excursion.toString()); + /////////////////////////////////////// + // Genéricos + /////////////////////////////////////// + + // Utilizando genéricos (a partir de Java 1.5) es posible detectar en tiempo de + // compilación errores de tipado (en versiones anteriores se detectarían como error + // de ejecución) + + List v = new ArrayList(); + v.add("test"); + String s = v.get(0); // Si intentamos recuperar s como otro tipo diferente a String + // (por ejemplo, un Integer) obtendríamos un error de compilación + } // Fin del método 'main' } // Fin de la clase AprendeJava -- cgit v1.2.3 From 34456d988c627a58ce8fca141cfb488c6d7998d4 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Mon, 22 Aug 2016 06:06:57 +0800 Subject: java: In Java 8, interfaces can have default method. (#2337) --- java.html.markdown | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 1f7d4115..56bffd88 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -585,10 +585,14 @@ public interface Edible { public interface Digestible { public void digest(); + // In Java 8, interfaces can have default method. + // public void digest() { + // System.out.println("digesting ..."); + // } } // We can now create a class that implements both of these interfaces. -public class Fruit implements Edible, Digestible { +public class Fruit implements Edible, Digestible { @Override public void eat() { // ... @@ -636,7 +640,7 @@ public abstract class Animal // Method can have a body public void eat() { - System.out.println("I am an animal and I am Eating."); + System.out.println("I am an animal and I am Eating."); // Note: We can access private variable here. age = 30; } -- cgit v1.2.3 From c6bfd82aa098ed8ef0c4d78e925f14a589940d59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Roun?= Date: Tue, 23 Aug 2016 21:36:57 +0200 Subject: added missing modulo division (#2339) --- cs-cz/javascript.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cs-cz/javascript.html.markdown b/cs-cz/javascript.html.markdown index 0b053595..b4596c40 100644 --- a/cs-cz/javascript.html.markdown +++ b/cs-cz/javascript.html.markdown @@ -1,4 +1,4 @@ ---- +--- language: javascript contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] @@ -59,6 +59,11 @@ delejNeco() // Včetně dělení 5 / 2; // = 2.5 +// A také dělení modulo +10 % 2; // = 0 +30 % 4; // = 2 +18.5 % 7; // = 4.5 + // Bitové operace také fungují; když provádíte bitové operace, desetinné číslo // (float) se převede na celé číslo (int) se znaménkem *do* 32 bitů 1 << 2; // = 4 -- cgit v1.2.3 From fc7ec89cee90d6e97d64fe3efd0b55979151ba11 Mon Sep 17 00:00:00 2001 From: "Ole Mathias Aa. Heggem" Date: Wed, 24 Aug 2016 08:59:57 +0200 Subject: Added NO version for JSON (#1532) --- no-nb/JSON-no.html.markdown | 59 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 no-nb/JSON-no.html.markdown diff --git a/no-nb/JSON-no.html.markdown b/no-nb/JSON-no.html.markdown new file mode 100644 index 00000000..6e63eb43 --- /dev/null +++ b/no-nb/JSON-no.html.markdown @@ -0,0 +1,59 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Ole Mathias Heggem", "https://github.com/msbone"] + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +--- + +JSON er en enkel tekstbasert standard for datautveksling. +Den er opprinnelig avledet fra JavaScript for å representere enkle datastrukturer. +Standarden er imidlertid uavhengig av JavaScript eller andre programmeringsspråk. + +JSON i sin reneste form har ingen faktiske kommentarer, men de fleste parsere vil akseptere +C-stil (`//`, `/* */`) kommentarer. + +```json +{ + "nøkkel": "verdi", + + "nøkler": "må alltid være i doble anførselstegn", + "tall": 0, + "strings": "Hellø, wørld. Alt unicode er godkjent, også \"escaping\".", + "har bools?": true, + "ingenting": null, + + "stort tall": 1.2e+100, + + "objekt": { + "kommentar": "Meste av strukturen kommer ifra objekt.", + + "array": [0, 1, 2, 3, "Arrays kan inneholde alt.", 5], + + "nytt object": { + "comment": "Ny kommentar" + } + }, + + "tull": [ + { + "Kilde til Kalium": ["bananer"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "Alternativ": { + "Kommentar": "Sjekk ut ditta!" + , "plassering av komma": "Sålenge den er før verdien er det gyldig" + , "Enda en kommentar": "TØFT!" + }, + + "Ferdig": "Da er den korte innledninga til JSON ferdig" +} +``` -- cgit v1.2.3 From 8032dbccc9e2a1b551079c39b0adb40fcdc0f2ab Mon Sep 17 00:00:00 2001 From: ven Date: Wed, 24 Aug 2016 09:00:23 +0200 Subject: fixup for #1532 --- no-nb/JSON-no.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/no-nb/JSON-no.html.markdown b/no-nb/JSON-no.html.markdown index 6e63eb43..6c8c3c79 100644 --- a/no-nb/JSON-no.html.markdown +++ b/no-nb/JSON-no.html.markdown @@ -1,6 +1,7 @@ --- language: json -filename: learnjson.json +filename: learnjson-no.json +lang: no-nb contributors: - ["Ole Mathias Heggem", "https://github.com/msbone"] - ["Anna Harren", "https://github.com/iirelu"] -- cgit v1.2.3 From e89fded52b67bc3afd1036f2aa977d24dd2185ed Mon Sep 17 00:00:00 2001 From: Martin Schimandl Date: Wed, 24 Aug 2016 18:32:01 +0200 Subject: Fix some typos --- de-de/perl-de.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/de-de/perl-de.html.markdown b/de-de/perl-de.html.markdown index 016c273f..fd8fb3c4 100644 --- a/de-de/perl-de.html.markdown +++ b/de-de/perl-de.html.markdown @@ -16,7 +16,7 @@ Perl 5 läuft auf über 100 Platformen von portablen Geräten bis hin zu Mainfra # Einzeilige Kommentare beginnen mit dem # Symbol. -#### Perl variablen typen +#### Perl Variablen Typen # Variablen beginnen mit einem Sigil, das ist ein Symbol das den Typ anzeigt. # Ein erlaubter Variablen-Name beginnt mit einem Buchstaben oder einem @@ -109,7 +109,7 @@ print for @elements; #### Reguläre Ausdrücke # Die Unterstützung von Perl für reguläre Ausdrücke ist weit und tiefgreifend. -# Sie ist ausführlichst in perlrequick, perlretut und sonstwo dokumentiert. +# Sie ist ausführlich in perlrequick, perlretut und sonstwo dokumentiert. # Die Kurzfassung: # Einfaches Vergleichen @@ -122,7 +122,7 @@ $a =~ s/foo/bar/; # Ersetzt foo mit bar in $a $a =~ s/foo/bar/g; # Ersetzt ALLE VORKOMMNISSE von foo mit bar in $a -#### Datien und Ein-/Ausgabe +#### Dateien und Ein-/Ausgabe # Dateien werden mit der "open()" Funktion zur Ein- oder Ausgabe geöffnet. @@ -150,14 +150,14 @@ sub logger { print $logfile $logmessage; } -# Nun könnne wir die Subroutine genau wie eine eingebaute Funktion verwenden: +# Nun können wir die Subroutine genau wie eine eingebaute Funktion verwenden: logger("We have a logger subroutine!"); ``` #### Verwenden von Perl Modulen -Perl Module lieferen eine Menge an Funktionen die dabei Helfen das Rad nicht neu erfinden zu müssen. Perl Module können von CPAN (http://www.cpan.org/) heruntergeladen werden. Einige populäre Module sind in der Perl Distribution selbst bereits enthalten. +Perl Module liefern eine Menge an Funktionen die dabei Helfen das Rad nicht neu erfinden zu müssen. Perl Module können von CPAN (http://www.cpan.org/) heruntergeladen werden. Einige populäre Module sind in der Perl Distribution selbst bereits enthalten. Perlfaq enthält Fragen und Antworten zu häufig vorkommenden Aufgaben. Sehr oft sind auch Vorschläge enthalten welches CPAN module am besten geeignet ist. -- cgit v1.2.3 From 6996dcf3e3304a60655fea1968ce0ee90d3eff77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Roun?= Date: Wed, 24 Aug 2016 18:49:07 +0200 Subject: added missing js examples for czech translation --- cs-cz/javascript.html.markdown | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/cs-cz/javascript.html.markdown b/cs-cz/javascript.html.markdown index b4596c40..e781db3e 100644 --- a/cs-cz/javascript.html.markdown +++ b/cs-cz/javascript.html.markdown @@ -105,6 +105,10 @@ false; // nepravda // Řetězce znaků se spojují pomocí + "Ahoj " + "světe!"; // = "Ahoj světe!" +// ... což funguje nejenom s řetězci +"1, 2, " + 3; // = "1, 2, 3" +"Ahoj " + ["světe", "!"] // = "Ahoj světe,!" + // a porovnávají se pomocí < nebo > "a" < "b"; // = true @@ -131,7 +135,7 @@ null === undefined; // = false // Existují také typy `null` a `undefined`. null; // značí, že žádnou hodnotu -undefined; // značí, že hodnota nebyla definovaná definovaná (ikdyž +undefined; // značí, že hodnota nebyla definovaná (ikdyž // `undefined` je hodnota sama o sobě) // false, null, undefined, NaN, 0 and "" vrací nepravdu (false). Všechno ostatní @@ -156,6 +160,9 @@ jinaPromenna = 10; // Proměnné vytvořené bez přiřazení obsahují hodnotu undefined. var dalsiPromenna; // = undefined +// Pokud chcete vytvořit několik proměnných najednou, můžete je oddělit čárkou +var someFourthVar = 2, someFifthVar = 4; + // Existuje kratší forma pro matematické operace na proměnné promenna += 5; // se provede stejně jako promenna = promenna + 5; // promenna je ted 10 @@ -313,6 +320,12 @@ setTimeout(funkce, 5000); // Poznámka: setTimeout není část JS jazyka, ale funkce poskytována // prohlížeči a NodeJS +// Další funkce poskytovaná prohlížeči je je setInterval +function myFunction(){ + // tento kód bude volán každých 5 vteřin +} +setInterval(myFunction, 5000); + // Objekty funkcí nemusíme ani deklarovat pomocí jména, můžeme je napsat jako // ananymní funkci přímo vloženou jako argument setTimeout(function(){ @@ -503,6 +516,11 @@ if (0){ // Tento kód se nespustí, protože 0 je nepravdivá (false) } +if (new Number(0)){ + // Tento kód se spustí, protože obalená čísla jsou objekty, + // a objekty jsou vždy pravdivé +} + // Avšak, obalovací objekty a normální vestavěnné typy sdílejí prototyp, takže // můžete přidat funkcionalitu k řetězci String.prototype.prvniZnak = function(){ -- cgit v1.2.3 From f4371a8367ab4dbb5ac3e112fe6a5fc6654a28c8 Mon Sep 17 00:00:00 2001 From: Jiang haiyun Date: Thu, 25 Aug 2016 14:32:09 +0800 Subject: Sync with the English version & minor tweaks --- zh-cn/yaml-cn.html.markdown | 82 ++++++++++++++++++++++++++++++++------------- 1 file changed, 58 insertions(+), 24 deletions(-) diff --git a/zh-cn/yaml-cn.html.markdown b/zh-cn/yaml-cn.html.markdown index fc510eb5..bbda20e9 100644 --- a/zh-cn/yaml-cn.html.markdown +++ b/zh-cn/yaml-cn.html.markdown @@ -4,33 +4,36 @@ contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] translators: - ["Zach Zhang", "https://github.com/checkcheckzz"] + - ["Jiang Haiyun", "https://github.com/haiiiiiyun"] filename: learnyaml-cn.yaml lang: zh-cn --- -YAML是一个数据序列化语言,被设计成人类直接可写可读的。 +YAML 是一个数据序列化语言,被设计成人类直接可写可读的。 -它是JSON的严格超集,增加了语法显著换行符和缩进,就像Python。但和Python不一样, -YAML根本不容许文字制表符。 +它是 JSON 的严格超集,增加了语法显著换行符和缩进,就像 Python。但和 Python 不一样, +YAML 根本不容许文字制表符。 ```yaml -# YAML中的注解看起来像这样。 +# YAML 中的注解看起来像这样。 ################ -# 标量类型 # +# 标量类型 # ################ -# 我们的根对象 (它们在整个文件里延续) 将会是一个地图, +# 我们的根对象 (它们在整个文件里延续) 将会是一个映射, # 它等价于在别的语言里的一个字典,哈西表或对象。 key: value another_key: Another value goes here. a_number_value: 100 +# 如果你想将数字 1 作为值,你必须要将它括在引号中。 +# 不然 YAML 解析器会假定它是一个布尔值 true。 scientific_notation: 1e+12 boolean: true null_value: null key with spaces: value -# 注意到字符串不需要被引用。但是,它们可以被引用。 +# 注意到字符串不需要被括在引号中。但是,它们可以被括起来。 "Keys can be quoted too.": "Useful if you want to put a ':' in your key." # 多行字符串既可以写成像一个'文字块'(使用 |), @@ -54,7 +57,7 @@ folded_style: > this text will appear over two lines. #################### -# 集合类型 # +# 集合类型 # #################### # 嵌套是通过缩进完成的。 @@ -64,18 +67,24 @@ a_nested_map: another_nested_map: hello: hello -# 地图不用有字符串键值。 +# 映射的键值不必是字符串。 0.25: a float key -# 键值也可以是多行对象,用?表明键值的开始。 +# 键值也可以是复合型的,比如多行对象 +# 我们用 ? 后跟一个空格来表示一个复合键的开始。 ? | This is a key that has multiple lines : and this is its value -# YAML也容许键值是集合类型,但是很多语言将会抱怨。 +# YAML 也允许使用复杂键语法表示序列间的映射关系。 +# 但有些语言的解析器可能会不支持。 +# 一个例子: +? - Manchester United + - Real Madrid +: [ 2001-01-01, 2002-02-02 ] -# 序列 (等价于表或数组) 看起来像这样: +# 序列 (等价于列表或数组) 看起来像这样: a_sequence: - Item 1 - Item 2 @@ -87,50 +96,75 @@ a_sequence: - This is a sequence - inside another sequence -# 因为YAML是JSON的超集,你也可以写JSON风格的地图和序列: +# 因为 YAML 是 JSON 的超集,你也可以写 JSON 风格的映射和序列: json_map: {"key": "value"} json_seq: [3, 2, 1, "takeoff"] ####################### -# 其余的YAML特点 # +# 其余的 YAML 特性 # ####################### -# YAML还有一个方便的特点叫'锚',它让你简单地在整个文件里重复内容。 -# 两个键值将会有相同的值: +# YAML 还有一个方便的特性叫 '锚',它能让你很容易在文档中进行文本复用。 +# 如下两个键会有相同的值: anchored_content: &anchor_name This string will appear as the value of two keys. other_anchor: *anchor_name -# YAML还有标签,你可以用它显示地声明类型。 +# 锚也可被用来复制/继承属性 +base: &base + name: Everyone has same name + +foo: &foo + <<: *base + age: 10 + +bar: &bar + <<: *base + age: 20 + +# foo 和 bar 将都含有 name: Everyone has same name + +# YAML 还有标签,你可以用它显示地声明类型。 explicit_string: !!str 0.5 -# 一些解析器实现特定语言的标签,就像这个为了Python的复数类型。 +# 一些解析器实现特定语言的标签,就像这个针对 Python 的复数类型。 python_complex_number: !!python/complex 1+2j +# 我们也可以在 YAML 的复合键中使用特定语言的标签 +? !!python/tuple [5, 7] +: Fifty Seven +# 将会是 Python 中的 {(5, 7): 'Fifty Seven'} + #################### -# 其余的YAML类型 # +# 其余的 YAML 类型 # #################### -# 字符串和数字不是仅有的YAML可以理解的标量。 -# ISO 格式的日期和日期时间文字也是可以被解析的。 +# 除了字符串和数字,YAML 还能理解其它标量。 +# ISO 格式的日期和日期时间文本也可以被解析。 datetime: 2001-12-15T02:59:43.1Z datetime_with_spaces: 2001-12-14 21:59:43.10 -5 date: 2002-12-14 -# 这个!!binary标签表明一个字符串实际上是一个二进制blob的base64编码表示。 +# 这个 !!binary 标签表明这个字符串实际上 +# 是一个用 base64 编码表示的二进制 blob。 gif_file: !!binary | R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= -# YAML还有一个集合类型,它看起来像这样: +# YAML 还有一个集合类型,它看起来像这样: set: ? item1 ? item2 ? item3 -# 像Python一样,集合仅是有null数值的地图;上面的集合等价于: +# 像 Python 一样,集合仅是值为 null 的映射;上面的集合等价于: set2: item1: null item2: null item3: null ``` + +### 更多资源 + ++ [YAML official website](http://yaml.org/) ++ [Online YAML Validator](http://codebeautify.org/yaml-validator) -- cgit v1.2.3 From df01c7fcff9098f092245afc42d597616988b169 Mon Sep 17 00:00:00 2001 From: Jiang haiyun Date: Fri, 26 Aug 2016 08:44:16 +0800 Subject: It is a a text --> It is a text --- vim.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vim.html.markdown b/vim.html.markdown index 80c5835a..cd61ca74 100644 --- a/vim.html.markdown +++ b/vim.html.markdown @@ -8,7 +8,7 @@ filename: LearnVim.txt [Vim](www.vim.org) -(Vi IMproved) is a clone of the popular vi editor for Unix. It is a a text +(Vi IMproved) is a clone of the popular vi editor for Unix. It is a text editor designed for speed and increased productivity, and is ubiquitous in most unix-based systems. It has numerous keybindings for speedy navigation to specific points in the file, and for fast editing. -- cgit v1.2.3 From 5a463a37256db3f1e42dd029d7d20e4cb03690dd Mon Sep 17 00:00:00 2001 From: Jiang Haiyun Date: Fri, 26 Aug 2016 16:05:48 +0800 Subject: Fix typo, 'Verbs ==> 'Verbs' (#2344) --- vim.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/vim.html.markdown b/vim.html.markdown index cd61ca74..edbc3da7 100644 --- a/vim.html.markdown +++ b/vim.html.markdown @@ -19,7 +19,7 @@ specific points in the file, and for fast editing. vim # Open in vim :q # Quit vim :w # Save current file - :wq # Save file and quit vim + :wq # Save file and quit vim :q! # Quit vim without saving file # ! *forces* :q to execute, hence quiting vim without saving :x # Save file and quit vim, shorter version of :wq @@ -77,9 +77,9 @@ specific points in the file, and for fast editing. Vim is based on the concept on **modes**. -Command Mode - vim starts up in this mode, used to navigate and write commands -Insert Mode - used to make changes in your file -Visual Mode - used to highlight text and do operations to them +Command Mode - vim starts up in this mode, used to navigate and write commands +Insert Mode - used to make changes in your file +Visual Mode - used to highlight text and do operations to them Ex Mode - used to drop down to the bottom with the ':' prompt to enter commands ``` @@ -105,15 +105,15 @@ Ex Mode - used to drop down to the bottom with the ':' prompt to enter comm Vim can be thought of as a set of commands in a 'Verb-Modifier-Noun' format, where: -Verb - your action -Modifier - how you're doing your action +Verb - your action +Modifier - how you're doing your action Noun - the object on which your action acts on -A few important examples of 'Verbs, 'Modifiers', and 'Nouns': +A few important examples of 'Verbs', 'Modifiers', and 'Nouns': ``` # 'Verbs' - + d # Delete c # Change y # Yank (copy) -- cgit v1.2.3 From 12c9b8daba15cf4950ae73f9813219d45bf373e8 Mon Sep 17 00:00:00 2001 From: prestonpeterson Date: Sat, 27 Aug 2016 01:03:37 -0700 Subject: Update java.html.markdown (#2346) --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 56bffd88..57c10390 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -566,7 +566,7 @@ class PennyFarthing extends Bicycle { // out: http://docs.oracle.com/javase/tutorial/java/annotations/ @Override public void setGear(int gear) { - gear = 0; + this.gear = 0; } } -- cgit v1.2.3 From 1732caa9f45d512601bd6457a7672072a9879c84 Mon Sep 17 00:00:00 2001 From: Jiang haiyun Date: Fri, 26 Aug 2016 08:43:08 +0800 Subject: [vim/zh-cn] translation --- zh-cn/vim-cn.html.markdown | 236 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 236 insertions(+) create mode 100644 zh-cn/vim-cn.html.markdown diff --git a/zh-cn/vim-cn.html.markdown b/zh-cn/vim-cn.html.markdown new file mode 100644 index 00000000..0c3f6043 --- /dev/null +++ b/zh-cn/vim-cn.html.markdown @@ -0,0 +1,236 @@ +--- +category: tool +tool: vim +filename: LearnVim-cn.txt +contributors: + - ["RadhikaG", "https://github.com/RadhikaG"] +translators: + - ["Jiang Haiyun", "https://github.com/haiiiiiyun"] +lang: zh-cn +--- + + +[Vim](www.vim.org) +(Vi IMproved) 是 Unix 上的流行编辑器 vi 的克隆版本。这个文本编辑器 +是为性能和提升效率而设计的,并且在大多数基于 unix 的系统上普遍存在。 +它有大量的快捷键可用来快速导航到文件的特定位置,以便进行快速编辑。 + +## Vim 导航基础 + +``` + vim # 在 Vim 中打开 + :q # 退出 Vim + :w # 保存当前文件 + :wq # 保存文件并退出 Vim + :q! # 退出 Vim 并且不保存文件 + # ! *强制* 执行 :q, 因此没有保存就退出 Vim + :x # 保存文件并且退出 Vim, 是 :wq 的简写版本 + + u # 撤销 + CTRL+R # 重做 + + h # 左移一个字符 + j # 下移一行 + k # 上移一行 + l # 右移一个字符 + + # 在行内移动 + + 0 # 移到行首 + $ # 移到行尾 + ^ # 移到行内的第一个非空白字符处 + + # 在文本中查找 + + /word # 光标之后的所有该词都高亮显示 + ?word # 光标之前的所有该词都高亮显示 + n # 查找后将光标移到该词的下一个出现位置 + N # 光标移到该词的上一个出现位置 + + :%s/foo/bar/g # 将文件每一行上的所有 'foo' 都改成 'bar' + :s/foo/bar/g # 将当前行上的所有 'foo' 都改成 'bar' + + # 跳到字符处 + + f<字符> # 向前跳移到 <字符> 上 + t<字符> # 向前跳移到 <字符> 的左侧 + + # 例如, + f< # 向前跣到 < 上 + t< # 向前跳移到 < 的左侧 + + # 按词移动 + + w # 前移一个词 + b # 后移一个词 + e # 移到当前词的末尾 + + # 移动的其它命令 + + gg # 移到文件顶部 + G # 移到文件末尾 + :NUM # 移到第 NUM 行 (NUM 是任意数字) + H # 移到屏幕顶部 + M # 移到屏幕中间位置 + L # 移到屏幕末尾 +``` + +## 模式: + +Vim 基于 **模式** 这个概念。 + +命令模式 - Vim 启动后就处于这个模式,用于导航和操作命令 +插入模式 - 用于在你的文件中进行修改 +可视模式 - 用于高亮文本并对它们进行操作 +Ex 模式 - 用于跳到底部的 ':' 提示行上输入命令 + +``` + i # 在光标位置前,将 Vim 切换到插入模式 + a # 在光标位置后,将 Vim 切换到插入模式 + v # 将 Vim 切换到可视模式 + : # 将 Vim 切换到 ex 模式 + # 无论你当前处于什么模式,都返回到命令模式 + + # 复制和粘贴文本 + + y # 复制所选的内容 + yy # 复制当前行 + d # 删除所选的内容 + dd # 删除当前行 + p # 在当前光标位置后粘贴复制的文本 + P # 在当前光标位置前粘贴复制的文本 + x # 删除当前光标位置处的字符 +``` + +## Vim 的 '语法' + +Vim 可以被认为是按 '动词-修饰词-名词' 格式编排的一组命令: + +动词 - 你的动作 +修饰词 - 你如何执行你的动作 +名词 - 你的动作所作用于的对象 + +关于 '动词','修饰词',和 '名词' 的几个重要例子: + +``` + # '动词' + + d # 删除 + c # 修改 + y # 复制 + v # 可视化选择 + + # '修饰词' + + i # 内部的 + a # 周围的 + NUM # 数字 (NUM 是任意数字) + f # 查找文本并位于其上 + t # 查找文本并停于其前面 + / # 从光标处开始查找字符串 + ? # 在光标前查找字符串 + + # '名词' + + w # 词 + s # 句子 + p # 段落 + b # 块 + + # 示例 '语句' 或命令 + + d2w # 删除 2 个词 + cis # 修改段落内的内容 + yip # 复制段落内的内容 (复制你所在的段落) + ct< # 修改直到括号开启处 + # 对你的当前位置直到下个括号开启处的内容进行修改 + d$ # 删除直到行尾 +``` + +## 一些快捷键和技巧 + + +``` + > # 将所选内容缩进一级 + < # 将所选内容取消缩进一级 + :earlier 15m # 将文档还原到 15 分钟前的状态 + :later 15m # 逆转上述命令 + ddp # 相邻行交换位置,先 dd 再 p + . # 重复之前动作 +``` + +## 宏 + +宏基本上来说就是可录制的动作。 +当你开始录制宏时,它会记录你使用的 **每个** 动作和命令, +直到你停止录制。当调用宏时,它会将这个完全相同的动作和命令序列 +再次应用于所选文本之上。 + +``` + qa # 开始录制一个叫 'a' 的宏 + q # 停止录制 + @a # 重播宏 +``` + +### 配置 ~/.vimrc + +.vimrc 可用于在启动时对 Vim 进行配置。 + +这里是一个示例 ~/.vimrc 文件: + +``` +" 示例 ~/.vimrc +" 2015.10 + +" 需要 Vim iMproved 版本 +set nocompatible + +" 根据文件名检测文件类型,以便能进行智能自动缩进等操作。 +filetype indent plugin on + +" 开启语法高亮 +syntax on + +" 更好的命令行补全 +set wildmenu + +" 除了当使用大写字母时使用大小写无关查找 +set ignorecase +set smartcase + +" 当新开一行时,如果没有开启文件特定的缩进规则, +" 则缩进保持与你当前行一致 +set autoindent + +" 在左侧显示行号 +set number + +" 缩进选项,根据个人偏好进行修改 + +" 每个 TAB 的可视空格数 +set tabstop=4 + +" 编辑时 TAB 对应的空格数 +set softtabstop=4 + +" 当使用缩进操作 (>> 和 <<) 时缩进的空格数 +set shiftwidth=4 + +" 将 TAB 转换成空格 +set expandtab + +" 为缩进和对齐开启智能化的 TAB 和空格切换功能 +set smarttab +``` + +### 参考 + +[Vim | Home](http://www.vim.org/index.php) + +`$ vimtutor` + +[A vim Tutorial and Primer](https://danielmiessler.com/study/vim/) + +[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about) + +[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim) -- cgit v1.2.3 From 00302473841679ef7d3115fa03aac481f31d390f Mon Sep 17 00:00:00 2001 From: haiiiiiyun Date: Sat, 27 Aug 2016 13:38:04 +0800 Subject: zh-cn ruby page sync with English version & minor tweaks --- zh-cn/ruby-cn.html.markdown | 401 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 339 insertions(+), 62 deletions(-) diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown index 14d38137..2d181de0 100644 --- a/zh-cn/ruby-cn.html.markdown +++ b/zh-cn/ruby-cn.html.markdown @@ -10,6 +10,7 @@ contributors: - ["ftwbzhao", "https://github.com/ftwbzhao"] translators: - ["Lin Xiangyu", "https://github.com/oa414"] + - ["Jiang Haiyun", "https://github.com/haiiiiiyun"] --- ```ruby @@ -35,6 +36,13 @@ translators: 8 - 1 #=> 7 10 * 2 #=> 20 35 / 5 #=> 7 +2**5 #=> 32 +5 % 3 #=> 2 + +# 位运算符 +3 & 5 #=> 1 +3 | 5 #=> 7 +3 ^ 5 #=> 6 # 算术符号只是语法糖而已 # 实际上是调用对象的方法 @@ -42,7 +50,7 @@ translators: 10.* 5 #=> 50 # 特殊的值也是对象 -nil # 空 +nil # 相当于其它语言中的 null true # 真 false # 假 @@ -54,13 +62,11 @@ false.class #=> FalseClass 1 == 1 #=> true 2 == 1 #=> false -# 不等运算符 +# 不相等运算符 1 != 1 #=> false 2 != 1 #=> true -!true #=> false -!false #=> true -# 除了false自己,nil是唯一的值为false的对象 +# 除了false自己,nil是唯一的另一个值为false的对象 !nil #=> true !false #=> true @@ -72,6 +78,26 @@ false.class #=> FalseClass 2 <= 2 #=> true 2 >= 2 #=> true + +# 组合比较运算符 +1 <=> 10 #=> -1 +10 <=> 1 #=> 1 +1 <=> 1 #=> 0 + +# 逻辑运算符 +true && false #=> false +true || false #=> true +!true #=> false + +# 也有优先级更低的逻辑运算符 +# 它们用于控制流结构中,用来串接语句,直到返回true或false。 + +# `do_something_else` 只当 `do_something` 返回true时才会被调用 +do_something() and do_something_else() +# `log_error` 只当 `do_something` 返回false时才会被调用 +do_something() or log_error() + + # 字符串是对象 'I am a string'.class #=> String @@ -81,9 +107,28 @@ placeholder = "use string interpolation" "I can #{placeholder} when using double quoted strings" #=> "I can use string interpolation when using double quoted strings" +# 尽可能优先使用单引号的字符串 +# 双引号的字符串会进行一些额外的内部处理 + +# 合并字符串,但不能和数字合并 +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" + +# 合并字符串及其运算符 +'hello ' * 3 #=> "hello hello hello " + +# 字符串追加 +'hello' << ' world' #=> "hello world" -# 输出值 +# 打印输出,并在末尾加换行符 puts "I'm printing!" +#=> I'm printing! +#=> nil + +# 打印输出,不加换行符 +print "I'm printing!" +#=> I'm printing! => nil # 变量 x = 25 #=> 25 @@ -96,17 +141,16 @@ x = y = 10 #=> 10 x #=> 10 y #=> 10 -# 按照惯例,用 snake_case 作为变量名 +# 按照惯例,使用类似snake_case风格的变量名 snake_case = true -# 使用具有描述性的运算符 +# 使用有意义的变量名 path_to_project_root = '/good/name/' path = '/bad/name/' # 符号(Symbols,也是对象) -# 符号是不可变的,内部用整数类型表示的可重用的值。 -# 通常用它代替字符串来有效地表示有意义的值。 - +# 符号是不可变的,内部用整数值表示的可重用的常数 +# 通常用它代替字符串来有效地表示有意义的值 :pending.class #=> Symbol @@ -132,26 +176,36 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] array[0] #=> 1 array[12] #=> nil -# 像运算符一样,[var]形式的访问 -# 也就是一个语法糖 -# 实际上是调用对象的[] 方法 +# 像运算符一样,[var] 形式的访问 +# 也只是语法糖 +# 实际上是调用对象的 [] 方法 array.[] 0 #=> 1 array.[] 12 #=> nil # 从尾部开始 array[-1] #=> 5 +array.last #=> 5 # 同时指定开始的位置和长度 array[2, 3] #=> [3, 4, 5] -# 或者指定一个范围 +# 将数组逆序 +a=[1,2,3] +a.reverse! #=> [3,2,1] + +# 或者指定一个区间 array[1..3] #=> [2, 3, 4] # 像这样往数组增加一个元素 array << 6 #=> [1, 2, 3, 4, 5, 6] +# 或者像这样 +array.push(6) #=> [1, 2, 3, 4, 5, 6] -# 哈希表是Ruby的键值对的基本数据结构 -# 哈希表由大括号定义 +# 检查元素是否包含在数组中 +array.include?(1) #=> true + +# 哈希表是 Ruby 的主要键/值对表示法 +# 哈希表由大括号表示 hash = {'color' => 'green', 'number' => 5} hash.keys #=> ['color', 'number'] @@ -163,19 +217,14 @@ hash['number'] #=> 5 # 查询一个不存在地键将会返回nil hash['nothing here'] #=> nil -# 用 #each 方法来枚举哈希表: -hash.each do |k, v| - puts "#{k} is #{v}" -end - -# 从Ruby 1.9开始, 用符号作为键的时候有特别的记号表示: +# 从Ruby 1.9开始,用符号作为键的时候有特别的记号表示: -new_hash = { defcon: 3, action: true} +new_hash = { defcon: 3, action: true } new_hash.keys #=> [:defcon, :action] # 小贴士:数组和哈希表都是可枚举的 -# 它们可以共享一些有用的方法,比如each, map, count 等等 +# 它们共享一些有用的方法,比如each,map,count等等 # 控制流 @@ -196,9 +245,15 @@ end #=> iteration 4 #=> iteration 5 -# 然而 -# 没人用for循环 -# 用`each`来代替,就像这样 + +# 但是,没有人用for循环。 +# 你应该使用"each"方法,然后再传给它一个块。 +# 所谓块就是可以传给像"each"这样的方法的代码段。 +# 它类似于其它语言中的lambdas, 匿名函数或闭包。 +# +# 区间上的"each"方法会对区间中的每个元素运行一次块代码。 +# 我们将counter作为一个参数传给了块。 +# 调用带有块的"each"方法看起来如下: (1..5).each do |counter| puts "iteration #{counter}" @@ -209,6 +264,23 @@ end #=> iteration 4 #=> iteration 5 +# 你也可以将块包含在一个大括号中: +(1..5).each { |counter| puts "iteration #{counter}" } + +# 数据结构中的内容也可以使用each来遍历。 +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + +# 如果你还需要索引值,可以使用"each_with_index",并且定义 +# 一个索引变量 +array.each_with_index do |element, index| + puts "#{element} is number #{index} in the array" +end + counter = 1 while counter <= 5 do puts "iteration #{counter}" @@ -220,6 +292,20 @@ end #=> iteration 4 #=> iteration 5 +# Ruby 中还有很多有用的循环遍历函数, +# 如"map","reduce","inject"等等。 +# 以map为例,它会遍历数组,并根据你在 +# 块中定义的逻辑对它进行处理,然后返回 +# 一个全新的数组。 +array = [1,2,3,4,5] +doubled = array.map do |element| + element * 2 +end +puts doubled +#=> [2,4,6,8,10] +puts array +#=> [1,2,3,4,5] + grade = 'B' case grade @@ -236,6 +322,33 @@ when 'F' else puts "Alternative grading system, eh?" end +#=> "Better luck next time" + +# case也可以用区间 +grade = 82 +case grade +when 90..100 + puts 'Hooray!' +when 80...90 + puts 'OK job' +else + puts 'You failed!' +end +#=> "OK job" + +# 异常处理: +begin + # 这里的代码可能会抛出异常 + raise NoMemoryError, 'You ran out of memory.' +rescue NoMemoryError => exception_variable + puts 'NoMemoryError was raised', exception_variable +rescue RuntimeError => other_exception_variable + puts 'RuntimeError was raised now' +else + puts 'This runs if no exceptions were thrown at all' +ensure + puts 'This code always runs no matter what' +end # 函数 @@ -243,7 +356,7 @@ def double(x) x * 2 end -# 函数 (以及所有的方法块) 隐式地返回了最后语句的值 +# 函数 (以及所有的块) 隐式地返回最后语句的值 double(2) #=> 4 # 当不存在歧义的时候括号是可有可无的 @@ -261,8 +374,8 @@ sum 3, 4 #=> 7 sum sum(3,4), 5 #=> 12 # yield -# 所有的方法都有一个隐式的块参数 -# 可以用yield参数调用 +# 所有的方法都有一个隐式的,可选的块参数 +# 可以用 'yield' 关键字调用 def surround puts "{" @@ -276,45 +389,84 @@ surround { puts 'hello world' } # hello world # } +# 可以向函数传递一个块 +# "&"标记传递的块是一个引用 +def guests(&block) + block.call 'some_argument' +end -# 用class关键字定义一个类 -class Human - - # 一个类变量,它被这个类地所有实例变量共享 - @@species = "H. sapiens" +# 可以传递多个参数,这些参数会转成一个数组, +# 这也是使用星号符 ("*") 的原因: +def guests(*array) + array.each { |guest| puts guest } +end - # 构造函数 - def initialize(name, age=0) - # 将参数name的值赋给实例变量@name - @name = name - # 如果没有给出age, 那么会采用参数列表中地默认地值 - @age = age - end +# 如果函数返回一个数组,在赋值时可以进行拆分: +def foods + ['pancake', 'sandwich', 'quesadilla'] +end +breakfast, lunch, dinner = foods +breakfast #=> 'pancake' +dinner #=> 'quesadilla' - # 基本的 setter 方法 - def name=(name) - @name = name - end +# 按照惯例,所有返回布尔值的方法都以?结尾 +5.even? # false +5.odd? # true - # 基本地 getter 方法 - def name - @name - end +# 如果方法名末尾有!,表示会做一些破坏性的操作,比如修改调用者自身。 +# 很多方法都会有一个!的版本来进行修改,和一个非!的版本 +# 只用来返回更新了的结果 +company_name = "Dunder Mifflin" +company_name.upcase #=> "DUNDER MIFFLIN" +company_name #=> "Dunder Mifflin" +company_name.upcase! # we're mutating company_name this time! +company_name #=> "DUNDER MIFFLIN" - # 一个类方法以self.开头 - # 它可以被类调用,但不能被类的实例调用 - def self.say(msg) - puts "#{msg}" - end - def species - @@species - end +# 用class关键字定义一个类 +class Human + # 一个类变量,它被这个类的所有实例变量共享 + @@species = "H. sapiens" + + # 基本构造函数 + def initialize(name, age = 0) + # 将参数值赋给实例变量"name" + @name = name + # 如果没有给出age,那么会采用参数列表中的默认值 + @age = age + end + + # 基本的setter方法 + def name=(name) + @name = name + end + + # 基本地getter方法 + def name + @name + end + + # 以上的功能也可以用下面的attr_accessor来封装 + attr_accessor :name + + # Getter/setter方法也可以像这样单独创建 + attr_reader :name + attr_writer :name + + # 类方法通过使用self与实例方法区别开来。 + # 它只能通过类来调用,不能通过实例调用。 + def self.say(msg) + puts "#{msg}" + end + + def species + @@species + end end -# 类的例子 +# 初始化一个类 jim = Human.new("Jim Halpert") dwight = Human.new("Dwight K. Schrute") @@ -327,7 +479,132 @@ jim.name #=> "Jim Halpert II" dwight.species #=> "H. sapiens" dwight.name #=> "Dwight K. Schrute" -# 调用对象的方法 -Human.say("Hi") #=> "Hi" +# 调用类方法 +Human.say('Hi') #=> "Hi" + +# 变量的作用域由它们的名字格式定义 +# 以$开头的变量具有全局域 +$var = "I'm a global var" +defined? $var #=> "global-variable" + +# 以@开头的变量具有实例作用域 +@var = "I'm an instance var" +defined? @var #=> "instance-variable" + +# 以@@开头的变量具有类作用域 +@@var = "I'm a class var" +defined? @@var #=> "class variable" + +# 以大写字母开头的变量是常数 +Var = "I'm a constant" +defined? Var #=> "constant" + +# 类也是对象。因此类也可以有实例变量。 +# 类变量在类以及其继承者之间共享。 + +# 基类 +class Human + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# 派生类 +class Worker < Human +end + +Human.foo # 0 +Worker.foo # 0 + +Human.foo = 2 # 2 +Worker.foo # 2 + +# 类实例变量不能在继承类间共享。 + +class Human + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(value) + @bar = value + end +end + +class Doctor < Human +end + +Human.bar # 0 +Doctor.bar # nil + +module ModuleExample + def foo + 'foo' + end +end + +# '包含'模块后,模块的方法会绑定为类的实例方法 +# '扩展'模块后,模块的方法会绑定为类方法 + +class Person + include ModuleExample +end + +class Book + extend ModuleExample +end + +Person.foo # => NoMethodError: undefined method `foo' for Person:Class +Person.new.foo # => 'foo' +Book.foo # => 'foo' +Book.new.foo # => NoMethodError: undefined method `foo' + +# 当包含或扩展一个模块时,相应的回调代码会被执行。 +module ConcernExample + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + + module ClassMethods + def bar + 'bar' + end + end + + module InstanceMethods + def qux + 'qux' + end + end +end + +class Something + include ConcernExample +end + +Something.bar # => 'bar' +Something.qux # => NoMethodError: undefined method `qux' +Something.new.bar # => NoMethodError: undefined method `bar' +Something.new.qux # => 'qux' ``` + + +## 其它资源 + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. +- [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Learn Ruby through a series of interactive tutorials. +- [Official Documentation](http://ruby-doc.org/core) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. +- [Try Ruby](http://tryruby.org) - Learn the basic of Ruby programming language, interactive in the browser. -- cgit v1.2.3 From e810b6fd41d9df92bb2b83ad394f12468e5b2a3a Mon Sep 17 00:00:00 2001 From: Philipp Klose Date: Tue, 30 Aug 2016 10:11:09 +0200 Subject: minor typo (#2349) --- cmake.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake.html.markdown b/cmake.html.markdown index a2c8cc8a..45cf0585 100644 --- a/cmake.html.markdown +++ b/cmake.html.markdown @@ -45,7 +45,7 @@ cmake_minimum_required (VERSION 2.8) cmake_minimum_required (VERSION 2.8 FATAL_ERROR) # We setup the name for our project. After we do that, this will change some -# directories naming convention genearted by CMake. We can send the LANG of +# directories naming convention generated by CMake. We can send the LANG of # code as second param project (learncmake C) -- cgit v1.2.3 From 98abad6935b77e66a4b8f2ddff340d57dbfeb173 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 31 Aug 2016 15:18:38 -0700 Subject: Remove redundant nl markdown and fix fortran file --- fortran95.html.markdown | 2 +- nl-nl/markdown-nl-html.markdown | 256 ---------------------------------------- tr-tr/c-tr.html.markdown | 2 +- 3 files changed, 2 insertions(+), 258 deletions(-) delete mode 100644 nl-nl/markdown-nl-html.markdown diff --git a/fortran95.html.markdown b/fortran95.html.markdown index 8479fef8..5d1424bf 100644 --- a/fortran95.html.markdown +++ b/fortran95.html.markdown @@ -17,7 +17,7 @@ This overview will discuss the features of Fortran 95 since it is the most widely implemented of the more recent specifications and the later versions are largely similar (by comparison FORTRAN 77 is a very different language). -```fortran +``` ! This is a comment. diff --git a/nl-nl/markdown-nl-html.markdown b/nl-nl/markdown-nl-html.markdown deleted file mode 100644 index 0f954715..00000000 --- a/nl-nl/markdown-nl-html.markdown +++ /dev/null @@ -1,256 +0,0 @@ ---- -language: markdown -contributors: - - ["Dan Turkel", "http://danturkel.com/"] -filename: learnmarkdown-nl.md -translators: - - ["Niels van Velzen", "https://nielsvanvelzen.me"] -lang: nl-nl ---- - -Markdown is gemaakt door John Gruber in 2004. De bedoeling was om een simpel te -lezen en schrijven syntax te creëren wat makkelijk om te zetten is naar -HTML (en tegenwoordig ook vele andere formaten). - -```markdown - - - - - - -# Dit is een

-## Dit is een

-### Dit is een

-#### Dit is een

-##### Dit is een

-###### Dit is een
- - -Dit is een h1 -============= - -Dit is een h2 -------------- - - - - -*Deze tekst staat schuin.* -_Net als deze tekst._ - -**Deze tekst is dikgedrukt.** -__Net als deze tekst.__ - -***En deze tekst is dik en schuin.*** -**_Net als dit!_** -*__En dit!__* - - - -~~Deze tekst is doorgehaald.~~ - - - - -Dit is een paragraaf. Ik typ in een paragraaf, is dat niet leuk? - -Nu ben ik in paragraaf 2. -Nog steeds in paragraaf 2! - -Dit is paragraaf drie! - - - -Ik eindig met twee spaties (selecteer mij om het te zien). - -Er is een nieuwe regel boven mij! - - - -> Dit is een citaat. Je kan -> handmatig je lijnen laten vormen of je kan je lijnen lang laten worden en vanzelf op nieuwe regels verder laten gaan. -> Het maakt niet uit zolang je maar begint met een `>`. - -> Je kunt ook meer dan 1 level ->> uitlijning gebruiken. -> Hoe handig is dat? - - - - -* Item -* Item -* Nog een item - -of - -+ Item -+ Item -+ Nog een item - -of - -- Item -- Item -- Nog een item - - - -1. Item een -2. Item twee -3. Item drie - - - -1. Item een -1. Item twee -1. Item drie - - - - - -1. Item een -2. Item twee -3. Item drie - * Sub-item een - * Sub-item twee -4. Item vier - - - -Checkboxes hieronder zonder de 'x' zijn leeg. -- [ ] Eerste taak. -- [ ] Tweede taak -Checkboxes met een 'x' zijn klaar. -- [x] Deze taak is klaar. - - - - - Dit is code - net als dit - - - - mijn_array.each do |item| - puts item - end - - - -John wist niet eens wat de `go_to()` functie deed! - - - -\`\`\`ruby -def foobar - puts "Hallo wereld!" -end -\`\`\` - - - - - - -*** ---- -- - - -**************** - - - - -[Klik op mij!](http://test.com/) - - - -[Klik op mij!](http://test.com/ "Link naar Test.com") - - - -[Ga naar de muziek](/music/). - - - -[Klik op deze link][link1] vor meer informatie erover! -[Bekijk deze ook eens][foobar] als je wilt. - -[link1]: http://test.com/ "Cool!" -[foobar]: http://foobar.biz/ "In orde!" - - - - - -[Dit][] is een link. - -[dit]: http://ditiseenlink.nl/ - - - - - - -![Dit is de alt attribuut van het plaatje](http://imgur.com/myimage.jpg "Een optionele titel") - - - -![Dit is de alt attribuut.][mijnplaatje] - -[mijnplaatje]: relative/urls/cool/image.jpg "Hier is de titel" - - - - - is hetzelfde als -[http://testwebsite.com/](http://testwebsite.com/) - - - - - - - -Ik wil *deze tekst met sterretjes typen* maar ik wil het niet schuin, dus ik doe dit: \*deze tekst met sterretjes typen\*. - - - - -Computer gecrashed? Gebruik eens -Ctrl+Alt+Del - - - - -| kolom1 | kolom2 |kolom3 | -| :--------------- | :---------: | ----------------: | -| Links-uitgelijnd | Gecentreerd | Rechts-uitgelijnd | -| blah | blah | blah | - - - -Kolom 1 | Kolom 2 | Kolom 3 -:-- | :-: | --: -Dit is zo lelijk | stop | er mee - - - -``` - -Voor meer informatie, bekijk Josn Gruber's officiele post over de syntax [hier](http://daringfireball.net/projects/markdown/syntax). Of bekijk Adam Pritchard's grote cheatsheet [hier](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) (beide Engels). diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown index 2d4240ed..33544765 100644 --- a/tr-tr/c-tr.html.markdown +++ b/tr-tr/c-tr.html.markdown @@ -202,7 +202,7 @@ int main() { 0x02 >> 1; // => 0x01 (bitwise right shift (by 1)) // Isaretli sayilari kaydirirken dikkatli olun - tanimsizlar sunlardir: - // - isaretli sayinin isaret bitinde yapilan kaydirma (int a = 1 << 32) + // - isaretli sayinin isaret bitinde yap?ilan kaydirma (int a = 1 << 32) // - negatif sayilarda sol kaydirma (int a = -1 << 2) // - LHS tipinde >= ile olan ofset genisletmelerde yapilan kaydirma: // int a = 1 << 32; // UB if int is 32 bits wide -- cgit v1.2.3 From 678fa3b97468a903fc256d95c58f54db5a531a64 Mon Sep 17 00:00:00 2001 From: Patrick Callahan Date: Thu, 1 Sep 2016 02:28:23 -0400 Subject: Remove Python 2 resources from Python 3 page (#2350) There were several resources here that teach Python 2, but not Python 3. I removed them so that a reader will only see resources that apply to Python 3. --- python3.html.markdown | 5 ----- 1 file changed, 5 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 6b3486a6..09b041b8 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -887,12 +887,9 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ### Free Online * [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) * [Ideas for Python Projects](http://pythonpracticeprojects.com) * [The Official Docs](http://docs.python.org/3/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [Python Course](http://www.python-course.eu/index.php) * [First Steps With Python](https://realpython.com/learn/python-first-steps/) * [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) @@ -903,5 +900,3 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ### Dead Tree * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From 3d270111bd45c8eac51a642951e81e3313436648 Mon Sep 17 00:00:00 2001 From: Alois Date: Thu, 1 Sep 2016 19:27:41 +0200 Subject: [WIP] [toml/en] Add TOML support (#2282) * Init support for TOML * Add scalar types section * Move comment to key value * Improve introduction * Move int comment to int key value * Add array support * Add version warning * Add support for table * Add inline table part * Add support array of table part * Fix bugs/typos to follow the review * Improve sub tables example * Fix wrong quotes on multiLineLiteralString * Fix letter case for coherence * Remove old comment * Move from variety to color Thanks @robochat --- toml.html.markdown | 274 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 274 insertions(+) create mode 100755 toml.html.markdown diff --git a/toml.html.markdown b/toml.html.markdown new file mode 100755 index 00000000..980563f9 --- /dev/null +++ b/toml.html.markdown @@ -0,0 +1,274 @@ +--- +language: toml +filename: learntoml.toml +contributors: + - ["Alois de Gouvello", "https://github.com/aloisdg"] +--- + +TOML stands for Tom's Obvious, Minimal Language. It is a data serialisation language designed to be a minimal configuration file format that's easy to read due to obvious semantics. + +It is an alternative to YAML and JSON. It aims to be more human friendly than JSON and simpler that YAML. TOML is designed to map unambiguously to a hash table. TOML should be easy to parse into data structures in a wide variety of languages. + +Be warned, TOML's spec is still changing a lot. Until it's marked as 1.0, you +should assume that it is unstable and act accordingly. This document follows TOML v0.4.0. + +```toml +# Comments in TOML look like this. + +################ +# SCALAR TYPES # +################ + +# Our root object (which continues for the entire document) will be a map, +# which is equivalent to a dictionary, hash or object in other languages. + +# The key, equals sign, and value must be on the same line +# (though some values can be broken over multiple lines). +key = "value" +string = "hello" +number = 42 +float = 3.14 +boolean = true +dateTime = 1979-05-27T07:32:00-08:00 +scientificNotation = 1e+12 +"key can be quoted" = true # Both " and ' are fine +"key may contains" = "letters, numbers, underscores, and dashes" + +# A bare key must be non-empty, but an empty quoted key is allowed +"" = "blank" # VALID but discouraged +'' = 'blank' # VALID but discouraged + +########## +# String # +########## + +# All strings must contain only valid UTF-8 characters. +# We can escape characters and some of them have a compact escape sequence. +# For example, \t add a tabulation. Refers to the spec to get all of them. +basicString = "are surrounded by quotation marks. \"I'm quotable\". Name\tJos" + +multiLineString = """ +are surrounded by three quotation marks +on each side and allow newlines.""" + +literalString = 'are surrounded by single quotes. Escaping are not allowed.' + +multiLineLiteralString = ''' +are surrounded by three single quotes on each side +and allow newlines. Still no escaping. +The first newline is trimmed in raw strings. + All other whitespace + is preserved. #! are preserved? +''' + +# For binary data it is recommended that you use Base64, another ASCII or UTF8 +# encoding. The handling of that encoding will be application specific. + +########### +# Integer # +########### + +## Integers can start with a +, a - or nothing. +## Leading zeros are not allowed. Hex, octal, and binary forms are not allowed. +## Values that cannot be expressed as a series of digits are not allowed. +int1 = +42 +int2 = 0 +int3 = -21 +integerRange = 64 + +## You can use underscores to enhance readability. Each +## underscore must be surrounded by at least one digit. +int4 = 5_349_221 +int5 = 1_2_3_4_5 # VALID but discouraged + +######### +# Float # +######### + +# Floats are an integer followed by a fractional and/or an exponent part. +flt1 = 3.1415 +flt2 = -5e6 +flt3 = 6.626E-34 + +########### +# Boolean # +########### + +bool1 = true +bool2 = false +boolMustBeLowercase = true + +############ +# Datetime # +############ + +date1 = 1979-05-27T07:32:00Z # follows the RFC 3339 spec +date2 = 1979-05-27T07:32:00 # without offset +date3 = 1979-05-27 # without offset nor time + +#################### +# COLLECTION TYPES # +#################### + +######### +# Array # +######### + +array1 = [ 1, 2, 3 ] +array2 = [ "Commas", "are", "delimiters" ] +array3 = [ "Don't mixed", "different", "types" ] +array4 = [ [ 1.2, 2.4 ], ["all", 'strings', """are the same""", '''type'''] ] +array5 = [ + "Whitespace", "is", "ignored" +] + +######### +# Table # +######### + +# Tables (or hash tables or dictionaries) are collections of key/value +# pairs. They appear in square brackets on a line by themselves. +# Empty tables are allowed and simply have no key/value pairs within them. +[table] + +# Under that, and until the next table or EOF are the key/values of that table. +# Key/value pairs within tables are not guaranteed to be in any specific order. +[table-1] +key1 = "some string" +key2 = 123 + +[table-2] +key1 = "another string" +key2 = 456 + +# Dots are prohibited in bare keys because dots are used to signify nested tables. +# Naming rules for each dot separated part are the same as for keys. +[dog."tater.man"] +type = "pug" + +# In JSON land, that would give you the following structure: +# { "dog": { "tater.man": { "type": "pug" } } } + +# Whitespace around dot-separated parts is ignored, however, best practice is to +# not use any extraneous whitespace. +[a.b.c] # this is best practice +[ d.e.f ] # same as [d.e.f] +[ j . "ʞ" . 'l' ] # same as [j."ʞ".'l'] + +# You don't need to specify all the super-tables if you don't want to. TOML knows +# how to do it for you. +# [x] you +# [x.y] don't +# [x.y.z] need these +[x.y.z.w] # for this to work + +# As long as a super-table hasn't been directly defined and hasn't defined a +# specific key, you may still write to it. +[a.b] +c = 1 + +[a] +d = 2 + +# You cannot define any key or table more than once. Doing so is invalid. + +# DO NOT DO THIS +[a] +b = 1 + +[a] +c = 2 + +# DO NOT DO THIS EITHER +[a] +b = 1 + +[a.b] +c = 2 + +# All table names must be non-empty. +[] # INVALID +[a.] # INVALID +[a..b] # INVALID +[.b] # INVALID +[.] # INVALID + +################ +# Inline table # +################ + +inlineTables = { areEnclosedWith = "{ and }", mustBeInline = true } +point = { x = 1, y = 2 } + +################### +# Array of Tables # +################### + +# An array of tables can be expressed by using a table name in double brackets. +# Each table with the same double bracketed name will be an item in the array. +# The tables are inserted in the order encountered. + +[[products]] +name = "array of table" +sku = 738594937 +emptyTableAreAllowed = true + +[[products]] + +[[products]] +name = "Nail" +sku = 284758393 +color = "gray" + +# You can create nested arrays of tables as well. Each double-bracketed +# sub-table will belong to the nearest table element above it. + +[[fruit]] + name = "apple" + + [fruit.Geometry] + shape = "round" + note = "I am an fruit's property" + + [[fruit.color]] + name = "red" + note = "I am an array's item in apple" + + [[fruit.color]] + name = "green" + note = "I am in the same array than red" + +[[fruit]] + name = "banana" + + [[fruit.color]] + name = "yellow" + note = "I am an array's item too but banana's one" +``` + +In JSON land, this code will be: + +```json +{ + "fruit": [ + { + "name": "apple", + "geometry": { "shape": "round", "note": "..."}, + "color": [ + { "name": "red", "note": "..." }, + { "name": "green", "note": "..." } + ] + }, + { + "name": "banana", + "color": [ + { "name": "yellow", "note": "..." } + ] + } + ] +} +``` + +### More Resources + ++ [TOML official repository](https://github.com/toml-lang/toml) -- cgit v1.2.3 From 425d1dee6704599029ef7e27445328ad4c91d341 Mon Sep 17 00:00:00 2001 From: ven Date: Thu, 1 Sep 2016 21:03:09 +0200 Subject: Delete HTML-fr.html.markdown --- HTML-fr.html.markdown | 115 -------------------------------------------------- 1 file changed, 115 deletions(-) delete mode 100644 HTML-fr.html.markdown diff --git a/HTML-fr.html.markdown b/HTML-fr.html.markdown deleted file mode 100644 index fdde9107..00000000 --- a/HTML-fr.html.markdown +++ /dev/null @@ -1,115 +0,0 @@ ---- -language: html -filename: learnhtml-fr.html -contributors: - - ["Christophe THOMAS", "https://github.com/WinChris"] -lang: fr-fr ---- -HTML signifie HyperText Markup Language. -C'est un langage (format de fichiers) qui permet d'écrire des pages internet. -C’est un langage de balisage, il nous permet d'écrire des pages HTML au moyen de balises (Markup, en anglais). -Les fichiers HTML sont en réalité de simple fichier texte. -Qu'est-ce que le balisage ? C'est une façon de hiérarchiser ses données en les entourant par une balise ouvrante et une balise fermante. -Ce balisage sert à donner une signification au texte ainsi entouré. -Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parlons de HTML5. - -**NOTE :** Vous pouvez tester les différentes balises que nous allons voir au fur et à mesure du tutoriel sur des sites comme [codepen](http://codepen.io/pen/) afin de voir les résultats, comprendre, et vous familiariser avec le langage. -Cet article porte principalement sur la syntaxe et quelques astuces. - - -```HTML - - - - - - - - - - - Mon Site - - -

Hello, world!

- Venez voir ce que ça donne -

Ceci est un paragraphe

-

Ceci est un autre paragraphe

-
    -
  • Ceci est un item d'une liste non ordonnée (liste à puces)
  • -
  • Ceci est un autre item
  • -
  • Et ceci est le dernier item de la liste
  • -
- - - - - - - - - - - - - - - - - - - - Mon Site - - - - - - - -

Hello, world!

- - Venez voir ce que ça donne -

Ceci est un paragraphe

-

Ceci est un autre paragraphe

-
    - -
  • Ceci est un item d'une liste non ordonnée (liste à puces)
  • -
  • Ceci est un autre item
  • -
  • Et ceci est le dernier item de la liste
  • -
- - - - - - - - - - - - - - - - - - - - - - - - - -
First Header Second Header
Première ligne, première cellule Première ligne, deuxième cellule
Deuxième ligne, première celluleDeuxième ligne, deuxième cellule
- -## Utilisation - -Le HTML s'écrit dans des fichiers `.html`. - -## En savoir plus - -* [Tutoriel HTML](http://slaout.linux62.org/html_css/html.html) -* [W3School](http://www.w3schools.com/html/html_intro.asp) -- cgit v1.2.3 From 7beaa529b912ccda6e26eee85acae50e79c6d6d5 Mon Sep 17 00:00:00 2001 From: Patrick Callahan Date: Thu, 1 Sep 2016 17:27:33 -0400 Subject: [python3/en] Adding "Dive Into Python 3" (#2353) The previous version of this file had the original Dive Into Python, which was written with Python 2 in mind. It has come to my attention that the author of the original has published an updated version designed for Python 3, so I added this version back in. --- python3.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/python3.html.markdown b/python3.html.markdown index 09b041b8..dc534f74 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -896,7 +896,9 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) * [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) * [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](http://www.diveintopython3.net/index.html) ### Dead Tree * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python 3](https://www.amazon.com/gp/product/1430224150?ie=UTF8&tag=diveintomark-20&creativeASIN=1430224150) -- cgit v1.2.3 From 66c8b036dcdbcd538f914e14d073194d704159fa Mon Sep 17 00:00:00 2001 From: robochat Date: Sat, 3 Sep 2016 19:30:53 +0200 Subject: [html/en] adding translation of html/fr (#2354) * [html/en] adding a translation of html/fr. * [html/en] small changes and 1 bug fix. * [html/fr] small bug fix. * [html/en] small bug fix. --- fr-fr/HTML-fr.html.markdown | 2 + html.html.markdown | 120 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 122 insertions(+) create mode 100644 html.html.markdown diff --git a/fr-fr/HTML-fr.html.markdown b/fr-fr/HTML-fr.html.markdown index 4d2da921..b52fd34a 100644 --- a/fr-fr/HTML-fr.html.markdown +++ b/fr-fr/HTML-fr.html.markdown @@ -106,6 +106,8 @@ Cet article porte principalement sur la syntaxe et quelques astuces. +``` + ## Utilisation Le HTML s'écrit dans des fichiers `.html`. diff --git a/html.html.markdown b/html.html.markdown new file mode 100644 index 00000000..3e5e43c3 --- /dev/null +++ b/html.html.markdown @@ -0,0 +1,120 @@ +--- +language: html +filename: learnhtml.html +contributors: + - ["Christophe THOMAS", "https://github.com/WinChris"] +translators: + - ["Robert Steed", "https://github.com/robochat"] +--- + +HTML stands for HyperText Markup Language. +It is a language which us to write pages for the world wide web. +It is a markup language, it enables us to write to write webpages using code to indicate how text and data should be displayed. +In fact, html files are simple text files. +What is this markup? It is a method of organising the page's data by surrounding it with opening tags and closing tags. +This markup serves to give significance to the text that it encloses. +Like other computer languages, HTML has many versions. Here we will talk about HTML5. + +**NOTE :** You can test the different tags and elements as you progress through the tutorial on a site like [codepen](http://codepen.io/pen/) in order to see their effects, understand how they work and familiarise yourself with the language. +This article is concerned principally with HTML syntax and some useful tips. + + +```html + + + + + + + + + + My Site + + +

Hello, world!

+ Come look at what this shows/a> +

This is a paragraph.

+

This is another paragraph.

+
    +
  • This is an item in a non-enumerated list (bullet list)
  • +
  • This is another item
  • +
  • And this is the last item on the list
  • +
+ + + + + + + + + + + + + + + + + + + + + My Site + + + + + + + +

Hello, world!

+ +
Come look at what this shows +

This is a paragraph.

+

This is another paragraph.

+
    + +
  • This is an item in a non-enumerated list (bullet list)
  • +
  • This is another item
  • +
  • And this is the last item on the list
  • +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
First Header Second Header
first row, first column first row, second column
second row, first columnsecond row, second column
+ +``` + +## Usage + +HTML is written in files ending with `.html`. + +## To Learn More + +* [wikipedia](https://en.wikipedia.org/wiki/HTML) +* [HTML tutorial](https://developer.mozilla.org/en-US/docs/Web/HTML) +* [W3School](http://www.w3schools.com/html/html_intro.asp) -- cgit v1.2.3 From a00c47f70141ee694eef7dabc54778d3c178607d Mon Sep 17 00:00:00 2001 From: Baurzhan Muftakhidinov Date: Mon, 5 Sep 2016 12:42:02 +0500 Subject: Add missing space. (#2356) --- binary-search.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/binary-search.html.markdown b/binary-search.html.markdown index 92df4875..ce436b44 100644 --- a/binary-search.html.markdown +++ b/binary-search.html.markdown @@ -9,7 +9,7 @@ contributors: ## Why Binary Search? -Searching is one of the prime problems in the domain of Computer Science.Today there are more than 1 trillion searches per year, and we need algorithms that can do that very fastly. Binary search is one of the fundamental algorithms in computer science. In order to explore it, we’ll first build up a theoretical backbone, then use that to implement the algorithm properly. +Searching is one of the prime problems in the domain of Computer Science. Today there are more than 1 trillion searches per year, and we need algorithms that can do that very fastly. Binary search is one of the fundamental algorithms in computer science. In order to explore it, we’ll first build up a theoretical backbone, then use that to implement the algorithm properly. ## Introduction -- cgit v1.2.3 From d75468c6fe58c3152facf0dffd8743a6c2edbec0 Mon Sep 17 00:00:00 2001 From: robochat Date: Mon, 5 Sep 2016 10:34:25 +0200 Subject: adding missing lang entries to headers for 3 tutorials (#2352) --- id-id/markdown.html.markdown | 1 + it-it/rust-it.html.markdown | 1 + pt-br/elixir.html.markdown | 1 + 3 files changed, 3 insertions(+) diff --git a/id-id/markdown.html.markdown b/id-id/markdown.html.markdown index 9a7c18cc..06ad1092 100644 --- a/id-id/markdown.html.markdown +++ b/id-id/markdown.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - ["Tasya Aditya Rukmana", "http://github.com/tadityar"] +lang: id-id filename: markdown-id.md --- diff --git a/it-it/rust-it.html.markdown b/it-it/rust-it.html.markdown index dd5005f2..8ef09712 100644 --- a/it-it/rust-it.html.markdown +++ b/it-it/rust-it.html.markdown @@ -2,6 +2,7 @@ language: rust contributors: - ["Carlo Milanesi", "http://github.com/carlomilanesi"] +lang: it-it filename: rust-it.html.markdown --- diff --git a/pt-br/elixir.html.markdown b/pt-br/elixir.html.markdown index b4ca8a52..f8c56101 100644 --- a/pt-br/elixir.html.markdown +++ b/pt-br/elixir.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Dzianis Dashkevich", "https://github.com/dskecse"] translators: - ["Rodrigo Muniz", "http://github.com/muniz95"] +lang: pt-br filename: learnelixir-pt.ex --- -- cgit v1.2.3 From 30e5ceed3174347d675b5eb9a474c960e1542d44 Mon Sep 17 00:00:00 2001 From: Ondrej Linek Date: Mon, 5 Sep 2016 22:19:17 +0200 Subject: add Czech [cs-cz] translation of the Go intro. (#2357) --- cs-cz/go.html.markdown | 431 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 431 insertions(+) create mode 100644 cs-cz/go.html.markdown diff --git a/cs-cz/go.html.markdown b/cs-cz/go.html.markdown new file mode 100644 index 00000000..f814d2da --- /dev/null +++ b/cs-cz/go.html.markdown @@ -0,0 +1,431 @@ +--- +name: Go +category: language +language: Go +filename: learngo.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] + - ["Christopher Bess", "https://github.com/cbess"] + - ["Jesse Johnson", "https://github.com/holocronweaver"] + - ["Quint Guvernator", "https://github.com/qguv"] + - ["Jose Donizetti", "https://github.com/josedonizetti"] + - ["Alexej Friesen", "https://github.com/heyalexej"] + - ["Clayton Walker", "https://github.com/cwalk"] +translators: + - ["Ondra Linek", "https://github.com/defectus/"] + +--- + +Jazyk Go byl vytvořen, jelikož bylo potřeba dokončit práci. Není to poslední +trend ve světě počítačové vědy, ale je to nejrychlejší a nejnovější způsob, +jak řešit realné problémy. + +Go používá známé koncepty imperativních jazyků se statickým typováním. +Rychle se kompiluje a také rychle běží. Přidává snadno pochopitelnou +podporu konkurenčnosti, což umožňuje využít výhody multi-core procesorů a +jazyk také obsahuje utility, které pomáhají se škálovatelným programováním. + +Go má již v základu vynikající knihovnu a je s ním spojená nadšená komunita. + +```go +// Jednořádkový komentář +/* Několika + řádkový komentář */ + +// Každý zdroják začíná deklarací balíčku (package) +// Main je vyhrazené jméno, které označuje spustitelný soubor, +// narozdíl od knihovny +package main + +// Importní deklarace říkají, které knihovny budou použity v tomto souboru. +import ( + "fmt" // Obsahuje formátovací funkce a tisk na konzolu + "io/ioutil" // Vstupně/výstupní funkce + m "math" // Odkaz na knihovnu math (matematické funkce) pod zkratkou m + "net/http" // Podpora http protokolu, klient i server. + "strconv" // Konverze řetězců, např. na čísla a zpět. +) + +// Definice funkce. Funkce main je zvláštní, je to vstupní bod do programu. +// Ať se vám to líbí, nebo ne, Go používá složené závorky +func main() { + // Println vypisuje na stdout. + // Musí být kvalifikováno jménem svého balíčko, ftm. + fmt.Println("Hello world!") + + // Zavoláme další funkci + svetPoHello() +} + +// Funkce mají své parametry v závorkách +// Pokud funkce nemá parametry, tak musíme stejně závorky uvést. +func svetPoHello() { + var x int // Deklarace proměnné. Proměnné musí být před použitím deklarované + x = 3 // Přiřazení hodnoty do proměnné + // Existuje "krátká" deklarace := kde se typ proměnné odvodí, + // proměnná vytvoří a přiřadí se jí hodnota + y := 4 + sum, prod := naucSeNasobit(x, y) // Funkce mohou vracet více hodnot + fmt.Println("sum:", sum, "prod:", prod) // Jednoduchý výstup + naucSeTypy() // < y minut je za námi, je čas učit se víc! +} + +/* <- začátek mnohořádkového komentáře +Funkce mohou mít parametry a (několik) návratových hodnot. +V tomto případě jsou `x`, `y` parametry a `sum`, `prod` jsou návratové hodnoty. +Všiměte si, že `x` a `sum` jsou typu `int`. +*/ +func naucSeNasobit(x, y int) (sum, prod int) { + return x + y, x * y // Vracíme dvě hodnoty +} + +// zabudované typy a literáty. +func naucSeTypy() { + // Krátká deklarace většinou funguje + str := "Learn Go!" // typ řetězec. + + s2 := `"surový" literát řetězce +může obsahovat nové řádky` // Opět typ řetězec. + + // Můžeme použít ne ASCII znaky, Go používá UTF-8. + g := 'Σ' // type runa, což je alias na int32 a ukládá se do něj znak UTF-8 + + f := 3.14195 // float64, je IEEE-754 64-bit číslem s plovoucí čárkou. + c := 3 + 4i // complex128, interně uložené jako dva float64. + + // takhle vypadá var s inicializací + var u uint = 7 // Číslo bez znaménka, jehož velikost záleží na implementaci, + // stejně jako int + var pi float32 = 22. / 7 + + // takto se převádí typy za pomoci krátké syntaxe + n := byte('\n') // byte je jiné jméno pro uint8. + + // Pole mají fixní délku, které se určuje v době kompilace. + var a4 [4]int // Pole 4 intů, všechny nastaveny na 0. + a3 := [...]int{3, 1, 5} // Pole nastaveno na tři hodnoty + // elementy mají hodntu 3, 1 a 5 + + // Slicy mají dynamickou velikost. Pole i slacy mají své výhody, + // ale většinou se používají slicy. + s3 := []int{4, 5, 9} // Podobně jako a3, ale není tu výpustka. + s4 := make([]int, 4) // Alokuj slice 4 intů, všechny nastaveny na 0. + var d2 [][]float64 // Deklarace slicu, nic se nealokuje. + bs := []byte("a slice") // Přetypování na slice + + // Protože jsou dynamické, můžeme ke slicům přidávat za běhu + // Přidat ke slicu můžeme pomocí zabudované funkce append(). + // Prvním parametrem je slice, návratová hodnota je aktualizovaný slice. + s := []int{1, 2, 3} // Výsledkem je slice se 3 elementy. + s = append(s, 4, 5, 6) // Přidány další 3 elementy. Slice má teď velikost 6. + fmt.Println(s) // Slice má hodnoty [1 2 3 4 5 6] + + // Pokud chceme k poli přičíst jiné pole, můžeme předat referenci na slice, + // nebo jeho literát a přidat výpustku, čímž se slicu "rozbalí" a přidá se k + // původnímu slicu. + s = append(s, []int{7, 8, 9}...) // druhým parametrem je literát slicu. + fmt.Println(s) // slice má teď hodnoty [1 2 3 4 5 6 7 8 9] + + p, q := naucSePraciSPameti() // Deklarujeme p a q jako typ pointer na int. + fmt.Println(*p, *q) // * dereferencuje pointer. Tím se vypíší dva inty. + + // Mapy jsou dynamické rostoucí asociativní pole, jako hashmapa, nebo slovník + // (dictionary) v jiných jazycích + m := map[string]int{"tri": 3, "ctyri": 4} + m["jedna"] = 1 + + // Napoužité proměnné jsou v Go chybou. + // Použijte podtržítko, abychom proměnno "použili". + _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs + // Výpis promenné se počítá jako použití. + fmt.Println(s, c, a4, s3, d2, m) + + naucSeVetveníProgramu() // Zpátky do běhu. +} + +// narozdíl od jiných jazyků, v Go je možné mít pojmenované návratové hodnoty. +// Tak můžeme vracet hodnoty z mnoha míst funkce, aniž bychom uváděli hodnoty v +// return. +func naucSePojmenovaneNavraty(x, y int) (z int) { + z = x * y + return // z je zde implicitní, jelikož bylo pojmenováno. +} + +// Go má garbage collector. Používá pointery, ale neumožňuje jejich aritmetiku. +// Můžete tedy udělat chybu použitím nil odkazu, ale ne jeho posunutím. +func naucSePraciSPameti() (p, q *int) { + // Pojmenované parametry p a q mají typ odkaz na int. + p = new(int) // Zabudované funkce new alokuje paměť. + // Alokované místo pro int má hodnotu 0 a p už není nil. + s := make([]int, 20) // Alokujeme paměť pro 20 intů. + s[3] = 7 // Jednu z nich nastavíme. + r := -2 // Deklarujeme další lokální proměnnou. + return &s[3], &r // a vezmeme si jejich odkaz pomocí &. +} + +func narocnyVypocet() float64 { + return m.Exp(10) +} + +func naucSeVetveníProgramu() { + // Výraz if vyžaduje složené závorky, ale podmínka nemusí být v závorkách. + if true { + fmt.Println("říkal jsme ti to") + } + // Formátování je standardizované pomocí utility "go fmt". + if false { + // posměšek. + } else { + // úšklebek. + } + // Použij switch, když chceš zřetězit if. + x := 42.0 + switch x { + case 0: + case 1: + case 42: + // jednotlivé case nepropadávají. není potřeba "break" + case 43: + // nedosažitelné, jelikož už bylo ošetřeno. + default: + // implicitní větev je nepovinná. + } + // Stejně jako if, for (smyčka) nepoužívá závorky. + // Proměnné definované ve for jsou lokální vůči smyčce. + for x := 0; x < 3; x++ { // ++ je výrazem. + fmt.Println("iterace", x) + } + // zde je x == 42. + + // For je jediná smyčka v Go, ale má několik tvarů. + for { // Nekonečná smyčka + break // Dělám si legraci + continue // Sem se nedostaneme + } + + // Můžete použít klíčové slovo range pro iteraci nad mapami, poli, slicy, + // řetězci a kanály. + // range vrací jednu (kanál) nebo dvě hodnoty (pole, slice, řetězec a mapa). + for key, value := range map[string]int{"jedna": 1, "dva": 2, "tri": 3} { + // pro každý pár (klíč a hodnota) je vypiš + fmt.Printf("klíč=%s, hodnota=%d\n", key, value) + } + + // stejně jako for, := v podmínce if přiřazuje hodnotu + // nejříve nastavíme y a pak otestujeme, jestli je y větší než x. + if y := narocnyVypocet(); y > x { + x = y + } + // Funkční literáty jsou tzv. uzávěry (closure) + xBig := func() bool { + return x > 10000 // odkazuje na x deklarované ve příkladu použití switch + } + x = 99999 + fmt.Println("xBig:", xBig()) // true + x = 1.3e3 // To udělá z x == 1300 + fmt.Println("xBig:", xBig()) // teď už false. + + // Dále je možné funkční literáty definovat a volat na místě jako parametr + // funkce, dokavaď: + // a) funkční literát je okamžitě volán pomocí (), + // b) výsledek se shoduje s očekávaným typem. + fmt.Println("Sečte + vynásobí dvě čísla: ", + func(a, b int) int { + return (a + b) * 2 + }(10, 2)) // Voláno s parametry 10 a 2 + // => Sečti a vynásob dvě čísla. 24 + + // Když to potřebujete, tak to milujete + goto miluji +miluji: + + naučteSeFunkčníFactory() // funkce vracející funkce je zábava(3)(3) + naučteSeDefer() // malá zajížďka k důležitému klíčovému slovu. + naučteSeInterfacy() // Přichází dobré věci! +} + +func naučteSeFunkčníFactory() { + // Následující dvě varianty jsou stejné, ale ta druhá je praktičtější + fmt.Println(větaFactory("létní")("Hezký", "den!")) + + d := větaFactory("letní") + fmt.Println(d("Hezký", "den!")) + fmt.Println(d("Líný", "odpoledne!")) +} + +// Dekorátory jsou běžné v jiných jazycích. To samé můžete udělat v Go +// pomocí parameterizovatelných funkčních literátů. +func větaFactory(můjŘetězec string) func(před, po string) string { + return func(před, po string) string { + return fmt.Sprintf("%s %s %s", před, můjŘetězec, po) // nový řetězec + } +} + +func naučteSeDefer() (ok bool) { + // Odloží (defer) příkazy na okamžik těsně před opuštěním funkce. + // tedy poslední se provede první + defer fmt.Println("odložené příkazy jsou zpravovaná v LIFO pořadí.") + defer fmt.Println("\nProto je tato řádka vytištěna první") + // Defer se běžně používá k zavírání souborů a tím se zajistí, že soubor + // bude po ukončení funkce zavřen. + return true +} + +// definuje typ interfacu s jednou metodou String() +type Stringer interface { + String() string +} + +// Definuje pár jako strukturu se dvěma poli typu int x a y. +type pár struct { + x, y int +} + +// Definuje method pár. Pár tedy implementuje interface Stringer. +func (p pár) String() string { // p je tu nazýváno "Receiver" - přijímač + // Sprintf je další veřejná funkce z balíčku fmt. + // Pomocí tečky přistupujeme k polím proměnné p + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func naučteSeInterfacy() { + // Složené závorky jsou "strukturální literáty. Vyhodnotí a inicializuje + // strukturu. Syntaxe := deklaruje a inicializuje strukturu. + p := pár{3, 4} + fmt.Println(p.String()) // Volá metodu String na p typu pár. + var i Stringer // Deklaruje i jako proměnné typu Stringer. + i = p // Toto je možné, jelikož oba implementují Stringer + // zavolá metodu String(( typu Stringer a vytiskne to samé jako předchozí. + fmt.Println(i.String()) + + // Funkce ve balíčku fmt volají metodu String, když zjišťují, jak se má typ + // vytisknout. + fmt.Println(p) // Vytiskne to samé, jelikož Println volá String(). + fmt.Println(i) // Ten samý výstup. + + naučSeVariabilníParametry("super", "učit se", "tady!") +} + +// Funcke mohou mít proměnlivé množství parametrů. +func naučSeVariabilníParametry(mojeŘetězce ...interface{}) { + // Iterujeme přes všechny parametry + // Potržítku tu slouží k ignorování indexu v poli. + for _, param := range mojeŘetězce { + fmt.Println("parameter:", param) + } + + // Použít variadický parametr jako variadický parametr, nikoliv pole. + fmt.Println("parametery:", fmt.Sprintln(mojeŘetězce...)) + + naučSeOšetřovatChyby() +} + +func naučSeOšetřovatChyby() { + // ", ok" je metodou na zjištění, jestli něco fungovalo, nebo ne. + m := map[int]string{3: "tri", 4: "ctyri"} + if x, ok := m[1]; !ok { // ok bude false, jelikož 1 není v mapě. + fmt.Println("není tu jedna") + } else { + fmt.Print(x) // x by bylo tou hodnotou, pokud by bylo v mapě. + } + // hodnota error není jen znamením OK, ale může říct více o chybě. + if _, err := strconv.Atoi("ne-int"); err != nil { // _ hodnotu zahodíme + // vytiskne 'strconv.ParseInt: parsing "non-int": invalid syntax' + fmt.Println(err) + } + // Znovu si povíme o interfacech, zatím se podíváme na + naučSeKonkurenčnost() +} + +// c je kanál, způsob, jak bezpečně komunikovat v konkurenčním prostředí. +func zvyš(i int, c chan int) { + c <- i + 1 // <- znamená "pošli" a posílá data do kanálu na levé straně. +} + +// Použijeme funkci zvyš a konkurečně budeme zvyšovat čísla. +func naučSeKonkurenčnost() { + // funkci make jsme již použili na slicy. make alokuje a inicializuje slidy, + // mapy a kanály. + c := make(chan int) + // nastartuj tři konkurenční go-rutiny. Čísla se budou zvyšovat + // pravděpodobně paralelně pokud je počítač takto nakonfigurován. + // Všechny tři zapisují do toho samého kanálu. + go zvyš(0, c) // go je výraz pro start nové go-rutiny. + go zvyš(10, c) + go zvyš(-805, c) + // Přečteme si tři výsledky a vytiskeneme je.. + // Nemůžeme říct, v jakém pořadí výsledky přijdou! + fmt.Println(<-c, <-c, <-c) // pokud je kanál na pravo, jedná se o "přijmi". + + cs := make(chan string) // Další kanál, tentokrát pro řetězce. + ccs := make(chan chan string) // Kanál kanálu řetězců. + go func() { c <- 84 }() // Start nové go-rutiny na posílání hodnot. + go func() { cs <- "wordy" }() // To samé s cs. + // Select má syntaxi jako switch, ale vztahuje se k operacím nad kanály. + // Náhodně vybere jeden case, který je připraven na komunikaci. + select { + case i := <-c: // Přijatá hodnota může být přiřazena proměnné. + fmt.Printf("je to typ %T", i) + case <-cs: // nebo může být zahozena + fmt.Println("je to řetězec") + case <-ccs: // prázdný kanál, nepřipraven ke komunikaci. + fmt.Println("to se nestane.") + } + // V tomto okamžiku máme hodnotu buď z kanálu c nabo cs. Jedna nebo druhá + // nastartovaná go-rutina skončila a další zůstane blokovaná. + + naučSeProgramovatWeb() // Go to umí. A vy to chcete taky. +} + +// jen jedna funkce z balíčku http spustí web server. +func naučSeProgramovatWeb() { + + // První parametr ListenAndServe je TCP adresa, kde poslouchat. + // Druhý parametr je handler, implementující interace http.Handler. + go func() { + err := http.ListenAndServe(":8080", pár{}) + fmt.Println(err) // neignoruj chyby + }() + + requestServer() +} + +// Umožní typ pár stát se http tím, že implementuje její jedinou metodu +// ServeHTTP. +func (p pár) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Servíruj data metodou http.ResponseWriter + w.Write([]byte("Naučil ses Go za y minut!")) +} + +func requestServer() { + resp, err := http.Get("http://localhost:8080") + fmt.Println(err) + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + fmt.Printf("\nWebserver řekl: `%s`", string(body)) +} +``` + +## Kam dále + +Vše hlavní o Go se nachází na [oficiálních stránkách go](http://golang.org/). +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 +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 +[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/) +tak se podíváte na dokumentaci. + +Dalším dobrým zdrojem informací je [Go v ukázkách](https://gobyexample.com/). + +Go mobile přidává podporu pro Android a iOS. Můžete s ním psát nativní mobilní aplikace nebo knihovny, které půjdou +spustit přes Javu (pro Android), nebo Objective-C (pro iOS). Navštivte [web Go Mobile](https://github.com/golang/go/wiki/Mobile) +pro více informací. -- cgit v1.2.3 From ffba631fdd0413bbcde75d2d3791f679c7029d8e Mon Sep 17 00:00:00 2001 From: ven Date: Mon, 5 Sep 2016 22:19:48 +0200 Subject: Update go.html.markdown --- cs-cz/go.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cs-cz/go.html.markdown b/cs-cz/go.html.markdown index f814d2da..36217414 100644 --- a/cs-cz/go.html.markdown +++ b/cs-cz/go.html.markdown @@ -2,7 +2,8 @@ name: Go category: language language: Go -filename: learngo.go +filename: learngo-cs.go +lang: cs-cz contributors: - ["Sonia Keys", "https://github.com/soniakeys"] - ["Christopher Bess", "https://github.com/cbess"] @@ -13,7 +14,6 @@ contributors: - ["Clayton Walker", "https://github.com/cwalk"] translators: - ["Ondra Linek", "https://github.com/defectus/"] - --- Jazyk Go byl vytvořen, jelikož bylo potřeba dokončit práci. Není to poslední -- cgit v1.2.3 From b59e6fa07d1cd13951f9bbd54f9aaf31e0367943 Mon Sep 17 00:00:00 2001 From: Martin Pacheco Date: Tue, 6 Sep 2016 05:13:39 -0300 Subject: add new resource link (#2307) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The link is a PDF elaborated by teachers of the course "Programación 3" (Algorithms and Data Structures) with examples about calculating the order of an algorithm and other topics in the context of asymptotic notation. This material is publicly listed here: https://eva.fing.edu.uy/pluginfile.php/95278/mod_resource/content/0/Apuntes%20sobre%20An%C3%A1lisis%20de%20Algoritmos.pdf but I uploaded it to Scribd because I know that the link could eventually change since it's hosted in a moodle platform and now and then the teachers change the location of the files. --- es-es/asymptotic-notation-es.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/es-es/asymptotic-notation-es.html.markdown b/es-es/asymptotic-notation-es.html.markdown index f3fe1614..3507429c 100644 --- a/es-es/asymptotic-notation-es.html.markdown +++ b/es-es/asymptotic-notation-es.html.markdown @@ -168,3 +168,4 @@ definiciones y ejemplos. * [MIT](http://web.mit.edu/16.070/www/lecture/big_o.pdf) * [KhanAcademy](https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation) +* [Apuntes Facultad de Ingeniería](https://www.scribd.com/document/317979564/Apuntes-Sobre-Analisis-de-Algoritmos) -- cgit v1.2.3 From a35179982940297bd857ceddfdc792c3ff2a73d0 Mon Sep 17 00:00:00 2001 From: Matthias Kern Date: Tue, 6 Sep 2016 10:25:45 +0200 Subject: [tmux] Updating for version 2.1 (#1733) * Update mouse option and remove old window-status-content options for tmux 2.1 compability * Add contribution and update timestamp --- tmux.html.markdown | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index ae73d912..e39d78fc 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -3,6 +3,7 @@ category: tool tool: tmux contributors: - ["mdln", "https://github.com/mdln"] + - ["matthiaskern", "https://github.com/matthiaskern"] filename: LearnTmux.txt --- @@ -116,7 +117,7 @@ like how .vimrc or init.el are used. ``` # Example tmux.conf -# 2014.10 +# 2015.12 ### General @@ -129,7 +130,7 @@ set -g history-limit 2048 set -g base-index 1 # Mouse -set-option -g mouse-select-pane on +set-option -g -q mouse on # Force reload of config file unbind r @@ -204,8 +205,6 @@ setw -g window-status-bg black setw -g window-status-current-fg green setw -g window-status-bell-attr default setw -g window-status-bell-fg red -setw -g window-status-content-attr default -setw -g window-status-content-fg yellow setw -g window-status-activity-attr default setw -g window-status-activity-fg yellow @@ -246,6 +245,4 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | [Display CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) -[tmuxinator - Manage complex tmux sessions](https://github.com/tmuxinator/tmuxinator) - - +[tmuxinator - Manage complex tmux sessions](https://github.com/tmuxinator/tmuxinator) -- cgit v1.2.3 From 91c1f6b83212f6a0403ace29dde0c24021d7ebd2 Mon Sep 17 00:00:00 2001 From: ven Date: Tue, 6 Sep 2016 10:26:04 +0200 Subject: #1733 --- tmux.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index e39d78fc..1214a5ba 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -3,7 +3,6 @@ category: tool tool: tmux contributors: - ["mdln", "https://github.com/mdln"] - - ["matthiaskern", "https://github.com/matthiaskern"] filename: LearnTmux.txt --- -- cgit v1.2.3 From 191019111b9c9c377ea0f4db6db845ced07fb546 Mon Sep 17 00:00:00 2001 From: IamRafy Date: Tue, 6 Sep 2016 13:56:22 +0530 Subject: Meteor Js (#1711) * Livescript is Updated * Revert "Livescript is Updated" This reverts commit 9f609e23e647abc3088fbae51551b9486531df0e. * Meteor js --- Meteor.html.markdown | 567 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 567 insertions(+) create mode 100644 Meteor.html.markdown diff --git a/Meteor.html.markdown b/Meteor.html.markdown new file mode 100644 index 00000000..d47d302b --- /dev/null +++ b/Meteor.html.markdown @@ -0,0 +1,567 @@ +--- +language: Meteor.js +Filename: Meteor.html.markdown +contributors: + - ["Mohammed Rafy", "https://github.com/IamRafy/"] + +--- + + + +Meteor is an ultra-simple environment for building modern websites. What once took weeks, even with the best tools, now takes hours with Meteor. + +The web was originally designed to work in the same way that mainframes worked in the 70s. The application server rendered a screen and sent it over the network to a dumb terminal. Whenever the user did anything, that server rerendered a whole new screen. This model served the Web well for over a decade. It gave rise to LAMP, Rails, Django, PHP. + +But the best teams, with the biggest budgets and the longest schedules, now build applications in JavaScript that run on the client. These apps have stellar interfaces. They don't reload pages. They are reactive: changes from any client immediately appear on everyone's screen. + +They've built them the hard way. Meteor makes it an order of magnitude simpler, and a lot more fun. You can build a complete application in a weekend, or a sufficiently caffeinated hackathon. No longer do you need to provision server resources, or deploy API endpoints in the cloud, or manage a database, or wrangle an ORM layer, or swap back and forth between JavaScript and Ruby, or broadcast data invalidations to clients. +Meteor Supports OS X, Windows, and Linux. // https://github.com/meteor/meteor/wiki/Supported-Platforms +On Windows? https://install.meteor.com/windows +On OS X or Linux? Install the latest official Meteor release from your terminal: +$ curl https://install.meteor.com/ | sh +The Windows installer supports Windows 7, Windows 8.1, Windows Server 2008, and Windows Server 2012. The command line installer supports Mac OS X 10.7 (Lion) and above, and Linux on x86 and x86_64 architectures. + +Once you've installed Meteor, create a project: +meteor create myapp +Run it locally: + +cd myapp +meteor +# Meteor server running on: http://localhost:3000/ + +Then, open a new terminal tab and unleash it on the world (on a free server we provide): + +meteor deploy myapp.meteor.com + +Principles of Meteor + +* Data on the Wire. Meteor doesn't send HTML over the network. The server sends data and lets the client render it. + +* One Language. Meteor lets you write both the client and the server parts of your application in JavaScript. + +* Database Everywhere. You can use the same methods to access your database from the client or the server. + +* Latency Compensation. On the client, Meteor prefetches data and simulates models to make it look like server method calls return instantly. + +* Full Stack Reactivity. In Meteor, realtime is the default. All layers, from database to template, update themselves automatically when necessary. + +* Embrace the Ecosystem. Meteor is open source and integrates with existing open source tools and frameworks. + +* Simplicity Equals Productivity. The best way to make something seem simple is to have it actually be simple. Meteor's main functionality has clean, classically beautiful APIs. + +Developer Resources +------------------- + +If anything in Meteor catches your interest, we hope you'll get involved with the project! + +TUTORIAL +Get started fast with the official Meteor tutorial! https://www.meteor.com/install + +STACK OVERFLOW +The best place to ask (and answer!) technical questions is on Stack Overflow. Be sure to add the meteor tag to your question. +http://stackoverflow.com/questions/tagged/meteor + +FORUMS +Visit the Meteor discussion forumsto announce projects, get help, talk about the community, or discuss changes to core. +https://forums.meteor.com/ + +GITHUB +The core code is on GitHub. If you're able to write code or file issues, we'd love to have your help. Please read Contributing to Meteor for how to get started. https://github.com/meteor/meteor + +THE METEOR MANUAL +In-depth articles about the core components of Meteor can be found on the Meteor Manual. The first article is about Tracker, our transparent reactivity framework. More articles (covering topics like Blaze, Unibuild, and DDP) are coming soon! http://manual.meteor.com/ + +What is Meteor? +--------------- + +Meteor is two things: + +A library of packages: pre-written, self-contained modules that you might need in your app. + +There are about a dozen core Meteor packages that most any app will use. Two examples: webapp, which handles incoming HTTP connections, and templating, which lets you make HTML templates that automatically update live as data changes. Then there are optional packages like email, which lets your app send emails, or the Meteor Accounts series (accounts-password, accounts-facebook, accounts-ui, and others) which provide a full-featured user account system that you can drop right into your app. In addition to these "core" packages, there are thousands of community-written packages in Atmosphere, one of which might do just what you need. + +A command-line tool called meteor. + +meteor is a build tool analogous to make, rake, or the non-visual parts of Visual Studio. It gathers up all of the source files and assets in your application, carries out any necessary build steps (such as compiling CoffeeScript, minifying CSS, building npm modules, or generating source maps), fetches the packages used by your app, and outputs a standalone, ready-to-run application bundle. In development mode it can do all of this interactively, so that whenever you change a file you immediately see the changes in your browser. It's super easy to use out of the box, but it's also extensible: you can add support for new languages and compilers by adding build plugin packages to your app. + +The key idea in the Meteor package system is that everything should work identically in the browser and on the server (wherever it makes sense, of course: browsers can't send email and servers can't capture mouse events). Our whole ecosystem has been built from the ground up to support this. + +Structuring your application +---------------------------- + +A Meteor application is a mix of client-side JavaScript that runs inside a web browser or PhoneGap mobile app, server-side JavaScript that runs on the Meteor server inside a Node.js container, and all the supporting HTML templates, CSS rules, and static assets. Meteor automates the packaging and transmission of these different components, and it is quite flexible about how you choose to structure those components in your file tree. + +Special Directories +------------------- + +By default, any JavaScript files in your Meteor folder are bundled and sent to the client and the server. However, the names of the files and directories inside your project can affect their load order, where they are loaded, and some other characteristics. Here is a list of file and directory names that are treated specially by Meteor: + +client + +Any directory named client is not loaded on the server. Similar to wrapping your code in if (Meteor.isClient) { ... }. All files loaded on the client are automatically concatenated and minified when in production mode. In development mode, JavaScript and CSS files are not minified, to make debugging easier. (CSS files are still combined into a single file for consistency between production and development, because changing the CSS file's URL affects how URLs in it are processed.) + +HTML files in a Meteor application are treated quite a bit differently from a server-side framework. Meteor scans all the HTML files in your directory for three top-level elements: , , and