diff options
72 files changed, 8082 insertions, 515 deletions
diff --git a/README.markdown b/README.markdown index 28fa5093..94afbcbe 100644 --- a/README.markdown +++ b/README.markdown @@ -8,7 +8,7 @@ commented code and explained as they go. ... to write more inline code tutorials. Just grab an existing file from this repo and copy the formatting (don't worry, it's all very simple). -Make a new file, send a pull request, and if it passes master I'll get it up pronto. +Make a new file, send a pull request, and if it passes muster I'll get it up pronto. Remember to fill in the "contributors" fields so you get credited properly! @@ -18,7 +18,7 @@ All contributions are welcome, from the tiniest typo to a brand new article. Tra in all languages are welcome (or, for that matter, original articles in any language). Send a pull request or open an issue any time of day or night. -**Please tag your issues pull requests with [language/lang-code] at the beginning** +**Please tag your issues and pull requests with [language/lang-code] at the beginning** **(e.g. [python/en] for English Python).** This will help everyone pick out things they care about. diff --git a/c++.html.markdown b/c++.html.markdown index 2bee51dc..d03092e5 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -310,6 +310,70 @@ basic_string(basic_string&& other); // constructor that "salvages" parts of that temporary string. You will see this // concept referred to as "move semantics". +///////////////////// +// Enums +///////////////////// + +// Enums are a way to assign a value to a constant most commonly used for +// easier visualization and reading of code +enum ECarTypes +{ + Sedan, + Hatchback, + SUV, + Wagon +}; + +ECarTypes GetPreferredCarType() +{ + return ECarTypes::Hatchback; +} + +// As of C++11 there is an easy way to assign a type to the enum which can be +// useful in serialization of data and converting enums back-and-forth between +// the desired type and their respective constants +enum ECarTypes : uint8_t +{ + Sedan, // 0 + Hatchback, // 1 + SUV = 254, // 254 + Hybrid // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Serialize the InputValue to a file +} + +void WritePreferredCarTypeToFile(ECarTypes InputCarType) +{ + // The enum is implicitly converted to a uint8_t due to its declared enum type + WriteByteToFile(InputCarType); +} + +// On the other hand you may not want enums to be accidentally cast to an integer +// type or to other enums so it is instead possible to create an enum class which +// won't be implicitly converted +enum class ECarTypes : uint8_t +{ + Sedan, // 0 + Hatchback, // 1 + SUV = 254, // 254 + Hybrid // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Serialize the InputValue to a file +} + +void WritePreferredCarTypeToFile(ECarTypes InputCarType) +{ + // Won't compile even though ECarTypes is a uint8_t due to the enum + // being declared as an "enum class"! + WriteByteToFile(InputCarType); +} + ////////////////////////////////////////// // Classes and object-oriented programming ////////////////////////////////////////// diff --git a/c.html.markdown b/c.html.markdown index a8f71057..3d632eab 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -445,6 +445,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 +541,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/clojure.html.markdown b/clojure.html.markdown index a125d18f..58e835c9 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -264,6 +264,31 @@ keymap ; => {:a 1, :b 2, :c 3} (print "Saying hello to " name) (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") + +; Use the threading macros (-> and ->>) to express transformations of +; data more clearly. + +; The "Thread-first" macro (->) inserts into each form the result of +; the previous, as the first argument (second item) +(-> + {:a 1 :b 2} + (assoc :c 3) ;=> (assoc {:a 1 :b 2} :c 3) + (dissoc :b)) ;=> (dissoc (assoc {:a 1 :b 2} :c 3) :b) + +; This expression could be written as: +; (dissoc (assoc {:a 1 :b 2} :c 3) :b) +; and evaluates to {:a 1 :c 3} + +; The double arrow does the same thing, but inserts the result of +; each line at the *end* of the form. This is useful for collection +; operations in particular: +(->> + (range 10) + (map inc) ;=> (map inc (range 10) + (filter odd?) ;=> (filter odd? (map inc (range 10)) + (into [])) ;=> (into [] (filter odd? (map inc (range 10))) + ; Result: [1 3 5 7 9] + ; Modules ;;;;;;;;;;;;;;; diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown index e2f0737d..70804a1e 100644 --- a/coldfusion.html.markdown +++ b/coldfusion.html.markdown @@ -1,14 +1,14 @@ --- -language: ColdFusion +language: coldfusion +filename: learncoldfusion.cfm contributors: - ["Wayne Boka", "http://wboka.github.io"] -filename: LearnColdFusion.cfm --- ColdFusion is a scripting language for web development. [Read more here.](http://www.adobe.com/products/coldfusion-family.html) -```ColdFusion +```html <em>HTML tags have been provided for output readability</em> diff --git a/csharp.html.markdown b/csharp.html.markdown index 7aca2c6f..dfdd98de 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] - ["Wouter Van Schandevijl", "http://github.com/laoujin"] - ["Jo Pearce", "http://github.com/jdpearce"] + - ["Chris Zimmerman", "https://github.com/chriszimmerman"] filename: LearnCSharp.cs --- @@ -394,6 +395,7 @@ on a new line! ""Wow!"", the masses cried"; ref int maxCount, // Pass by reference out int count) { + //the argument passed in as 'count' will hold the value of 15 outside of this function count = 15; // out param must be assigned before control leaves the method } @@ -911,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/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/csharp-de.html.markdown b/de-de/csharp-de.html.markdown index 8ad7d71f..78bb0a6b 100644 --- a/de-de/csharp-de.html.markdown +++ b/de-de/csharp-de.html.markdown @@ -883,7 +883,7 @@ zur nächsten Zeile, ""Wahnsinn!"", die Massen waren kaum zu bändigen"; * [LINQ](http://shop.oreilly.com/product/9780596519254.do)
* [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx)
* [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials)
- * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials)
+ * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/overview/exploring-webmatrix)
* [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials)
* [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208)
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/latex-de.html.markdown b/de-de/latex-de.html.markdown new file mode 100644 index 00000000..2c18b8fd --- /dev/null +++ b/de-de/latex-de.html.markdown @@ -0,0 +1,235 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] +translators: + - ["Moritz Kammerer", "https://github.com/phxql"] +lang: de-de +filename: latex-de.tex +--- +``` +% Alle Kommentare starten fangen mit % an +% Es gibt keine Kommentare über mehrere Zeilen + +% LateX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B. +% MS Word oder OpenOffice Writer + +% Jedes LateX-Kommando startet mit einem Backslash (\) + +% LateX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen +% Weitere Dokumententypen sind z.B. book, report, presentations, etc. +% Optionen des Dokuments stehen zwischen den eckigen Klammern []. In diesem Fall +% wollen wir einen 12 Punkte-Font verwenden. +\documentclass[12pt]{article} + +% Als nächstes definieren wir die Pakete, die wir verwenden wollen. +% Wenn du z.B. Grafiken, farbigen Text oder Quelltext in dein Dokument einbetten möchtest, +% musst du die Fähigkeiten von Latex durch Hinzufügen von Paketen erweitern. +% Wir verwenden die Pakete float und caption für Bilder. +\usepackage{caption} +\usepackage{float} + +% Mit diesem Paket können leichter Umlaute getippt werden +\usepackage[utf8]{inputenc} + +% Es können durchaus noch weitere Optione für das Dokument gesetzt werden! +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} +\date{\today} +\title{Learn LaTeX in Y Minutes!} + +% Nun kann's losgehen mit unserem Dokument. +% Alles vor dieser Zeile wird die Preamble genannt. +\begin{document} +% Wenn wir den Autor, das Datum und den Titel gesetzt haben, kann +% LateX für uns eine Titelseite generieren +\maketitle + +% Die meisten Paper haben ein Abstract. LateX bietet dafür einen vorgefertigen Befehl an. +% Das Abstract sollte in der logischen Reihenfolge, also nach dem Titel, aber vor dem +% Inhalt erscheinen. +% Dieser Befehl ist in den Dokumentenklassen article und report verfügbar. +\begin{abstract} + LateX documentation geschrieben in LateX! Wie ungewöhnlich und garantiert nicht meine Idee! +\end{abstract} + +% Section Befehle sind intuitiv. +% Alle Titel der sections werden automatisch in das Inhaltsverzeichnis übernommen. +\section{Einleitung} +Hi, mein Name ist Moritz und zusammen werden wir LateX erforschen! + +\section{Noch eine section} +Das hier ist der Text für noch eine section. Ich glaube, wir brauchen eine subsection. + +\subsection{Das ist eine subsection} % Subsections sind auch ziemlich intuitiv. +Ich glaube, wir brauchen noch eine. + +\subsubsection{Pythagoras} +So ist's schon viel besser. +\label{subsec:pythagoras} + +% Wenn wir den Stern nach section schreiben, dann unterdrückt LateX die Nummerierung. +% Das funktioniert auch bei anderen Befehlen. +\section*{Das ist eine unnummerierte section} +Es müssen nicht alle sections nummeriert sein! + +\section{Ein paar Notizen} +LateX ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht. +Falls eine Zeile \\ mal \\ woanders \\ umgebrochen \\ werden \\ soll, füge +\textbackslash\textbackslash in den Code ein.\\ + +\section{Listen} +Listen sind eine der einfachsten Dinge in LateX. Ich muss morgen einkaufen gehen, +also lass uns eine Einkaufsliste schreiben: +\begin{enumerate} % Dieser Befehl erstellt eine "enumerate" Umgebung. + % \item bringt enumerate dazu, eins weiterzuzählen. + \item Salat. + \item 27 Wassermelonen. + \item einen Hasen. + % Wir können die Nummer des Eintrags durch [] überschreiben + \item[Wie viele?] Mittelgroße Wasserpistolen. + + Kein Listeneintrag, aber immer noch Teil von enumerate. + +\end{enumerate} % Alle Umgebungen müssen ein end haben. + +\section{Mathe} + +Einer der Haupteinsatzzwecke von LateX ist das Schreiben von akademischen +Artikeln oder Papern. Meistens stammen diese aus dem Bereich der Mathe oder +anderen Wissenschaften. Und deswegen müssen wir in der Lage sein, spezielle +Symbole zu unserem Paper hinzuzufügen! \\ + +Mathe kennt sehr viele Symbole, viel mehr als auf einer Tastatur zu finden sind; +Symbole für Mengen und relationen, Pfeile, Operatoren und Griechische Buchstaben, +um nur ein paar zu nennen.\\ + +Mengen und Relationen spielen eine sehr wichtige Rolle in vielen mathematischen +Papern. So schreibt man in LateX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\ + +% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LateX schreiben, +% geschieht dies standardmäßig im Textmodus. Die Mathe-Symbole existieren allerdings +% nur im Mathe-Modus. Wir können den Mathe-Modus durch das $ Zeichen aktivieren und +% ihn mit $ wieder verlassen. Variablen können auch im Mathe-Modus angezeigt werden. + +Mein Lieblingsbuchstabe im Griechischen ist $\xi$. Ich mag auch $\beta$, $\gamma$ und $\sigma$. +Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den LateX nicht kennt! + +Operatoren sind ebenfalls wichtige Bestandteile von mathematischen Dokumenten: +Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$), +Logarithmus und Exponenten ($\log$, $\exp$), +Grenzwerte ($\lim$), etc. haben vordefinierte Befehle. +Lass uns eine Gleichung schreiben: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$\\ + +Brüche (Zähler / Nenner) können so geschrieben werden: + +% 10 / 7 +$^{10}/_{7}$ + +% Komplexere Brüche können so geschrieben werden: +% \frac{Zähler}{Nenner} +$\frac{n!}{k!(n - k)!}$ \\ + +Wir können Gleichungen auch in einer equation Umgebung verwenden. + +% Dies zeigt Mathe in einer equation Umgebung an +\begin{equation} % Aktiviert automatisch den Mathe-Modus. + c^2 = a^2 + b^2. + \label{eq:pythagoras} % Pythagoras referenzieren +\end{equation} % Alle \begin Befehle müssen einen \end Befehl besitzen + +Wir können nun unsere Gleichung referenzieren! +Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in +Abschnitt ~\ref{subsec:pythagoras} behandelt. Es können sehr viele Sachen mit Labels versehen werden: +Grafiken, Gleichungen, Sections, etc. + +Summen und Integrale können mit den sum und int Befehlen dargestellt werden: + +% Manche LateX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Grafiken} + +Lass uns eine Grafik einfügen. Das Platzieren von Grafiken kann etwas trickreich sein. +Aber keine Sorge, ich muss auch jedes mal nachschauen, welche Option wie wirkt. + +\begin{figure}[H] % H ist die Platzierungsoption + \centering % Zentriert die Grafik auf der Seite + % Fügt eine Grafik ein, die auf 80% der Seitenbreite einnimmt. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Auskommentiert, damit es nicht im Dokument auftaucht. + \caption{Dreieck mit den Seiten $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} + +\subsection{Tabellen} +Wir können Tabellen genauso wie Grafiken einfügen. + +\begin{table}[H] + \caption{Überschrift der Tabelle.} + % Die {} Argumente geben an, wie eine Zeile der Tabelle dargestellt werden soll. + % Auch hier muss ich jedes Mal nachschauen. Jedes. einzelne. Mal. + \begin{tabular}{c|cc} + Nummer & Nachname & Vorname \\ % Spalten werden durch & getrennt + \hline % Eine horizontale Linie + 1 & Biggus & Dickus \\ + 2 & Monty & Python + \end{tabular} +\end{table} + +% \section{Links} % Kommen bald! + +\section{Verhindern, dass LateX etwas kompiliert (z.B. Quelltext)} +Angenommen, wir wollen Quelltext in unserem LateX-Dokument. LateX soll +in diesem Fall nicht den Quelltext als LateX-Kommandos interpretieren, +sondern es einfach ins Dokument schreiben. Um das hinzubekommen, verwenden +wir eine verbatim Umgebung. + +% Es gibt noch weitere Pakete für Quelltexte (z.B. minty, lstlisting, etc.) +% aber verbatim ist das simpelste. +\begin{verbatim} + print("Hello World!") + a%b; % Schau dir das an! Wir können % im verbatim verwenden! + random = 4; #decided by fair random dice roll +\end{verbatim} + +\section{Kompilieren} + +Ich vermute, du wunderst dich, wie du dieses tolle Dokument in ein PDF +verwandeln kannst. (Ja, dieses Dokument kompiliert wirklich!) \\ + +Dafür musst du folgende Schritte durchführen: + \begin{enumerate} + \item Schreibe das Dokument. (den LateX-Quelltext). + \item Kompiliere den Quelltext in ein PDF. + Das Kompilieren sieht so ähnlich wie das hier aus (Linux): \\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +Manche LateX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt +2 wird unsichtbar im Hintergrund ausgeführt. + +Alle Formatierungsoptionen werden in Schritt 1 in den Quelltext geschrieben. Schritt 2 verwendet +dann diese Informationen und kümmert sich drum, dass das Dokument korrekt erstellt wird. + +\section{Ende} + +Das war's erst mal! + +% Dokument beenden +\end{document} +``` +## Mehr Informationen über LateX + +* Das tolle LaTeX wikibook: [https://de.wikibooks.org/wiki/LaTeX-Kompendium](https://de.wikibooks.org/wiki/LaTeX-Kompendium) +* Ein Tutorial (englisch): [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) diff --git a/de-de/ruby-de.html.markdown b/de-de/ruby-de.html.markdown new file mode 100644 index 00000000..bdeaa30b --- /dev/null +++ b/de-de/ruby-de.html.markdown @@ -0,0 +1,613 @@ +--- +language: ruby +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"] +translators: + - ["Christian Albrecht", "https://github.com/coastalchief"] +filename: ruby-de.rb +lang: de-de +--- + +# Dies ist ein Kommentar + +=begin +Dies sind multi-line +Kommentare. Niemand benutzt +die wirklich. +=end + +# Objekte - Alles ist ein Objekt + +## Zahlen sind Objekte +``` +3.class #=> Fixnum +3.to_s #=> "3" +``` + +### Simple Arithmetik +``` +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 +``` + +// Arithmetik ist aber eigentlich nur syntaktischer Zucker +// um eine Methode eines Objekt aufzurufen +``` +1.+(3) #=> 4 +10.* 5 #=> 50 +``` + +## Special values sind Objekte +``` +nil # Nothing to see here +true # truth +false # falsehood + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass +``` + +## Objektvergleiche +### Gleicheit +``` +1 == 1 #=> true +2 == 1 #=> false +``` +### Ungleichheit +``` +1 != 1 #=> false +2 != 1 #=> true +``` +### Neben false selbst, nil ist ein anderer 'falsey' Wert +``` +!nil #=> true +!false #=> true +!0 #=> false +``` +### Weitere Vergleiche +``` +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true +``` +### Logische Operatoren +``` +true && false #=> false +true || false #=> true +!true #=> false +``` + +Es gibt alternative Versionen der logischen Operatoren mit niedrigerer +Wertigkeit. Diese werden meistens bei Flow-Control eingesetzt, um +verschiedenen Ausdrücke zu verketten bis einer true oder false zurück +liefert. + +#### and +##### `do_something_else` wird nur ausgewertet wenn `do_something` true ist. +do_something() and do_something_else() + +#### or +#####`log_error` wird nur ausgewertet wenn `do_something` false ist. +do_something() or log_error() + +## Strings sind Objekte +``` +'I am a string'.class #=> String +"I am a string too".class #=> String + + +platzhalter = 'Ruby' +"Ich kann in #{placeholder} Platzhalter mit doppelten Anführungsstrichen füllen." +``` +Einfache Anführungszeichen sollten bevorzugt werden. +Doppelte Anführungszeichen führen interne Berechnungen durch. + +### Strings können verbunden werden, aber nicht mit Zahlen +``` +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +``` +#### Zahl muss in String konvertiert werden +``` +'hello ' + 3.to_s #=> "hello 3" +``` +### Text ausgeben +``` +puts "I'm printing!" +``` +# Variablen +## Zuweisungen +### Diese Zuweisung gibt den zugeordneten Wert zurück +``` +x = 25 #=> 25 +x #=> 25 +``` +### Damit funktionieren auch mehrfache Zuweisungen +``` +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 +``` +## Benennung +### Konvention ist snake_case +``` +snake_case = true +``` +### Benutze verständliche Variablennamen +``` +path_to_project_root = '/good/name/' +path = '/bad/name/' +``` +# Symbols (sind auch Objekte) +Symbols sind unveränderliche, wiederverwendbare Konstanten, welche intern +als integer repräsentiert werden. Sie werden häufig anstelle von Strings +verwendet, um sinnvoll Werte zu übermitteln. +Symbols werden mit dem Doppelpunkt gekennzeichnet. + +``` +:pending.class #=> Symbol +status = :pending +status == :pending #=> true +status == 'pending' #=> false +status == :approved #=> false +``` +# Arrays + +## Ein Array anlegen +``` +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] +``` + +## Array können verschiedene Typen beinhalten +``` +[1, 'hello', false] #=> [1, "hello", false] +``` + +## Wie bei arithmetischen Ausdrücken auch wird beim Zugriff auf +## [0] eigentlich die Methode [] des Array Objekts aufgerufen. +``` +array.[] 0 #=> 1 +array.[] 12 #=> nil +``` + +## Arrays können von vorne indiziert werden +``` +array[0] #=> 1 +array[12] #=> nil +``` + +## Arrays können von hinten indiziert werden +``` +array[-1] #=> 5 +``` + +## Arrays können mit Stard Index und Länge indiziert werden +``` +array[2, 3] #=> [3, 4, 5] +``` + +## Arrays können mit einer Range indiziert werden +``` +array[1..3] #=> [2, 3, 4] +``` + +## Einen Wert hinzufügen +``` +array << 6 #=> [1, 2, 3, 4, 5, 6] +array.push(6) #=> [1, 2, 3, 4, 5, 6] +``` + +## Testen, ob ein Element schon vorhanden ist +``` +array.include?(1) #=> true +``` + +# Hashes +Hashes sind das Hauptfeature um Key/Values zu speichern + +``` + +## Ein Hash anlegen +``` +hash = { 'color' => 'green', 'number' => 5 } +hash.keys #=> ['color', 'number'] +``` + +## Wert per key herausfinden +``` +hash['color'] #=> 'green' +hash['number'] #=> 5 +hash['nothing here'] #=> nil +// Asking a hash for a key that doesn't exist returns nil: +``` + +## Symbols können auch keys sein +``` +new_hash = { defcon: 3, action: true } +new_hash.keys #=> [:defcon, :action] +``` + +## Testen ob ein Key oder ein Value existiert +``` +new_hash.has_key?(:defcon) #=> true +new_hash.has_value?(3) #=> true +``` + +### Tip: Arrays und Hashes sind Enumerable +### Und haben gemeinsame, hilfreiche Methoden wie: +### each, map, count, and more + +# Kontrolstrukturen +## if +``` +if true + 'if statement' +elsif false + 'else if, optional' +else + 'else, also optional' +end +``` +## for - Allerdings werden for Schleifen nicht oft vewendet. +``` +for counter in 1..5 + puts "iteration #{counter}" +end +``` +## Stattdessen: "each" Methode und einen Bloch übergeben +Ein Block ist ein Codeteil, den man einer Methode übergeben kann +Ähnelt stark lambdas, anonymen Funktionen oder Closures in anderen +Programmiersprachen. + +``` +(1..5).each do |counter| + puts "iteration #{counter}" +end +``` + +Die each Methode einer Range führt den Block für jedes Element der Range aus. + +Dem Block wird ein "counter" parameter übergeben. + +### Den Block kann man auch in geschweiften Klammern schreiben +``` +(1..5).each { |counter| puts "iteration #{counter}" } +``` + +### Each kann auch über den Inhalt von Datenstrukturen iterieren +``` +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end +``` + +## case +``` +grade = 'B' + +case grade +when 'A' + puts 'Way to go kiddo' +when 'B' + puts 'Better luck next time' +when 'C' + puts 'You can do better' +when 'D' + puts 'Scraping through' +when 'F' + puts 'You failed!' +else + puts 'Alternative grading system, eh?' +end +=> "Better luck next time" +``` + +### Case können auch ranges +``` +grade = 82 +case grade +when 90..100 + puts 'Hooray!' +when 80...90 + puts 'OK job' +else + puts 'You failed!' +end +=> "OK job" +``` + +# exception handling: +``` +begin + # code here that might raise an exception + raise NoMemoryError, 'You ran out of memory.' +rescue NoMemoryError => exception_variable + puts 'NoMemoryError was raised', exception_variable +rescue RuntimeError => other_exception_variable + puts 'RuntimeError was raised now' +else + puts 'This runs if no exceptions were thrown at all' +ensure + puts 'This code always runs no matter what' +end +``` +# Funktionen +``` +def double(x) + x * 2 +end +``` +## Funktionen (und Blocks) +## geben implizit den Wert des letzten Statements zurück +``` +double(2) #=> 4 +``` + +### Klammern sind optional wenn das Ergebnis nicht mehdeutig ist +``` +double 3 #=> 6 +double double 3 #=> 12 +def sum(x, y) + x + y +end +``` + +### Methoden Parameter werden per Komma getrennt +``` +sum 3, 4 #=> 7 +sum sum(3, 4), 5 #=> 12 +``` + +## yield +### Alle Methoden haben einen impliziten, optionalen block Parameter +### Dieser wird mit dem Schlüsselword "yield" aufgerufen +``` +def surround + puts '{' + yield + puts '}' +end +surround { puts 'hello world' } +``` + +## Einen Block kann man auch einer Methoden übergeben +### "&" kennzeichnet die Referenz zum übergebenen Block +``` +def guests(&block) + block.call 'some_argument' +end +``` + +### Eine Liste von Parametern kann man auch übergeben, +### Diese wird in ein Array konvertiert +### "*" kennzeichnet dies. +``` +def guests(*array) + array.each { |guest| puts guest } +end +``` +# Klassen +## Werden mit dem class Schlüsselwort definiert +``` +class Human +``` + +### Konstruktor bzw. Initializer +``` + def initialize(name, age = 0) + # Assign the argument to the "name" instance variable for the instance + @name = name + # If no age given, we will fall back to the default in the arguments list. + @age = age + end +``` + +### setter Methode +``` + def name=(name) + @name = name + end +``` +### getter Methode +``` + def name + @name + end +``` + +#### getter können mit der attr_accessor Methode vereinfacht definiert werden +``` + attr_accessor :name + # Getter/setter methods can also be created individually like this + attr_reader :name + attr_writer :name + # A class method uses self to distinguish from instance methods. + # It can only be called on the class, not an instance. + def self.say(msg) + puts msg + end + def species + @@species + end +end +``` + +## Eine Klasse instanziieren +``` +jim = Human.new('Jim Halpert') +dwight = Human.new('Dwight K. Schrute') +``` + +## Methodenaufrufe +``` +jim.species #=> "H. sapiens" +jim.name #=> "Jim Halpert" +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.name #=> "Jim Halpert II" +dwight.species #=> "H. sapiens" +dwight.name #=> "Dwight K. Schrute" +``` + +## Eine Klassenmethode aufrufen +``` +Human.say('Hi') #=> "Hi" +``` + +## Variable Gültigkeit +### Variablen die mit "$" starten, gelten global +``` +$var = "I'm a global var" +defined? $var #=> "global-variable" +``` + +### Variablen die mit "@" starten, gelten für die Instanz +``` +@var = "I'm an instance var" +defined? @var #=> "instance-variable" +``` + +### Variablen die mit "@@" starten, gelten für die Klasse +``` +@@var = "I'm a class var" +defined? @@var #=> "class variable" +``` + +### Variablen die mit einem Großbuchstaben anfangen, sind Konstanten +``` +Var = "I'm a constant" +defined? Var #=> "constant" +``` + +## Class ist auch ein Objekt +### Hat also auch Instanzvariablen +### Eine Klassenvariable wird innerhalb der Klasse und Ableitungen geteilt. + +### Basis Klasse +``` +class Human + @@foo = 0 + def self.foo + @@foo + end + def self.foo=(value) + @@foo = value + end +end +``` + +### Abgeleitete Klasse +``` +class Worker < Human +end +Human.foo # 0 +Worker.foo # 0 +Human.foo = 2 # 2 +Worker.foo # 2 +``` + +### Eine Klasseninstanzvariable wird nicht geteilt +``` +class Human + @bar = 0 + def self.bar + @bar + end + def self.bar=(value) + @bar = value + end +end +``` +``` +class Doctor < Human +end +``` +``` +Human.bar # 0 +Doctor.bar # nil +``` +``` +module ModuleExample + def foo + 'foo' + end +end +``` +### Module einbinden, heisst ihre Methoden an die Instanzen der Klasse zu binden +### Module erweitern, heisst ihre Mothden an die Klasse selbst zu binden +``` +class Person + include ModuleExample +end +``` +``` +class Book + extend ModuleExample +end +``` +``` +Person.foo # => NoMethodError: undefined method `foo' for Person:Class +Person.new.foo # => 'foo' +Book.foo # => 'foo' +Book.new.foo # => NoMethodError: undefined method `foo' +``` +### Callbacks werden ausgeführt, wenn ein Modul eingebunden oder erweitert wird +``` + module ConcernExample + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + module ClassMethods + def bar + 'bar' + end + end + module InstanceMethods + def qux + 'qux' + end + end + end + class Something + include ConcernExample + end +``` +``` +Something.bar # => 'bar' +Something.qux # => NoMethodError: undefined method `qux' +Something.new.bar # => NoMethodError: undefined method `bar' +Something.new.qux # => 'qux' +``` + +## Weiterführende Hinweise + +//EN + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. +- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. diff --git a/de-de/ruby-ecosystem-de.html.markdown b/de-de/ruby-ecosystem-de.html.markdown new file mode 100644 index 00000000..a7e1f75f --- /dev/null +++ b/de-de/ruby-ecosystem-de.html.markdown @@ -0,0 +1,149 @@ +--- +category: tool +tool: ruby ecosystem +contributors: + - ["Jon Smock", "http://github.com/jonsmock"] + - ["Rafal Chmiel", "http://github.com/rafalchmiel"] +translators: + - ["Christian Albrecht", "https://github.com/coastalchief"] +filename: ruby-ecosystem-de.txt +lang: de-de +--- + +Hier gibt es einen Überblick über die gängigsten Tools zur Verwaltung +von verschiedenen Ruby Versionen, Gems und Dependencies. + +## Ruby Managers + +Einige Betriebssysteme haben bereits eine Ruby Version vorinstalliert +oder bieten sie als Package zum Download an. Die meisten Rubyisten +benutzen diese aber eher nicht und wenn, dann um damit einen Ruby +Manager zu installieren. Damit kann man komfortabel zwischen den +verschiedenen Versionen hin und herspringen. + +Dies sind die beliebtesten: + +* [RVM](https://rvm.io/) - Installiert und wechselt zwischen rubies + RVM kennt verschiedene Ruby Versionen und hat das Konzept der gemsets, + um gem Abhängigkeiten pro Projekt zu managen. +* [ruby-build](https://github.com/sstephenson/ruby-build) + Installiert nur rubies, kann diese aber sehr gut verwalten +* [rbenv](https://github.com/sstephenson/rbenv) - Wechselt Ruby Versionen. + Wird zusammen mit ruby-build benutzt. Hiermit kann man kontrollieren, + wie rubies laden. +* [chruby](https://github.com/postmodern/chruby) - Wechselt Ruby Versionen. + Ähnlich rbenv. + +## Ruby Versionen + +Ruby wurde von Yukihiro "Matz" Matsumoto vor gut 20 Jahren veröffentlicht. +Matz ist nach wie vor in die Entwicklung involviert. Daher kommt auch der +Name der Referenzimplementierung: MRI (Matz' Reference Implementation). + +Die aktuellste Version ist **2.2.3** und wurde im August 2015 veröffentlicht! + +Hier eine kurze Versionshistorie: + +* 2.0.0 - Release im Februar 2013 -- Release zum 20. Geburtstag der Sprache + [Rubies are forever](http://www.heise.de/developer/artikel/Ruby-2-0-als-Geschenk-zum-20-Geburtstag-1808109.html) +* 1.9.3 - Release im Oktober 2011 + [End of Life](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) +* 1.8.7 - Release im Juni 2006 + [End of Life](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). + +Die Veränderung zwischen 1.8.7 und 1.9.x war sehr groß und eine Migration +nicht so einfach möglich. Der Versionssprung auf 2.0.0 war verglichen dazu +weit weniger dramatisch. +Beispielsweise hat 1.9. Encodings und eine Bytecode VM eingeführt. +Es gibt immer noch Projekte die auf der stabilen Version 1.8.7 laufen, +aber diese sind mittlerweile in der Minderheit. Die meisten Projekte +laufen auf 1.9.x oder auf 2.x. + +## Ruby Implementierungen + +Das Ruby Ecosystem beinhaltet viele verschiedene Implementierungen von Ruby, +jedes mit seinen eigenen Vorteilen und verschiedenen Graden von +Kompatibilität. Auch wenn alle diese Implementierungen in verschiedenen +Sprachen geschrieben sind, sind sie doch **alle Ruby**. +Jede Implementierung bietet neben ihren speziellen Features immer auch +die Möglichkeit normale ruby Dateien auszuführen. + +Am ausgereiftesten und stabilsten: + +* [MRI](https://github.com/ruby/ruby) - Geschrieben in C, das ist die Referenz Implementierung. + Sie ist 100% kompatibel (mit sich selbst ;-). Alle anderen rubies + bleiben kompatibel mit MRI (siehe [RubySpec](#rubyspec) weiter unten). +* [JRuby](http://jruby.org/) - Geschrieben in Java and Ruby, Robust und ziemlich schnell. + Der größte Vorteil von JRuby ist die Interoperabilität mit JVM/Java und damit die + Benutzung von Ruby im Java Ecosystem. +* [Rubinius](http://rubini.us/) - Geschrieben in Ruby mit C++ bytecode VM. + Auch sehr ausgereift und schnell. + +Mittel ausgereift / kompatibel: + +* [Maglev](http://maglev.github.io/) - Baut auf Gemstone, ein Smalltalk VM. + Dieses Projekt versucht das großartige Smalltalk Tooling in die Ruby Welt + zu bringen. +* [RubyMotion](http://www.rubymotion.com/) - Ruby in der iOS Entwicklung. + +Weniger ausgereift/kompatibel: + +* [Topaz](http://topazruby.com/) - Geschrieben in RPython (via PyPy) + Topaz ist noch ziemlich jung und versucht die schnellste Implementierung + zu werden. +* [IronRuby](http://ironruby.net/) - Geschrieben in C# für die .NET Plaftform + Das letzte Release von IronRuby ist mittlerweile 5 Jahre her. + +Die Ruby Implementierungen haben ihre eigenen Versionsnummern, sind aber +trotzdem immer zu einer MRI Version kompatibel. +Viele können sogar zwischen verschiedenen Modi wechseln (1.8 mode -> 1.9 mode) + +## RubySpec + +Die meisten Ruby Implementierungen vertrauen der [RubySpec](http://rubyspec.org/). +sehr stark. Da Ruby keine offizielle Spezifikation hat, hat die +Community ausführbare Specs (in Ruby) geschrieben, um so die Kompatibilität +zur MRI testen zu können. + +## RubyGems + +[RubyGems](http://rubygems.org/) ist der Community Paket Manager von Ruby. +RubyGems kommt mit Ruby zusammen, so dass kein extra Tool nötig ist. + +Ruby Pakete werden "gems" genannt und könnten auf RubyGems.org +veröffentlicht werden. Jedes Gem enthält den Source Code und Meta Daten, +wie die Versionsnummer, weitere Abhängigkeiten, Autoren und Lizenzen. + +## Bundler + +[Bundler](http://bundler.io/) ist ein Tool um Abhängigkeiten zwischen +Gems aufzulösen und zu managen. Dazu werden diese in einem gemfile +zusammengefasst und Bundler kümmert sich darum die Abhängigkeiten +untereinander rekursiv aufzulösen. Entweder es klappt und alle gems +konnten runtergeladen werden, oder es wird abgebrochen und +der Konflikt gemeldet. +Zum Beispiel: +Wenn Gem A die Version 3 oder höher von Gem Z braucht, aber Gem B +von Gem Z die Version 2, dann ist das ein Konflikt. + +# Testing + +Test-Driven Development ist ein essentieller Teil der Ruby Kultur. +Ruby bringt sein eigenes Unit-Test framework mit, minitest. Darüberhinaus +gibt es noch viele weitere Testframeworks mit unterschiedlichsten Zielen: + +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - Eingebaut in Ruby 1.8 + "Unit-style" Testframework +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - Eingebaut in Ruby 1.9/2.0 + "Unit-style" Testframework +* [RSpec](http://rspec.info/) - Ein Testframework welches auf verständliche Testdefinition setzt +* [Cucumber](http://cukes.info/) - Ein BDD Testframework welches Gherkin tests parsen kann + +## Be Nice +Die Ruby Community ist stolz darauf eine offene, vielfältige und einladende +Community zu sein. Es gibt viele aktive Ruby User Gruppen und diverse +Ruby Konferenzen. Matz selbst ist so oft es geht dabei. + +* [Euruko](http://www.euruko2015.org) +* [User Groups](https://www.ruby-lang.org/de/community/user-groups/) + diff --git a/de-de/scala-de.html.markdown b/de-de/scala-de.html.markdown new file mode 100644 index 00000000..7fd299b4 --- /dev/null +++ b/de-de/scala-de.html.markdown @@ -0,0 +1,816 @@ +--- +language: Scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] + - ["Dominic Bou-Samra", "http://dbousamra.github.com"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Ha-Duong Nguyen", "http://reference-error.org"] +translators: + - ["Christian Albrecht", "https://github.com/coastalchief"] +filename: learnscala-de.scala +lang: de-de +--- + +Scala ist eine funktionale und objektorientierte Programmiersprache +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 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 + +/* + Mehrzeilige Kommentare, werden starten + mit Slash-Stern und enden mit 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. +``` +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 +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. +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 +``` +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 + +// Funktionen werden so definiert +// +// def functionName(args...): ReturnType = { body... } +// +// 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) + return z // Zeile macht z zum return Wert von foo + else + z + 2 // Zeile ist der return Wert von anonFunc + } + anonFunc(x) // Zeile ist der return Wert von foo +} +``` + +# 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 +// 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. +// While in Scala läuft schneller ab als in Java und die o.g. +// Kombinatoren und Zusammenlegungen sind einfacher zu verstehen +// 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 +``` +val x = 10 +if (x == 1) println("yeah") +if (x == 10) println("yeah") +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 +``` +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // Exception +``` + +## 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) +``` +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 +// 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 + +Diesen Sprachelemente wenden wir uns jetzt zu. + +## 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 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) +``` +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. +``` +trait Hund { + def sorte: String + def farbe: String + def bellen: Boolean = true + def beissen: Boolean +} +class Bernhardiner extends Hund{ + val sorte = "Bernhardiner" + val farbe = "braun" + def beissen = false +} +``` + +``` +scala> b +res0: Bernhardiner = Bernhardiner@3e57cd70 +scala> b.sorte +res1: String = Bernhardiner +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" +} +trait Hund { + def sorte: String + def farbe: String +} +class Bernhardiner extends Hund with Bellen{ + val sorte = "Bernhardiner" + val farbe = "braun" +} +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. +``` +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" + case "woof" => "String" + case true | false => "Boolean" + 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: + case "Hello world" => "Got the string Hello world" + // Typen: + case x: Double => "Got a Double: " + x + // Conditions: + case x: Int if x > 10000 => "Got a pretty big number!" + // Case Classes: + case Person(name, number) => s"Got contact info for $name!" + // RegEx: + case email(name, domain) => s"Got email address $name@$domain" + // Tuples: + case (a: Int, b: Double, c: String) => s"Got a tuple: $a, $b, $c" + // Strukturen: + case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c" + // 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 +Scala erlaubt, das Methoden und Funktion wiederum Funtionen und Methoden +als Aufrufparameter oder Return Wert verwenden. Diese Methoden heissen +higher-order functions +Es gibt zahlreiche higher-order functions nicht nur für Listen, auch für +die meisten anderen Collection Typen, sowie andere Klassen in Scala +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 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 nimmt zwei Elemente und kombiniert sie zu einem Element, +// und zwar solange bis nur noch ein Element da ist. + +## 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 +// 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 +///////////////////////////////////////////////// + +**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 +// lexikalischen Scope und im companion object nach einem implicit Wert, +// der vom Typ passt, oder nach einer implicit Methode mit der er in den +// 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 +``` +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 +``` +object Application { + def main(args: Array[String]): Unit = { + // stuff goes here. + } +} +``` + +## 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 + +// DE +* [Scala Tutorial](https://scalatutorial.wordpress.com) +* [Scala Tutorial](http://scalatutorial.de) + +// EN +* [Scala for the impatient](http://horstmann.com/scala/) +* [Twitter Scala school](http://twitter.github.io/scala_school/) +* [The scala documentation](http://docs.scala-lang.org/) +* [Try Scala in your browser](http://scalatutorials.com/tour/) +* [Neophytes Guide to Scala](http://danielwestheide.com/scala/neophytes.html) +* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) diff --git a/el-gr/css-gr.html.markdown b/el-gr/css-gr.html.markdown new file mode 100644 index 00000000..327dc1a0 --- /dev/null +++ b/el-gr/css-gr.html.markdown @@ -0,0 +1,243 @@ +--- +language: css +contributors: + - ["Kostas Bariotis", "http://kostasbariotis.com"] +filename: css-gr.html.markdown +lang: el-gr +--- + +Η αρχική μορφή του Παγκόσμιου Ιστού αποτελούταν απο καθαρό κείμενο, χωρίς οπτικά αντικείμενα. Με το πέρας +του χρόνου και την εξέλιξη των Φυλλομετρητών, οι πλούσιες σελίδες, σε οπτικά και πολυμεσικά αντικείμενα, +γίναν καθημερινότητα. + +Η CSS μας βοηθάει να διαχωρήσουμε το περιεχόμενο της σελίδας μας (HTML) απο την οπτική της περιγραφή. + +Με την CSS ορίζουμε οπτικές ιδιότητες (χρώμα, μέγεθος, κλπ) σε HTML αντικείμενα (H1, div, κλπ). + +```css +/* Σχόλια εμφανίζονται εντός καθέτου-αστερίσκου, όπως εδώ. + Δεν υπάρχουν σχόλια μια γραμμής και πολλών. */ + +/* #################### + ## ΚΑΝΟΝΕΣ + #################### */ + +/* ένας κανόνας χρησιμοποιείτε για να στοχεύσουμε ένα αντικείμενο (selector). +selector { property: value; /* περισσότερες ιδιότητες...*/ } + +/* +Αυτό είναι ενα παράδειγμα αντικειμένου¨ + +<div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' /> +*/ + +/* Μπορούμε να το στοχεύσουμε με την χρήση CSS κλάσεων */ +.class1 { } + +/* Ή και με τις δύο κλάσεις! */ +.class1.class2 { } + +/* Και με το όνομα του */ +div { } + +/* Ή με το id του */ +#anID { } + +/* Ή με το γεγονός ότι περιέχει ενα attribute */ +[attr] { font-size:smaller; } + +/* Ή οτι το attribute αυτό έχει μια συγκεκριμένη τιμή */ +[attr='value'] { font-size:smaller; } + +/* Ξεκινάει απο το λεκτικό (CSS 3) */ +[attr^='val'] { font-size:smaller; } + +/* Καταλήγει σε αυτο το λεκτικό (CSS 3) */ +[attr$='ue'] { font-size:smaller; } + +/* Περιέχει κάποιο λεκτικό */ +[otherAttr~='foo'] { } +[otherAttr~='bar'] { } + +/* περιέχει το λεκτικό σε λίστα χωρισμένη με παύλες, δηλαδή: "-" (U+002D) */ +[otherAttr|='en'] { font-size:smaller; } + + +/* Μπορούμε να προσθέσουμε μεταξύ τους selectors για να δημιουργήσουμε πιο αυστηρούς. + Δεν βάζουμε κενά ανάμεσα. */ +div.some-class[attr$='ue'] { } + +/* Μπορούμε να επιλέξουμε αντικείμενα που βρίσκονται μέσα σε άλλα. */ +div.some-parent > .class-name { } + +/* Ή κάποιο αντικείμενο απόγονο ανεξαρτήτου του βάθους της σχέσης τους. */ +div.some-parent .class-name { } + +/* ΠΡΟΣΟΧΗ: ο ίδιος selector χωρίς κενά έχει άλλο νόημα. (Άσκηση προς τον αναγνώστη) */ +div.some-parent.class-name { } + +/* Μπορούμε να επιλέξουμε αντικείμενα με βάση το αμέσως επόμενο αντικείμενο στο ίδιο επίπεδο. */ +.i-am-just-before + .this-element { } + +/* Ή οποιοδήποτε αντικείμενο που προηγείται */ +.i-am-any-element-before ~ .this-element { } + +/* Με την βοήθεια των ψευδο-κλάσεων μπορούμε να επιλέξουμε αντικείμενα που βρίσκονται σε μια + ορισμένη κατάασταση. */ + +/* π.χ. όταν ο κέρσορας είναι πάνω απο ένα αντικείμενο */ +selector:hover { } + +/* ή ένας υπερσύνδεσμος που πατήθηκε */ +selector:visited { } + +/* ή που δεν πατήθηκε */ +selected:link { } + +/* ή ένα αντικείμενο που επιλέχθηκε */ +selected:focus { } + +/* οποιοδήποτε αντικείμενο είναι το πρώτο παιδί των γονέων του */ +selector:first-child {} + +/* οποιοδήποτε αντικείμενο είναι το πρώτοτελευταίο παιδί των γονέων του */ +selector:last-child {} + +/* Όπως και με τις ψευδο-κλάσεις, τα ψευδο-αντικείμενα μας επιτρέπουν τα τροποοιήσουμε συγκεκριμένα + κομμάτια της σελίδας */ + +/* επιλέγει το ψευδο-αντικείμενο ακριβώς πριν απο το αντικείμενο */ +selector::before {} + +/* επιλέγει το ψευδο-αντικείμενο ακριβώς μετά απο τον αντικείμενο */ +selector::after {} + +/* Σε σωστά σημεία (όχι πολύ ψηλά στην ιεραρχία) ο αστερίσκος μπορείς να χρησιμοποιηθεί για να + επιλέξουμε όλα τα αντικείμενα */ +* { } /* όλα τα αντικείμενα της σελίδας */ +.parent * { } /* όλους τους απόγονους */ +.parent > * { } /* όλους τους απόγονους πρώτου επιπέδου */ + +/* #################### + ## Ιδιότητες + #################### */ + +selector { + + /* Οι μονάδες μπορούν να είναι είτε απόλυτες είτε σχετικές */ + + /* Σχετικές μονάδες */ + width: 50%; /* ποσοστό επί του πλάτους του γονέα */ + font-size: 2em; /* πολλαπλασιαστής της αρχικής τιμής του αντικειμένου */ + font-size: 2rem; /* ή της τιμής του πρώτου αντικειμένου στην ιεραρχία */ + font-size: 2vw; /* πολλαπλαστιαστής του 1% του οπτικού πλάτους */ + font-size: 2vh; /* ή τους ύψους */ + font-size: 2vmin; /* οποιοδήποτε απο αυτα τα δύο είναι το μικρότερο */ + font-size: 2vmax; /* ή το μεγαλύτερο */ + + /* Απόλυτες μονάδες */ + width: 200px; /* pixels */ + font-size: 20pt; /* στιγμες */ + width: 5cm; /* εκατοστά */ + min-width: 50mm; /* χιλιοστά */ + max-width: 5in; /* ίντσες */ + + /* Χρώματα */ + color: #F6E; /* σύντομη δεκαεξαδική μορφή */ + color: #FF66EE; /* δεκαεξαδική μορφή */ + color: tomato; /* χρώμα με το όνομα του (συγκεκριμένα χρώματα) */ + color: rgb(255, 255, 255); /* τιμή RGB */ + color: rgb(10%, 20%, 50%); /* τιμή RGB με ποσοστά */ + color: rgba(255, 0, 0, 0.3); /* τιμή RGBA (CSS3) σσ. 0 < a < 1 */ + color: transparent; /* όπως και το παραπάνω με a = 0 */ + color: hsl(0, 100%, 50%); /* τιμή hsl με ποσοστά (CSS 3) */ + color: hsla(0, 100%, 50%, 0.3); /* τιμή hsla με ποσοστά και a */ + + /* Εικόνες μπορούν να τοποθετηθούν στον φόντο ενός αντικειμένου */ + background-image: url(/img-path/img.jpg); + + /* Γραμματοσειρές */ + font-family: Arial; + /* εάν η γραμματοσειρα περιέχει κενά */ + font-family: "Courier New"; + /* εάν η πρώτη γραμματοσειρα δε βρεθεί εγκατεστημένη στο Λειτουργικό Σύστυμα, αυτόματα + επιλέγετε η δεύτερη, κ.κ.ε. */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; +} +``` + +## Χρήση + +Αποθηκεύουμε ένα αρχείο CSS με την επέκταση `.css`. + +```xml +<!-- Πρέπει να συμπεριλάβουμε το αρχείο στην επικεφαλίδα(head) ενος HTML αρχείου. + σσ. http://stackoverflow.com/questions/8284365 --> +<link rel='stylesheet' type='text/css' href='path/to/style.css' /> + +<!-- Μπορούμε να το ενσωματώσουμε --> +<style> + a { color: purple; } +</style> + +<!-- Ή απευθείας σε κάποιο αντικείμενο (inline) --> +<div style="border: 1px solid red;"> +</div> +``` + +## Ειδικότητα των κανόνων (Cascading απο το αγγλικό τίτλο Cascading Style Sheets) + +Ένα αντικείμενο μπορεί να στοχευθεί απο πολλούς κανόνες και μπορεί η ίδια ιδιότητα να +περιλαμβάνετε σε πολλούς κανόνες. Σε αυτές της περιπτώσεις υπερισχύει πάντα ο πιο ειδικός +κανόνας και απο αυτούς, αυτός που εμφανίζεται τελευταίος. + +```css +/* A */ +p.class1[attr='value'] + +/* B */ +p.class1 { } + +/* C */ +p.class2 { } + +/* D */ +p { } + +/* E */ +p { property: value !important; } +``` + +```xml +<p style='/*F*/ property:value;' class='class1 class2' attr='value' /> +``` + +Η σειρά θα είναι: + +* `E` έχει μεγαλύτερο βάρος λόγω του `!important`. Κάλες πρακτικές λένε να το αποφεύγουμε. +* `F` επόμενο λόγω του inline κανόνα. +* `A` επόμενο λόγω του το οτι είναι πιο ειδικό. Περιέχει τρεις selectors. +* `C` επόμενο, λόγω του οτι εμφανίζεται μετα το Β και ας έχει την ίδια ειδικότητα. +* `B` επόμενο. +* `D` τελευταίο. + +## Συμβατότητα + +Τα περισσότερα απο τα παραπάνω ήδη υποστηρίζονται απο τους γνωστούς φυλλομετρητές. Άλλα θα πρέπει +πάντα να ελέγχουμε πρωτου τους χρησιμοποιήσουμε. + +## Περισσότερα + +* Έλεγχος συμβατότητας, [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/) + +## Μελέτη + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing +* [CSS-Tricks](https://css-tricks.com) diff --git a/el-gr/racket-gr.html.markdown b/el-gr/racket-gr.html.markdown index 4c4576bb..589adfeb 100644 --- a/el-gr/racket-gr.html.markdown +++ b/el-gr/racket-gr.html.markdown @@ -31,12 +31,12 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ ;; Τα σχόλια S-expression (εκφράσεις S) comments απορρίπτουν την ;; έκφραση που ακολουθεί, δυνατότητα που είναι χρήσιμη για να -;; κάνουμε σχόλια κάποιες εκφράσεις κατα τη διάρκεια του debugging +;; κάνουμε σχόλια κάποιες εκφράσεις κατά τη διάρκεια του debugging #; (αυτή η έκφραση δεν θα εκτελεστεί) ;; (Αν δεν καταλαβαίνεται τι είναι οι εκφράσεις , περιμένετε... Θα το μάθουμε -;; πολύ συντομα!) +;; πολύ σύντομα!) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -57,8 +57,8 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ ;; όπου το f είναι η συνάρτηση και τα x y z ;; είναι οι όροι που η συνάρτηση δέχεται ;; ως ορίσματα. Αν θέλουμε να δημιουργήσουμε -;; μια λίστα στην κυριολεξία απο δίαφορα δεδομένα, -;; χρησιμοποιούμε το ' για να το εμποδίσουμε απο το να +;; μια λίστα στην κυριολεξία από δίαφορα δεδομένα, +;; χρησιμοποιούμε το ' για να το εμποδίσουμε από το να ;; αξιολογηθεί σαν έκφραση. Για παράδειγμα: '(+ 1 2) ; => Παραμένει (+ 1 2) και δεν γίνεται η πράξη ;; Τώρα , ας κάνουμε μερικές πράξεις @@ -88,15 +88,15 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ ;;; Τα αλφαριθμητικά είναι πίνακες χαρακτήρων συγκεκριμένου μήκους "Hello, world!" "Benjamin \"Bugsy\" Siegel" ; Το backslash είναι χαρακτήρας διαφυγής -"Foo\tbar\41\x21\u0021\a\r\n" ; Συμπεριλαμβάνονται οι χαρακτήες διαφυγής της C, +"Foo\tbar\41\x21\u0021\a\r\n" ; Συμπεριλαμβάνονται οι χαρακτήρες διαφυγής της C, ; σε Unicode "λx:(μα.α→α).xx" ; Μπορούν να υπάρχουν και Unicode χαρακτήρες -;; Μπορούμε να εννώσουμε αλφαριθμητικά! +;; Μπορούμε να ενώσουμε αλφαριθμητικά! (string-append "Hello " "world!") ; => "Hello world!" -;; Ένα αλφαριθμητικό μπορούμε να το χρησιμοπιησουμε -;; όπως και μια λίστα απο χαρακτήρες +;; Ένα αλφαριθμητικό μπορούμε να το χρησιμοποιήσουμε +;; όπως και μια λίστα από χαρακτήρες (string-ref "Apple" 0) ; => #\A ;; Παίρνουμε το πρώτο στοιχείο ;; Η συνάρτηση format μπορεί να χρησιμοποιηθεί για @@ -117,18 +117,18 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ some-var ; => 5 ;; Μπορούμε επίσης να χρησιμοποιήσουμε unicode χαρακτήρες. -(define ⊆ subset?) ;; Εδώ ουστιαστικά δίνουμε στη ήδη ύπαρχουσα συνάρτηση subset? +(define ⊆ subset?) ;; Εδώ ουσιαστικά δίνουμε στη ήδη υπάρχουσα συνάρτηση subset? ;; ένα νέο όνομα ⊆ , και παρακάτω την καλούμε με το νέο της όνομα. (⊆ (set 3 2) (set 1 2 3)) ; => #t -;; Αν ζητήσουμε μια μεταβλητή που δεν έχει οριστεί πρίν π.χ +;; Αν ζητήσουμε μια μεταβλητή που δεν έχει οριστεί πριν π.χ. (printf name) ;; θα πάρουμε το παρακάτω μήνυμα ;name: undefined; ; cannot reference undefined identifier ; context...: -;; Η τοπική δέσμευση : `me' δευσμεύεται με το "Bob" μόνο μέσα στο (let ...) +;; Η τοπική δέσμευση : `me' δεσμεύεται με το "Bob" μόνο μέσα στο (let ...) (let ([me "Bob"]) "Alice" me) ; => "Bob" @@ -156,7 +156,7 @@ my-pet ; => #<dog> ;;; Λίστες ;; Οι λίστες είναι linked-list δομές δεδομένων, -;; που έχουν δημιουργηθεί απο ζευγάρια 'cons' +;; που έχουν δημιουργηθεί από ζευγάρια 'cons' ;; και τελειώνουν με 'null' (ή αλλιώς '()) για να ;; δηλώσουν ότι αυτό είναι το τέλος της λίστας (cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3) @@ -191,12 +191,12 @@ my-pet ; => #<dog> ;; Τα διανύσματα είναι πίνακες σταθερού μήκους #(1 2 3) ; => '#(1 2 3) -;; Χρησιμοποιύμε το `vector-append' για να προσθέσουμε διανύσματα +;; Χρησιμοποιούμε το `vector-append' για να προσθέσουμε διανύσματα (vector-append #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) ;;; Σύνολα -;; Δημιουργούμε ένα σύνολο απο μία λίστα +;; Δημιουργούμε ένα σύνολο από μία λίστα (list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3) ;; Προσθέτουμε έναν αριθμό στο σύνολο χρησιμοποιώντας το `set-add' @@ -214,10 +214,10 @@ my-pet ; => #<dog> ;; Δημιουργήστε ένα αμετάβλητο πίνακα κατακερματισμού (define m (hash 'a 1 'b 2 'c 3)) -;; Παίρνουμε μια τιμή απο τον πίνακα +;; Παίρνουμε μια τιμή από τον πίνακα (hash-ref m 'a) ; => 1 -;; Άν ζητήσουμε μια τιμή που δέν υπάρχει παίρνουμε μία εξαίρεση +;; Αν ζητήσουμε μια τιμή που δεν υπάρχει παίρνουμε μία εξαίρεση ; (hash-ref m 'd) => no value found for key ;; Μπορούμε να δώσουμε μια default τιμή για τα κλειδιά που λείπουν @@ -234,7 +234,7 @@ m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3)) m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' ;; Χρησιμοποιούμε το `hash-remove' για να αφαιρέσουμε -;; κλειδία +;; κλειδιά (hash-remove m 'a) ; => '#hash((b . 2) (c . 3)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -247,12 +247,12 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' ;; Μπορούμε επίσης να χρησιμοποιήσουμε το `λ' (λ () "Hello World") ; => Ίδια συνάρτηση -;; Χρησιμοποιύμε τις παρενθέσεις για να καλέσουμε όλες τις συναρτήσεις +;; Χρησιμοποιούμε τις παρενθέσεις για να καλέσουμε όλες τις συναρτήσεις ;; συμπεριλαμβανομένων και των εκφράσεων 'λάμδα' ((lambda () "Hello World")) ; => "Hello World" ((λ () "Hello World")) ; => "Hello World" -;; Εκχωρούμε σε μια μετάβλητη την συνάρτηση +;; Εκχωρούμε σε μια μεταβλητή την συνάρτηση (define hello-world (lambda () "Hello World")) (hello-world) ; => "Hello World" @@ -302,7 +302,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (lambda (name . args) (format "Hello ~a, you passed ~a extra args" name (length args)))) -;; Και με λέξεις κλειδία +;; Και με λέξεις κλειδιά (define (hello-k #:name [name "World"] #:greeting [g "Hello"] . args) (format "~a ~a, ~a extra args" g name (length args))) (hello-k) ; => "Hello World, 0 extra args" @@ -347,7 +347,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (eq? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f -;; Το `eqv?' υποστηρίζει την σύκριση αριθμών αλλα και χαρακτήρων +;; Το `eqv?' υποστηρίζει την σύγκριση αριθμών αλλά και χαρακτήρων ;; Για άλλα ήδη μεταβλητών το `eqv?' και το `eq?' επιστρέφουν το ίδιο. (eqv? 3 3.0) ; => #f (eqv? (expt 2 100) (expt 2 100)) ; => #t @@ -365,12 +365,12 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (equal? (list 3) (list 3)) ; => #t ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 5. Έλεχγος Ροής +;; 5. Έλεγχος Ροής ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Συνθήκες (conditionals) -(if #t ; έκφραση ελέχγου +(if #t ; έκφραση ελέγχου "this is true" ; έκφραση then "this is false") ; έκφραση else ; => "this is true" @@ -483,7 +483,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (values i (number->string i))) ; => '#hash((1 . "1") (2 . "2") (3 . "3")) -;; Υπάρχουν πολλά είδη απο προϋπάρχοντες τρόπους για να συλλέγουμε +;; Υπάρχουν πολλά είδη από προϋπάρχοντες τρόπους για να συλλέγουμε ;; τιμές από τους βρόχους (for/sum ([i 10]) (* i i)) ; => 285 @@ -491,7 +491,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (for/and ([i 10] [j (in-range 10 20)]) (< i j)) ; => #t (for/or ([i 10] [j (in-range 0 20 2)]) (= i j)) ; => #t -;; Και για να χρησιμοποιήσουμε ένα αφθαίρετο συνδιασμό χρησιμοποιούμε +;; Και για να χρησιμοποιήσουμε ένα αυθαίρετο συνδυασμό χρησιμοποιούμε ;; το 'for/fold' (for/fold ([sum 0]) ([i '(1 2 3 4)]) (+ sum i)) ; => 10 @@ -524,17 +524,17 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (set! n (add1 n)) n ; => 6 -;; Χρησιμοποιούμε τα boxes για να δηλώσουμε ρητά ότι μια μεταβητή -;; θα είναι mutable (θα μπορεί να αλλάξη η τιμή της) +;; Χρησιμοποιούμε τα boxes για να δηλώσουμε ρητά ότι μια μεταβλητή +;; θα είναι mutable (θα μπορεί να αλλάξει η τιμή της) ;; Αυτό είναι παρόμοιο με τους pointers σε άλλες γλώσσες (define n* (box 5)) (set-box! n* (add1 (unbox n*))) (unbox n*) ; => 6 -;; Πολλοί τύποι μεταβλητών στη Racket είναι αμετάβλητοι πχ τα ζεύγη, οι +;; Πολλοί τύποι μεταβλητών στη Racket είναι αμετάβλητοι π.χ. τα ζεύγη, οι ;; λίστες κτλ. Άλλοι υπάρχουν και σε μεταβλητή και σε αμετάβλητη μορφή -;; πχ αλφαριθμητικά, διανύσματα κτλ +;; π.χ. αλφαριθμητικά, διανύσματα κτλ. (define vec (vector 2 2 3 4)) (define wall (make-vector 100 'bottle-of-beer)) ;; Χρησιμοποιούμε το 'vector-set!' για να ανεώσουμε κάποια @@ -579,7 +579,7 @@ vec ; => #(1 2 3 4) (printf fmt (make-string n ch)) (newline))) -;; Χρησιμοποιομε το 'require' για να πάρουμε όλα τα +;; Χρησιμοποιουμε το 'require' για να πάρουμε όλα τα ;; παρεχόμενα ονόματα από μία ενότητα (require 'cake) ; το ' είναι για τοπική υποενότητα (print-cake 3) @@ -634,7 +634,7 @@ vec ; => #(1 2 3 4) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Οι μακροεντολές μας επιτρέπουν να επεκτείνουμε -;; το συντακτικό μιάς γλώσσας. +;; το συντακτικό μιας γλώσσας. ;; Ας προσθέσουμε έναν βρόχο while (define-syntax-rule (while condition body ...) @@ -664,20 +664,20 @@ vec ; => #(1 2 3 4) ;; (set! tmp other) ;; (set! other tmp_1)) -;; Αλλά ακόμα υπάρχουν ακόμη μετασχηματισμοί του κώδικα, π.χ: +;; Αλλά ακόμα υπάρχουν ακόμη μετασχηματισμοί του κώδικα, π.χ.: (define-syntax-rule (bad-while condition body ...) (when condition body ... (bad-while condition body ...))) -;; αυτή η μακροεντολή είναι χαλασμένη: δημιουγεί ατέρμονα βρόχο +;; αυτή η μακροεντολή είναι χαλασμένη: δημιουργεί ατέρμονα βρόχο ;; και αν προσπαθήσουμε να το χρησιμοποιήσουμε, ο μεταγλωττιστής -;; θα μπεί στον ατέρμονα βρόχο. +;; θα μπει στον ατέρμονα βρόχο. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 10. Συμβόλαια (Contracts) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; Τα συμβόλαια βάζουν περιορισμόυς σε τιμές που προέρχονται +;; Τα συμβόλαια βάζουν περιορισμούς σε τιμές που προέρχονται ;; από ενότητες (modules) (module bank-account racket (provide (contract-out @@ -719,7 +719,7 @@ vec ; => #(1 2 3 4) (displayln "Hola mundo" out-port) (close-output-port out-port) -;; Διαβάζουμε απο αρχείο ξανά +;; Διαβάζουμε από αρχείο ξανά (define in-port (open-input-file "/tmp/tmp.txt")) (displayln (read-line in-port)) ; => "Hello World" diff --git a/el-gr/scala-gr.html.markdown b/el-gr/scala-gr.html.markdown index e29c7e70..415fda5c 100644 --- a/el-gr/scala-gr.html.markdown +++ b/el-gr/scala-gr.html.markdown @@ -40,7 +40,7 @@ Scala - Η επεκτάσιμη γλώσσα /* Τα σχόλια που επεκτείνονται σε πολλές γραμμές , όπως μπορείτε - να δείτε , φαίνοται κάπως έτσι. + να δείτε , φαίνονται κάπως έτσι. */ // Εκτύπωση με νέα γραμμή στην επόμενη εκτύπωση @@ -59,12 +59,12 @@ var y = 10 y = 20 // το y είναι τώρα 20 /* - Η Scala είναι στατικού τύπου γλώσσα, εν τούτις προσέξτε ότι στις παραπάνω + Η Scala είναι στατικού τύπου γλώσσα, εν τούτοις προσέξτε ότι στις παραπάνω δηλώσεις , δεν προσδιορίσαμε κάποιον τύπο. Αυτό συμβαίνει λόγω ενός χαρακτηριστικού της Scala που λέγεται συμπερασματολογία τύπων. Στις περισσότερες των περιπτώσεων, ο μεταγλωττιστής της Scala μπορεί να - μαντέψει ποιός είναι ο τύπος μιας μεταβλητής. Μπορούμε να δηλώσουμε - αναλυτικά τον τύπο μιάς μεταβλητής ως εξής: + μαντέψει ποιος είναι ο τύπος μιας μεταβλητής. Μπορούμε να δηλώσουμε + αναλυτικά τον τύπο μιας μεταβλητής ως εξής: */ val z: Int = 10 val a: Double = 1.0 @@ -85,7 +85,7 @@ false true == false // false 10 > 5 // true -// Η αριθμιτική είναι όπως τα συνηθισμένα +// Η αριθμητική είναι όπως τα συνηθισμένα 1 + 1 // 2 2 - 1 // 1 5 * 3 // 15 @@ -117,14 +117,14 @@ true == false // false "Τα αλφαριθμητικά στην Scala περικλείονται από διπλά εισαγωγικά" 'a' // Ένας χαρακτήρας στην Scala // res30: Char = a -// 'Αλφαριθημτικά με μονά εισαγωγικά δεν υφίστανται <= Αυτό θα προκαλέσει σφάλμα. +// Αλφαριθημτικά με μονά εισαγωγικά δεν υφίστανται <= Αυτό θα προκαλέσει σφάλμα. // Τα αλφαριθμητικά έχουν τις συνηθισμένες μεθόδους της Java ορισμένες πάνω τους. "hello world".length "hello world".substring(2, 6) "hello world".replace("C", "3") -// Έχουν επίσης μερικές επιπλένον μεθόδους Scala. +// Έχουν επίσης μερικές επιπλέον μεθόδους Scala. // Δείτε επίσης : scala.collection.immutable.StringOps "hello world".take(5) "hello world".drop(5) @@ -253,7 +253,7 @@ r foreach println var i = 0 while (i < 10) { println("i " + i); i+=1 } -while (i < 10) { println("i " + i); i+=1 } // Ναι ξανά! Τι συνέβει; Γιατί; +while (i < 10) { println("i " + i); i+=1 } // Ναι ξανά! Τι συνέβη; Γιατί; i // Εμφάνισε την τιμή του i. Σημειώστε ότι ένας βρόχος while είναι βρόχος // με την κλασική έννοια - εκτελείται σειριακά καθώς αλλάζει η μεταβλητή @@ -268,8 +268,8 @@ do { } while (x < 10) // Η αναδρομή ουράς είναι ένας ιδιωματικός τρόπος να κάνεις επαναλαμβανόμενα -// πράγματα στην Scala. Οι αναδρομικές συναρτήσεις απαιτούν να γράφτεί -// ρητά ο τύπος που θα επιστρέψουν , αλλιώς ο μεταγλωττιστής δεν μπορεί +// πράγματα στην Scala. Οι αναδρομικές συναρτήσεις απαιτούν να γραφτεί +// ρητά ο τύπος που θα επιστρέψουν, αλλιώς ο μεταγλωττιστής δεν μπορεί // αλλιώς να τον συνάγει. Παρακάτω είναι μια συνάρτηση που επιστρέφει Unit. def showNumbersInRange(a:Int, b:Int):Unit = { print(a) @@ -332,7 +332,7 @@ s(1) val divideInts = (x:Int, y:Int) => (x / y, x % y) divideInts(10,3) // Η συνάρτηση divideInts επιστρέφει το αποτέλεσμα - // της ακαίρεας διαίρεσης και το υπόλοιπο. + // της ακέραιας διαίρεσης και το υπόλοιπο. // Για να έχουμε πρόσβαση στα στοιχεία μιας πλειάδας, χρησιμοποιούμε το _._n // όπου το n είναι ο δείκτης με βάση το 1 του στοιχείου. @@ -349,7 +349,7 @@ d._2 /* Ότι έχουμε κάνει ως τώρα σε αυτό το tutorial ήταν απλές εκφράσεις - (τιμές , συναρτήσεις , κτλ). Αυτές οι εκφράσεις βολεύουν όταν τις + (τιμές, συναρτήσεις, κτλ.). Αυτές οι εκφράσεις βολεύουν όταν τις γράφουμε στο REPL για γρήγορες δοκιμές, αλλά δεν μπορούν να υπάρχουν από μόνες τους σε ένα αρχείο Scala. Για παράδειγμα , δεν μπορούμε να έχουμε μόνο ένα "val x = 5" στο αρχείο Scala. Αντί αυτού , τα μόνα @@ -394,7 +394,7 @@ println(mydog.bark) // => "Woof, woof!" // αυτές καθ' αυτές, αλλά η συμπρεριφορά που σχετίζεται με όλα τα instances // της κλάσης πάνε μέσα στο object. Η διαφορά είναι παρόμοια με τις // μεθόδους κλάσεων σε σχέση με στατικές μεθόδους σε άλλες γλώσσες. -// Προσέξτε οτι τα objects και οι κλάσεις μπορούν να έχουν το ίδιο όνομα. +// Προσέξτε ότι τα objects και οι κλάσεις μπορούν να έχουν το ίδιο όνομα. object Dog { def allKnownBreeds = List("pitbull", "shepherd", "retriever") def createDog(breed: String) = new Dog(breed) @@ -402,7 +402,7 @@ object Dog { // Οι κλάσεις περίπτωσης (case classes) είναι που έχουν την επιπλέον // λειτουργικότητα ενσωματωμένη. Μιά συνήθης ερώτηση για αρχάριους στην -// Scala είναι πότε να χρησιμοπούνται κλάσεις και πότε case κλάσεις. +// Scala είναι πότε να χρησιμοποιούνται κλάσεις και πότε case κλάσεις. // Γενικά οι κλάσεις τείνουν να εστιάζουν στην ενθυλάκωση, τον // πολυμορφισμό και τη συμπεριφορά. Οι τιμές μέσα σε αυτές τις κλάσεις // τείνουν να είναι private , και μόνο οι μέθοδοι είναι εκτεθειμένες. @@ -411,7 +411,7 @@ object Dog { // έχουν παρενέργειες. case class Person(name: String, phoneNumber: String) -// Δημιουργία ενός instance. Πραρατηρήστε ότι τα case classes +// Δημιουργία ενός instance. Παρατηρήστε ότι τα case classes // δεν χρειάζονται την λέξη "new" . val george = Person("George", "1234") val kate = Person("Kate", "4567") @@ -419,7 +419,7 @@ val kate = Person("Kate", "4567") // Με τα case classes, παίρνεις μερικά προνόμια δωρεάν , όπως: george.phoneNumber // => "1234" -// Ελέχγεται η ισότητα για κάθε πεδίο (δεν χρειάζεται να +// Ελέγχεται η ισότητα για κάθε πεδίο (δεν χρειάζεται να // κάνουμε override στο .equals) Person("George", "1234") == Person("Kate", "1236") // => false @@ -509,7 +509,7 @@ List(1, 2, 3) map (x => x + 10) // ένα όρισμα στην ανώνυμη συνάρτηση. Έτσι δεσμεύεται ως η μεταβλητή. List(1, 2, 3) map (_ + 10) -// Αν το μπλόκ της ανώνυμης συνάρτησης ΚΑΙ η συνάρτηση που εφαρμόζεται +// Αν το μπλοκ της ανώνυμης συνάρτησης ΚΑΙ η συνάρτηση που εφαρμόζεται // (στην περίπτωσή μας το foreach και το println) παίρνουν ένα όρισμα // μπορείτε να παραλείψετε την κάτω παύλα. List("Dom", "Bob", "Natalia") foreach println diff --git a/elixir.html.markdown b/elixir.html.markdown index c8599838..eedeb227 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -369,6 +369,13 @@ spawn(f) #=> #PID<0.40.0> # messages to the process. To do message passing we use the `send` operator. # For all of this to be useful we need to be able to receive messages. This is # achieved with the `receive` mechanism: + +# The `receive do` block is used to listen for messages and process +# them when they are received. A `receive do` block will only +# process one received message. In order to process multiple +# messages, a function with a `receive do` block must recursively +# call itself to get into the `receive do` block again. + defmodule Geometry do def area_loop do receive do @@ -384,6 +391,8 @@ end # Compile the module and create a process that evaluates `area_loop` in the shell pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> +# Alternatively +pid = spawn(Geometry, :area_loop, []) # Send a message to `pid` that will match a pattern in the receive statement send pid, {:rectangle, 2, 3} diff --git a/es-es/amd-es.html.markdown b/es-es/amd-es.html.markdown new file mode 100644 index 00000000..7a59ddd6 --- /dev/null +++ b/es-es/amd-es.html.markdown @@ -0,0 +1,214 @@ +--- + +category: tool +tool: amd +contributors: + - ["Frederik Ring", "https://github.com/m90"] + +translators: + - ["Damaso Sanoja", "https://github.com/damasosanoja"] +filename: learnamd-es.js +lang: es-es +--- + +## Iniciando con AMD + +El API del **Módulo de Definición Asíncrono** especifica un mecanismo para definir módulos JavaScript de manera tal que tanto el módulo como sus dependencias puedan ser cargadas de manera asíncrona. Esto es particularmente adecuado para el entorno del navegador donde la carga sincronizada de los módulos genera problemas de rendimiento, usabilidad, depuración y acceso de multi-dominios. + +### Conceptos básicos +```javascript +// El API básico de AMD consiste en tan solo dos métodos: `define` y `require` +// y se basa en la definición y consumo de los módulos: +// `define(id?, dependencias?, fábrica)` define un módulo +// `require(dependencias, callback)` importa un conjunto de dependencias y +// las consume al invocar el callback + +// Comencemos usando define para definir un nuevo módulo +// que no posee dependencias. Lo haremos enviando un nombre +// y una función fábrica para definirla: +define('awesomeAMD', function(){ + var isAMDAwesome = function(){ + return true; + }; + // El valor que regresa la función fábrica del módulo será + // lo que los otros módulos o llamados require recibirán cuando + // soliciten nuestro módulo `awesomeAMD`. + // El valor exportado puede ser cualquier cosa, funciones (constructores), + // objetos, primitivos, incluso indefinidos (aunque eso no ayuda mucho). + return isAMDAwesome; +}); + +// Ahora definamos otro módulo que dependa de nuestro módulo `awesomeAMD`. +// Observe que ahora hay un argumento adicional que define +// las dependencias de nuestro módulo: +define('loudmouth', ['awesomeAMD'], function(awesomeAMD){ + // las dependencias serán enviadas a los argumentos de la fábrica + // en el orden que sean especificadas + var tellEveryone = function(){ + if (awesomeAMD()){ + alert('This is sOoOo rad!'); + } else { + alert('Pretty dull, isn\'t it?'); + } + }; + return tellEveryone; +}); + +// Como ya sabemos utilizar define usemos ahora `require` para poner en marcha +// nuestro programa. La firma de `require` es `(arrayOfDependencies, callback)`. +require(['loudmouth'], function(loudmouth){ + loudmouth(); +}); + +// Para hacer que este tutorial corra código, vamos a implementar una +// versión muy básica (no-asíncrona) de AMD justo aquí: +function define(name, deps, factory){ + // observa como son manejados los módulos sin dependencias + define[name] = require(factory ? deps : [], factory || deps); +} + +function require(deps, callback){ + var args = []; + // primero recuperemos todas las dependencias que necesita + // el llamado require + for (var i = 0; i < deps.length; i++){ + args[i] = define[deps[i]]; + } + // satisfacer todas las dependencias del callback + return callback.apply(null, args); +} +// puedes ver este código en acción aquí: http://jsfiddle.net/qap949pd/ +``` + +### Uso en el mundo real con require.js + +En contraste con el ejemplo introductorio, `require.js` (la librería AMD más popular) implementa la **A** de **AMD**, permitiéndote cargar los módulos y sus dependencias asincrónicamente via XHR: + +```javascript +/* file: app/main.js */ +require(['modules/someClass'], function(SomeClass){ + // el callback es diferido hasta que la dependencia sea cargada + var thing = new SomeClass(); +}); +console.log('So here we are, waiting!'); // esto correrá primero +``` + +Por convención, usualmente guardas un módulo en un fichero. `require.js` puede resolver los nombres de los módulos basados en rutas de archivo, de forma que no tienes que nombrar tus módulos, simplemente referenciarlos usando su ubicación. En el ejemplo `someClass` asumimos que se ubica en la carpeta `modules`, relativa a tu `baseUrl` configurada: + +* app/ + * main.js + * modules/ + * someClass.js + * someHelpers.js + * ... + * daos/ + * things.js + * ... + +Esto significa que podemos definir `someClass` sin especificar su id de módulo: + +```javascript +/* file: app/modules/someClass.js */ +define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){ + // definición de módulo, por supuesto, ocurrirá también asincrónicamente + function SomeClass(){ + this.method = function(){/**/}; + // ... + } + return SomeClass; +}); +``` + +Para alterar el comportamiento del mapeo de ruta usa `requirejs.config(configObj)` en tu `main.js`: + +```javascript +/* file: main.js */ +requirejs.config({ + baseUrl : 'app', + paths : { + // también puedes cargar módulos desde otras ubicaciones + jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}); +require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolLib, helpers){ + // un fichero `main` necesita llamar a require al menos una vez, + // de otra forma jamás correrá el código + coolLib.doFancyStuffWith(helpers.transform($('#foo'))); +}); +``` +Las aplicaciones basadas en `require.js` usualmente tendrán un solo punto de entrada (`main.js`) que se pasa a la etiqueta del script `require.js` como un atributo de datos. Será cargado y ejecutado automáticamente al cargar la página: + +```html +<!DOCTYPE html> +<html> +<head> + <title>Cien etiquetas de script? Nunca más!</title> +</head> +<body> + <script src="require.js" data-main="app/main"></script> +</body> +</html> +``` + +### Optimizar todo un proyecto usando r.js + +Muchas personas prefieren usar AMD para la organización del código durante el desarrollo, pero quieren enviar para producción un solo fichero en vez de ejecutar cientos de XHRs en las cargas de página. + +`require.js` incluye un script llamado `r.js` (el que probablemente correrás en node.js, aunque Rhino también es soportado) que puede analizar el gráfico de dependencias de tu proyecto, y armar un solo fichero que contenga todos tus módulos (adecuadamente nombrados), minificado y listo para consumo. + +Instálalo usando `npm`: +```shell +$ npm install requirejs -g +``` + +Ahora puedes alimentarlo con un fichero de configuración: +```shell +$ r.js -o app.build.js +``` + +Para nuestro ejemplo anterior el archivo de configuración luciría así: +```javascript +/* file : app.build.js */ +({ + name : 'main', // nombre del punto de entrada + out : 'main-built.js', // nombre del fichero donde se escribirá la salida + baseUrl : 'app', + paths : { + // `empty:` le dice a r.js que esto aún debe ser cargado desde el CDN, usando + // la ubicación especificada en `main.js` + jquery : 'empty:', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}) +``` + +Para usar el fichero creado en producción, simplemente intercambia `data-main`: +```html +<script src="require.js" data-main="app/main-built"></script> +``` + +Un increíblemente detallado [resumen de opciones de generación](https://github.com/jrburke/r.js/blob/master/build/example.build.js) está disponible en el repositorio de GitHub. + +### Tópicos no cubiertos en este tutorial +* [Cargador de plugins / transformaciones](http://requirejs.org/docs/plugins.html) +* [Cargando y exportando estilos CommonJS](http://requirejs.org/docs/commonjs.html) +* [Configuración avanzada](http://requirejs.org/docs/api.html#config) +* [Configuración de Shim (cargando módulos no-AMD)](http://requirejs.org/docs/api.html#config-shim) +* [Cargando y optimizando CSS con require.js](http://requirejs.org/docs/optimization.html#onecss) +* [Usando almond.js para construcciones](https://github.com/jrburke/almond) + +### Otras lecturas: + +* [Especificaciones oficiales](https://github.com/amdjs/amdjs-api/wiki/AMD) +* [¿Por qué AMD?](http://requirejs.org/docs/whyamd.html) +* [Definición Universal de Módulos](https://github.com/umdjs/umd) + +### Implementaciones: + +* [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/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/es-es/tmux-es.html.markdown b/es-es/tmux-es.html.markdown new file mode 100644 index 00000000..a7354be1 --- /dev/null +++ b/es-es/tmux-es.html.markdown @@ -0,0 +1,253 @@ +--- +category: tool +tool: tmux +contributors: + - ["mdln", "https://github.com/mdln"] +filename: LearnTmux-es.txt +translators: + - ["Damaso Sanoja", "https://github.com/damasosanoja"] +lang: es-es +--- + + +[tmux](http://tmux.sourceforge.net) +es un terminal multiplexor: habilita la creación, acceso y control +de múltiples terminales controlados desde una sola pantalla. tmux +puede ser separado de una pantalla y continuar corriendo en el fondo +y luego ser insertado nuevamente. + + +``` + + tmux [command] # Corre un comando + # 'tmux' sin comandos creará una nueva sesión + + new # Crea una nueva sesión + -s "Session" # Crea sesión con nombre + -n "Window" # Crea ventana con nombre + -c "/dir" # Comienza en el directorio destino + + attach # Adjunta sesión última/disponible + -t "#" # Adjunta sesión destino + -d # Separa la sesión de otras instancias + + ls # Lista las sesiones abiertas + -a # Lista todas las sesiones abiertas + + lsw # Lista las ventanas + -a # Lista todas las ventanas + -s # Lista todas las ventanas en la sesión + + lsp # Lista los páneles + -a # Lista todos los páneles + -s # Lista todos los páneles de la sesión + -t # Lista los páneles de aplicación en el destino + + kill-window # Cierra la ventana actual + -t "#" # Cierra la ventana destino + -a # Cierra todas las ventanas + -a -t "#" # Cierra todas las ventanas menos el destino + + kill-session # Cierra la sesión actual + -t "#" # Cierra la sesión destino + -a # Cierra todas las sesiones + -a -t "#" # Cierra todas las sesiones menos el destino + +``` + + +### Atajos de Teclado + +El método para controlar una sesión adjunta tmux es mediante +combinaciones de teclas llamadas teclas 'Prefijo'. + +``` +---------------------------------------------------------------------- + (C-b) = Ctrl + b # combinación 'Prefijo' necesaria para usar atajos + + (M-1) = Meta + 1 -o- Alt + 1 +---------------------------------------------------------------------- + + ? # Lista todos los atajos de teclado + : # Entra en la línea de comandos tmux + r # Fuerza el redibujado del cliente adjuntado + c # Crea una nueva ventana + + ! # Separa el panel actual fuera de la ventana. + % # Separa el panel actual en dos, izquierdo y derecho + " # Separa el panel actual en dos, superior e inferior + + n # Cambia a la siguiente ventana + p # Cambia a la ventana previa + { # Intercambia el panel actual con el anterior + } # Intercambia el panel actual con el próximo + + s # Selecciona una nueva sesión para el cliente adjuntado + interactivamente + w # Elegir la ventana actual interactivamente + 0 al 9 # Seleccionar ventanas 0 al 9 + + d # Separa el cliente actual + D # Elige un cliente para separar + + & # Cierra la ventana actual + x # Cierra el panel actual + + Up, Down # Cambia al panel superior, inferior, izquierdo, o derecho + Left, Right + + M-1 to M-5 # Organizar páneles: + # 1) uniformes horizontales + # 2) uniformes verticales + # 3) principal horizontal + # 4) principal vertical + # 5) mozaico + + C-Up, C-Down # Redimensiona el panel actual en pasos de una celda + C-Left, C-Right + + M-Up, M-Down # Redimensiona el panel actual en pasos de cinco celdas + M-Left, M-Right + +``` + + +### Configurando ~/.tmux.conf + +tmux.conf puede usarse para establecer opciones automáticas al arrancar, parecido a como .vimrc o init.el hacen. + +``` +# Ejemplo de tmux.conf +# 2014.10 + + +### General +########################################################################### + +# Habilita UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Fuera de pantalla/Historia límite +set -g history-limit 2048 + +# Comienzo de índice +set -g base-index 1 + +# Ratón +set-option -g mouse-select-pane on + +# Forza recarga de fichero de configuración +unbind r +bind r source-file ~/.tmux.conf + + +### Atajos de teclado +########################################################################### + +# Desvincula C-b como el prefijo por defecto +unbind C-b + +# Establece el nuevo prefijo +set-option -g prefix ` + +# Regresa a la ventana previa cuando el prefijo es accionado dos veces +bind C-a last-window +bind ` last-window + +# Permite intercambiar C-a y ` usando F11/F12 +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` + +# Preferencias de atajos +setw -g mode-keys vi +set-option -g status-keys vi + +# Moviéndose entre paneles con movimientos de teclas vim +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R + +# Ciclo/Intercambio de Ventana +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +# División rápida de paneles +bind = split-window -h +bind - split-window -v +unbind '"' +unbind % + +# Activar sesión mas interna (cuando se anida tmux) para enviar comandos +bind a send-prefix + + +### Temas +########################################################################### + +# Paleta de Colores de la Barra de estado +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +# Paleta de Colores del Borde del Panel +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +# Paleta de Colores de Mensajes +set-option -g message-fg black +set-option -g message-bg green + +# Paleta de Colores de la Ventana +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +# Notificación +setw -g monitor-activity on +set -g visual-activity on +set-option -g bell-action any +set-option -g visual-bell off + +# Establece automáticamente títulos de ventanas +set-option -g set-titles on +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) + +# Ajustes de barra de estado +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" + +# Muestra indicadores de rendimiento en barra de estado +# Requiere https://github.com/thewtex/tmux-mem-cpu-load/ +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + + +### Referencias + +[Tmux | Inicio](http://tmux.sourceforge.net) + +[Tmux Manual](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) + +[Mostrar CPU/MEM % en barra de estado](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) diff --git a/fr-fr/clojure-fr.html.markdown b/fr-fr/clojure-fr.html.markdown index d3c5a67b..63bc25b5 100644 --- a/fr-fr/clojure-fr.html.markdown +++ b/fr-fr/clojure-fr.html.markdown @@ -248,7 +248,7 @@ keymap ; => {:a 1, :b 2, :c 3} ; Il y a encore d'autres fonctions dans l'espace de nom clojure.sets. -; Formes utiles +; Formes et macros utiles ;;;;;;;;;;;;;;; ; Les constructions logiques en Clojure sont juste des macros, et @@ -275,6 +275,33 @@ ressemblent à toutes les autres formes: (let [name "Urkel"] (print "Saying hello to " name) (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") + +; Utilisez les Threading Macros (-> et ->>) pour exprimer plus +; clairement vos transformations, en y pensant de manière multi-niveaux. + +; La "flèche simple" ou "Thread-first", insère, à chaque niveau +; de la transformation, la forme courante en la seconde position +; de la forme suivante, constituant à chaque fois un nouvel étage +; de transformation. Par exemple: +(-> + {:a 1 :b 2} + (assoc :c 3) ;=> Génère ici (assoc {:a 1 :b 2} :c 3) + (dissoc :b)) ;=> Génère ici (dissoc (assoc {:a 1 :b 2} :c 3) :b) + +; Cette expression est ré-écrite en: +; (dissoc (assoc {:a 1 :b 2} :c 3) :b) +; et est évaluée en : {:a 1 :c 3} + +; La "flèche double" ou "Thread-last" procède de la même manière +; que "->", mais insère le résultat de la réécriture de chaque +; étage en dernière position. Par exemple: +(->> + (range 10) + (map inc) ;=> Génère ici (map inc (range 10) + (filter odd?) ;=> Génère ici (filter odd? (map inc (range 10)) + (into [])) ;=> Génère ici (into [] (filter odd? (map inc (range 10))), ce qui est évalué au final à; + ; [1 3 5 7 9] + ; Modules ;;;;;;;;;;;;;;; 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/git.html.markdown b/git.html.markdown index 971d53e4..bedc9853 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -371,9 +371,12 @@ Pulls from a repository and merges it with another branch. # Update your local repo, by merging in new changes # from the remote "origin" and "master" branch. # git pull <remote> <branch> -# git pull => implicitly defaults to => git pull origin master $ git pull origin master +# By default, git pull will update your current branch +# by merging in new changes from its remote-tracking branch +$ git pull + # Merge in changes from remote branch and rebase # branch commits onto your local repo, like: "git pull <remote> <branch>, git rebase <branch>" $ git pull origin master --rebase @@ -387,9 +390,12 @@ Push and merge changes from a branch to a remote & branch. # Push and merge changes from a local repo to a # remote named "origin" and "master" branch. # git push <remote> <branch> -# git push => implicitly defaults to => git push origin master $ git push origin master +# By default, git push will push and merge changes from +# the current branch to its remote-tracking branch +$ git push + # To link up current local branch with a remote branch, add -u flag: $ git push -u origin master # Now, anytime you want to push from that same local branch, use shortcut: @@ -527,3 +533,6 @@ $ git rm /pather/to/the/file/HelloWorld.c * [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) * [Pro Git](http://www.git-scm.com/book/en/v2) + +* [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) + 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..08611e63 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -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/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/it-it/bash-it.html.markdown b/it-it/bash-it.html.markdown index f892845f..af8823c4 100644 --- a/it-it/bash-it.html.markdown +++ b/it-it/bash-it.html.markdown @@ -13,13 +13,14 @@ contributors: filename: LearnBash.sh translators: - ["Robert Margelli", "http://github.com/sinkswim/"] + - ["Tommaso Pifferi", "http://github.com/neslinesli93/"] lang: it-it --- Bash è il nome della shell di unix, la quale è stata distribuita anche come shell del sistema oprativo GNU e la shell di default su Linux e Mac OS X. Quasi tutti gli esempi sottostanti possono fare parte di uno shell script o eseguiti direttamente nella shell. -[Per saperne di piu'.](http://www.gnu.org/software/bash/manual/bashref.html) +[Per saperne di più.](http://www.gnu.org/software/bash/manual/bashref.html) ```bash #!/bin/bash @@ -34,32 +35,34 @@ echo Ciao mondo! echo 'Questa è la prima riga'; echo 'Questa è la seconda riga' # Per dichiarare una variabile: -VARIABILE="Una stringa" +Variabile="Una stringa" # Ma non così: -VARIABILE = "Una stringa" -# Bash stabilirà che VARIABILE è un comando da eseguire e darà un errore +Variabile = "Una stringa" +# Bash stabilirà che Variabile è un comando da eseguire e darà un errore # perchè non esiste. # Usare la variabile: -echo $VARIABILE -echo "$VARIABILE" -echo '$VARIABILE' +echo $Variabile +echo "$Variabile" +echo '$Variabile' # Quando usi la variabile stessa - assegnala, esportala, oppure — scrivi # il suo nome senza $. Se vuoi usare il valore della variabile, devi usare $. # Nota che ' (singolo apice) non espande le variabili! # Sostituzione di stringhe nelle variabili -echo ${VARIABILE/Una/A} +echo ${Variabile/Una/A} # Questo sostituirà la prima occorrenza di "Una" con "La" # Sottostringa di una variabile -echo ${VARIABILE:0:7} +Lunghezza=7 +echo ${Variabile:0:Lunghezza} # Questo ritornerà solamente i primi 7 caratteri # Valore di default per la variabile -echo ${FOO:-"ValoreDiDefaultSeFOOMancaOÈ Vuoto"} -# Questo funziona per null (FOO=), stringa vuota (FOO=""), zero (FOO=0) ritorna 0 +echo ${Foo:-"ValoreDiDefaultSeFooMancaOppureÈVuoto"} +# Questo funziona per null (Foo=), stringa vuota (Foo=""), zero (Foo=0) ritorna 0 +# Nota: viene ritornato il valore di default, il contenuto della variabile pero' non cambia. # Variabili builtin: # Ci sono delle variabili builtin molto utili, come @@ -71,31 +74,40 @@ echo "Argomenti dello script separati in variabili distinte: $1 $2..." # Leggere un valore di input: echo "Come ti chiami?" -read NOME # Nota che non abbiamo dovuto dichiarare una nuova variabile -echo Ciao, $NOME! +read Nome # Nota che non abbiamo dovuto dichiarare una nuova variabile +echo Ciao, $Nome! # Classica struttura if: # usa 'man test' per maggiori informazioni sulle condizionali -if [ $NOME -ne $USER ] +if [ $Nome -ne $USER ] then echo "Il tuo nome non è lo username" else echo "Il tuo nome è lo username" fi +# Nota: se $Name è vuoto, la condizione precedente viene interpretata come: +if [ -ne $USER ] +# che genera un errore di sintassi. Quindi il metodo sicuro per usare +# variabili che possono contenere stringhe vuote è il seguente: +if [ "$Name" -ne $USER ] ... +# che viene interpretato come: +if [ "" -ne $USER ] ... +# e dunque funziona correttamente. + # C'è anche l'esecuzione condizionale echo "Sempre eseguito" || echo "Eseguito solo se la prima condizione fallisce" echo "Sempre eseguito" && echo "Eseguito solo se la prima condizione NON fallisce" # Per usare && e || con l'if, c'è bisogno di piu' paia di parentesi quadre: -if [ $NOME == "Steve" ] && [ $ETA -eq 15 ] +if [ "$Nome" == "Steve" ] && [ "$Eta" -eq 15 ] then - echo "Questo verrà eseguito se $NOME è Steve E $ETA è 15." + echo "Questo verrà eseguito se $Nome è Steve E $Eta è 15." fi -if [ $NOME == "Daniya" ] || [ $NOME == "Zach" ] +if [ "$Nome" == "Daniya" ] || [ "$Nome" == "Zach" ] then - echo "Questo verrà eseguito se $NAME è Daniya O Zach." + echo "Questo verrà eseguito se $Nome è Daniya O Zach." fi # Le espressioni sono nel seguente formato: @@ -137,7 +149,7 @@ python hello.py > /dev/null 2>&1 # se invece vuoi appendere usa ">>": python hello.py >> "output.out" 2>> "error.err" -# Sovrascrivi output.txt, appendi a error.err, e conta le righe: +# Sovrascrivi output.out, appendi a error.err, e conta le righe: info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err wc -l output.out error.err @@ -145,7 +157,7 @@ wc -l output.out error.err # vedi: man fd echo <(echo "#ciaomondo") -# Sovrascrivi output.txt con "#helloworld": +# Sovrascrivi output.out con "#helloworld": cat > output.out <(echo "#helloworld") echo "#helloworld" > output.out echo "#helloworld" | cat > output.out @@ -164,7 +176,7 @@ echo "Ci sono $(ls | wc -l) oggetti qui." echo "Ci sono `ls | wc -l` oggetti qui." # Bash utilizza uno statemente case che funziona in maniera simile allo switch in Java e C++: -case "$VARIABILE" in +case "$Variabile" in #Lista di pattern per le condizioni che vuoi soddisfare 0) echo "C'è uno zero.";; 1) echo "C'è un uno.";; @@ -172,10 +184,10 @@ case "$VARIABILE" in esac # I cicli for iterano per ogni argomento fornito: -# I contenuti di $VARIABILE sono stampati tre volte. -for VARIABILE in {1..3} +# I contenuti di $Variabile sono stampati tre volte. +for Variabile in {1..3} do - echo "$VARIABILE" + echo "$Variabile" done # O scrivilo con il "ciclo for tradizionale": @@ -186,16 +198,16 @@ done # Possono essere usati anche per agire su file.. # Questo eseguirà il comando 'cat' su file1 e file2 -for VARIABILE in file1 file2 +for Variabile in file1 file2 do - cat "$VARIABILE" + cat "$Variabile" done # ..o dall'output di un comando # Questo eseguirà cat sull'output di ls. -for OUTPUT in $(ls) +for Output in $(ls) do - cat "$OUTPUT" + cat "$Output" done # while loop: @@ -223,7 +235,7 @@ bar () } # Per chiamare la funzione -foo "Il mio nome è" $NOME +foo "Il mio nome è" $Nome # Ci sono un sacco di comandi utili che dovresti imparare: # stampa le ultime 10 righe di file.txt @@ -245,7 +257,7 @@ grep "^foo.*bar$" file.txt grep -c "^foo.*bar$" file.txt # se vuoi letteralmente cercare la stringa, # e non la regex, usa fgrep (o grep -F) -fgrep "^foo.*bar$" file.txt +fgrep "^foo.*bar$" file.txt # Leggi la documentazione dei builtin di bash con il builtin 'help' di bash: diff --git a/it-it/brainfuck-it.html.markdown b/it-it/brainfuck-it.html.markdown index 4999d7e6..08d2ede9 100644 --- a/it-it/brainfuck-it.html.markdown +++ b/it-it/brainfuck-it.html.markdown @@ -1,75 +1,72 @@ --- - language: brainfuck contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] translators: - ["Ivan Sala", "http://slavni96.github.io/"] + - ["Christian Grasso", "http://chris54721.net"] lang: it-it - --- -Brainfuck è un linguaggio di programmazione estremamente minimale, -ma è ingrado di rappresentare completamente una macchina di turnig, -e sfrutta solo 8 caratteri. -[Per saperne di più](http://it.wikipedia.org/wiki/Brainfuck) +Brainfuck è un linguaggio di programmazione +[Turing equivalente](https://it.wikipedia.org/wiki/Turing_equivalenza) +estremamente minimale, composto da solo 8 comandi. + +Puoi provarlo nel tuo browser utilizzando +[brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). ``` -Qualsiasi carattere che non sia "><+-.,[]" (escludendo gli apici) +Qualsiasi carattere diverso da "><+-.,[]" (escludendo gli apici) viene ignorato. -Branfuck è caratterizzato da un array (vettore) di 30,000 celle -inizializzare a zero, e un puntatore che punta alla cella corrente. +Branfuck è caratterizzato da un array di 30,000 celle inizializzate a zero +e da un puntatore che punta alla cella corrente. -Vi sono solo otto comando: +Vi sono otto comandi: + : Incrementa il valore della cella attuale di uno. - : Decrementa il valore della cella attuale di uno. -> : Sposta il puntatore sulla cella seguente (prossima a destra). -< : Sposta il puntatore sulla cella precendete (precedente a sinistra). -. : Stampa il valore in ASCII della cella corrente. (es: 65 = 'A') -, : Legge un singolo carattere come input per la cella corrente. -[ : Se il valore della cella corrente è zero, conclude il ciclo - andando alla sua corrispondente ]. +> : Sposta il puntatore sulla cella seguente (sulla destra). +< : Sposta il puntatore sulla cella precendete (sulla sinistra). +. : Stampa il valore ASCII della cella corrente. (es. 65 = 'A') +, : Legge un singolo carattere come input e lo salva nella cella corrente. +[ : Se il valore della cella corrente è zero, prosegue fino alla ] corrispondente. Altrimenti, passa alla prossima istruzione. ] : Se il valore della cella corrente è zero, passa alla prossima istruzione. - Altrimenti torna indetro fino alla [ corrispondente. + Altrimenti, torna indietro fino alla [ corrispondente. -[ e ] creano un loop (while). Ovviamente dovranno essere bilanciati. -Per ogni [ dovrà corrispondere una ] +[ e ] formano un ciclo while. Ovviamente dovranno essere bilanciati. +(Ad ogni [ dovrà corrispondere una ]) -Alcuni semplici esempi di programmi scritti in Brainfuck: +Ecco alcuni semplici esempi di programmi scritti in Brainfuck: ++++++ [ > ++++++++++ < - ] > +++++ . -Questo programma stampa in output la lettera 'A'. Priam incrementa -la cella #1 fino a 6, Quindi la cella #1 viene usata per crare un ciclo. -Poi, entra in un loop ([) e si sposta alla cella #2. -Incrementa la cella #2 10 volte, e torna alla cella #1, e la decrementa. -Questo avviene 6 volte (servono che la cella #1 venga decrementata 6 volte -per raggiungere lo 0. Quindi passa alla corrispondente ] e prosegue). +Questo programma stampa in output la lettera 'A'. Prima di tutto, incrementa +la cella #1 fino al valore 6. La cella #1 verrà utilizzata per il ciclo. +Poi, entra nel ciclo ([) e si sposta alla cella #2. Incrementa la cella #2 10 +volte, torna alla cella #1, e decrementa quest'ultima. +Il ciclo si ripete 6 volte (la cella #1 viene decrementata 6 volte prima di +raggiungere lo 0, quindi prosegue oltre la corrispondente ]). -A questo punto, siamo sulla cella #1, che ha valore 0, -la cella #2 ha valore 60 (6*10). Ci spostiamo sulla cella #2, incrementiamo -per 5 volte, e otteniamo il valore 65, quindi stampaimo il valore della cella -#2 (.). -65 è 'A' in ASCII, quindi alla fine viene stampata 'A'. +A questo punto, siamo sulla cella #1, che ha valore 0, mentre la cella #2 ha +valore 60. Ci spostiamo sulla cella #2, la incrementiamo per 5 volte, ottenendo +il valore 65, quindi stampiamo il valore della cella #2. +Il valore 65 equivale ad 'A' in ASCII, per cui viene stampato 'A' nel terminale. , [ > + < - ] > . -Questo programma legge un carattere come input dall'utente, -quindi salva il carattere dentro la cella #1. -In seguito, incominca a ciclare. -Si sposta alla cella #², e increementa il valore della cella (#2). -Quindi torna alla cella #1, e decrementa il valore della cella (#1). -Questo continua fino a quando la cella #²1 diventa 0, e quindi la cella #2 -avrà il valore iniziale della cella #1. -Infine, visto che ci troviamo sulla cella #1 alla fine del ciclo, si sposta -sulla cella #2 e stampa il valore in ASCII. +Questo programma legge un carattere come input dall'utente, quindi salva il +carattere nella cella #1. Dopodichè entra in un ciclo. Si sposta alla cella #2, +incrementa quest'ultima, torna alla cella #1, e decrementa quest'ultima. +Il ciclo continua fino a quando la cella #1 diventa 0, e quindi la cella #2 +avrà il valore iniziale della cella #1. Infine, visto che ci troviamo sulla +cella #1 alla fine del ciclo, si sposta sulla cella #2 e stampa il valore in +ASCII. -Gli spazi nel codice sovrastante, sono presenti solo a scopo di ottenere -una maggiore leggibilità, si poteva anche scrivere senza: +Gli spazi nel codice sovrastante sono presenti solo a scopo di ottenere +una maggiore leggibilità. Lo stesso programma poteva essere scritto senza spazi: ,[>+<-]>. @@ -77,25 +74,19 @@ Proviamo, adesso, a capire cosa fa invece questo programma: ,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> -Prende due numeri in input e quindi li moltiplica. +Il programma legge 2 numeri come input dall'utente, e li moltiplica. -Prima prende in input i due numeri (,>,<), quindi inizia un cilclo -basandosi sulla cella #1. -Quindi si sposta sulla cella #2, e inizia un altro ciclo condizionato -dal valore della cella #2, incrementando la cella #3. +Innanzitutto, legge in input i due numeri. Poi entra nel ciclo più esterno +basandosi sulla cella #1. Quindi si sposta sulla cella #2, e inizia il ciclo +più interno basandosi sul valore della cella #2, incrementando la cella #3. Arrivati a questo punto abbiamo un problema: alla fine del ciclo interno -la cella #2 ha valore 0. In questo caso, quando il ciclo esterno rifarà -partire il ciclo interno, non funzionerà più perchè la cella #2 ha valore 0. -Per ovviare a questo problema, oltre alla cella 3, incrementiamo anche la cella -#4, e alla fine di ogni ciclo interno copiala il valore della cella #4 -nella cella #2, in modo che il ciclo interno -possa essere eseguito una altra volta. -Alla fine la cella #3 contiene il risultato. +la cella #2 avrà valore 0. Ciò impedirà di eseguire nuovamente il ciclo interno. +Per ovviare a questo problema, incrementiamo anche la cella #4, e copiamo il +valore di quest'ultima nella cella #2. +Il risultato sarà infine contenuto nella cella #3. ``` -E questo è brainfuck...Non è difficele, vero? -Per divertimento adesso puoi scrivere i tuoi programmi in brainfuck, -oppure puoi scrivere un interprete brainfuck in un altro linguaggio. -L'interprete è abbastanza semplice da implementare, ma se sei veramente -masochista prova ad implementare un interprete brainfuck in... -brainfuck. +E questo è brainfuck. Non è così difficile, eh? Se vuoi, ora puoi scrivere per +divertimento altri programmi in brainfuck, oppure scrivere un interprete +brainfuck in un altro linguaggio. L'interprete è abbastanza semplice da +implementare, ma se sei veramente masochista, prova ad implementare un interprete brainfuck... in brainfuck. diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown index e7e1d89e..92ebc165 100644 --- a/it-it/c++-it.html.markdown +++ b/it-it/c++-it.html.markdown @@ -4,6 +4,8 @@ filename: learncpp-it.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] - ["Matt Kline", "https://github.com/mrkline"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Connor Waters", "http://github.com/connorwaters"] translators: - ["Robert Margelli", "http://github.com/sinkswim/"] lang: it-it @@ -54,11 +56,11 @@ int main(int argc, char** argv) // Tuttavia, il C++ varia nei seguenti modi: -// In C++, i caratteri come letterali sono da un byte. -sizeof('c') == 1 +// In C++, i caratteri come letterali sono dei char. +sizeof('c') == sizeof(char) == 1 -// In C, i caratteri come letterali sono della stessa dimensione degli interi. -sizeof('c') == sizeof(10) +// In C, i caratteri come letterali sono degli interi. +sizeof('c') == sizeof(int) // C++ ha prototipizzazione rigida @@ -160,11 +162,14 @@ void foo() int main() { - // Assume che tutto venga dal namespace "Secondo" - // a meno che non venga dichiarato altrimenti. + // Include tutti i simboli del namespace Secondo nello scope attuale. + // Osserva che chiamare semplicemente foo() non va più bene perché è ambiguo: + // bisogna specificare se vogliamo chiamare foo definita nel namespace Secondo + // o foo definita nel livello principale del programma. + using namespace Secondo; - foo(); // stampa "Questa è Secondo::foo" + Secondo::foo(); // stampa "Questa è Secondo::foo" Primo::Annidato::foo(); // stampa "Questa è Primo::Annidato::foo" ::foo(); // stampa "Questa è foo globale" } @@ -244,12 +249,137 @@ cout << fooRef; // Stampa "Io sono foo. Ciao!" // Non riassegna "fooRef". Questo è come scrivere "foo = bar", e // foo == "Io sono bar" // dopo questa riga. +cout << &fooRef << endl; // Stampa l'indirizzo di foo fooRef = bar; +cout << &fooRef << endl; // Stampa lo stesso l'indirizzo di foo +cout << fooRef; // Stampa "Io sono bar" + +// L'indirizzo di fooRef rimane lo stesso, ovvero si riferisce ancora a foo. + const string& barRef = bar; // Crea un riferimento const a bar. // Come in C, i valori const (i puntatori e i riferimenti) non possono essere modificati. barRef += ". Ciao!"; // Errore, i riferimenti const non possono essere modificati. +// Facciamo un piccolo excursus: prima di approfondire ancora i riferimenti, è necessario +// introdurre il concetto di oggetto temporaneo. Supponiamo di avere il seguente codice: +string tempObjectFun() { ... } +string retVal = tempObjectFun(); + +// Nella seconda riga si ha che: +// - un oggetto di tipo stringa viene ritornato da tempObjectFun +// - viene costruita una nuova stringa, utilizzando l'oggetto ritornato come +// argomento per il costruttore +// - l'oggetto ritornato da tempObjectFun viene distrutto +// L'oggetto ritornato da tempObjectFun viene detto oggetto temporaneo. +// Un oggetto temporaneo viene creato quando una funzione ritorna un oggetto, e viene +// distrutto quando l'espressione che lo racchiude termina la sua esecuzione - questo +// comportamento viene definito dallo standard, ma i compilatori possono modificarlo +// a piacere. Cerca su google "return value optimization" se vuoi approfondire. +// Dunque nel seguente codice: +foo(bar(tempObjectFun())) + +// dando per scontato che foo e bar esistano, l'oggetto ritornato da tempObjectFun +// è passato a bar ed è distrutto prima dell'invocazione di foo. + +// Tornando ai riferimenti, c'è un'eccezione a quanto appena detto. +// Infatti un oggetto temporaneo "viene distrutto quando l'espressione +// che lo racchiude termina la sua esecuzione", tranne quando è legato ad un +// riferimento di tipo const. In tal caso la sua vita viene estesa per tutto +// lo scope attuale: + +void constReferenceTempObjectFun() { + // constRef riceve l'oggetto temporaneo, che non viene distrutto fino + // alla fine di questa funzione. + const string& constRef = tempObjectFun(); + ... +} + +// Un altro tipo di riferimento introdotto nel C++11 è specifico per gli +// oggetti temporanei. Non puoi dichiarare una variabile di quel tipo, ma +// ha la precedenza nella risoluzione degli overload: + +void someFun(string& s) { ... } // Riferimento normale +void someFun(string&& s) { ... } // Riferimento ad un oggetto temporaneo + +string foo; +someFun(foo); // Chiama la versione con il riferimento normale +someFun(tempObjectFun()); // Chiama la versione con il riferimento temporaneo + +// Ad esempio potrai vedere questi due costruttori per std::basic_string: +basic_string(const basic_string& other); +basic_string(basic_string&& other); + +// L'idea è che se noi costruiamo una nuova stringa a partire da un oggetto temporaneo +// (che in ogni caso verrà distrutto), possiamo avere un costruttore più efficiente +// che in un certo senso "recupera" parti di quella stringa temporanea. +// Ci si riferisce a questo concetto come "move semantics". + +///////////////////// +// Enum +///////////////////// + +// Gli enum sono un modo per assegnare un valore ad una costante, e sono +// principalmente usati per rendere il codice più leggibile. +enum ETipiMacchine +{ + AlfaRomeo, + Ferrari, + SUV, + Panda +}; + +ETipiMacchine GetPreferredCarType() +{ + return ETipiMacchine::Ferrari; +} + +// Dal C++11 in poi c'è un modo molto semplice per assegnare un tipo ad un enum, +// che può essere utile per la serializzazione dei dati o per convertire gli enum +// tra il tipo desiderato e le rispettive costanti. +enum ETipiMacchine : uint8_t +{ + AlfaRomeo, // 0 + Ferrari, // 1 + SUV = 254, // 254 + Ibrida // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Serializza InputValue in un file +} + +void WritePreferredCarTypeToFile(ETipiMacchine InputCarType) +{ + // L'enum viene implicitamente convertito ad un uint8_t poiché + // è stato dichiarato come tale + WriteByteToFile(InputCarType); +} + +// D'altro canto potresti voler evitare che un enum venga accidentalmente convertito +// in un intero o in un altro tipo, quindi è possibile create una classe enum che +// impedisce la conversione implicita. +enum class ETipiMacchine : uint8_t +{ + AlfaRomeo, // 0 + Ferrari, // 1 + SUV = 254, // 254 + Ibrida // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Serializza InputValue in un file +} + +void WritePreferredCarTypeToFile(ETipiMacchine InputCarType) +{ + // Il compilatore darà errore anche se ETipiMacchine è un uint8_t: questo + // perchè abbiamo dichiarato l'enum come "enum class"! + WriteByteToFile(InputCarType); +} + ////////////////////////////////////////////////// // Classi e programmazione orientata agli oggetti ///////////////////////////////////////////////// @@ -296,13 +426,16 @@ public: // Questi sono chiamati quando un oggetto è rimosso o esce dalla visibilità. // Questo permette paradigmi potenti come il RAII // (vedi sotto) - // I distruttori devono essere virtual per permettere a classi di essere derivate da questa. + // I distruttori devono essere virtual per permettere a classi di essere + // derivate da questa; altrimenti, il distruttore della classe derivata + // non viene chiamato se l'oggetto viene distrutto tramite un riferimento alla + // classe da cui ha ereditato o tramite un puntatore. virtual ~Dog(); }; // Un punto e virgola deve seguire la definizione della funzione // Le funzioni membro di una classe sono generalmente implementate in files .cpp . -void Cane::Cane() +Cane::Cane() { std::cout << "Un cane è stato costruito\n"; } @@ -325,7 +458,7 @@ void Cane::print() const std::cout << "Il cane è " << nome << " e pesa " << peso << "kg\n"; } -void Cane::~Cane() +Cane::~Cane() { cout << "Ciao ciao " << nome << "\n"; } @@ -340,10 +473,12 @@ int main() { // Ereditarietà: -// Questa classe eredita tutto ciò che è public e protected dalla classe Cane +// Questa classe eredita tutto ciò che è public e protected dalla classe Cane, +// ma anche ciò che privato: tuttavia non potrà accedere direttamente a membri/metodi +// privati se non c'è un metodo pubblico o privato che permetta di farlo. class MioCane : public Cane { - void impostaProprietario(const std::string& proprietarioCane) + void impostaProprietario(const std::string& proprietarioCane); // Sovrascrivi il comportamento della funzione print per tutti i MioCane. Vedi // http://it.wikipedia.org/wiki/Polimorfismo_%28informatica%29 @@ -447,6 +582,7 @@ int main () { // definire una classe o una funzione che prende un parametro di un dato tipo: template<class T> class Box { +public: // In questa classe, T può essere usato come qualsiasi tipo. void inserisci(const T&) { ... } }; @@ -519,19 +655,23 @@ printMessage<10>(); // Stampa "Impara il C++ più velocemente in soli 10 minuti // (vedi http://en.cppreference.com/w/cpp/error/exception) // ma ogni tipo può essere lanciato come eccezione #include <exception> +#include <stdexcept> // Tutte le eccezioni lanciate all'interno del blocco _try_ possono essere catturate dai successivi // handlers _catch_. try { // Non allocare eccezioni nello heap usando _new_. - throw std::exception("È avvenuto un problema"); + throw std::runtime_error("C'è stato un problema."); } + // Cattura le eccezioni come riferimenti const se sono oggetti catch (const std::exception& ex) { - std::cout << ex.what(); + std::cout << ex.what(); +} + // Cattura ogni eccezioni non catturata dal blocco _catch_ precedente -} catch (...) +catch (...) { std::cout << "Catturata un'eccezione sconosciuta"; throw; // Rilancia l'eccezione @@ -541,7 +681,7 @@ catch (const std::exception& ex) // RAII /////// -// RAII sta per Resource Allocation Is Initialization. +// RAII sta per "Resource Allocation Is Initialization". // Spesso viene considerato come il più potente paradigma in C++. // È un concetto semplice: un costruttore di un oggetto // acquisisce le risorse di tale oggetto ed il distruttore le rilascia. @@ -563,9 +703,9 @@ void faiQualcosaConUnFile(const char* nomefile) // Sfortunatamente, le cose vengono complicate dalla gestione degli errori. // Supponiamo che fopen fallisca, e che faiQualcosaConUnFile e // faiQualcosAltroConEsso ritornano codici d'errore se falliscono. -// (Le eccezioni sono la maniera preferita per gestire i fallimenti, -// ma alcuni programmatori, specialmente quelli con un passato in C, -// non sono d'accordo con l'utilità delle eccezioni). +// (Le eccezioni sono la maniera preferita per gestire i fallimenti, +// ma alcuni programmatori, specialmente quelli con un passato in C, +// non sono d'accordo con l'utilità delle eccezioni). // Adesso dobbiamo verificare che ogni chiamata per eventuali fallimenti e chiudere il gestore di file // se un problema è avvenuto. bool faiQualcosaConUnFile(const char* nomefile) @@ -615,7 +755,7 @@ void faiQualcosaConUnFile(const char* nomefile) { FILE* fh = fopen(nomefile, "r"); // Apre il file in modalità lettura if (fh == nullptr) - throw std::exception("Non è stato possibile aprire il file."). + throw std::runtime_error("Errore nell'apertura del file."); try { faiQualcosaConIlFile(fh); @@ -678,26 +818,29 @@ class Foo { virtual void bar(); }; class FooSub : public Foo { - virtual void bar(); // sovrascrive Foo::bar! + virtual void bar(); // Sovrascrive Foo::bar! }; // 0 == false == NULL (la maggior parte delle volte)! bool* pt = new bool; -*pt = 0; // Setta il valore puntato da 'pt' come falso. +*pt = 0; // Setta il valore puntato da 'pt' come falso. pt = 0; // Setta 'pt' al puntatore null. Entrambe le righe vengono compilate senza warnings. // nullptr dovrebbe risolvere alcune di quei problemi: int* pt2 = new int; -*pt2 = nullptr; // Non compila +*pt2 = nullptr; // Non compila pt2 = nullptr; // Setta pt2 a null. -// Ma in qualche modo il tipo 'bool' è una eccezione (questo è per rendere compilabile `if (ptr)`. -*pt = nullptr; // Questo compila, anche se '*pt' è un bool! +// C'è un'eccezione per i bool. +// Questo permette di testare un puntatore a null con if(!ptr), ma +// come conseguenza non puoi assegnare nullptr a un bool direttamente! +*pt = nullptr; // Questo compila, anche se '*pt' è un bool! // '=' != '=' != '='! -// Chiama Foo::Foo(const Foo&) o qualche variante del costruttore di copia. +// Chiama Foo::Foo(const Foo&) o qualche variante (vedi "move semantics") +// del costruttore di copia. Foo f2; Foo f1 = f2; @@ -711,6 +854,22 @@ Foo f1 = fooSub; Foo f1; f1 = f2; + +// Come deallocare realmente le risorse all'interno di un vettore: +class Foo { ... }; +vector<Foo> v; +for (int i = 0; i < 10; ++i) + v.push_back(Foo()); + +// La riga seguente riduce la dimensione di v a 0, ma il distruttore non +// viene chiamato e dunque le risorse non sono deallocate! +v.empty(); +v.push_back(Foo()); // Il nuovo valore viene copiato nel primo Foo che abbiamo inserito + +// Distrugge realmente tutti i valori dentro v. Vedi la sezione riguardante gli +// oggetti temporanei per capire come mai funziona così. +v.swap(vector<Foo>()); + ``` Letture consigliate: diff --git a/it-it/coffeescript-it.html.markdown b/it-it/coffeescript-it.html.markdown index 16eb9bd4..31973369 100644 --- a/it-it/coffeescript-it.html.markdown +++ b/it-it/coffeescript-it.html.markdown @@ -4,6 +4,8 @@ contributors: - ["Luca 'Kino' Maroni", "http://github.com/kino90"] - ["Tenor Biel", "http://github.com/L8D"] - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Tommaso Pifferi","http://github.com/neslinesli93"] filename: coffeescript-it.coffee lang: it-it --- @@ -59,34 +61,34 @@ matematica = quadrato: quadrato cubo: (x) -> x * quadrato x #=> var matematica = { -# "radice": Math.sqrt, -# "quadrato": quadrato, -# "cubo": function(x) { return x * quadrato(x); } -#} +# "radice": Math.sqrt, +# "quadrato": quadrato, +# "cubo": function(x) { return x * quadrato(x); } +# } # Splats: gara = (vincitore, partecipanti...) -> print vincitore, partecipanti #=>gara = function() { -# var partecipanti, vincitore; -# vincitore = arguments[0], partecipanti = 2 <= arguments.length ? __slice.call(arguments, 1) : []; -# return print(vincitore, partecipanti); -#}; +# var partecipanti, vincitore; +# vincitore = arguments[0], partecipanti = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(vincitore, partecipanti); +# }; # Esistenza: alert "Lo sapevo!" if elvis? #=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Lo sapevo!"); } # Comprensione degli Array: -cubi = (matematica.cubo num for num in lista) +cubi = (matematica.cubo num for num in lista) #=>cubi = (function() { -# var _i, _len, _results; -# _results = []; -# for (_i = 0, _len = lista.length; _i < _len; _i++) { -# num = lista[_i]; -# _results.push(matematica.cubo(num)); -# } -# return _results; +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = lista.length; _i < _len; _i++) { +# num = lista[_i]; +# _results.push(matematica.cubo(num)); +# } +# return _results; # })(); cibi = ['broccoli', 'spinaci', 'cioccolato'] diff --git a/it-it/elixir-it.html.markdown b/it-it/elixir-it.html.markdown index f5d0c172..60301b1a 100644 --- a/it-it/elixir-it.html.markdown +++ b/it-it/elixir-it.html.markdown @@ -4,6 +4,8 @@ contributors: - ["Luca 'Kino' Maroni", "https://github.com/kino90"] - ["Joao Marques", "http://github.com/mrshankly"] - ["Dzianis Dashkevich", "https://github.com/dskecse"] +translators: + - ["Tommaso Pifferi","http://github.com/neslinesli93"] filename: learnelixir-it.ex lang: it-it --- @@ -379,6 +381,12 @@ spawn(f) #=> #PID<0.40.0> # Per passare messaggi si usa l'operatore `send`. # Perché tutto questo sia utile dobbiamo essere capaci di ricevere messaggi, # oltre ad inviarli. Questo è realizzabile con `receive`: + +# Il blocco `receive do` viene usato per mettersi in ascolto di messaggi +# ed elaborarli quando vengono ricevuti. Un blocco `receive do` elabora +# un solo messaggio ricevuto: per fare elaborazione multipla di messaggi, +# una funzione con un blocco `receive do` al suo intero dovrà chiamare +# ricorsivamente sé stessa per entrare di nuovo nel blocco `receive do`. defmodule Geometria do def calcolo_area do receive do @@ -394,6 +402,8 @@ end # Compila il modulo e crea un processo che esegue `calcolo_area` nella shell pid = spawn(fn -> Geometria.calcolo_area() end) #=> #PID<0.40.0> +# Alternativamente +pid = spawn(Geometria, :calcolo_area, []) # Invia un messaggio a `pid` che farà match su un pattern nel blocco in receive send pid, {:rettangolo, 2, 3} diff --git a/it-it/java-it.html.markdown b/it-it/java-it.html.markdown index 6eabd61f..54602cff 100644 --- a/it-it/java-it.html.markdown +++ b/it-it/java-it.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Madison Dickson", "http://github.com/mix3d"] translators: - ["Ivan Sala","http://github.com/slavni96"] + - ["Tommaso Pifferi","http://github.com/neslinesli93"] lang: it-it --- @@ -31,9 +32,9 @@ import java.security.*; // Ogni file .java contiene una classe pubblica, con lo stesso nome del file public class LearnJava { - // Un programma deve avere un metodo main come punto di partenza - // Ma si possono creare anche file senza main, che però per essere usati - // devono essere richiamati da altri file. + // Un programma deve avere un metodo main come punto di partenza. + // Tuttavia si possono creare anche file senza main, che però + // per essere usati devono essere richiamati da altri file. public static void main (String[] args) { // Per stampare a schermo si usa System.out.println @@ -47,88 +48,157 @@ public class LearnJava { System.out.print("Ciao "); System.out.print("Mondo "); + // Per stampare del testo formattato, si puo' usare System.out.printf + System.out.printf("pi greco = %.5f", Math.PI); // => pi greco = 3.14159 /////////////////////////////////////// - // Tipi e Variabili + // Variabili /////////////////////////////////////// - // Si dichiara una variabile usando <tipo> <nome> - // Byte - variabile intera da 8 bit con segno + + /* + * Dichiarazione delle Variabili + */ + // Per dichiarare una variabile basta fare <tipoDato> <nomeVariabile> + int fooInt; + // Per dichiarare piu' di una variabile dello lo stesso tipo si usa: + // <tipoDato> <nomeVariabile1>, <nomeVariabile2>, <nomeVariabile3> + int fooInt1, fooInt2, fooInt3; + + /* + * Inizializzazione delle Variabili + */ + + // Per inizializzare una variabile si usa + // <tipoDato> <nomeVariabile> = <valore> + int fooInt = 1; + // Per inizializzare piu' di una variabile dello lo stesso tipo + // si usa <tipoDato> <nomeVariabile1>, <nomeVariabile2>, <nomeVariabile3> = <valore> + int fooInt1, fooInt2, fooInt3; + fooInt1 = fooInt2 = fooInt3 = 1; + + /* + * Tipi di Variabili + */ + // Byte - intero con segno a 8 bit (in complemento a 2) // (-128 <= byte <= 127) byte fooByte = 100; - // Short - variabile intera da 18 bit con segno + // Short - intero con segno a 16 bit (in complemento a 2) // (-32,768 <= short <= 32,767) short fooShort = 10000; - // Integer - variabile intera da 32 bit con segno + // Integer - intero con segno a 32 bit (in complemento a 2) // (-2,147,483,648 <= int <= 2,147,483,647) int fooInt = 1; - // Long - variabile da 64 bit intera con segno + // Long - intero con segno a 64 bit (in complemento a 2) // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) long fooLong = 100000L; - // L viene usato per specificare che il valore dalla variabile - // e' di tipo "Long", qualsiasi variabile che non viene contrassegnata - // e' trattata di base come un intero. + // L viene usato per indicare che il valore e' di tipo Long; + // altrimenti il valore viene considerato come intero. - // Nota: Java non dispone di variabili senza segno + // Nota: Java non dispone di interi senza segno. - // Float - variabile piu' precisa, con virgola [numeri reali] - // di grandezza 32 bit + // Float - Numero in virgola mobile a 32 bit con precisione singola (IEEE 754) + // 2^-149 <= float <= (2-2^-23) * 2^127 float fooFloat = 234.5f; - // f e' usato per specificare che la variabile e'' di tipo "float" - // altrimenti di default viene trattata come un "dobule" + // f o F indicano the la variabile e' di tipo float; + // altrimenti il valore viene considerato come double. - // Double - ancora piu' precisione la si puo' ottenere con una variabile - // Double, con granzezza di 64 bit. + // Double - Numero in virgola mobile a 64 bit con precisione doppia (IEEE 754) + // 2^-1074 <= x <= (2-2^-52) * 2^1023 double fooDouble = 123.4; - // Boolean - vero & falso + // Boolean - Puo' assumere il valore vero (true) o falso (false) boolean fooBoolean = true; boolean barBoolean = false; - // Char - un singolo carattere con grandezza 16 bit + // Char - Un singolo carattere Unicode a 16-bit char fooChar = 'A'; - // final - Costanti, non possono essere riassegnate ad un altro oggetto - final int ORE_LAVORATIVE_DI_UNA_SETTIMANA = 9001; - - // String - Stringhe, array di caratteri - String fooString = "Ecco una stringa!"; - - // \n e' un carattere speciale che permette di andare a capo. - String barString = "Andare a capo?\nNessun problema!"; - // \t e' un carattere speciale che permette di aggiungere un 'Tab' - String bazString = "Vuoi inserire tab?\tNessun problema"; + // Le variabili precedute da final possono essere inizializzate una volta sola, + final int HOURS_I_WORK_PER_WEEK = 9001; + // pero' e' possibile dichiararle e poi inizializzarle in un secondo momento. + final double E; + E = 2.71828; + + + // BigInteger - Interi a precisione arbitraria + // + // BigInteger e' un tipo di dato che permette ai programmatori di + // gestire interi piu' grandi di 64 bit. Internamente, le variabili + // di tipo BigInteger vengono memorizzate come un vettore di byte e + // vengono manipolate usando funzioni dentro la classe BigInteger. + // + // Una variabile di tipo BigInteger puo' essere inizializzata usando + // un array di byte oppure una stringa. + + BigInteger fooBigInteger = new BigDecimal(fooByteArray); + + // BigDecimal - Numero con segno, immutabile, a precisione arbitraria + // + // Una variabile di tipo BigDecimal e' composta da due parti: un intero + // a precisione arbitraria detto 'non scalato', e un intero a 32 bit + // che rappresenta la 'scala', ovvero la potenza di 10 con cui + // moltiplicare l'intero non scalato. + // + // I BigDecimal permettono un controllo completo sull'arrotondamento + // dei numeri. Essi sono molto usati in ambito finanziario, nella + // gestione delle valute, e in ogni altro posto in cui serve + // precisione esatta. + // + // Le variabili di tipo BigDecimal possono essere inizializzate con un + // int, long, double o String, oppure con un intero non scalato + // (di tipo BigInteger) e una scala (int). + + BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); + + + + // Stringhe + String fooString = "Questa e' la mia stringa!"; + + // \n e' un carattere di escape che rappresenta l'andare a capo + String barString = "Stampare su una nuova riga?\nNessun problema!"; + // \t e' un carattere di escape che aggiunge un tab + String bazString = "Vuoi aggiungere un tab?\tNessun problema!"; System.out.println(fooString); System.out.println(barString); System.out.println(bazString); - // Vettori [array] - //La lunghezza del vettore deve essere decisa quando viene istanziato - //Si puo' dichiarare come segue: - //<tipodato> [] <nomevariabile> = new <tipodato>[<grandezza vettore>]; - //<tipodato> <nomevariabile>[] = new <tipodato>[<grandezza vettore>]; - int [] intArray = new int[10]; - String [] stringArray = new String[1]; - boolean boolArray [] = new boolean[100]; - - // Un altro modo per dichiarare & inizializzare un vettore - int [] y = {9000, 1000, 1337}; - String nomi [] = {"Andrea", "Bob", "Pippo", "Susan"}; + // Vettori + // La dimensione di un array deve essere decisa in fase di + // istanziazione. Per dichiarare un array si puo' fare in due modi: + // <tipoDato>[] <nomeVariabile> = new <tipoDato>[<dimensioneArray>]; + // <tipoDato> <nomeVariabile>[] = new <tipoDato>[<dimensioneArray>]; + int[] intArray = new int[10]; + String[] stringArray = new String[1]; + boolean boolArray[] = new boolean[100]; + + // Un altro modo per dichiarare ed insieme inizializzare un vettore. + int[] y = {9000, 1000, 1337}; + String names[] = {"Gianni", "Anna", "Luca", "Cristina"}; boolean bools[] = new boolean[] {true, false, false}; - - // I vettori vengono indicizzati a parire dallo 0 + + // Per accedere ad un elemento di un vettore System.out.println("intArray @ 0: " + intArray[0]); - // e' possibile un accesso diretto ad un elemento + // I vettori non sono immutabili (ma la loro dimensione si!) + // e gli indici partono da 0. intArray[1] = 1; System.out.println("intArray @ 1: " + intArray[1]); // => 1 - // Altro da vedere: - // Liste di array - come i vettori ma piu' funzionali - // e la loro grandezza puo' variare in corso di esecuzione - // Liste concatenate di memoria + // Ci sono altri tipo di dato interessanti. + // ArrayList - Simili ai vettori, pero' offrono altre funzionalita', + // e la loro dimensione puo' essere modificata. + // LinkedList - Si tratta di una lista linkata doppia, e come tale + // implementa tutte le operazioni del caso. + // Map - Un insieme di oggetti che fa corrispondere delle chiavi + // a dei valori. Non permette l'inserimento di chiavi uguali. + // HashMap - Questa classe usa una tabella di hash per implementare + // l'interfaccia di tipo Map. Questo permette di effettuare + // operazioni basilari, come inserimento e cancellazione, + // in tempo costante anche su insiemi molto grandi. /////////////////////////////////////// // Operatori diff --git a/it-it/json-it.html.markdown b/it-it/json-it.html.markdown index 0c401753..379bad73 100644 --- a/it-it/json-it.html.markdown +++ b/it-it/json-it.html.markdown @@ -1,29 +1,36 @@ --- - language: json contributors: - - ["Anna Harren", "https://github.com/iirelu"] - - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] translators: - ["Robert Margelli", "http://github.com/sinkswim/"] + - ["Christian Grasso", "http://chris54721.net"] lang: it-it - --- -Dato che JSON è un formato per lo scambio di dati estremamente semplice, questo sarà con molta probabilità -il più semplice Learn X in Y Minutes. +JSON è un formato per l'interscambio di dati estremamente semplice, per cui questo sarà +con molta probabilità il più semplice Learn X in Y Minutes. Nella sua forma più pura JSON non ha commenti, ma molti parser accettano commenti in stile C (//, /\* \*/). Per lo scopo prefissato, tuttavia, tutto sarà 100% JSON valido. Fortunatamente, si spiega da sè. +I tipi supportati da JSON comprendono: numeri, stringhe, boolean, array, oggetti e null. +I browser supportati sono: Firefox (Mozilla) 3.5+, Internet Explorer 8+, Google Chrome, +Opera 10+, Safari 4+. +I file JSON sono salvati nel formato ".json". Il MIME type per documenti JSON è +"application/json". Gli svantaggi del JSON includono l'assenza di una definizione dei tipi +e di una sorta di [DTD](https://it.wikipedia.org/wiki/Document_Type_Definition). + ```json { "chiave": "valore", "chiavi": "devono sempre essere racchiuse tra doppi apici", "numeri": 0, - "stringhe": "Ciaø, møndø. Tutti gli unicode sono permessi, assieme con l \"escaping\".", + "stringhe": "Ciaø, møndø. Tutti i caratteri Unicode sono permessi, insieme all'\"escaping\".", "ha booleani?": true, "il nulla": null, @@ -52,8 +59,8 @@ commenti in stile C (//, /\* \*/). Per lo scopo prefissato, tuttavia, tutto sar ], "stile alternativo": { - "commento": "Guarda quà!" - , "posizione della virgola": "non conta - fintantochè è prima del valore, allora è valida" + "commento": "Guarda qua!" + , "posizione della virgola": "non conta - se è prima della chiave successiva, allora è valida" , "un altro commento": "che bello" }, diff --git a/java.html.markdown b/java.html.markdown index 35ec57d8..aae64ccf 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 --- @@ -137,7 +138,7 @@ 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). @@ -184,8 +185,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 @@ -250,7 +255,7 @@ public class LearnJava { // If statements are c-like int j = 10; - if (j == 10){ + if (j == 10) { System.out.println("I get printed"); } else if (j > 10) { System.out.println("I don't"); @@ -285,7 +290,18 @@ public class LearnJava { // Iterated 10 times, fooFor 0->9 } System.out.println("fooFor Value: " + fooFor); - + + // Nested For Loop Exit with Label + outer: + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // breaks out of outer loop instead of only the inner one + } + } + } + // For Each Loop // The for loop is also able to iterate over arrays as well as objects // that implement the Iterable interface. @@ -320,7 +336,7 @@ public class LearnJava { // Starting in Java 7 and above, switching Strings works like this: String myAnswer = "maybe"; - switch(myAnswer){ + switch(myAnswer) { case "yes": System.out.println("You answered yes."); break; @@ -434,6 +450,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() { diff --git a/javascript.html.markdown b/javascript.html.markdown index 6ea0b0bb..cce488e1 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -16,12 +16,8 @@ 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). - ```js -// Comments are like C. Single-line comments start with two slashes, +// Comments are like C's. Single-line comments start with two slashes, /* and multiline comments start with slash-star and end with star-slash */ @@ -54,6 +50,11 @@ doStuff() // Including uneven division. 5 / 2; // = 2.5 +// And modulo division. +10 % 2; // = 0 +30 % 4; // = 2 +18.5 % 7; // = 4.5 + // Bitwise operations also work; when you perform a bitwise operation your float // is converted to a signed int *up to* 32 bits. 1 << 2; // = 4 @@ -104,7 +105,7 @@ null == undefined; // = true // ...unless you use === "5" === 5; // = false -null === undefined; // = false +null === undefined; // = false // ...which can result in some weird behaviour... 13 + !0; // 14 @@ -144,6 +145,10 @@ someOtherVar = 10; // Variables declared without being assigned to are set to undefined. var someThirdVar; // = undefined +// if you wan't 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 @@ -220,15 +225,15 @@ for (var i = 0; i < 5; i++){ //The For/In statement loops iterates over every property across the entire prototype chain var description = ""; -var person = {fname:"Paul", lname:"Ken", age:18}; +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, +//If only want to consider properties attached to the object itself, //and not its prototypes use hasOwnProperty() check var description = ""; -var person = {fname:"Paul", lname:"Ken", age:18}; +var person = {fname:"Paul", lname:"Ken", age:18}; for (var x in person){ if (person.hasOwnProperty(x)){ description += person[x] + " "; @@ -282,12 +287,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 @@ -301,6 +303,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(){ @@ -319,7 +327,7 @@ i; // = 5 - not undefined as you'd expect in a block-scoped language // scope. (function(){ var temporary = 5; - // We can access the global scope by assiging to the "global object", which + // We can access the global scope by assigning to the "global object", which // in a web browser is always `window`. The global object may have a // different name in non-browser environments such as Node.js. window.permanent = 10; @@ -413,7 +421,7 @@ var doubler = product.bind(this, 2); doubler(8); // = 16 // When you call a function with the `new` keyword, a new object is created, and -// made available to the function via the this keyword. Functions designed to be +// made available to the function via the `this` keyword. Functions designed to be // called like that are called constructors. var MyConstructor = function(){ @@ -522,28 +530,32 @@ 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. -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 Garden][5] is an in-depth guide of all the counter-intuitive parts +of the language. -[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: The Definitive Guide][6] is a classic guide and reference book. -[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 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 e180e622..31231a70 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -6,6 +6,8 @@ contributors: - ["Sricharan Chiruvolu", "http://sricharan.xyz"] filename: learn-latex.tex --- + +```tex % All comment lines start with % % There are no multi-line comments @@ -104,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! @@ -225,6 +230,7 @@ That's all for now! % end the document \end{document} ``` + ## More on LaTeX * The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) 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/matlab.html.markdown b/matlab.html.markdown index 0cbc6f57..4d97834c 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. @@ -261,7 +262,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 +330,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 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/nl-nl/yaml-nl.html.markdown b/nl-nl/yaml-nl.html.markdown new file mode 100644 index 00000000..a4a9d5fc --- /dev/null +++ b/nl-nl/yaml-nl.html.markdown @@ -0,0 +1,139 @@ +--- +language: yaml +filename: learnyaml-nl.yaml +contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +translators: + - ["Niels van Velzen", "https://nielsvanvelzen.me"] +lang: nl-nl +--- + +YAML is een data serialisatie taal ontworpen om snel te kunnen worden begrepen door mensen. + +Het is een strikte superset van JSON en bevat nieuwe regels en een stricte manier van inspringen, zoals bij Python. In tegenstelling tot Python kan je alleen geen tab tekens gebruiken. + +```yaml +# Commentaar in YAML ziet er zo uit + +################ +# SCALAR TYPES # +################ + +# Ons hoofd object (Wat in het hele document gebruikt wordt) is een map, +# dit staat gelijk aan een dictionary, hash of object in andere talen. +sleutel: waarde +nog_een_sleutel: Een andere waarde +nummer_waarde: 100 +wetenschappelijke_waarde: 1e+12 +boolean_waarde: true +null_waarde: null +sleutel met spaties: waarde +# Merk op dat strings niet verplicht in quotes moeten, maar dit kan wel. +quote_waarde: "Een string in quotes" +"Ook sleutels kunnen in quotes": "Dit is bijvoorbeeld handig als je een dubbelepunt wilt gebruiken in je key" + +# Tekst over meerdere lijnen kan je schrijven als een 'letterlijk blok' (met |) +# Of een 'gevouwen blok' (met >) +letterlijk_blok: | + Dit hele blok met tekst is de waarde van de 'letterlijk_blok' sleutel, + met nieuwe lijnen behouden. + + Het blok blijft door gaan tot het geeindigd wordt door korter te inspringen. + + Lijnen die groter zijn ingesprongen behouden dit. +gevouwen_stijl: > + Dit blok met tekst zal de waarde zijn van 'gevouwen_stijl', + maar deze keer zullen alle nieuwe lijnen worden vervangen met een spatie. + + Lege lijnen, zoals hierboven, zullen worden vertaald naar een nieuwe lijn. + + Meer ingesprongen lijnen zullen hun nieuwe lijnen ook behouden, + deze tekst zal over 2 lijnen te zien zijn. + +#################### +# COLLECTION TYPES # +#################### + +# Nesten wordt bereikt met inspringen. +geneste_map: + sleutel: waarde + andere_sleutel: andere waarde + andere_geneste_map: + hallo: wereld + +# In een map is een sleutel niet verplicht om een string te gebruiken +0.25: een float als sleutel + +# Sleutels kunnen ook meerdere lijnen gebruiken met behulp van het vraagteken +? | + Dit is een sleutel + met meerdere lijnen +: en dit is de waarde + +# YAML staat ook collection types toe in sleutels, maar veel programmeertalen +# zullen hierover klagen. + +# Sequences (gelijk aan lijsten of arrays) zien er zo uit: +een_sequence: + - Item 1 + - Item 2 + - 0.5 # sequences kunnen meerdere type waardes bevatten. + - Item 4 + - sleutel: waarde + andere_sleutel: andere waarde + - + - Dit is een sequence + - in een andere sequence + +# Doordat YAML een superset van JSON is kan je ook JSON-stijl mappen en +# sequences maken: +json_map: {"sleutel": "waarde"} +json_seq: [3, 2, 1, "takeoff"] + +####################### +# EXTRA YAML FUNCTIES # +####################### + +# YAML heeft ook een handige functie genaamd 'anchors' (ankers), deze laten je +# makkelijk de waarde van ergens anders in je document kopieëren. Beide sleutels +# krijgen dezelfde waarde: +geankert_content: &anker_naam Deze string zal verschijnen als waarde voor de twee sleutels +andere_anker: *anker_naam + +# YAML heeft ook tags, deze gebruik je om een expliciet type te verklaren +expliciete_string: !!str 0.5 +# Sommige parsers gebruiken taal specifieke tags, zoals deze voor Python's +# complexe nummer type: +python_complex_nummer: !!python/complex 1+2j + +#################### +# EXTRA YAML TYPES # +#################### + +# Strings en nummer zijn niet de enige types die YAML begrijpt. +# ISO opgemaakte datum en datumtijd notaties werken ook: +datumtijd: 2001-12-15T02:59:43.1Z +datumtijd_met_spaties: 2001-12-14 21:59:43.10 -5 +datum: 2002-12-14 + +# De !!binary tag geeft aan dat de string een base64-gecodeerde +# binary blob is. +gif_bestand: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + +# YAML heeft ook een set type, dat ziet er zo uit: +set: + ? item1 + ? item2 + ? item3 + +# Zoals in Python zijn sets gewoon mappen met null waardes; +# bovenstaand is gelijk aan: +set2: + item1: null + item2: null + item3: null +``` diff --git a/objective-c.html.markdown b/objective-c.html.markdown index cf6bf780..f130ea0c 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -148,7 +148,13 @@ int main (int argc, const char * argv[]) [mutableDictionary setObject:@"value1" forKey:@"key1"]; [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) @@ -682,7 +688,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/ocaml.html.markdown b/ocaml.html.markdown index 02435e4d..8faab297 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -196,7 +196,7 @@ let (~/) x = 1.0 /. x ;; ~/4.0 (* = 0.25 *) -(*** Built-in datastructures ***) +(*** Built-in data structures ***) (* Lists are enclosed in square brackets, items are separated by semicolons. *) @@ -341,10 +341,10 @@ let say x = say (Cat "Fluffy") ;; (* "Fluffy says meow". *) -(** Traversing datastructures with pattern matching **) +(** Traversing data structures with pattern matching **) (* Recursive types can be traversed with pattern matching easily. - Let's see how we can traverse a datastructure of the built-in list type. + Let's see how we can traverse a data structure of the built-in list type. Even though the built-in cons ("::") looks like an infix operator, it's actually a type constructor and can be matched like any other. *) let rec sum_list l = diff --git a/perl6.html.markdown b/perl6.html.markdown index 0f015b45..45b15f05 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -11,9 +11,7 @@ Perl 6 is a highly capable, feature-rich programming language made for at least the next hundred years. The primary Perl 6 compiler is called [Rakudo](http://rakudo.org), which runs on -the JVM and [the MoarVM](http://moarvm.com) and -[prior to March 2015](http://pmthium.com/2015/02/suspending-rakudo-parrot/), -[the Parrot VM](http://parrot.org/). +the JVM and [the MoarVM](http://moarvm.com). Meta-note : the triple pound signs are here to denote headlines, double paragraphs, and single notes. diff --git a/php.html.markdown b/php.html.markdown index 39ec5aef..0504ced2 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -12,7 +12,7 @@ This document describes PHP 5+. <?php // PHP code must be enclosed with <?php tags // If your php file only contains PHP code, it is best practice -// to omit the php closing tag. +// to omit the php closing tag to prevent accidental output. // Two forward slashes start a one-line comment. @@ -103,6 +103,9 @@ END; // String concatenation is done with . echo 'This string ' . 'is concatenated'; +// Strings can be passed in as parameters to echo +echo 'Multiple', 'Parameters', 'Valid'; // Returns 'MultipleParametersValid' + /******************************** * Constants @@ -115,8 +118,10 @@ echo 'This string ' . 'is concatenated'; // 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' + /******************************** @@ -141,6 +146,8 @@ echo $array[0]; // => "One" // Add an element to the end of an array $array[] = 'Four'; +// or +array_push($array, 'Five'); // Remove element from array unset($array[3]); @@ -155,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'; @@ -215,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; @@ -379,7 +390,7 @@ for ($i = 0; $i < 5; $i++) { // Define a function with "function": function my_function () { - return 'Hello'; + return 'Hello'; } echo my_function(); // => "Hello" @@ -388,8 +399,8 @@ echo my_function(); // => "Hello" // number of letters, numbers, or underscores. function add ($x, $y = 1) { // $y is optional and defaults to 1 - $result = $x + $y; - return $result; + $result = $x + $y; + return $result; } echo add(4); // => 5 @@ -400,21 +411,21 @@ echo add(4, 2); // => 6 // Since PHP 5.3 you can declare anonymous functions; $inc = function ($x) { - return $x + 1; + return $x + 1; }; echo $inc(2); // => 3 function foo ($x, $y, $z) { - echo "$x - $y - $z"; + echo "$x - $y - $z"; } // Functions can return functions function bar ($x, $y) { - // Use 'use' to bring in outside variables - return function ($z) use ($x, $y) { - foo($x, $y, $z); - }; + // Use 'use' to bring in outside variables + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; } $bar = bar('A', 'B'); @@ -426,6 +437,31 @@ echo $function_name(1, 2); // => 3 // Useful for programatically determining which function to run. // Or, use call_user_func(callable $callback [, $parameter [, ... ]]); + +// You can get the all the parameters passed to a function +function parameters() { + $numargs = func_num_args(); + if ($numargs > 0) { + echo func_get_arg(0) . ' | '; + } + $args_array = func_get_args(); + foreach ($args_array as $key => $arg) { + echo $key . ' - ' . $arg . ' | '; + } +} + +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 */ @@ -693,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 * @@ -702,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 } @@ -719,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/pl-pl/python-pl.html.markdown b/pl-pl/python-pl.html.markdown index c3e8287a..ade1d7ca 100644 --- a/pl-pl/python-pl.html.markdown +++ b/pl-pl/python-pl.html.markdown @@ -125,7 +125,7 @@ not False # => True # Ta metoda jest obecnie polecana: "{0} są {1}".format("napisy", "fajne") # Jeśli nie chce ci się liczyć użyj słów kluczowych. -"{imie} chce zjeść {jadlo}".format(imie="Bob", jasno="lasagne") +"{imie} chce zjeść {jadlo}".format(imie="Bob", jadlo="makaron") # None jest obiektem None # => None @@ -158,7 +158,7 @@ print "Jestem Python. Miło poznać!" print("Ja też jestem Python! ") # Nie trzeba deklarować zmiennych przed przypisaniem. -jakas_zmienna = 5 # Konwencja mówi: używaj małych znaków i podłogi _ +jakas_zmienna = 5 # Konwencja mówi: używaj małych znaków i kładki _ jakas_zmienna # => 5 # Próba dostępu do niezadeklarowanej zmiennej da błąd. diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown new file mode 100644 index 00000000..ed6f6c4c --- /dev/null +++ b/pt-br/css-pt.html.markdown @@ -0,0 +1,257 @@ +--- +language: css +filename: learncss-pt.css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Geoffrey Liu", "https://github.com/g-liu"] + - ["Connor Shea", "https://github.com/connorshea"] + - ["Deepanshu Utkarsh", "https://github.com/duci9y"] +translators: + - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"] +lang: pt-br +--- + +Nos primeiros dias da web não havia elementos visuais, apenas texto puro. Mas com maior desenvolvimento de navegadores da web, páginas web totalmente visuais também se tornou comum. + +CSS ajuda a manter a separação entre o conteúdo (HTML) e o look-and-feel de uma página web. + +CSS permite atingir diferentes elementos em uma página HTML e atribuir diferentes propriedades visuais para eles. + +Este guia foi escrito para CSS2, embora CSS3 está rapidamente se tornando popular. + +**NOTA:** Porque CSS produz resultados visuais, a fim de aprender, você precisa tentar de tudo em um playground CSS como [dabblet](http://dabblet.com/). +O foco principal deste artigo é sobre a sintaxe e algumas dicas gerais. + +```css +/* Comentários aparecem dentro do slash-asterisk, tal como esta linha! + não há "comentários de uma linha"; este é o único estilo de comentário * / + +/* #################### + ## SELETORES + #################### */ + +/* O seletor é usado para direcionar um elemento em uma página. + seletor { propriedade: valor; / * Mais propriedades ... * / } + +/* +Abaixo um elemento de exemplo: + +<div class='class1 class2' id='anID' attr='value' otherAttr='pt-br foo bar' /> +*/ + +/* Você pode direciona-lo usando uma das suas classes CSS */ +.class1 { } + +/* ou ambas as classes! */ +.class1.class2 { } + +/* ou o seu nome */ +div { } + +/* ou o seu id */ +#anID { } + +/* ou utilizando o fator de que tem um atributo!*/ +[attr] { font-size:smaller; } + +/* ou que o atributo tem um valor específico */ +[attr='value'] { font-size:smaller; } + +/* começa com um valor (CSS 3) */ +[attr^='val'] { font-size:smaller; } + +/* ou terminando com um valor (CSS 3) */ +[attr$='ue'] { font-size:smaller; } + + +/* Ou contém um valor em uma lista separada por espaços */ +[otherAttr ~ = 'foo'] {} +[otherAttr ~ = 'bar'] {} + +/* Ou contém um valor em uma lista separada por hífen, ou seja, "-" (U + 002D) */ +[otherAttr | = 'en'] {font-size: smaller; } + + +/* Você pode concatenar diferentes seletores para criar um seletor mais estreito. Não + colocar espaços entre eles. */ +classe div.some [attr $ = 'ue'] {} + +/* Você pode selecionar um elemento que é filho de outro elemento */ +div.some-parent> .class-name {} + +/* Ou um descendente de um outro elemento. As crianças são os descendentes diretos de + seu elemento pai, apenas um nível abaixo da árvore. Pode ser qualquer descendentes + nivelar por baixo da árvore. */ +div.some-parent class-name {} + +/* Atenção: o mesmo seletor sem espaço tem um outro significado. + Você consegue adivinhar o que? */ +div.some-parent.class-name {} + +/* Você também pode selecionar um elemento com base em seu irmão adjacente */ +.i am just-antes + .Este elemento {} + +/* Ou qualquer irmão que o precede */ +.i am-qualquer-elemento antes ~ .Este elemento {} + +/* Existem alguns selectores chamado pseudo classes que podem ser usados para selecionar um + elemento quando ele está em um determinado estado */ + +/* Por exemplo, quando o cursor passa sobre um elemento */ +seletor:hover {} + +/* Ou um link foi visitado */ +seletor:visited {} + +/* Ou não tenha sido visitado */ +seletor:link {} + +/* Ou um elemento em foco */ +seletor:focus {} + +/* Qualquer elemento que é o primeiro filho de seu pai */ +seletor:first-child {} + +/* Qualquer elemento que é o último filho de seu pai */ +seletor:last-child {} + +/* Assim como pseudo classes, pseudo elementos permitem que você estilo certas partes de um documento */ + +/* Corresponde a um primeiro filho virtual do elemento selecionado */ +seletor::before {} + +/* Corresponde a um último filho virtual do elemento selecionado */ +seletor::after {} + +/* Nos locais apropriados, um asterisco pode ser utilizado como um curinga para selecionar todos + elemento */ +* {} /* */ Todos os elementos +.parent * {} /* */ todos os descendentes +.parent> * {} /* */ todas as crianças + +/* #################### + ## PROPRIEDADES + #################### */ + +seletor { + + /* Unidades de comprimento pode ser absoluta ou relativa. */ + + /* Unidades relativas */ + width: 50%; /* Percentagem de largura elemento pai */ + font-size: 2em; /* Múltiplos de font-size original de elemento */ + font-size: 2rem; /* Ou do elemento raiz font-size */ + font-size: 2vw; /* Múltiplos de 1% da largura da janela de exibição (CSS 3) */ + font-size: 2vh; /* Ou a sua altura */ + font-size: 2vmin; /* Qualquer um de VH ou um VW é menor */ + font-size: 2vmax; /* Ou superior */ + + /* Unidades absolutas */ + width: 200px; /* píxeis */ + font-size: 20pt; /* Pontos */ + width: 5cm; /* Centímetros */ + min-width: 50mm; /* Milímetros */ + max-width: 5 polegadas; /* Polegadas */ + + /* Cores */ + color: # F6E; /* Formato hexadecimal curto */ + color: # FF66EE; /* Formato hexadecimal longo */ + color: tomato; /* Uma cor nomeada */ + color: rgb (255, 255, 255); /* Como valores rgb */ + 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: 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 */ + + /* Imagens como fundos de elementos */ + background-image: url (/img-path/img.jpg); /* Citações dentro url () opcional */ + + /* Fontes */ + font-family: Arial; + /* Se o nome da família de fonte tem um espaço, deve ser citado */ + font-family: "Courier New"; + /* Se o primeiro não for encontrada, o navegador usa o próximo, e assim por diante */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; +} +``` + +## Uso + +Guardar uma folha de estilo CSS com a extensão `.css`. + +```xml +<!-- Você precisa incluir o arquivo css no da sua página <head>. Isto é o + método recomendado. Consulte http://stackoverflow.com/questions/8284365 --> +<link rel='stylesheet' type='text/css' href='path/to/style.css' /> + +<!-- Você também pode incluir alguns CSS inline na sua marcação. --> +<style> + a { color: purple; } +</style> + +<!-- Ou diretamente definir propriedades CSS no elemento. --> +<div style="border: 1px solid red;"> +</div> +``` + +## Precedência ou Cascata + +Um elemento pode ser alvo de vários seletores e pode ter um conjunto de propriedades em que mais de uma vez. Nestes casos, uma das regras tem precedência sobre os outros. Geralmente, uma regra em um seletor mais específico têm precedência sobre um menos específico, e uma regra que ocorre mais tarde na folha de estilo substitui uma anterior. + +Este processo é chamado de cascata, portanto, as Fichas de nome de estilo em cascata. + +Dado o seguinte CSS: + +```css +/* UMA */ +p.class1[attr="value"] + +/* B */ +p.class1 {} + +/* C */ +p.class2 {} + +/* D */ +p { } + +/* E */ +p { property: value !important; } +``` + +e a seguinte marcação: + +```xml +<p style='/*F*/ property:value;' class='class1 class2' attr='value' /> +``` + +A precedência de estilo é a seguinte. Lembre-se, a precedência é para cada **propriedade**, não para todo o bloco. + +* `E` tem a precedência mais alta por causa de uma palavra-chave`!important`. É recomendável que você evitar seu uso. +* `F` é a próxima, porque é um estilo interno. +* `A` é a próxima, porque é mais" específico "do que qualquer outra coisa. Tem 3 especificadores: O nome do elemento `p`, o seu `class1` classe, um atributo `attr='value'`. +* `C` está próximo, mesmo que ele tenha a mesma especificidade que `B`. Isso é porque ele aparece depois de `B`. +* `B` é o próximo. +* `D` é a última. + +## Compatibilidade + +A maior parte dos recursos do CSS 2 (e muitos em CSS 3) estão disponíveis em todos os navegadores e dispositivos. Mas é sempre boa prática para verificar antes de usar um novo recurso. + +## Recursos + +* Para executar uma verificação de compatibilidade rápida, [CanIUse](http://caniuse.com). +* CSS Playground [Dabblet](http://dabblet.com/). +* [Documentação CSS Mozilla Developer Rede](https://developer.mozilla.org/en-US/docs/Web/CSS) +* [Codrops 'Referência CSS](http://tympanus.net/codrops/css_reference/) + +## Leitura adicional + +* [Entendendo Estilo Precedência em CSS: Especificidade, Herança, eo Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecionando elementos usando atributos](https://css-tricks.com/almanac/selectors/a/attribute/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - O empilhamento context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) e [menos](http://lesscss.org/) para CSS pré-processamento +* [CSS-Tricks](https://css-tricks.com) diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown index fc63b126..e4f10a61 100644 --- a/pt-br/json-pt.html.markdown +++ b/pt-br/json-pt.html.markdown @@ -35,7 +35,7 @@ tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si. "array": [0, 1, 2, 3, "Arrays podem ter qualquer coisa em si.", 5], "outro objeto": { - "ccomentário": "Estas coisas podem ser aninhadas, muito úteis." + "comentário": "Estas coisas podem ser aninhadas, muito úteis." } }, 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 new file mode 100644 index 00000000..105896b2 --- /dev/null +++ b/pt-br/sass-pt.html.markdown @@ -0,0 +1,477 @@ +--- +language: sass +filename: learnsass-pt.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] + - ["Sean Corrales", "https://github.com/droidenator"] +translators: + - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"] +lang: pt-br +--- + +Sass é uma linguagem de extensão CSS que adiciona recursos, como variáveis, aninhamento, mixins e muito mais. +Sass (e outros pré-processadores, como [Less](http://lesscss.org/)) ajudam os desenvolvedores a escrever código de fácil manutenção e DRY (Do not Repeat Yourself). + +Sass tem duas opções de sintaxe diferentes para escolher. SCSS, que tem a mesma sintaxe de CSS, mas com os recursos adicionais de Sass. Ou Sass (a sintaxe original), que usa o recuo, em vez de chaves e ponto e vírgula. +Este tutorial é escrito usando SCSS. + +Se você já está familiarizado com CSS3, você será capaz de pegar Sass de forma relativamente rápida. Ele não fornece quaisquer novas opções de estilo, mas sim as ferramentas para escrever sua CSS de forma mais eficiente e fazer a manutenção mais fácilmente. + +```scss + + +// Comentários de linha única são removidos quando Sass é compilado para CSS. + +/* Comentários multi-line são preservados. */ + + + +/*Variáveis +==============================*/ + + + +/* É possível armazenar um valor CSS (tais como a cor) de uma variável. +Use o símbolo "$" para criar uma variável. */ + +$primary-color: #A3A4FF; +$secondary-color: #51527F; +$body-font: 'Roboto', sans-serif; + +/* Você pode usar as variáveis em toda a sua folha de estilo. +Agora, se você quer mudar a cor, você só tem que fazer a mudança uma vez. */ + +body { + background-color: $primary-color; + color: $secondary-color; + font-family: $body-font; +} + +/* Quando compilar ficaria assim: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/ * Este é muito mais fácil de manter do que ter de mudar a cor +cada vez que aparece em toda a sua folha de estilo. * / + + + + +/*Mixins +==============================*/ + + + +/* Se você achar que você está escrevendo o mesmo código para mais de um +elemento, você pode querer armazenar esse código em um mixin. + +Use a diretiva '@mixin', além de um nome para o seu mixin. */ + +@mixin center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Você pode usar o mixin com '@include' e o nome mixin. */ + +div { + @include center; + background-color: $primary-color; +} + +/* Apoś compilar ficaria assim: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + + +/* Você pode usar mixins para criar uma propriedade estenográfica. */ + +@mixin size($width, $height) { + width: $width; + height: $height; +} + +/* O que você pode invocar passando argumentos de largura e altura. */ + +.rectangle { + @include size(100px, 60px); +} + +.square { + @include size(40px, 40px); +} + +/* Isso compilado ficará assim: */ +.rectangle { + width: 100px; + height: 60px; +} + +.square { + width: 40px; + height: 40px; +} + + + +/*Funções +==============================*/ + + + +/* Sass fornece funções que podem ser utilizados para realizar uma variedade de + tarefas. Considere o seguinte */ + +/* Funções pode ser chamado usando seu nome e passando o + argumentos necessários */ +body { + width: round(10.25px); +} + +.footer { + background-color: fade_out(#000000, 0.25) +} + +/* Compiles to: */ + +body { + width: 10px; +} + +.footer { + 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 + lógica que pode ser usado em todo o seu código Sass. Os exemplos + seção Operadores Math 'são candidatos ideais para se tornar um reutilizável + função. */ + +/* Esta função terá um tamanho de destino eo tamanho do pai e calcular + e voltar a percentagem */ + +@function calculate-percentage($target-size, $parent-size) { + @return $target-size / $parent-size * 100%; +} + +$main-content: calculate-percentage(600px, 960px); + +.main-content { + width: $main-content; +} + +.sidebar { + width: calculate-percentage(300px, 960px); +} + +/* Compila para: */ + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + + + +/* Extend (Herança) +============================== */ + + + +/*Extend é uma maneira de compartilhar as propriedades de um seletor com outro. */ + +.display { + @include size(5em, 5em); + border: 5px solid $secondary-color; +} + +.display-success { + @extend .display; + border-color: #22df56; +} + +/* Compiles to: */ +.display, .display-success { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.display-success { + border-color: #22df56; +} + +/* Ampliando uma declaração CSS é preferível a criação de um mixin + por causa da maneira agrupa as classes que todos compartilham + o mesmo estilo base. Se isso for feito com um mixin, a largura, + altura, e a borda seria duplicado para cada instrução que + o chamado mixin. Enquanto isso não irá afetar o seu fluxo de trabalho, será + adicionar inchaço desnecessário para os arquivos criados pelo compilador Sass. */ + + + +/*Assentamento +==============================*/ + + + +/ * Sass permite seletores ninhos dentro seletores * / + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* '&' será substituído pelo selector pai. */ +/* Você também pode aninhar pseudo-classes. */ +/* Tenha em mente que o excesso de nidificação vai fazer seu código menos sustentável. +Essas práticas também recomendam não vai mais de 3 níveis de profundidade quando nidificação. +Por exemplo: */ + + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Compila para: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/*Parciais e Importações +==============================*/ + + +/* Sass permite criar arquivos parciais. Isso pode ajudar a manter seu Sass + código modularizado. Arquivos parciais deve começar com um '_', por exemplo, _reset.css. + Parciais não são geradas em CSS. */ + + + +/* Considere o seguinte CSS que nós vamos colocar em um arquivo chamado _reset.css */ + +html, +body, +ul, +ol { + margin: 0; + 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 + importadas arquivo e combina com o código compilado. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Compiles to: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/*Placeholder Selectors +==============================*/ + + + +/* 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 + de '.' ou '#'. Espaços reservados não aparece no CSS compilado. * / + +%content-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + @extend %content-window; + background-color: #0000ff; +} + +/* Compilado para: */ + +.message-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + background-color: #0000ff; +} + + + +/*Operações Math +============================== * / + + +/* 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 + de uma criação de um projeto simples de duas colunas. * / + +$content-area: 960px; +$main-content: 600px; +$sidebar-content: 300px; + +$main-size: $main-content / $content-area * 100%; +$sidebar-size: $sidebar-content / $content-area * 100%; +$gutter: 100% - ($main-size + $sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: $main-size; +} + +.sidebar { + width: $sidebar-size; +} + +.gutter { + width: $gutter; +} + +/* Compiles to: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + + +``` + + + +## SASS ou Sass? +Alguma vez você já se perguntou se Sass é um acrônimo ou não? Você provavelmente não tem, mas vou dizer-lhe de qualquer maneira. O nome do idioma é uma palavra, "Sass", e não uma sigla. +Porque as pessoas estavam constantemente a escrevê-lo como "SASS", o criador da linguagem de brincadeira chamou de "StyleSheets Sintaticamente Incríveis". + + +## Prática Sass +Se você quiser jogar com Sass em seu navegador, vá para [SassMeister](http://sassmeister.com/). +Você pode usar uma sintaxe, basta ir para as configurações e selecionar Sass ou SCSS. + + +## Compatibilidade + +Sass pode ser usado em qualquer projeto, desde que você tenha um programa para compilá-lo +em CSS. Você vai querer verificar se o CSS que você está usando é compatível +com os seus navegadores de destino. + +[QuirksMode CSS](http://www.quirksmode.org/css/) e [CanIUse](http://caniuse.com) são ótimos recursos para verificação de compatibilidade. + + +## Leitura +* [Official Documentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) fornece tutoriais (iniciante avançados) e artigos. diff --git a/pt-br/tmux-pt.html.markdown b/pt-br/tmux-pt.html.markdown new file mode 100644 index 00000000..9d5bf292 --- /dev/null +++ b/pt-br/tmux-pt.html.markdown @@ -0,0 +1,254 @@ +--- +category: tool +tool: tmux +contributors: + - ["mdln", "https://github.com/mdln"] +translators: + - ["Luis Custodio", "http://luiscustodio.com"] +lang: pt-br +filename: LearnTmux-pt.txt +--- + +O [tmux](http://tmux.sourceforge.net) +é um multiplexador de terminal, ele permite que terminais sejam criados, +acessados e controlados a partir de uma unica instância. tmux pode ser separado +de uma tela e continuar rodando no plano de fundo e depois ser reacoplado à +instância (ou tela original). + +``` + + tmux [command] # Roda um [comando] + # 'tmux' sem comandos irá criar uma nova seção + + new # Cria uma nova seção + -s "Nome" # Cria uma nova seção com nome "Nome" + -n "Janela" # Cria uma janela com o nome "Janela" + -c "/dir" # Inícia em uma pasta específica + + attach # Reacopla a última seção disponível + -t "#" # Reacopla a seção com nome "#" + -d # Separa (Desacopla) a sessaão de outras instâncias. + + ls # Lista todas as seções + -a # Lista todas as seções abertas + + lsw # Lista as janelas + -a # Lista todas as janelas + -s # Lista todas janleas em uma seção + + lsp # Lista os painéis + -a # Lista todos os painéis + -s # Lista todos os painéis em uma seção + -t "#" # Lista os painéis baseado no nome "#" + + kill-window # Encerrar a janela corrente + -t "#" # Encerrar a janela baseado no nome "#" + -a # Encerrar todas as janelas + -a -t "#" # Encerrar todas as janelas exceto a com nome "#" + + kill-session # Encerrar seção corrente + -t "#" # Encerrar seção com nome "#" + -a # Encerrar todas as seções + -a -t "#" # Encerrar todas as seções exceto a com nome "#" + +``` + + +### Teclas de atalhos (comandos) + +A maneira de controllar uma seção tmux acoplada é através de uma +combinação de teclas de prefixo. + +``` +---------------------------------------------------------------------- + (C-b) = Ctrl + b # Combinação de prefixos para usar comandos(atalhos). + + (M-1) = Meta + 1 -or- Alt + 1 +---------------------------------------------------------------------- + + ? # Lista todos os comandos. + : # Acessa o lugar (prompt command) para receber comandos do tmux + r # Força a redefiniçao do cliente acoplado. + c # Cria uma nova janela. + + ! # Retira o painel corrente da janela. + % # Divide o painel corrente em dois para a esquerda e direita. + " # Divide o painel corrente em dois para cima e para baixo. + + n # Move para a próxima janela. + p # Move para a janela anterior. + { # Troca o painel corrente pelo anterior. + } # Troca o painel corrent pelo posterior. + + s # Seleciona uma nova seção para o cliente acoplado iterativamente. + w # Seleciona a janela corrente iterativamente. + 0 to 9 # Seleciona a janela de 0 à 9. + + d # Separa o cliente atual. + D # Seleciona um cliente a ser separado. + + & # Encerra a janela corrente. + x # Encerra o painel corrente. + + Up, Down # Move para o painel acima, abaixo, a esquerda ou a direita. + Left, Right + + M-1 to M-5 # Organiza os paines: + # 1) Horizontalmente de maneira igual + # 2) Verticalmente de maineira igual. + # 3) Principal horizontalmente + # 4) Principal verticamente. + # 5) Mosaico + + C-Up, C-Down # Altera o tamanho do painel corrente baseado em uma célula. + C-Left, C-Right + + M-Up, M-Down # Altera o tamanho do painel corrente baseado em cinco células. + M-Left, M-Right + +``` + + +### Configurando ~/.tmux.conf + +Existe um arquivo chamado tmux.conf, ele pode ser usado para definir opções no + momento de inicialização, da mesma maneira que .vimrc, init.el, .bash_profile são usados. + + +``` +# Exemplo de tmux.conf +# 2014.10 + + +### General +########################################################################### + +# Habilita UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Limite da história de comandos +set -g history-limit 2048 + +# Indíce de inicialização +set -g base-index 1 + +# Mouse +set-option -g mouse-select-pane on + +# Recarregar o arquivo de configuração sem a necessidade de reiniciar o programa +unbind r +bind r source-file ~/.tmux.conf + + +### Teclas de atalho +########################################################################### + +# Desvincular C-b como prefixo padrão. +unbind C-b + +# Define um novo prefixo padrão. +set-option -g prefix ` + +# Definir prefixos que podem ser usados para voltar para a janela anterior. +bind C-a last-window +bind ` last-window + +# Fazer com que F11 e F12 alterem o comportamento de C-a e ` +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` + +# Preferencia de teclas de atalho +setw -g mode-keys vi +set-option -g status-keys vi + +# Mover enter paineis com teclas de orientaçao do vim +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R + +# Iterar entre as Janelas +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +# Iterar entre os painéis +bind = split-window -h +bind - split-window -v +unbind '"' +unbind % + +# Habilitar a sub-seção a enviar comandos. +bind a send-prefix + + +### Theme +########################################################################### + +# Paleta de cores para a barra de status +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +# Paleta de cores para bordas do painel +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +# Palta de cores para mensagem +set-option -g message-fg black +set-option -g message-bg green + +# Paleta de cores para janela de status +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +# Notificações +setw -g monitor-activity on +set -g visual-activity on +set-option -g bell-action any +set-option -g visual-bell off + +# Definir automaticamente o título de janelas +set-option -g set-titles on +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) + +# Ajustes na barra de status +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" + +# Mostrar indicativos de performance na barra de status +# Requires https://github.com/thewtex/tmux-mem-cpu-load/ +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + + +### Referências + +[Tmux | Início](http://tmux.sourceforge.net) + +[Manual Tmux (em inglês)](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) + +[Mostrar CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) + +Possui uma sugestão? Uma correção, talvez? Abra um issue no Repositório GitHub, ou então faça um pull request. diff --git a/purescript.html.markdown b/purescript.html.markdown index a006cdff..6d8cfbb9 100644 --- a/purescript.html.markdown +++ b/purescript.html.markdown @@ -2,40 +2,49 @@ language: purescript contributors: - ["Fredrik Dyrkell", "http://www.lexicallyscoped.com"] + - ["Thimoteus", "https://github.com/Thimoteus"] --- PureScript is a small strongly, statically typed language compiling to Javascript. * Learn more at [http://www.purescript.org/](http://www.purescript.org/) -* Documentation: [http://docs.purescript.org/en/latest/](http://docs.purescript.org/en/latest/) +* Documentation: [http://pursuit.purescript.org/](http://pursuit.purescript.org/) * Book: Purescript by Example, [https://leanpub.com/purescript/](https://leanpub.com/purescript/) +All the noncommented lines of code can be run in the PSCI REPL, though some will +require the `--multi-line-mode` flag. + ```haskell -- -- 1. Primitive datatypes that corresponds to their Javascript -- equivalents at runtime. +import Prelude -- Numbers -1 + 7*5 :: Number -- 36 +1.0 + 7.2*5.5 :: Number -- 40.6 +-- Ints +1 + 2*5 :: Int -- 11 -- Types are inferred, so the following works fine -9 / 2.5 + 4.4 -- 8 +9.0/2.5 + 4.4 -- 8.0 +-- But Ints and Numbers don't mix, so the following won't +5/2 + 2.5 -- Expression 2.5 does not have type Int -- Hexadecimal literals 0xff + 1 -- 256 -- Unary negation 6 * -3 -- -18 6 * negate 3 -- -18 --- Modulus -3 % 2 -- 1 -4 % 2 -- 0 +-- Modulus, from purescript-math (Math) +3.0 % 2.0 -- 1.0 +4.0 % 2.0 -- 0.0 -- Inspect the type of an expression in psci -:t 9 / 2.5 + 4.4 -- Prim.Number +:t 9.5/2.5 + 4.4 -- Prim.Number -- Booleans true :: Boolean -- true false :: Boolean -- false -- Negation -not true --false +not true -- false 23 == 23 -- true 1 /= 4 -- true 1 >= 4 -- false @@ -49,19 +58,22 @@ true && (9 >= 19 || 1 < 2) -- true -- Strings "Hellow" :: String -- "Hellow" --- Multiline string +-- Multiline string without newlines, to run in psci use the --multi-line-mode flag "Hellow\ \orld" -- "Helloworld" +-- Multiline string with newlines +"""Hello +world""" -- "Hello\nworld" -- Concatenate "such " ++ "amaze" -- "such amaze" -- -- 2. Arrays are Javascript arrays, but must be homogeneous -[1,1,2,3,5,8] :: [Number] -- [1,1,2,3,5,8] -[true, true, false] :: [Boolean] -- [true,true,false] +[1,1,2,3,5,8] :: Array Number -- [1,1,2,3,5,8] +[true, true, false] :: Array Boolean -- [true,true,false] -- [1,2, true, "false"] won't work --- `Cannot unify Prim.Number with Prim.Boolean` +-- `Cannot unify Prim.Int with Prim.Boolean` -- Cons (prepend) 1 : [2,4,3] -- [1,2,4,3] @@ -84,91 +96,95 @@ append [1,2,3] [4,5,6] -- [1,2,3,4,5,6] -- -- 3. Records are Javascript objects, with zero or more fields, which --- can have different types +-- can have different types. +-- In psci you have to write `let` in front of the function to get a +-- top level binding. let book = {title: "Foucault's pendulum", author: "Umberto Eco"} -- Access properties book.title -- "Foucault's pendulum" -getTitle b = b.title +let getTitle b = b.title -- Works on all records with a title (but doesn't require any other field) getTitle book -- "Foucault's pendulum" getTitle {title: "Weekend in Monaco", artist: "The Rippingtons"} -- "Weekend in Monaco" +-- Can use underscores as shorthand +_.title book -- "Foucault's pendulum" -- Update a record -changeTitle b t = b {title = t} -changeTitle book "Ill nome della rosa" -- {title: "Ill nome della - -- rosa", author: "Umberto Eco"} +let changeTitle b t = b {title = t} +getTitle (changeTitle book "Ill nome della rosa") -- "Ill nome della rosa" -- -- 4. Functions -sumOfSquares x y = x*x+y*y +-- In psci's multiline mode +let sumOfSquares :: Int -> Int -> Int + sumOfSquares x y = x*x + y*y sumOfSquares 3 4 -- 25 --- In psci you have to write `let` in front of the function to get a --- top level binding -mod x y = x % y -mod 3 2 -- 1 +let myMod x y = x % y +myMod 3.0 2.0 -- 1.0 -- Infix application of function 3 `mod` 2 -- 1 --- function application have higher precedence than all other +-- function application has higher precedence than all other -- operators sumOfSquares 3 4 * sumOfSquares 4 5 -- 1025 -- Conditional -abs' n = if n>=0 then n else -n +let abs' n = if n>=0 then n else -n abs' (-3) -- 3 -- Guarded equations -abs n | n >= 0 = n - | otherwise = -n +let abs'' n | n >= 0 = n + | otherwise = -n -- Pattern matching --- Note the type signature, input is an array of numbers The pattern --- matching destructures and binds the array into parts -first :: [Number] -> Number -first (x:_) = x -first [3,4,5] -- 3 -second :: [Number] -> Number -second (_:y:_) = y -second [3,4,5] -- 4 -sumTwo :: [Number] -> [Number] -sumTwo (x:y:rest) = (x+y) : rest -sumTwo [2,3,4,5,6] -- [5,4,5,6] - --- sumTwo doesn't handle when the array is empty or just have one --- element in which case you get an error +-- Note the type signature, input is a list of numbers. The pattern matching +-- destructures and binds the list into parts. +-- Requires purescript-lists (Data.List) +let first :: forall a. List a -> a + first (Cons x _) = x +first (toList [3,4,5]) -- 3 +let second :: forall a. List a -> a + second (Cons _ (Cons y _)) = y +second (toList [3,4,5]) -- 4 +let sumTwo :: List Int -> List Int + sumTwo (Cons x (Cons y rest)) = x + y : rest +fromList (sumTwo (toList [2,3,4,5,6])) :: Array Int -- [5,4,5,6] + +-- sumTwo doesn't handle when the list is empty or there's only one element in +-- which case you get an error. sumTwo [1] -- Failed pattern match -- Complementing patterns to match -- Good ol' Fibonacci -fib 1 = 1 -fib 2 = 2 -fib x = fib (x-1) + fib (x-2) +let fib 1 = 1 + fib 2 = 2 + fib x = fib (x-1) + fib (x-2) fib 10 -- 89 -- Use underscore to match any, where you don't care about the binding name -isZero 0 = true -isZero _ = false +let isZero 0 = true + isZero _ = false -- Pattern matching on records -ecoTitle {author = "Umberto Eco", title = t} = Just t -ecoTitle _ = Nothing +let ecoTitle {author = "Umberto Eco", title = t} = Just t + ecoTitle _ = Nothing ecoTitle book -- Just ("Foucault's pendulum") ecoTitle {title: "The Quantum Thief", author: "Hannu Rajaniemi"} -- Nothing -- ecoTitle requires both field to type check: -ecoTitle {title: "The Quantum Thief"} -- Object does not have property author +ecoTitle {title: "The Quantum Thief"} -- Object lacks required property "author" -- Lambda expressions (\x -> x*x) 3 -- 9 (\x y -> x*x + y*y) 4 5 -- 41 -sqr = \x -> x*x +let sqr = \x -> x*x -- Currying -add x y = x + y -- is equivalent with -add = \x -> (\y -> x+y) -add3 = add 3 -:t add3 -- Prim.Number -> Prim.Number +let myAdd x y = x + y -- is equivalent with +let myAdd' = \x -> \y -> x + y +let add3 = myAdd 3 +:t add3 -- Prim.Int -> Prim.Int -- Forward and backward function composition -- drop 3 followed by taking 5 @@ -177,9 +193,9 @@ add3 = add 3 (drop 3 <<< take 5) (1..20) -- [4,5] -- Operations using higher order functions -even x = x % 2 == 0 +let even x = x `mod` 2 == 0 filter even (1..10) -- [2,4,6,8,10] -map (\x -> x+11) (1..5) -- [12,13,14,15,16] +map (\x -> x + 11) (1..5) -- [12,13,14,15,16] -- Requires purescript-foldable-traversabe (Data.Foldable) diff --git a/python.html.markdown b/python.html.markdown index b939ebbe..42a52bcf 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 --- @@ -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 @@ -165,6 +172,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 +226,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) # => 3 +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 @@ -309,6 +328,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 +488,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 +544,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 +563,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 +599,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 +707,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.html.markdown b/pythonstatcomp.html.markdown new file mode 100644 index 00000000..78b62e33 --- /dev/null +++ b/pythonstatcomp.html.markdown @@ -0,0 +1,234 @@ +--- +language: Statistical computing with Python +contributors: + - ["e99n09", "https://github.com/e99n09"] +filename: pythonstatcomp.py +--- + +This is a tutorial on how to do some typical statistical programming tasks using Python. It's intended for people basically familiar with Python and experienced at statistical programming in a language like R, Stata, SAS, SPSS, or MATLAB. + +```python + +# 0. Getting set up ==== + +""" Get set up with IPython and pip install the following: numpy, scipy, pandas, + matplotlib, seaborn, requests. + Make sure to do this tutorial in the IPython notebook so that you get + the inline plots and easy documentation lookup. +""" + +# 1. Data acquisition ==== + +""" One reason people choose Python over R is that they intend to interact a lot + with the web, either by scraping pages directly or requesting data through + an API. You can do those things in R, but in the context of a project + already using Python, there's a benefit to sticking with one language. +""" + +import requests # for HTTP requests (web scraping, APIs) +import os + +# web scraping +r = requests.get("https://github.com/adambard/learnxinyminutes-docs") +r.status_code # if 200, request was successful +r.text # raw page source +print(r.text) # prettily formatted +# save the page source in a file: +os.getcwd() # check what's the working directory +f = open("learnxinyminutes.html","wb") +f.write(r.text.encode("UTF-8")) +f.close() + +# downloading a csv +fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/" +fn = "pets.csv" +r = requests.get(fp + fn) +print(r.text) +f = open(fn,"wb") +f.write(r.text.encode("UTF-8")) +f.close() + +""" for more on the requests module, including APIs, see + http://docs.python-requests.org/en/latest/user/quickstart/ +""" + +# 2. Reading a CSV file ==== + +""" Wes McKinney's pandas package gives you 'DataFrame' objects in Python. If + you've used R, you will be familiar with the idea of the "data.frame" already. +""" + +import pandas as pd, numpy as np, scipy as sp +pets = pd.read_csv(fn) +pets +# name age weight species +# 0 fluffy 3 14 cat +# 1 vesuvius 6 23 fish +# 2 rex 5 34 dog + +""" R users: note that Python, like most normal programming languages, starts + indexing from 0. R is the unusual one for starting from 1. +""" + +# two different ways to print out a column +pets.age +pets["age"] + +pets.head(2) # prints first 2 rows +pets.tail(1) # prints last row + +pets.name[1] # 'vesuvius' +pets.species[0] # 'cat' +pets["weight"][2] # 34 + +# in R, you would expect to get 3 rows doing this, but here you get 2: +pets.age[0:2] +# 0 3 +# 1 6 + +sum(pets.age)*2 # 28 +max(pets.weight) - min(pets.weight) # 20 + +""" If you are doing some serious linear algebra and number-crunching, you may + just want arrays, not DataFrames. DataFrames are ideal for combining columns + of different types. +""" + +# 3. Charts ==== + +import matplotlib as mpl, matplotlib.pyplot as plt +%matplotlib inline + +# To do data vizualization in Python, use matplotlib + +plt.hist(pets.age); + +plt.boxplot(pets.weight); + +plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); + +# seaborn sits atop matplotlib and makes plots prettier + +import seaborn as sns + +plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); + +# there are also some seaborn-specific plotting functions +# notice how seaborn automatically labels the x-axis on this barplot +sns.barplot(pets["age"]) + +# R veterans can still use ggplot +from ggplot import * +ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") +# source: https://pypi.python.org/pypi/ggplot + +# there's even a d3.js port: https://github.com/mikedewar/d3py + +# 4. Simple data cleaning and exploratory analysis ==== + +""" Here's a more complicated example that demonstrates a basic data + cleaning workflow leading to the creation of some exploratory plots + and the running of a linear regression. + The data set was transcribed from Wikipedia by hand. It contains + all the Holy Roman Emperors and the important milestones in their lives + (birth, death, coronation, etc.). + The goal of the analysis will be to explore whether a relationship + exists between emperor birth year and emperor lifespan. + data source: https://en.wikipedia.org/wiki/Holy_Roman_Emperor +""" + +# load some data on Holy Roman Emperors +url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" +r = requests.get(url) +fp = "hre.csv" +f = open(fp,"wb") +f.write(r.text.encode("UTF-8")) +f.close() + +hre = pd.read_csv(fp) + +hre.head() +""" + Ix Dynasty Name Birth Death Election 1 +0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN +1 NaN Carolingian Louis I 778 20 June 840 NaN +2 NaN Carolingian Lothair I 795 29 September 855 NaN +3 NaN Carolingian Louis II 825 12 August 875 NaN +4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN + + Election 2 Coronation 1 Coronation 2 Ceased to be Emperor +0 NaN 25 December 800 NaN 28 January 814 +1 NaN 11 September 813 5 October 816 20 June 840 +2 NaN 5 April 823 NaN 29 September 855 +3 NaN Easter 850 18 May 872 12 August 875 +4 NaN 29 December 875 NaN 6 October 877 + + Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 +0 NaN NaN NaN NaN +1 Charles I son NaN NaN +2 Louis I son NaN NaN +3 Lothair I son NaN NaN +4 Louis I son NaN NaN +""" + +# clean the Birth and Death columns + +import re # module for regular expressions + +rx = re.compile(r'\d+$') # match trailing digits + +""" This function applies the regular expression to an input column (here Birth, + Death), flattens the resulting list, converts it to a Series object, and + finally converts the type of the Series object from string to integer. For + more information into what different parts of the code do, see: + - https://docs.python.org/2/howto/regex.html + - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list + - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html +""" +def extractYear(v): + return(pd.Series(reduce(lambda x,y: x+y,map(rx.findall,v),[])).astype(int)) + +hre["BirthY"] = extractYear(hre.Birth) +hre["DeathY"] = extractYear(hre.Death) + +# make a column telling estimated age +hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int) + +# simple scatterplot, no trend line, color represents dynasty +sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False); + +# use scipy to run a linear regression +from scipy import stats +(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge) +# code source: http://wiki.scipy.org/Cookbook/LinearRegression + +# check the slope +slope # 0.0057672618839073328 + +# check the R^2 value: +rval**2 # 0.020363950027333586 + +# check the p-value +pval # 0.34971812581498452 + +# use seaborn to make a scatterplot and plot the linear regression trend line +sns.lmplot("BirthY", "EstAge", data=hre); + +""" For more information on seaborn, see + - http://web.stanford.edu/~mwaskom/software/seaborn/ + - https://github.com/mwaskom/seaborn + For more information on SciPy, see + - http://wiki.scipy.org/SciPy + - http://wiki.scipy.org/Cookbook/ + To see a version of the Holy Roman Emperors analysis using R, see + - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R +""" +``` + +If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial. + +You can also find plenty of interactive IPython tutorials on subjects specific to your interests, like Cam Davidson-Pilon's <a href="http://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/" Title="Probabilistic Programming and Bayesian Methods for Hackers">Probabilistic Programming and Bayesian Methods for Hackers</a>. + +Some more modules to research: + - text analysis and natural language processing: nltk, http://www.nltk.org + - social network analysis: igraph, http://igraph.org/python/ 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/css-ru.html.markdown b/ru-ru/css-ru.html.markdown new file mode 100644 index 00000000..2e2d40b7 --- /dev/null +++ b/ru-ru/css-ru.html.markdown @@ -0,0 +1,250 @@ +--- +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Geoffrey Liu", "https://github.com/g-liu"] +filename: learncss-ru.css +lang: ru-ru +--- + +В свои ранние дни веб состоял в основном из чистого текста. С развитием браузеров +веб-страницы с графическими элементами стали обычным делом. +CSS - язык, разграничивающий содержимое (HTML) и внешний вид веб-страниц. + +Если коротко, то CSS предоставляет синтаксис, позволяющий выбирать различные +HTML элементы и определять их внешний вид. + +Как и у других языков, у CSS много версий. Мы описываем CSS2.0 - не самую новую, +но самую поддерживаемую и распространенную версию. + +**ВАЖНО:** Так как результатом применения CSS является изменение внешнего вида +элементов, постарайтесь использовать CSS-песочницы при изучении языка. +Например [dabblet](http://dabblet.com/). +В данной статье рассматриваются в первую очередь синтаксис и общие рекомендации. + + +```css +/* Для комментариев используется слеш-астериск, как на этой строчке. + В CSS нет однострочных комментариев; все комментарии записываются таким способом */ + +/* #################### + ## СЕЛЕКТОРЫ + #################### */ + +/* Выражения в CSS очень просты */ +селектор { атрибут: значение; /* другие атрибуты...*/ } + +/* селекторы используются для выбора элементов на странице + +Чтобы выбрать все элементы, используйте астериск: */ +* { color:red; } + +/* +Если на странице присутствует такой элемент: + +<div class='some-class class2' id='someId' attr='value' otherAttr='en-us foo bar' /> +*/ + +/* его можно выбрать по одному классу */ +.some-class { } + +/* или по обоим классам */ +.some-class.class2 { } + +/* по названию тега */ +div { } + +/* по идентификатору */ +#someId { } + +/* по имеющемуся атрибуту */ +[attr] { font-size:smaller; } + +/* или по атрибуту с определенным значением */ +[attr='value'] { font-size:smaller; } + +/* можно выбрать атрибуты, начинающиеся с определенного значения (CSS3) */ +[attr^='val'] { font-size:smaller; } + +/* или заканчивающиеся определенным значением (CSS3) */ +[attr$='ue'] { font-size:smaller; } + +/* содержащие отделенное пробелами значение в названии атрибута (CSS3) */ +[otherAttr~='foo'] { font-size:smaller; } + +/* можно выбрать атрибут как с точным, так и со стоящим после значения “-” (U+002D) */ +[otherAttr|='en'] { font-size:smaller; } + + +/* Более того, все это можно использовать вместе - между разными частями +не должно быть пробелов, иначе селектор будет иметь совершенно иное значение */ +div.some-class[attr$='ue'] { } + +/* Вы можете выбрать элемент по его родителю */ + +/* прямой потомок другого элемента (выбранного с помощью селектора) */ +div.some-parent > .class-name {} + +/* потомок любого родителя в дереве элементов + следующая строка означает: "любой элемент класса "class-name", + являющийся потомком div-элемента класса "some-parent" + НЕЗАВИСИМО ОТ УРОВНЯ ВЛОЖЕННОСТИ" */ +div.some-parent .class-name {} + +/* важно: этот же селектор без пробелов имеет иное значение + можете догадаться, какое? */ +div.some-parent.class-name {} + +/* вы можете выбрать элемент по первому предшествующему + родственному элементу */ +.i-am-before + .this-element { } + +/* или любому предшествующему родственнику перед элементом */ +.i-am-any-before ~ .this-element {} + + +/* Существуют псевдо-классы, позволяющие изменять внешний вид элемента + в зависимости от событий, произошедших с элементом */ + +/* например, когда курсор наведен на элемент */ +element:hover {} + +/* когда пользователь проходил по ссылке ранее */ +element:visited {} + +/* или еще не проходил по ней */ +element:link {} + +/* выбранное поле воода (input) */ +element:focus {} + + +/* #################### + ## АТРИБУТЫ + #################### */ + +selector { + + /* Единицы измерения */ + width: 50%; /* проценты */ + font-size: 2em; /* умножается на высоту шрифта (2em - в два раза больше) */ + width: 200px; /* пиксели */ + font-size: 20pt; /* пункты */ + width: 5cm; /* сантиметры */ + min-width: 50mm; /* милиметры */ + max-width: 5in; /* дюймы */ + height: 0.2vh; /* умножается на высоту окна браузера (CSS3) */ + width: 0.4vw; /* умножается на ширину окна браузера (CSS3) */ + min-height: 0.1vmin; /* наименьшее из vh и vw (CSS3) */ + max-width: 0.3vmax; /* наибольшее из vh и vw (CSS3) */ + + /* Цвета */ + background-color: #F6E; /* сокращенная запись шестнадцатеричного кода */ + background-color: #F262E2; /* стандартная запись шестнадцатеричного кода */ + background-color: tomato; /* название цвета */ + background-color: rgb(255, 255, 255); /* цветовая модель rgb */ + background-color: rgb(10%, 20%, 50%); /* цветовая модель rgb в процентах */ + background-color: rgba(255, 0, 0, 0.3); /* цветовая модель rgb (последний аргумент отвечает за прозрачность цвета) (CSS3) */ + background-color: transparent; /* прозрачный цвет */ + background-color: hsl(0, 100%, 50%); /* в формате hsl (CSS3) */ + background-color: hsla(0, 100%, 50%, 0.3); /* в формате hsl (последний аргумент отвечает за непрозрачность цвета) (CSS3) */ + + + /* Изображения */ + background-image: url(/path-to-image/image.jpg); /* кавычки внутри url() опциональны */ + + /* Шрифты */ + font-family: Arial; + font-family: "Courier New"; /* если в названии есть пробелы, заключите его в кавычки */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; /* если шрифт не найден, + будет использован следующий за ним в списке */ +} + +``` + +## Использование + +Сохраните готовый файл с расширением .css + +```xml +<!-- добавьте css файл в тег <head> на странице: --> +<link rel='stylesheet' type='text/css' href='path/to/style.css' /> + +<!-- Можно использовать встроенные стили. Рекомендуется избегать подобного подхода. --> +<body> + <style> + a { color: purple; } + </style> +</body> + +<!-- Можно установить стиль элемента напрямую. +Используйте этот способ только в случае крайней необходимости. --> +<div style="border: 1px solid red;"> +</div> + +``` + +## Приоритет + +Как вы заметили, внешний вид элемента может определяться несколькими селекторами, +а значение атрибута элемента может быть установлено больше одного раза. +В подобных случаях одно из значений оказывается приоритетнее остальных. + +Если взять следующую таблицу стилей: + +```css +/*A*/ +p.class1[attr='value'] + +/*B*/ +p.class1 {} + +/*C*/ +p.class2 {} + +/*D*/ +p {} + +/*E*/ +p { property: value !important; } + +``` + +и следующую разметку: + +```xml +<p style='/*F*/ property:value;' class='class1 class2' attr='value'> +</p> +``` + +Приоритет стилей будет таким: +Помните: приоритет выставляется для **атрибута**, а не для всего блока стилей. + +* `E` имеет наивысший приоритет благодаря ключевому слову `!important`. + Используйте только в случае крайней необходимости. +* `F` идет следующим, так как является встроенным стилем. +* `A` следующий, как самый конкретизированный. + конкретизированный == большее количество определителей. + В этом примере 3 определителя: 1 тег `p` + + название класса `class1` + 1 атрибут `attr='value'` +* `C` следующий. Несмотря на одинаковое с `B` количество определителей, + `C` определен позже. +* Затем `B` +* И последний `D`. + +## Совместимость + +Несмотря на то, что большая часть функций CSS2 (а также CSS3) подеррживается всеми +браузерами и устройствами, не забывайте проверять совместимость CSS-правил +с современными браузерами. + +[QuirksMode CSS](http://www.quirksmode.org/css/) замечательно подходит для этого. + +To run a quick compatibility check, [CanIUse](http://caniuse.com) is a great resource. + +## Ресурсы для самостоятельного изучения + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown index a0e2b474..3852a550 100644 --- a/ru-ru/python-ru.html.markdown +++ b/ru-ru/python-ru.html.markdown @@ -167,6 +167,10 @@ li = [] # Можно сразу начать с заполненного списка other_li = [4, 5, 6] +# строка разделена в список +a="adambard" +list(a) #=> ['a','d','a','m','b','a','r','d'] + # Объекты добавляются в конец списка методом append li.append(1) # [1] li.append(2) # [1, 2] @@ -238,7 +242,6 @@ d, e, f = 4, 5, 6 # Обратите внимание, как легко поменять местами значения двух переменных e, d = d, e # теперь d == 5, а e == 4 - # Словари содержат ассоциативные массивы empty_dict = {} # Вот так описывается предзаполненный словарь diff --git a/ruby.html.markdown b/ruby.html.markdown index 0e798706..998b4bf7 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -12,7 +12,8 @@ contributors: - ["Dzianis Dashkevich", "https://github.com/dskecse"] - ["Levi Bostian", "https://github.com/levibostian"] - ["Rahil Momin", "https://github.com/iamrahil"] - - ["Gabriel Halley", https://github.com/ghalley"] + - ["Gabriel Halley", "https://github.com/ghalley"] + - ["Persa Zula", "http://persazula.com"] --- ```ruby @@ -40,6 +41,7 @@ You shouldn't either 35 / 5 #=> 7 2**5 #=> 32 5 % 3 #=> 2 +5 ^ 6 #=> 3 # Arithmetic is just syntactic sugar # for calling a method on an object @@ -107,6 +109,12 @@ placeholder = 'use string interpolation' 'hello ' + 3 #=> TypeError: can't convert Fixnum into String 'hello ' + 3.to_s #=> "hello 3" +# Combine strings and operators +'hello ' * 3 #=> "hello hello hello " + +# Append to string +'hello' << ' world' #=> "hello world" + # print to the output with a newline at the end puts "I'm printing!" #=> I'm printing! @@ -284,7 +292,7 @@ end #=> iteration 4 #=> iteration 5 -# There are a bunch of other helpful looping functions in Ruby, +# There are a bunch of other helpful looping functions in Ruby, # for example "map", "reduce", "inject", the list goes on. Map, # for instance, takes the array it's looping over, does something # to it as defined in your block, and returns an entirely new array. diff --git a/scala.html.markdown b/scala.html.markdown index 7f545196..192e03d7 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -278,21 +278,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 +313,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/ta_in/css.html.markdown b/ta_in/css.html.markdown new file mode 100644 index 00000000..56f94ed0 --- /dev/null +++ b/ta_in/css.html.markdown @@ -0,0 +1,254 @@ +--- +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Geoffrey Liu", "https://github.com/g-liu"] + - ["Connor Shea", "https://github.com/connorshea"] + - ["Deepanshu Utkarsh", "https://github.com/duci9y"] +translators: + - ["Rasendran Kirushan", "https://github.com/kirushanr"] +filename: learncss.css +lang:in-ta +--- + + +இணையத்தின் ஆரம்ப காலத்தில் முழுமையாக உரைகளை மட்டுமே கொண்டிருந்தன. +ஆனால் உலாவிகளில் கொண்டு வரப்பட்ட மாற்றங்களில் முழுமையான காட்சிபடுத்தல்களுடன் +கூடிய இணையதளங்கள் உருவாகின. + + +CSS ஆனது HTML மற்றும் அதன் அழகுபடுத்கூடிய காரணிகளையும் வேறுபடுத்த உதவியது. + +ஒரு html இல் உள்ள உறுப்புகளை(elements) வெவ்வேறு வகையான காட்சி பண்புகளை வழங்க உதவுகிறது. + +இந்த வழிகாட்டி CSS2 உக்கு எழுதப்பட்டுள்ளது, இருப்பினும் தற்போது CSS 3 வேகமாக பிரபல்யமாகி வருகிறது. + +**குறிப்பு:** +CSS ஆனது முற்று முழுதாக visual(காட்சி) மாற்றங்களை தருவதால் அதை நீங்கள் முயற்சிக்க +இதை உபயோகபடுத்தலாம் [dabblet](http://dabblet.com/). +இந்த வழிகாட்டியின் பிரதான நோக்கம் CSS இன் syntax மற்றும் மேலும் சில வழிமுறைகளை +உங்களுக்கு கற்று தருவதாகும் + +```css +/* css இல் குறிப்புகளை இப்படி இடலாம் */ + +/* #################### + ## SELECTORS + #################### */ + +/* ஒரு HTML பக்கத்தில் இருக்கும் உறுப்பை நாம் selector மூலம் தெரிவு செய்யலாம் +selector { property: value; /* more properties...*/ } + +/* +கிழே ஒரு உதாரணம் காட்டப்பட்டுள்ளது: + +<div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' /> +*/ + +/* நீங்கள் அந்த உறுப்பை அதன் CSS class மூலம் தெரியலாம் */ +.class1 { } + +/* அல்லது இவ்வாறு இரண்டு class மூலம் தெரியலாம்! */ +.class1.class2 { } + +/* அல்லது அதன் பெயரை பாவித்து தெரியலாம் */ +div { } + +/* அல்லது அதன் id ஐ பயன்படுத்தி தெரியலாம்*/ +#anID { } + +/* அல்லது ஒரு உறுப்பின் பண்பு ஒன்றின் மூலம்! */ +[attr] { font-size:smaller; } + +/* அல்லது அந்த பண்பு ஒரு குறிப்பிட்ட பெறுமானத்தை கொண்டு இருப்பின் */ +[attr='value'] { font-size:smaller; } + +/* ஒரு பெறுமதியுடன் ஆரம்பமாகும் போது (CSS 3) */ +[attr^='val'] { font-size:smaller; } + +/* அல்லது ஒரு பெறுமதியுடன் முடிவடையும் போது (CSS 3) */ +[attr$='ue'] { font-size:smaller; } + +/* அல்லது காற்புள்ளியால் பிரிக்கப்பட்ட பெறுமானங்களை கொண்டு இருப்பின் */ +[otherAttr~='foo'] { } +[otherAttr~='bar'] { } + +/* அல்லது `-` பிரிக்கப்பட்ட பெறுமானங்களை கொண்டு இருப்பின், உ.ம்:-, "-" (U+002D) */ +[otherAttr|='en'] { font-size:smaller; } + + +/* நாம் இரண்டு selectors ஐ ஒன்றாக உபயோகித்தும் ஒரு உறுப்பை அணுக முடியும் , +அவற்றுக்கு இடயே இடைவெளி காணப்படகூடாது + */ +div.some-class[attr$='ue'] { } + +/*அல்லது ஒரு உறுப்பினுள் இருக்கும் இன்னொரு உறுப்பை (child element) அணுக */ +div.some-parent > .class-name { } + +/* ஒரு ஒரு பிரதான உறுப்பில் உள்ள உப உறுப்புகளை அணுக*/ +div.some-parent .class-name { } + +/* மேலே குறிபிட்ட அணுகுமுறையில் இடைவெளி காணப்படாது விடின் + அந்த selector வேலை செய்யாது + */ +div.some-parent.class-name { } + +/* அல்லது ஒரு உறுப்புக்கு அடுத்துள்ள */ +.i-am-just-before + .this-element { } + +/* or அல்லது அதற்கு முந்தய உறுப்பின் மூலம் */ +.i-am-any-element-before ~ .this-element { } + +/* + சில selectors ஐ pseudo class மூலம் அணுக முடியும் , எப்போது எனில் அவை + குறித்த ஒரு நிலையில் இருக்கும் போது ஆகும் + */ + +/* உதாரணமாக நாம் ஒரு உறுப்பின் மீதாக cursor ஐ நகர்த்தும் போது */ +selector:hover { } + +/* அல்லது ஒரு +பார்வையிட்ட இணைப்பு */ +selector:visited { } + +/* அல்லது ஒரு பார்வையிடபடாத இணைப்பு */ +selected:link { } + +/* அல்லது ஒரு element ஐ focus செய்யும் போது */ +selected:focus { } + +/* + எல்லா elementகளையும் ஒரே நேரத்தில் அணுக `*` +*/ +* { } /* all elements */ +.parent * { } /* all descendants */ +.parent > * { } /* all children */ + +/* #################### + ## பண்புகள் + #################### */ + +selector { + + /* நீளத்தின் அலகுகள் absolute அல்லது relative ஆக இருக்கலாம். */ + + /* Relative units */ + width: 50%; /* percentage of parent element width */ + font-size: 2em; /* multiples of element's original font-size */ + font-size: 2rem; /* or the root element's font-size */ + font-size: 2vw; /* multiples of 1% of the viewport's width (CSS 3) */ + font-size: 2vh; /* or its height */ + font-size: 2vmin; /* whichever of a vh or a vw is smaller */ + font-size: 2vmax; /* or greater */ + + /* Absolute units */ + width: 200px; /* pixels */ + font-size: 20pt; /* points */ + width: 5cm; /* centimeters */ + min-width: 50mm; /* millimeters */ + max-width: 5in; /* inches */ + + + /* Colors */ + color: #F6E; /* short hex format */ + color: #FF66EE; /* long hex format */ + 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: 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 */ + + /* Images as backgrounds of elements */ + background-image: url(/img-path/img.jpg); /* quotes inside url() optional */ + + /* Fonts */ + font-family: Arial; + /* if the font family name has a space, it must be quoted */ + font-family: "Courier New"; + /* if the first one is not found, the browser uses the next, and so on */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; +} +``` + +## Usage + +ஒரு css file ஐ save செய்ய `.css`. + +```xml +<!-- உங்கள் css file ஐ <head>. உள் குறிப்பிட வேண்டும் + சரியான முறையை பார்க்க http://stackoverflow.com/questions/8284365 --> +<link rel='stylesheet' type='text/css' href='path/to/style.css' /> + +<!-- நீங்கள் css ஐ html உள்ளும் எழுத முடியும் --> +<style> + a { color: purple; } +</style> + +<!-- அல்லது css ஐ நேரடியாக அந்த element இல் எழுத முடியும் --> +<div style="border: 1px solid red;"> +</div> +``` + +## Precedence அல்லது Cascade + +ஒரு element ஆனது ஒன்றுக்கு மேற்பட்ட selectors மூலம் அணுகபடலாம் ,இவ்வாறான சந்தர்பங்களில் +ஒரு குறிபிட்ட விதிமுறையை பின்பற்றுகிறது இது cascading என அழைக்கபடுகிறது, அதனால் தன +இது Cascading Style Sheets என அழைக்கபடுகிறது. + + +கிழே தரப்பட்டுள்ள css இன் படி: + +```css +/* A */ +p.class1[attr='value'] + +/* B */ +p.class1 { } + +/* C */ +p.class2 { } + +/* D */ +p { } + +/* E */ +p { property: value !important; } +``` + +அத்துடன் கிழே தரப்பட்டுள்ள கட்டமைப்பின்படியும்: + +```xml +<p style='/*F*/ property:value;' class='class1 class2' attr='value' /> +``` + + +css முன்னுரிமை பின்வருமாறு +* `E` இதுவே அதிக முக்கியத்துவம் வாய்ந்தது காரணம் இது `!important` பயன்படுத்துகிறது. இதை பயன்படுத்துவதை தவிர்க்கவும் +* `F` இது இரண்டாவது காரணம் இது inline style. +* `A` இது மூன்றவதாக வருகிறது, காரணம் இது மூன்று காரணிகளை குறிக்கிறது : element(உறுப்பு) பெயர் `p`, அதன் class `class1`, an அதன் பண்பு(attribute) `attr='value'`. +* `C` இது அடுத்த நிலையில் உள்ளது கடைசி. +* `B` இது அடுத்தது. +* `D` இதுவே கடைசி . + +## css அம்சங்களின் பொருந்தகூடிய தன்மை + +பெரும்பாலான css 2 வின் அம்சங்கள் எல்லா உலாவிகளிலும் , கருவிகளிலும் உள்ளன. ஆனால் முன்கூட்டியே அந்த அம்சங்களை பரிசோதிப்பது நல்லது. + +## வளங்கள் + +* 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/) + +## மேலும் வாசிக்க + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing +* [CSS-Tricks](https://css-tricks.com) diff --git a/ta_in/javascript.html.markdown b/ta_in/javascript.html.markdown new file mode 100644 index 00000000..f0b0a36a --- /dev/null +++ b/ta_in/javascript.html.markdown @@ -0,0 +1,594 @@ +--- +language: javascript +contributors: + - ['Adam Brenecki', 'http://adam.brenecki.id.au'] + - ['Ariel Krakowski', 'http://www.learneroo.com'] +translators: + - ["Rasendran Kirushan", "https://github.com/kirushanr"] +filename: javascript.js +lang:in-ta +--- + +javascript 1995 ஆம் ஆண்டு Netscape இல் பணிபுரிந்த Brendan Eich +என்பவரால் உருவாக்கபட்டது.ஆரம்பத்தில் மிகவும் எளிமையான +ஸ்க்ரிப்டிங் மொழியாக இணையதளங்களில் பயன்படுத்தபட்டது. +இது ஜாவா (java ) வில் உருவாக்கபட்ட மிகவும் சிக்கலான இணைய செயலிகளுக்கு +உதவும் முகமாக உருவாக்கபட்டது. எனினும் இணையதள பக்கங்களில் இதன் முழுதான பயன்பாடு +மற்றும் உலாவிகளில் பயன்படுத்த கூடிய வகையில் இருந்தமையாலும் Java வை விட +இணையதளகளின் முகப்பு உருவாக்கத்தில் இன்றளவில் முன்னிலை பெற்றுள்ளது. + +உலாவிகளுக்கு மட்டும் மட்டுபடுத்தபடவில்லை , Node.js மூலமாக +மிகவும் பிரபல்யமடைந்து வருகின்றது , உதாரணமாக கூகிள்க்ரோம் உலாவியின் +V8 JavaScript engine Node .js உதவியுடன் இயங்குகிறது . + +உங்கள் கருத்துக்கள் மிகவும் வரவேற்கபடுகின்றன , என்னுடன் தொடர்புகொள்ள +[@adambrenecki](https://twitter.com/adambrenecki), or +[adam@brenecki.id.au](mailto:adam@brenecki.id.au). + +```js +// குறிப்புக்கள் C நிரலாக்கத்தை ஒத்தது .ஒரு வரி குறிப்புக்கள் "//" குறியீடுடன் ஆரம்பமாகும் + +/* பலவரி குறிப்புக்கள் "/*" ஆரம்பமாகி "/*" இல் முடிவடையும் */ + +// ஒரு கூற்று முற்றுபெற செய்ய ; இடல் வேண்டும் . +doStuff(); + +// ...ஆனால் அரைபுள்ளி இட வேண்டும் என்று அவசியம் இல்லை ஏன் எனில் +// ஒரு வரி புதிதாக இடப்படும் போது அரைபுள்ளிகள் தானாகவே இடப்படும் ஆனால் சில தருணங்களை தவிர . +doStuff() + +// ஆனால் அவ்வாறான தருணங்கள் எதிர்பாராத முடிவுகளை தரலாம் + +// எனவே நாம் தொடர்ந்து ஒரு கூற்று நிறைவடையும் போது அரைபுள்ளி ஒன்றை இடுவோம் . + +/////////////////////////////////// +// 1. எண்கள்(Number) ,சரம் (String),செயற்குறிகள்(Operators) + +// JavaScript ஒரே ஒரு எண்வகை காணப்படுகிறது தசமி (which is a 64-bit IEEE 754 double). +// தசமி எண்வகை (Doubles) 2^ 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 + + +//bitwise பொறிமுறையை உபயோகிக்கும் போது +//உங்கள் தசம எண்ணின் பெறுமானமானது ஒரு நேர் அல்லது மறை அல்லது பூசியமாகவுள்ள முழு எண்ணாக +//மாற்றம் பெறுகிறது இது 32 இருமம்(bit) வரை செல்லலாம் + +1 << 2; // = 4 + +// நிரலாக்கத்தில் செயலியை அமுல்படுத்தும் வரிசைமுறையில் அடைப்பு குறிக்கு முன்னிலை வழங்கபடுகிறது +(1 + 3) * 2; // = 8 + +// மெய் எண் அல்லாத மூன்றுபெறுமானங்கள் உள்ளன : +Infinity; // result of e.g. 1/0 +-Infinity; // result of e.g. -1/0 +NaN; // result of e.g. 0/0, இது எண் அல்ல என்பதை குறிக்கும் + +// தர்க ரீதியில் ஆன கட்டமைப்பு காணப்படுகிறது . +true; +false; + +// சரம் (string) ' அல்லது " குறியீட்டினால் உருவாக்கபடுகிறது +'abc'; +"Hello, world"; + +// ஒரு boolean பெறுமானத்தின் எதிர்மறை பெறுமானத்தை பெற ! குறியீடு பயன்படுத்தபடுகிறது +!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 + +// இரண்டு சரங்களை(Strings) ஒன்றாக இணைப்பதற்கு + +"Hello " + "world!"; // = "Hello world!" + +// இரண்டு மாறிகளை/பெறுமானங்களை ஒப்பிட < and > +"a" < "b"; // = true + +// இரண்டு பெறுமானங்கள் / மாறிகள் ஒரேவகையை சேர்ந்தவையா என பார்க்க +"5" == 5; // = true +null == undefined; // = true + +// ...இல்லாவிடின் === +"5" === 5; // = false +null === undefined; // = false + +// ...கிழே உள்ள கூற்றுகள் எதிர்பாராத +வெளியீடுகளை தரலாம் ... +13 + !0; // 14 +"13" + !0; // '13true' + +// ஒரு சரத்தில்(string ) உள்ள எழுத்தை பெற `charAt` +"This is a string".charAt(0); // = 'T' + + +//... ஒரு சரத்தை(string ) சொற்களாக பிரிக்க (substring) `substring +"Hello world".substring(0, 5); // = "Hello" + +// `length` ஒரு சரத்தில்(string) உள்ள சொற்களின் எண்ணிக்கை அல்லது நீளத்தை(length)அறிய +"Hello".length; // = 5 + +// `null` மற்றும் `undefined` இரு பெறுமானங்கள் உள்ளன . +null; // மதிப்பு அற்ற ஒரு பெறுமானத்தை குறிக்கும் +undefined; // பெறுமானம் இன்னும் நிர்ணயிக்க படவில்லை என்பதை குறிக்கும் ( + // `undefined` இருப்பினும் இதுவும் ஒரு பெறுமானமாக கருதபடுகிறது ) + +// ஆகியன தர்க்க ரீதியாக பிழையானவை(false) , மற்றவை யாவும் சரியானவை (true). +// 0 மானது பிழையை (false) குறிக்கும் "0" சரியை (true) குறிக்கும் எனினும் 0 == "0". + +/////////////////////////////////// +// 2. மாறிகள் (Variables),அணிகள் (Arrays) மற்றும் பொருட்கள் (Objects) + +// மாறிகளை உருவாக்க `var ` என்னும் குறியீட்டு சொல் (keyword ) பயன்படுகிறது . +//உருவாக்கப்படும் மாறிகள் எந்த வகையை சார்ந்தன என்பதை JavaScript +//தானாகவே நிர்ணயிக்கும் . மாறிக்கு ஒரு பெறுமானத்தை வழங்க `=` பாவிக்க +var someVar = 5; + +// //நீங்கள் மாறிகளை நிறுவ 'var' குறியீட்டு சொல்லை பயன்படுத்தா விடினும் +//அது தவறில்லை ... +someOtherVar = 10; + +// ...ஆனால் நீங்கள் நிறுவிய மாறி(variable) எல்லா உங்கள் ப்ரோக்ராம் இன் சகல இடங்களிலும் +//அணுக கூடியதாய் அமையும் , இல்லாவிடின் அது ஒரு குறிபிட்ட இடத்திற்கு மட்டும் +//மட்டுபடுத்தபடும் . + +//பெறுமானம் வழங்கபடாத மாறிகளுக்கு ,இயல்பாக/தானாக undefined என்ற பெறுமானம் +//வழங்கப்படும் +var someThirdVar; // = undefined + +// மாறிகளில் கணித செயல்பாடுகளை நடத்த சுருக்கெழுத்து முறைகள் காணப்படுகின்றன : +someVar += 5; // இது someVar = someVar + 5; ஐ ஒத்தது someVar இன் பெறுமானம் இப்போது 10 +someVar *= 10; // someVar இன் பெறுமானம் இப்போது 100 + +//மிகவும் சுருக்கமான சுருகேழுத்து முறை கூட்டல் அல்லது கழித்தல் செயன்முறையை +//மேற்கொள்ள +someVar++; // someVar இன் பெறுமானம் இப்போது is 101 +someVar--; // someVar இன் பெறுமானம் இப்போது 100 + +// அணிகள்(Arrays) எல்லாவகையான பெறுமானங்களையும் உள்ளடக்க கூடியது +var myArray = ["Hello", 45, true]; + +// அணிகள்(Arrays) உறுப்பினர்கள் சதுர அடைப்புக்குறிக்குள் அதன் தான இலக்கத்தை கொண்டு +//அணுகமுடியும் . +// அணிகளில் உள்ள உறுப்புகள் 0 இருந்து ஆரம்பமாகும் . +myArray[1]; // = 45 + +// அணிகள் உள்ள உறுப்புகளை மாற்றமுடியும் அத்துடன் உறுப்புகளின் எண்ணிக்கையும் மாறலாம் . +myArray.push("World"); +myArray.length; // = 4 + +// அணியில்(Array) ஒரு குறிப்பிட்ட இடத்தில உள்ள பெறுமானத்தை மாற்ற . +myArray[3] = "Hello"; + +// JavaScript's பொருள் (objects) அகராதியை ஒத்தன +// ஒழுங்கு படுத்த படாத சேகரிப்பு (collection) ஆகும் இதில் ஒரு சாவியும்(key) +//அதுக்குரிய பெறுமானமும்(value) காணப்படும் . +var myObj = {key1: "Hello", key2: "World"}; + +// விசைகள் சரங்களை, ஆனால் அவர்கள் சரியான என்றால் மேற்கோள் அவசியம் இல்லை +//சாவிகளை உ.ம் : "key" என நிறுவலாம் ஆனால் , மேற்கோள் ஆனது சாவி முன்பே நிறுவபட்டிருப்பின் +//அவசியம் இல்லை +// சாவிகளுக்குரிய பெறுமானங்கள் எந்த வகையாகவும் இருக்கலாம் +var myObj = {myKey: "myValue", "my other key": 4}; + +//பொருள் பண்புகளை சதுர அடைப்புக்குறிக்குள் அதன் சாவியின் பெயரை (key) கொண்டு +//அணுகமுடியும் , +myObj["my other key"]; // = 4 + +// ... அல்லது புள்ளி குறியீட்டை பயன்படுத்தி ,சாவியின் (key is a valid identifier) +//பெயர் மூலம் அணுக முடியும் +myObj.myKey; // = "myValue" + +// பொருட்கள்(ஒப்ஜெக்ட்ஸ்) மாற்றபடகூடியான சாவிகளின் பெறுமதிகளை மாற்ற முடியும் அத்துடன் புதிய +//சாவிகளை(keys) இடவும் முடியும் +myObj.myThirdKey = true; + +//பெறுமதி வரையறுக்கபடாத ஒரு சாவியினை அணுகும் போது +//அது வெளியிடும் பெறுமதி `undefined`. +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. தர்க்கம் மற்றும் கட்டுப்பாட்டு கட்டமைப்பு + +// கீழே காட்டப்பட்டுள்ள தொடரியல் ஜாவா வை ஒத்தது + +// The `if` ஒரு குறித்த தர்க்கம் சரியாயின் +//அல்லது என்ற வடிவமைப்பை +var count = 1; +if (count == 3){ + // count இன் பெறுமானம் 3 சமமா என பார்க்கபடுகிறது +} else if (count == 4){ + // count இன் பெறுமானம் 4க்கு சமமா என பார்க்கபடுகிறது +} else { + // count ஆனது 3 அல்ல 4 அல்ல எனின் +} + +// ஒரு குறிப்பிட்ட ஒப்பீடு உண்மையாக இருக்கும் வரை `while`. +while (true){ + // இந்த இருக்கும் கூற்றுகள் முடிவிலி தடவை மறுபடி செயற்படுத்தப்படும் ! +} + +// while போல் அல்லாது do-while ,அவை ஒரு தடவையேனும் அதனுள் உள்ள கூற்றுகள் செயற்படுத்தபடும் +var input; +do { + input = getInput(); +} while (!isValid(input)) + +// for (loop /சுற்று ) C , ஜாவாவை ஒத்தது +//மாறிக்கு பெறுமானத்தை வழங்கல் , மாறியானது தர்க்கத்தை பூர்த்தி செய்கிறதா என பார்த்தல் , +//சுற்றுக்குள் இருக்கும் கூற்றை செயற்படுதல் + +for (var i = 0; i < 5; i++){ + // இந்த சுற்று 5 தடவைகள் தொடர்ந்து செயற்படுத்தபடும் +} + +//for /In சுற்றுகள் prototype சங்கிலியில் உள்ள சகல காரணிகள் ஊடகவும் செல்லும் +var description = ""; +var person = {fname:"Paul", lname:"Ken", age:18}; +for (var x in person){ + description += person[x] + " "; +} + +//ஒரு பொருளில் (Object) இடப்பட்ட பண்புகளை (properties) கருத்தில் கொள்ளும் போது +//குறிப்பிட்ட பண்புகளை அந்த Object கொண்டுள்ளதா என பார்க்க +var description = ""; +var person = {fname:"Paul", lname:"Ken", age:18}; +for (var x in person){ + if (person.hasOwnProperty(x)){ + description += person[x] + " "; + } +} + +//for /in ஆனது அணியில் உள்ள பண்புகள் ஒழுங்குபடுத்தப்பட்டவிதம் முக்கியம் +//ஆயின் பாவிப்பதை தவிர்க்கவும் ஏனெனில் அது சரியான ஒழுங்கில் +//வெளியீட்டை தரும் என்பது ஐயம் ஆகும் + +// && is logical and, || is logical or +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear"; +} +if (colour == "red" || colour == "blue"){ + // colour is either red or blue +} + +// && and || "short circuit", which is useful for setting default values. +var name = otherName || "default"; + + + +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, Scope and Closures + +// JavaScript இல் functions நிறுவ `function` keyword.பயன்படும் +function myFunction(thing){ + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +//ஒரு பெறுமானத்தை return செய்ய வேண்டும் எனின் இரண்டும் ஒரே வரியில் +//இருக்க வேண்டும் இல்லாவிடின் return ஆனது `undefined ` return செய்யும் +//காற் புள்ளி தானாகவே இடப்படும் , நீங்கள் Allman style உபயோகிக்கும் போது +//அவதானமாக இருக்கவும் +function myFunction() +{ + return // <- semicolon automatically inserted here + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + +// JavaScript functions ஆனது first class objects ஆகும் ,எனவே அவற்றை மாறிகளுக்கு +//assign செய்ய முடியும் அதுமட்டும் அல்லது functions களில் arguments ஆக அனுப்பமுடியும் +// உதாரணமாக ஒரு event handler: +function myFunction(){ + //இந்த code 5 செக்கன்களில் செயற்படுத்தப்படும் +} +setTimeout(myFunction, 5000); +// Note: setTimeout ஆனது ஜாவஸ்க்ரிப்ட் சேர்ந்தது அன்று , ஆனால் அந்த வசதி +//உலாவிகளிலும் ,Node .js காணப்படுகிறது + +// Function objects கட்டாயம் பெயரிடப்பட வீண்டும் என்று அவசியம் இல்லை +// அவை anonymous(பெயரிடப்படாமல்) உருவாக்கபடலாம் +setTimeout(function(){ + //இந்த code 5 செக்கன்களில் செயற்படுத்தப்படும் +}, 5000); + +// JavaScript function ஒரு குறிப்பிட்ட scope(எல்லை) கொண்டுள்ளது ; +//functions தமக்கென ஒரு scope கொண்டுள்ளன . + +if (true){ + var i = 5; +} +i; // = 5 - //இது undefined அல்ல + +// இதன் காரணமாக anonymous functions உடனடியாக செயற்படுத்தபடுகின்றன +//இதன் மூலம் தற்காலிக மாறிகள்(variable) குளோபல் scope +//இற்கு மாறுவதை தவிர்க்கலாம் . +(function(){ + var temporary = 5; + //நாங்கள் ஒரு மாறியை எங்கிருந்தும் அணுக (access) அதை "global object" + //ஒன்றுக்கு வழங்க வேண்டும் உலாவியில் அது எப்போதும் `window` ஆகும் . + //உலாவி அல்லாத சூழலில் (Node.js) வேறு பெயருடன் இருக்கும் + window.permanent = 10; +})(); +temporary; // raises ReferenceError +permanent; // = 10 + +//JavaScript's மிகவும் சக்தி வாய்ந்த ஒரு வசதி closures ஆகும் +//ஒரு function இன்னொரு function உள் உருவாக்கபடின் +//அது உருவாகப்பட்ட function இன் மாறிகளை அணுக முடியும் +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!"; + // Inner functions ஆனது local scope இல் காணப்படும் + //அது `var ` என்ற குறியீட்டு சொல்லால் நிறுவப்படும் + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + //setTimeout ஆனது background இல் இயங்கும் , எனவே sayHelloInFiveSeconds function, + //செயற்பாடு முடிவடைய ,setTimeout ஆனது inner function call செய்யும். + +} +sayHelloInFiveSeconds("Adam"); // //இது ஒரு popup ஐ ஐந்து செக்கன்களில் காட்டும் + +/////////////////////////////////// +// 5. Objects; Constructors and Prototypes பற்றி மேலும் + +// Objects functions ஐ கொண்டிருக்கலாம் +var myObj = { + myFunc: function(){ + return "Hello world!"; + } +}; +myObj.myFunc(); // = "Hello world!" + +//functions ஆனது objects உடன் இணைக்கப்பட்டுள போது அவை object ஐ அணுக முடியும் +//அவை this என்ற குறியீட்டு சொல்லை பயன்படுத்தி இணைக்கபடுகின்றன +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = "Hello world!" + +//எங்கள் function ஆனது தொழிற் படாமல் போகலாம் அது context(அமைப்பு ) of the object call செய்யபடவிடின் +var myFunc = myObj.myFunc; +myFunc(); // = undefined + + +//function ஆனது ஒரு object உக்கு assign செய்யலாம் பிறகு அதை நாம் அணுகமுடியும் +//`this` மூலம் +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" + +//ஒரு function ஒரு அமைப்பை நாம் உருவாக்க முடியும் +//அதை நாம் `call` அல்லது `apply` மூலம் செயல்படுத்த முடியும் + +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" + +//apply செயற்பாட்டளவில் ஒத்தன ,ஆனால் அது array (அணி) argument +//ஆக எடுக்கிறது. + +anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" + +//இது தொடர்ச்சியான arguments ஐ நாம் function ஒன்றுக்குள் pass பண்ண +//வேண்டும் எனில் மிகவும் உபயோகமானது + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +//ஆனால் `call ` ,`apply ` இரண்டும் தற்காலிகமானவை +//அவற்றை நிரந்தரமாக்க bind function ஐ பயன்படுத்தவும் + +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" + +//`bind ` ஐ உபயோகித்து ஒரு function ஐ பகுதியாக apply செய்ய முடியும் + +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + + +//ஒரு function ஐ நாம் new என்ற குறியீட்டு சொல்லை பயன்படுத்தி +//அழைக்கும் போது புதிய object உருவாக்கப்படும் .இவ்வாறான functions +//constructors என அழைக்கப்படும் + +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +//ஒவ்வொரு JavaScript object உம் ஒரு `prototype ` கொண்டுள்ளது +//நீங்கள் object ஒன்றின் ஒரு property ஐ அணுகும் போது +//அந்த property இல்லாவிடின் interpreter ஆனது +//அதன் prototype உள்ளதா என பார்க்கும் + +//JS இன் சில செயலாக்கங்கள் ஒரு object இன் protoype ஐ +//இலகுவாக `__proto__` மூலம் access செய்ய முடியும் . +//இது prototype பாவணை யை இலகுவாக்கினாலும் +//இது சரியான ஒரு முறை அல்ல +var myObj = { + myString: "Hello world!" +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// This works for functions, too. +myObj.myFunc(); // = "hello world!" + +//உங்கள் property prototype இல் இல்லது இருப்பின் , protype இன் +//prototype search செய்யப்படும் +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +//ஒவ்வொரு object உம் அதன் protype க்கும் reference (மேற்கோள் ) ஒன்றை வைத்திருக்கும் +//நாம் ஒரு protype இணை மாற்றினால் அதன் மாற்றங்கள் எல்லா இடத்திலும் (program இல் ) +//பிரதிபலிக்கும் +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + + +//நாம் முன்பு கூறியது போல் `__proto__` பயன்படுத்துவது சரியான முறை அல்ல +//எனவே நாம் ஒரு protype ஐ object இல் உருவாக்க இரண்டு வழிமுறைகள் +//உள்ளன + +// முதல் முறை Object.create இது அண்மையில் அறிமுகம் செய்ய பட்ட ஒன்று +//எனவே சில இடங்களில் இந்த முறை இன்னும் அறிமுகம் ஆகவில்லை + +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + + +// இரண்டாவது முறை , இது சகல இடங்களிலும் வேலைசெய்யும், இது constructors மூலம். +//constructors prototype என்னும் ஒரு காரணியை கொண்டுள்ளது , இது constructor function +//இன் prototype அன்று. ,இது நாம் new என்ற குறியீட்டு சொல்லையும் அந்த constructor உபயோகித்து +//உருவாக்கபடுகிறது + +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function(){ + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 + +// Built-in types like strings and numbers also have constructors that create +// equivalent wrapper objects. +// JavaScript இல் உள்ள strings மற்றும் numbers வகைகளும் constructors கொண்டுள்ளன +//இவை wrapper objects ஐ ஒத்தன + +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + + +//இவை மிக சிறிய அளவில் ஒத்தவை +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // இந்த கூற்றானது செயல்படுத்தபடாது ஏனெனில் ௦ false ஆகும் +} + +// However, the wrapper objects and the regular builtins share a prototype, so +// you can actually add functionality to a string, for instance. + +//இருப்பினும் wrapper objects மற்றும் regular builtins ஆகியன prototype ஒன்றை கொண்டுள்ளன +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// This fact is often used in "polyfilling", which is implementing newer +// features of JavaScript in an older subset of JavaScript, so that they can be +// used in older environments such as outdated browsers. + +//இந்த முறையானது "polyfilling" இல் உபயோகபடுத்தபடுகிறது. +//புதிய சில வசதிகளை JavaScript பழைய JavaScript பிரதிகளில் இல் உருவாக்குகிறது. +//இது பழைய சூழல்களில் உபயோகிகப்படும். + + +//நாங்கள் முன்பு கூறி இருந்தோம் Object.create சில இடங்களில் இந்த முறை இன்னும் +//அறிமுகம் ஆகவில்லை என்று ஆனால் இதை polyfill ஐ பயன்படுத்தி உருவாக்க +//முடியும் + +if (Object.create === undefined){ // don't overwrite it if it exists + Object.create = function(proto){ + // make a temporary constructor with the right prototype + var Constructor = function(){}; + Constructor.prototype = proto; + // then use it to create a new, appropriately-prototyped object + return new Constructor(); + } +} +``` + +## மேலும் JavaScript பற்றி கற்க + +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. + +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) + +[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. + +[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. diff --git a/ta_in/json.html.markdown b/ta_in/json.html.markdown new file mode 100644 index 00000000..d85e0d82 --- /dev/null +++ b/ta_in/json.html.markdown @@ -0,0 +1,86 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] +translators: + - ["Rasendran Kirushan", "https://github.com/kirushanr"] +lang: ta-in +--- + +ஜேசன் ஒரு ஒரு மிக எளிய தரவு உள்மாற்றீட்டு வடிவம் ஆகும். +Learn X in Y Minutes இதுவே மிகவும் இலகுவான பகுதியாக அமைய போகிறது. + + +ஜேசன் இன் எளிமையான கட்டமைப்பில் குறிப்புக்கள் (Comments) இல்லை , எனினும் +பெரும்பாலான பாகுபடுத்திகளில் C - style முறையிலான (`//`, `/* */`) குறிப்புகளை இட முடியும். +சில பாகுபடுத்திகள்(interpreter) குறிப்புகளுக்கு (comments)தொடர்ச்சியாக வரும் + காற்புள்ளியை அனுமதிக்கின்றன (உதாரணமாக ஒரு அணியை (array) அடுத்துவரும் காற்புள்ளி + அல்லது ஒரு பொருளில் (object)உள்ள கடைசி உறுப்பை/சொத்தை( last property) அடுத்து வரும் காற்புள்ளி ) +எனினும் சகல இடங்களிலும் ஜேசன் பயன்படுத்த பட வேண்டும் எனில் மேற்கூறிய குறிப்புகளை தவிர்த்தல் நல்லது .\ + + +ஜேசன் 100% மிக சரியாக அமைவது மட்டும் இன்றி +இலகுவாக புரியக் கூடிய எளிய தரவு உள்மாற்றீட்டு வடிவம் ஆகும். + + +ஜேசன் அனுமதிக்கும் தரவு வகைகள் : சரம் (string),முழு (int),பூலியன் (தர்க ரீதியில் ஆன கட்டமைப்பு), +அணி (array ),கழி (null ),பொருள் (object). + +ஜேசன் அனுமதிக்கும் அல்லது பாவனைக்கு உட்படுத்த கூடிய உலாவிகள் (browsers): +Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4. + +ஜேசனின் கோப்புவகை(filetype) ".json " ஆகும் . + +ஜேசன் உரைக்கான MIME வகை "application/json" ஆகும். +ஜேசன் இல் காணப்படும் பிரதான பின்னடைவு தரவு இனம் இதுவென்று வரையறுக்க +படாமை ஆகும் . + +ஒரு ஜேசன் இன் எளிய கட்டமைப்பு கீழே காட்டப்பட்டுள்ளது + +```json +{ + "key": "ஒரு சாவிக்கு ஒரு பெறுமதி உள்ளது ", + + "keys": "சாவிகள் , மற்றும் பெறுமானங்கள் மேற்கோள் குறிக்குள் இடல் வேண்டும்", + "numbers": 0, + "strings": "Hellø, wørld. எல்லாவகையான unicode உம் அனுமதிக்கப்படும், அத்துடன் \"escaping\".", + "has bools?": true, + "nothingness": null, + + "big number": 1.2e+100, + + "objects": { + "comment": "பெரும்பாலான கட்டமைப்புகள் objects இல் இருந்தே வருகின்றன", + + "array": [0, 1, 2, 3, "array யானது எல்லாவகையான பெறுமானங்களையும் கொண்டிருக்கும்", 5], + + "another object": { + "comment": "இவை ஒன்றுக்குள் இன்னொன்றை எழுத முடியும்" + } + }, + + "silliness": [ + { + "sources of potassium": ["வாழைபழம்"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternative style": { + "comment": "இதை பார்க்கவும்" + , "comma position": "doesn't matter - as long as it's before the value, then it's valid" + , "another comment": "how nice" + }, + + "that was short": "நீங்கள் ஜேசன் பற்றி யாவற்றையும் கற்றுள்ளீர்கள்" +} +``` + diff --git a/ta_in/xml.html.markdown b/ta_in/xml.html.markdown new file mode 100644 index 00000000..a9bfa9cd --- /dev/null +++ b/ta_in/xml.html.markdown @@ -0,0 +1,145 @@ +--- +language: xml +filename: learnxml.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Rasendran Kirushan", "https://github.com/kirushanr"] +lang:in-ta +--- + + +XML ஆனது ஒரு கட்டமைப்பு மொழி ஆகும் இது தகவலை சேமிக்கவும் +தகவலை பரிமாறவும் உருவாக்கபட்டுள்ளது + + +HTML போல் அன்றி , XML ஆனது தகவலை மட்டும் கொண்டு செல்ல்கிறது +* XML வாக்கிய அமைப்பு + + +```xml +<!-- இது ஒரு XML குறிப்பு --> + +<?xml version="1.0" encoding="UTF-8"?> +<bookstore> + <book category="COOKING"> + <title lang="en">Everyday Italian</title> + <author>Giada De Laurentiis</author> + <year>2005</year> + <price>30.00</price> + </book> + <book category="CHILDREN"> + <title lang="en">Harry Potter</title> + <author>J K. Rowling</author> + <year>2005</year> + <price>29.99</price> + </book> + <book category="WEB"> + <title lang="en">Learning XML</title> + <author>Erik T. Ray</author> + <year>2003</year> + <price>39.95</price> + </book> +</bookstore> + + + <!-- + + மேல காட்டப்பட்டுள்ளது ஒரு xml file இன் உதாரணம் ஆகும் + அது metadata உடன் ஆரம்பமாகிறது + XML ஆனது ஒரு மரத்தை போன்ற கட்டமைப்பை ஒத்தது. + இங்கு root node (கொப்பு) `bookstore` இது மூன்று கிளைகள் (child nodes) + கொண்டுள்ளது. இந்த கிளைகள் மேலும் சில கிளைகளை கொண்டு இருக்கலாம் + ஒவொரு node கட்டமைப்பும் ஒரு `<` ஆரம்பாமாகி `>` முடிவடையும் + கிளைகள் இந்த கட்டமைப்புக்கு இடையில் நிறுவப்படும் + --> + + +<!-- +XML இரண்டு வகையான தகவல்களை கொண்டு செல்லக்கூடியது +1- Attributes -> ஒரு கணு(node) பற்றிய metadata +பொதுவாக XML Parser இந்த தகவலை பயன்படுத்தியே தகவலை +சரியான முறையில் சேமிக்க. +இது xml கட்டமைப்பின் ஆரம்பத்தில் உள்ள name="value" +தீர்மானிக்கபடுகிறது. + +2-Elements ->இவற்றில் முற்றிலும் தகவல்களே சேமிக்கபட்டு இருக்கும் +Elements ஒரு `<` ஆரம்பாமாகி `>` முடிவடையும் காணப்படும் + + +--> + +<!-- கிழே உள்ள element இரண்டு பெறுமானங்களை கொண்டுள்ளது --> +<file type="gif" id="4293">computer.gif</file> + + +``` + +* சரியான முறையில் ஒழுகுபடுத்தபட்ட X document + + +ஒரு XML document ஆனது சரியான முறையில் எழுத பட்டிருப்பின் மட்டுமே அது +சிறந்த வகையில் வடிவமைக்கபட்டுள்ளது,எனினும் மேலும் பல கட்டுபாடுகளை +நாம் ஒரு xml document உக்கு இட முடியும் உ.ம்:-DTD மற்றும் XML Schema. + + +ஒரு xml document ஆனது ஒரு வரையறுக்கபட்டிருப்பின் மட்டுமே +அது சரி என கொள்ளப்படும் + + +With this tool, you can check the XML data outside the application logic. +இந்த கருவியை உபயோகித்து xml தகவல்களை சோதிக்க முடியும் + +```xml + +<!-- கீழே bookstore html document இன் எளிமையான வடிவம் + DTD வரையறைகளுடன் +--> + +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE note SYSTEM "Bookstore.dtd"> +<bookstore> + <book category="COOKING"> + <title >Everyday Italian</title> + <price>30.00</price> + </book> +</bookstore> + +<!-- DTD ஆனது பின்வருமாறு அமையும் :--> + +<!DOCTYPE note +[ +<!ELEMENT bookstore (book+)> +<!ELEMENT book (title,price)> +<!ATTLIST book category CDATA "Literature"> +<!ELEMENT title (#PCDATA)> +<!ELEMENT price (#PCDATA)> +]> + + +<!-- DTD ஆனது root node ஐ உருவாக்கிய பின் நிறுவ படுகிறது ,இது ஒன்று அல்லது +ஒன்றிக்கு மேற்பட்ட child node களை எதிர்பார்க்கிறது. + ஒவ்வொரு 'book' உம் கட்டாயமாக ஒரு 'title' , 'price','category', with "Literature" + ஆகிய பெறுமானங்களை கொண்டிருத்தல் அவசியம். +--> + +<!-- DTD ஆனது xml file ஒன்றினுள் உருவாக்கபடுகிறது--> + +<?xml version="1.0" encoding="UTF-8"?> + +<!DOCTYPE note +[ +<!ELEMENT bookstore (book+)> +<!ELEMENT book (title,price)> +<!ATTLIST book category CDATA "Literature"> +<!ELEMENT title (#PCDATA)> +<!ELEMENT price (#PCDATA)> +]> + +<bookstore> + <book category="COOKING"> + <title >Everyday Italian</title> + <price>30.00</price> + </book> +</bookstore> +``` diff --git a/tmux.html.markdown b/tmux.html.markdown index c11da5fc..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 @@ -249,3 +249,7 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | [Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) [Display CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) + +[tmuxinator - Manage complex tmux sessions](https://github.com/tmuxinator/tmuxinator) + + diff --git a/vi-vn/json-vi.html.markdown b/vi-vn/json-vi.html.markdown new file mode 100644 index 00000000..257216ff --- /dev/null +++ b/vi-vn/json-vi.html.markdown @@ -0,0 +1,76 @@ +--- +language: json +filename: learnjson-vi.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] +translators: + - ["Thanh Phan", "https://github.com/thanhpd"] +lang: vi-vn +--- + +Do JSON là một ngôn ngữ trao đổi dữ liệu hết sức đơn giản, đây có thể sẽ là bài +đơn giản nhất của Học X trong Y phút (Learn X in Y Minutes) từ trước tới nay. + +JSON ở dạng thuần túy nhất không có chú thích cho câu lệnh (comment) nào, nhưng +hầu hết các trình phân tích cú pháp (parser) đều chấp nhận chú thích theo phong +cách của ngôn ngữ C (`//`, `/* */`). Một số trình phân tích cú pháp còn chấp +nhận dấu phẩy cuối cùng (vd: một dấu phẩy sau phần tử cuối cùng của một mảng +hoặc sau thuộc tính cuối cùng của một object), nhưng những trường hợp này nên +tránh để có sự tương thích tốt hơn. + +Để phục vụ cho mục đích bài học này, tất cả cú pháp JSON ở đây sẽ đều là 100% hợp lệ. +May mắn thay, chúng cũng tự trình bày cho chính mình mà không cần thêm giải thích. + +Các kiểu dữ liệu được JSON hỗ trợ bao gồm: số (*numbers*), chuỗi kí tự +(*string*), toán tử đúng/sai (*boolean*), mảng (*array*), *object* và *null*. +Các trình duyệt hỗ trợ bao gồm: Mozilla Firefox phiên bản 3.5 trở lên, +Internet Explorer 8 trở lên, Google Chrome, Opera 10 trở lên, Safari 4 trở lên. +Kiểu tệp JSON có dạng ".json". Kiểu MIME (Multipurpose Internet Mail Extensions) +cho JSON là "application/json". Điểm yếu của JSON đó là thiếu các định dạng cho +kiểu dữ liệu cũng như quy chuẩn cú pháp chặt chẽ sử dụng DTD. + +```json +{ + "khóa": "dữ liệu", + + "các khóa": "phải luôn được đặt trong dấu ngoặc kép", + "số": 0, + "chuỗi kí tự": "Xin chàø. Tất cả kí tự unicode đều được chấp nhận, sử dụng với dạng \"kí tự\"." + "có đúng không?": true, + "không có gì": null, + + "số rất lớn": 1.2e+100, + + "objects": { + "chú thích": "Hầu hết các cấu trúc dữ liệu bạn sẽ dùng sẽ sử dụng object.", + + "mảng": [0, 1, 2, 3, "Mảng có thể chứa bất kì thứ gì bên trong.", 5], + + "một object khác": { + "chú thích": "Những thứ này có thể lồng vào nhau, rất tiện." + } + }, + + "ngớ ngẩn": [ + { + "nguồn cung cấp kali": ["chuối"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "phong cách khác": { + "chú thích": "kiểm tra cái này xem!" + , "vị trí dấu phẩy": "không quan trọng - chỉ cần nó ở trước khóa tiếp theo là được" + , "chú thích khác": "tiện phải không" + }, + + "nó rất ngắn": "Và bạn đã xong rồi đấy. Bạn đã biết tất cả những thứ mà JSON có thể cung cấp." +} +``` diff --git a/whip.html.markdown b/whip.html.markdown index 3faee98a..61c301a5 100644 --- a/whip.html.markdown +++ b/whip.html.markdown @@ -2,6 +2,7 @@ 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 @@ -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 @@ -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..b95d6088 100644 --- a/xml.html.markdown +++ b/xml.html.markdown @@ -3,6 +3,7 @@ language: xml filename: learnxml.xml contributors: - ["João Farias", "https://github.com/JoaoGFarias"] + - ["Rachel Stiyer", "https://github.com/rstiyer"] --- XML is a markup language designed to store and transport data. @@ -65,12 +66,12 @@ Unlike HTML, XML does not specify how to display or to format data, it just carr * Well-Formated Document x Validation -A XML document is well-formated if it is syntactically correct. +An XML document is well-formatted if it is syntactically correct. However, it is possible to inject more constraints in the document, using document definitions, such as DTD and XML Schema. -A XML document which follows a document definition is called valid, -regarding that document. +An XML document which follows a document definition is called valid, +in regards to that document. With this tool, you can check the XML data outside the application logic. diff --git a/zfs.html.markdown b/zfs.html.markdown new file mode 100644 index 00000000..74487e35 --- /dev/null +++ b/zfs.html.markdown @@ -0,0 +1,400 @@ +--- +category: tool +tool: zfs +contributors: + - ["sarlalian", "http://github.com/sarlalian"] +filename: LearnZfs.txt +--- + + +[ZFS](http://open-zfs.org/wiki/Main_Page) +is a rethinking of the storage stack, combining traditional file systems as well as volume +managers into one cohesive tool. ZFS has some specific teminology that sets it appart from +more traditional storage systems, however it has a great set of features with a focus on +usability for systems administrators. + + +## ZFS Concepts + +### Virtual Devices + +A VDEV is similar to a raid device presented by a RAID card, there are several different +types of VDEV's that offer various advantages, including redundancy and speed. In general +VDEV's offer better reliability and safety than a RAID card. It is discouraged to use a +RAID setup with ZFS, as ZFS expects to directly manage the underlying disks. + +Types of VDEV's +* stripe (a single disk, no redundancy) +* mirror (n-way mirrors supported) +* raidz + * raidz1 (1-disk parity, similar to RAID 5) + * raidz2 (2-disk parity, similar to RAID 6) + * raidz3 (3-disk parity, no RAID analog) +* disk +* file (not recommended for production due to another filesystem adding unnecessary layering) + +Your data is striped across all the VDEV's present in your Storage Pool, so more VDEV's will +increase your IOPS. + +### Storage Pools + +ZFS uses Storage Pools as an abstraction over the lower level storage provider (VDEV), allow +you to separate the user visable file system from the physcal layout. + +### ZFS Dataset + +ZFS datasets are analagous to traditional filesystems but with many more features. They +provide many of ZFS's advantages. Datasets support [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write) +snapshots, quota's, compression and deduplication. + + +### Limits + +One directory may contain up to 2^48 files, up to 16 exabytes each. A single storage pool +can contain up to 256 zettabytes (2^78) of space, and can be striped across 2^64 devices. A +single host can have 2^64 storage pools. The limits are huge. + + +## Commands + +### Storage Pools + +Actions: +* List +* Status +* Destroy +* Get/Set properties + +List zpools + +```bash +# Create a raidz zpool +$ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 + +# List ZPools +$ zpool list +NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT +zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - + +# List detailed information about a specific zpool +$ zpool list -v zroot +NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT +zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 141G 106G 35.2G - 43% 75% +``` + +Status of zpools + +```bash +# Get status information about zpools +$ zpool status + pool: zroot + state: ONLINE + scan: scrub repaired 0 in 2h51m with 0 errors on Thu Oct 1 07:08:31 2015 +config: + + NAME STATE READ WRITE CKSUM + zroot ONLINE 0 0 0 + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0 + +errors: No known data errors + +# Scrubbing a zpool to correct any errors +$ zpool scrub zroot +$ zpool status -v zroot + pool: zroot + state: ONLINE + scan: scrub in progress since Thu Oct 15 16:59:14 2015 + 39.1M scanned out of 106G at 1.45M/s, 20h47m to go + 0 repaired, 0.04% done +config: + + NAME STATE READ WRITE CKSUM + zroot ONLINE 0 0 0 + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0 + +errors: No known data errors +``` + +Properties of zpools + +```bash + +# Getting properties from the pool properties can be user set or system provided. +$ zpool get all zroot +NAME PROPERTY VALUE SOURCE +zroot size 141G - +zroot capacity 75% - +zroot altroot - default +zroot health ONLINE - +... + +# Setting a zpool property +$ zpool set comment="Storage of mah stuff" zroot +$ zpool get comment +NAME PROPERTY VALUE SOURCE +tank comment - default +zroot comment Storage of mah stuff local +``` + +Remove zpool + +```bash +$ zpool destroy test +``` + + +### Datasets + +Actions: +* Create +* List +* Rename +* Delete +* Get/Set properties + +Create datasets + +```bash +# Create dataset +$ zfs create tank/root/data +$ mount | grep data +tank/root/data on /data (zfs, local, nfsv4acls) + +# Create child dataset +$ zfs create tank/root/data/stuff +$ mount | grep data +tank/root/data on /data (zfs, local, nfsv4acls) +tank/root/data/stuff on /data/stuff (zfs, local, nfsv4acls) + + +# Create Volume +$ zfs create -V zroot/win_vm +$ zfs list zroot/win_vm +NAME USED AVAIL REFER MOUNTPOINT +tank/win_vm 4.13G 17.9G 64K - +``` + +List datasets + +```bash +# List all datasets +$ zfs list +NAME USED AVAIL REFER MOUNTPOINT +zroot 106G 30.8G 144K none +zroot/ROOT 18.5G 30.8G 144K none +zroot/ROOT/10.1 8K 30.8G 9.63G / +zroot/ROOT/default 18.5G 30.8G 11.2G / +zroot/backup 5.23G 30.8G 144K none +zroot/home 288K 30.8G 144K none +... + +# List a specific dataset +$ zfs list zroot/home +NAME USED AVAIL REFER MOUNTPOINT +zroot/home 288K 30.8G 144K none + +# List snapshots +$ zfs list -t snapshot +zroot@daily-2015-10-15 0 - 144K - +zroot/ROOT@daily-2015-10-15 0 - 144K - +zroot/ROOT/default@daily-2015-10-15 0 - 24.2G - +zroot/tmp@daily-2015-10-15 124K - 708M - +zroot/usr@daily-2015-10-15 0 - 144K - +zroot/home@daily-2015-10-15 0 - 11.9G - +zroot/var@daily-2015-10-15 704K - 1.42G - +zroot/var/log@daily-2015-10-15 192K - 828K - +zroot/var/tmp@daily-2015-10-15 0 - 152K - +``` + +Rename datasets + +```bash +$ zfs rename tank/root/home tank/root/old_home +$ zfs rename tank/root/new_home tank/root/home +``` + +Delete dataset + +```bash +# Datasets cannot be deleted if they have any snapshots +zfs destroy tank/root/home +``` + +Get / set properties of a dataset + +```bash +# Get all properties +$ zfs get all zroot/usr/home │157 # Create Volume +NAME PROPERTY VALUE SOURCE │158 $ zfs create -V zroot/win_vm +zroot/home type filesystem - │159 $ zfs list zroot/win_vm +zroot/home creation Mon Oct 20 14:44 2014 - │160 NAME USED AVAIL REFER MOUNTPOINT +zroot/home used 11.9G - │161 tank/win_vm 4.13G 17.9G 64K - +zroot/home available 94.1G - │162 ``` +zroot/home referenced 11.9G - │163 +zroot/home mounted yes - +... + +# Get property from dataset +$ zfs get compression zroot/usr/home +NAME PROPERTY VALUE SOURCE +zroot/home compression off default + +# Set property on dataset +$ zfs set compression=gzip-9 mypool/lamb + +# Get a set of properties from all datasets +$ zfs list -o name,quota,reservation +NAME QUOTA RESERV +zroot none none +zroot/ROOT none none +zroot/ROOT/default none none +zroot/tmp none none +zroot/usr none none +zroot/home none none +zroot/var none none +... +``` + + +### Snapshots + +ZFS snapshots are one of the things about zfs that are a really big deal + +* The space they take up is equal to the difference in data between the filesystem and its snapshot +* Creation time is only seconds +* Recovery is as fast as you can write data. +* They are easy to automate. + +Actions: +* Create +* Delete +* Rename +* Access snapshots +* Send / Receive +* Clone + + +Create snapshots + +```bash +# Create a snapshot of a single dataset +zfs snapshot tank/home/sarlalian@now + +# Create a snapshot of a dataset and its children +$ zfs snapshot -r tank/home@now +$ zfs list -t snapshot +NAME USED AVAIL REFER MOUNTPOINT +tank/home@now 0 - 26K - +tank/home/sarlalian@now 0 - 259M - +tank/home/alice@now 0 - 156M - +tank/home/bob@now 0 - 156M - +... + +Destroy snapshots + +```bash +# How to destroy a snapshot +$ zfs destroy tank/home/sarlalian@now + +# Delete a snapshot on a parent dataset and its children +$ zfs destroy -r tank/home/sarlalian@now + +``` + +Renaming Snapshots + +```bash +# Rename a snapshot +$ zfs rename tank/home/sarlalian@now tank/home/sarlalian@today +$ zfs rename tank/home/sarlalian@now today + +# zfs rename -r tank/home@now @yesterday +``` + +Accessing snapshots + +```bash +# CD Into a snapshot directory +$ cd /home/.zfs/snapshot/ +``` + +Sending and Receiving + +```bash +# Backup a snapshot to a file +$ zfs send tank/home/sarlalian@now | gzip > backup_file.gz + +# Send a snapshot to another dataset +$ zfs send tank/home/sarlalian@now | zfs recv backups/home/sarlalian + +# Send a snapshot to a remote host +$ zfs send tank/home/sarlalian@now | ssh root@backup_server 'zfs recv tank/home/sarlalian' + +# Send full dataset with snapshos to new host +$ zfs send -v -R tank/home@now | ssh root@backup_server 'zfs recv tank/home' +``` + +Cloneing Snapshots + +```bash +# Clone a snapshot +$ zfs clone tank/home/sarlalian@now tank/home/sarlalian_new + +# Promoting the clone so it is no longer dependent on the snapshot +$ zfs promote tank/home/sarlalian_new +``` + +### Putting it all together + +This following a script utilizing FreeBSD, jails and ZFS to automate +provisioning a clean copy of a mysql staging database from a live replication +slave. + +```bash +#!/bin/sh + +echo "==== Stopping the staging database server ====" +jail -r staging + +echo "==== Cleaning up existing staging server and snapshot ====" +zfs destroy -r zroot/jails/staging +zfs destroy zroot/jails/slave@staging + +echo "==== Quiescing the slave database ====" +echo "FLUSH TABLES WITH READ LOCK;" | /usr/local/bin/mysql -u root -pmyrootpassword -h slave + +echo "==== Snapshotting the slave db filesystem as zroot/jails/slave@staging ====" +zfs snapshot zroot/jails/slave@staging + +echo "==== Starting the slave database server ====" +jail -c slave + +echo "==== Cloning the slave snapshot to the staging server ====" +zfs clone zroot/jails/slave@staging zroot/jails/staging + +echo "==== Installing the staging mysql config ====" +mv /jails/staging/usr/local/etc/my.cnf /jails/staging/usr/local/etc/my.cnf.slave +cp /jails/staging/usr/local/etc/my.cnf.staging /jails/staging/usr/local/etc/my.cnf + +echo "==== Setting up the staging rc.conf file ====" +mv /jails/staging/etc/rc.conf.local /jails/staging/etc/rc.conf.slave +mv /jails/staging/etc/rc.conf.staging /jails/staging/etc/rc.conf.local + +echo "==== Starting the staging db server ====" +jail -c staging + +echo "==== Make sthe staging database not pull from the master ====" +echo "STOP SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging +echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging +``` + + +### Additional Reading + +* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) +* [FreeBSD Handbook on ZFS](https://wiki.freebsd.org/ZF://wiki.freebsd.org/ZFS) +* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) +* [Oracle's Tuning Guide](http://www.oracle.com/technetwork/articles/servers-storage-admin/sto-recommended-zfs-settings-1951715.html) +* [OpenZFS Tuning Guide](http://open-zfs.org/wiki/Performance_tuning) +* [FreeBSD ZFS Tuning Guide](https://wiki.freebsd.org/ZFSTuningGuide) |