diff options
78 files changed, 4677 insertions, 796 deletions
diff --git a/c.html.markdown b/c.html.markdown index a8f71057..7c2386ef 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -148,15 +148,10 @@ int main (int argc, char** argv) printf("Enter the array size: "); // ask the user for an array size int size; fscanf(stdin, "%d", &size); - char buf[size]; - fgets(buf, sizeof buf, stdin); - - // strtoul parses a string to an unsigned integer - size_t size2 = strtoul(buf, NULL, 10); - int var_length_array[size2]; // declare the VLA + int var_length_array[size]; // declare the VLA printf("sizeof array = %zu\n", sizeof var_length_array); - // A possible outcome of this program may be: + // Example: // > Enter the array size: 10 // > sizeof array = 40 @@ -445,6 +440,17 @@ int main (int argc, char** argv) for (xx = 0; xx < 20; xx++) { *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx } // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints) + + // Note that there is no standard way to get the length of a + // dynamically allocated array in C. Because of this, if your arrays are + // going to be passed around your program a lot, you need another variable + // to keep track of the number of elements (size) of an array. See the + // functions section for more info. + int size = 10; + int *my_arr = malloc(sizeof(int) * size); + // Add an element to the array + my_arr = realloc(my_arr, ++size); + my_arr[10] = 5; // Dereferencing memory that you haven't allocated gives // "unpredictable results" - the program is said to invoke "undefined behavior" @@ -530,6 +536,29 @@ swapTwoNumbers(&first, &second); printf("first: %d\nsecond: %d\n", first, second); // values will be swapped */ + +/* +With regards to arrays, they will always be passed to functions +as pointers. Even if you statically allocate an array like `arr[10]`, +it still gets passed as a pointer to the first element in any function calls. +Again, there is no standard way to get the size of a dynamically allocated +array in C. +*/ +// Size must be passed! +// Otherwise, this function has no way of knowing how big the array is. +void printIntArray(int *arr, int size) { + int i; + for (i = 0; i < size; i++) { + printf("arr[%d] is: %d\n", i, arr[i]); + } +} +/* +int my_arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; +int size = 10; +printIntArray(my_arr, size); +// will print "arr[0] is: 1" etc +*/ + // if referring to external variables outside function, must use extern keyword. int i = 0; void testFunc() { diff --git a/chapel.html.markdown b/chapel.html.markdown index 7252a3e4..866e92d2 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -629,7 +629,7 @@ for (i, j) in zip( toThisArray.domain, -100..#5 ){ } writeln( toThisArray ); -// This is all very important in undestanding why the statement +// This is all very important in understanding why the statement // var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j; // exhibits a runtime error. // Even though the domain of the array and the loop-expression are @@ -914,7 +914,7 @@ proc main(){ [ val in myBigArray ] val = 1 / val; // Parallel operation // Atomic variables, common to many languages, are ones whose operations - // occur uninterupted. Multiple threads can both modify atomic variables + // occur uninterrupted. Multiple threads can both modify atomic variables // and can know that their values are safe. // Chapel atomic variables can be of type bool, int, uint, and real. var uranium: atomic int; diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown index e2f0737d..d49ad254 100644 --- a/coldfusion.html.markdown +++ b/coldfusion.html.markdown @@ -1,15 +1,19 @@ --- -language: ColdFusion +language: coldfusion +filename: learncoldfusion.cfm contributors: - ["Wayne Boka", "http://wboka.github.io"] -filename: LearnColdFusion.cfm + - ["Kevin Morris", "https://twitter.com/kevinmorris"] --- ColdFusion is a scripting language for web development. [Read more here.](http://www.adobe.com/products/coldfusion-family.html) -```ColdFusion +### CFML +_**C**old**F**usion **M**arkup **L**anguage_ +ColdFusion started as a tag-based language. Almost all functionality is available using tags. +```html <em>HTML tags have been provided for output readability</em> <!--- Comments start with "<!---" and end with "--->" ---> @@ -314,8 +318,13 @@ ColdFusion is a scripting language for web development. <cfoutput><p>#getWorld()#</p></cfoutput> ``` +### CFScript +_**C**old**F**usion **S**cript_ +In recent years, the ColdFusion language has added script syntax to mirror tag functionality. When using an up-to-date CF server, almost all functionality is available using scrypt syntax. + ## Further Reading The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. 1. [Coldfusion Reference From Adobe](https://helpx.adobe.com/coldfusion/cfml-reference/topics.html) +2. [Open Source Documentation](http://cfdocs.org/) diff --git a/csharp.html.markdown b/csharp.html.markdown index 31c0417e..dfdd98de 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -913,6 +913,35 @@ on a new line! ""Wow!"", the masses cried"; public DbSet<Bicycle> Bikes { get; set; } } + + // Classes can be split across multiple .cs files + // A1.cs + public partial class A + { + public static void A1() + { + Console.WriteLine("Method A1 in class A"); + } + } + + // A2.cs + public partial class A + { + public static void A2() + { + Console.WriteLine("Method A2 in class A"); + } + } + + // Program using the partial class "A" + public class Program + { + static void Main() + { + A.A1(); + A.A2(); + } + } } // End Namespace ``` diff --git a/css.html.markdown b/css.html.markdown index d8f30ca3..8ee4f4b9 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -6,20 +6,21 @@ contributors: - ["Geoffrey Liu", "https://github.com/g-liu"] - ["Connor Shea", "https://github.com/connorshea"] - ["Deepanshu Utkarsh", "https://github.com/duci9y"] + - ["Tyler Mumford", "https://tylermumford.com"] filename: learncss.css --- -In the early days of the web there were no visual elements, just pure text. But with further development of web browsers, fully visual web pages also became common. +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 helps maintain separation between the content (HTML) and the look-and-feel of a web page. +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 lets you target different elements on an HTML page and assign different visual properties to them. +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 for CSS 2, though CSS 3 is fast becoming popular. - -**NOTE:** Because CSS produces visual results, in order to learn it, you need 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 + ```css /* comments appear inside slash-asterisk, just like this line! there are no "one-line comments"; this is the only comment style */ @@ -28,7 +29,7 @@ The main focus of this article is on the syntax and some general tips. ## SELECTORS #################### */ -/* the selector is used to target an element on a page. +/* the selector is used to target an element on a page. */ selector { property: value; /* more properties...*/ } /* @@ -69,7 +70,7 @@ div { } [otherAttr|='en'] { font-size:smaller; } -/* You can concatenate different selectors to create a narrower selector. Don't +/* You can combine different selectors to create a more focused selector. Don't put spaces between them. */ div.some-class[attr$='ue'] { } @@ -92,7 +93,7 @@ div.some-parent.class-name { } .i-am-any-element-before ~ .this-element { } /* There are some selectors called pseudo classes that can be used to select an - element when it is in a particular state */ + element only when it is in a particular state */ /* for example, when the cursor hovers over an element */ selector:hover { } @@ -103,7 +104,7 @@ selector:visited { } /* or hasn't been visited */ selected:link { } -/* or an element in focus */ +/* or an element is in focus */ selected:focus { } /* any element that is the first child of its parent */ @@ -156,10 +157,10 @@ selector { color: tomato; /* a named color */ color: rgb(255, 255, 255); /* as rgb values */ color: rgb(10%, 20%, 50%); /* as rgb percentages */ - color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 < a < 1 */ + color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 <= a <= 1 */ 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 hsla percentages with alpha */ + 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 */ @@ -194,7 +195,7 @@ 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. Generally, a rule in a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one. +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. This process is called cascading, hence the name Cascading Style Sheets. @@ -238,10 +239,10 @@ Most of the features in CSS 2 (and many in CSS 3) are available across all brows ## Resources -* To run a quick compatibility check, [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/) +* [CanIUse](http://caniuse.com) (Detailed compatibility info) +* [Dabblet](http://dabblet.com/) (CSS playground) +* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) (Tutorials and reference) +* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) (Reference) ## Further Reading diff --git a/d.html.markdown b/d.html.markdown index 80c1dc65..6f3710ab 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -199,8 +199,8 @@ our getter and setter methods, and keep the clean syntax of accessing members directly! Other object-oriented goodies at our disposal -include `interface`s, `abstract class`es, -and `override`ing methods. D does inheritance just like Java: +include interfaces, abstract classes, +and overriding methods. D does inheritance just like Java: Extend one class, implement as many interfaces as you please. We've seen D's OOP facilities, but let's switch gears. D offers @@ -247,7 +247,7 @@ void main() { // and take advantage of as many cores as we have available. auto arr = new double[1_000_000]; - // Use an index, and an array element by referece, + // Use an index, and an array element by reference, // and just call parallel on the array! foreach(i, ref elem; parallel(arr)) { ref = sqrt(i + 1.0); diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown index fb9cd9d4..541d28bb 100644 --- a/de-de/bash-de.html.markdown +++ b/de-de/bash-de.html.markdown @@ -28,18 +28,50 @@ echo Hello, world! echo 'Dies ist die erste Zeile'; echo 'Dies die zweite Zeile' # Variablen deklariert man so: -VARIABLE="irgendein String" +Variable="irgendein String" # Aber nicht so: -VARIABLE = "irgendein String" -# Bash wird VARIABLE für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben, +Variable = "irgendein String" +# Bash wird 'Variable' für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben, # weil es den Befehl nicht findet. +# Und so auch nicht: +Variable= 'Some string' +# Bash wird 'Variable' wieder für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben, +# Hier wird der Teil 'Variable=' als nur für diesen einen Befehl gültige Zuweisung an die Variable gesehen. + # Eine Variable wird so benutzt: -echo $VARIABLE -echo "$VARIABLE" -# Wenn du eine Variable selbst benutzt – ihr Werte zuweist, sie exportierst oder irgendetwas anders –, +echo $Variable +echo "$Variable" +echo ${Variable} +# aber +echo '$Variable' +# Wenn du eine Variable selbst benutzt – ihr Werte zuweist, sie exportierst oder irgendetwas anderes –, # dann über ihren Namen ohne $. Aber wenn du ihren zugewiesenen Wert willst, dann musst du $ voranstellen. +# Beachte: ' (Hochkomma) verhindert das Interpretieren der Variablen + +# Ersetzen von Zeichenketten in Variablen +echo ${Variable/irgendein/neuer} +# Ersetzt das erste Vorkommen von "irgendein" durch "neuer" + +# Teil einer Zeichenkette +Laenge=7 +echo ${Variable:0:Laenge} +# Gibt nur die ersten 7 Zeichen zurück + +# Standardwert verwenden +echo ${Foo:-"ErsatzWennLeerOderUngesetzt"} +# Das funktioniert mit nicht gesetzten Variablen (Foo=) und leeren Zeichenketten (Foo="") +# Die Zahl 0 (Foo=0) liefert 0. +# Beachte: der wert der Variablen wird nicht geändert + +# Eingebaute Variable (BUILTINS): +# Einige nützliche Beispiele +echo "Rückgabewert des letzten Befehls: $?" +echo "Die PID des skripts: $$" +echo "Anzahl der Argumente beim Aufruf: $#" +echo "Alle Argumente beim Aufruf: $@" +echo "Die Argumente in einzelnen Variablen: $1 $2..." # Einen Wert aus der Eingabe lesen: echo "Wie heisst du?" @@ -47,14 +79,30 @@ read NAME # Wir mussten nicht mal eine neue Variable deklarieren echo Hello, $NAME! # Wir haben die übliche if-Struktur: -if true +# 'man test' liefert weitere Informationen zu Bedingungen +if [ "$NAME" -ne $USER ] then - echo "Wie erwartet" + echo "Dein Name ist nicht dein Login-Name" else - echo "Und dies nicht" + echo "Dein Name ist dein Login-Name" +fi + +# Es gibt auch bedingte Ausführung +echo "immer ausgeführt" || echo "Nur ausgeführt wenn der erste Befehl fehlschlägt" +echo "immer ausgeführt" && echo "Nur ausgeführt wenn der erste Befehl Erfolg hat" + +# Um && und || mit if statements zu verwenden, braucht man mehrfache Paare eckiger Klammern: +if [ $NAME == "Steve" ] && [ $Alter -eq 15 ] +then + echo "Wird ausgeführt wenn $NAME gleich 'Steve' UND $Alter gleich 15." +fi + +if [ $Name == "Daniya" ] || [ $Name == "Zach" ] +then + echo "Wird ausgeführt wenn $NAME gleich 'Daniya' ODER $NAME gleich 'Zach'." fi -# Ausdrücke werden im folgenden Format festgehalten: +# Ausdrücke haben folgendes Format: echo $(( 10 + 5 )) # Anders als andere Programmiersprachen ist Bash eine Shell – es arbeitet also im Kontext von Verzeichnissen. @@ -69,13 +117,60 @@ ls -l # Liste alle Dateien und Unterverzeichnisse auf einer eigenen Zeile auf # txt-Dateien im aktuellen Verzeichnis auflisten: ls -l | grep "\.txt" -# Befehle können innerhalb anderer Befehle mit $( ) erstetzt werden: +# Ein- und Ausgabe können umgeleitet werden (stdin, stdout, and stderr). +# Von stdin lesen bis "EOF" allein in einer Zeile auftaucht +# und die Datei hello.py mit den Zeilen zwischen den beiden "EOF" +# überschreiben: +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 + +# Führe hello.py mit verschiedenen Umleitungen von +# stdin, stdout und stderr aus: +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 +# Die Fehlerausgabe würde die Datei "error.err" überschreiben (falls sie existiert) +# verwende ">>" um stattdessen anzuhängen: +python hello.py >> "output.out" 2>> "error.err" + +# Überschreibe output.out, hänge an error.err an und zähle die Zeilen beider Dateien: +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# Führe einen Befehl aus und gib dessen "file descriptor" (zB /dev/fd/123) aus +# siehe: man fd +echo <(echo "#helloworld") + +# Mehrere Arten, um output.out mit "#helloworld" zu überschreiben: +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# Löschen der Hilfsdateien von oberhalb, mit Anzeige der Dateinamen +# (mit '-i' für "interactive" erfolgt für jede Date eine Rückfrage) +rm -v output.out error.err output-and-error.log + +# Die Ausgabe von Befehlen kann mit Hilfe von $( ) in anderen Befehlen verwendet weden: # Der folgende Befehl zeigt die Anzahl aller Dateien und Unterverzeichnisse # im aktuellen Verzeichnis an. echo "Dieser Ordner beinhaltet $(ls | wc -l) Dateien und Verzeichnisse." +# Dasselbe kann man mit "backticks" `` erreichen, aber diese können +# nicht verschachtelt werden. $() ist die empfohlene Methode. +echo "Dieser Ordner beinhaltet `ls | wc -l` Dateien und Verzeichnisse." + # Bash nutzt einen case-Ausdruck, der sich ähnlich wie switch in Java oder C++ verhält. -case "$VARIABLE" +case "$Variable" in # Liste der Fälle, die unterschieden werden sollen 0) echo "Hier ist eine Null." @@ -83,10 +178,106 @@ in *) echo "Das ist nicht Null." esac -# loops iterieren über die angegebene Zahl von Argumenten: -# Der Inhalt von $VARIABLE wird dreimal ausgedruckt. -for $VARIABLE in x y z +# 'for' Schleifen iterieren über die angegebene Zahl von Argumenten: +# Der Inhalt von $Variable wird dreimal ausgedruckt. +for $Variable in {1..3} do - echo "$VARIABLE" + echo "$Variable" done + +# Oder verwende die "traditionelle 'for'-Schleife": +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Schleifen können auch mit Dateien arbeiten: +# 'cat' zeigt zuerst file1 an und dann file2 +for Variable in file1 file2 +do + cat "$Variable" +done + +# .. oder mit der Ausgabe eines Befehls: +# Ausgabe des Inhalts jeder Datei, die von 'ls' aufgezählt wird +for Output in $(ls) +do + cat "$Output" +done + +# while Schleife: +while [ true ] +do + echo "Schleifenkörper..." + break +done + +# Funktionen definieren +# Definition: +function foo () +{ + echo "Argumente funktionieren wie bei skripts: $@" + echo Und: $1 $2..." + echo "Dies ist eine Funktion" + return 0 +} + +# oder einfacher +bar () +{ + echo "Auch so kann man Funktionen deklarieren!" + return 0 +} + +# Aufruf der Funktion: +foo "My name is" $Name + +# Was du noch lernen könntest: +# Ausgabe der letzten 10 Zeilen von file.txt +tail -n 10 file.txt +# Ausgabe der ersten 10 Zeilen von file.txt +head -n 10 file.txt +# sortierte Ausgabe von file.txt +sort file.txt +# Mehrfachzeilen in sortierten Dateien unterdrücken +# oder (mit -d) nur diese ausgeben +uniq -d file.txt +# Ausgabe nur der ersten Spalte (vor dem ersten ',') +cut -d ',' -f 1 file.txt +# ersetze in file.txt jedes vorkommende 'gut' durch 'super' (versteht regex) +sed -i 's/gut/super/g' file.txt +# Ausgabe nach stdout aller Zeilen von file.txt, die auf eine regex passen +# Im Beispiel: Zeilen, die mit "foo" beginnen und mit "bar" enden +grep "^foo.*bar$" file.txt +# Mit der Option "-c" wird stattdessen die Anzahl der gefundenen Zeilen ausgegeben +grep -c "^foo.*bar$" file.txt +# verwende 'fgrep' oder 'grep -F' wenn du buchstäblich nach den Zeichen +# suchen willst, ohne sie als regex zu interpretieren +fgrep "^foo.*bar$" file.txt + +# Dokumentation über die in bash eingebauten Befehle +# bekommst du mit dem eingebauten Befehl 'help' +help +help help +help for +help return +help source +help . + +# Das bash-Handbuch liest du mit 'man' +apropos bash +man 1 bash +man bash + +# Dann gibt es noch das 'info' System (drücke ? um Hilfe angezeigt zu bekommen) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# info Dokumentation über bash: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash ``` diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown index 43939129..dea329d5 100644 --- a/de-de/git-de.html.markdown +++ b/de-de/git-de.html.markdown @@ -18,12 +18,12 @@ Anmerkung des Übersetzers: Einige englische Begriffe wie *Repository*, *Commit* ### Was ist Versionsverwaltung? -Eine Versionskontrolle erfasst die Änderungen einer Datei oder eines Verzeichnisses im Verlauf der Zeit. +Eine Versionsverwaltung erfasst die Änderungen einer Datei oder eines Verzeichnisses im Verlauf der Zeit. ### Zentrale im Vergleich mit verteilter Versionverwaltung -* Zentrale Versionskontrolle konzentriert sich auf das Synchronisieren, Verfolgen und Sichern von Dateien. -* Verteilte Versionskontrolle konzentriert sich auf das Teilen der Änderungen. Jede Änderung hat eine eindeutige ID. +* Zentrale Versionsverwaltung konzentriert sich auf das Synchronisieren, Verfolgen und Sichern von Dateien. +* Verteilte Versionsverwaltung konzentriert sich auf das Teilen der Änderungen. Jede Änderung hat eine eindeutige ID. * Verteilte Systeme haben keine vorbestimmte Struktur. Ein SVN-ähnliches, zentrales System wäre mit Git ebenso umsetzbar. [Weiterführende Informationen](http://git-scm.com/book/en/Getting-Started-About-Version-Control) @@ -61,7 +61,7 @@ Der Index ist die die Staging-Area von Git. Es ist im Grunde eine Ebene, die Arb ### Commit -Ein Commit ist ein Schnappschuss von Uderungen in deinem Arbeitsverzeichnis. Wenn du zum Beispiel 5 Dateien hinzugefügt und 2 andere entfernt hast, werden diese Änderungen im Commit (Schnappschuss) enthalten sein. Dieser Commit kann dann in andere Repositorys gepusht werden. Oder nicht! +Ein Commit ist ein Schnappschuss von Änderungen in deinem Arbeitsverzeichnis. Wenn du zum Beispiel 5 Dateien hinzugefügt und 2 andere entfernt hast, werden diese Änderungen im Commit (Schnappschuss) enthalten sein. Dieser Commit kann dann in andere Repositories gepusht werden. Oder nicht! ### Branch @@ -69,7 +69,9 @@ Ein Branch, ein Ast oder Zweig, ist im Kern ein Pointer auf den letzten Commit, ### HEAD und head (Teil des .git-Verzeichnisses) -HEAD ist ein Pointer auf den aktuellen Branch. Ein Repository hat nur einen *aktiven* HEAD. Ein head ist ein Pointer, der auf ein beliebige Zahl von heads zeigt. +HEAD ist ein Pointer auf den aktuellen Branch. Ein Repository hat nur einen *aktiven* HEAD. + +Ein *head* ist ein Pointer, der auf einen beliebigen Commit zeigt. Ein Repository kann eine beliebige Zahl von *heads* enthalten. ### Konzeptionelle Hintergründe @@ -127,7 +129,7 @@ Zeigt die Unterschiede zwischen Index (im Grunde dein Arbeitsverzeichnis/-reposi ```bash -# Zeigt den Branch, nicht-verfolgte Dateien, Uderungen und andere Unterschiede an +# Zeigt den Branch, nicht-verfolgte Dateien, Änderungen und andere Unterschiede an $ git status # Anderes Wissenswertes über git status anzeigen @@ -151,7 +153,7 @@ $ git add ./*.java ### branch -Verwalte alle Branches. Du kannst sie mit diesem Befehl ansehen, bearbeiten, neue erschaffen oder löschen. +Verwalte alle Branches. Du kannst sie mit diesem Befehl ansehen, bearbeiten, neue erzeugen oder löschen. ```bash # Liste alle bestehenden Branches und Remotes auf @@ -186,7 +188,7 @@ $ git checkout -b newBranch ### clone -Ein bestehendes Repository in ein neues Verzeichnis klonen oder kopieren. Es fügt außerdem für hedes geklonte Repo remote-tracking Branches hinzu. Du kannst auf diese Remote-Branches pushen. +Ein bestehendes Repository in ein neues Verzeichnis klonen oder kopieren. Es fügt außerdem für jedes geklonte Repository remote-tracking Branches hinzu. Du kannst auf diese Remote-Branches pushen. ```bash # Klone learnxinyminutes-docs @@ -288,16 +290,16 @@ $ git mv -f myFile existingFile ### pull -Führe einen Pull, zieht alle Daten, eines Repositorys und f?? einen Merge mit einem anderen Branch durch. +Führe einen Pull (zieht alle Daten eines Repositories) aus und führt einen Merge mit einem anderen Branch durch. ```bash -# Update deines lokalen Repos, indem ein Merge der neuen Uderungen -# von den remote-liegenden "origin"- und "master"-Branches durchgef?? wird. +# Update deines lokalen Repos, indem ein Merge der neuen Änderungen +# von den remote-liegenden "origin"- und "master"-Branches durchgeführt wird. # git pull <remote> <branch> # git pull => impliziter Verweis auf origin und master $ git pull origin master -# F?? einen Merge von Uderungen eines remote-Branch und ein Rebase +# Führt einen Merge von Änderungen eines remote-Branch und ein Rebase # des Branch-Commits im lokalen Repo durch. Wie: pull <remote> <branch>, git rebase <branch>" $ git pull origin master --rebase ``` @@ -337,8 +339,8 @@ $ git reset # Setze die Staging-Area zurück, um dem letzten Commit zu entsprechen und überschreibe das Arbeitsverzeichnis $ git reset --hard -# Bewegt die Spitze des Branches zu dem angegebenen Commit (das Verzeichnis bleibt unber??) -# Alle Uderungen bleiben im Verzeichnis erhalten +# Bewegt die Spitze des Branches zu dem angegebenen Commit (das Verzeichnis bleibt unberührt) +# Alle Änderungen bleiben im Verzeichnis erhalten $ git reset 31f2bb1 # Bewegt die Spitze des Branches zurück zu dem angegebenen Commit diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 765372e0..d3a192fe 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -3,6 +3,7 @@ language: Go filename: learngo-de.go contributors: - ["Joseph Adams", "https://github.com/jcla1"] + - ["Dennis Keller", "https://github.com/denniskeller"] lang: de-de --- Go wurde entwickelt, um Probleme zu lösen. Sie ist zwar nicht der neueste Trend in @@ -24,7 +25,7 @@ aktive Community. zeiliger Kommentar */ // Eine jede Quelldatei beginnt mit einer Paket-Klausel. -// "main" ist ein besonderer Pkaetname, da er ein ausführbares Programm +// "main" ist ein besonderer Paketname, da er ein ausführbares Programm // einleitet, im Gegensatz zu jedem anderen Namen, der eine Bibliothek // deklariert. package main @@ -37,7 +38,7 @@ import ( "strconv" // Zeichenkettenmanipulation ) -// Es folgt die Definition einer Funktions, in diesem Fall von "main". Auch hier +// Es folgt die Definition einer Funktion, in diesem Fall von "main". Auch hier // ist der Name wieder besonders. "main" markiert den Eintrittspunkt des // Programms. Vergessen Sie nicht die geschweiften Klammern! func main() { @@ -55,7 +56,7 @@ func beyondHello() { var x int // Deklaration einer Variable, muss vor Gebrauch geschehen. x = 3 // Zuweisung eines Werts. // Kurze Deklaration: Benutzen Sie ":=", um die Typisierung automatisch zu - // folgern, die Variable zu deklarieren und ihr einen Wert zu zuweisen. + // folgern, die Variable zu deklarieren und ihr einen Wert zuzuweisen. y := 4 // Eine Funktion mit mehreren Rückgabewerten. @@ -146,7 +147,7 @@ func learnFlowControl() { if false { // nicht hier } else { - // sonder hier! spielt die Musik + // sondern hier! spielt die Musik } // Benutzen Sie ein "switch" Statement anstatt eine Anreihung von if-s @@ -165,7 +166,7 @@ func learnFlowControl() { // Ab hier gilt wieder: x == 1 // For ist die einzige Schleifenform in Go, sie hat aber mehrere Formen: - for { // Endloschleife + for { // Endlosschleife break // nur ein Spaß continue // wird nie ausgeführt } @@ -262,10 +263,10 @@ func learnConcurrency() { // Auslesen und dann Ausgeben der drei berechneten Werte. // Man kann nicht im voraus feststellen in welcher Reihenfolge die Werte // ankommen. - fmt.Println(<-c, <-c, <-c) // mit dem Kannal rechts ist <- der Empfangs-Operator + fmt.Println(<-c, <-c, <-c) // mit dem Kanal rechts ist <- der Empfangs-Operator - cs := make(chan string) // ein weiterer Kannal, diesmal für strings - cc := make(chan chan string) // ein Kannal für string Kannäle + cs := make(chan string) // ein weiterer Kanal, diesmal für strings + cc := make(chan chan string) // ein Kanal für string Kanäle // Start einer neuen Goroutine, nur um einen Wert zu senden go func() { c <- 84 }() @@ -282,7 +283,7 @@ func learnConcurrency() { fmt.Println("wird nicht passieren.") } // Hier wird eine der beiden Goroutines fertig sein, die andere nicht. - // Sie wird warten bis der Wert den sie sendet von dem Kannal gelesen wird. + // Sie wird warten bis der Wert den sie sendet von dem Kanal gelesen wird. learnWebProgramming() // Go kann es und Sie hoffentlich auch bald. } @@ -300,13 +301,13 @@ func learnWebProgramming() { // Methode implementieren: ServeHTTP func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Senden von Daten mit einer Methode des http.ResponseWriter - w.Write([]byte("Sie habe Go in Y Minuten gelernt!")) + w.Write([]byte("Sie haben Go in Y Minuten gelernt!")) } ``` ## Weitere Resourcen Alles zu Go finden Sie auf der [offiziellen Go Webseite](http://golang.org/). -Dort können sie der Tutorial folgen, interaktiv Quelltext ausprobieren und viel +Dort können sie dem Tutorial folgen, interaktiv Quelltext ausprobieren und viel Dokumentation lesen. Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr diff --git a/de-de/haskell-de.html.markdown b/de-de/haskell-de.html.markdown index 2c548961..d1a0008e 100644 --- a/de-de/haskell-de.html.markdown +++ b/de-de/haskell-de.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Adit Bhargava", "http://adit.io"] translators: - ["Henrik Jürges", "https://github.com/santifa"] + - ["Nikolai Weh", "http://weh.hamburg"] filename: haskell-de.hs --- @@ -58,12 +59,13 @@ not False -- True -- Strings und Zeichen "Das ist ein String." 'a' -- Zeichen -'Einfache Anfuehrungszeichen gehen nicht.' -- error! +'Einfache Anführungszeichen gehen nicht.' -- error! -- Strings können konkateniert werden. "Hello " ++ "world!" -- "Hello world!" -- Ein String ist eine Liste von Zeichen. +['H', 'a', 'l', 'l', 'o', '!'] -- "Hallo!" "Das ist eine String" !! 0 -- 'D' @@ -76,11 +78,23 @@ not False -- True [1, 2, 3, 4, 5] [1..5] --- Haskell unterstuetzt unendliche Listen! -[1..] -- Die Liste aller natuerlichen Zahlen +-- Die zweite Variante nennt sich die "range"-Syntax. +-- Ranges sind recht flexibel: +['A'..'F'] -- "ABCDEF" + +-- Es ist möglich eine Schrittweite anzugeben: +[0,2..10] -- [0,2,4,6,8,10] +[5..1] -- [], da Haskell standardmässig inkrementiert. +[5,4..1] -- [5,4,3,2,1] + +-- Der "!!"-Operator extrahiert das Element an einem bestimmten Index: +[1..10] !! 3 -- 4 + +-- Haskell unterstützt unendliche Listen! +[1..] -- Die Liste aller natürlichen Zahlen -- Unendliche Listen funktionieren in Haskell, da es "lazy evaluation" --- unterstuetzt. Haskell evaluiert erst etwas, wenn es benötigt wird. +-- unterstützt. Haskell evaluiert erst etwas, wenn es benötigt wird. -- Somit kannst du nach dem 1000. Element fragen und Haskell gibt es dir: [1..] !! 999 -- 1000 @@ -92,12 +106,9 @@ not False -- True -- Zwei Listen konkatenieren [1..5] ++ [6..10] --- Ein Element als Head hinzufuegen +-- Ein Element als Head hinzufügen 0:[1..5] -- [0, 1, 2, 3, 4, 5] --- Gibt den 5. Index zurueck -[0..] !! 5 -- 5 - -- Weitere Listenoperationen head [1..5] -- 1 tail [1..5] -- [2, 3, 4, 5] @@ -114,7 +125,8 @@ last [1..5] -- 5 -- Ein Tupel: ("haskell", 1) --- Auf Elemente eines Tupels zugreifen: +-- Ein Paar (Pair) ist ein Tupel mit 2 Elementen, auf die man wie folgt +-- zugreifen kann: fst ("haskell", 1) -- "haskell" snd ("haskell", 1) -- 1 @@ -140,9 +152,9 @@ add 1 2 -- 3 (//) a b = a `div` b 35 // 4 -- 8 --- Guards sind eine einfache Möglichkeit fuer Fallunterscheidungen. +-- Guards sind eine einfache Möglichkeit für Fallunterscheidungen. fib x - | x < 2 = x + | x < 2 = 1 | otherwise = fib (x - 1) + fib (x - 2) -- Pattern Matching funktioniert ähnlich. @@ -174,7 +186,7 @@ foldl1 (\acc x -> acc + x) [1..5] -- 15 -- 4. Mehr Funktionen ---------------------------------------------------- --- currying: Wenn man nicht alle Argumente an eine Funktion uebergibt, +-- currying: Wenn man nicht alle Argumente an eine Funktion übergibt, -- so wird sie eine neue Funktion gebildet ("curried"). -- Es findet eine partielle Applikation statt und die neue Funktion -- nimmt die fehlenden Argumente auf. @@ -190,23 +202,28 @@ foo 5 -- 15 -- Funktionskomposition -- Die (.) Funktion verkettet Funktionen. -- Zum Beispiel, die Funktion Foo nimmt ein Argument addiert 10 dazu und --- multipliziert dieses Ergebnis mit 5. -foo = (*5) . (+10) +-- multipliziert dieses Ergebnis mit 4. +foo = (*4) . (+10) + +-- (5 + 10) * 4 = 60 +foo 5 -- 60 --- (5 + 10) * 5 = 75 -foo 5 -- 75 +-- Haskell hat einen Operator `$`, welcher Funktionsapplikation durchführt. +-- Im Gegenzug zu der Standard-Funktionsapplikation, welche linksassoziativ ist +-- und die höchstmögliche Priorität von "10" hat, ist der `$`-Operator +-- rechtsassoziativ und hat die Priorität 0. Dieses hat (idr.) den Effekt, +-- dass der `komplette` Ausdruck auf der rechten Seite als Parameter für die +-- Funktion auf der linken Seite verwendet wird. +-- Mit `.` und `$` kann man sich so viele Klammern ersparen. --- Haskell hat eine Funktion `$`. Diese ändert den Vorrang, --- so dass alles links von ihr zuerst berechnet wird und --- und dann an die rechte Seite weitergegeben wird. --- Mit `.` und `$` kann man sich viele Klammern ersparen. +(even (fib 7)) -- false --- Vorher -(even (fib 7)) -- true +-- Äquivalent: +even $ fib 7 -- false --- Danach -even . fib $ 7 -- true +-- Funktionskomposition: +even . fib $ 7 -- false ---------------------------------------------------- -- 5. Typensystem @@ -221,31 +238,31 @@ even . fib $ 7 -- true True :: Bool -- Funktionen haben genauso Typen. --- `not` ist Funktion die ein Bool annimmt und ein Bool zurueckgibt: +-- `not` ist Funktion die ein Bool annimmt und ein Bool zurückgibt: -- not :: Bool -> Bool -- Eine Funktion die zwei Integer Argumente annimmt: -- add :: Integer -> Integer -> Integer -- Es ist guter Stil zu jeder Funktionsdefinition eine --- Typdefinition darueber zu schreiben: +-- Typdefinition darüber zu schreiben: double :: Integer -> Integer double x = x * 2 ---------------------------------------------------- --- 6. If-Anweisung und Kontrollstrukturen +-- 6. If-Ausdrücke und Kontrollstrukturen ---------------------------------------------------- --- If-Anweisung: +-- If-Ausdruck: haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" --- If-Anweisungen können auch ueber mehrere Zeilen verteilt sein. --- Das Einruecken ist dabei äußerst wichtig. +-- If-Ausdrücke können auch über mehrere Zeilen verteilt sein. +-- Die Einrückung ist dabei wichtig. haskell = if 1 == 1 then "awesome" else "awful" --- Case-Anweisung: Zum Beispiel "commandline" Argumente parsen. +-- Case-Ausdruck: Am Beispiel vom Parsen von "commandline"-Argumenten. case args of "help" -> printHelp "start" -> startProgram @@ -276,7 +293,7 @@ foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 -- die Abarbeitung sieht so aus: -(2 * 3 + (2 * 2 + (2 * 1 + 4))) +(2 * 1 + (2 * 2 + (2 * 3 + 4))) ---------------------------------------------------- -- 7. Datentypen @@ -300,7 +317,7 @@ data Maybe a = Nothing | Just a -- Diese sind alle vom Typ Maybe: Just "hello" -- vom Typ `Maybe String` Just 1 -- vom Typ `Maybe Int` -Nothing -- vom Typ `Maybe a` fuer jedes `a` +Nothing -- vom Typ `Maybe a` für jedes `a` ---------------------------------------------------- -- 8. Haskell IO @@ -309,8 +326,8 @@ Nothing -- vom Typ `Maybe a` fuer jedes `a` -- IO kann nicht völlig erklärt werden ohne Monaden zu erklären, -- aber man kann die grundlegenden Dinge erklären. --- Wenn eine Haskell Programm ausgefuehrt wird, so wird `main` aufgerufen. --- Diese muss etwas vom Typ `IO ()` zurueckgeben. Zum Beispiel: +-- Wenn eine Haskell Programm ausgeführt wird, so wird `main` aufgerufen. +-- Diese muss etwas vom Typ `IO ()` zurückgeben. Zum Beispiel: main :: IO () main = putStrLn $ "Hello, sky! " ++ (say Blue) @@ -338,10 +355,10 @@ sayHello = do -- an die Variable "name" gebunden putStrLn $ "Hello, " ++ name --- Uebung: Schreibe deine eigene Version von `interact`, +-- Übung: Schreibe deine eigene Version von `interact`, -- die nur eine Zeile einliest. --- `sayHello` wird niemals ausgefuehrt, nur `main` wird ausgefuehrt. +-- `sayHello` wird niemals ausgeführt, nur `main` wird ausgeführt. -- Um `sayHello` laufen zulassen kommentiere die Definition von `main` -- aus und ersetze sie mit: -- main = sayHello @@ -359,7 +376,7 @@ action = do input1 <- getLine input2 <- getLine -- Der Typ von `do` ergibt sich aus der letzten Zeile. - -- `return` ist eine Funktion und keine Schluesselwort + -- `return` ist eine Funktion und keine Schlüsselwort return (input1 ++ "\n" ++ input2) -- return :: String -> IO String -- Nun können wir `action` wie `getLine` benutzen: @@ -370,7 +387,7 @@ main'' = do putStrLn result putStrLn "This was all, folks!" --- Der Typ `IO` ist ein Beispiel fuer eine Monade. +-- Der Typ `IO` ist ein Beispiel für eine Monade. -- Haskell benutzt Monaden Seiteneffekte zu kapseln und somit -- eine rein funktional Sprache zu sein. -- Jede Funktion die mit der Außenwelt interagiert (z.B. IO) @@ -387,7 +404,7 @@ main'' = do -- Starte die REPL mit dem Befehl `ghci` -- Nun kann man Haskell Code eingeben. --- Alle neuen Werte muessen mit `let` gebunden werden: +-- Alle neuen Werte müssen mit `let` gebunden werden: let foo = 5 @@ -396,7 +413,7 @@ let foo = 5 >:t foo foo :: Integer --- Auch jede `IO ()` Funktion kann ausgefuehrt werden. +-- Auch jede `IO ()` Funktion kann ausgeführt werden. > sayHello What is your name? @@ -420,6 +437,6 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater Haskell ist sehr einfach zu installieren. Hohl es dir von [hier](http://www.haskell.org/platform/). -Eine sehr viele langsamere Einfuehrung findest du unter: +Eine sehr viele langsamere Einführung findest du unter: [Learn you a Haskell](http://learnyouahaskell.com/) oder [Real World Haskell](http://book.realworldhaskell.org/). diff --git a/de-de/scala-de.html.markdown b/de-de/scala-de.html.markdown index 7fd299b4..456403a2 100644 --- a/de-de/scala-de.html.markdown +++ b/de-de/scala-de.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Dominic Bou-Samra", "http://dbousamra.github.com"] - ["Geoff Liu", "http://geoffliu.me"] - ["Ha-Duong Nguyen", "http://reference-error.org"] + - ["Dennis Keller", "github.com/denniskeller"] translators: - ["Christian Albrecht", "https://github.com/coastalchief"] filename: learnscala-de.scala @@ -16,167 +17,172 @@ für die Java Virtual Machine (JVM), um allgemeine Programmieraufgaben zu erledigen. Scala hat einen akademischen Hintergrund und wurde an der EPFL (Lausanne / Schweiz) unter der Leitung von Martin Odersky entwickelt. - -# 0. Umgebung einrichten +```scala +/* Scala Umgebung einrichten: 1. Scala binaries herunterladen- http://www.scala-lang.org/downloads 2. Unzip/untar in ein Verzeichnis 3. das bin Unterverzeichnis der `PATH` Umgebungsvariable hinzufügen 4. Mit dem Kommando `scala` wird die REPL gestartet und zeigt als Prompt: -``` + scala> -``` Die REPL (Read-Eval-Print Loop) ist der interaktive Scala Interpreter. Hier kann man jeden Scala Ausdruck verwenden und das Ergebnis wird direkt ausgegeben. Als nächstes beschäftigen wir uns mit ein paar Scala Basics. +*/ -# 1. Basics -Einzeilige Kommentare beginnen mit zwei vorwärts Slash +///////////////////////////////////////////////// +// 1. Basics +///////////////////////////////////////////////// + +// Einzeilige Kommentare beginnen mit zwei Slashes /* - Mehrzeilige Kommentare, werden starten - mit Slash-Stern und enden mit Stern-Slash + Mehrzeilige Kommentare, starten + mit einem Slash-Stern und enden mit einem Stern-Slash */ // Einen Wert, und eine zusätzliche neue Zeile ausgeben -``` + println("Hello world!") println(10) -``` + // Einen Wert, ohne eine zusätzliche neue Zeile ausgeben -``` + print("Hello world") -``` -// Variablen werden entweder mit var oder val deklariert. -// Deklarationen mit val sind immutable, also unveränderlich -// Deklarationen mit var sind mutable, also veränderlich -// Immutability ist gut. -``` +/* + Variablen werden entweder mit var oder val deklariert. + Deklarationen mit val sind immutable, also unveränderlich + Deklarationen mit var sind mutable, also veränderlich + Immutability ist gut. +*/ val x = 10 // x ist 10 x = 20 // error: reassignment to val var y = 10 y = 20 // y ist jetzt 20 -``` -Scala ist eine statisch getypte Sprache, auch wenn in dem o.g. Beispiel +/* +Scala ist eine statisch getypte Sprache, auch wenn wir in dem o.g. Beispiel keine Typen an x und y geschrieben haben. -In Scala ist etwas eingebaut, was sich Type Inference nennt. D.h. das der -Scala Compiler in den meisten Fällen erraten kann, von welchen Typ eine ist, -so dass der Typ nicht jedes mal angegeben werden soll. +In Scala ist etwas eingebaut, was sich Type Inference nennt. Das heißt das der +Scala Compiler in den meisten Fällen erraten kann, von welchen Typ eine Variable ist, +so dass der Typ nicht jedes mal angegeben werden muss. Einen Typ gibt man bei einer Variablendeklaration wie folgt an: -``` +*/ val z: Int = 10 val a: Double = 1.0 -``` + // Bei automatischer Umwandlung von Int auf Double wird aus 10 eine 10.0 -``` + val b: Double = 10 -``` + // Boolean Werte -``` + true false -``` + // Boolean Operationen -``` + !true // false !false // true true == false // false 10 > 5 // true -``` + // Mathematische Operationen sind wie gewohnt -``` + 1 + 1 // 2 2 - 1 // 1 5 * 3 // 15 6 / 2 // 3 6 / 4 // 1 6.0 / 4 // 1.5 -``` + // Die Auswertung eines Ausdrucks in der REPL gibt den Typ // und das Ergebnis zurück. -``` + scala> 1 + 7 res29: Int = 8 -``` +/* Das bedeutet, dass das Resultat der Auswertung von 1 + 7 ein Objekt von Typ Int ist und einen Wert 0 hat. "res29" ist ein sequentiell generierter name, um das Ergebnis des Ausdrucks zu speichern. Dieser Wert kann bei Dir anders sein... - +*/ "Scala strings werden in doppelten Anführungszeichen eingeschlossen" 'a' // A Scala Char // 'Einzeln ge-quotete strings gibt es nicht!' <= This causes an error // Für Strings gibt es die üblichen Java Methoden -``` + "hello world".length "hello world".substring(2, 6) "hello world".replace("C", "3") -``` + // Zusätzlich gibt es noch extra Scala Methoden // siehe: scala.collection.immutable.StringOps -``` + "hello world".take(5) "hello world".drop(5) -``` + // String interpolation: prefix "s" -``` + val n = 45 s"We have $n apples" // => "We have 45 apples" -``` -// Ausdrücke im innern von interpolierten Strings gibt es auch -``` + +// Ausdrücke im Innern von interpolierten Strings gibt es auch + val a = Array(11, 9, 6) val n = 100 s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" -``` + // Formatierung der interpolierten Strings mit dem prefix "f" -``` + f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" -``` + // Raw Strings, ignorieren Sonderzeichen. -``` + raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r." -``` + // Manche Zeichen müssen "escaped" werden, z.B. // ein doppeltes Anführungszeichen in innern eines Strings. -``` + "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" -``` + // Dreifache Anführungszeichen erlauben es, dass ein String über mehrere Zeilen geht // und Anführungszeichen enthalten kann. -``` + val html = """<form id="daform"> <p>Press belo', Joe</p> <input type="submit"> </form>""" -``` -# 2. Funktionen + +///////////////////////////////////////////////// +// 2. Funktionen +///////////////////////////////////////////////// // Funktionen werden so definiert // @@ -184,74 +190,74 @@ val html = """<form id="daform"> // // Beachte: Es gibt kein return Schlüsselwort. In Scala ist der letzte Ausdruck // in einer Funktion der Rückgabewert. -``` + def sumOfSquares(x: Int, y: Int): Int = { val x2 = x * x val y2 = y * y x2 + y2 } -``` + // Die geschweiften Klammern können weggelassen werden, wenn // die Funktion nur aus einem einzigen Ausdruck besteht: -``` + def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y -``` + // Syntax für Funktionsaufrufe: -``` + sumOfSquares(3, 4) // => 25 -``` + // In den meisten Fällen (mit Ausnahme von rekursiven Funktionen), können // Rückgabetypen auch weggelassen werden, da dieselbe Typ Inference, wie bei // Variablen, auch bei Funktionen greift: -``` + def sq(x: Int) = x * x // Compiler errät, dass der return type Int ist -``` + // Funktionen können default parameter haben: -``` + def addWithDefault(x: Int, y: Int = 5) = x + y addWithDefault(1, 2) // => 3 addWithDefault(1) // => 6 -``` + // Anonyme Funktionen sehen so aus: -``` + (x: Int) => x * x -``` + // Im Gegensatz zu def bei normalen Funktionen, kann bei anonymen Funktionen // sogar der Eingabetyp weggelassen werden, wenn der Kontext klar ist. // Beachte den Typ "Int => Int", dies beschreibt eine Funktion, // welche Int als Parameter erwartet und Int zurückgibt. -``` + val sq: Int => Int = x => x * x -``` + // Anonyme Funktionen benutzt man ganz normal: -``` + sq(10) // => 100 -``` + // Wenn ein Parameter einer anonymen Funktion nur einmal verwendet wird, // bietet Scala einen sehr kurzen Weg diesen Parameter zu benutzen, // indem die Parameter als Unterstrich "_" in der Parameterreihenfolge // verwendet werden. Diese anonymen Funktionen werden sehr häufig // verwendet. -``` + val addOne: Int => Int = _ + 1 val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3) addOne(5) // => 6 weirdSum(2, 4) // => 16 -``` + // Es gibt einen keyword return in Scala. Allerdings ist seine Verwendung // nicht immer ratsam und kann fehlerbehaftet sein. "return" gibt nur aus // dem innersten def, welches den return Ausdruck umgibt, zurück. // "return" hat keinen Effekt in anonymen Funktionen: -``` + def foo(x: Int): Int = { val anonFunc: Int => Int = { z => if (z > 5) @@ -261,28 +267,30 @@ def foo(x: Int): Int = { } anonFunc(x) // Zeile ist der return Wert von foo } -``` -# 3. Flow Control -## Wertebereiche und Schleifen -``` +///////////////////////////////////////////////// +// 3. Flow Control +///////////////////////////////////////////////// + +// Wertebereiche und Schleifen + 1 to 5 val r = 1 to 5 r.foreach(println) r foreach println (5 to 1 by -1) foreach (println) -``` -// Scala ist syntaktisch sehr grosszügig, Semikolons am Zeilenende + +// Scala ist syntaktisch sehr großzügig, Semikolons am Zeilenende // sind optional, beim Aufruf von Methoden können die Punkte // und Klammern entfallen und Operatoren sind im Grunde austauschbare Methoden // while Schleife -``` + var i = 0 while (i < 10) { println("i " + i); i += 1 } i // i ausgeben, res3: Int = 10 -``` + // Beachte: while ist eine Schleife im klassischen Sinne - // Sie läuft sequentiell ab und verändert die loop-Variable. @@ -291,28 +299,28 @@ i // i ausgeben, res3: Int = 10 // und zu parellelisieren. // Ein do while Schleife -``` + do { println("x ist immer noch weniger wie 10") x += 1 } while (x < 10) -``` + // Endrekursionen sind ideomatisch um sich wiederholende // Dinge in Scala zu lösen. Rekursive Funtionen benötigen explizit einen // return Typ, der Compiler kann ihn nicht erraten. // Unit, in diesem Beispiel. -``` + def showNumbersInRange(a: Int, b: Int): Unit = { print(a) if (a < b) showNumbersInRange(a + 1, b) } showNumbersInRange(1, 14) -``` -## Conditionals -``` + +// Conditionals + val x = 10 if (x == 1) println("yeah") if (x == 10) println("yeah") @@ -320,186 +328,193 @@ if (x == 11) println("yeah") if (x == 11) println ("yeah") else println("nay") println(if (x == 10) "yeah" else "nope") val text = if (x == 10) "yeah" else "nope" -``` -# 4. Daten Strukturen (Array, Map, Set, Tuples) -## Array -``` +///////////////////////////////////////////////// +// 4. Daten Strukturen (Array, Map, Set, Tuples) +///////////////////////////////////////////////// + +// Array + val a = Array(1, 2, 3, 5, 8, 13) a(0) a(3) a(21) // Exception -``` -## Map - Speichert Key-Value-Paare -``` + +// Map - Speichert Key-Value-Paare + val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") m("fork") m("spoon") m("bottle") // Exception val safeM = m.withDefaultValue("no lo se") safeM("bottle") -``` -## Set - Speichert Unikate, unsortiert (sortiert -> SortedSet) -``` + +// Set - Speichert Unikate, unsortiert (sortiert -> SortedSet) + val s = Set(1, 3, 7) s(0) //false s(1) //true val s = Set(1,1,3,3,7) s: scala.collection.immutable.Set[Int] = Set(1, 3, 7) -``` -## Tuple - Speichert beliebige Daten und "verbindet" sie miteinander + +// Tuple - Speichert beliebige Daten und "verbindet" sie miteinander // Ein Tuple ist keine Collection. -``` + (1, 2) (4, 3, 2) (1, 2, "three") (a, 2, "three") -``` + // Hier ist der Rückgabewert der Funktion ein Tuple // Die Funktion gibt das Ergebnis, so wie den Rest zurück. -``` + val divideInts = (x: Int, y: Int) => (x / y, x % y) divideInts(10, 3) -``` + // Um die Elemente eines Tuples anzusprechen, benutzt man diese // Notation: _._n wobei n der index des Elements ist (Index startet bei 1) -``` + val d = divideInts(10, 3) d._1 d._2 -``` -# 5. Objekt Orientierte Programmierung -Bislang waren alle gezeigten Sprachelemente einfache Ausdrücke, welche zwar -zum Ausprobieren und Lernen in der REPL gut geeignet sind, jedoch in -einem Scala file selten alleine zu finden sind. -Die einzigen Top-Level Konstrukte in Scala sind nämlich: -- Klassen (classes) -- Objekte (objects) -- case classes -- traits +///////////////////////////////////////////////// +// 5. Objektorientierte Programmierung +///////////////////////////////////////////////// + +/* + Bislang waren alle gezeigten Sprachelemente einfache Ausdrücke, welche zwar + zum Ausprobieren und Lernen in der REPL gut geeignet sind, jedoch in + einem Scala file selten alleine zu finden sind. + Die einzigen Top-Level Konstrukte in Scala sind nämlich: + + - Klassen (classes) + - Objekte (objects) + - case classes + - traits -Diesen Sprachelemente wenden wir uns jetzt zu. + Diesen Sprachelemente wenden wir uns jetzt zu. +*/ -## Klassen +// Klassen // Zum Erstellen von Objekten benötigt man eine Klasse, wie in vielen // anderen Sprachen auch. // erzeugt Klasse mit default Konstruktor -``` + class Hund scala> val t = new Hund t: Hund = Hund@7103745 -``` + // Der Konstruktor wird direkt hinter dem Klassennamen deklariert. -``` + class Hund(sorte: String) scala> val t = new Hund("Dackel") t: Hund = Hund@14be750c scala> t.sorte //error: value sorte is not a member of Hund -``` + // Per val wird aus dem Attribut ein unveränderliches Feld der Klasse // Per var wird aus dem Attribut ein veränderliches Feld der Klasse -``` + class Hund(val sorte: String) scala> val t = new Hund("Dackel") t: Hund = Hund@74a85515 scala> t.sorte res18: String = Dackel -``` + // Methoden werden mit def geschrieben -``` + def bark = "Woof, woof!" -``` + // Felder und Methoden können public, protected und private sein // default ist public // private ist nur innerhalb des deklarierten Bereichs sichtbar -``` + class Hund { private def x = ... def y = ... } -``` + // protected ist nur innerhalb des deklarierten und aller // erbenden Bereiche sichtbar -``` + class Hund { protected def x = ... } class Dackel extends Hund { // x ist sichtbar } -``` -## Object -Wird ein Objekt ohne das Schlüsselwort "new" instanziert, wird das sog. -"companion object" aufgerufen. Mit dem "object" Schlüsselwort wird so -ein Objekt (Typ UND Singleton) erstellt. Damit kann man dann eine Klasse -benutzen ohne ein Objekt instanziieren zu müssen. -Ein gültiges companion Objekt einer Klasse ist es aber erst dann, wenn -es genauso heisst und in derselben Datei wie die Klasse definiert wurde. -``` + +// Object +// Wird ein Objekt ohne das Schlüsselwort "new" instanziert, wird das sog. +// "companion object" aufgerufen. Mit dem "object" Schlüsselwort wird so +// ein Objekt (Typ UND Singleton) erstellt. Damit kann man dann eine Klasse +// benutzen ohne ein Objekt instanziieren zu müssen. +// Ein gültiges companion Objekt einer Klasse ist es aber erst dann, wenn +// es genauso heisst und in derselben Datei wie die Klasse definiert wurde. + object Hund { def alleSorten = List("Pitbull", "Dackel", "Retriever") def createHund(sorte: String) = new Hund(sorte) } -``` -## Case classes -Fallklassen bzw. Case classes sind Klassen die normale Klassen um extra -Funktionalität erweitern. Mit Case Klassen bekommt man ein paar -Dinge einfach dazu, ohne sich darum kümmern zu müssen. Z.B. -ein companion object mit den entsprechenden Methoden, -Hilfsmethoden wie toString(), equals() und hashCode() und auch noch -Getter für unsere Attribute (das Angeben von val entfällt dadurch) -``` + +// Case classes +// Fallklassen bzw. Case classes sind Klassen die normale Klassen um extra +// Funktionalität erweitern. Mit Case Klassen bekommt man ein paar +// Dinge einfach dazu, ohne sich darum kümmern zu müssen. Z.B. +// ein companion object mit den entsprechenden Methoden, +// Hilfsmethoden wie toString(), equals() und hashCode() und auch noch +// Getter für unsere Attribute (das Angeben von val entfällt dadurch) + class Person(val name: String) class Hund(val sorte: String, val farbe: String, val halter: Person) -``` + // Es genügt das Schlüsselwort case vor die Klasse zu schreiben. -``` + case class Person(name: String) case class Hund(sorte: String, farbe: String, halter: Person) -``` + // Für neue Instanzen brauch man kein "new" -``` + val dackel = Hund("dackel", "grau", Person("peter")) val dogge = Hund("dogge", "grau", Person("peter")) -``` + // getter -``` + dackel.halter // => Person = Person(peter) -``` + // equals -``` + dogge == dackel // => false -``` + // copy // otherGeorge == Person("george", "9876") -``` + val otherGeorge = george.copy(phoneNumber = "9876") -``` -## Traits -Ähnlich wie Java interfaces, definiert man mit traits einen Objekttyp -und Methodensignaturen. Scala erlaubt allerdings das teilweise -implementieren dieser Methoden. Konstruktorparameter sind nicht erlaubt. -Traits können von anderen Traits oder Klassen erben, aber nur von -parameterlosen. -``` + +// Traits +// Ähnlich wie Java interfaces, definiert man mit traits einen Objekttyp +// und Methodensignaturen. Scala erlaubt allerdings das teilweise +// implementieren dieser Methoden. Konstruktorparameter sind nicht erlaubt. +// Traits können von anderen Traits oder Klassen erben, aber nur von +// parameterlosen. + trait Hund { def sorte: String def farbe: String @@ -511,9 +526,9 @@ class Bernhardiner extends Hund{ val farbe = "braun" def beissen = false } -``` + -``` + scala> b res0: Bernhardiner = Bernhardiner@3e57cd70 scala> b.sorte @@ -522,10 +537,10 @@ scala> b.bellen res2: Boolean = true scala> b.beissen res3: Boolean = false -``` + // Traits können auch via Mixins (Schlüsselwort "with") eingebunden werden -``` + trait Bellen { def bellen: String = "Woof" } @@ -541,25 +556,27 @@ scala> val b = new Bernhardiner b: Bernhardiner = Bernhardiner@7b69c6ba scala> b.bellen res0: String = Woof -``` -# 6. Pattern Matching -Pattern matching in Scala ist ein sehr nützliches und wesentlich -mächtigeres Feature als Vergleichsfunktionen in Java. In Scala -benötigt ein case Statement kein "break", ein fall-through gibt es nicht. -Mehrere Überprüfungen können mit einem Statement gemacht werden. -Pattern matching wird mit dem Schlüsselwort "match" gemacht. -``` +///////////////////////////////////////////////// +// 6. Pattern Matching +///////////////////////////////////////////////// + +// Pattern matching in Scala ist ein sehr nützliches und wesentlich +// mächtigeres Feature als Vergleichsfunktionen in Java. In Scala +// benötigt ein case Statement kein "break", ein fall-through gibt es nicht. +// Mehrere Überprüfungen können mit einem Statement gemacht werden. +// Pattern matching wird mit dem Schlüsselwort "match" gemacht. + val x = ... x match { case 2 => case 3 => case _ => } -``` + // Pattern Matching kann auf beliebige Typen prüfen -``` + val any: Any = ... val gleicht = any match { case 2 | 3 | 5 => "Zahl" @@ -568,19 +585,19 @@ val gleicht = any match { case 45.35 => "Double" case _ => "Unbekannt" } -``` + // und auf Objektgleichheit -``` + def matchPerson(person: Person): String = person match { case Person("George", nummer) => "George! Die Nummer ist " + number case Person("Kate", nummer) => "Kate! Die Nummer ist " + nummer case Person(name, nummer) => "Irgendjemand: " + name + ", Telefon: " + nummer } -``` + // Und viele mehr... -``` + val email = "(.*)@(.*)".r // regex def matchEverything(obj: Any): String = obj match { // Werte: @@ -600,18 +617,21 @@ def matchEverything(obj: Any): String = obj match { // Patterns kann man ineinander schachteln: case List(List((1, 2, "YAY"))) => "Got a list of list of tuple" } -``` + // Jedes Objekt mit einer "unapply" Methode kann per Pattern geprüft werden // Ganze Funktionen können Patterns sein -``` + val patternFunc: Person => String = { case Person("George", number) => s"George's number: $number" case Person(name, number) => s"Random person's number: $number" } -``` -# 7. Higher-order functions + +///////////////////////////////////////////////// +// 37. Higher-order functions +///////////////////////////////////////////////// + Scala erlaubt, das Methoden und Funktion wiederum Funtionen und Methoden als Aufrufparameter oder Return Wert verwenden. Diese Methoden heissen higher-order functions @@ -621,116 +641,117 @@ Nennenswerte sind: "filter", "map", "reduce", "foldLeft"/"foldRight", "exists", "forall" ## List -``` + def isGleichVier(a:Int) = a == 4 val list = List(1, 2, 3, 4) val resultExists4 = list.exists(isEqualToFour) -``` + ## map // map nimmt eine Funktion und führt sie auf jedem Element aus und erzeugt // eine neue Liste // Funktion erwartet ein Int und returned ein Int -``` + val add10: Int => Int = _ + 10 -``` + // add10 wird auf jedes Element angewendet -``` + List(1, 2, 3) map add10 // => List(11, 12, 13) -``` + // Anonyme Funktionen können anstatt definierter Funktionen verwendet werden -``` + List(1, 2, 3) map (x => x + 10) -``` + // Der Unterstrich wird anstelle eines Parameters einer anonymen Funktion // verwendet. Er wird an die Variable gebunden. -``` + List(1, 2, 3) map (_ + 10) -``` + // Wenn der anonyme Block und die Funtion beide EIN Argument erwarten, // kann sogar der Unterstrich weggelassen werden. -``` + List("Dom", "Bob", "Natalia") foreach println -``` -## filter + +// filter // filter nimmt ein Prädikat (eine Funktion von A -> Boolean) und findet // alle Elemente die auf das Prädikat passen -``` + List(1, 2, 3) filter (_ > 2) // => List(3) case class Person(name: String, age: Int) List( Person(name = "Dom", age = 23), Person(name = "Bob", age = 30) ).filter(_.age > 25) // List(Person("Bob", 30)) -``` -## reduce + +// reduce // reduce nimmt zwei Elemente und kombiniert sie zu einem Element, // und zwar solange bis nur noch ein Element da ist. -## foreach +// foreach // foreach gibt es für einige Collections -``` + val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) aListOfNumbers foreach (x => println(x)) aListOfNumbers foreach println -``` -## For comprehensions + +// For comprehensions // Eine for-comprehension definiert eine Beziehung zwischen zwei Datensets. // Dies ist keine for-Schleife. -``` + for { n <- s } yield sq(n) val nSquared2 = for { n <- s } yield sq(n) for { n <- nSquared2 if n < 10 } yield n for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared -``` + ///////////////////////////////////////////////// -# 8. Implicits +// 8. Implicits ///////////////////////////////////////////////// -**ACHTUNG:** -Implicits sind ein sehr mächtiges Sprachfeature von Scala. Es sehr einfach -sie falsch zu benutzen und Anfänger sollten sie mit Vorsicht oder am -besten erst dann benutzen, wenn man versteht wie sie funktionieren. -Dieses Tutorial enthält Implicits, da sie in Scala an jeder Stelle -vorkommen und man auch mit einer Lib die Implicits benutzt nichts sinnvolles -machen kann. -Hier soll ein Grundverständnis geschaffen werden, wie sie funktionieren. +// **ACHTUNG:** +// Implicits sind ein sehr mächtiges Sprachfeature von Scala. +// Es sehr einfach +// sie falsch zu benutzen und Anfänger sollten sie mit Vorsicht oder am +// besten erst dann benutzen, wenn man versteht wie sie funktionieren. +// Dieses Tutorial enthält Implicits, da sie in Scala an jeder Stelle +// vorkommen und man auch mit einer Lib die Implicits benutzt nichts sinnvolles +// machen kann. +// Hier soll ein Grundverständnis geschaffen werden, wie sie funktionieren. // Mit dem Schlüsselwort implicit können Methoden, Werte, Funktion, Objekte // zu "implicit Methods" werden. -``` + implicit val myImplicitInt = 100 implicit def myImplicitFunction(sorte: String) = new Hund("Golden " + sorte) -``` + // implicit ändert nicht das Verhalten eines Wertes oder einer Funktion -``` + myImplicitInt + 2 // => 102 myImplicitFunction("Pitbull").sorte // => "Golden Pitbull" -``` + // Der Unterschied ist, dass diese Werte ausgewählt werden können, wenn ein // anderer Codeteil einen implicit Wert benötigt, zum Beispiel innerhalb von // implicit Funktionsparametern // Diese Funktion hat zwei Parameter: einen normalen und einen implicit -``` + def sendGreetings(toWhom: String)(implicit howMany: Int) = s"Hello $toWhom, $howMany blessings to you and yours!" -``` + // Werden beide Parameter gefüllt, verhält sich die Funktion wie erwartet -``` + sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!" -``` + // Wird der implicit Parameter jedoch weggelassen, wird ein anderer // implicit Wert vom gleichen Typ genommen. Der Compiler sucht im @@ -739,66 +760,69 @@ sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours! // geforderten Typ konvertieren kann. // Hier also: "myImplicitInt", da ein Int gesucht wird -``` + sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!" -``` + // bzw. "myImplicitFunction" // Der String wird erst mit Hilfe der Funktion in Hund konvertiert, und // dann wird die Methode aufgerufen -``` + "Retriever".sorte // => "Golden Retriever" -``` -# 9. Misc -## Importe -``` + +///////////////////////////////////////////////// +// 19. Misc +///////////////////////////////////////////////// +// Importe + import scala.collection.immutable.List -``` + // Importiere alle Unterpackages -``` + import scala.collection.immutable._ -``` + // Importiere verschiedene Klassen mit einem Statement -``` + import scala.collection.immutable.{List, Map} -``` + // Einen Import kann man mit '=>' umbenennen -``` + import scala.collection.immutable.{List => ImmutableList} -``` + // Importiere alle Klasses, mit Ausnahem von.... // Hier ohne: Map and Set: -``` + import scala.collection.immutable.{Map => _, Set => _, _} -``` -## Main -``` + +// Main + object Application { def main(args: Array[String]): Unit = { - // stuff goes here. + // Sachen kommen hierhin } } -``` -## I/O + +// I/O // Eine Datei Zeile für Zeile lesen -``` + import scala.io.Source for(line <- Source.fromFile("myfile.txt").getLines()) println(line) -``` + // Eine Datei schreiben -``` + val writer = new PrintWriter("myfile.txt") writer.write("Schreibe Zeile" + util.Properties.lineSeparator) writer.write("Und noch eine Zeile" + util.Properties.lineSeparator) writer.close() + ``` ## Weiterführende Hinweise diff --git a/de-de/yaml-de.html.markdown b/de-de/yaml-de.html.markdown index 19ea9e87..a46c30f6 100644 --- a/de-de/yaml-de.html.markdown +++ b/de-de/yaml-de.html.markdown @@ -30,7 +30,7 @@ null_Wert: null Schlüssel mit Leerzeichen: value # Strings müssen nicht immer mit Anführungszeichen umgeben sein, können aber: jedoch: "Ein String in Anführungzeichen" -"Ein Schlüssel in Anführungszeichen": "Nützlich, wenn du einen Doppelpunkt im Schluessel haben willst." +"Ein Schlüssel in Anführungszeichen": "Nützlich, wenn du einen Doppelpunkt im Schlüssel haben willst." # Mehrzeilige Strings schreibst du am besten als 'literal block' (| gefolgt vom Text) # oder ein 'folded block' (> gefolgt vom text). @@ -64,7 +64,7 @@ eine_verschachtelte_map: hallo: hallo # Schlüssel müssen nicht immer String sein. -0.25: ein Float-Wert als Schluessel +0.25: ein Float-Wert als Schlüssel # Schlüssel können auch mehrzeilig sein, ? symbolisiert den Anfang des Schlüssels ? | diff --git a/edn.html.markdown b/edn.html.markdown new file mode 100644 index 00000000..d0bdddfc --- /dev/null +++ b/edn.html.markdown @@ -0,0 +1,108 @@ +--- +language: edn +filename: learnedn.edn +contributors: + - ["Jason Yeo", "https://github.com/jsyeo"] +--- + +Extensible Data Notation (EDN) is a format for serializing data. + +The notation is used internally by Clojure to represent programs. It is also +used as a data transfer format like JSON. Though it is more commonly used in +Clojure, there are implementations of EDN for many other languages. + +The main benefit of EDN over JSON and YAML is that it is extensible. We +will see how it is extended later on. + +```Clojure +; Comments start with a semicolon. +; Anything after the semicolon is ignored. + +;;;;;;;;;;;;;;;;;;; +;;; Basic Types ;;; +;;;;;;;;;;;;;;;;;;; + +nil ; also known in other languages as null + +; Booleans +true +false + +; Strings are enclosed in double quotes +"hungarian breakfast" +"farmer's cheesy omelette" + +; Characters are preceeded by backslashes +\g \r \a \c \e + +; Keywords start with a colon. They behave like enums. Kind of +; like symbols in Ruby. +:eggs +:cheese +:olives + +; Symbols are used to represent identifiers. They start with #. +; You can namespace symbols by using /. Whatever preceeds / is +; the namespace of the name. +#spoon +#kitchen/spoon ; not the same as #spoon +#kitchen/fork +#github/fork ; you can't eat with this + +; Integers and floats +42 +3.14159 + +; Lists are sequences of values +(:bun :beef-patty 9 "yum!") + +; Vectors allow random access +[:gelato 1 2 -2] + +; Maps are associative data structures that associate the key with its value +{:eggs 2 + :lemon-juice 3.5 + :butter 1} + +; You're not restricted to using keywords as keys +{[1 2 3 4] "tell the people what she wore", + [5 6 7 8] "the more you see the more you hate"} + +; You may use commas for readability. They are treated as whitespace. + +; Sets are collections that contain unique elements. +#{:a :b 88 "huat"} + +;;;;;;;;;;;;;;;;;;;;;;; +;;; Tagged Elements ;;; +;;;;;;;;;;;;;;;;;;;;;;; + +; EDN can be extended by tagging elements with # symbols. + +#MyYelpClone/MenuItem {:name "eggs-benedict" :rating 10} + +; Let me explain this with a clojure example. Suppose I want to transform that +; piece of EDN into a MenuItem record. + +(defrecord MenuItem [name rating]) + +; To transform EDN to clojure values, I will need to use the built in EDN +; reader, edn/read-string + +(edn/read-string "{:eggs 2 :butter 1 :flour 5}") +; -> {:eggs 2 :butter 1 :flour 5} + +; To transform tagged elements, define the reader function and pass a map +; that maps tags to reader functions to edn/read-string like so + +(edn/read-string {:readers {'MyYelpClone/MenuItem map->menu-item}} + "#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}") +; -> #user.MenuItem{:name "eggs-benedict", :rating 10} + +``` + +# References + +- [EDN spec](https://github.com/edn-format/edn) +- [Implementations](https://github.com/edn-format/edn/wiki/Implementations) +- [Tagged Elements](http://www.compoundtheory.com/clojure-edn-walkthrough/) diff --git a/es-es/brainfuck-es.html.markdown b/es-es/brainfuck-es.html.markdown index e33d672d..550511da 100644 --- a/es-es/brainfuck-es.html.markdown +++ b/es-es/brainfuck-es.html.markdown @@ -9,8 +9,10 @@ lang: es-es --- Brainfuck (con mayúscula sólo al inicio de una oración) es un -lenguaje de programación mínimo, computacionalmente universal -en tamaño con sólo 8 comandos. +lenguaje de programación extremadamente pequeño, Turing completo con sólo 8 comandos. + +Puedes probar brainfuck en tu navegador con [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + ``` @@ -18,7 +20,7 @@ Cualquier caracter que no sea "><+-.,[]" (sin incluir las comillas) será ignorado. Brainfuck es representado por un arreglo de 30,000 celdas inicializadas -en cero y un apuntador en la celda actual. +en cero y un puntero apuntando la celda actual. Existen ocho comandos: @@ -26,7 +28,7 @@ Existen ocho comandos: - : Decrementa 1 al valor de la celda actual. > : Mueve el apuntador a la siguiente celda. (a la derecha) < : Mueve el apuntador a la celda anterior. (a la izquierda) -. : Imprime el valor en ASCII de la celda actual (i.e. 65 = 'A') +. : Imprime el valor en ASCII de la celda actual (p.e. 65 = 'A') , : Lee un caracter como input y lo escribe en la celda actual. [ : Si el valor en la celda actual es cero mueve el apuntador hasta el primer ']' que encuentre. Si no es cero sigue a la @@ -37,7 +39,7 @@ Existen ocho comandos: [ y ] forman un while. Obviamente, deben estar balanceados. -Ahora unos ejemplos de programas escritos con brainfuck. +Estos son algunos ejemplos de programas escritos con brainfuck. ++++++ [ > ++++++++++ < - ] > +++++ . @@ -63,7 +65,7 @@ Esto continúa hasta que la celda #1 contenga un cero. Cuando #1 contenga un cero la celda #2 tendrá el valor inicial de #1. Como este ciclo siempre terminara en la celda #1 nos movemos a la celda #2 e imprimimos (.). -Ten en mente que los espacios son sólo para fines de legibilidad. +Ten en cuenta que los espacios son sólo para fines de legibilidad. Es lo mismo escribir el ejemplo de arriba que esto: ,[>+<-]>. @@ -81,7 +83,7 @@ hasta la próxima vez. Para resolver este problema también incrementamos la celda #4 y luego copiamos la celda #4 a la celda #2. La celda #3 contiene el resultado. ``` -Y eso es brainfuck. ¿No tan difícil o sí? Como diversión, puedes escribir +Y eso es brainfuck. No es tan difícil, ¿verdad? Como diversión, puedes escribir tu propio intérprete de brainfuck o tu propio programa en brainfuck. El intérprete es relativamente sencillo de hacer, pero si eres masoquista, -intenta construir tu proprio intérprete de brainfuck... en brainfuck. +puedes intentar construir tu propio intérprete de brainfuck... en brainfuck. diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown index 18b544b4..4e1e68ba 100644 --- a/es-es/git-es.html.markdown +++ b/es-es/git-es.html.markdown @@ -18,11 +18,11 @@ versionar y administrar nuestro código fuente. ## Versionamiento, conceptos. -### Qué es el control de versiones? +### ¿Qué es el control de versiones? El control de versiones es un sistema que guarda todos los cambios realizados en uno o varios archivos, a lo largo del tiempo. -### Versionamiento centralizado vs Versionamiento Distribuido. +### Versionamiento centralizado vs versionamiento distribuido. + El versionamiento centralizado se enfoca en sincronizar, rastrear, y respaldar archivos. @@ -33,9 +33,9 @@ uno o varios archivos, a lo largo del tiempo. [Información adicional](http://git-scm.com/book/es/Empezando-Acerca-del-control-de-versiones) -### Por qué usar Git? +### ¿Por qué usar Git? -* Se puede trabajar sin conexion. +* Se puede trabajar sin conexión. * ¡Colaborar con otros es sencillo!. * Derivar, crear ramas del proyecto (aka: Branching) es fácil. * Combinar (aka: Merging) @@ -47,7 +47,7 @@ uno o varios archivos, a lo largo del tiempo. ### Repositorio Un repositorio es un conjunto de archivos, directorios, registros, cambios (aka: -comits), y encabezados (aka: heads). Imagina que un repositorio es una clase, +commits), y encabezados (aka: heads). Imagina que un repositorio es una clase, y que sus atributos otorgan acceso al historial del elemento, además de otras cosas. @@ -62,12 +62,12 @@ y mas. ### Directorio de trabajo (componentes del repositorio) -Es basicamente los directorios y archivos dentro del repositorio. La mayoría de +Es básicamente los directorios y archivos dentro del repositorio. La mayoría de las veces se le llama "directorio de trabajo". ### Índice (componentes del directorio .git) -El índice es el área de inicio en git. Es basicamente la capa que separa el +El índice es el área de inicio en git. Es básicamente la capa que separa el directorio de trabajo del repositorio en git. Esto otorga a los desarrolladores más poder sobre lo que se envía y se recibe del repositorio. diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index d475cf42..9ef0c63e 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -30,7 +30,7 @@ Aunque JavaScript no sólo se limita a los navegadores web: Node.js, Un proyecto // Cada sentencia puede ser terminada con punto y coma ; hazAlgo(); -// ... aunque no es necesario, ya que el punto y coma se agrega automaticamente +// ... aunque no es necesario, ya que el punto y coma se agrega automáticamente // cada que se detecta una nueva línea, a excepción de algunos casos. hazAlgo() @@ -109,7 +109,7 @@ null == undefined; // = true null === undefined; // false // Los Strings funcionan como arreglos de caracteres -// Puedes accesar a cada caracter con la función charAt() +// Puedes acceder a cada caracter con la función charAt() "Este es un String".charAt(0); // = 'E' // ...o puedes usar la función substring() para acceder a pedazos más grandes @@ -186,7 +186,7 @@ miObjeto.miLlave; // = "miValor" // agregar nuevas llaves. miObjeto.miTerceraLlave = true; -// Si intentas accesar con una llave que aún no está asignada tendrás undefined. +// Si intentas acceder con una llave que aún no está asignada tendrás undefined. miObjeto.miCuartaLlave; // = undefined /////////////////////////////////// @@ -301,7 +301,7 @@ i; // = 5 - en un lenguaje que da ámbitos por bloque esto sería undefined, per //inmediatamente", que preveé variables temporales de fugarse al ámbito global (function(){ var temporal = 5; - // Podemos accesar al ámbito global asignando al 'objeto global', el cual + // Podemos acceder al ámbito global asignando al 'objeto global', el cual // en un navegador siempre es 'window'. El objeto global puede tener // un nombre diferente en ambientes distintos, por ejemplo Node.js . window.permanente = 10; @@ -321,7 +321,7 @@ function decirHolaCadaCincoSegundos(nombre){ alert(texto); } setTimeout(interna, 5000); - // setTimeout es asíncrono, así que la funcion decirHolaCadaCincoSegundos + // setTimeout es asíncrono, así que la función decirHolaCadaCincoSegundos // terminará inmediatamente, y setTimeout llamará a interna() a los cinco segundos // Como interna está "cerrada dentro de" decirHolaCadaCindoSegundos, interna todavía tiene // acceso a la variable 'texto' cuando es llamada. @@ -339,7 +339,7 @@ var miObjeto = { }; miObjeto.miFuncion(); // = "¡Hola Mundo!" -// Cuando las funciones de un objeto son llamadas, pueden accesar a las variables +// Cuando las funciones de un objeto son llamadas, pueden acceder a las variables // del objeto con la palabra clave 'this'. miObjeto = { miString: "¡Hola Mundo!", @@ -401,11 +401,11 @@ var MiConstructor = function(){ miNuevoObjeto = new MiConstructor(); // = {miNumero: 5} miNuevoObjeto.miNumero; // = 5 -// Todos los objetos JavaScript tienen un 'prototipo'. Cuando vas a accesar a una +// Todos los objetos JavaScript tienen un 'prototipo'. Cuando vas a acceder a una // propiedad en un objeto que no existe en el objeto el intérprete buscará en // el prototipo. -// Algunas implementaciones de JavaScript te permiten accesar al prototipo de +// Algunas implementaciones de JavaScript te permiten acceder al prototipo de // un objeto con la propiedad __proto__. Mientras que esto es útil para explicar // prototipos, no es parte del estándar; veremos formas estándar de usar prototipos // más adelante. @@ -440,7 +440,7 @@ miPrototipo.sentidoDeLaVida = 43; miObjeto.sentidoDeLaVida; // = 43 // Mencionabamos anteriormente que __proto__ no está estandarizado, y que no -// existe una forma estándar de accesar al prototipo de un objeto. De todas formas. +// existe una forma estándar de acceder al prototipo de un objeto. De todas formas. // hay dos formas de crear un nuevo objeto con un prototipo dado. // El primer método es Object.create, el cual es una adición reciente a JavaScript, @@ -476,7 +476,7 @@ typeof miNumero; // = 'number' typeof miNumeroObjeto; // = 'object' miNumero === miNumeroObjeyo; // = false if (0){ - // Este código no se ejecutara porque 0 es false. + // Este código no se ejecutará porque 0 es false. } // Aún así, los objetos que envuelven y los prototipos por defecto comparten diff --git a/es-es/json-es.html.markdown b/es-es/json-es.html.markdown index fff678eb..c98049f9 100644 --- a/es-es/json-es.html.markdown +++ b/es-es/json-es.html.markdown @@ -21,22 +21,22 @@ JSON en su forma más pura no tiene comentarios, pero la mayoría de los parsead "llaves": "siempre debe estar entre comillas (ya sean dobles o simples)", "numeros": 0, "strings": "Høla, múndo. Todo el unicode está permitido, así como \"escapar\".", - "soporta booleanos?": true, - "vacios": null, + "¿soporta booleanos?": true, + "vacíos": null, "numero grande": 1.2e+100, "objetos": { - "comentario": "La mayoria de tu estructura vendra de objetos.", + "comentario": "La mayoría de tu estructura vendrá de objetos.", "arreglo": [0, 1, 2, 3, "Los arreglos pueden contener cualquier cosa.", 5], "otro objeto": { - "comentario": "Estas cosas pueden estar anidadas, muy util." + "comentario": "Estas cosas pueden estar anidadas, muy útil." } }, - "tonteria": [ + "tontería": [ { "fuentes de potasio": ["bananas"] }, @@ -50,10 +50,10 @@ JSON en su forma más pura no tiene comentarios, pero la mayoría de los parsead "estilo alternativo": { "comentario": "Mira esto!" - , "posicion de la coma": "no importa - mientras este antes del valor, entonces sera valido" - , "otro comentario": "que lindo" + , "posición de la coma": "no importa - mientras este antes del valor, entonces sera válido" + , "otro comentario": "qué lindo" }, - "eso fue rapido": "Y, estas listo. Ahora sabes todo lo que JSON tiene para ofrecer." + "eso fue rapido": "Y, estás listo. Ahora sabes todo lo que JSON tiene para ofrecer." } ``` diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown index d90e3eb5..bc481df7 100644 --- a/es-es/markdown-es.html.markdown +++ b/es-es/markdown-es.html.markdown @@ -11,7 +11,7 @@ lang: es-es Markdown fue creado por John Gruber en 2004. Su propósito es ser una sintaxis fácil de leer y escribir que se convierta fácilmente a HTML (y, actualmente, otros formatos también). -¡Denme todo la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests! +¡Denme toda la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests! ```markdown @@ -44,7 +44,7 @@ Esto es un h2 ------------- <!-- Estilos para texto plano --> -<!-- El texto puede ser fácilmente estilizaedo con italicas, negritas o tachado +<!-- El texto puede ser fácilmente estilizado con italicas, negritas o tachado usando markdown --> *Este texto está en itálicas.* @@ -62,7 +62,7 @@ Markdown en Github, también tenemos: --> ~~Este texto está tachado.~~ -<!-- Los párrafos son una o múltuples líneas de texto adyacentes separadas por +<!-- Los párrafos son una o múltiples líneas de texto adyacentes separadas por una o múltiples líneas en blanco--> Este es un párrafo. Estoy escribiendo un párrafo, ¿No es divertido? diff --git a/es-es/ruby-es.html.markdown b/es-es/ruby-es.html.markdown index 66a5d0fe..d8b67fe7 100644 --- a/es-es/ruby-es.html.markdown +++ b/es-es/ruby-es.html.markdown @@ -5,8 +5,18 @@ contributors: - ["David Underwood", "http://theflyingdeveloper.com"] - ["Joel Walden", "http://joelwalden.net"] - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gabriel Halley", "https://github.com/ghalley"] + - ["Persa Zula", "http://persazula.com"] translators: - ["Camilo Garrido", "http://www.twitter.com/hirohope"] + - ["Erick Bernal", "http://www.twitter.com/billowkib"] lang: es-es --- @@ -33,6 +43,8 @@ Tu tampoco deberías 8 - 1 #=> 7 10 * 2 #=> 20 35 / 5 #=> 7 +2**5 #=> 32 +5 % 3 #=> 2 # La aritmética es sólo azúcar sintáctico # para llamar un método de un objeto @@ -55,8 +67,6 @@ false.class #=> FalseClass # Desigualdad 1 != 1 #=> false 2 != 1 #=> true -!true #=> false -!false #=> true # Además de 'false', 'nil' es otro valor falso @@ -70,14 +80,29 @@ false.class #=> FalseClass 2 <= 2 #=> true 2 >= 2 #=> true +# Operadores lógicos +true && false #=> false +true || false #=> true +!true #=> false + +# Existen versiones alternativas de los operadores lógicos con menor prioridad +# Estos son usados como constructores controladores de flujo que encadenan +# sentencias hasta que una de ellas retorne verdadero o falso + +# `has_otra_cosa` solo se llama si `has_algo` retorna verdadero. +has_algo() and has_otra_cosa() +# `registra_error` solo se llama si `has_algo` falla +has_algo() or registra_error() + + # Los strings son objetos 'Soy un string'.class #=> String "Soy un string también".class #=> String -referente = "usar interpolacion de strings" +referente = "usar interpolación de strings" "Yo puedo #{referente} usando strings de comillas dobles" -#=> "Yo puedo usar interpolacion de strings usando strings de comillas dobles" +#=> "Yo puedo usar interpolación de strings usando strings de comillas dobles" # Imprime a la salida estándar @@ -119,15 +144,16 @@ status == :aprovado #=> false # Arreglos # Esto es un arreglo -[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] +arreglo = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # Arreglos pueden contener elementos de distintos tipos -arreglo = [1, "hola", false] #=> => [1, "hola", false] +[1, "hola", false] #=> => [1, "hola", false] # Arreglos pueden ser indexados # Desde el frente arreglo[0] #=> 1 +arreglo.first #=> 1 arreglo[12] #=> nil # Tal como la aritmética, el acceso como variable[índice] @@ -138,15 +164,25 @@ arreglo.[] 12 #=> nil # Desde el final arreglo[-1] #=> 5 +arreglo.last #=> 5 + +# Con un índice de inicio y longitud +arreglo[2, 3] #=> [3, 4, 5] -# Con un índice de inicio y final -arreglo[2, 4] #=> [3, 4, 5] +# Invertir un arreglo +a = [1, 2, 3] +a.reverse! #=> [3, 2, 1] # O con rango arreglo[1..3] #=> [2, 3, 4] # Añade elementos a un arreglo así arreglo << 6 #=> [1, 2, 3, 4, 5, 6] +# O así +arreglo.push(6) #=> [1, 2, 3, 4, 5, 6] + +#Verifica si un elemento ya existe en ese arreglo +arreglo.include?(1) #=> true # Hashes son los diccionarios principales de Ruby con pares llave/valor. # Hashes se denotan con llaves: @@ -161,17 +197,16 @@ hash['numero'] #=> 5 # Preguntarle a un hash por una llave que no existe retorna 'nil': hash['nada aqui'] #=> nil -# Itera sobre un hash con el método 'each': -hash.each do |k, v| - puts "#{k} is #{v}" -end - # Desde Ruby 1.9, hay una sintaxis especial cuando se usa un símbolo como llave: nuevo_hash = { defcon: 3, accion: true} nuevo_hash.keys #=> [:defcon, :accion] +# Verifica la existencia de llaves y valores en el hash +new_hash.has_key?(:defcon) #=> true +new_hash.has_value?(3) #=> true + # Tip: Tanto los arreglos como los hashes son Enumerable (enumerables) # Comparten muchos métodos útiles tales como 'each', 'map', 'count', y más @@ -194,9 +229,15 @@ end #=> iteracion 4 #=> iteracion 5 -# Aunque -# Nadie usa los ciclos `for` -# Usa `each`, así: +# SIN EMBARGO, nadie usa ciclos `for` +# En su lugar debes usar el método "each" y pasarle un block (bloque). +# Un bloque es un fragmento código que puedes pasar a métodos como `each`. +# Es símilar a las funciones lambda, funciones anónimas o `closures` en otros +# lenguajes de programación. +# +# El método `each` de un Range (rango) ejecuta el bloque una vez por cada elemento. +# Al bloque se le pasa un contador como parametro. +# Usar el método `each` con un bloque se ve así: (1..5).each do |contador| puts "iteracion #{contador}" @@ -207,10 +248,27 @@ end #=> iteracion 4 #=> iteracion 5 -counter = 1 -while counter <= 5 do - puts "iteracion #{counter}" - counter += 1 +# También puedes envolver el bloque entre llaves: +(1..5).each { |counter| puts "iteración #{contador}" } + +#El contenido de las estructuras de datos en ruby puede ser iterado usando `each`. +arreglo.each do |elemento| + puts "#{elemento} es parte del arreglo" +end +hash.each do |llave, valor| + puts "#{llave} es #{valor}" +end + +# Si aún necesitas un índice puedes usar "each_with_index" y definir una variable +# índice. +arreglo.each_with_index do |element, index| + puts "#{element} tiene la posición #{index} en el arreglo" +end + +contador = 1 +while contador <= 5 do + puts "iteracion #{contador}" + contador += 1 end #=> iteracion 1 #=> iteracion 2 @@ -218,6 +276,19 @@ end #=> iteracion 4 #=> iteracion 5 +# Hay una gran variedad de otras funciones iterativas útiles en Ruby, +# por ejemplo `map`, `reduce`, `inject`, entre otras. Map, por ejemplo, +# toma el arreglo sobre el cuál está iterando, le hace cambios +# definidos en el bloque, y retorna un arreglo completamente nuevo. +arreglo = [1,2,3,4,5] +duplicado = array.map do |elemento| + elemento * 2 +end +puts duplicado +#=> [2,4,6,8,10] +puts array +#=> [1,2,3,4,5] + nota = 'B' case nota @@ -234,6 +305,34 @@ when 'F' else puts "Sistema alternativo de notas, ¿eh?" end +#=> "Mejor suerte para la proxima" + +# Los casos también pueden usar rangos +nota = 82 + +case nota +when 90..100 + puts 'Excelente!' +when 80..100 + puts 'Buen trabajo' +else + puts '¡Reprobaste!' +end +#=> "Buen trabajo" + +# Manejo de excepciones +begin + # código que podría causar excepción + raise NoMemoryError, 'Se te acabó la memoria' +rescue NoMemoryError => variable_de_excepcion + puts 'El error NoMemoryError ocurrió', variable_de_excepcion +rescue RuntimeError => otra_variable_de_excepcion + puts 'El error RuntimeError ocurrió' +else + puts 'Esto se ejecuta si ningun error ocurrió' +ensure + puts 'Este código siempre se ejecuta, sin importar que' +end # Funciones @@ -244,7 +343,7 @@ end # Funciones (y todos los bloques) implícitamente retornan el valor de la última instrucción doble(2) #=> 4 -# Paréntesis son opcionales cuando el resultado es ambiguo +# Paréntesis son opcionales cuando el resultado no es ambiguo doble 3 #=> 6 doble doble 3 #=> 12 @@ -259,7 +358,7 @@ suma 3, 4 #=> 7 suma suma(3,4), 5 #=> 12 # yield -# Todos los métodos tienen un parámetro de bloqueo opcional e implícitp +# Todos los métodos tienen un parámetro bloque opcional e implícito # puede llamarse con la palabra clave 'yield' def alrededor @@ -274,6 +373,17 @@ alrededor { puts 'hola mundo' } # hola mundo # } +# Puedes pasar un bloque a una función +# '&' representa una referencia a un bloque +def visitantes(&bloque) + bloque.call +end + +# Puedes pasar una lista de argumentos, que serán convertidos en un arreglo +# Para eso sirve el operador ('*') +def visitantes(*arreglo) + arreglo.each { |visitante| puts visitante } +end # Define una clase con la palabra clave 'class' class Humano @@ -299,16 +409,26 @@ class Humano @nombre end + # La funcionalidad anterior puede ser encapsulada usando el método attr_accessor + # de la siguiente manera + + attr_accessor :name + + # Los métodos de tipo getter y setter también se pueden crear de manera individual + # de la siguiente manera + + attr_reader :name + attr_writer :name + # Un método de clase usa 'self' (sí mismo) para distinguirse de métodos de instancia. # Sólo puede ser llamado en la clase, no por una instancia. def self.decir(mensaje) - puts "#{mensaje}" + puts mensaje end def especie @@especie end - end @@ -328,6 +448,23 @@ dwight.nombre #=> "Dwight K. Schrute" # Llama el método de clase Humano.decir("Hi") #=> "Hi" +# El alcance de las variables es definido por la manera en que las nombramos. +# Las variables que inician con $ tienen un alcance global +$var = "Soy una variable global" +defined? $var #=> "global-variable" + +# Las variables que empiezan con @ tienen un alcance de instancia +@var = "Soy una variable de instancia" +defined? @var #=> "instance-variable" + +# Variables que empiezan con @@ tienen un alcance de clase +@@var = "Soy una variable de clase" +defined? @@var #=> "class variable" + +# Las variables que empiezan con letra mayuscula son constantes +Var = "Soy una constante" +defined? Var #=> "constant" + # Las clases también son un objeto en ruby. Por lo cual, las clases también pueden tener variables de instancia. # Variables de clase son compartidas a través de la clase y todos sus descendientes. @@ -371,7 +508,67 @@ end class Doctor < Humano end -Human.bar # 0 +Humano.bar # 0 Doctor.bar # nil +module ModuloEjemplo + def foo + 'foo' + end +end + +# Al incluir un módulo sus métodos se comparten con las instancias de la clase +# Al extender un módulo sus métodos se comparten con la clase misma + +class Persona + include ModuloEjemplo +end + +class Libro + extend ModuloEjemplo +end + +Persona.foo # => NoMethodError: undefined method `foo' for Persona:Class +Persona.new.foo # => 'foo' +Libro.foo # => 'foo' +Libro.new.foo # => NoMethodError: undefined method `foo' + +# Las llamadas de retorno (callbacks) son ejecutadas cuando se incluye o +# extiende un módulo +module EjemploConcern + def self.incluido(base) + base.extend(MetodosClase) + base.send(:include, MetodosInstancia) + end + + module MetodosClase + def bar + 'bar' + end + end + + module MetodosInstancia + def qux + 'qux' + end + end +end + +class Algo + include EjemploConcern +end + +Algo.bar #=> 'bar' +Algo.qux #=> NoMethodError: undefined method `qux' +Algo.new.bar # => NoMethodError: undefined method `bar' +Algo.new.qux # => 'qux' ``` + +## Recursos adicionales +- [Aprende Ruby Mediante Ejemplo con Ejercicios](http://www.learneroo.com/modules/61/nodes/338) - Una variante de +esta referencia con ejercicios en navegador. +- [Documentación Oficial](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby desde otros lenguajes](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programando Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Una +[edición antigua](http://ruby-doc.com/docs/ProgrammingRuby/) gratuita disponible en línea. +- [Guía de estilo de Ruby](https://github.com/bbatsov/ruby-style-guide) - Guía de estilo creada por la comunidad. diff --git a/fa-ir/brainfuck.html.markdown b/fa-ir/brainfuck-fa.html.markdown index ef2bcba3..ef2bcba3 100644 --- a/fa-ir/brainfuck.html.markdown +++ b/fa-ir/brainfuck-fa.html.markdown diff --git a/fa-ir/javascript.html.markdown b/fa-ir/javascript-fa.html.markdown index fe3555af..fe3555af 100644 --- a/fa-ir/javascript.html.markdown +++ b/fa-ir/javascript-fa.html.markdown diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown new file mode 100644 index 00000000..d9bd9b48 --- /dev/null +++ b/fr-fr/d.html.markdown @@ -0,0 +1,264 @@ +--- +language: D +filename: learnd-fr.d +contributors: + - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] +translators: + - ["Quentin Ladeveze", "aceawan.eu"] +lang: fr-fr +--- + +```d +// Commençons par un classique +module hello; + +import std.stdio; + +// args n'est pas obligatoire +void main(string[] args) { + writeln("Bonjour le monde !"); +} +``` + +Si vous êtes comme moi et que vous passez beaucoup trop de temps sur internet, il y a +de grandes chances pour que vous ayez déjà entendu parler du [D](http://dlang.org/). +D est un langage de programmation moderne, généraliste, multi-paradigmes qui contient +des fonctionnalités aussi bien de bas niveau que de haut niveau. + +D est activement développé par de nombreuses personnes très intelligents, guidées par +[Walter Bright](https://fr.wikipedia.org/wiki/Walter_Bright))) et +[Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu). +Après cette petite introduction, jetons un coup d'oeil à quelques exemples. + +```d +import std.stdio; + +void main() { + //Les conditions et les boucles sont classiques. + for(int i = 0; i < 10000; i++) { + writeln(i); + } + + // On peut utiliser auto pour inférer automatiquement le + // type d'une variable. + auto n = 1; + + // On peut faciliter la lecture des valeurs numériques + // en y insérant des `_`. + while(n < 10_000) { + n += n; + } + + do { + n -= (n / 2); + } while(n > 0); + + // For et while sont très utiles, mais en D, on préfère foreach. + // Les deux points : '..', créent un intervalle continue de valeurs + // incluant la première mais excluant la dernière. + foreach(i; 1..1_000_000) { + if(n % 2 == 0) + writeln(i); + } + + // On peut également utiliser foreach_reverse pour itérer à l'envers. + foreach_reverse(i; 1..int.max) { + if(n % 2 == 1) { + writeln(i); + } else { + writeln("Non !"); + } + } +} +``` +On peut définir de nouveaux types avec les mots-clés `struct`, `class`, +`union` et `enum`. Ces types sont passés au fonction par valeur (ils sont copiés) +De plus, on peut utiliser les templates pour rendre toutes ces abstractions génériques. + +```d +// Ici, 'T' est un paramètre de type. Il est similaire au <T> de C++/C#/Java. +struct LinkedList(T) { + T data = null; + + // Utilisez '!' pour instancier un type paramétré. + // Encore une fois semblable à '<T>' + LinkedList!(T)* next; +} + +class BinTree(T) { + T data = null; + + // Si il n'y a qu'un seul paramètre de template, + // on peut s'abstenir de mettre des parenthèses. + BinTree!T left; + BinTree!T right; +} + +enum Day { + Sunday, + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, +} + +// Utilisez alias pour créer des abreviations pour les types. +alias IntList = LinkedList!int; +alias NumTree = BinTree!double; + +// On peut tout aussi bien créer des templates de function ! +T max(T)(T a, T b) { + if(a < b) + return b; + + return a; +} + +// On peut utiliser le mot-clé ref pour s'assurer que quelque chose est passé +// par référence, et ceci, même si a et b sont d'ordinaire passés par valeur. +// Ici ils seront toujours passés par référence à 'swap()'. +void swap(T)(ref T a, ref T b) { + auto temp = a; + + a = b; + b = temp; +} + +// Avec les templates, on peut également passer des valeurs en paramètres. +class Matrix(uint m, uint n, T = int) { + T[m] rows; + T[n] columns; +} + +auto mat = new Matrix!(3, 3); // T est 'int' par défaut + +``` +À propos de classes, parlons des propriétés. Une propriété est, en gros, +une méthode qui peut se comporter comme une lvalue. On peut donc utiliser +la syntaxe des structures classiques (`struct.x = 7`) comme si il +s'agissait de méthodes getter ou setter. + +```d +// Considérons une classe paramétrée avec les types 'T' et 'U' +class MyClass(T, U) { + T _data; + U _other; +} + +// Et des méthodes "getter" et "setter" comme suit: +class MyClass(T, U) { + T _data; + U _other; + + // Les constructeurs s'apellent toujours 'this'. + this(T t, U u) { + // Ceci va appeller les setters ci-dessous. + 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; + } +} + +// Et on l'utilise de cette façon: +void main() { + auto mc = new MyClass!(int, string)(7, "seven"); + + // Importer le module 'stdio' de la bibliothèque standard permet + // d'écrire dans la console (les imports peuvent être locaux à une portée) + import std.stdio; + + // On appelle les getters pour obtenir les valeurs. + writefln("Earlier: data = %d, str = %s", mc.data, mc.other); + + // On appelle les setter pour assigner de nouvelles valeurs. + mc.data = 8; + mc.other = "eight"; + + // On appelle les setter pour obtenir les nouvelles valeurs. + writefln("Later: data = %d, str = %s", mc.data, mc.other); +} +``` +Avec les propriétés, on peut constuire nos setters et nos getters +comme on le souhaite, tout en gardant un syntaxe très propre, +comme si on accédait directement à des membres de la classe. + +Les autres fonctionnalités orientées objets à notre disposition +incluent les interfaces, les classes abstraites, et la surcharge +de méthodes. D gère l'héritage comme Java: On ne peut hériter que +d'une seule classe et implémenter autant d'interface que voulu. + +Nous venons d'explorer les fonctionnalités objet du D, mais changeons +un peu de domaine. D permet la programmation fonctionelle, avec les fonctions +de premier ordre, les fonctions `pure` et les données immuables. +De plus, tout vos algorithmes fonctionelles favoris (map, reduce, filter) +sont disponibles dans le module `std.algorithm`. + +```d +import std.algorithm : map, filter, reduce; +import std.range : iota; // construit un intervalle excluant la dernière valeur. + +void main() { + // On veut un algorithm qui affiche la somme de la listes des carrés + // des entiers paires de 1 à 100. Un jeu d'enfant ! + + // On se content de passer des expressions lambda en paramètre à des templates. + // On peut fournier au template n'importe quelle fonction, mais dans notre + // cas, les lambdas sont pratiques. + auto num = iota(1, 101).filter!(x => x % 2 == 0) + .map!(y => y ^^ 2) + .reduce!((a, b) => a + b); + + writeln(num); +} +``` + +Vous voyez comme on a calculé `num` comme on le ferait en haskell par exemple ? +C'est grâce à une innvoation de D qu'on appelle "Uniform Function Call Syntax". +Avec l'UFCS, on peut choisir d'écrire un appelle à une fonction de manière +classique, ou comme un appelle à une méthode. Walter Brighter a écrit un +article en anglais sur l'UFCS [ici.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) +Pour faire court, on peut appeller une fonction dont le premier paramètre +est de type A, comme si c'était une méthode de A. + +J'aime le parallélisme. Vous aimez les parallélisme ? Bien sur que vous aimez ça +Voyons comment on le fait en D ! + +```d +import std.stdio; +import std.parallelism : parallel; +import std.math : sqrt; + +void main() { + // On veut calculer la racine carré de tous les nombres + // dans notre tableau, et profiter de tous les coeurs + // à notre disposition. + auto arr = new double[1_000_000]; + + // On utilise un index et une référence à chaque élément du tableau. + // On appelle juste la fonction parallel sur notre tableau ! + foreach(i, ref elem; parallel(arr)) { + ref = sqrt(i + 1.0); + } +} + + +``` diff --git a/fr-fr/livescript-fr.html.markdown b/fr-fr/livescript-fr.html.markdown index 9c3b8003..13bbffe5 100644 --- a/fr-fr/livescript-fr.html.markdown +++ b/fr-fr/livescript-fr.html.markdown @@ -4,7 +4,7 @@ filename: learnLivescript-fr.ls contributors: - ["Christina Whyte", "http://github.com/kurisuwhyte/"] translators: - - ["Morgan Bohn", "https://github.com/morganbohn"] + - ["Morgan Bohn", "https://github.com/dotmobo"] lang: fr-fr --- diff --git a/fr-fr/perl-fr.html.markdown b/fr-fr/perl-fr.html.markdown new file mode 100644 index 00000000..e737b7aa --- /dev/null +++ b/fr-fr/perl-fr.html.markdown @@ -0,0 +1,174 @@ +--- +name: perl +category: language +language: perl +filename: learnperl-fr.pl +contributors: + - ["Korjavin Ivan", "http://github.com/korjavin"] + - ["Matteo Taroli", "http://www.matteotaroli.be"] +translators: + - ["Matteo Taroli", "http://www.matteotaroli.be"] +lang: fr-fr +--- +Perl 5 est un langage de programmation riche en fonctionnalité, avec plus de 25 ans de développement. + +Perl 5 fonctionne sur plus de 100 plateformes, allant des pc portables aux mainframes et +est autant adapté à un prototypage rapide qu'à des projets de grande envergure. + +```perl +# Les commentaires en une ligne commencent par un dièse + + +#### Types de variables de Perl + +# Les variables comment par un symbole précisant le type. +# Un nom de variable valide commence par une lettre ou un underscore, +# suivi d'un nombre quelconque de lettres, chiffres ou underscores. + +### Perl a trois types principaux de variables: $scalaire, @tableau and %hash + +## Scalaires +# Un scalaire représente une valeur unique : +my $animal = "chameau"; +my $reponse = 42; + +# Les valeurs scalaires peuvent être des strings, des entiers ou des nombres à virgule flottante +# et Perl les convertira automatiquement entre elles quand nécessaire. + +## Tableaux +# Un tableau représente une liste de valeurs : +my @animaux = ("chameau", "lama", "chouette"); +my @nombres = (23, 42, 69); +my @melange = ("chameau", 42, 1.23); + +## Hashes +# Un hash représente un ensemble de paires de clé/valeur : +my %fruit_couleur = ("pomme", "rouge", "banane", "jaune"); + +# Vous pouvez utiliser des espaces et l'opérateur "=>" pour les disposer plus joliment : + +my %fruit_couleur = ( + pomme => "rouge", + banane => "jaune" +); + +# Les scalaires, tableaux et hashes sont plus amplement documentés dans le perldata +# (perldoc perldata) + +# Des types de données plus complexes peuvent être construits en utilisant des références, +# vous permettant de construire des listes et des hashes à l'intérieur d'autres listes et hashes. + +#### Conditions et boucles + +# Perl possède la plupart des conditions et boucles habituelles. + +if ($var) { + ... +} elsif ($var eq 'bar') { + ... +} else { + ... +} + +unless (condition) { + ... +} +# Ceci est fourni en tant que version plus lisible de "if (!condition)" + +# la postcondition à la sauce Perl + +print "Yow!" if $zippy; +print "Nous n'avons pas de banane." unless $bananes; + +# while +while (condition) { + ... +} + +# boucle for et iteration +for (my $i = 0; $i < $max; $i++) { + print "l'index est $i"; +} + +for (my $i = 0; $i < @elements; $i++) { + print "L'élément courant est " . $elements[$i]; +} + +for my $element (@elements) { + print $element; +} + +# implicitement + +# La variable de contexte scalaire $_ est utilisée par défaut dans différentes +# situations, comme par exemple dans la boucle foreach ou en argument par défaut +# de la plupart des fonctions pour en simplifier l'écriture. + +# Dans l'exemple suivant, $_ prends successivement la valeur de +# chaque élément de la liste. + +for (@elements) { + print; # affiche le contenu de $_ +} + + +#### Expressions régulières + +# Le support des expressions régulières par Perl est aussi large que profond +# et est sujet à une longue documentation sur perlrequick, perlretut et ailleurs. +# Cependant, pour faire court : + +# Simple correspondance +if (/foo/) { ... } # vrai si $_ contient "foo" +if ($a =~ /foo/) { ... } # vrai si $a contient "foo" + +# Simple substitution + +$a =~ s/foo/bar/; # remplace le premier foo par bar dans $a +$a =~ s/foo/bar/g; # remplace TOUTES LES INSTANCES de foo par bar dans $a + + +#### Fichiers et E/S + +# Vous pouvez ouvrir un fichier pour y écrire ou pour le lire avec la fonction "open()". + +open(my $in, "<", "input.txt") or die "Impossible d'ouvrir input.txt: $!"; +open(my $out, ">", "output.txt") or die "Impossible d'ouvrir output.txt: $!"; +open(my $log, ">>", "my.log") or die "Impossible d'ouvrir my.log: $!"; + +# Vous pouvez lire depuis un descripteur de fichier grâce à l'opérateur "<>". +# Dans un contexte scalaire, il lit une seule ligne depuis le descripteur de fichier +# et dans un contexte de liste, il lit le fichier complet, assignant chaque ligne à un +# élément de la liste : + +my $ligne = <$in> +my $lignes = <$in> + +#### Ecrire des fonctions + +# Ecrire des fonctions est facile : + +sub logger { + my $logmessage = shift; + + open my $logfile, ">>", "my.log" or die "Impossible d'ouvrir my.log: $!"; + + print $logfile $logmessage; +} + +# Maintenant, nous pouvons utiliser cette fonction comme n'importe quelle fonction intégrée : + +logger("On a une fonction de logging!!"); +``` + +#### Utiliser des modules Perl + +Les modules Perl fournissent une palette de fonctionnalités vous évitant de réinventer la roue et peuvent être téléchargés depuis CPAN (http://www.cpan.org/). Un certain nombre de modules populaires sont inclus dans la distribution même de Perl. + +Perlfaq contiens des questions et réponses liées aux tâches habituelles et propose souvent des suggestions quant aux bons modules à utiliser. + +#### Pour en savoir plus + - [perl-tutorial](http://perl-tutorial.org/) + - [Learn at www.perl.com](http://www.perl.org/learn.html) + - [perldoc](http://perldoc.perl.org/) + - and perl built-in : `perldoc perlintro` diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown index 3f6dcabb..d78291be 100644 --- a/fr-fr/python-fr.html.markdown +++ b/fr-fr/python-fr.html.markdown @@ -14,8 +14,7 @@ Je suis tombé amoureux de Python de par la clarté de sa syntaxe. C'est pratiqu Vos retours sont grandement appréciés. Vous pouvez me contacter sur Twitter [@louiedinh](http://twitter.com/louiedinh) ou par e-mail: louiedinh [at] [google's email service] -NB: Cet artice s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x -Vous pourrez bientôt trouver un article pour Python 3 en Français. Pour le moment vous pouvez jettez un coup d'oeil à l'article [Python 3 en Anglais](http://learnxinyminutes.com/docs/python3/). +N.B. : Cet article s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x. Python 2.7 est en fin de vie et ne sera plus maintenu à partir de 2020, il est donc recommandé d'apprendre Python avec Python 3. Pour Python 3.x, il existe un autre [tutoriel pour Python 3](http://learnxinyminutes.com/docs/fr-fr/python3-fr/). ```python # Une ligne simple de commentaire commence par un dièse diff --git a/fsharp.html.markdown b/fsharp.html.markdown index 76318d7d..809a1da2 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -31,14 +31,14 @@ If you want to try out the code below, you can go to [tryfsharp.org](http://www. // The "let" keyword defines an (immutable) value let myInt = 5 let myFloat = 3.14 -let myString = "hello" //note that no types needed +let myString = "hello" // note that no types needed // ------ Lists ------ -let twoToFive = [2;3;4;5] // Square brackets create a list with +let twoToFive = [2; 3; 4; 5] // Square brackets create a list with // semicolon delimiters. let oneToFive = 1 :: twoToFive // :: creates list with new 1st element -// The result is [1;2;3;4;5] -let zeroToFive = [0;1] @ twoToFive // @ concats two lists +// The result is [1; 2; 3; 4; 5] +let zeroToFive = [0; 1] @ twoToFive // @ concats two lists // IMPORTANT: commas are never used as delimiters, only semicolons! @@ -53,7 +53,7 @@ add 2 3 // Now run the function. // to define a multiline function, just use indents. No semicolons needed. let evens list = - let isEven x = x%2 = 0 // Define "isEven" as a sub function + let isEven x = x % 2 = 0 // Define "isEven" as a sub function List.filter isEven list // List.filter is a library function // with two parameters: a boolean function // and a list to work on @@ -75,7 +75,7 @@ let sumOfSquaresTo100piped = // you can define lambdas (anonymous functions) using the "fun" keyword let sumOfSquaresTo100withFun = - [1..100] |> List.map (fun x -> x*x) |> List.sum + [1..100] |> List.map (fun x -> x * x) |> List.sum // In F# there is no "return" keyword. A function always // returns the value of the last expression used. @@ -109,7 +109,7 @@ optionPatternMatch invalidValue // 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] +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#. @@ -131,19 +131,19 @@ module FunctionExamples = // basic usage of a function let a = add 1 2 - printfn "1+2 = %i" a + printfn "1 + 2 = %i" a // partial application to "bake in" parameters let add42 = add 42 let b = add42 1 - printfn "42+1 = %i" b + 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 + printfn "3 + 7 = %i" c // higher order functions [1..10] |> List.map add3 |> printfn "new list is %A" @@ -151,7 +151,7 @@ module FunctionExamples = // lists of functions, and more let add6 = [add1; add2; add3] |> List.reduce (>>) let d = add6 7 - printfn "1+2+3+7 = %i" d + printfn "1 + 2 + 3 + 7 = %i" d // ================================================ // Lists and collection @@ -168,12 +168,12 @@ module FunctionExamples = module ListExamples = // lists use square brackets - let list1 = ["a";"b"] + 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] + let squares = [for i in 1..10 do yield i * i] // prime number generator let rec sieve = function @@ -190,8 +190,8 @@ module ListExamples = | [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; 2; 3; 4] + listMatcher [1; 2] listMatcher [1] listMatcher [] @@ -219,7 +219,7 @@ module ListExamples = module ArrayExamples = // arrays use square brackets with bar - let array1 = [| "a";"b" |] + let array1 = [| "a"; "b" |] let first = array1.[0] // indexed access using dot // pattern matching for arrays is same as for lists @@ -230,13 +230,13 @@ module ArrayExamples = | [| first; second |] -> printfn "array is %A and %A" first second | _ -> printfn "the array has more than two elements" - arrayMatcher [| 1;2;3;4 |] + 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.map (fun i -> i + 3) + |> Array.filter (fun i -> i % 2 = 0) |> Array.iter (printfn "value is %i. ") @@ -248,14 +248,14 @@ module SequenceExamples = // sequences can use yield and // can contain subsequences let strange = seq { - // "yield! adds one element + // "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 }} + if i % 2 = 0 then yield i }} // test strange |> Seq.toList @@ -280,11 +280,11 @@ module DataTypeExamples = // Tuples are quick 'n easy anonymous types // -- Use a comma to create a tuple - let twoTuple = 1,2 - let threeTuple = "a",2,true + let twoTuple = 1, 2 + let threeTuple = "a", 2, true // Pattern match to unpack - let x,y = twoTuple //sets x=1 y=2 + let x, y = twoTuple // sets x = 1, y = 2 // ------------------------------------ // Record types have named fields @@ -297,7 +297,7 @@ module DataTypeExamples = let person1 = {First="John"; Last="Doe"} // Pattern match to unpack - let {First=first} = person1 //sets first="john" + let {First = first} = person1 // sets first="John" // ------------------------------------ // Union types (aka variants) have a set of choices @@ -331,14 +331,14 @@ module DataTypeExamples = | Worker of Person | Manager of Employee list - let jdoe = {First="John";Last="Doe"} + let jdoe = {First="John"; Last="Doe"} let worker = Worker jdoe // ------------------------------------ - // Modelling with types + // Modeling with types // ------------------------------------ - // Union types are great for modelling state without using flags + // Union types are great for modeling state without using flags type EmailAddress = | ValidEmailAddress of string | InvalidEmailAddress of string @@ -383,8 +383,8 @@ module DataTypeExamples = 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 ] + 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" @@ -419,14 +419,14 @@ module ActivePatternExamples = | _ -> printfn "%c is something else" ch // print a list - ['a';'b';'1';' ';'-';'c'] |> List.iter printChar + ['a'; 'b'; '1'; ' '; '-'; 'c'] |> List.iter printChar // ----------------------------------- // FizzBuzz using active patterns // ----------------------------------- // You can create partial matching patterns as well - // Just use undercore in the defintion, and return Some if matched. + // Just use underscore in the defintion, 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 @@ -479,7 +479,7 @@ module AlgorithmExamples = List.concat [smallerElements; [firstElem]; largerElements] // test - sort [1;5;23;18;9;1;3] |> printfn "Sorted = %A" + sort [1; 5; 23; 18; 9; 1; 3] |> printfn "Sorted = %A" // ================================================ // Asynchronous Code @@ -526,7 +526,7 @@ module AsyncExample = |> Async.RunSynchronously // start them off // ================================================ -// .NET compatability +// .NET compatibility // ================================================ module NetCompatibilityExamples = @@ -536,7 +536,7 @@ module NetCompatibilityExamples = // ------- work with existing library functions ------- - let (i1success,i1) = System.Int32.TryParse("123"); + let (i1success, i1) = System.Int32.TryParse("123"); if i1success then printfn "parsed as %i" i1 else printfn "parse failed" // ------- Implement interfaces on the fly! ------- @@ -570,12 +570,12 @@ module NetCompatibilityExamples = // abstract base class with virtual methods [<AbstractClass>] type Shape() = - //readonly properties + // readonly properties abstract member Width : int with get abstract member Height : int with get - //non-virtual method + // non-virtual method member this.BoundingArea = this.Height * this.Width - //virtual method with base implementation + // virtual method with base implementation abstract member Print : unit -> unit default this.Print () = printfn "I'm a shape" @@ -586,19 +586,19 @@ module NetCompatibilityExamples = override this.Height = y override this.Print () = printfn "I'm a Rectangle" - //test - let r = Rectangle(2,3) + // 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. + // Just as in C#, F# can extend existing classes with extension methods. type System.String with member this.StartsWithA = this.StartsWith "A" - //test + // test let s = "Alice" printfn "'%s' starts with an 'A' = %A" s s.StartsWithA diff --git a/git.html.markdown b/git.html.markdown index bedc9853..e7ca07d6 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Leo Rudberg" , "http://github.com/LOZORD"] - ["Betsy Lorton" , "http://github.com/schbetsy"] - ["Bruno Volcov", "http://github.com/volcov"] + - ["Andrew Taylor", "http://github.com/andrewjt71"] filename: LearnGit.txt --- @@ -333,6 +334,9 @@ $ git log --oneline # Show merge commits only $ git log --merges + +# Show all commits represented by an ASCII graph +$ git log --graph ``` ### merge @@ -499,6 +503,16 @@ $ 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. + +```bash +# Revert a specified commit +$ git revert <commit> +``` ### rm diff --git a/go.html.markdown b/go.html.markdown index a857a76c..dc684227 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -108,12 +108,13 @@ can include line breaks.` // Same string type. bs := []byte("a slice") // Type conversion syntax. // Because they are dynamic, slices can be appended to on-demand. - // To append elements to a slice, built-in append() function is used. + // To append elements to a slice, the built-in append() function is used. // First argument is a slice to which we are appending. Commonly, // the array variable is updated in place, as in example below. s := []int{1, 2, 3} // Result is a slice of length 3. s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6. fmt.Println(s) // Updated slice is now [1 2 3 4 5 6] + // To append another slice, instead of list of atomic elements we can // pass a reference to a slice or a slice literal like this, with a // trailing ellipsis, meaning take a slice and unpack its elements, diff --git a/haskell.html.markdown b/haskell.html.markdown index 369b1b20..936744a0 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -81,7 +81,7 @@ not False -- True [5,4..1] -- [5, 4, 3, 2, 1] -- indexing into a list -[0..] !! 5 -- 5 +[1..10] !! 3 -- 4 -- You can also have infinite lists in Haskell! [1..] -- a list of all the natural numbers @@ -195,11 +195,11 @@ foo 5 -- 15 -- function composition -- the (.) function chains functions together. -- For example, here foo is a function that takes a value. It adds 10 to it, --- multiplies the result of that by 5, and then returns the final value. -foo = (*5) . (+10) +-- multiplies the result of that by 4, and then returns the final value. +foo = (*4) . (+10) --- (5 + 10) * 5 = 75 -foo 5 -- 75 +-- (5 + 10) * 4 = 60 +foo 5 -- 60 -- fixing precedence -- Haskell has another operator called `$`. This operator applies a function diff --git a/hu-hu/coffeescript-hu.html.markdown b/hu-hu/coffeescript-hu.html.markdown new file mode 100644 index 00000000..267db4d0 --- /dev/null +++ b/hu-hu/coffeescript-hu.html.markdown @@ -0,0 +1,106 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Tamás Diószegi", "http://github.com/ditam"] +filename: coffeescript-hu.coffee +--- + +A CoffeeScript egy apró nyelv ami egy-az-egyben egyenértékű Javascript kódra fordul, és így futásidőben már nem szükséges interpretálni. +Mint a JavaScript egyik követője, a CoffeeScript mindent megtesz azért, hogy olvasható, jól formázott és jól futó JavaScript kódot állítson elő, ami minden JavaScript futtatókörnyezetben jól működik. + +Rézletekért lásd még a [CoffeeScript weboldalát](http://coffeescript.org/), ahol egy teljes CoffeScript tutorial is található. + +```coffeescript +# A CoffeeScript egy hipszter nyelv. +# Követi több modern nyelv trendjeit. +# Így a kommentek, mint Ruby-ban és Python-ban, a szám szimbólummal kezdődnek. + +### +A komment blokkok ilyenek, és közvetlenül '/ *' és '* /' jelekre fordítódnak +az eredményül kapott JavaScript kódban. + +Mielőtt tovább olvasol, jobb, ha a JavaScript alapvető szemantikájával +tisztában vagy. + +(A kód példák alatt kommentként látható a fordítás után kapott JavaScript kód.) +### + +# Értékadás: +number = 42 #=> var number = 42; +opposite = true #=> var opposite = true; + +# Feltételes utasítások: +number = -42 if opposite #=> if(opposite) { number = -42; } + +# Függvények: +square = (x) -> x * x #=> var square = function(x) { return x * x; } + +fill = (container, liquid = "coffee") -> + "Filling the #{container} with #{liquid}..." +#=>var fill; +# +#fill = function(container, liquid) { +# if (liquid == null) { +# liquid = "coffee"; +# } +# return "Filling the " + container + " with " + liquid + "..."; +#}; + +# Szám tartományok: +list = [1..5] #=> var list = [1, 2, 3, 4, 5]; + +# Objektumok: +math = + root: Math.sqrt + square: square + cube: (x) -> x * square x +#=> var math = { +# "root": Math.sqrt, +# "square": square, +# "cube": function(x) { return x * square(x); } +# }; + +# "Splat" jellegű függvény-paraméterek: +race = (winner, runners...) -> + print winner, runners +#=>race = function() { +# var runners, winner; +# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(winner, runners); +# }; + +# Létezés-vizsgálat: +alert "I knew it!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } + +# Tömb értelmezések: (array comprehensions) +cubes = (math.cube num for num in list) +#=>cubes = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = list.length; _i < _len; _i++) { +# num = list[_i]; +# _results.push(math.cube(num)); +# } +# return _results; +# })(); + +foods = ['broccoli', 'spinach', 'chocolate'] +eat food for food in foods when food isnt 'chocolate' +#=>foods = ['broccoli', 'spinach', 'chocolate']; +# +#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) { +# food = foods[_k]; +# if (food !== 'chocolate') { +# eat(food); +# } +#} +``` + +## További források + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read)
\ No newline at end of file diff --git a/hu-hu/go.html.markdown b/hu-hu/go-hu.html.markdown index 638c9489..638c9489 100644 --- a/hu-hu/go.html.markdown +++ b/hu-hu/go-hu.html.markdown diff --git a/hu-hu/ruby.html.markdown b/hu-hu/ruby-hu.html.markdown index 169f2b8e..169f2b8e 100644 --- a/hu-hu/ruby.html.markdown +++ b/hu-hu/ruby-hu.html.markdown diff --git a/id-id/xml-id.html.markdown b/id-id/xml-id.html.markdown index c1e985aa..8b8d72ae 100644 --- a/id-id/xml-id.html.markdown +++ b/id-id/xml-id.html.markdown @@ -1,6 +1,6 @@ --- language: xml -filename: learnxml.xml +filename: learnxml-id.xml contributors: - ["João Farias", "https://github.com/JoaoGFarias"] translators: diff --git a/java.html.markdown b/java.html.markdown index c2c1a18b..84978ecc 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -7,6 +7,7 @@ contributors: - ["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 --- @@ -127,7 +128,7 @@ public class LearnJava { // // BigInteger can be initialized using an array of bytes or a string. - BigInteger fooBigInteger = new BigDecimal(fooByteArray); + BigInteger fooBigInteger = new BigInteger(fooByteArray); // BigDecimal - Immutable, arbitrary-precision signed decimal number @@ -137,13 +138,18 @@ public class LearnJava { // // BigDecimal allows the programmer complete control over decimal // rounding. It is recommended to use BigDecimal with currency values - // and where exact decimal percision is required. + // and where exact decimal precision is required. // // BigDecimal can be initialized with an int, long, double or String // or by initializing the unscaled value (BigInteger) and scale (int). BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); - + + // Be wary of the constructor that takes a float or double as + // the inaccuracy of the float/double will be copied in BigDecimal. + // Prefer the String constructor when you need an exact value. + + BigDecimal tenCents = new BigDecimal("0.1"); // Strings @@ -184,8 +190,12 @@ public class LearnJava { // LinkedLists - Implementation of doubly-linked list. All of the // operations perform as could be expected for a // doubly-linked list. - // Maps - A set of objects that maps keys to values. A map cannot - // contain duplicate keys; each key can map to at most one value. + // Maps - A set of objects that map keys to values. Map is + // an interface and therefore cannot be instantiated. + // The type of keys and values contained in a Map must + // be specified upon instantiation of the implementing + // class. Each key may map to only one corresponding value, + // and each key may appear only once (no duplicates). // HashMaps - This class uses a hashtable to implement the Map // interface. This allows the execution time of basic // operations, such as get and insert element, to remain @@ -202,8 +212,8 @@ public class LearnJava { 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 truncated down) - System.out.println("1/2 = " + (i1 / (i2*1.0))); // => 0.5 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns an int) + System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 // Modulo System.out.println("11%3 = "+(11 % 3)); // => 2 @@ -411,7 +421,7 @@ public class LearnJava { // easier way, by using something that is called Double Brace // Initialization. - private static final Set<String> COUNTRIES = HashSet<String>() {{ + private static final Set<String> COUNTRIES = new HashSet<String>() {{ add("DENMARK"); add("SWEDEN"); add("FINLAND"); @@ -445,6 +455,17 @@ class Bicycle { protected int gear; // Protected: Accessible from the class and subclasses String name; // default: Only accessible from within this package + static String className; // Static class variable + + // Static block + // Java has no implementation of static constructors, but + // has a static block that can be used to initialize class variables + // (static variables). + // This block will be called when the class is loaded. + static { + className = "Bicycle"; + } + // Constructors are a way of creating classes // This is a constructor public Bicycle() { @@ -681,6 +702,66 @@ public abstract class Mammal() return true; } } + + +// Enum Type +// +// An enum type is a special data type that enables for a variable to be a set +// of predefined constants. The variable must be equal to one of the values that +// have been predefined for it. Because they are constants, the names of an enum +// type's fields are in uppercase letters. In the Java programming language, you +// define an enum type by using the enum keyword. For example, you would specify +// a days-of-the-week enum type as: + +public enum Day { + SUNDAY, MONDAY, TUESDAY, WEDNESDAY, + THURSDAY, FRIDAY, SATURDAY +} + +// We can use our enum Day like that: + +public class EnumTest { + + // Variable 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 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 + ``` ## Further Reading @@ -704,7 +785,7 @@ The links provided here below are just to get an understanding of the topic, fee * [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) -* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) **Online Practice and Tutorials** diff --git a/javascript.html.markdown b/javascript.html.markdown index 9c4f06fc..98261334 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -16,13 +16,14 @@ JavaScript isn't just limited to web browsers, though: Node.js, a project that provides a standalone runtime for Google Chrome's V8 JavaScript engine, is becoming more and more popular. -Feedback would be highly appreciated! You can reach me at -[@adambrenecki](https://twitter.com/adambrenecki), or -[adam@brenecki.id.au](mailto:adam@brenecki.id.au). +JavaScript has a C-like syntax, so if you've used languages like C or Java, +a lot of the basic syntax will already be familiar. Despite this, and despite +the similarity in name, JavaScript's object model is significantly different to +Java's. ```js -// Comments are like C. Single-line comments start with two slashes, -/* and multiline comments start with slash-star +// Single-line comments start with two slashes. +/* Multiline comments start with slash-star, and end with star-slash */ // Statements can be terminated by ; @@ -40,7 +41,7 @@ doStuff() // JavaScript has one number type (which is a 64-bit IEEE 754 double). // Doubles have a 52-bit mantissa, which is enough to store integers -// up to about 9✕10¹⁵ precisely. +// up to about 9✕10¹⁵ precisely. 3; // = 3 1.5; // = 1.5 @@ -100,6 +101,10 @@ false; // Strings are concatenated with + "Hello " + "world!"; // = "Hello world!" +// ... which works with more than just strings +"1, 2, " + 3; // = "1, 2, 3" +"Hello " + ["world", "!"] // = "Hello world,!" + // and are compared with < and > "a" < "b"; // = true @@ -140,7 +145,7 @@ undefined; // used to indicate a value is not currently present (although // character. var someVar = 5; -// if you leave the var keyword off, you won't get an error... +// If you leave the var keyword off, you won't get an error... someOtherVar = 10; // ...but your variable will be created in the global scope, not in the scope @@ -149,6 +154,10 @@ someOtherVar = 10; // Variables declared without being assigned to are set to undefined. var someThirdVar; // = undefined +// If you want to declare a couple of variables, then you could use a comma +// separator +var someFourthVar = 2, someFifthVar = 4; + // There's shorthand for performing math operations on variables: someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now someVar *= 10; // now someVar is 100 @@ -194,8 +203,6 @@ myObj.myFourthKey; // = undefined /////////////////////////////////// // 3. Logic and Control Structures -// The syntax for this section is almost identical to Java's. - // The `if` structure works as you'd expect. var count = 1; if (count == 3){ @@ -223,15 +230,15 @@ for (var i = 0; i < 5; i++){ // will run 5 times } -//The For/In statement loops iterates over every property across the entire prototype chain +// The for/in statement iterates over every property across the entire prototype chain. var description = ""; var person = {fname:"Paul", lname:"Ken", age:18}; for (var x in person){ description += person[x] + " "; } -//If only want to consider properties attached to the object itself, -//and not its prototypes use hasOwnProperty() check +// To only consider properties attached to the object itself +// and not its prototypes, use the `hasOwnProperty()` check. var description = ""; var person = {fname:"Paul", lname:"Ken", age:18}; for (var x in person){ @@ -240,8 +247,9 @@ for (var x in person){ } } -//for/in should not be used to iterate over an Array where the index order is important. -//There is no guarantee that for/in will return the indexes in any particular order +// For/in should not be used to iterate over an Array where the index order +// is important, as there is no guarantee that for/in will return the indexes +// in any particular order. // && is logical and, || is logical or if (house.size == "big" && house.colour == "blue"){ @@ -256,7 +264,7 @@ var name = otherName || "default"; // The `switch` statement checks for equality with `===`. -// use 'break' after each case +// Use 'break' after each case // or the cases after the correct one will be executed too. grade = 'B'; switch (grade) { @@ -287,12 +295,9 @@ myFunction("foo"); // = "FOO" // Note that the value to be returned must start on the same line as the // `return` keyword, otherwise you'll always return `undefined` due to // automatic semicolon insertion. Watch out for this when using Allman style. -function myFunction() -{ +function myFunction(){ return // <- semicolon automatically inserted here - { - thisIsAn: 'object literal' - } + {thisIsAn: 'object literal'} } myFunction(); // = undefined @@ -306,6 +311,12 @@ setTimeout(myFunction, 5000); // Note: setTimeout isn't part of the JS language, but is provided by browsers // and Node.js. +// Another function provided by browsers is setInterval +function myFunction(){ + // this code will be called every 5 seconds +} +setInterval(myFunction, 5000); + // Function objects don't even have to be declared with a name - you can write // an anonymous function definition directly into the arguments of another. setTimeout(function(){ @@ -500,6 +511,10 @@ myNumber === myNumberObj; // = false if (0){ // This code won't execute, because 0 is falsy. } +if (new Number(0)){ + // This code will execute, because wrapped numbers are objects, and objects + // are always truthy. +} // However, the wrapper objects and the regular builtins share a prototype, so // you can actually add functionality to a string, for instance. @@ -527,28 +542,42 @@ if (Object.create === undefined){ // don't overwrite it if it exists ## Further Reading -The [Mozilla Developer -Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides -excellent documentation for JavaScript as it's used in browsers. Plus, it's a -wiki, so as you learn more you can help others out by sharing your own -knowledge. +The [Mozilla Developer Network][1] provides excellent documentation for +JavaScript as it's used in browsers. Plus, it's a wiki, so as you learn more you +can help others out by sharing your own knowledge. + +MDN's [A re-introduction to JavaScript][2] covers much of the concepts covered +here in more detail. This guide has quite deliberately only covered the +JavaScript language itself; if you want to learn more about how to use +JavaScript in web pages, start by learning about the [Document Object Model][3]. + +[Learn Javascript by Example and with Challenges][4] is a variant of this +reference with built-in challenges. + +[JavaScript Garden][5] is an in-depth guide of all the counter-intuitive parts +of the language. + +[JavaScript: The Definitive Guide][6] is a classic guide and reference book. + +[Eloquent Javascript][8] by Marijn Haverbeke is an excellent JS book/ebook with attached terminal + +[Eloquent Javascript - The Annotated Version][9] by Gordon Zhu is also a great derivative of Eloquent Javascript with extra explanations and clarifications for some of the more complicated examples. -MDN's [A re-introduction to -JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -covers much of the concepts covered here in more detail. This guide has quite -deliberately only covered the JavaScript language itself; if you want to learn -more about how to use JavaScript in web pages, start by learning about the -[Document Object -Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) +[Javascript: The Right Way][10] is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices. -[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth -guide of all the counter-intuitive parts of the language. +In addition to direct contributors to this article, some content is adapted from +Louie Dinh's Python tutorial on this site, and the [JS Tutorial][7] on the +Mozilla Developer Network. -[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book. -In addition to direct contributors to this article, some content is adapted -from Louie Dinh's Python tutorial on this site, and the [JS -Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -on the Mozilla Developer Network. +[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://watchandcode.com/courses/eloquent-javascript-the-annotated-version +[10]: http://jstherightway.org/ diff --git a/json.html.markdown b/json.html.markdown index 060e9c3d..cde7bc40 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -5,22 +5,30 @@ contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] - ["himanshu", "https://github.com/himanshu81494"] + - ["Michael Neth", "https://github.com/infernocloud"] --- -As JSON is an extremely simple data-interchange format, this is most likely going -to be the simplest Learn X in Y Minutes ever. +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. Some parsers also tolerate a trailing comma -(i.e. a comma after the last element of an array or the after the last property of an object), -but they should be avoided for better compatibility. +JSON in its purest form has no actual comments, but most parsers will accept C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma (i.e. a comma after the last element of an array or the after the last property of an object), but they should be avoided for better compatibility. For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself. -Data types supported by JSON includes: numbers, string, boolean, array, object and null. -Supporting browsers are: Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4. -JSON file type for JSON files is ".json". The MIME type for JSON text is "application/json" -Drawbacks of JSON include lack of type definition and some sort of DTD. +A JSON value must be a number, a string, an array, an object, or one of the following 3 literal names: true, false, null. + +Supporting browsers are: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, and Safari 4.0+. + +File extension for JSON files is ".json" and the MIME type for JSON text is "application/json". + +Many programming languages have support for serializing (encoding) and unserializing (decoding) JSON data into native data structures. Javascript has implicit support for manipulating JSON text as data. + +More information can be found at http://www.json.org/ + +JSON is built on two structures: +* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. +* An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence. + +An object with various name/value pairs. ```json { @@ -60,8 +68,18 @@ Drawbacks of JSON include lack of type definition and some sort of DTD. "comment": "check this out!" , "comma position": "doesn't matter - as long as it's before the next key, then it's valid" , "another comment": "how nice" - }, - - "that was short": "And, you're done. You now know everything JSON has to offer." + } } ``` + +A single array of values by itself is also valid JSON. + +```json +[1, 2, 3, "text", true] +``` + +Objects can be a part of the array as well. + +```json +[{"name": "Bob", "age": 25}, {"name": "Jane", "age": 29}, {"name": "Jack", "age": 31}] +``` diff --git a/julia.html.markdown b/julia.html.markdown index c5089dc3..cba7cd45 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -117,11 +117,11 @@ catch e println(e) end -# Variable names start with a letter. +# Variable names start with a letter or underscore. # After that, you can use letters, digits, underscores, and exclamation points. SomeOtherVar123! = 6 # => 6 -# You can also use unicode characters +# You can also use certain unicode characters ☃ = 8 # => 8 # These are especially handy for mathematical notation 2 * π # => 6.283185307179586 diff --git a/latex.html.markdown b/latex.html.markdown index 9b7b4feb..31231a70 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -106,6 +106,9 @@ Here's how you state all y that belong to X, $\forall$ x $\in$ X. \\ % However, the math symbols only exist in math-mode. % We can enter math-mode from text mode with the $ signs. % The opposite also holds true. Variable can also be rendered in math-mode. +% We can also enter math mode with \[\] + +\[a^2 + b^2 = c^2 \] My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. I haven't found a Greek letter that yet that LaTeX doesn't know about! diff --git a/lua.html.markdown b/lua.html.markdown index 0809215f..3d95c146 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 --- behavior. Later we'll see how metatables support js-prototypey behavior. +-- behavior. Later we'll see how metatables support js-prototypey behaviour. f1 = {a = 1, b = 2} -- Represents the fraction a/b. f2 = {a = 2, b = 3} diff --git a/make.html.markdown b/make.html.markdown index 563139d1..e8cfd2b5 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -234,10 +234,8 @@ bar = 'hello' endif
```
-
### More Resources
+ [gnu make documentation](https://www.gnu.org/software/make/manual/)
+ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/)
+ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)
-
diff --git a/markdown.html.markdown b/markdown.html.markdown index 2333110f..b956a5f2 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -11,7 +11,7 @@ Give me as much feedback as you want! / Feel free to fork and pull request! ```markdown -<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown, that +<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown. This means we can use HTML elements in Markdown, such as the comment element, and they won't be affected by a markdown parser. However, if you create an HTML element in your markdown file, you cannot use markdown syntax within that @@ -21,9 +21,9 @@ element's contents. --> guide will attempt to clarify when features are universal or when they are specific to a certain parser. --> -<!-- Headers --> +<!-- Headings --> <!-- You can create HTML elements <h1> through <h6> easily by prepending the -text you want to be in that element by a number of hashes (#) --> +text you want to be in that element by a number of hashes (#). --> # This is an <h1> ## This is an <h2> ### This is an <h3> @@ -31,7 +31,7 @@ text you want to be in that element by a number of hashes (#) --> ##### This is an <h5> ###### This is an <h6> -<!-- Markdown also provides us with two alternative ways of indicating h1 and h2 --> +<!-- Markdown also provides us with two alternative ways of indicating h1 and h2. --> This is an h1 ============= @@ -39,7 +39,7 @@ This is an h2 ------------- <!-- Simple text styles --> -<!-- Text can be easily styled as italic or bold using markdown --> +<!-- Text can be easily styled as italic or bold using markdown. --> *This text is in italics.* _And so is this text._ @@ -85,7 +85,7 @@ There's a <br /> above me! > How neat is that? <!-- Lists --> -<!-- Unordered lists can be made using asterisks, pluses, or hyphens --> +<!-- Unordered lists can be made using asterisks, pluses, or hyphens. --> * Item * Item @@ -103,21 +103,21 @@ or - Item - One last item -<!-- Ordered lists are done with a number followed by a period --> +<!-- Ordered lists are done with a number followed by a period. --> 1. Item one 2. Item two 3. Item three <!-- You don't even have to label the items correctly and markdown will still -render the numbers in order, but this may not be a good idea --> +render the numbers in order, but this may not be a good idea. --> 1. Item one 1. Item two 1. Item three <!-- (This renders the same as the above example) --> -<!-- You can also use sublists --> +<!-- You can also use sublists. --> 1. Item one 2. Item two @@ -136,13 +136,13 @@ This checkbox below will be a checked HTML checkbox. <!-- Code blocks --> <!-- You can indicate a code block (which uses the <code> element) by indenting -a line with four spaces or a tab --> +a line with four spaces or a tab. --> This is code So is this <!-- You can also re-tab (or add an additional four spaces) for indentation -inside your code --> +inside your code. --> my_array.each do |item| puts item @@ -152,7 +152,7 @@ inside your code --> John didn't even know what the `go_to()` function did! -<!-- In Github Flavored Markdown, you can use a special syntax for code --> +<!-- In Github Flavored Markdown, you can use a special syntax for code. --> \`\`\`ruby <!-- except remove those backslashes when you do this, just ```ruby ! --> def foobar @@ -174,11 +174,11 @@ with or without spaces. --> <!-- Links --> <!-- One of the best things about markdown is how easy it is to make links. Put -the text to display in hard brackets [] followed by the url in parentheses () --> +the text to display in hard brackets [] followed by the url in parentheses (). --> [Click me!](http://test.com/) -<!-- You can also add a link title using quotes inside the parentheses --> +<!-- You can also add a link title using quotes inside the parentheses. --> [Click me!](http://test.com/ "Link to Test.com") @@ -186,7 +186,7 @@ the text to display in hard brackets [] followed by the url in parentheses () -- [Go to music](/music/). -<!-- Markdown also supports reference style links --> +<!-- Markdown also supports reference style links. --> [Click this link][link1] for more info about it! [Also check out this link][foobar] if you want to. @@ -198,7 +198,7 @@ the text to display in hard brackets [] followed by the url in parentheses () -- entirely. The references can be anywhere in your document and the reference IDs can be anything so long as they are unique. --> -<!-- There is also "implicit naming" which lets you use the link text as the id --> +<!-- There is also "implicit naming" which lets you use the link text as the id. --> [This][] is a link. @@ -211,7 +211,7 @@ can be anything so long as they are unique. --> ![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title") -<!-- And reference style works as expected --> +<!-- And reference style works as expected. --> ![This is the alt-attribute.][myimage] @@ -233,7 +233,7 @@ I want to type *this text surrounded by asterisks* but I don't want it to be in italics, so I do this: \*this text surrounded by asterisks\*. <!-- Keyboard keys --> -<!-- In Github Flavored Markdown, you can use a <kbd> tag to represent keyboard keys --> +<!-- In Github Flavored Markdown, you can use a <kbd> tag to represent keyboard keys. --> Your computer crashed? Try sending a <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd> diff --git a/matlab.html.markdown b/matlab.html.markdown index 0cbc6f57..25f762bb 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -1,10 +1,11 @@ --- language: Matlab +filename: learnmatlab.mat contributors: - ["mendozao", "http://github.com/mendozao"] - ["jamesscottbrown", "http://jamesscottbrown.com"] - ["Colton Kohnke", "http://github.com/voltnor"] - + - ["Claudson Martins", "http://github.com/claudsonm"] --- MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics. @@ -14,6 +15,7 @@ If you have any feedback please feel free to reach me at [osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). ```matlab +%% Code sections start with two percent signs. Section titles go on the same line. % Comments start with a percent sign. %{ @@ -122,6 +124,7 @@ x(2:end) % ans = 32 53 7 1 x = [4; 32; 53; 7; 1] % Column vector x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 +x = [1:2:10] % Increment by 2, i.e. x = 1 3 5 7 9 % Matrices A = [1 2 3; 4 5 6; 7 8 9] @@ -204,6 +207,8 @@ transpose(A) % Transpose the matrix, which is the same as: A one ctranspose(A) % Hermitian transpose the matrix % (the transpose, followed by taking complex conjugate of each element) +A' % Concise version of complex transpose +A.' % Concise version of transpose (without taking complex conjugate) @@ -253,6 +258,8 @@ axis equal % Set aspect ratio so data units are the same in every direction scatter(x, y); % Scatter-plot hist(x); % Histogram +stem(x); % Plot values as stems, useful for displaying discrete data +bar(x); % Plot bar graph z = sin(x); plot3(x,y,z); % 3D line plot @@ -261,7 +268,7 @@ pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value contour(A) % Contour plot of matrix mesh(A) % Plot as a mesh surface -h = figure % Create new figure object, with handle f +h = figure % Create new figure object, with handle h figure(h) % Makes the figure corresponding to handle h the current figure close(h) % close figure with handle h close all % close all open figure windows @@ -329,7 +336,7 @@ double_input(6) % ans = 12 % anonymous function. Useful when quickly defining a function to pass to % another function (eg. plot with fplot, evaluate an indefinite integral % with quad, find roots with fzero, or find minimum with fminsearch). -% Example that returns the square of it's input, assigned to to the handle sqr: +% Example that returns the square of it's input, assigned to the handle sqr: sqr = @(x) x.^2; sqr(10) % ans = 100 doc function_handle % find out more @@ -399,7 +406,7 @@ exp(x) sqrt(x) log(x) log10(x) -abs(x) +abs(x) %If x is complex, returns magnitude min(x) max(x) ceil(x) @@ -410,6 +417,14 @@ rand % Uniformly distributed pseudorandom numbers randi % Uniformly distributed pseudorandom integers randn % Normally distributed pseudorandom numbers +%Complex math operations +abs(x) % Magnitude of complex variable x +phase(x) % Phase (or angle) of complex variable x +real(x) % Returns the real part of x (i.e returns a if x = a +jb) +imag(x) % Returns the imaginary part of x (i.e returns b if x = a+jb) +conj(x) % Returns the complex conjugate + + % Common constants pi NaN @@ -459,11 +474,14 @@ length % length of a vector sort % sort in ascending order sum % sum of elements prod % product of elements -mode % modal value +mode % modal value median % median value mean % mean value std % standard deviation perms(x) % list all permutations of elements of x +find(x) % Finds all non-zero elements of x and returns their indexes, can use comparison operators, + % i.e. find( x == 3 ) returns indexes of elements that are equal to 3 + % i.e. find( x >= 3 ) returns indexes of elements greater than or equal to 3 % Classes diff --git a/ms-my/coffeescript-my.html.markdown b/ms-my/coffeescript-my.html.markdown new file mode 100644 index 00000000..9820a561 --- /dev/null +++ b/ms-my/coffeescript-my.html.markdown @@ -0,0 +1,105 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +filename: coffeescript-ms.coffee +translators: + - ["hack1m", "https://github.com/hack1m"] +lang: ms-my +--- + +CoffeeScript adalah bahasa kecil yang menyusun/kompil satu-per-satu menjadi setara JavaScript, dan tidak ada interpretasi di runtime. +Sebagai salah satu pengganti kepada JavaScript, CoffeeScript mencuba yang terbaik untuk output kod JavaScript yang mudah dibaca, cantik-dicetak dan berfungsi lancar, yang mana berfungsi baik pada setiap runtime JavaScript. + +Lihat juga [Laman sesawang CoffeeScript](http://coffeescript.org/), yang mana ada tutorial lengkap untuk CoffeeScript. + +```coffeescript +# CoffeeScript adalah bahasa hipster. +# Ia beredar mengikut trend kebanyakkan bahasa moden. +# Jadi komen sama seperti Ruby dan Python, ia menggunakan simbol nombor. + +### +Blok komen seperti ini, dan ia terjemah terus ke '/ *'s dan '* /'s +untuk keputusan kod JavaScript. + +Sebelum meneruskan anda perlu faham kebanyakkan daripada +JavaScript adalah semantik. +### + +# Menetapkan: +number = 42 #=> var number = 42; +opposite = true #=> var opposite = true; + +# Bersyarat: +number = -42 if opposite #=> if(opposite) { number = -42; } + +# Fungsi: +square = (x) -> x * x #=> var square = function(x) { return x * x; } + +fill = (container, liquid = "coffee") -> + "Filling the #{container} with #{liquid}..." +#=>var fill; +# +#fill = function(container, liquid) { +# if (liquid == null) { +# liquid = "coffee"; +# } +# return "Filling the " + container + " with " + liquid + "..."; +#}; + +# Julat: +list = [1..5] #=> var list = [1, 2, 3, 4, 5]; + +# Objek: +math = + root: Math.sqrt + square: square + cube: (x) -> x * square x +#=> var math = { +# "root": Math.sqrt, +# "square": square, +# "cube": function(x) { return x * square(x); } +# }; + +# Splats: +race = (winner, runners...) -> + print winner, runners +#=>race = function() { +# var runners, winner; +# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(winner, runners); +# }; + +# Kewujudan: +alert "I knew it!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } + +# Pemahaman array: +cubes = (math.cube num for num in list) +#=>cubes = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = list.length; _i < _len; _i++) { +# num = list[_i]; +# _results.push(math.cube(num)); +# } +# return _results; +# })(); + +foods = ['broccoli', 'spinach', 'chocolate'] +eat food for food in foods when food isnt 'chocolate' +#=>foods = ['broccoli', 'spinach', 'chocolate']; +# +#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) { +# food = foods[_k]; +# if (food !== 'chocolate') { +# eat(food); +# } +#} +``` + +## Sumber tambahan + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) diff --git a/ms-my/javascript-my.html.markdown b/ms-my/javascript-my.html.markdown new file mode 100644 index 00000000..90e37133 --- /dev/null +++ b/ms-my/javascript-my.html.markdown @@ -0,0 +1,588 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +filename: javascript-ms.js +translators: + - ["abdalim", "https://github.com/abdalim"] +lang: ms-my +--- + +Javascript dicipta oleh Brendan Eich dari Netscape pada 1995. Pada awalnya, ia +dicipta sebagai bahasa skrip yang ringkas untuk laman web, melengkapi penggunaan +Java untuk aplikasi web yang lebih rumit, namun begitu, integrasi rapat pada +halaman web dan sokongan tersedia dalam pelayar web telah menyebabkan ia menjadi +lebih kerap digunakan berbanding Java pada bahagian hadapan laman web. + +Namun begitu, Javascript tidak terhad pada pelayar web; Node.js, sebuah projek +yang menyediakan 'runtime' berdiri sendiri untuk enjin V8 Google Chrome sedang +kian mendapat sambutan yang hangat. + +```js +// Komentar adalah seperti dalam C. Komentar sebaris bermula dengan dua sengkang +/* dan komentar banyak baris bermula dengan sengkang-bintang + dan berakhir dengan bintang-sengkang */ + +// Pernyataan boleh ditamatkan dengan ';' +doStuff(); + +// ... tetapi ia tidak wajib, kerana koma bertitik secara automatik akan +// dimasukkan dimana tempat yang ada baris baru, kecuali dalam kes - kes +// tertentu. +doStuff() + +// Disebabkan kes - kes itu boleh menyebabkan hasil yang tidak diduga, kami +// akan sentiasa menggunakan koma bertitik dalam panduan ini. + +/////////////////////////////////// +// 1. Nombor, String dan Operator + +// Javascript mempunyai satu jenis nombor (iaitu 64-bit IEEE 754 double). +// Double mempunyai 52-bit mantissa, iaitu ia cukup untuk menyimpan integer +// sehingga 9✕10¹⁵ secara tepatnya. +3; // = 3 +1.5; // = 1.5 + +// Sebahagian aritmetic asas berfungsi seperti yang anda jangkakan. +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// Termasuk pembahagian tidak rata. +5 / 2; // = 2.5 + +// Dan pembahagian modulo. +10 % 2; // = 0 +30 % 4; // = 2 +18.5 % 7; // = 4.5 + +// Operasi bitwise juga boleh digunakan; bila anda melakukan operasi bitwise, +// float anda akan ditukarkan kepada int bertanda *sehingga* 32 bit. +1 << 2; // = 4 + +// Keutamaan ditekankan menggunakan kurungan. +(1 + 3) * 2; // = 8 + +// Terdapat tiga nilai nombor-tidak-nyata istimewa +Infinity; // hasil operasi seperti 1/0 +-Infinity; // hasil operasi seperti -1/0 +NaN; // hasil operasi seperti 0/0, bermaksud 'Bukan Sebuah Nombor' + +// Terdapat juga jenis boolean +true; +false; + +// Talian dicipta dengan ' atau ''. +'abc'; +"Hello, world"; + +// Penafian menggunakan simbol ! +!true; // = tidak benar +!false; // = benar + +// Sama ialah === +1 === 1; // = benar +2 === 1; // = tidak benar + +// Tidak sama ialah !== +1 !== 1; // = tidak benar +2 !== 1; // = benar + +// Lagi perbandingan +1 < 10; // = benar +1 > 10; // = tidak benar +2 <= 2; // = benar +2 >= 2; // = benar + +// Talian disambungkan dengan + +"Hello " + "world!"; // = "Hello world!" + +// dan dibandingkan dengan < dan > +"a" < "b"; // = benar + +// Paksaan jenis dilakukan untuk perbandingan menggunakan dua sama dengan... +"5" == 5; // = benar +null == undefined; // = benar + +// ...melainkan anda menggunakan === +"5" === 5; // = tidak benar +null === undefined; // = tidak benar + +// ...yang boleh menghasilkan keputusan yang pelik... +13 + !0; // 14 +"13" + !0; // '13true' + +// Anda boleh akses huruf dalam perkataan dengan `charAt` +"This is a string".charAt(0); // = 'T' + +// ...atau menggunakan `substring` untuk mendapatkan bahagian yang lebih besar. +"Hello world".substring(0, 5); // = "Hello" + +// `length` adalah ciri, maka jangan gunakan (). +"Hello".length; // = 5 + +// Selain itu, terdapat juga `null` dan `undefined`. +null; // digunakan untuk menandakan bukan-nilai yang disengajakan +undefined; // digunakan untuk menandakan nilai yang tidak wujud pada waktu ini (walaupun `undefined` adalah nilai juga) + +// false, null, undefined, NaN, 0 dan "" adalah tidak benar; semua selain itu adalah benar. +// Peringatan, 0 adalah tidak benar dan "0" adalah benar, walaupun 0 == "0". + +/////////////////////////////////// +// 2. Pembolehubah, Array dan Objek + +// Pembolehubah digunakan dengan kata kunci 'var'. Javascript ialah sebuah +// bahasa aturcara yang jenisnya dinamik, maka anda tidak perlu spesifikasikan +// jenis pembolehubah. Penetapan menggunakan satu '=' karakter. +var someVar = 5; + +// jika anda tinggalkan kata kunci var, anda tidak akan dapat ralat... +someOtherVar = 10; + +// ...tetapi pembolehubah anda akan dicipta di dalam skop global, bukan di +// dalam skop anda menciptanya. + +// Pembolehubah yang dideklarasikan tanpa ditetapkan sebarang nilai akan +// ditetapkan kepada undefined. +var someThirdVar; // = undefined + +// jika anda ingin mendeklarasikan beberapa pembolehubah, maka anda boleh +// menggunakan koma sebagai pembahagi +var someFourthVar = 2, someFifthVar = 4; + +// Terdapat cara mudah untuk melakukan operasi - operasi matematik pada +// pembolehubah: +someVar += 5; // bersamaan dengan someVar = someVar +5; someVar sama dengan 10 sekarang +someVar *= 10; // sekarang someVar bernilai 100 + +// dan cara lebih mudah untuk penambahan atau penolakan 1 +someVar++; // sekarang someVar ialah 101 +someVar--; // kembali kepada 100 + +// Array adalah senarai nilai yang tersusun, yang boleh terdiri daripada +// pembolehubah pelbagai jenis. +var myArray = ["Hello", 45, true]; + +// Setiap ahli array boleh diakses menggunakan syntax kurungan-petak. +// Indeks array bermula pada sifar. +myArray[1]; // = 45 + +// Array boleh diubah dan mempunyai panjang yang tidak tetap dan boleh ubah. +myArray.push("World"); +myArray.length; // = 4 + +// Tambah/Ubah di index yang spesifik +myArray[3] = "Hello"; + +// Objek javascript adalah sama dengan "dictionaries" atau "maps" dalam bahasa +// aturcara yang lain: koleksi pasangan kunci-nilai yang tidak mempunyai +// sebarang susunan. +var myObj = {key1: "Hello", key2: "World"}; + +// Kunci adalah string, tetapi 'quote' tidak diperlukan jika ia adalah pengecam +// javascript yang sah. Nilai boleh mempunyai sebarang jenis. +var myObj = {myKey: "myValue", "my other key": 4}; + +// Ciri - ciri objek boleh juga diakses menggunakan syntax subskrip (kurungan- +// petak), +myObj["my other key"]; // = 4 + +// ... atau menggunakan syntax titik, selagi kuncinya adalah pengecam yang sah. +myObj.myKey; // = "myValue" + +// Objek adalah boleh diubah; nilai boleh diubah dan kunci baru boleh ditambah. +myObj.myThirdKey = true; + +// Jika anda cuba untuk akses nilai yang belum ditetapkan, anda akan mendapat +// undefined. +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. Logik dan Struktur Kawalan + +// Syntax untuk bahagian ini adalah hampir sama dengan Java. + +// Struktur `if` berfungsi seperti yang anda jangkakan. +var count = 1; +if (count == 3){ + // dinilai jika count ialah 3 +} else if (count == 4){ + // dinilai jika count ialah 4 +} else { + // dinilai jika count bukan 3 atau 4 +} + +// Sama juga dengan `while`. +while (true){ + // Sebuah ulangan yang tidak terhingga! + // An infinite loop! +} + +// Ulangan do-while adalah sama dengan ulangan while, kecuali ia akan diulang +// sekurang-kurangnya sekali. +var input; +do { + input = getInput(); +} while (!isValid(input)) + +// Ulangan `for` adalah sama dengan C dan Java: +// Persiapan; kondisi untuk bersambung; pengulangan. +for (var i = 0; i < 5; i++){ + // akan berulang selama 5 kali +} + +// Pernyataan ulangan For/In akan mengulang setiap ciri seluruh jaringan +// 'prototype' +var description = ""; +var person = {fname:"Paul", lname:"Ken", age:18}; +for (var x in person){ + description += person[x] + " "; +} + +// Jika anda cuma mahu mengambil kira ciri - ciri yang ditambah pada objek it +// sendiri dan bukan 'prototype'nya, sila gunakan semakan hasOwnProperty() +var description = ""; +var person = {fname:"Paul", lname:"Ken", age:18}; +for (var x in person){ + if (person.hasOwnProperty(x)){ + description += person[x] + " "; + } +} + +// for/in tidak sepatutnya digunakan untuk mengulang sebuah Array di mana +// indeks susunan adalah penting. +// Tiada sebarang jaminan bahawa for/in akan mengembalikan indeks dalam +// mana - mana susunan + +// && adalah logikal dan, || adalah logikal atau +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear"; +} +if (colour == "red" || colour == "blue"){ + // warna adalah sama ada 'red' atau 'blue' +} + +// && dan || adalah "lintar pintas", di mana ia berguna untuk menetapkan +// nilai asal. +var name = otherName || "default"; + + +// Pernyataan `switch` menyemak persamaan menggunakan `===`. +// gunakan pernyataan `break` selepas setiap kes +// atau tidak, kes - kes selepas kes yang betul akan dijalankan juga. +grade = 'B'; +switch (grade) { + case 'A': + console.log("Great job"); + break; + case 'B': + console.log("OK job"); + break; + case 'C': + console.log("You can do better"); + break; + default: + console.log("Oy vey"); + break; +} + + +/////////////////////////////////// +// 4. Functions, Skop dan Closures + +// Function javascript dideklarasikan dengan kata kunci `function`. +function myFunction(thing){ + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +// Perhatikan yang nilai yang dikembalikan mesti bermula pada baris yang sama +// dengan kata kunci `return`, jika tidak, anda akan sentiasa mengembalikan +// `undefined` disebabkan kemasukan 'semicolon' secara automatik. Sila berjaga - +// jaga dengan hal ini apabila menggunakan Allman style. +function myFunction(){ + return // <- semicolon dimasukkan secara automatik di sini + {thisIsAn: 'object literal'} +} +myFunction(); // = undefined + +// Function javascript adalah objek kelas pertama, maka ia boleh diberikan +// nama pembolehubah yang lain dan diberikan kepada function yang lain sebagai +// input - sebagai contoh, apabila membekalkan pengendali event: +function myFunction(){ + // kod ini akan dijalankan selepas 5 saat +} +setTimeout(myFunction, 5000); +// Nota: setTimeout bukan sebahagian daripada bahasa JS, tetapi ia disediakan +// oleh pelayar web dan Node.js. + +// Satu lagi function yang disediakan oleh pelayar web adalah setInterval +function myFunction(){ + // kod ini akan dijalankan setiap 5 saat +} +setInterval(myFunction, 5000); + +// Objek function tidak perlu dideklarasikan dengan nama - anda boleh menulis +// function yang tidak bernama didalam input sebuah function lain. +setTimeout(function(){ + // kod ini akan dijalankan dalam 5 saat +}, 5000); + +// Javascript mempunyai skop function; function mempunyai skop mereka +// tersendiri tetapi blok tidak. +if (true){ + var i = 5; +} +i; // = 5 - bukan undefined seperti yang anda jangkakan di dalam bahasa blok-skop + +// Ini telah menyebabkan corak biasa iaitu "immediately-executing anonymous +// functions", yang mengelakkan pembolehubah sementara daripada bocor ke +// skop global. +(function(){ + var temporary = 5; + // Kita boleh akses skop global dengan menetapkan nilai ke "objek global", + // iaitu dalam pelayar web selalunya adalah `window`. Objek global mungkin + // mempunyai nama yang berlainan dalam alam bukan pelayar web seperti Node.js. + window.permanent = 10; +})(); +temporary; // akan menghasilkan ralat ReferenceError +permanent; // = 10 + +// Salah satu ciri terhebat Javascript ialah closure. Jika sebuah function +// didefinisikan di dalam sebuah function lain, function yang di dalam akan +// mempunyai akses kepada semua pembolehubah function yang di luar, mahupun +// selepas function yang di luar tersebut selesai. +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!"; + // Function dalam diletakkan di dalam skop lokal secara asal, seperti + // ia dideklarasikan dengan `var`. + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout adalah tak segerak atau asinkroni, maka function sayHelloInFiveSeconds akan selesai serta merta, dan setTimeout akan memanggil + // inner selepas itu. Walaubagaimanapun, disebabkan inner terletak didalam + // sayHelloInFiveSeconds, inner tetap mempunyai akses kepada pembolehubah + // `prompt` apabila ia dipanggil. +} +sayHelloInFiveSeconds("Adam"); // akan membuka sebuah popup dengan "Hello, Adam!" selepas 5s + +/////////////////////////////////// +// 5. Lagi tentang Objek, Constructor dan Prototype + +// Objek boleh mengandungi function. +var myObj = { + myFunc: function(){ + return "Hello world!"; + } +}; +myObj.myFunc(); // = "Hello world!" + +// Apabila function sesebuah object dipanggil, ia boleh mengakses objek asalnya +// dengan menggunakan kata kunci `this`. +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = "Hello world!" + +// Nilai sebenar yang ditetapkan kepada this akan ditentukan oleh bagaimana +// sesebuah function itu dipanggil, bukan dimana ia didefinisikan. Oleh it, +// sesebuah function tidak akan berfungsi jika ia dipanggil bukan pada konteks +// objeknya. +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// Sebaliknya, sebuah function boleh ditetapkan kepada objek dan mendapat akses +// kepada objek itu melalui `this`, walaupun ia tidak ditetapkan semasa ia +// didefinisikan. +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" + +// Kita juga boleh menentukan konteks untuk sebuah function dijalankan apabila +// ia dipanggil menggunakan `call` atau `apply`. + +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" + +// Function `apply` adalah hampir sama, tetapi ia mengambil sebuah array +// sebagai senarai input. + +anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" + +// Ini sangat berguna apabila menggunakan sebuah function yang menerima senarai +// input dan anda mahu menggunakan sebuah array sebagai input. + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// Tetapi, `call` dan `apply` adalah hanya sementara, sebagaimana hidup ini. +// Apabila kita mahu ia kekal, kita boleh menggunakan `bind`. + +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" + +// `bind` boleh juga digunakan untuk menggunakan sebuah function tidak +// sepenuhnya (curry). + +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// Apabila anda memanggil sebuah function dengan kata kunci `new`, sebuah +// objek baru akan dicipta dan dijadikan tersedia kepada function itu melalui +// kata kunci `this`. Function yang direka bentuk untuk dipanggil sebegitu rupa +// dikenali sebagai constructors. + +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// Setiap objek JavaScript mempunyai `prototype`. Apabila anda akses sesuatu +// ciri sebuah objek yang tidak wujud dalam objek sebenar itu, interpreter akan +// mencari ciri itu didalam `prototype`nya. + +// Sebahagian implementasi JS membenarkan anda untuk akses prototype sebuah +// objek pada ciri istimewa `__proto__`. Walaupun ini membantu dalam menerangkan +// mengenai prototypes, ia bukan sebahagian dari piawai; kita akan melihat +// cara - cara piawai untuk menggunakan prototypes nanti. +var myObj = { + myString: "Hello world!" +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// Ini berfungsi untuk function juga. +myObj.myFunc(); // = "hello world!" + +// Sudah pasti, jika ciri anda bukan pada prototype anda, prototype kepada +// prototype anda akan disemak, dan seterusnya. +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// Tiada penyalinan terlibat disini; setiap objek menyimpan rujukan kepada +// prototypenya sendiri. Ini bermaksud, kita boleh mengubah prototypenya dan +// pengubahsuaian itu akan dilihat dan berkesan dimana sahaja. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// Kami menyatakan yang `__proto__` adalah bukan piawai, dan tiada cara rasmi +// untuk mengubah prototype sesebuah objek. Walaubagaimanapun, terdapat dua +// cara untuk mencipta objek baru dengan sesebuah prototype. + +// Yang pertama ialah Object.create, yang merupakan tambahan terbaru pada JS, +// dan oleh itu tiada dalam semua implementasi buat masa ini. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// Cara kedua, yang boleh digunakan dimana sahaja, adalah berkaitan dengan +// constructor. Constructors mempunyai sebuah ciri yang dipanggil prototype. +// Ini *bukan* prototype constructor terbabit; tetapi, ia adalah prototype yang +// diberikan kepada objek baru apabila ia dicipta menggunakan constructor dan +// kata kunci new. +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function(){ + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 + +// Jenis yang terbina sedia seperti string dan nombor juga mempunyai constructor +// yang mencipta objek pembalut yang serupa. +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// Kecuali, mereka sebenarnya tak sama sepenuhnya. +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // Kod ini tidak akan dilaksanakan, kerana 0 adalah tidak benar. +} + +// Walaubagaimanapun, pembalut objek dan jenis terbina yang biasa berkongsi +// prototype, maka sebagai contoh, anda sebenarnya boleh menambah fungsi +// kepada string. +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// Fakta ini selalu digunakan dalam "polyfilling", iaitu melaksanakan fungsi +// baru JavaScript didalam subset JavaScript yang lama, supaya ia boleh +// digunakan di dalam persekitaran yang lama seperti pelayar web yang lama. + +// Sebagai contoh, kami menyatakan yang Object.create belum lagi tersedia +// di semua implementasi, tetapi kita masih boleh menggunakannya dengan polyfill: +if (Object.create === undefined){ // jangan ganti jika ia sudah wujud + Object.create = function(proto){ + // buat satu constructor sementara dengan prototype yang betul + var Constructor = function(){}; + Constructor.prototype = proto; + // kemudian gunakannya untuk mencipta objek baru yang diberikan + // prototype yang betul + return new Constructor(); + } +} +``` +## Bacaan Lanjut + +[Mozilla Developer Network][1] menyediakan dokumentasi yang sangat baik untuk +JavaScript kerana ia digunakan di dalam pelayar - pelayar web. Tambahan pula, +ia adalah sebuah wiki, maka, sambil anda belajar lebih banyak lagi, anda boleh +membantu orang lain dengan berkongsi pengetahuan anda. + +[A re-introduction to JavaScript][2] oleh MDN meliputi semua konsep yang +diterangkan di sini dengan lebih terperinci. Panduan ini menerangkan bahasa +aturcara JavaScript dengan agak mudah; jika anda mahu belajar lebih lanjut +tentang menggunakan JavaScript didalam laman web, mulakan dengan mempelajari +tentang [Document Object Model][3]. + +[Learn Javascript by Example and with Challenges][4] adalah variasi panduan ini +dengan cabaran yang tersedia pakai. + +[JavaScript Garden][5] pula adalah panduan yang lebih terperinci mengenai +semua bahagian bahasa aturcara ini yang bertentangan dengan naluri atau +kebiasaan. + +[JavaScript: The Definitive Guide][6] adalah panduan klasik dan buku rujukan. + +Selain daripada penyumbang terus kepada artikel ini, sebahagian kandungannya +adalah adaptasi daripada tutorial Python Louie Dinh di dalam laman web ini, +dan [JS Tutorial][7] di Mozilla Developer Network. + + +[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 diff --git a/nl-nl/amd-nl.html.markdown b/nl-nl/amd-nl.html.markdown new file mode 100644 index 00000000..d5e0022a --- /dev/null +++ b/nl-nl/amd-nl.html.markdown @@ -0,0 +1,235 @@ +--- +category: tool +tool: amd +contributors: + - ["Frederik Ring", "https://github.com/m90"] +translators: + - ["Reinoud Kruithof", "https://github.com/reinoudk"] +filename: learnamd-nl.js +lang: nl-nl +--- + +## Aan de slag met AMD + +De **Asynchronous Module Definition** API specificeert een mechanisme om JavaScript + modules the definiren zodat de module en dependencies (afhankelijkheden) asynchroon + geladen kunnen worden. Dit is vooral erg geschikt voor de browseromgeving, waar het + synchroon laden van modules zorgt voor problemen qua prestatie, gebruiksvriendelijkheid, + debugging en cross-domain toegangsproblemen. + +### Basis concept +```javascript +// De basis AMD API bestaat uit niks meer dan twee methodes: `define` en `require` +// and gaat vooral over de definitie en gebruik van modules: +// `define(id?, dependencies?, factory)` definieert een module +// `require(dependencies, callback)` importeert een set van dependencies en +// gebruikt ze in de gegeven callback + +// Laten we starten met het gebruiken van define om een nieuwe module (met naam) +// te creeren, welke geen dependencies heeft. Dit doen we door een naam +// en een zogeheten factory functie door te geven aan define: +define('awesomeAMD', function(){ + var isAMDAwesome = function(){ + return true; + }; + // De return waarde van een module's factory functie is + // wat andere modules of require calls ontvangen wanneer + // ze onze `awesomeAMD` module requiren. + // De gexporteerde waarde kan van alles zijn: (constructor) functies, + // objecten, primitives, zelfs undefined (hoewel dat niet veel nut heeft). + return isAMDAwesome; +}); + + +// We gaan nu een andere module defineren die afhankelijk is van onze +// `awesomeAMD` module. Merk hierbij op dat er nu een extra functieargument +// is die de dependencies van onze module defineert: +define('schreewlelijk', ['awesomeAMD'], function(awesomeAMD){ + // dependencies worden naar de factory's functieargumenten + // gestuurd in de volgorde waarin ze gespecificeert zijn + var vertelIedereen = function(){ + if (awesomeAMD()){ + alert('Dit is zOoOo cool!'); + } else { + alert('Vrij saai, niet?'); + } + }; + return vertelIedereen; +}); + +// Nu we weten hoe we define moeten gebruiken, kunnen we require gebruiken +// om ons programma mee te starten. De vorm van `require` is +// `(arrayVanDependencies, callback)`. +require(['schreeuwlelijk'], function(schreewlelijk){ + schreeuwlelijk(); +}); + +// Om deze tutorial code uit te laten voeren, gaan we hier een vrij basic +// (niet-asynchrone) versie van AMD implementeren: +function define(naam, deps, factory){ + // merk op hoe modules zonder dependencies worden afgehandeld + define[naam] = require(factory ? deps : [], factory || deps); +} + +function require(deps, callback){ + var args = []; + // we halen eerst alle dependecies op die nodig zijn + // om require aan te roepen + for (var i = 0; i < deps.length; i++){ + args[i] = define[deps[i]]; + } + // voldoe aan alle dependencies van de callback + return callback.apply(null, args); +} +// je kan deze code hier in actie zien (Engels): http://jsfiddle.net/qap949pd/ +``` + +### require.js in de echte wereld + +In contrast met het voorbeeld uit de introductie, implementeert `require.js` + (de meest populaire AMD library) de **A** in **AMD**. Dit maakt het mogelijk + om je modules en hun dependencies asynchroon in the laden via XHR: + +```javascript +/* file: app/main.js */ +require(['modules/someClass'], function(SomeClass){ + // de callback word uitgesteld tot de dependency geladen is + var things = new SomeClass(); +}); +console.log('Dus, hier wachten we!'); // dit wordt als eerste uitgevoerd +``` + +De afspraak is dat je over het algemeen n module in n bestand opslaat. +`require.js` kan module-namen achterhalen gebaseerd op de bestandslocatie, +dus je hoeft je module geen naam te geven. Je kan simpelweg aan ze referen + door hun locatie te gebruiken. +In het voorbeeld nemen we aan dat `someClass` aanwezig is in de `modules` map, + relatief ten opzichte van de `baseUrl` uit je configuratie. + +* app/ + * main.js + * modules/ + * someClass.js + * someHelpers.js + * ... + * daos/ + * things.js + * ... + +Dit betekent dat we `someClass` kunnen defineren zonder een module-id te specificeren: + +```javascript +/* file: app/modules/someClass.js */ +define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){ + // definitie van de module gebeurt, natuurlijk, ook asynchroon + function SomeClass(){ + this.method = function(){/**/}; + // ... + } + return SomeClass; +}); +``` +Gebruik `requirejs.config(configObj)` om het gedrag van de standaard mapping + aan te passen in je `main.js`: + +```javascript +/* file: main.js */ +requirejs.config({ + baseUrl : 'app', + paths : { + // je kan ook modules uit andere locatie inladen + jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', + coolLibUitBower : '../bower_components/cool-lib/coollib' + } +}); +require(['jquery', 'coolLibUitBower', 'modules/someHelpers'], function($, coolLib, helpers){ + // een `main` bestand moet require minstens eenmaal aanroepen, + // anders zal er geen code uitgevoerd worden + coolLib.doFancyDingenMet(helpers.transform($('#foo'))); +}); +``` +Op `require.js` gebaseerde apps hebben vaak een enkel beginpunt (`main.js`) + welke toegevoegd wordt aan de `require.js` script tag als een data-attribuut. +Deze zal automisch geladen en uitgevoerd worden als de pagina laadt: + +```html +<!DOCTYPE html> +<html> +<head> + <title>Honder script tags? Nooi meer!</title> +</head> +<body> + <script src="require.js" data-main="app/main"></script> +</body> +</html> +``` + +### Een heel project optimaliseren met r.js + +Veel mensen geven er de voorkeur aan om AMD te gebruiken tijdens de + ontwikkelfase om code op een gezonde manier te organiseren maar + willen nog steeds een enkel scriptbestand gebruiken in productie in + plaats van honderderen XHR verzoeken uit te voeren als de pagina laadt. + +`require.js` wordt geleverd met een script genaamd `r.js` (die je waarschijnlijk +uitvoert in node.js, hoewel Rhino ook ondersteund wordt) welke de +dependency book van je project analyseert en een enkel bestand bouwt met daarin +al je module (juist genaamd), geminificeerd en klaar voor productie. + +Instaleren met `npm`: +```shell +$ npm install requirejs -g +``` + +Nu kun je het een configuratiebestand voeden: +```shell +$ r.js -o app.build.js +``` + +Voor ons bovenstaande voorbeeld zou de configuratie er zo uit kunnen zien: +```javascript +/* file : app.build.js */ +({ + name : 'main', // naam van het beginpunt + out : 'main-built.js', // naam van het bestand waar de output naar geschreven wordt + baseUrl : 'app', + paths : { + // `empty:` verteld r.js dat dee nog steeds geladen moet worden van de CDN, + // gebruik makend van de locatie gespecificeert in `main.js` + jquery : 'empty:', + coolLibUitBower : '../bower_components/cool-lib/coollib' + } +}) +``` +Verwissel simpelweg `data-main` om het gebouwde bestand te gebruiken in productie: +```html +<script src="require.js" data-main="app/main-built"></script> +``` + +Een erg gedetaileerd [overzicht van bouwopties](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is +beschikbar in de GitHub repo (Engels). + +Hieronder vind je nog meer informatie over AMD (Engels). + +### Onderwerpen die niet aan bod zijn gekomen +* [Loader plugins / transforms](http://requirejs.org/docs/plugins.html) +* [CommonJS style loading and exporting](http://requirejs.org/docs/commonjs.html) +* [Advanced configuration](http://requirejs.org/docs/api.html#config) +* [Shim configuration (loading non-AMD modules)](http://requirejs.org/docs/api.html#config-shim) +* [CSS loading and optimizing with require.js](http://requirejs.org/docs/optimization.html#onecss) +* [Using almond.js for builds](https://github.com/jrburke/almond) + +### Verder lezen: + +* [Official Spec](https://github.com/amdjs/amdjs-api/wiki/AMD) +* [Why AMD?](http://requirejs.org/docs/whyamd.html) +* [Universal Module Definition](https://github.com/umdjs/umd) + +### Implementaties: + +* [require.js](http://requirejs.org) +* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) +* [cujo.js](http://cujojs.com/) +* [curl.js](https://github.com/cujojs/curl) +* [lsjs](https://github.com/zazl/lsjs) +* [mmd](https://github.com/alexlawrence/mmd) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index cf6bf780..097cb846 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -1,13 +1,12 @@ --- - language: Objective-C contributors: - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] - ["Yannick Loriot", "https://github.com/YannickL"] - ["Levi Bostian", "https://github.com/levibostian"] - ["Clayton Walker", "https://github.com/cwalk"] + - ["Fernando Valverde", "http://visualcosita.xyz"] filename: LearnObjectiveC.m - --- Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. @@ -20,6 +19,10 @@ It is a general-purpose, object-oriented programming language that adds Smalltal 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 // Same tag, now with a separator + // Imports the Foundation headers with #import // Use <> to import global files (in general frameworks) // Use "" to import local files (from project) @@ -149,6 +152,12 @@ int main (int argc, const char * argv[]) [mutableDictionary setObject:@"value2" forKey:@"key2"]; [mutableDictionary removeObjectForKey:@"key1"]; + // Change types from Mutable To Immutable + //In general [object mutableCopy] will make the object mutable whereas [object copy] will make the object immutable + NSMutableDictionary *aMutableDictionary = [aDictionary mutableCopy]; + NSDictionary *mutableDictionaryChanged = [mutableDictionary copy]; + + // Set object NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order) @@ -593,6 +602,52 @@ int main (int argc, const char * argv[]) { @end +// Starting in Xcode 7.0, you can create Generic classes, +// allowing you to provide greater type safety and clarity +// without writing excessive boilerplate. +@interface Result<__covariant A> : NSObject + +- (void)handleSuccess:(void(^)(A))success + failure:(void(^)(NSError *))failure; + +@property (nonatomic) A object; + +@end + +// we can now declare instances of this class like +Result<NSNumber *> *result; +Result<NSArray *> *result; + +// Each of these cases would be equivalent to rewriting Result's interface +// and substituting the appropriate type for A +@interface Result : NSObject +- (void)handleSuccess:(void(^)(NSArray *))success + failure:(void(^)(NSError *))failure; +@property (nonatomic) NSArray * object; +@end + +@interface Result : NSObject +- (void)handleSuccess:(void(^)(NSNumber *))success + failure:(void(^)(NSError *))failure; +@property (nonatomic) NSNumber * object; +@end + +// It should be obvious, however, that writing one +// Class to solve a problem is always preferable to writing two + +// Note that Clang will not accept generic types in @implementations, +// so your @implemnation of Result would have to look like this: + +@implementation Result + +- (void)handleSuccess:(void (^)(id))success + failure:(void (^)(NSError *))failure { + // Do something +} + +@end + + /////////////////////////////////////// // Protocols /////////////////////////////////////// @@ -682,7 +737,7 @@ addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any pa mutableVar = 32; // Assigning new value to __block variable. return n + outsideVar; // Return statements are optional. } -int addUp = add(10 + 16); // Calls block code with arguments. +int addUp = addUp(10 + 16); // Calls block code with arguments. // Blocks are often used as arguments to functions to be called later, or for callbacks. @implementation BlockExample : NSObject diff --git a/php.html.markdown b/php.html.markdown index 13cc83eb..0504ced2 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -104,7 +104,8 @@ END; echo 'This string ' . 'is concatenated'; // Strings can be passed in as parameters to echo -echo 'Multiple', 'Parameters', 'Valid'; +echo 'Multiple', 'Parameters', 'Valid'; // Returns 'MultipleParametersValid' + /******************************** * Constants @@ -117,8 +118,10 @@ echo 'Multiple', 'Parameters', 'Valid'; // followed by any number of letters, numbers, or underscores. define("FOO", "something"); -// access to a constant is possible by direct using the choosen name -echo 'This outputs '.FOO; +// access to a constant is possible by calling the choosen name without a $ +echo FOO; // Returns 'something' +echo 'This outputs '.FOO; // Returns 'This ouputs something' + /******************************** @@ -159,9 +162,9 @@ echo('Hello World!'); print('Hello World!'); // The same as echo -// echo is actually a language construct, so you can drop the parentheses. +// echo and print are language constructs too, so you can drop the parentheses echo 'Hello World!'; -print 'Hello World!'; // So is print +print 'Hello World!'; $paragraph = 'paragraph'; @@ -219,7 +222,11 @@ assert($a !== $d); assert(1 === '1'); assert(1 !== '1'); -// spaceship operator since PHP 7 +// 'Spaceship' operator (since PHP 7) +// Returns 0 if values on either side are equal +// Returns 1 if value on the left is greater +// Returns -1 if the value on the right is greater + $a = 100; $b = 1000; @@ -445,6 +452,16 @@ function parameters() { parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | +// Since PHP 5.6 you can get a variable number of arguments +function variable($word, ...$list) { + echo $word . " || "; + foreach ($list as $item) { + echo $item . ' | '; + } +} + +variable("Separate", "Hello", "World") // Separate || Hello | World | + /******************************** * Includes */ @@ -712,6 +729,43 @@ use My\Namespace as SomeOtherNamespace; $cls = new SomeOtherNamespace\MyClass(); + +/********************** +* Late Static Binding +* +*/ + +class ParentClass { + public static function who() { + echo "I'm a " . __CLASS__ . "\n"; + } + public static function test() { + // self references the class the method is defined within + self::who(); + // static references the class the method was invoked on + static::who(); + } +} + +ParentClass::test(); +/* +I'm a ParentClass +I'm a ParentClass +*/ + +class ChildClass extends ParentClass { + public static function who() { + echo "But I'm " . __CLASS__ . "\n"; + } +} + +ChildClass::test(); +/* +I'm a ParentClass +But I'm ChildClass +*/ + + /********************** * Error Handling * @@ -721,15 +775,15 @@ $cls = new SomeOtherNamespace\MyClass(); try { // Do something -} catch ( Exception $e) { +} catch (Exception $e) { // Handle exception } // When using try catch blocks in a namespaced enviroment use the following -try { +try { // Do something -} catch (\Exception $e) { +} catch (\Exception $e) { // Handle exception } @@ -738,13 +792,13 @@ try { class MyException extends Exception {} try { - - $condition = true; - + + $condition = true; + if ($condition) { throw new MyException('Something just happend'); } - + } catch (MyException $e) { // Handle my exception } diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown index 43688724..2c274f12 100644 --- a/pt-br/c-pt.html.markdown +++ b/pt-br/c-pt.html.markdown @@ -7,29 +7,30 @@ contributors: translators: - ["João Farias", "https://github.com/JoaoGFarias"] - ["Elton Viana", "https://github.com/eltonvs"] + - ["Cássio Böck", "https://github.com/cassiobsilva"] lang: pt-br filename: c-pt.el --- Ah, C. Ainda é **a** linguagem de computação de alta performance. -C é a liguangem de mais baixo nível que a maioria dos programadores -irão usar, e isso dá a ela uma grande velocidade bruta. Apenas fique -antento que este manual de gerenciamento de memória e C vai levanter-te -tão longe quanto você precisa. +C é a linguagem de mais baixo nível que a maioria dos programadores +utilizarão, e isso dá a ela uma grande velocidade bruta. Apenas fique +atento se este manual de gerenciamento de memória e C vai te levar +tão longe quanto precisa. ```c // Comentários de uma linha iniciam-se com // - apenas disponível a partir do C99 /* -Comentários de multiplas linhas se parecem com este. +Comentários de múltiplas linhas se parecem com este. Funcionam no C89 também. */ // Constantes: #define <palavra-chave> #definie DAY_IN_YEAR 365 -//enumarações também são modos de definir constantes. +//enumerações também são modos de definir constantes. enum day {DOM = 1, SEG, TER, QUA, QUI, SEX, SAB}; // SEG recebe 2 automaticamente, TER recebe 3, etc. @@ -54,13 +55,13 @@ int soma_dois_ints(int x1, int x2); // protótipo de função // O ponto de entrada do teu programa é uma função // chamada main, com tipo de retorno inteiro int main() { - // Usa-se printf para escrever na tela, + // Usa-se printf para escrever na tela, // para "saída formatada" // %d é um inteiro, \n é uma nova linha printf("%d\n", 0); // => Imprime 0 // Todos as declarações devem acabar com // ponto e vírgula - + /////////////////////////////////////// // Tipos /////////////////////////////////////// @@ -78,7 +79,7 @@ int main() { // longs tem entre 4 e 8 bytes; longs long tem garantia // de ter pelo menos 64 bits long x_long = 0; - long long x_long_long = 0; + long long x_long_long = 0; // floats são normalmente números de ponto flutuante // com 32 bits @@ -93,7 +94,7 @@ int main() { unsigned int ux_int; unsigned long long ux_long_long; - // caracteres dentro de aspas simples são inteiros + // caracteres dentro de aspas simples são inteiros // no conjunto de caracteres da máquina. '0' // => 48 na tabela ASCII. 'A' // => 65 na tabela ASCII. @@ -104,7 +105,7 @@ int main() { // Se o argumento do operador `sizeof` é uma expressão, então seus argumentos // não são avaliados (exceto em VLAs (veja abaixo)). - // O valor devolve, neste caso, é uma constante de tempo de compilação. + // O valor devolve, neste caso, é uma constante de tempo de compilação. int a = 1; // size_t é um inteiro sem sinal com pelo menos 2 bytes que representa // o tamanho de um objeto. @@ -120,7 +121,7 @@ int main() { // Você pode inicializar um array com 0 desta forma: char meu_array[20] = {0}; - // Indexar um array é semelhante a outras linguages + // Indexar um array é semelhante a outras linguagens // Melhor dizendo, outras linguagens são semelhantes a C meu_array[0]; // => 0 @@ -129,7 +130,7 @@ int main() { printf("%d\n", meu_array[1]); // => 2 // No C99 (e como uma features opcional em C11), arrays de tamanho variável - // VLA (do inglês), podem ser declarados também. O tamanho destes arrays + // VLA (do inglês), podem ser declarados também. O tamanho destes arrays // não precisam ser uma constante de tempo de compilação: printf("Entre o tamanho do array: "); // Pergunta ao usuário pelo tamanho char buf[0x100]; @@ -144,14 +145,14 @@ int main() { // > Entre o tamanho do array: 10 // > sizeof array = 40 - // String são apenas arrays de caracteres terminados por um + // String são apenas arrays de caracteres terminados por um // byte nulo (0x00), representado em string pelo caracter especial '\0'. // (Não precisamos incluir o byte nulo em literais de string; o compilador // o insere ao final do array para nós.) - char uma_string[20] = "Isto é uma string"; + char uma_string[20] = "Isto é uma string"; // Observe que 'é' não está na tabela ASCII // A string vai ser salva, mas a saída vai ser estranha - // Porém, comentários podem conter acentos + // Porém, comentários podem conter acentos printf("%s\n", uma_string); // %s formata a string printf("%d\n", uma_string[17]); // => 0 @@ -175,7 +176,7 @@ int main() { /////////////////////////////////////// // Atalho para multiplas declarações: - int i1 = 1, i2 = 2; + int i1 = 1, i2 = 2; float f1 = 1.0, f2 = 2.0; int a, b, c; @@ -206,7 +207,7 @@ int main() { 2 <= 2; // => 1 2 >= 2; // => 1 - // C não é Python - comparações não se encadeam. + // C não é Python - comparações não se encadeiam. int a = 1; // Errado: int entre_0_e_2 = 0 < a < 2; @@ -231,7 +232,7 @@ int main() { char *s = "iLoveC"; int j = 0; s[j++]; // => "i". Retorna o j-ésimo item de s E DEPOIS incrementa o valor de j. - j = 0; + j = 0; s[++j]; // => "L". Incrementa o valor de j. E DEPOIS retorna o j-ésimo item de s. // o mesmo com j-- e --j @@ -308,7 +309,7 @@ int main() { exit(-1); break; } - + /////////////////////////////////////// // Cast de tipos @@ -327,8 +328,8 @@ int main() { // Tipos irão ter overflow sem aviso printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 se char tem 8 bits) - // Para determinar o valor máximo de um `char`, de um `signed char` e de - // um `unisigned char`, respectivamente, use as macros CHAR_MAX, SCHAR_MAX + // Para determinar o valor máximo de um `char`, de um `signed char` e de + // um `unisigned char`, respectivamente, use as macros CHAR_MAX, SCHAR_MAX // e UCHAR_MAX de <limits.h> // Tipos inteiros podem sofrer cast para pontos-flutuantes e vice-versa. @@ -341,7 +342,7 @@ int main() { /////////////////////////////////////// // Um ponteiro é uma variável declarada para armazenar um endereço de memória. - // Seu declaração irá também dizer o tipo de dados para o qual ela aponta. Você + // Sua declaração irá também dizer o tipo de dados para o qual ela aponta. Você // Pode usar o endereço de memória de suas variáveis, então, brincar com eles. int x = 0; @@ -363,13 +364,13 @@ int main() { printf("%d\n", *px); // => Imprime 0, o valor de x // Você também pode mudar o valor que o ponteiro está apontando. - // Teremo que cercar a de-referência entre parenteses, pois + // Temos que cercar a de-referência entre parênteses, pois // ++ tem uma precedência maior que *. (*px)++; // Incrementa o valor que px está apontando por 1 printf("%d\n", *px); // => Imprime 1 printf("%d\n", x); // => Imprime 1 - // Arrays são um boa maneira de alocar um bloco contínuo de memória + // Arrays são uma boa maneira de alocar um bloco contínuo de memória int x_array[20]; // Declara um array de tamanho 20 (não pode-se mudar o tamanho int xx; for (xx = 0; xx < 20; xx++) { @@ -379,7 +380,7 @@ int main() { // Declara um ponteiro do tipo int e inicialize ele para apontar para x_array int* x_ptr = x_array; // x_ptr agora aponta para o primeiro elemento do array (o inteiro 20). - // Isto funciona porque arrays são apenas ponteiros para seu primeiros elementos. + // Isto funciona porque arrays são apenas ponteiros para seus primeiros elementos. // Por exemplo, quando um array é passado para uma função ou é atribuído a um // ponteiro, ele transforma-se (convertido implicitamente) em um ponteiro. // Exceções: quando o array é o argumento de um operador `&` (endereço-de): @@ -395,7 +396,7 @@ int main() { printf("%zu, %zu\n", sizeof arr, sizeof ptr); // provavelmente imprime "40, 4" ou "40, 8" // Ponteiros podem ser incrementados ou decrementados baseado no seu tipo - // (isto é chamado aritimética de ponteiros + // (isto é chamado aritmética de ponteiros printf("%d\n", *(x_ptr + 1)); // => Imprime 19 printf("%d\n", x_array[1]); // => Imprime 19 @@ -413,9 +414,9 @@ int main() { // "resultados imprevisíveis" - o programa é dito ter um "comportamento indefinido" printf("%d\n", *(my_ptr + 21)); // => Imprime quem-sabe-o-que? Talvez até quebre o programa. - // Quando termina-se de usar um bloco de memória alocado, você pode liberá-lo, + // Quando se termina de usar um bloco de memória alocado, você pode liberá-lo, // ou ninguém mais será capaz de usá-lo até o fim da execução - // (Isto cham-se "memory leak"): + // (Isto chama-se "memory leak"): free(my_ptr); // Strings são arrays de char, mas elas geralmente são representadas @@ -537,7 +538,7 @@ int area(retan r) return r.largura * r.altura; } -// Se você tiver structus grande, você pode passá-las "por ponteiro" +// Se você tiver structus grande, você pode passá-las "por ponteiro" // para evitar cópia de toda a struct: int area(const retan *r) { @@ -554,8 +555,8 @@ conhecidos. Ponteiros para funções são como qualquer outro ponteiro diretamente e passá-las para por toda parte. Entretanto, a sintaxe de definição por ser um pouco confusa. -Exemplo: use str_reverso através de um ponteiro -*/ +Exemplo: use str_reverso através de um ponteiro +*/ void str_reverso_através_ponteiro(char *str_entrada) { // Define uma variável de ponteiro para função, nomeada f. void (*f)(char *); //Assinatura deve ser exatamente igual à função alvo. @@ -575,7 +576,7 @@ typedef void (*minha_função_type)(char *); // Declarando o ponteiro: // ... -// minha_função_type f; +// minha_função_type f; //Caracteres especiais: '\a' // Alerta (sino) @@ -586,7 +587,7 @@ typedef void (*minha_função_type)(char *); '\r' // Retorno de carroça '\b' // Backspace '\0' // Caracter nulo. Geralmente colocado ao final de string em C. - // oi\n\0. \0 é usado por convenção para marcar o fim da string. + // oi\n\0. \0 é usado por convenção para marcar o fim da string. '\\' // Barra invertida '\?' // Interrogação '\'' // Aspas simples @@ -606,7 +607,7 @@ typedef void (*minha_função_type)(char *); "%p" // ponteiro "%x" // hexadecimal "%o" // octal -"%%" // imprime % +"%%" // imprime % /////////////////////////////////////// // Ordem de avaliação diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown index ed6f6c4c..b1fbd961 100644 --- a/pt-br/css-pt.html.markdown +++ b/pt-br/css-pt.html.markdown @@ -159,11 +159,11 @@ seletor { color: # FF66EE; /* Formato hexadecimal longo */ color: tomato; /* Uma cor nomeada */ color: rgb (255, 255, 255); /* Como valores rgb */ - cor: RGB (10%, 20%, 50%); /* Como porcentagens rgb */ - cor: rgba (255, 0, 0, 0,3); /* Como valores RGBA (CSS 3) NOTA: 0 <a <1 */ + color: RGB (10%, 20%, 50%); /* Como porcentagens rgb */ + color: rgba (255, 0, 0, 0,3); /* Como valores RGBA (CSS 3) NOTA: 0 <a <1 */ color: transparent; /* Equivale a definir o alfa a 0 */ - cor: HSL (0, 100%, 50%); /* Como porcentagens HSL (CSS 3) */ - cor: HSLA (0, 100%, 50%, 0,3); /* Como porcentagens HSLA com alfa */ + color: HSL (0, 100%, 50%); /* Como porcentagens HSL (CSS 3) */ + color: HSLA (0, 100%, 50%, 0,3); /* Como porcentagens HSLA com alfa */ /* Imagens como fundos de elementos */ background-image: url (/img-path/img.jpg); /* Citações dentro url () opcional */ diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown index a884f273..3c9512aa 100644 --- a/pt-br/java-pt.html.markdown +++ b/pt-br/java-pt.html.markdown @@ -405,6 +405,219 @@ class Velocipede extends Bicicleta { } +// Interfaces +// Sintaxe de declaração de Interface +// <nível de acesso> Interface <nome-da-interface> extends <super-interfaces> { +// // Constantes +// // Declarações de método +//} + +// Exemplo - Comida: +public interface Comestivel { + public void comer(); // Qualquer classe que implementa essa interface, deve + // Implementar este método. +} + +public interface Digestivel { + public void digerir(); +} + + +// Agora podemos criar uma classe que implementa ambas as interfaces. +public class Fruta implements Comestivel, Digestivel { + + @Override + public void comer() { + // ... + } + + @Override + public void digerir() { + // ... + } +} + +// Em Java, você pode estender somente uma classe, mas você pode implementar muitas +// Interfaces. Por exemplo: +public class ClasseExemplo extends ExemploClassePai implements InterfaceUm, + InterfaceDois { + + @Override + public void InterfaceUmMetodo() { + } + + @Override + public void InterfaceDoisMetodo() { + } + +} + +// Classes abstratas + +// Sintaxe de declaração de classe abstrata +// <Nível de acesso> abstract <nome-da-classe-abstrata> extends <estende super-abstratas-classes> { +// // Constantes e variáveis +// // Declarações de método +//} + +// Marcar uma classe como abstrata significa que ela contém métodos abstratos que devem +// ser definido em uma classe filha. Semelhante às interfaces, classes abstratas não podem +// ser instanciadas, ao invés disso devem ser extendidas e os métodos abstratos +// definidos. Diferente de interfaces, classes abstratas podem conter uma mistura de +// métodos concretos e abstratos. Métodos em uma interface não podem ter um corpo, +// a menos que o método seja estático, e as variáveis sejam finais, por padrão, ao contrário de um +// classe abstrata. Classes abstratas também PODEM ter o método "main". + +public abstract class Animal +{ + public abstract void fazerSom(); + + // Método pode ter um corpo + public void comer() + { + System.out.println("Eu sou um animal e estou comendo."); + //Nota: Nós podemos acessar variáveis privadas aqui. + idade = 30; + } + + // Não há necessidade de inicializar, no entanto, em uma interface + // a variável é implicitamente final e, portanto, tem + // de ser inicializado. + protected int idade; + + public void mostrarIdade() + { + System.out.println(idade); + } + + //Classes abstratas podem ter o método main. + public static void main(String[] args) + { + System.out.println("Eu sou abstrata"); + } +} + +class Cachorro extends Animal +{ + + // Nota: ainda precisamos substituir os métodos abstratos na + // classe abstrata + @Override + public void fazerSom() + { + System.out.println("Bark"); + // idade = 30; ==> ERRO! idade é privada de Animal + } + + // NOTA: Você receberá um erro se usou a + // anotação Override aqui, uma vez que java não permite + // sobrescrita de métodos estáticos. + // O que está acontecendo aqui é chamado de "esconder o método". + // Vejá também este impressionante SO post: http://stackoverflow.com/questions/16313649/ + public static void main(String[] args) + { + Cachorro pluto = new Cachorro(); + pluto.fazerSom(); + pluto.comer(); + pluto.mostrarIdade(); + } +} + +// Classes Finais + +// Sintaxe de declaração de classe final +// <nível de acesso> final <nome-da-classe-final> { +// // Constantes e variáveis +// // Declarações de método +//} + +// Classes finais são classes que não podem ser herdadas e são, portanto, um +// filha final. De certa forma, as classes finais são o oposto de classes abstratas +// Porque classes abstratas devem ser estendidas, mas as classes finais não pode ser +// estendidas. +public final class TigreDenteDeSabre extends Animal +{ + // Nota: Ainda precisamos substituir os métodos abstratos na + // classe abstrata. + @Override + public void fazerSom(); + { + System.out.println("Roar"); + } +} + +// Métodos Finais +public abstract class Mamifero() +{ + // Sintaxe de Métodos Finais: + // <modificador-de-acesso> final <tipo-de-retorno> <nome-do-método>(<argumentos>) + + // Métodos finais, como, classes finais não podem ser substituídas por uma classe filha, + // e são, portanto, a implementação final do método. + public final boolean EImpulsivo() + { + return true; + } +} + + +// Tipo Enum +// +// Um tipo enum é um tipo de dado especial que permite a uma variável ser um conjunto de constantes predefinidas. A +// variável deve ser igual a um dos valores que foram previamente definidos para ela. +// Por serem constantes, os nomes dos campos de um tipo de enumeração estão em letras maiúsculas. +// Na linguagem de programação Java, você define um tipo de enumeração usando a palavra-chave enum. Por exemplo, você poderia +// especificar um tipo de enum dias-da-semana como: + +public enum Dia { + DOMINGO, SEGUNDA, TERÇA, QUARTA, + QUINTA, SEXTA, SABADO +} + +// Nós podemos usar nosso enum Dia assim: + +public class EnumTeste { + + // Variável Enum + Dia dia; + + public EnumTeste(Dia dia) { + this.dia = dia; + } + + public void digaComoE() { + switch (dia) { + case SEGUNDA: + System.out.println("Segundas são ruins."); + break; + + case SEXTA: + System.out.println("Sextas são melhores."); + break; + + case SABADO: + case DOMINGO: + System.out.println("Finais de semana são os melhores."); + break; + + default: + System.out.println("Dias no meio da semana são mais ou menos."); + break; + } + } + + public static void main(String[] args) { + EnumTeste primeiroDia = new EnumTeste(Dia.SEGUNDA); + primeiroDia.digaComoE(); // => Segundas-feiras são ruins. + EnumTeste terceiroDia = new EnumTeste(Dia.QUARTA); + terceiroDia.digaComoE(); // => Dias no meio da semana são mais ou menos. + } +} + +// Tipos Enum são muito mais poderosos do que nós mostramos acima. +// O corpo de um enum pode incluir métodos e outros campos. +// Você pode ver mais em https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html + ``` ## Leitura Recomendada diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown index e4f10a61..fd822c03 100644 --- a/pt-br/json-pt.html.markdown +++ b/pt-br/json-pt.html.markdown @@ -3,6 +3,7 @@ language: json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Francisco Marques", "https://github.com/ToFran"] translators: - ["Miguel Araújo", "https://github.com/miguelarauj1o"] lang: pt-br @@ -12,10 +13,16 @@ filename: learnjson-pt.json Como JSON é um formato de intercâmbio de dados, este será, muito provavelmente, o "Learn X in Y minutes" mais simples existente. -JSON na sua forma mais pura não tem comentários em reais, mas a maioria dos analisadores -aceitarão comentários no estilo C (//, /\* \*/). Para os fins do presente, no entanto, -tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si. +JSON na sua forma mais pura não tem comentários, mas a maioria dos analisadores +aceitarão comentários no estilo C (//, /\* \*/). No entanto estes devem ser evitados para otimizar a compatibilidade. +Um valor JSON pode ser um numero, uma string, um array, um objeto, um booleano (true, false) ou null. + +Os browsers suportados são: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, e Safari 4.0+. + +A extensão dos ficheiros JSON é “.json” e o tipo de mídia de Internet (MIME) é “application/json”. + +Mais informação em: http://www.json.org/ ```json { @@ -57,6 +64,6 @@ tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si. , "outro comentário": "que bom" }, - "que foi curto": "E, você está feito. Você já sabe tudo que JSON tem para oferecer.". + "que foi curto": "E, você está feito. Você já sabe tudo que JSON tem para oferecer." } ``` diff --git a/pt-br/matlab-pt.html.markdown b/pt-br/matlab-pt.html.markdown new file mode 100644 index 00000000..eb660d4c --- /dev/null +++ b/pt-br/matlab-pt.html.markdown @@ -0,0 +1,540 @@ +--- +language: Matlab +contributors: + - ["mendozao", "http://github.com/mendozao"] + - ["jamesscottbrown", "http://jamesscottbrown.com"] + - ["Colton Kohnke", "http://github.com/voltnor"] +translators: + - ["Claudson Martins", "https://github.com/claudsonm"] +lang: pt-br +filename: learnmatlab-pt.mat + +--- + +MATLAB significa MATrix LABoratory. É uma poderosa linguagem de computação numérica geralmente utilizada em engenharia e matemática. + +Se você tem algum feedback, por favor fique a vontade para me contactar via +[@the_ozzinator](https://twitter.com/the_ozzinator), ou +[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). + +```matlab +% Comentários iniciam com um sinal de porcentagem + +%{ +Comentários de múltiplas linhas +parecem +com +algo assim +%} + +% Comandos podem ocupar várinhas linhas, usando '...': + a = 1 + 2 + ... + + 4 + +% Comandos podem ser passados para o sistema operacional +!ping google.com + +who % Exibe todas as variáveis na memória +whos % Exibe todas as variáveis na memória, com seus tipos +clear % Apaga todas as suas variáveis da memória +clear('A') % Apaga uma variável em particular +openvar('A') % Abre a variável no editor de variável + +clc % Apaga o conteúdo escrito na sua janela de comando +diary % Alterna o conteúdo escrito na janela de comando para um arquivo de texto +ctrl-c % Aborta a computação atual + +edit('minhafuncao.m') % Abre a função/script no editor +type('minhafuncao.m') % Imprime o código-fonte da função/script na janela de comando + +profile on % Ativa o perfil de código +profile off % Desativa o perfil de código +profile viewer % Visualiza os resultados na janela de Profiler + +help comando % Exibe a documentação do comando na janela de comando +doc comando % Exibe a documentação do comando na janela de ajuda +lookfor comando % Procura por comando na primeira linha comentada de todas as funções +lookfor comando -all % Procura por comando em todas as funções + + +% Formatação de saída +format short % 4 casas decimais em um número flutuante +format long % 15 casas decimais +format bank % 2 dígitos após o ponto decimal - para cálculos financeiros +fprintf('texto') % Imprime na tela "texto" +disp('texto') % Imprime na tela "texto" + +% Variáveis & Expressões +minhaVariavel = 4 % O painel Workspace mostra a variável recém-criada +minhaVariavel = 4; % Ponto e vírgula suprime a saída para a janela de comando +4 + 6 % Resposta = 10 +8 * minhaVariavel % Resposta = 32 +2 ^ 3 % Resposta = 8 +a = 2; b = 3; +c = exp(a)*sin(pi/2) % c = 7.3891 + +% A chamada de funções pode ser feita por uma das duas maneiras: +% Sintaxe de função padrão: +load('arquivo.mat', 'y') % Argumentos entre parênteses, separados por vírgula +% Sintaxe de comando: +load arquivo.mat y % Sem parênteses, e espaços ao invés de vírgulas +% Observe a falta de aspas na forma de comando: entradas são sempre passadas +% como texto literal - não pode passar valores de variáveis. +% Além disso, não pode receber saída: +[V,D] = eig(A); % Isto não tem um equivalente na forma de comando +[~,D] = eig(A); % Se você só deseja D e não V + + + +% Operadores Lógicos e Relacionais +1 > 5 % Resposta = 0 +10 >= 10 % Resposta = 1 +3 ~= 4 % Diferente de -> Resposta = 1 +3 == 3 % Igual a -> Resposta = 1 +3 > 1 && 4 > 1 % E -> Resposta = 1 +3 > 1 || 4 > 1 % OU -> Resposta = 1 +~1 % NOT -> Resposta = 0 + +% Operadores Lógicos e Relacionais podem ser aplicados a matrizes +A > 5 +% Para cada elemento, caso seja verdade, esse elemento será 1 na matriz retornada +A( A > 5 ) +% Retorna um vetor com os elementos de A para os quais a condição é verdadeira + +% Cadeias de caracteres (Strings) +a = 'MinhaString' +length(a) % Resposta = 11 +a(2) % Resposta = i +[a,a] % Resposta = MinhaStringMinhaString + + +% Vetores de células +a = {'um', 'dois', 'três'} +a(1) % Resposta = 'um' - retorna uma célula +char(a(1)) % Resposta = um - retorna uma string + +% Estruturas +A.b = {'um','dois'}; +A.c = [1 2]; +A.d.e = false; + +% Vetores +x = [4 32 53 7 1] +x(2) % Resposta = 32, índices no Matlab começam por 1, não 0 +x(2:3) % Resposta = 32 53 +x(2:end) % Resposta = 32 53 7 1 + +x = [4; 32; 53; 7; 1] % Vetor coluna + +x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 + +% Matrizes +A = [1 2 3; 4 5 6; 7 8 9] +% Linhas são separadas por um ponto e vírgula; +% Elementos são separados com espaço ou vírgula +% A = + +% 1 2 3 +% 4 5 6 +% 7 8 9 + +A(2,3) % Resposta = 6, A(linha, coluna) +A(6) % Resposta = 8 +% (implicitamente encadeia as colunas do vetor, e então as indexa) + + +A(2,3) = 42 % Atualiza a linha 2 coluna 3 com o valor 42 +% A = + +% 1 2 3 +% 4 5 42 +% 7 8 9 + +A(2:3,2:3) % Cria uma nova matriz a partir da antiga +%Resposta = + +% 5 42 +% 8 9 + +A(:,1) % Todas as linhas na coluna 1 +%Resposta = + +% 1 +% 4 +% 7 + +A(1,:) % Todas as colunas na linha 1 +%Resposta = + +% 1 2 3 + +[A ; A] % Concatenação de matrizes (verticalmente) +%Resposta = + +% 1 2 3 +% 4 5 42 +% 7 8 9 +% 1 2 3 +% 4 5 42 +% 7 8 9 + +% Isto é o mesmo de +vertcat(A,A); + + +[A , A] % Concatenação de matrizes (horizontalmente) + +%Resposta = + +% 1 2 3 1 2 3 +% 4 5 42 4 5 42 +% 7 8 9 7 8 9 + +% Isto é o mesmo de +horzcat(A,A); + + +A(:, [3 1 2]) % Reorganiza as colunas da matriz original +%Resposta = + +% 3 1 2 +% 42 4 5 +% 9 7 8 + +size(A) % Resposta = 3 3 + +A(1, :) =[] % Remove a primeira linha da matriz +A(:, 1) =[] % Remove a primeira coluna da matriz + +transpose(A) % Transposta a matriz, que é o mesmo de: +A one +ctranspose(A) % Transposta a matriz +% (a transposta, seguida pelo conjugado complexo de cada elemento) + + + + +% Aritmética Elemento por Elemento vs. Aritmética com Matriz +% Naturalmente, os operadores aritméticos agem em matrizes inteiras. Quando +% precedidos por um ponto, eles atuam em cada elemento. Por exemplo: +A * B % Multiplicação de matrizes +A .* B % Multiplica cada elemento em A por seu correspondente em B + +% Existem vários pares de funções nas quais uma atua sob cada elemento, e a +% outra (cujo nome termina com m) age na matriz por completo. +exp(A) % Exponencia cada elemento +expm(A) % Calcula o exponencial da matriz +sqrt(A) % Tira a raiz quadrada de cada elemento +sqrtm(A) % Procura a matriz cujo quadrado é A + + +% Gráficos +x = 0:.10:2*pi; % Vetor que começa em 0 e termina em 2*pi com incrementos de 0,1 +y = sin(x); +plot(x,y) +xlabel('eixo x') +ylabel('eixo y') +title('Gráfico de y = sin(x)') +axis([0 2*pi -1 1]) % x vai de 0 a 2*pi, y vai de -1 a 1 + +plot(x,y1,'-',x,y2,'--',x,y3,':') % Para várias funções em um só gráfico +legend('Descrição linha 1', 'Descrição linha 2') % Curvas com uma legenda + +% Método alternativo para traçar várias funções em um só gráfico: +% Enquanto 'hold' estiver ativo, os comandos serão adicionados ao gráfico +% existente ao invés de o substituirem. +plot(x, y) +hold on +plot(x, z) +hold off + +loglog(x, y) % Plotar em escala loglog +semilogx(x, y) % Um gráfico com eixo x logarítmico +semilogy(x, y) % Um gráfico com eixo y logarítmico + +fplot (@(x) x^2, [2,5]) % Plotar a função x^2 para x=2 até x=5 + +grid on % Exibe as linhas de grade; Oculta com 'grid off' +axis square % Torna quadrada a região dos eixos atuais +axis equal % Taxa de proporção onde as unidades serão as mesmas em todas direções + +scatter(x, y); % Gráfico de dispersão ou bolha +hist(x); % Histograma + +z = sin(x); +plot3(x,y,z); % Plotar em espaço em 3D + +pcolor(A) % Mapa de calor da matriz: traça uma grade de retângulos, coloridos pelo valor +contour(A) % Plotar de contorno da matriz +mesh(A) % Plotar malha 3D + +h = figure % Cria uma nova figura objeto, com identificador h +figure(h) % Cria uma nova janela de figura com h +close(h) % Fecha a figura h +close all % Fecha todas as janelas de figuras abertas +close % Fecha a janela de figura atual + +shg % Traz uma janela gráfica existente para frente, ou cria uma nova se necessário +clf clear % Limpa a janela de figura atual e redefine a maioria das propriedades da figura + +% Propriedades podem ser definidas e alteradas através de um identificador. +% Você pode salvar um identificador para uma figura ao criá-la. +% A função gcf retorna o identificador da figura atual +h = plot(x, y); % Você pode salvar um identificador para a figura ao criá-la +set(h, 'Color', 'r') +% 'y' amarelo; 'm' magenta, 'c' ciano, 'r' vermelho, 'g' verde, 'b' azul, 'w' branco, 'k' preto +set(h, 'LineStyle', '--') + % '--' linha sólida, '---' tracejada, ':' pontilhada, '-.' traço-ponto, 'none' sem linha +get(h, 'LineStyle') + + +% A função gca retorna o identificador para os eixos da figura atual +set(gca, 'XDir', 'reverse'); % Inverte a direção do eixo x + +% Para criar uma figura que contém vários gráficos use subplot, o qual divide +% a janela de gráficos em m linhas e n colunas. +subplot(2,3,1); % Seleciona a primeira posição em uma grade de 2-por-3 +plot(x1); title('Primeiro Plot') % Plota algo nesta posição +subplot(2,3,2); % Seleciona a segunda posição na grade +plot(x2); title('Segundo Plot') % Plota algo ali + + +% Para usar funções ou scripts, eles devem estar no caminho ou na pasta atual +path % Exibe o caminho atual +addpath /caminho/para/pasta % Adiciona o diretório ao caminho +rmpath /caminho/para/pasta % Remove o diretório do caminho +cd /caminho/para/mudar % Muda o diretório + + +% Variáveis podem ser salvas em arquivos *.mat +save('meuArquivo.mat') % Salva as variáveis do seu Workspace +load('meuArquivo.mat') % Carrega as variáveis em seu Workspace + +% Arquivos M (M-files) +% Um arquivo de script é um arquivo externo contendo uma sequência de instruções. +% Eles evitam que você digite os mesmos códigos repetidamente na janela de comandos. +% Possuem a extensão *.m + +% Arquivos M de Funções (M-file Functions) +% Assim como scripts e têm a mesma extensão *.m +% Mas podem aceitar argumentos de entrada e retornar uma saída. +% Além disso, possuem seu próprio workspace (ex. diferente escopo de variáveis). +% O nome da função deve coincidir com o nome do arquivo (salve o exemplo como dobra_entrada.m) +% 'help dobra_entrada.m' retorna os comentários abaixo da linha de início da função +function output = dobra_entrada(x) + %dobra_entrada(x) retorna duas vezes o valor de x + output = 2*x; +end +dobra_entrada(6) % Resposta = 12 + + +% Você também pode ter subfunções e funções aninhadas. +% Subfunções estão no mesmo arquivo da função primária, e só podem ser chamados +% por funções dentro do arquivo. Funções aninhadas são definidas dentro de +% outras funções, e têm acesso a ambos workspaces. + +% Se você quer criar uma função sem criar um novo arquivo, você pode usar uma +% função anônima. Úteis para definir rapidamente uma função para passar a outra +% função (ex. plotar com fplot, avaliar uma integral indefinida com quad, +% procurar raízes com fzero, ou procurar mínimo com fminsearch). +% Exemplo que retorna o quadrado de sua entrada, atribuído ao identificador sqr: +sqr = @(x) x.^2; +sqr(10) % Resposta = 100 +doc function_handle % Saiba mais + +% Entrada do usuário +a = input('Digite o valor: ') + +% Para a execução do arquivo e passa o controle para o teclado: o usuário pode +% examinar ou alterar variáveis. Digite 'return' para continuar a execução, ou 'dbquit' para sair +keyboard + +% Leitura de dados (ou xlsread/importdata/imread para arquivos excel/CSV/imagem) +fopen(nomedoarquivo) + +% Saída +disp(a) % Imprime o valor da variável a +disp('Olá Mundo') % Imprime a string +fprintf % Imprime na janela de comandos com mais controle + +% Estruturas Condicionais (os parênteses são opicionais, porém uma boa prática) +if (a > 15) + disp('Maior que 15') +elseif (a == 23) + disp('a é 23') +else + disp('Nenhuma condição reconheceu') +end + +% Estruturas de Repetição +% Nota: fazer o loop sobre elementos de um vetor/matriz é lento! +% Sempre que possível, use funções que atuem em todo o vetor/matriz de uma só vez. +for k = 1:5 + disp(k) +end + +k = 0; +while (k < 5) + k = k + 1; +end + +% Tempo de Execução de Código (Timing Code Execution): 'toc' imprime o tempo +% passado desde que 'tic' foi chamado. +tic +A = rand(1000); +A*A*A*A*A*A*A; +toc + +% Conectando a uma base de dados MySQL +dbname = 'nome_base_de_dados'; +username = 'root'; +password = 'root'; +driver = 'com.mysql.jdbc.Driver'; +dburl = ['jdbc:mysql://localhost:8889/' dbname]; +%Abaixo, o xx depende da versão, download disponível em http://dev.mysql.com/downloads/connector/j/ +javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); +conn = database(dbname, username, password, driver, dburl); +sql = ['SELECT * FROM nome_tabela WHERE id = 22'] % Exemplo de uma consulta SQL +a = fetch(conn, sql) %a will contain your data + + +% Funções Matemáticas Comuns +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 % Números pseudo-aleatórios uniformemente distribuídos +randi % Inteiros pseudo-aleatórios uniformemente distribuídos +randn % Números pseudo-aleatórios normalmente distribuídos + +% Constantes Comuns +pi +NaN +inf + +% Resolvendo equações matriciais (se não houver solução, retorna uma solução de mínimos quadrados) +% Os operadores \ e / são equivalentes às funções mldivide e mrdivide +x=A\b % Resolve Ax=b. Mais rápido e numericamente mais preciso do que inv(A)*b. +x=b/A % Resolve xA=b + +inv(A) % Calcula a matriz inversa +pinv(A) % Calcula a pseudo-inversa + +% Funções Matriciais Comuns +zeros(m,n) % Matriz de zeros m x n +ones(m,n) % Matriz de 1's m x n +diag(A) % Extrai os elementos diagonais da matriz A +diag(x) % Constrói uma matriz com os elementos diagonais listados em x, e zero nas outras posições +eye(m,n) % Matriz identidade +linspace(x1, x2, n) % Retorna n pontos igualmente espaçados, com min x1 e max x2 +inv(A) % Inverso da matriz A +det(A) % Determinante da matriz A +eig(A) % Valores e vetores próprios de A +trace(A) % Traço da matriz - equivalente a sum(diag(A)) +isempty(A) % Testa se a matriz está vazia +all(A) % Testa se todos os elementos são diferentes de zero ou verdadeiro +any(A) % Testa se algum elemento é diferente de zero ou verdadeiro +isequal(A, B) % Testa a igualdade de duas matrizes +numel(A) % Número de elementos na matriz +triu(x) % Retorna a parte triangular superior de x +tril(x) % Retorna a parte triangular inferior de x +cross(A,B) % Retorna o produto cruzado das matrizes A e B +dot(A,B) % Retorna o produto escalar de duas matrizes (devem possuir mesmo tamanho) +transpose(A) % Retorna a matriz transposta de A +fliplr(A) % Inverte a matriz da esquerda para a direita +flipud(A) % Inverte a matriz de cima para baixo + +% Fatorações de Matrizes +% Decomposição LU: PA = LU,L é triangular inferior, U é triangular superior, P é a matriz de permutação +[L, U, P] = lu(A) +% Decomposição em Autovalores: AP = PD, colunas de P são autovetores e as diagonais de D são autovalores +[P, D] = eig(A) +% SVD: XV = US, U e V são matrizes unitárias, S possui elementos não negativos na diagonal em ordem decrescente +[U,S,V] = svd(X) + +% Funções Vetoriais Comuns +max % Maior componente +min % Menor componente +length % Tamanho do vetor +sort % Ordena em orcer ascendente +sum % Soma de elementos +prod % Produto de elementos +mode % Valor modal +median % Valor mediano +mean % Valor médio +std % Desvio padrão +perms(x) % Lista todas as permutações de elementos de x + + +% Classes +% Matlab pode suportar programação orientada a objetos. +% Classes devem ser colocadas em um arquivo de mesmo nome com a extensão *.m +% Para começar, criamos uma simples classe que armazena posições de GPS +% Início ClassePosicoesGPS.m +classdef ClassePosicoesGPS % O nome da classe. + properties % As propriedades da classe comportam-se como estruturas + latitude + longitude + end + methods + % Este método que tem o mesmo nome da classe é o construtor. + function obj = ClassePosicoesGPS(lat, lon) + obj.latitude = lat; + obj.longitude = lon; + end + + % Outras funções que usam os objetos de PosicoesGPS + function r = multiplicarLatPor(obj, n) + r = n*[obj.latitude]; + end + + % Se quisermos somar dois objetos de PosicoesGPS juntos sem chamar + % uma função especial nós podemos sobrepor a aritmética do Matlab, desta maneira: + function r = plus(o1,o2) + r = ClassePosicoesGPS([o1.latitude] +[o2.latitude], ... + [o1.longitude]+[o2.longitude]); + end + end +end +% End ClassePosicoesGPS.m + +% Podemos criar um objeto da classe usando o construtor +a = ClassePosicoesGPS(45.0, 45.0) + +% Propriedades da classe se comportam exatamente como estruturas Matlab +a.latitude = 70.0 +a.longitude = 25.0 + +% Métodos podem ser chamados da mesma forma que funções +ans = multiplicarLatPor(a,3) + +% O método também pode ser chamado usando a notação de ponto. Neste caso, +% o objeto não precisa ser passado para o método. +ans = a.multiplicarLatPor(a,1/3) + +% Funções do Matlab podem ser sobrepostas para lidar com objetos. +% No método abaixo, nós sobrepomos a forma como o Matlab lida com a soma de +% dois objetos PosicoesGPS. +b = ClassePosicoesGPS(15.0, 32.0) +c = a + b + +``` + +## Mais sobre Matlab + +* O site oficial [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) +* O fórum oficial de respostas: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) + diff --git a/pt-br/sass-pt.html.markdown b/pt-br/sass-pt.html.markdown index 105896b2..3d91f1ca 100644 --- a/pt-br/sass-pt.html.markdown +++ b/pt-br/sass-pt.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Sean Corrales", "https://github.com/droidenator"] translators: - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"] + - ["Cássio Böck", "https://github.com/cassiobsilva"] lang: pt-br --- @@ -155,16 +156,6 @@ body { background-color: rgba(0, 0, 0, 0.75); } -/* You may also define your own functions. Functions are very similar to - mixins. When trying to choose between a function or a mixin, remember - that mixins are best for generating CSS while functions are better for - logic that might be used throughout your Sass code. The examples in - the Math Operators' section are ideal candidates for becoming a reusable - function. */ - -/* This function will take a target size and the parent size and calculate - and return the percentage */ - /* Você também pode definir suas próprias funções. As funções são muito semelhantes aos mixins. Ao tentar escolher entre uma função ou um mixin, lembre- que mixins são os melhores para gerar CSS enquanto as funções são melhores para @@ -319,11 +310,6 @@ ol { padding: 0; } -/* Sass offers @import which can be used to import partials into a file. - This differs from the traditional CSS @import statement which makes - another HTTP request to fetch the imported file. Sass takes the - imported file and combines it with the compiled code. */ - /* Sass oferece @import que pode ser usado para importar parciais em um arquivo. Isso difere da declaração CSS @import tradicional, que faz outra solicitação HTTP para buscar o arquivo importado. Sass converte os @@ -354,12 +340,6 @@ body { ==============================*/ - -/* Placeholders are useful when creating a CSS statement to extend. If you - wanted to create a CSS statement that was exclusively used with @extend, - you can do so using a placeholder. Placeholders begin with a '%' instead - of '.' or '#'. Placeholders will not appear in the compiled CSS. */ - /* Os espaços reservados são úteis na criação de uma declaração CSS para ampliar. Se você queria criar uma instrução CSS que foi usado exclusivamente com @extend, Você pode fazer isso usando um espaço reservado. Espaços reservados começar com um '%' em vez @@ -396,11 +376,6 @@ body { ============================== * / -/* Sass provides the following operators: +, -, *, /, and %. These can - be useful for calculating values directly in your Sass files instead - of using values that you've already calculated by hand. Below is an example - of a setting up a simple two column design. */ - /* Sass fornece os seguintes operadores: +, -, *, /, e %. estes podem ser úteis para calcular os valores diretamente no seu Sass arquivos em vez de usar valores que você já calculados pela mão. Abaixo está um exemplo diff --git a/python.html.markdown b/python.html.markdown index b939ebbe..2b43c5fc 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Louie Dinh", "http://ldinh.ca"] - ["Amin Bandali", "http://aminbandali.com"] - ["Andre Polykanine", "https://github.com/Oire"] + - ["evuez", "http://github.com/evuez"] filename: learnpython.py --- @@ -14,8 +15,8 @@ executable pseudocode. 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 reachong end of life and will stop beeign maintained in 2020, -it is though recommended to start learnign Python with Python 3. +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, @@ -58,6 +59,12 @@ allow you to write Python 3 code that will run on Python 2, so check out the Pyt -5 // 3 # => -2 -5.0 // 3.0 # => -2.0 +# Note that we can also import division module(Section 6 Modules) +# to carry out normal division with just one '/'. +from __future__ import division +11/4 # => 2.75 ...normal division +11//4 # => 2 ...floored division + # Modulo operation 7 % 3 # => 1 @@ -116,11 +123,16 @@ not False # => True # A string can be treated like a list of characters "This is a string"[0] # => 'T' -# % can be used to format strings, like this: -"%s can be %s" % ("strings", "interpolated") +#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. +x = 'apple' +y = 'lemon' +z = "The items in the basket are %s and %s" % (x,y) # A newer way to format strings is the format method. # This method is the preferred way +"{} is a {}".format("This", "placeholder") "{0} can be {1}".format("strings", "formatted") # You can use keywords if you don't want to count. "{name} wants to eat {food}".format(name="Bob", food="lasagna") @@ -137,8 +149,16 @@ None is None # => True # very useful when dealing with primitive values, but is # very useful when dealing with objects. -# None, 0, and empty strings/lists all evaluate to False. -# All other values are True +# Any object can be used in a Boolean context. +# The following values are considered falsey: +# - None +# - zero of any numeric type (e.g., 0, 0L, 0.0, 0j) +# - empty sequences (e.g., '', (), []) +# - empty containers (e.g., {}, set()) +# - instances of user-defined classes meeting certain conditions +# see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ +# +# All other values are truthy (using the bool() function on them returns True). bool(0) # => False bool("") # => False @@ -165,6 +185,7 @@ some_var # => 5 some_other_var # Raises a name error # if can be used as an expression +# Equivalent of C's '?:' ternary operator "yahoo!" if 3 > 2 else 2 # => "yahoo!" # Lists store sequences @@ -218,6 +239,17 @@ li + other_li # => [1, 2, 3, 4, 5, 6] # Concatenate lists with "extend()" li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] +# Remove first occurrence of a value +li.remove(2) # li is now [1, 3, 4, 5, 6] +li.remove(2) # Raises a ValueError as 2 is not in the list + +# Insert an element at a specific index +li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again + +# Get the index of the first item found +li.index(2) # => 1 +li.index(7) # Raises a ValueError as 7 is not in the list + # Check for existence in a list with "in" 1 in li # => True @@ -238,8 +270,9 @@ tup[:2] # => (1, 2) # You can unpack tuples (or lists) into variables a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +d, e, f = 4, 5, 6 # you can leave out the parentheses # Tuples are created by default if you leave out the parentheses -d, e, f = 4, 5, 6 +g = 4, 5, 6 # => (4, 5, 6) # Now look how easy it is to swap two values e, d = d, e # d is now 5 and e is now 4 @@ -309,6 +342,15 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6} # Do set difference with - {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} +# Do set symmetric difference with ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Check if set on the left is a superset of set on the right +{1, 2} >= {1, 2, 3} # => False + +# Check if set on the left is a subset of set on the right +{1, 2} <= {1, 2, 3} # => True + # Check for existence in a set with in 2 in filled_set # => True 10 in filled_set # => False @@ -460,19 +502,19 @@ def pass_all_the_args(*args, **kwargs): # Function Scope x = 5 -def setX(num): +def set_x(num): # Local var x not the same as global variable x x = num # => 43 print x # => 43 -def setGlobalX(num): +def set_global_x(num): global x print x # => 5 x = num # global var x is now set to 6 print x # => 6 -setX(43) -setGlobalX(6) +set_x(43) +set_global_x(6) # Python has first class functions def create_adder(x): @@ -516,6 +558,10 @@ class Human(object): # Assign the argument to the instance's name attribute self.name = name + # Initialize property + self.age = 0 + + # An instance method. All methods take "self" as the first argument def say(self, msg): return "{0}: {1}".format(self.name, msg) @@ -531,6 +577,23 @@ class Human(object): def grunt(): return "*grunt*" + # A property is just like a getter. + # It turns the method age() into an read-only attribute + # of the same name. + @property + def age(self): + return self._age + + # This allows the property to be set + @age.setter + def age(self, age): + self._age = age + + # This allows the property to be deleted + @age.deleter + def age(self): + del self._age + # Instantiate a class i = Human(name="Ian") @@ -550,6 +613,16 @@ j.get_species() # => "H. neanderthalensis" # Call the static method Human.grunt() # => "*grunt*" +# Update the property +i.age = 42 + +# Get the property +i.age # => 42 + +# Delete the property +del i.age +i.age # => raises an AttributeError + #################################################### ## 6. Modules @@ -648,7 +721,7 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( * [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/) -* [The Official Docs](http://docs.python.org/2.6/) +* [The Official Docs](http://docs.python.org/2/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [Python Module of the Week](http://pymotw.com/2/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) diff --git a/python3.html.markdown b/python3.html.markdown index a1125c73..2398e7ac 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Steven Basart", "http://github.com/xksteven"] - ["Andre Polykanine", "https://github.com/Oire"] - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] filename: learnpython3.py --- @@ -216,6 +217,17 @@ li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. # Remove arbitrary elements from a list with "del" del li[2] # li is now [1, 2, 3] +# Remove first occurrence of a value +li.remove(2) # li is now [1, 3] +li.remove(2) # Raises a ValueError as 2 is not in the list + +# Insert an element at a specific index +li.insert(1, 2) # li is now [1, 2, 3] again + +# Get the index of the first item found +li.index(2) # => 3 +li.index(4) # Raises a ValueError as 4 is not in the list + # You can add lists # Note: values for li and for other_li are not modified. li + other_li # => [1, 2, 3, 4, 5, 6] @@ -249,6 +261,8 @@ tup[:2] # => (1, 2) # You can unpack tuples (or lists) into variables a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +# You can also do extended unpacking +a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4 # Tuples are created by default if you leave out the parentheses d, e, f = 4, 5, 6 # Now look how easy it is to swap two values @@ -306,6 +320,11 @@ filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} # Remove keys from a dictionary with del del filled_dict["one"] # Removes the key "one" from filled dict +# From Python 3.5 you can also use the additional unpacking options +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + + # Sets store ... well sets empty_set = set() @@ -332,6 +351,15 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6} # Do set difference with - {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} +# Do set symmetric difference with ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Check if set on the left is a superset of set on the right +{1, 2} >= {1, 2, 3} # => False + +# Check if set on the left is a subset of set on the right +{1, 2} <= {1, 2, 3} # => True + # Check for existence in a set with in 2 in filled_set # => True 10 in filled_set # => False @@ -439,7 +467,7 @@ with open("myfile.txt") as f: filled_dict = {"one": 1, "two": 2, "three": 3} our_iterable = filled_dict.keys() -print(our_iterable) # => range(1,10). This is an object that implements our Iterable interface +print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface. # We can loop over it. for i in our_iterable: @@ -528,19 +556,19 @@ x, y = swap(x, y) # => x = 2, y = 1 # Function Scope x = 5 -def setX(num): +def set_x(num): # Local var x not the same as global variable x x = num # => 43 print (x) # => 43 -def setGlobalX(num): +def set_global_x(num): global x print (x) # => 5 x = num # global var x is now set to 6 print (x) # => 6 -setX(43) -setGlobalX(6) +set_x(43) +set_global_x(6) # Python has first class functions @@ -589,6 +617,9 @@ class Human: # Assign the argument to the instance's name attribute self.name = name + # Initialize property + self.age = 0 + # An instance method. All methods take "self" as the first argument def say(self, msg): return "{name}: {message}".format(name=self.name, message=msg) @@ -604,6 +635,23 @@ class Human: def grunt(): return "*grunt*" + # A property is just like a getter. + # It turns the method age() into an read-only attribute + # of the same name. + @property + def age(self): + return self._age + + # This allows the property to be set + @age.setter + def age(self, age): + self._age = age + + # This allows the property to be deleted + @age.deleter + def age(self): + del self._age + # Instantiate a class i = Human(name="Ian") @@ -623,6 +671,17 @@ j.get_species() # => "H. neanderthalensis" # Call the static method Human.grunt() # => "*grunt*" +# Update the property +i.age = 42 + +# Get the property +i.age # => 42 + +# Delete the property +del i.age +i.age # => raises an AttributeError + + #################################################### ## 6. Modules diff --git a/pythonstatcomp.markdown.html b/pythonstatcomp.html.markdown index 78b62e33..78b62e33 100644 --- a/pythonstatcomp.markdown.html +++ b/pythonstatcomp.html.markdown diff --git a/r.html.markdown b/r.html.markdown index 93751df5..8539b10e 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -3,6 +3,7 @@ language: R contributors: - ["e99n09", "http://github.com/e99n09"] - ["isomorphismes", "http://twitter.com/isomorphisms"] + - ["kalinn", "http://github.com/kalinn"] filename: learnr.r --- @@ -15,7 +16,8 @@ R is a statistical computing language. It has lots of libraries for uploading an # You can't make multi-line comments, # but you can stack multiple comments like so. -# in Windows or Mac, hit COMMAND-ENTER to execute a line +# in Windows you can use CTRL-ENTER to execute a line. +# on Mac it is COMMAND-ENTER @@ -196,6 +198,14 @@ 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 @@ -234,6 +244,9 @@ class(NA) # "logical" 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: @@ -664,15 +677,101 @@ write.csv(pets, "pets2.csv") # to make a new .csv file ######################### +# 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") -# Regressions! -linearModel <- lm(price ~ time, data = list1) -linearModel # outputs result of regression # Plot regression line on existing plot abline(linearModel, col = "red") # Get a variety of nice diagnostics diff --git a/ru-ru/clojure-ru.html.markdown b/ru-ru/clojure-ru.html.markdown index 2f508a00..451da312 100644 --- a/ru-ru/clojure-ru.html.markdown +++ b/ru-ru/clojure-ru.html.markdown @@ -144,7 +144,7 @@ Clojure, это представитель семейства Lisp-подобн ;;;;;;;;;;;;;;;;;;;;; ; Функция создается специальной формой fn. -; "Тело"" функции может состоять из нескольких форм, +; "Тело" функции может состоять из нескольких форм, ; но результатом вызова функции всегда будет результат вычисления ; последней из них. (fn [] "Hello World") ; => fn diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown index 005495cc..b24ad555 100644 --- a/ru-ru/java-ru.html.markdown +++ b/ru-ru/java-ru.html.markdown @@ -451,7 +451,7 @@ public class Fruit implements Edible, Digestible { } } -// В Java Вы можете наследоватьтолько один класс, однако можете реализовывать +// В Java Вы можете наследовать только один класс, однако можете реализовывать // несколько интерфейсов. Например: public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { public void InterfaceOneMethod() { diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 8655ae4a..54499f46 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -330,7 +330,7 @@ function sayHelloInFiveSeconds(name) { sayHelloInFiveSeconds("Адам"); // Через 5 с откроется окно «Привет, Адам!» /////////////////////////////////// -// 5. Подробнее об объектах; конструкторы и прототипы +// 5. Подробнее об объектах; Конструкторы и Прототипы // Объекты могут содержать в себе функции. var myObj = { diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown index 5672aa90..37b6a86e 100644 --- a/ru-ru/php-ru.html.markdown +++ b/ru-ru/php-ru.html.markdown @@ -420,8 +420,6 @@ include_once 'my-file.php'; require 'my-file.php'; require_once 'my-file.php'; -// Same as include(), except require() will cause a fatal error if the -// file cannot be included. // Действует также как и include(), но если файл не удалось подключить, // функция выдает фатальную ошибку @@ -485,7 +483,7 @@ echo MyClass::MY_CONST; // Выведет 'value'; echo MyClass::$staticVar; // Выведет 'static'; MyClass::myStaticMethod(); // Выведет 'I am static'; -// Новый экземпляр класса используя new +// Создание нового экземпляра класса используя new $my_class = new MyClass('An instance property'); // Если аргументы отсутствуют, можно не ставить круглые скобки diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown index 3852a550..43142eff 100644 --- a/ru-ru/python-ru.html.markdown +++ b/ru-ru/python-ru.html.markdown @@ -280,7 +280,7 @@ filled_dict.get("four", 4) #=> 4 # Присваивайте значение ключам так же, как и в списках filled_dict["four"] = 4 # теперь filled_dict["four"] => 4 -# Метод setdefault вставляет() пару ключ-значение, только если такого ключа нет +# Метод setdefault() вставляет пару ключ-значение, только если такого ключа нет filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5 filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5 diff --git a/ruby.html.markdown b/ruby.html.markdown index 4e9f8aee..782ffc4c 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -42,13 +42,18 @@ You shouldn't either 2**5 #=> 32 5 % 3 #=> 2 +# Bitwise operators +3 & 5 #=> 1 +3 | 5 #=> 7 +3 ^ 5 #=> 6 + # Arithmetic is just syntactic sugar # for calling a method on an object 1.+(3) #=> 4 10.* 5 #=> 50 # Special values are objects -nil # Nothing to see here +nil # equivalent to null in other languages true # truth false # falsehood @@ -76,6 +81,11 @@ false.class #=> FalseClass 2 <= 2 #=> true 2 >= 2 #=> true +# Combined comparison operator +1 <=> 10 #=> -1 +10 <=> 1 #=> 1 +1 <=> 1 #=> 0 + # Logical operators true && false #=> false true || false #=> true @@ -121,7 +131,7 @@ puts "I'm printing!" # print to the output without a newline print "I'm printing!" -#=> I'm printing! => nill +#=> I'm printing! => nil # Variables x = 25 #=> 25 diff --git a/scala.html.markdown b/scala.html.markdown index 7f545196..bc8cd422 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -169,6 +169,12 @@ def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y // Syntax for calling functions is familiar: sumOfSquares(3, 4) // => 25 +// You can use parameters names to specify them in different order +def subtract(x: Int, y: Int): Int = x - y + +subtract(10, 3) // => 7 +subtract(y=10, x=3) // => -7 + // In most cases (with recursive functions the most notable exception), function // return type can be omitted, and the same type inference we saw with variables // will work with function return values: @@ -278,21 +284,21 @@ val text = if (x == 10) "yeah" else "nope" ///////////////////////////////////////////////// val a = Array(1, 2, 3, 5, 8, 13) -a(0) -a(3) +a(0) // Int = 1 +a(3) // Int = 5 a(21) // Throws an exception val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") -m("fork") -m("spoon") +m("fork") // java.lang.String = tenedor +m("spoon") // java.lang.String = cuchara m("bottle") // Throws an exception val safeM = m.withDefaultValue("no lo se") -safeM("bottle") +safeM("bottle") // java.lang.String = no lo se val s = Set(1, 3, 7) -s(0) -s(1) +s(0) // Boolean = false +s(1) // Boolean = true /* Look up the documentation of map here - * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map @@ -313,15 +319,16 @@ s(1) // Why have this? val divideInts = (x: Int, y: Int) => (x / y, x % y) -divideInts(10, 3) // The function divideInts gives you the result and the remainder +// The function divideInts gives you the result and the remainder +divideInts(10, 3) // (Int, Int) = (3,1) // To access the elements of a tuple, use _._n where n is the 1-based index of // the element -val d = divideInts(10, 3) +val d = divideInts(10, 3) // (Int, Int) = (3,1) -d._1 +d._1 // Int = 3 -d._2 +d._2 // Int = 1 ///////////////////////////////////////////////// diff --git a/swift.html.markdown b/swift.html.markdown index f451288d..f3746613 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Joey Huang", "http://github.com/kamidox"] - ["Anthony Nguyen", "http://github.com/anthonyn60"] - ["Clayton Walker", "https://github.com/cwalk"] + - ["Fernando Valverde", "http://visualcosita.xyz"] filename: learnswift.swift --- @@ -25,6 +26,7 @@ import UIKit // Xcode supports landmarks to annotate your code and lists them in the jump bar // MARK: Section mark +// MARK: - Section mark with a separator line // TODO: Do something soon // FIXME: Fix this code @@ -82,7 +84,7 @@ if someOptionalString != nil { someOptionalString = nil /* - Trying to use ! to access a non-existent optional value triggers a runtime + Trying to use ! to access a non-existent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value. */ @@ -128,6 +130,7 @@ shoppingList[1] = "bottle of water" let emptyArray = [String]() // let == immutable let emptyArray2 = Array<String>() // same as above var emptyMutableArray = [String]() // var == mutable +var explicitEmptyMutableStringArray: [String] = [] // same as above // Dictionary @@ -139,6 +142,7 @@ occupations["Jayne"] = "Public Relations" let emptyDictionary = [String: Float]() // let == immutable let emptyDictionary2 = Dictionary<String, Float>() // same as above var emptyMutableDictionary = [String: Float]() // var == mutable +var explicitEmptyMutableDictionary: [String: Float] = [:] // same as above // diff --git a/ta_in/css.html.markdown b/ta_in/css-ta.html.markdown index 56f94ed0..56f94ed0 100644 --- a/ta_in/css.html.markdown +++ b/ta_in/css-ta.html.markdown diff --git a/ta_in/javascript.html.markdown b/ta_in/javascript-ta.html.markdown index f0b0a36a..f0b0a36a 100644 --- a/ta_in/javascript.html.markdown +++ b/ta_in/javascript-ta.html.markdown diff --git a/ta_in/json.html.markdown b/ta_in/json-ta.html.markdown index d85e0d82..d85e0d82 100644 --- a/ta_in/json.html.markdown +++ b/ta_in/json-ta.html.markdown diff --git a/ta_in/xml.html.markdown b/ta_in/xml-ta.html.markdown index a9bfa9cd..a9bfa9cd 100644 --- a/ta_in/xml.html.markdown +++ b/ta_in/xml-ta.html.markdown diff --git a/tmux.html.markdown b/tmux.html.markdown index 49d1bba6..868302a8 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -38,7 +38,7 @@ then later reattached. lsp # List panes -a # List all panes -s # List all panes in session - -t # List app panes in target + -t # List all panes in target kill-window # Kill current window -t "#" # Kill target window diff --git a/tr-tr/brainfuck-tr.html.markdown b/tr-tr/brainfuck-tr.html.markdown index baca4217..bd842b17 100644 --- a/tr-tr/brainfuck-tr.html.markdown +++ b/tr-tr/brainfuck-tr.html.markdown @@ -19,7 +19,7 @@ gözardı edilir. Brainfuck 30,000 hücresi olan ve ilk değerleri sıfır olarak atanmış bir dizidir. İşaretçi ilk hücreyi işaret eder. -Sekik komut vardır: +Sekiz komut vardır: + : Geçerli hücrenin değerini bir artırır. - : Geçerli hücrenin değerini bir azaltır. > : Veri işaretçisini bir sonraki hücreye hareket ettirir(sağdaki hücreye). diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown index 128901de..2d4240ed 100644 --- a/tr-tr/c-tr.html.markdown +++ b/tr-tr/c-tr.html.markdown @@ -91,9 +91,9 @@ int main() { // Örneğin, printf("%lu\n", sizeof(int)); // => 4 (bir çok makinede 4-byte words) - // If the argument of the `sizeof` operator an expression, then its argument - // is not evaluated (except VLAs (see below)). - // The value it yields in this case is a compile-time constant. + // Eger arguman düzenli ifae olan sizeof operatoru ise degerlendirilmez. + // VLAs hariç asagiya bakiniz). + // Bu durumda verimliligin degeri derleme-zamani sabitidir. int a = 1; // size_t bir objeyi temsil etmek için kullanılan 2 byte uzunluğundaki bir @@ -101,7 +101,7 @@ int main() { size_t size = sizeof(a++); // a++ is not evaluated printf("sizeof(a++) = %zu where a = %d\n", size, a); - // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture) + // yazdirilan "sizeof(a++) = 4 where a = 1" (32-bit mimaride) // Diziler somut bir boyut ile oluşturulmalıdır. char my_char_array[20]; // Bu dizi 1 * 20 = 20 byte alan kaplar @@ -119,19 +119,19 @@ int main() { my_array[1] = 2; printf("%d\n", my_array[1]); // => 2 - // In C99 (and as an optional feature in C11), variable-length arrays (VLAs) - // 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 + // C99'da (ve C11 istege bagli bir ozellik olarak), değidken-uzunluklu diziler (VLAs) bildirilebilirler. + // Böyle bir dizinin boyuunu derlenmesi gerekmez + // zaman sabiti: + printf("Enter the array size: "); // dizi boyutu kullaniciya soruluyor char buf[0x100]; fgets(buf, sizeof buf, stdin); - // strtoul parses a string to an unsigned integer + // strtoul isaretsiz integerlar icin string ayiricisidir. size_t size = strtoul(buf, NULL, 10); int var_length_array[size]; // declare the VLA printf("sizeof array = %zu\n", sizeof var_length_array); - // A possible outcome of this program may be: + // Bu programın olası bir sonucu olabilir: // > Enter the array size: 10 // > sizeof array = 40 @@ -151,8 +151,8 @@ int main() { printf("%d\n", a_string[16]); // => 0 // i.e., byte #17 is 0 (as are 18, 19, and 20) - // If we have characters between single quotes, that's a character literal. - // It's of type `int`, and *not* `char` (for historical reasons). + // Tek tirnak arasinda karakterlere sahipsek, bu karakterler degismezdir. + // Tip `int` ise, `char` *degildir* (tarihsel sebeplerle). int cha = 'a'; // fine char chb = 'a'; // fine too (implicit conversion from int to char) @@ -201,10 +201,10 @@ int main() { 0x01 << 1; // => 0x02 (bitwise left shift (by 1)) 0x02 >> 1; // => 0x01 (bitwise right shift (by 1)) - // Be careful when shifting signed integers - the following are undefined: - // - shifting into the sign bit of a signed integer (int a = 1 << 32) - // - left-shifting a negative number (int a = -1 << 2) - // - shifting by an offset which is >= the width of the type of the LHS: + // Isaretli sayilari kaydirirken dikkatli olun - tanimsizlar sunlardir: + // - isaretli sayinin isaret bitinde yapilan 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 /////////////////////////////////////// @@ -485,4 +485,4 @@ Readable code is better than clever code and fast code. For a good, sane coding Diğer taraftan google sizin için bir arkadaş olabilir. -[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 diff --git a/ua-ua/javascript-ua.html.markdown b/ua-ua/javascript-ua.html.markdown new file mode 100644 index 00000000..fedbf5ac --- /dev/null +++ b/ua-ua/javascript-ua.html.markdown @@ -0,0 +1,501 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +filename: javascript-ru.js +translators: + - ["Alexey Gonchar", "http://github.com/finico"] + - ["Andre Polykanine", "https://github.com/Oire"] +lang: ru-ru +--- + +JavaScript було створено в 1995 році Бренданом Айком, який працював у копаніх Netscape. +Він був задуманий як проста мова сценаріїв для веб-сайтів, який би доповнював Java +для більш складних веб-застосунків. Але тісна інтеграція з веб-сторінками і +вбудована підтримка браузерами призвела до того, що JavaScript став популярніший +за власне Java. + +Зараз JavaScript не обмежується тільки веб-браузеорм. Наприклад, Node.js, +програмна платформа, що дозволяє виконувати JavaScript код з використанням +рушія V8 від браузера Google Chrome, стає все більш і більш популярною. + +```js +// С-подібні коментарі. Однорядкові коментарі починаються з двох символів /(слеш) +/* а багаторядкові коментарі починаються з послідовності слеша та зірочки і + закінчуються символами зірочка-слеш */ + +Інструкції можуть закінчуватися крапкою з комою ; +doStuff(); + +// ... але не обов’язково, тому що крапка з комою автоматично вставляється на +// місці символу нового рядка, крім деяких випадків. +doStuff() + +// Ми завжди будемо використовувати крапку з комою в цьому посібнику, тому що ці +// винятки можуть призвести до неочікуваних результатів + +/////////////////////////////////// +// 1. Числа, Рядки і Оператори + +// В JavaScript числа зберігаються тільки в одному форматі (64-bit IEEE 754 double) +// Цей тип має 52-бітну мантису, якої достатньо для збереження чисел з +// точністю до 9✕10¹⁵. +3; // = 3 +1.5; // = 1.5 + +// Деякі прості арифметичні операції працють так, як ми очікуємо. +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 (а деякі - ні) +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// В тому числі ділення з остачою +5 / 2; // = 2.5 + +// В JavaScript є побітові операції; коли ви виконуєте таку операцію, +// число з плаваючою точкою переводиться в ціле зі знаком +// довжиною *до* 32 розрядів. +1 << 2; // = 4 + +// Пріоритет у виразах можна задати явно круглими дужками +(1 + 3) * 2; // = 8 + +// Є три спеціальні значення, які не є реальними числами: +Infinity; // "нескінченність", наприклад, як результат ділення на 0 +-Infinity; // "мінус нескінченність", як результат ділення від’ємного числа на 0 +NaN; // "не число", наприклад, ділення 0/0 + +// Логічні типи +true; +false; + +// Рядки створюються за допомогою подвійних та одинарних лапок +'абв'; +"Hello, world!"; + +// Для логічного заперечення використовується знак оклику. +!true; // = false +!false; // = true + +// Строга рівність === +1 === 1; // = true +2 === 1; // = false + +// Строга нерівність !== +1 !== 1; // = false +2 !== 1; // = true + +// Інші оператори порівняння +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// Рядки об’єднуються за допомогою оператор + +"hello, " + "world!"; // = "hello, world!" + +// І порівнюються за допомогою > і < +"a" < "b"; // = true + +// Перевірка на рівність з приведнням типів здійснюється оператором == +"5" == 5; // = true +null == undefined; // = true + +// ... але приведення не виконується при === +"5" === 5; // = false +null === undefined; // = false + +// ... приведення типів може призвести до дивних результатів +13 + !0; // 14 +"13" + !0; // '13true' + +// Можна отримати доступ до будь-якого символа рядка за допомгою charAt +"Это строка".charAt(0); // = 'Э' + +// ... або використати метод substring, щоб отримати більший кусок +"Hello, world".substring(0, 5); // = "Hello" + +// length - це не метод, а поле +"Hello".length; // = 5 + +// Типи null и undefined +null; // навмисна відсутність результату +undefined; // використовується для позначення відсутності присвоєного значення + +// false, null, undefined, NaN, 0 и "" — хиба; все інше - істина. +// Потрібно відмітити, що 0 — це зиба, а "0" — істина, не зважаючи на те що: +// 0 == "0". + +/////////////////////////////////// +// 2. Змінні, Масиви, Об’єкти + +// Змінні оголошуються за допомогою ключового слова var. JavaScript — мова з +// динамічною типізацією, тому не потрібно явно вказувати тип. Для присвоєння +// значення змінної використовується символ = +var someVar = 5; + +// якщо пропустити слово var, ви не отримаєте повідомлення про помилку, ... +someOtherVar = 10; + +// ... але ваша змінна буде створення в глобальному контексті, а не там, де +// ви її оголосили + +// Змінні, які оголошені без присвоєння, автоматично приймають значення undefined +var someThirdVar; // = undefined + +// У математичних операцій є скорочені форми: +someVar += 5; // як someVar = someVar + 5; +someVar *= 10; // тепер someVar = 100 + +// Інкремент і декремент +someVar++; // тепер someVar дорівнює 101 +someVar--; // а зараз 100 + +// Масиви — це нумеровані списку, які зберігають значення будь-якого типу. +var myArray = ["Hello", 45, true]; + +// Доступ до елементів можна отримати за допомогою синтаксиса з квадратними дужками +// Індексація починається з нуля +myArray[1]; // = 45 + +// Массивы можно изменять, как и их длину, +myArray.push("Мир"); +myArray.length; // = 4 + +// додавання і редагування елементів +myArray[3] = "Hello"; + +// Об’єкти в JavaScript сході на словники або асоціативні масиви в інших мовах +var myObj = {key1: "Hello", key2: "World"}; + +// Ключі - це рядки, але лапки не обов’язкі, якщо ключ задовольняє +// правилам формування назв змінних. Значення можуть бути будь-яких типів. +var myObj = {myKey: "myValue", "my other key": 4}; + +// Атрибути можна отримати використовуючи квадратні дужки +myObj["my other key"]; // = 4 + +// Або через точку, якщо ключ є правильним ідентифікатором +myObj.myKey; // = "myValue" + +// Об’єкти можна динамічно змінювати й додавати нові поля +myObj.myThirdKey = true; + +// Коли ви звертаєтесб до поля, яке не існує, ви отримуєте значення undefined +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. Управляючі конструкції + +// Синтаксис для цього розділу майже такий самий, як у Java + +// Умовна конструкція +var count = 1; +if (count == 3) { + // виконується, якщо count дорівнює 3 +} else if (count == 4) { + // .. +} else { + // ... +} + +// ... цикл while. +while (true){ + // Нескінченний цикл! +} + +// Цикл do-while такий самий, як while, але завжди виконується принаймні один раз. +var input +do { + input = getInput(); +} while (!isValid(input)) + +// цикл for такий самий, кяк в C і Java: +// ініціалізація; умова; крок. +for (var i = 0; i < 5; i++) { + // виконається 5 разів +} + +// && — логічне І, || — логічне АБО +if (house.size == "big" && house.color == "blue") { + house.contains = "bear"; +} +if (color == "red" || color == "blue") { + // колір червоний або синій +} + +// && і || використовують скорочене обчислення +// тому їх можна використовувати для задання значень за замовчуванням. +var name = otherName || "default"; + +// Оператор switch виконує перевірку на рівність за допомогою === +// використовуйте break, щоб призупити виконання наступного case, +grade = 4; +switch (grade) { + case 5: + console.log("Відмінно"); + break; + case 4: + console.log("Добре"); + break; + case 3: + console.log("Можна краще"); + break; + default: + console.log("Погано!"); + break; +} + + +/////////////////////////////////// +// 4. Функції, область видимості і замикання + +// Функції в JavaScript оголошуються за допомогою ключового слова function. +function myFunction(thing) { + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +// Зверність увагу, що значення яке буде повернено, повинно починатися на тому ж +// рядку, що і ключове слово return, інакше завжди буде повертатися значення undefined +// із-за автоматичної вставки крапки з комою +function myFunction() +{ + return // <- крапка з комою вставляється автоматично + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + +// В JavaScript функції - це об`єкти першого класу, тому вони можуть присвоюватися +// іншим змінним і передаватися іншим функціям, наприклад, щоб визначити обробник +// події. +function myFunction() { + // код буде виконано через 5 сек. +} +setTimeout(myFunction, 5000); +// setTimeout не є частиною мови, але реалізований в браузерах і Node.js + +// Функции не обязательно должны иметь имя при объявлении — вы можете написать +// анонимное определение функции непосредственно в аргументе другой функции. +// Функції не обов’язково мають мати ім’я при оголошенні — ви можете написати +// анонімну функцію прямо в якості аргумента іншої функції +setTimeout(function() { + // Цей код буде виконано через п’ять секунд +}, 5000); + +// В JavaScript реалізована концепція області видимості; функції мають свою +// область видимости, а інші блоки не мають +if (true) { + var i = 5; +} +i; // = 5, а не undefined, як це звичайно буває в інших мова + +// Така особливість призвела до шаблону "анонімних функцій, які викликають самих себе" +// що дозволяє уникнути проникнення змінних в глобальну область видимості +(function() { + var temporary = 5; + // об’єкт window зберігає глобальний контекст; таким чином ми можемо також додавати + // змінні до глобальної області + window.permanent = 10; +})(); +temporary; // повідомлення про помилку ReferenceError +permanent; // = 10 + +// Одной из самых мощных возможностей JavaScript являются замыкания. Если функция +// определена внутри другой функции, то внутренняя функция имеет доступ к +// переменным внешней функции даже после того, как контекст выполнения выйдет из +// внешней функции. +// Замикання - одна з найпотужніших інтрументів JavaScript. Якщо функція визначена +// всередині іншої функції, то внутрішня функція має доступ до змінних зовнішньої +// функції навіть після того, як код буде виконуватися поза контекстом зовнішньої функції +function sayHelloInFiveSeconds(name) { + var prompt = "Hello, " + name + "!"; + // Внутрішня функція зберігається в локальній області так, + // ніби функція була оголошена за допомогою ключового слова var + function inner() { + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout асинхронна, тому функція sayHelloInFiveSeconds зразу завершиться, + // після чого setTimeout викличе функцію inner. Але функція inner + // «замкнута» кругом sayHelloInFiveSeconds, вона все рівно має доступ до змінної prompt +} +sayHelloInFiveSeconds("Адам"); // Через 5 с відкриється вікно «Hello, Адам!» + +/////////////////////////////////// +// 5. Об’єкти: конструктори і прототипи + +// Об’єкти можуть містити функції +var myObj = { + myFunc: function() { + return "Hello, world!"; + } +}; +myObj.myFunc(); // = "Hello, world!" + +// Функції, що прикріплені до об’єктів мають доступ до поточного об’єкта за +// допомогою ключового слова this. +myObj = { + myString: "Hello, world!", + myFunc: function() { + return this.myString; + } +}; +myObj.myFunc(); // = "Hello, world!" + +// Значення this залежить від того, як функція викликається +// а не від того, де вона визначена. Таким чином наша функція не працює, якщо +// вона викликана не в контексті об’єкта +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// Функція може бути присвоєна іншому об’єкту. Тоді вона матиме доступ до +// цього об’єкта через this +var myOtherFunc = function() { +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO, WORLD!" + +// Контекст виконання функції можна задати за допомогою сall або apply +var anotherFunc = function(s) { + return this.myString + s; +} +anotherFunc.call(myObj, " Hello!"); // = "Hello, world! Hello!" + +// Функцiя apply приймає в якості аргументу масив +anotherFunc.apply(myObj, [" Hello!"]); // = "Hello, world! Hello!" + +// apply можна використати, коли функція працює послідовністю аргументів, а +// ви хочете передати масив +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (Ой-ой!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// Але call і apply — тимчасові. Коли ми хочемо зв’язати функцію і об’єкт +// використовують bind +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" Hello!"); // = "Hello world, Hello!" + +// Bind можна використати для задання аргументів +var product = function(a, b) { return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// Коли ви викликаєте функцію за допомогою ключового слова new, створюється новий об’єкт, +// доступний функції за допомогою this. Такі функції називають конструкторами. +var MyConstructor = function() { + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// У кожного об’єкта є прототип. Коли ви звертаєтесь до поля, яке не існує в цьому +// об’єктів, інтерпретатор буде шукати поле в прототипі + +// Деякі реалізації мови дозволяють отримати доступ до прототипа об’єкта через +// "магічну" властивість __proto__. Це поле не є частиною стандарта, але існують +// стандартні способи використання прототипів, які ми побачимо пізніше +var myObj = { + myString: "Hello, world!" +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function() { + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// Аналогічно для функцій +myObj.myFunc(); // = "Hello, world!" + +// Якщо інтерпретатор не знайде властивість в прототипі, то він продвжить пошук +// в прототипі прототипа і так далі +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// Кожег об’єкт зберігає посилання на свій прототип. Це значить, що ми можемо змінити +// наш прототип, і наші зміни будуть всюди відображені. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// Ми сказали, що властивість __proto__ нестандартне, і нема ніякого стандартного способу +// змінити прототип об’єкта, що вже існує. Але є два способи створити новий об’єкт зі заданим +// прототипом + +// Перший спосіб — це Object.create, який з’явився JavaScript недавно, +// а тому в деяких реалізаціях може бути не доступним. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// Другий спосіб: у конструкторів є властивість з іменем prototype. Це *не* +// прототип функції-конструктора, це прототип для нових об’єктів, які будуть створені +// цим конструктором і ключового слова new. +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function() { + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 + +// У вбудованих типів(рядок, число) теж є конструктори, які створють еквівалентні +// об’єкти-обгортки +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// Але вони не ідентичні +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0) { + // Этот код не выполнится, потому что 0 - это ложь. +} + +// Об’єкти-обгортки і вбудовані типи мають спільні прототипи, тому +// ви можете розширити функціонал рядків: +String.prototype.firstCharacter = function() { + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// Такий прийом часто використовуються в поліфілах, які реалізують нові можливості +// JavaScript в старій реалізації мови, так що вони можуть бути використані в старих +// середовищах + +// Наприклад, Object.create доступний не у всіх реалізація, но ми можемо +// використати функції за допомогою наступного поліфіла: +if (Object.create === undefined) { // не перезаписываем метод, если он существует + Object.create = function(proto) { + // Створюємо правильний конструктор з правильним прототипом + var Constructor = function(){}; + Constructor.prototype = proto; + + return new Constructor(); + } +} +``` + +## Що почитати + +[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/ diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown index bdfdcc10..dfb89307 100644 --- a/visualbasic.html.markdown +++ b/visualbasic.html.markdown @@ -9,13 +9,13 @@ filename: learnvisualbasic.vb Module Module1 Sub Main() - ' A Quick Overview of Visual Basic Console Applications before we dive - ' in to the deep end. - ' Apostrophe starts comments. - ' To Navigate this tutorial within the Visual Basic Complier, I've put - ' together a navigation system. - ' This navigation system is explained however as we go deeper into this - ' tutorial, you'll understand what it all means. + 'A Quick Overview of Visual Basic Console Applications before we dive + 'in to the deep end. + 'Apostrophe starts comments. + 'To Navigate this tutorial within the Visual Basic Complier, I've put + 'together a navigation system. + 'This navigation system is explained however as we go deeper into this + 'tutorial, you'll understand what it all means. Console.Title = ("Learn X in Y Minutes") Console.WriteLine("NAVIGATION") 'Display Console.WriteLine("") @@ -32,6 +32,9 @@ Module Module1 Console.WriteLine("50. About") Console.WriteLine("Please Choose A Number From The Above List") Dim selection As String = Console.ReadLine + 'The "Case" in the Select statement is optional. + 'For example, "Select selection" instead of "Select Case selection" + 'will also work. Select Case selection Case "1" 'HelloWorld Output Console.Clear() 'Clears the application and opens the private sub @@ -88,12 +91,12 @@ Module Module1 'Two Private Sub HelloWorldInput() Console.Title = "Hello World YourName | Learn X in Y Minutes" - ' Variables - ' Data entered by a user needs to be stored. - ' Variables also start with a Dim and end with an As VariableType. + 'Variables + 'Data entered by a user needs to be stored. + 'Variables also start with a Dim and end with an As VariableType. - ' In this tutorial, we want to know what your name, and make the program - ' respond to what is said. + 'In this tutorial, we want to know what your name, and make the program + 'respond to what is said. Dim username As String 'We use string as string is a text based variable. Console.WriteLine("Hello, What is your name? ") 'Ask the user their name. diff --git a/whip.html.markdown b/whip.html.markdown index 3faee98a..e7e5e427 100644 --- a/whip.html.markdown +++ b/whip.html.markdown @@ -2,13 +2,14 @@ language: whip contributors: - ["Tenor Biel", "http://github.com/L8D"] + - ["Saurabh Sandav", "http://github.com/SaurabhSandav"] author: Tenor Biel author_url: http://github.com/L8D filename: whip.lisp --- Whip is a LISP-dialect made for scripting and simplified concepts. -It has also borrowed a lot of functions and syntax from Haskell(a non-related language). +It has also borrowed a lot of functions and syntax from Haskell (a non-related language). These docs were written by the creator of the language himself. So is this line. @@ -93,13 +94,13 @@ null ; used to indicate a deliberate non-value undefined ; user to indicate a value that hasn't been set ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -; 2. Vairbles, Lists, and Dicts +; 2. Variables, Lists, and Dicts ; Variables are declared with the `def` or `let` functions. ; Variables that haven't been set will be `undefined`. (def some_var 5) ; `def` will keep the variable in the global context. -; `let` will only have the variable inside its context, and has a wierder syntax. +; `let` will only have the variable inside its context, and has a weirder syntax. (let ((a_var 5)) (+ a_var 5)) ; => 10 (+ a_var 5) ; = undefined + 5 => undefined @@ -163,7 +164,7 @@ undefined ; user to indicate a value that hasn't been set (my_function 10 10) ; = (+ (+ 10 10) 10) => 30 -; Obiously, all lambdas by definition are anonymous and +; Obviously, all lambdas by definition are anonymous and ; technically always used anonymously. Redundancy. ((lambda (x) x) 10) ; => 10 @@ -171,12 +172,12 @@ undefined ; user to indicate a value that hasn't been set ; Comprehensions ; `range` or `..` generates a list of numbers for -; each number between it's two args. +; each number between its two args. (range 1 5) ; => (1 2 3 4 5) (.. 0 2) ; => (0 1 2) -; `map` applies it's first arg(which should be a lambda/function) -; to each item in the following arg(which should be a list) +; `map` applies its first arg (which should be a lambda/function) +; to each item in the following arg (which should be a list) (map (-> (x) (+ x 1)) (1 2 3)) ; => (2 3 4) ; Reduce @@ -191,7 +192,7 @@ undefined ; user to indicate a value that hasn't been set (slice (.. 1 5) 2) ; => (3 4 5) (\ (.. 0 100) -5) ; => (96 97 98 99 100) -; `append` or `<<` is self expanatory +; `append` or `<<` is self explanatory (append 4 (1 2 3)) ; => (1 2 3 4) (<< "bar" ("foo")) ; => ("foo" "bar") diff --git a/xml.html.markdown b/xml.html.markdown index efc2340f..b4b54330 100644 --- a/xml.html.markdown +++ b/xml.html.markdown @@ -3,18 +3,77 @@ language: xml filename: learnxml.xml contributors: - ["João Farias", "https://github.com/JoaoGFarias"] + - ["Rachel Stiyer", "https://github.com/rstiyer"] + - ["Deepanshu Utkarsh", "https://github.com/duci9y"] --- -XML is a markup language designed to store and transport data. +XML is a markup language designed to store and transport data. It is supposed to be both human readable and machine readable. Unlike HTML, XML does not specify how to display or to format data, it just carries it. -* XML Syntax +Distinctions are made between the **content** and the **markup**. In short, content could be anything, markup is defined. + +## Some definitions and introductions + +XML Documents are basically made up of *elements* which can have *attributes* describing them and may contain some textual content or more elements as its children. All XML documents must have a root element, which is the ancestor of all the other elements in the document. + +XML Parsers are designed to be very strict, and will stop parsing malformed documents. Therefore it must be ensured that all XML documents follow the [XML Syntax Rules](http://www.w3schools.com/xml/xml_syntax.asp). ```xml -<!-- Comments in XML are like this --> +<!-- This is a comment. It must not contain two consecutive hyphens (-). --> +<!-- Comments can span + multiple lines --> + +<!-- Elements --> +<!-- An element is a basic XML component. There are two types, empty: --> +<element1 attribute="value" /> <!-- Empty elements do not hold any content --> +<!-- and non-empty: --> +<element2 attribute="value">Content</element2> +<!-- Element names may only contain alphabets and numbers. --> + +<empty /> <!-- An element either consists an empty element tag… --> +<!-- …which does not hold any content and is pure markup. --> + +<notempty> <!-- Or, it consists of a start tag… --> + <!-- …some content… --> +</notempty> <!-- and an end tag. --> + +<!-- Element names are case sensitive. --> +<element /> +<!-- is not the same as --> +<eLEMENT /> + +<!-- Attributes --> +<!-- An attribute is a key-value pair and exists within an element. --> +<element attribute="value" another="anotherValue" many="space-separated list" /> +<!-- An attribute may appear only once in an element. It holds just one value. + Common workarounds to this involve the use of space-separated lists. --> + +<!-- Nesting elements --> +<!-- An element's content may include other elements: --> +<parent> + <child>Text</child> + <emptysibling /> +</parent> +<!-- Standard tree nomenclature is followed. Each element being called a node. + An ancestor a level up is the parent, descendants a level down are children. + Elements within the same parent element are siblings. --> + +<!-- XML preserves whitespace. --> +<child> + Text +</child> +<!-- is not the same as --> +<child>Text</child> +``` + +## An XML document +This is what makes XML versatile. It is human readable too. The following document tells us that it defines a bookstore which sells three books, one of which is Learning XML by Erik T. Ray. All this without having used an XML Parser yet. + +```xml <?xml version="1.0" encoding="UTF-8"?> +<!-- This is called an XML prolog. Optional, but recommended. --> <bookstore> <book category="COOKING"> <title lang="en">Everyday Italian</title> @@ -35,85 +94,49 @@ Unlike HTML, XML does not specify how to display or to format data, it just carr <price>39.95</price> </book> </bookstore> - -<!-- Above is a typical XML file. - It starts with a declaration, informing some metadata (optional). - - XML uses a tree structure. Above, the root node is 'bookstore', which has - three child nodes, all 'books'. Those nodes have more child nodes (or - children), and so on... - - Nodes are created using open/close tags, and children are just nodes between - the open and close tags.--> - - -<!-- XML carries two kinds of data: - 1 - Attributes -> That's metadata about a node. - Usually, the XML parser uses this information to store the data properly. - It is characterized by appearing with the format name="value" within the opening - tag. - 2 - Elements -> That's pure data. - That's what the parser will retrieve from the XML file. - Elements appear between the open and close tags. --> - - -<!-- Below, an element with two attributes --> -<file type="gif" id="4293">computer.gif</file> - - ``` -* 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. +## Well-formedness and Validation -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. +A XML document is *well-formed* if it is syntactically correct. However, it is possible to add more constraints to the document, using Document Type Definitions (DTDs). A document whose elements are attributes are declared in a DTD and which follows the grammar specified in that DTD is called *valid* with respect to that DTD, in addition to being well-formed. ```xml - -<!-- Below, you can see an simplified version of bookstore document, - with the addition of DTD definition.--> - +<!-- Declaring a DTD externally: --> <?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE note SYSTEM "Bookstore.dtd"> +<!DOCTYPE bookstore SYSTEM "Bookstore.dtd"> +<!-- Declares that bookstore is our root element and 'Bookstore.dtd' is the path + to our DTD file. --> <bookstore> <book category="COOKING"> - <title>Everyday Italian</title> + <title lang="en">Everyday Italian</title> + <author>Giada De Laurentiis</author> + <year>2005</year> <price>30.00</price> </book> </bookstore> -<!-- This DTD could be something like:--> - -<!DOCTYPE note -[ +<!-- The DTD file: --> <!ELEMENT bookstore (book+)> -<!ELEMENT book (title,price)> +<!-- The bookstore element may contain one or more child book elements. --> +<!ELEMENT book (title, price)> +<!-- Each book must have a title and a price as its children. --> <!ATTLIST book category CDATA "Literature"> +<!-- A book should have a category attribute. If it doesn't, its default value + will be 'Literature'. --> <!ELEMENT title (#PCDATA)> +<!-- The element title must only contain parsed character data. That is, it may + only contain text which is read by the parser and must not contain children. + Compare with CDATA, or character data. --> <!ELEMENT price (#PCDATA)> ]> - -<!-- The DTD starts with a declaration. - Following, the root node is declared, requiring 1 or more child nodes 'book'. - Each 'book' should contain exactly one 'title' and 'price' and an attribute - called 'category', with "Literature" as its default value. - The 'title' and 'price' nodes contain a parsed character data.--> - <!-- The DTD could be declared inside the XML file itself.--> <?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE note -[ +<!DOCTYPE bookstore [ <!ELEMENT bookstore (book+)> -<!ELEMENT book (title,price)> +<!ELEMENT book (title, price)> <!ATTLIST book category CDATA "Literature"> <!ELEMENT title (#PCDATA)> <!ELEMENT price (#PCDATA)> @@ -126,3 +149,18 @@ With this tool, you can check the XML data outside the application logic. </book> </bookstore> ``` + +## DTD Compatibility and XML Schema Definitions + +Support for DTDs is ubiquitous because they are so old. Unfortunately, modern XML features like namespaces are not supported by DTDs. XML Schema Definitions (XSDs) are meant to replace DTDs for defining XML document grammar. + +## Resources + +* [Validate your XML](http://www.xmlvalidation.com) + +## Further Reading + +* [XML Schema Definitions Tutorial](http://www.w3schools.com/schema/) +* [DTD Tutorial](http://www.w3schools.com/xml/xml_dtd_intro.asp) +* [XML Tutorial](http://www.w3schools.com/xml/default.asp) +* [Using XPath queries to parse XML](http://www.w3schools.com/xml/xml_xpath.asp) diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown index 8904970f..b0b1183f 100644 --- a/zh-cn/haskell-cn.html.markdown +++ b/zh-cn/haskell-cn.html.markdown @@ -200,13 +200,13 @@ foo 5 -- 75 -- 你可以使用 `$` 来移除多余的括号。 -- 修改前 -(even (fib 7)) -- true +(even (fib 7)) -- False -- 修改后 -even . fib $ 7 -- true +even . fib $ 7 -- False -- 等价地 -even $ fib 7 -- true +even $ fib 7 -- False ---------------------------------------------------- -- 5. 类型声明 diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown index 12afa59a..a8fd2a4c 100644 --- a/zh-cn/java-cn.html.markdown +++ b/zh-cn/java-cn.html.markdown @@ -405,4 +405,4 @@ class PennyFarthing extends Bicycle { * [泛型](http://docs.oracle.com/javase/tutorial/java/generics/index.html) -* [Java代码规范](http://www.oracle.com/technetwork/java/codeconv-138413.html) +* [Java代码规范](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) |