diff options
76 files changed, 12027 insertions, 261 deletions
diff --git a/HTML-fr.html.markdown b/HTML-fr.html.markdown new file mode 100644 index 00000000..fdde9107 --- /dev/null +++ b/HTML-fr.html.markdown @@ -0,0 +1,115 @@ +--- +language: html +filename: learnhtml-fr.html +contributors: + - ["Christophe THOMAS", "https://github.com/WinChris"] +lang: fr-fr +--- +HTML signifie HyperText Markup Language. +C'est un langage (format de fichiers) qui permet d'écrire des pages internet. +C’est un langage de balisage, il nous permet d'écrire des pages HTML au moyen de balises (Markup, en anglais). +Les fichiers HTML sont en réalité de simple fichier texte. +Qu'est-ce que le balisage ? C'est une façon de hiérarchiser ses données en les entourant par une balise ouvrante et une balise fermante. +Ce balisage sert à donner une signification au texte ainsi entouré. +Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parlons de HTML5. + +**NOTE :** Vous pouvez tester les différentes balises que nous allons voir au fur et à mesure du tutoriel sur des sites comme [codepen](http://codepen.io/pen/) afin de voir les résultats, comprendre, et vous familiariser avec le langage. +Cet article porte principalement sur la syntaxe et quelques astuces. + + +```HTML +<!-- Les commentaires sont entouré comme cette ligne! --> + +<!-- #################### Les balises #################### --> + +<!-- Voici un exemple de fichier HTML que nous allons analyser --> +<!-- Venez voir ce que ça donne --> + +<!doctype html> + <html> + <head> + <title>Mon Site</title> + </head> + <body> + <h1>Hello, world!</h1> + <a href = "http://codepen.io/anon/pen/xwjLbZ">Venez voir ce que ça donne</a> + <p>Ceci est un paragraphe</p> + <p>Ceci est un autre paragraphe</p> + <ul> + <li>Ceci est un item d'une liste non ordonnée (liste à puces)</li> + <li>Ceci est un autre item</li> + <li>Et ceci est le dernier item de la liste</li> + </ul> + </body> + </html> + +<!-- Un fichier HTML débute toujours par indiquer au navigateur que notre page est faite en HTML --> + +<!doctype html> + +<!-- Après ça on commence par ouvrir une balise <html> --> +<html> +</html> +<!-- Et puis on la referme à la fin du fichier avec </html> --> +<!-- après cette balise de fin, plus rien ne doit apparaître. --> + +<!-- À l'intérieur (entre la balise ouvrant et fermante <html></html>), on trouve : --> + +<!-- Un entête (<head> en anglais ; il faut le refermer avec </head>) --> +<!-- L'entête contient des descriptions et informations annexes qui ne sont pas affichées : se sont les métadonnées --> + +<head> + <title>Mon Site</title><!-- La balise <title> permet d'indiquer au navigateur le titre à afficher dans la barre de l'onglet de la fenêtre --> +</head> + +<!-- Après la balise <head>, on trouve la balise <body> --> +<!-- Pour le moment, rien n'est encore affiché dans la fenêtre du navigateur. --> +<!-- Il faut ensuite remplir le corps (balise <body>) avec du contenu --> + +<body> + <h1>Hello, world!</h1> <!-- La balise h1 permet de structurer le texte, c'est un titre --> + <!-- Il exite différents sous-titres à <h1> qui sont hiérarchisés du plus important (h2) au plus précis (h6) --> + <a href = "http://codepen.io/anon/pen/xwjLbZ">Venez voir ce que ça donne</a> <!-- Lien vers la source cible indiqué dans href="" --> + <p>Ceci est un paragraphe </p> <!-- La balise <p> permet d'inclure du texte à la page html --> + <p>Ceci est un autre paragraphe</p> + <ul> <!-- La balise <ul> permet d'introduire une liste à puces --> + <!-- Si on souhaite une liste ordonnée : <ol> liste numérotée, 1. pour le premier élément, 2. pour le second, etc --> + <li>Ceci est un item d'une liste non ordonnée (liste à puces)</li> + <li>Ceci est un autre item</li> + <li>Et ceci est le dernier item de la liste</li> + </ul> +</body> + +<!-- Voilà comment créer un fichier HTML simple --> + +<!-- Mais il est possible d'ajouter encore des balises plus spécifiques --> + +<!-- Pour insérer une image --> +<img src="http://i.imgur.com/XWG0O.gif"/> <!-- On indique la source de l'image dans src="" --> +<!-- La source peut-être un URL ou encore la destination d'un fichier de votre ordinateur --> + +<!-- Il est possible de réaliser des tableaux également --> + +<table> <!-- On ouvre la balise <table> --> + <tr> <!-- <tr> permet de créer une ligne --> + <th>First Header</th> <!-- <th> permet de créer un titre au tableau --> + <th>Second Header</th> + </tr> + <tr> + <td>Première ligne, première cellule</td> <!-- <td> permet de créer une cellule --> + <td>Première ligne, deuxième cellule</td> + </tr> + <tr> + <td>Deuxième ligne, première cellule</td> + <td>Deuxième ligne, deuxième cellule</td> + </tr> +</table> + +## Utilisation + +Le HTML s'écrit dans des fichiers `.html`. + +## En savoir plus + +* [Tutoriel HTML](http://slaout.linux62.org/html_css/html.html) +* [W3School](http://www.w3schools.com/html/html_intro.asp) diff --git a/bash.html.markdown b/bash.html.markdown index 02d7f31e..b1a14bdb 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -11,6 +11,10 @@ contributors: - ["Rahil Momin", "https://github.com/iamrahil"] - ["Gregrory Kielian", "https://github.com/gskielian"] - ["Etan Reisner", "https://github.com/deryni"] + - ["Jonathan Wang", "https://github.com/Jonathansw"] + - ["Leo Rudberg", "https://github.com/LOZORD"] + - ["Betsy Lorton", "https://github.com/schbetsy"] + - ["John Detter", "https://github.com/jdetter"] filename: LearnBash.sh --- @@ -19,6 +23,8 @@ Nearly all examples below can be a part of a shell script or executed directly i [Read more here.](http://www.gnu.org/software/bash/manual/bashref.html) +Another recommened link: [The Command Line Crash Course](http://cli.learncodethehardway.org/book/) + ```bash #!/bin/bash # First line of the script is shebang which tells the system how to execute @@ -54,6 +60,13 @@ echo '$Variable' # its name without $. If you want to use the variable's value, you should use $. # Note that ' (single quote) won't expand the variables! +# Parameter expansion ${ }: +echo ${Variable} +# This is a simple usage of parameter expansion +# Parameter Expansion gets a value from a variable. It "expands" or prints the value +# During the expansion time the value or parameter are able to be modified +# Below are other modifications that add onto this expansion + # String substitution in variables echo ${Variable/Some/A} # This will substitute the first occurrence of "Some" with "A" @@ -68,6 +81,12 @@ echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} # This works for null (Foo=) and empty string (Foo=""); zero (Foo=0) returns 0. # Note that it only returns default value and doesn't change variable value. +# Brace Expansion { } +# Used to generate arbitrary strings +echo {1..10} +echo {a..z} +# This will output the range from the start value to the end value + # Builtin variables: # There are some useful builtin variables, like echo "Last program's return value: $?" @@ -76,6 +95,21 @@ echo "Number of arguments passed to script: $#" echo "All arguments passed to script: $@" echo "Script's arguments separated into different variables: $1 $2..." +# Now that we know how to echo and use variables, +# let's learn some of the other basics of bash! + +# Getting our current directory is available through the command `pwd`. +# `pwd` stands for "print working directory". +# We can also use the builtin variable `$PWD`. +# Observer that the following are equivalent: +echo "I'm in $(pwd)" # execs `pwd` and interpolates output +echo "I'm in $PWD" # interpolates the variable + +# If you get too much output in your terminal, or from a script, the command +# `clear` clears your screen +clear +# Ctrl-L also works for clearing output + # Reading a value from input: echo "What's your name?" read Name # Note that we didn't need to declare a new variable @@ -124,12 +158,37 @@ ls # These commands have options that control their execution: ls -l # Lists every file and directory on a separate line +ls -t # Sort the directory contents by last-modified date (descending) +ls -R # Recursively `ls` this directory and all of its subdirectories # Results of the previous command can be passed to the next command as input. # grep command filters the input with provided patterns. That's how we can list # .txt files in the current directory: ls -l | grep "\.txt" +# Use `cat` to print files to stdout: +cat file.txt + +# We can also read the file using `cat`: +Contents=$(cat file.txt) +echo "START OF FILE\n$Contents\nEND OF FILE" + +# Use `cp` to copy files or directories from one place to another. +# `cp` creates NEW versions of the sources, +# so editing the copy won't affect the original (and vice versa). +# Note that it will overwrite the destination if it already exists. +cp srcFile.txt clone.txt +cp -r srcDirectory/ dst/ # recursively copy + +# Look into `scp` or `sftp` if you plan on exchanging files between computers. +# `scp` behaves very similarly to `cp`. +# `sftp` is more interactive. + +# Use `mv` to move files or directories from one place to another. +# `mv` is similar to `cp`, but it deletes the source. +# `mv` is also useful for renaming files! +mv s0urc3.txt dst.txt # sorry, l33t hackers... + # Since bash works in the context of a current directory, you might want to # run your command in some other directory. We have cd for changing location: cd ~ # change to home directory @@ -138,6 +197,14 @@ cd .. # go up one directory cd /home/username/Documents # change to specified directory cd ~/Documents/.. # still in home directory..isn't it?? +# Use subshells to work across directories +(echo "First, I'm here: $PWD") && (cd someDir; echo "Then, I'm here: $PWD") +pwd # still in first directory + +# Use `mkdir` to create new directories. +mkdir myNewDir +# The `-p` flag causes new intermediate directories to be created as necessary. +mkdir -p myNewDir/with/intermediate/directories # You can redirect command input and output (stdin, stdout, and stderr). # Read from stdin until ^EOF$ and overwrite hello.py with the lines @@ -177,7 +244,9 @@ echo "#helloworld" | cat > output.out echo "#helloworld" | tee output.out >/dev/null # Cleanup temporary files verbosely (add '-i' for interactive) +# WARNING: `rm` commands cannot be undone rm -v output.out error.err output-and-error.log +rm -r tempDir/ # recursively delete # Commands can be substituted within other commands using $( ): # The following command displays the number of files and directories in the @@ -268,10 +337,25 @@ sed -i 's/okay/great/g' file.txt grep "^foo.*bar$" file.txt # pass the option "-c" to instead print the number of lines matching the regex grep -c "^foo.*bar$" file.txt +# Other useful options are: +grep -r "^foo.*bar$" someDir/ # recursively `grep` +grep -n "^foo.*bar$" file.txt # give line numbers +grep -rI "^foo.*bar$" someDir/ # recursively `grep`, but ignore binary files +# perform the same initial search, but filter out the lines containing "baz" +grep "^foo.*bar$" file.txt | grep -v "baz" + # if you literally want to search for the string, # and not the regex, use fgrep (or grep -F) fgrep "foobar" file.txt +# trap command allows you to execute a command when a signal is received by your script. +# Here trap command will execute rm if any one of the three listed signals is received. +trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM + +# `sudo` is used to perform commands as the superuser +$NAME1=$(whoami) +$NAME2=$(sudo whoami) +echo "Was $NAME1, then became more powerful $NAME2" # Read Bash shell builtins documentation with the bash 'help' builtin: help diff --git a/binary-search.html.markdown b/binary-search.html.markdown new file mode 100644 index 00000000..92df4875 --- /dev/null +++ b/binary-search.html.markdown @@ -0,0 +1,63 @@ +--- +category: Algorithms & Data Structures +name: Binary Search +contributors: + - ["Abhishek Jaisingh", "http://github.com/abhishekjiitr"] +--- + +# Binary Search + +## Why Binary Search? + +Searching is one of the prime problems in the domain of Computer Science.Today there are more than 1 trillion searches per year, and we need algorithms that can do that very fastly. Binary search is one of the fundamental algorithms in computer science. In order to explore it, we’ll first build up a theoretical backbone, then use that to implement the algorithm properly. + +## Introduction + +A simple approach to implement search is to do a linear search, but this approach takes a lot of time and this time grows linearly with the amount or number of data points. i.e., start from the leftmost element of arr[] and one by one compare x with each element of arr[], if x matches with an element, return the index. If x doesn’t match with any of elements, return -1. + +``` +Linear Search: O (n) Linear Time + +Binary Search: O ( log(n) ) Logarithmic Time + +``` +``` +def search(arr, x): + + for i in range(len(arr)): + + if arr[i] == x: + return i + + return -1 + +``` +## Binary Search Algorithm + +The basic requirement for binary search to work is that the data to search should be sorted (in any order). +### Algo + +``` +The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Logn). We basically ignore half of the elements just after one comparison. +1) Compare x with the middle element. +2) If x matches with middle element, we return the mid index. +3) Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half. +4) Else (x is smaller) recur for the left half. +Following is Recursive implementation of Binary Search. + +``` + +### Ending Notes + +There is another form of binary search that is very useful. + +## Books + +* [CLRS](https://mitpress.mit.edu/books/introduction-algorithms) +* [Algorithms](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X) +* [Algorithm Design](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651) + +## Online Resources + +* [GeeksforGeeks](http://www.geeksforgeeks.org/the-ubiquitous-binary-search-set-1/) +* [Topcoder Tutorial](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/) diff --git a/c++.html.markdown b/c++.html.markdown index a02e7e5b..5dc1af59 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -6,6 +6,8 @@ contributors: - ["Matt Kline", "https://github.com/mrkline"] - ["Geoff Liu", "http://geoffliu.me"] - ["Connor Waters", "http://github.com/connorwaters"] + - ["Ankush Goyal", "http://github.com/ankushg07"] + - ["Jatin Dhankhar", "https://github.com/jatindhankhar"] lang: en --- @@ -806,8 +808,8 @@ void doSomethingWithAFile(const std::string& filename) // have default comparators, but you can override it. class Foo { public: - int j; - Foo(int a) : j(a) {} + int j; + Foo(int a) : j(a) {} }; struct compareFunction { bool operator()(const Foo& a, const Foo& b) const { @@ -946,7 +948,7 @@ f1 = f2; #include<tuple> -// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members , +// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members, // its elements are accessed by their order in the tuple. // We start with constructing a tuple. @@ -956,10 +958,10 @@ const int maxN = 1e9; const int maxL = 15; auto second = make_tuple(maxN, maxL); -// printing elements of 'first' tuple +// Printing elements of 'first' tuple cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A -// printing elements of 'second' tuple +// Printing elements of 'second' tuple cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 15 // Unpacking tuple into variables @@ -985,6 +987,143 @@ cout << get<0>(concatenated_tuple) << "\n"; // prints: 10 cout << get<3>(concatenated_tuple) << "\n"; // prints: 15 cout << get<5>(concatenated_tuple) << "\n"; // prints: 'A' + +///////////////////// +// Containers +///////////////////// + +// Containers or the Standard Template Library are some predefined templates. +// They manage the storage space for its elements and provide +// member functions to access and manipulate them. + +// Few containers are as follows: + +// Vector (Dynamic array) +// Allow us to Define the Array or list of objects at run time +#include<vector> +vector<Data_Type> Vector_name; // used to initialize the vector +cin >> val; +Vector_name.push_back(val); // will push the value of variable into array + +// To iterate through vector, we have 2 choices: +// Normal looping +for(int i=0; i<Vector_name.size(); i++) +// It will iterate through the vector from index '0' till last index + +// Iterator +vector<Data_Type>::iterator it; // initialize the iteartor for vector +for(it=vector_name.begin(); it!=vector_name.end();++it) + +// For accessing the element of the vector +// Operator [] +var = vector_name[index]; // Will assign value at that index to var + + +// Set +// Sets are containers that store unique elements following a specific order. +// Set is a very useful container to store unique values in sorted order +// without any other functions or code. + +#include<set> +set<int> ST; // Will initialize the set of int data type +ST.insert(30); // Will insert the value 30 in set ST +ST.insert(10); // Will insert the value 10 in set ST +ST.insert(20); // Will insert the value 20 in set ST +ST.insert(30); // Will insert the value 30 in set ST +// Now elements of sets are as follows +// 10 20 30 + +// To erase an element +ST.erase(20); // Will erase element with value 20 +// Set ST: 10 30 +// To iterate through Set we use iterators +set<int>::iterator it; +for(it=ST.begin();it<ST.end();it++) { + cout << *it << endl; +} +// Output: +// 10 +// 30 + +// To clear the complete container we use Container_name.clear() +ST.clear(); +cout << ST.size(); // will print the size of set ST +// Output: 0 + +// NOTE: for duplicate elements we can use multiset + +// Map +// Maps store elements formed by a combination of a key value +// and a mapped value, following a specific order. + +#include<map> +map<char, int> mymap; // Will initalize the map with key as char and value as int + +mymap.insert(pair<char,int>('A',1)); +// Will insert value 1 for key A +mymap.insert(pair<char,int>('Z',26)); +// Will insert value 26 for key Z + +// To iterate +map<char,int>::iterator it; +for (it=mymap.begin(); it!=mymap.end(); ++it) + std::cout << it->first << "->" << it->second << '\n'; +// Output: +// A->1 +// Z->26 + +// To find the value correponsing to a key +it = mymap.find('Z'); +cout << it->second; + +// Output: 26 + + +/////////////////////////////////// +// Logical and Bitwise operators +////////////////////////////////// + +// Most of the operators in C++ are same as in other languages + +// Logical operators + +// C++ uses Short-circuit evaluation for boolean expressions, i.e, the second argument is executed or +// evaluated only if the first argument does not suffice to determine the value of the expression + +true && false // Performs **logical and** to yield false +true || false // Performs **logical or** to yield true +! true // Performs **logical not** to yield false + +// Instead of using symbols equivalent keywords can be used +true and false // Performs **logical and** to yield false +true or false // Performs **logical or** to yield true +not true // Performs **logical not** to yield false + +// Bitwise operators + +// **<<** Left Shift Operator +// << shifts bits to the left +4 << 1 // Shifts bits of 4 to left by 1 to give 8 +// x << n can be thought as x * 2^n + + +// **>>** Right Shift Operator +// >> shifts bits to the right +4 >> 1 // Shifts bits of 4 to right by 1 to give 2 +// x >> n can be thought as x / 2^n + +~4 // Performs a bitwise not +4 | 3 // Performs bitwise or +4 & 3 // Performs bitwise and +4 ^ 3 // Performs bitwise xor + +// Equivalent keywords are +compl 4 // Performs a bitwise not +4 bitor 3 // Performs bitwise or +4 bitand 3 // Performs bitwise and +4 xor 3 // Performs bitwise xor + + ``` Further Reading: diff --git a/cmake.html.markdown b/cmake.html.markdown index e13e7f67..a2c8cc8a 100644 --- a/cmake.html.markdown +++ b/cmake.html.markdown @@ -5,15 +5,15 @@ contributors: filename: CMake --- -CMake it's a cross-platform, open-source build system. This tool will allow you +CMake is a cross-platform, open-source build system. This tool will allow you to test, compile and create packages of your source code. -The problem that CMake tries to solve it's the problem of Makefiles and -Autoconfigure on cross-platform (different make interpreters have different +The problem that CMake tries to solve is the problem of Makefiles and +Autoconfigure on cross-platforms (different make interpreters have different command) and the ease-of-use on linking 3rd party libraries. CMake is an extensible, open-source system that manages the build process in -an operating system and in a compiler-independent manner. Unlike many +an operating system and compiler-independent manner. Unlike many cross-platform systems, CMake is designed to be used in conjunction with the native build environment. Simple configuration files placed in each source directory (called CMakeLists.txt files) are used to generate standard build diff --git a/csharp.html.markdown b/csharp.html.markdown index 8d185462..4c9e8411 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -8,6 +8,7 @@ contributors: - ["Wouter Van Schandevijl", "http://github.com/laoujin"] - ["Jo Pearce", "http://github.com/jdpearce"] - ["Chris Zimmerman", "https://github.com/chriszimmerman"] + - ["Shawn McGuire", "https://github.com/bigbash"] filename: LearnCSharp.cs --- @@ -825,7 +826,7 @@ on a new line! ""Wow!"", the masses cried"; } // Methods can also be static. It can be useful for helper methods - public static bool DidWeCreateEnoughBycles() + public static bool DidWeCreateEnoughBicycles() { // Within a static method, we only can reference static class members return BicyclesCreated > 9000; @@ -947,6 +948,24 @@ on a new line! ""Wow!"", the masses cried"; A.A2(); } } + + // String interpolation by prefixing the string with $ + // and wrapping the expression you want to interpolate with { braces } + public class Rectangle + { + public int Length { get; set; } + public int Width { get; set; } + } + + class Program + { + static void Main(string[] args) + { + Rectangle rect = new Rectangle { Length = 5, Width = 3 }; + Console.WriteLine($"The length is {rect.Length} and the width is {rect.Width}"); + } + } + } // End Namespace ``` diff --git a/css.html.markdown b/css.html.markdown index 5dae06ca..fc07fce4 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -169,6 +169,13 @@ selector { color: transparent; /* equivalent to setting the alpha to 0 */ color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */ color: hsla(0, 100%, 50%, 0.3); /* as hsl percentages with alpha */ + + /* Borders */ + border-width:5px; + border-style:solid; + border-color:red; /* similar to how background-color is set */ + border: 5px solid red; /* this is a short hand approach for the same */ + border-radius:20px; /* this is a CSS3 property */ /* Images as backgrounds of elements */ background-image: url(/img-path/img.jpg); /* quotes inside url() optional */ diff --git a/de-de/java-de.html.markdown b/de-de/java-de.html.markdown new file mode 100644 index 00000000..001c6888 --- /dev/null +++ b/de-de/java-de.html.markdown @@ -0,0 +1,497 @@ +--- +language: java +filename: LearnJavaDe.java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Jakukyo Friel", "http://weakish.github.io"] + - ["Madison Dickson", "http://github.com/mix3d"] + - ["Simon Morgan", "http://sjm.io/"] +translators: + - ["Michael Dähnert", "http://github.com/JaXt0r"] +lang: de-de +--- + +Java ist eine Programmiersprache für vielfältige Aufgaben. Sie ist imperative und objektorientiert. +Oftmals wird sie für Desktop- Webapplikationen sowie als Programmiersprache im Betriebssystem Android verwendet. +[Weitere Informationen \(Englisch\](http://docs.oracle.com/javase/tutorial/java/) + +```java +// Einzeilige Kommentare starten mit // +/* +Mehrzeilige Kommentare sehen so aus. +*/ +/** +JavaDoc Kommentare haben dieses Format. Sie werden verwendet um Klassen, Attribute sowie Methoden zu beschreiben. +*/ + +// Importieren der Klasse ArrayList aus dem Paket java.util +import java.util.ArrayList; +// Importieren aller Klassen innerhalb des Paketes java.security +import java.security.*; + +// Jede .java Datei besteht aus einer äußeren öffentlichen (public) Klasse. +// Der Name der Klasse muss identisch des Dateinamens sein. +public class LearnJavaDe { + + // Ein Programm muss eine main Methode als Eintrittspunkt besitzen. + public static void main (String[] args) { + + // System.out.println() wird zum Schreiben von zeilenweisen Ausgaben verwendet. + System.out.println("Hello World!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Zum Schreiben von Ausgaben ohne Zeilenumbruch wird System.out.print() verwendet. + System.out.print("Hello "); + System.out.print("World"); + + + /////////////////////////////////////// + // Typen & Variablen + /////////////////////////////////////// + + // Zum Deklarieren einer Variable nutze <type> <name> + // Byte - 8-bit vorzeichenbehaftete (signed), binäre Ganzzahl + // (-128 <= byte <= 127) + byte fooByte = 100; + + // Short - 16-bit vorzeichenbehaftete (signed), binäre Ganzzahl + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Integer - 32-bit vorzeichenbehaftete (signed), binäre Ganzzahl + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Long - 64-bit vorzeichenbehaftete (signed), binäre Ganzzahl + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L wird verwendet um zu kennzeichnen, dass ein Variablenwert vom Typ long ist. + // Ohne diesen Buchstaben wird die Zahl automatisch als Integer behandelt. + + // Hinweis: Java besitzt keine vorzeichenlosen (unsigned) Typen. + + // Float - Typ mit einfacher Genauigkeit (Single-precision), 32-bit IEEE 754 Fließkommazahl + float fooFloat = 234.5f; + // f wird verwendet um zu kennzeichnen, dass ein Variablenwert vom Typ float ist; + // Ohne diesen Buchstaben wird die Zahl automatisch als Integer behandelt. + + // Double - Typ mit doppelter Genauigkeit (Double-precision), 64-bit IEEE 754 Fließkommazahl + double fooDouble = 123.4; + + // Boolean - Wahr & Falsch (true & false) + boolean fooBoolean = true; + boolean barBoolean = false; + + // Char - Ein einfacher 16-bit Unicode Buchstabe + char fooChar = 'A'; + + // final Variablen können von einem anderen Objekt nicht erneut zugeordnet werden. + final int HOURS_I_WORK_PER_WEEK = 9001; + + // Zeichenketten (Strings) + String fooString = "My String Is Here!"; + + // \n ist ein Escape Zeichen welcher eine neue Zeile startet. + String barString = "Schreiben auf einer neuen Zeile?\nKein Problem!"; + // \t ist ein Escape Zeichen welcher einen Tab-Zeichen anhängt. + String bazString = "Möchtest du einen Tabulator anhängen?\tKein Problem!"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // Arrays + // Die Arraygröße muss bei Instanziierung entschieden werden. + // Das folgende Format funktioniert bei Deklaration eines Arrays + // <datentyp>[] <variablenname> = new <datentyp>[<arraygröße>]; + // <datentyp> <variablenname>[] = new <datentyp>[<arraygröße>]; + int[] intArray = new int[10]; + String[] stringArray = new String[1]; + boolean boolArray[] = new boolean[100]; + + // Eine weitere Möglichkeit ein Array zu deklarieren & initialisieren. + int[] y = {9000, 1000, 1337}; + String names[] = {"Bob", "John", "Fred", "Juan Pedro"}; + boolean bools[] = new boolean[] {true, false, false}; + + // Indexierung eines Arrays - Zugriff auf ein Element + System.out.println("intArray @ 0: " + intArray[0]); + + // Arrays sind 0-indexiert und veränderbar. + intArray[1] = 1; + System.out.println("intArray @ 1: " + intArray[1]); // => 1 + + // Weitere nennenswerte Typen + // ArrayLists - Ähnlich Arrays, allerdings werden mehr Funktionen geboten, + // ebenso ist die Arraygröße verwänderbar + // LinkedLists - Implementierung einer doppelt verlinkten Liste. + // Alle Operationen funktioneren so, wie es von einer doppelt verlinkten Liste erwartet wird. + // Weitere Informationen: https://de.wikipedia.org/wiki/Liste_(Datenstruktur)#Doppelt_.28mehrfach.29_verkettete_Liste + // Maps - Eine Sammlung von Objekten, welche eine Verknüpfung von Schlüsseln zu Werten (key => value) vornimmt. + // Eine Map kann keine Duplikate enthalten; Jeder Schlüssel kann genau einen Wert beinhalten. + // HashMaps - Diese Klasse nutzt eine Hashtabelle zur Implementierung eines Map Interfaces. + // Dies erlaubt es zur Laufzeit Standardoperationen wie gib (get) und einfügen (insert) + // selbst für große Mengen in einer konstanten Zeit auszuführen (Laufzeitverhalten O(n)). + + /////////////////////////////////////// + // Operatoren + /////////////////////////////////////// + System.out.println("\n->Operatoren"); + + int i1 = 1, i2 = 2; // Kurform zur Deklaration mehrerer Variablen. + + // Arithmetische Operationen sind einfach nutzbar. + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 Nachkommazahl abgeschnitten) + + // Modulo + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Vergleichsoperationen + System.out.println("3 == 2? " + (3 == 2)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // Bitwise Operatoren! + /* + ~ Unäres (unary) bitweise Komplement + << Vorzeichenbehaftete (signed) linke Verschiebung + >> Vorzeichenbehaftete (signed) rechte Verschiebung + >>> Vorzeichenlose (unsigned) linke Verschiebung + & Bitweise UND (AND) + ^ Bitweise exklusive ODER (OR) + | Bitweise inklusive ODER (OR) + */ + + // Inkrementierungen + int i = 0; + System.out.println("\n->Inc/Dec-rementierung"); + // Die ++ und -- operatoren inkrementieren und dekrementieren jeweils um 1. + // Werden sie vor die Variable gesetzt, ink-/dekrementieren sie und geben anschließend ihren Wert zurück. + // Hinter der Variable geben sie ihren Wert zurück und ändern ihn anschließend. + System.out.println(i++); // i = 1, schreibt 0 (post-increment) + System.out.println(++i); // i = 2, schreibt 2 (pre-increment) + System.out.println(i--); // i = 1, schreibt 2 (post-decrement) + System.out.println(--i); // i = 0, schreibt 0 (pre-decrement) + + /////////////////////////////////////// + // Kontrollstrukturen + /////////////////////////////////////// + System.out.println("\n->Kontrollstrukturen"); + + // If Bedingungen sind wie in den C-Sprachen aufgebaut + int j = 10; + if (j == 10){ + System.out.println("Ich wurde geprinted"); + } else if (j > 10) { + System.out.println("Ich nicht"); + } else { + System.out.println("Ich auch nicht"); + } + + // While Schleife + int fooWhile = 0; + while(fooWhile < 100) { + System.out.println(fooWhile); + // Den Zähler inkrementieren + // 100x iterieren, fooWhile 0,1,2...99 + fooWhile++; + } + System.out.println("fooWhile Wert: " + fooWhile); + + // Do While Schleife + int fooDoWhile = 0; + do { + System.out.println(fooDoWhile); + // Den Zähler inkrementieren + // 99x iterieren, fooDoWhile 0->99 + fooDoWhile++; + } while(fooDoWhile < 100); + System.out.println("fooDoWhile Wert: " + fooDoWhile); + + // For Schleife + int fooFor; + // for Schleifenstruktur => for(<start_statement>; <Bedingung>; <Schritt>) + for (fooFor = 0; fooFor < 10; fooFor++) { + System.out.println(fooFor); + // 10x iterieren, fooFor 0->9 + } + System.out.println("fooFor Wert: " + fooFor); + + // For Each Schleife + // The for Schleife kann verwendet werden um über Arrays ebenso wie Objekte, + // welche das Interface Iterable implementieren zu iterieren. + int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + // for each Schleifenstruktur => for (<Objekt> : <iterable>) + // Wird gelesen als: Iteriere für jedes Element im Iterable + // Hinweis: Der Objekttyp muss dem Elementtyp des Iterable entsprechen. + + for (int bar : fooList) { + System.out.println(bar); + //9x iterieren und die Werte 1-9 auf jeweils einer neuen Zeile schreiben + } + + // Switch Case + // A Schalter (switch) funktioniert mit den Datentypen byte, short, char und int. + // Ebenso kann er für Aufzählungen (Enums) verwendet werden (Enum Typen folgen weiter unten) + // der String Klasse (ab Java SE7) und ein paar spezielle Klassen, welche die primitiven Typen ummanteln (wrap): + // Character, Byte, Short, and Integer. + int monat = 3; + String monatsString; + switch (monat) { + case 1: monatsString = "Januar"; + break; + case 2: monatsString = "Februar"; + break; + case 3: monatsString = "März"; + break; + default: monatsString = "Ein anderer Monat"; + break; + } + System.out.println("Switch Case Ergebnis: " + monatsString); + + // Bedingungsoperator (Conditional Shorthand) + // Der Operator '?' kann für schnelle Zuweisungen oder logische Verzweigungen genutzt werden. + // Er ist wie folgt zu lesen: Wenn die Bedingung wahr ist, nutze <erster Wert> + // ansonsten nutze <zweiter Wert> + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println(bar); // Schreibt A, denn die Bedingung ist wahr. + + + //////////////////////////////////////// + // Typkonvertierung und Type-Casting + //////////////////////////////////////// + + // Konvertierung von Daten + + // Konvertiere String nach Integer + Integer.parseInt("123");// Gibt die Integer Repräsentation von "123" zurück + + // Konvertiere String nach Integer + Integer.toString(123);// Gibt die String Repräsentation von 123 zurück + + // Für andere Konvertierungen sind die folgenden Klassen zu betrachten: + // Double + // Long + // String + + // Tpe-Casting + // Java Objekte können benfalls konvertiert werden, hierbei gibt es vielfältige Konzepte. + // Weitere Informationen finden sich hier (englisch): + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Klassen und Funktionen + /////////////////////////////////////// + + System.out.println("\n->Klassen & Funktionen"); + + // (Die Definition der Klasse Fahrrad folgt) + + // Verwendung einer neuen Klasseninstanz + Fahrrad trek = new Fahrrad(); + + // Aufruf von Methoden des Objektes + trek.erhöheGeschwindigkeit(3); // Es sollten immer getter- und setter- Methoden verwendet werden + trek.setTrittfrequenz(100); + + // toString gibt die StringRepräsentation des Objektes zurück. + System.out.println("trek info: " + trek.toString()); + + } // Ende der Main Methode +} // Ende der LearnJavaDe Klasse + + +// In einer .java-Datei können zusätzliche nicht öffentliche (non-public) äüßere Klassen vorhanden sein. + + +// Syntax der Klassendeklaration: +// <public/private/protected> class <Klassenname> { +// // Es folgen Datenfelder, Konstruktoren, Funktionen. +// // Funktionen werden in Java Methoden genannt. +// } + +class Fahrrad { + + // Felder/Variablen der Klasse Fahrrad + public int trittfrequenz; // Public: Kann von überall her angesprochen werden + private int geschwindigkeit; // Private: Nur innerhalb der Klasse sichtbar + protected int gang; // Protected: Erreichbar innerhalb der Klasse oder Subklassen (sub classes) + String name; // default: Nur innerhalb des Paketes verwendbar + + // Eine Klasse kann mittelst Konstruktoren erstellt werden. + // Das ist ein Konstruktor + public Fahrrad() { + gang = 1; + trittfrequenz = 50; + geschwindigkeit = 5; + name = "Bontrager"; + } + + // Das ist ein Konstruktor mit Argumenten + public Bicycle(int initialTrittfrequenz, int initialGeschwindigkeit, int initialGang, + String name) { + this.gang = initialGang; + this.trittfrequenz = initialTrittfrequenz; + this.geschwindigkeit = initialGeschwindigkeit; + this.name = name; + } + + // Syntax von Methoden (Funktionen): + // <public/private/protected> <Rückgabetyp> <Funktionsname>(<Argumente>) + + // Java Klassen implementieren oftmals getter- und setter-Methoden ihrer Felder + + // Syntax von Methodendeklarationen: + // <Sichtbarkeit> <Rückgabetyp> <Methodenname>(<Argumente>) + public int getTrittfrequenz() { + return tri; + } + + // void Methoden benötigen kein return Statement. + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void erhöheGeschwindigkeit(int increment) { + speed += increment; + } + + public void verringereGeschwindigkeit(int decrement) { + speed -= decrement; + } + + public void setName(String newName) { + name = newName; + } + + public String getName() { + return name; + } + + //Methode zur Darstellung der Attributwerte des Objektes. + @Override + public String toString() { + return "Gang: " + gang + " Trittfrequenz: " + trittfrequenz + " Geschwindigkeit: " + geschwindigkeit + + " name: " + name; + } +} // Ende der Klasse Fahrrad + +// Hochrad ist eine Subklasse von Fahrrad +class Hochrad extends Fahrrad { + // (Hochräder sind Fahrräder mit einem extrem großen Vorderrad. + // Sie haben keine Gänge.) + + public Hochrad(int initialTrittfrequenz, int initialGeschwindigkeit){ + // Aufruf des Vater-Konstruktors (parent constructor) mit dem Wort super. + super(initialTrittfrequenz, initialGeschwindigkeit, 0, "Hochrad"); + } + + // Überschriebene Methoden sollten die Annotation @Override besitzen. + // Mehr zu Annotationen und deren Verwendungszwecken kann hier nachgelesen werden: + // (englisch) http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setGang(int gang) { + gang = 0; + } +} + +// Schnittstellen (Interfaces) +// Interface Deklaration +// <Zugriffsrecht> interface <Name> extends <super-Interface> { +// // Konstanten +// // Methodendeklarationen +// } + +// Beispiel - Nahrung: +public interface Essbar { + public void essen(); // Jede Klasse, die dieses Interface implementiert + // muss auch diese Methode implementieren. +} + + +public interface Verdaulich { + public void verdauen(); +} + + +// Nun können wir eine Klasse erstellen, die beide Interfaces implementiert. +public class Frucht implements Essbar, Verdaulich { + @Override + public void essen() { + // ... + } + + @Override + public void verdauen() { + // ... + } +} + +// Mit Java kann man nur eine Klasse erweitern (extends) jedoch mehrere Interfaces implementieren. +// z.B.: +public class BeispielKlasse extends ParentBeispielKlasse implements InterfaceEins, + InterfaceZwei { + @Override + public void methodeInterfaceEins() { + } + + @Override + public void methodeInterfaceZwei() { + } +} +``` + +## Weitere Informationen (in englisch) + +Die folgenden Links dienen lediglich dazu Verständnis für die Kapitel aufzubauen. +Für tiefergreifende Fragen ist Google der beste Startpunkt. + +**Offizielle Oracle Guides**: + +* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) + +**Online Tutorials** + +* [Learneroo.com - Learn Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Bücher**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Thinking in Java](http://www.mindview.net/Books/TIJ/) + +* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) diff --git a/de-de/python3-de.html.markdown b/de-de/python3-de.html.markdown new file mode 100644 index 00000000..ef1786c8 --- /dev/null +++ b/de-de/python3-de.html.markdown @@ -0,0 +1,655 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["kultprok", "http:/www.kulturproktologie.de"] + - ["matthiaskern", "https://github.com/matthiaskern"] +filename: learnpython3-de.py +lang: de-de +--- + +Anmerkungen des ursprünglichen Autors: +Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen Übersichtlichkeit verliebt. Eigentlich ist es ausführbarer Pseudocode. + +Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service]. + +Hinweis: Dieser Beitrag bezieht sich insplizit auf Python 3. Falls du lieber Python 2.7 lernen möchtest, schau [hier](http://learnxinyminutes.com/docs/python/) weiter. + +```python + +# Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz) + +""" Mehrzeilige Strings werden mit + drei '-Zeichen geschrieben und werden + oft als Kommentare genutzt. +""" + +#################################################### +## 1. Primitive Datentypen und Operatoren +#################################################### + +# Die Zahlen +3 #=> 3 + +# Mathematik funktioniert so, wie man das erwartet +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 + +# Außer Division, welche automatisch Gleitkommazahlen zurückgibt +35 / 5 # => 7.0 + +# Eine Division kann mit "//" für positive sowie negative Werte abgerundet werden. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Benutzt man eine Gleitkommazahl, ist auch das Ergebnis eine solche +3 * 2.0 # => 6.0 + +# Der Rest einer Division +7 % 3 # => 1 + +# Potenz +2**4 # => 16 + +# Rangfolge wird mit Klammern erzwungen +(1 + 3) * 2 #=> 8 + +# Boolesche Ausdrücke sind primitive Datentypen +True +False + +# Mit not wird negiert +not True #=> False +not False #=> True + +# Boolesche Operatoren +# Hinweis: "and" und "or" müssen klein geschrieben werden +True and False #=> False +False or True #=> True + +# Für die Benutzung von Booleschen Operatoren und ganzen Zahlen +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# Gleichheit ist == +1 == 1 #=> True +2 == 1 #=> False + +# Ungleichheit ist != +1 != 1 #=> False +2 != 1 #=> True + +# Ein paar weitere Vergleiche +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Vergleiche können verknüpft werden! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Strings werden mit " oder ' gebildet +"Das ist ein String." +'Das ist auch ein String.' + +# Strings können auch addiert werden! Vermeide dies aber lieber. +"Hallo " + "Welt!" #=> "Hallo Welt!" +# Strings können ohne "+" addiert werden +"Hallo " "welt!" # => "Hallo Welt!" + +# Ein String kann wie eine Liste von Zeichen verwendet werden +"Das ist ein String"[0] #=> 'D' + +# .format kann Strings formatieren +"{} können {} werden".format("Strings", "formatiert") + +# Schneller geht das mit Wiederholungen +"{0} mag Spagetthi, {0} liebt es zu Schwimmen und ganz besonders mag {0} {1}".format("Hans", "Blattsalat") +#=> "Hans mag Spagetthi, Hans liebt es zu Schwimmen und ganz besonders mag Hans Blattsalat" + +# Wir können Schlüsselwörter verwenden, wenn wir nicht abzählen wollen. +"{name} will {food} essen".format(name="Bob", food="Lasagne") +#=> "Bob will Lasagne kochen" + +#Falls dein Python 3 Code auch unter Python 2.5 oder darunter laufen soll, kann das alte Format benutzt werden: +"%s können %s werden" % ("Strings", "interpoliert") + + +# None ist ein Objekt +None #=> None + +# Verwendet nicht das Symbol für Gleichheit `==`, um Objekte mit None zu vergleichen +# Benutzt stattdessen `is`. Dieser Operator testet Objektidentität +"etc" is None #=> False +None is None #=> True + + + +# None, 0, und leere Strings/Listen werden alle als False bewertet. +# Alle anderen Werte sind True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Variablen und Collections +#################################################### + +# Textausgabe ist sehr einfach +print "Ich bin Python. Schön, dich kennenzulernen!" + +# Es gibt keinen Grund, Variablen vor der Zuweisung zu deklarieren. +some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm +some_var #=> 5 + +# Das Ansprechen einer noch nicht deklarierte Variable löst eine Exception aus. +# Unter "Kontrollstruktur" kann noch mehr über +# Ausnahmebehandlung erfahren werden. +some_unknown_var # Löst einen NameError aus + +# Listen speichern Sequenzen +li = [] +# Wir können mit einer bereits gefüllten Liste anfangen +other_li = [4, 5, 6] + +# append fügt Daten am Ende der Liste ein +li.append(1) #li ist jetzt [1] +li.append(2) #li ist jetzt [1, 2] +li.append(4) #li ist jetzt [1, 2, 4] +li.append(3) #li ist jetzt [1, 2, 4, 3] +# Vom Ende der Liste mit pop entfernen +li.pop() #=> 3 und li ist jetzt [1, 2, 4] +# und dann wieder hinzufügen +li.append(3) # li ist jetzt wieder [1, 2, 4, 3]. + +# Greife auf Listen wie auf Arrays zu +li[0] #=> 1 +# Das letzte Element ansehen +li[-1] #=> 3 + +# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError +li[4] # Verursacht einen IndexError + +# Wir können uns Ranges mit Slice-Syntax ansehen +li[1:3] #=> [2, 4] +# Den Anfang auslassen +li[2:] #=> [4, 3] +# Das Ende auslassen +li[:3] #=> [1, 2, 4] +# Jeden Zweiten Eintrag auswählen +li[::2] # =>[1, 4] +# Eine umgekehrte Kopie zurückgeben +li[::-1] # => [3, 4, 2, 1] +# Jegliche Kombination dieser Syntax machen fortgeschrittene Slices möglich +# li[Start:Ende:Schritt] + +# Ein bestimmtes Element mit del aus der Liste entfernen +del li[2] # li ist jetzt [1, 2, 3] + +# Listen können addiert werden +li + other_li #=> [1, 2, 3, 4, 5, 6] - Hinweis: li und other_li werden in Ruhe gelassen + +# Listen mit extend verknüpfen +li.extend(other_li) # Jetzt ist li [1, 2, 3, 4, 5, 6] + +# Mit in auf Existenz eines Elements prüfen +1 in li #=> True + +# Die Länge der Liste mit len ermitteln +len(li) #=> 6 + + +# Tupel sind wie Listen, nur unveränderlich. +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Löst einen TypeError aus + +# Wir können all diese Listen-Dinge auch mit Tupeln anstellen +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Wir können Tupel (oder Listen) in Variablen entpacken +a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3 +# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen +d, e, f = 4, 5, 6 +# Es ist kinderleicht zwei Werte zu tauschen +e, d = d, e # d is now 5 and e is now 4 + + +# Dictionarys (Wörterbucher) speichern Schlüssel-Werte-Paare +empty_dict = {} +# Hier ein gefülltes Wörterbuch +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Wir können Einträge mit [] nachschlagen +filled_dict["one"] #=> 1 + +# So holen wir alle Keys (Schlüssel) als Liste +list(filled_dict.keys()) #=> ["three", "two", "one"] +# Hinweis - Die Reihenfolge von Schlüsseln in der Liste ist nicht garantiert. +# Einzelne Resultate können anders angeordnet sein. + +# Alle Values (Werte) als Liste +list(filled_dict.values()) #=> [3, 2, 1] +# Hinweis - Hier gelten dieselben Einschränkungen für die Reihenfolge wie bei Schlüsseln. + +# Das Vorhandensein eines Schlüssels im Wörterbuch mit "in" prüfen +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Einen nicht vorhandenenen Schlüssel zu suchen, löst einen KeyError aus +filled_dict["four"] # KeyError + +# Mit der get-Methode verhindern wir das +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# Die get-Methode unterstützt auch ein Standardargument, falls der Wert fehlt +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# Die setdefault-Methode ist ein sicherer Weg, ein neues Schlüssel-Wert-Paar anzulegen +filled_dict.setdefault("five", 5) #filled_dict["five"] wird auf 5 gesetzt +filled_dict.setdefault("five", 6) #filled_dict["five"] ist noch immer 5 + +# Einträge zu einem Wörterbuch hinzufügen +filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 # noch ein Weg, Werte hinzuzufügen + +# Schlüssel von einem Wörterbuch entfernen +del filled_dict["one"] # Entfert den Schlüssel "one" + + +# Sets speichern Mengen +empty_set = set() +# Initialisieren wir ein Set mit ein paar Werten +some_set = {1, 1, 2, 2, 3, 4} # some_set ist jetzt {1, 2, 3, 4} + +# Neue Variablen können einer Menge gleichgesetzt werden +filled_set = some_set + +# Mehr Elemente hinzufügen +filled_set.add(5) # filled_set ist jetzt {1, 2, 3, 4, 5} + +# Schnittmengen werden mit & gebildet +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# Mengen werden mit | vereinigt +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# Die Differenz einer Menge mit - bilden +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Auf Vorhandensein von Elementen mit in prüfen +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. Kontrollstruktur und Iteratoren +#################################################### + +# Erstellen wir mal eine Variable +some_var = 5 + +# Hier eine if-Anweisung. Die Einrückung ist in Python wichtig! +# gibt "some_var ist kleiner als 10" aus +if some_var > 10: + print "some_var ist viel größer als 10." +elif some_var < 10: # Dieser elif-Absatz ist optional. + print "some_var ist kleiner als 10." +else: # Das hier ist auch optional. + print "some_var ist tatsächlich 10." + + +""" +For-Schleifen iterieren über Listen +Ausgabe: + hund ist ein Säugetier + katze ist ein Säugetier + maus ist ein Säugetier +""" +for animal in ["hund", "katze", "maus"]: + # Wir können Strings mit format() formatieren + print("{} ist ein Säugetier".format(animal)) + +""" +`range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder +Ausgabe: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +"range(unten, oben)" gibt eine Liste von der unteren Zahl bis zur oberen Zahl aus +Ausgabe: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +While-Schleifen laufen, bis eine Bedingung erfüllt ist. +Ausgabe: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Kurzform für x = x + 1 + +# Ausnahmebehandlung mit einem try/except-Block +try: + # Mit raise wird ein Fehler ausgegeben + raise IndexError("Das hier ist ein Index-Fehler") +except IndexError as e: + pass # Pass ist nur eine no-op. Normalerweise würden wir hier den Fehler klären. +except (TypeError, NameError): + pass # Mehrere Fehler können zusammen geklärt werden, falls erforderlich. +else: # Optional, hinter allen except-Blöcken + print("Keine Probleme!") # Wird nur ausgeführt, wenn keine Ausnahmen aufgetreten sind +finally: # Wird immer ausgeführt + print("Hier können wir Ressourcen aufräumen") + +# alternativ zu einem try/finally Block um Aufzuräumen: +with open("meineDatei.txt") as f: + for line in f: + print(line) + +# Python bietet ein fundamentales Konzept der Iteration. +# Das Objekt, auf das die Interation, also die Wiederholung einer Methode angewandt wird heißt auf Englisch "iterable". +# Die range Method gibt ein solches Objekt aus. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) #=> range(1,10). Dies ist ein "iterable" Objekt. + +# Über dieses können wir auch iterieren +for i in our_iterable: + print(i) # Gibt one, two, three aus + +# Allerdings können wir die einzelnen Elemente nicht mit ihrem index ausgeben +our_iterable[1] # TypeError + +# Ein iterable ist ein Objekt, das weiß wie es einen Iteratoren erschafft. +our_iterator = iter(our_iterable) + +# Unser Iterator ist ein Objekt, das sich merkt, welchen Status es geraden hat während wir durch es gehen. +# Das jeweeils nächste Objekt bekommen wir mit "next()" +next(our_iterator) #=> "one" + +# Es hält den vorherigen Status +next(our_iterator) #=> "two" +next(our_iterator) #=> "three" + +# Nachdem alle Daten ausgegeben worden sind, kommt eine StopIterator Ausnahme zurück +next(our_iterator) # Gibt StopIteration aus + +# Alle Elemente können mit "list()" ausgegeben werden +list(filled_dict.keys()) #=> ["one", "two", "three"] + + + +#################################################### +## 4. Funktionen +#################################################### + +# Mit def neue Funktionen erstellen +def add(x, y): + print "x ist %s und y ist %s" % (x, y) + return x + y # Werte werden mit return zurückgegeben + +# Funktionen mit Parametern aufrufen +add(5, 6) #=> Ausgabe ist "x ist 5 und y ist 6" und gibt 11 zurück + +# Ein anderer Weg des Funktionsaufrufs sind Schlüsselwort-Argumente +add(y=6, x=5) # Schlüsselwörter können in beliebiger Reihenfolge übergeben werden. + +# Wir können Funktionen mit beliebiger Anzahl von # Positionsargumenten definieren +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Wir können auch Funktionen mit beliebiger Anzahl +# Schlüsselwort-Argumenten definieren +def keyword_args(**kwargs): + return kwargs + +# Rufen wir es mal auf, um zu sehen, was passiert +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Wir können beides gleichzeitig machem, wenn wir wollen +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) Ausgabe: + (1, 2) + {"a": 3, "b": 4} +""" + +# Beim Aufruf von Funktionen können wir das Gegenteil von varargs/kwargs machen! +# Wir benutzen dann *, um Tupel auszuweiten, und ** für kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # äquivalent zu foo(1, 2, 3, 4) +all_the_args(**kwargs) # äquivalent zu foo(a=3, b=4) +all_the_args(*args, **kwargs) # äquivalent zu foo(1, 2, 3, 4, a=3, b=4) + + +# Anwendungsbereich von Funktionen +x = 5 + +def setX(num): + # lokale Variable x ist nicht die globale Variable x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # globale Variable x ist jetzt 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python hat First-Class-Funktionen +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Es gibt auch anonyme Funktionen +(lambda x: x > 2)(3) #=> True + +# Es gibt auch Funktionen höherer Ordnung als Built-Ins +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Wir können bei map- und filter-Funktionen auch List Comprehensions einsetzen +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + +#################################################### +## 5. Klassen +#################################################### + +# Wir bilden die Unterklasse eines Objekts, um Klassen zu erhalten. +class Human(object): + + # Ein Klassenattribut. Es wird von allen Instanzen einer Klasse geteilt + species = "H. sapiens" + + # Ein simpler Konstruktor + def __init__(self, name): + # Wir weisen das Argument name dem name-Attribut der Instanz zu + self.name = name + + # Eine Instanzmethode. Alle Methoden erhalten self als erstes Argument. + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Eine Klassenmethode wird von allen Instanzen geteilt. + # Sie werden mit der aufrufenden Klasse als erstem Argument aufgerufen + @classmethod + def get_species(cls): + return cls.species + + # Eine statische Methode wird ohne Klasse oder Instanz aufgerufen + @staticmethod + def grunt(): + return "*grunt*" + + +# Eine Instanz einer Klasse erstellen +i = Human(name="Ian") +print i.say("hi") # gibt "Ian: hi" aus + +j = Human("Joel") +print j.say("hello") #gibt "Joel: hello" aus + +# Rufen wir mal unsere Klassenmethode auf +i.get_species() #=> "H. sapiens" + +# Ändern wir mal das gemeinsame Attribut +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Aufruf der statischen Methode +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Module +#################################################### + +# Wir können Module importieren +import math +print math.sqrt(16) #=> 4 + +# Wir können auch nur spezielle Funktionen eines Moduls importieren +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Wir können auch alle Funktionen eines Moduls importieren +# Warnung: Dies wird nicht empfohlen +from math import * + +# Wir können Modulnamen abkürzen +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Module sind in Python nur gewöhnliche Dateien. Wir +# können unsere eigenen schreiben und importieren. Der Name des +# Moduls ist der Dateiname. + +# Wir können auch die Funktionen und Attribute eines +# Moduls herausfinden. +import math +dir(math) + + +#################################################### +## 7. Fortgeschritten +#################################################### + +# Generatoren helfen um Code schnell und einfach zu schreiben +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Ein Generator erschafft Werte spontan +# Statt alle Werte auf einmal, wird bei jeder Iteration einer erschaffen. +# iteration. Das heißt, Werte größer als 15 werden nicht behandelt. +# Die range-Methode ist auch ein Generator. Im Fall einer Liste von 1-900000000 +# würde das sehr viel Zeit in Anspruch nehmen. +# Wenn wir eine variable mit einem Namen erschaffen wollen, das +# normalerweise mit einem Python - Schlüsselwort kollidieren würde, +# benutzen wir einen Unterstrich nach dem Wort. +range_ = range(1, 900000000) +# Alle Nummern bis zu einem Ergebnis von >=30 werden verdoppelt +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Dekoratoren +# In diesem Beispiel die Methode beg umwickelt say +# Beim Aufruf von beg, say wird aufgerufen +# Falls say_please true ist, ändert sich die ausgegebene Nachricht +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( + +``` + +## Lust auf mehr? + +### Kostenlos online (Englisch) + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) + +### Totholz (Englisch) + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/de-de/sass-de.html.markdown b/de-de/sass-de.html.markdown new file mode 100644 index 00000000..0c14e249 --- /dev/null +++ b/de-de/sass-de.html.markdown @@ -0,0 +1,450 @@ +--- +language: sass +filename: learnsass-de.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] + - ["Sean Corrales", "https://github.com/droidenator"] + - ["Kyle Mendes", "https://github.com/pink401k"] +translators: + - ["Philipp Bochmann", "https://github.com/phbo85"] +lang: de-de +--- +Sass ist eine CSS-erweiternde Sprache, welche Features wie Variablen, Verschachtelung, Mixins und mehr hinzufügt. +Sass (und andere Präprozessoren wie [Less](http://lesscss.org/)) helfen Entwicklern dabei ihren Code wartbar und DRY (Don't Repeat Yourself - wiederhole dich nicht) zu schreiben. + +Sass hat zwei verschiedene Syntax-Optionen. SCSS, mit der gleichen Syntax wie CSS aber mit den zusätzlichen Features von Sass. Oder Sass (die originale Syntax), welche Einrückung statt geschweiften Klammern und Semikolons benutzt. +Dieses Tutorial wurde mit SCSS geschrieben. + +Wenn du bereits mit CSS3 vertraut bist, wirst du dir Sass relativ schnell aneignen. Es bietet keine neuen Styling-Eigenschaft, sondern Werkzeuge mit denen du dein CSS effizienter schreiben kannst und die Wartung viel einfacher machst. + + +```scss + + +//Einzeilige Kommentare werden entfernt, wenn Sass zu CSS kompiliert wird. + +/* Mehrzeilige Kommentare bleiben bestehen. */ + + + +/* Variablen +============================== */ + + + +/* Du kannst einen CSS-Wert (wie eine Farbe) in einer Variable speichern. +Benutze das '$'-Zeichen um eine Variable zu erstellen. */ + +$primary-color: #A3A4FF; +$secondary-color: #51527F; +$body-font: 'Roboto', sans-serif; + +/* Du kannst die Variablen überall in deinem Stylesheet verwenden. +Wenn du nun eine Farbe ändern willst, musst du das nur einmal tun. */ + +body { + background-color: $primary-color; + color: $secondary-color; + font-family: $body-font; +} + +/* Das wird kompiliert zu: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/* Dies ist viel besser wartbar als die Farbe +an jeder Stelle im Stylesheet einzeln ändern zu müssen. */ + + + +/* Mixins +============================== */ + + + +/* Wenn du merkst, dass du den gleichen Code für mehr als ein +Element schreiben musst, kannst du ihn in einem mixin speichern. + +Dazu benutzt du '@mixin' plus einem Namen für dein mixin. */ + +@mixin center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Du kannst das mixin mit '@include' und dem Namen des mixin benutzen. */ + +div { + @include center; + background-color: $primary-color; +} + +/* Das kompiliert zu: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + + +/* Du kannst Mixins benutzen, um shorthand Eigenschaften zu erstellen. */ + +@mixin size($width, $height) { + width: $width; + height: $height; +} + +/* Diese kannst du aufrufen und width und height als Parameter übergeben. */ + +.rectangle { + @include size(100px, 60px); +} + +.square { + @include size(40px, 40px); +} + +/* Compiles to: */ +.rectangle { + width: 100px; + height: 60px; +} + +.square { + width: 40px; + height: 40px; +} + + + +/* Funktionen +============================== */ + + + +/* Sass bietet Funktionen, welche benutzt werden können um eine Reihe + von Aufgaben zu bewältigen. Berücksichtige das Folgende: */ + +/* Funktionen können aufgerufen werden indem du ihren Namen benutzt + und die benötigten Parameter übergibst. */ +body { + width: round(10.25px); +} + +.footer { + background-color: fade_out(#000000, 0.25) +} + +/* Kompiliert: */ + +body { + width: 10px; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* Du kannst auch deine eigenen Funktionen definieren. Funktionen ähneln + Mixins. Wenn du zwischen Funktionen und Mixins auswählen musst, denke + daran, dass Mixins am besten zur Generierung von CSS eignen, während + Funktionen besser für Logik in deinem Sass Code genutzt werden. Die + Beispiele mit in der Sektion "Mathematische Operatoren" sind ideale + Kandidaten für wiederverwendbare Funktionen. */ + +/* Diese Funktion errechnet den Prozentwert aus target-size und parent-size + und gibt diesen zurück. */ + +@function calculate-percentage($target-size, $parent-size) { + @return $target-size / $parent-size * 100%; +} + +$main-content: calculate-percentage(600px, 960px); + +.main-content { + width: $main-content; +} + +.sidebar { + width: calculate-percentage(300px, 960px); +} + +/* Kompiliert: */ + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + + + +/* Extend (Vererbung) +============================== */ + + + +/* Extend ist ein Weg um Eigenschaften eines Selektoren mit einem anderem + zu teilen. */ + +.display { + @include size(5em, 5em); + border: 5px solid $secondary-color; +} + +.display-success { + @extend .display; + border-color: #22df56; +} + +/* Kompiliert: */ +.display, .display-success { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.display-success { + border-color: #22df56; +} + +/* Aufgrund der Art wie Sass die Klassen zusammen gruppiert, welche + alle das gleiche Grund-Styling haben, ist Extend der Erstellung + eines Mixins vorzuziehen. Wenn dies mit einem Mixin gemacht worden + wäre, würden width, height und border für jedes Element dupliziert + werden, welches das Mixin aufruft. Dies beeinflusst zwar nicht + deinen Workflow, bläht aber die vom Sass-Compiler erzeugten Dateien + unnötige auf. */ + + + +/* Nesting (Verschachtelung) +============================== */ + + + +/* Sass erlaubt es Selektoren in Selektoren zu verschachteln. */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* '&' wird durch den übergeordneten Selektor ersetzt. */ +/* Du kannst auch Pseudo-Klassen verschachteln. */ +/* Denk daran, dass zu viel Verschachtelung deinen Code schlechter + wartbar macht. + Die Best Practices empfehlen nicht mehr als 3 Ebenen zu verschachteln. + Zum Beispiel: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Kompiliert: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/* Partials und Imports +============================== */ + + + +/* Sass erlaubt dir das Erstellen partieller Dateien (partials). + Das hilft dir modularisierten Sass Code zu schreiben. + Partielle Dateien fangen mit einem '_' an, z.B. _reset.css. + Partielle Dateien werden nicht zu CSS generiert. */ + +/* Schau dir folgendes CSS an, was wir in einer Datei namens _reset.css haben */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Mit @import kannst du in Sass partielle Dateien importieren. + Dies unterscheidet sich vom traditionellen CSS @import Statement + welches einen neuen HTTP Request macht, um die zu importierende Datei + zu holen. Sass nimmt die importierte Datei und kombiniert sie mit + dem kompilierten Code. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Kompiliert: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/* Platzhalter Selektoren +============================== */ + + + +/* Platzhalter sind nützlich, um ein CSS Statement zum Erweitern zu + erstellen. Wenn du ein CSS Statement erstellst, welches du ausschließlich + zur Verwendung mit @extend nutzen willst, kannst du das mit einem + Platzhalter tun. Platzhalter fangen mit einem '%' statt einem '.' + oder '#' an und erscheinen nicht im kompilierten CSS. */ + +%content-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + @extend %content-window; + background-color: #0000ff; +} + +/* Kompiliert: */ + +.message-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + background-color: #0000ff; +} + + + +/* Mathematische Operationen +============================== */ + + + +/* Sass bietet die folgenden Operatoren: +, -, *, /, und %. Diese können + nützlich sein, wenn du Werte direkt in Sass berechnen willst, anstatt + vorher manuell errechnete Werte zu verwenden. Unten folgt ein Beispiel + für ein einfaches zweispaltiges Design. */ + +$content-area: 960px; +$main-content: 600px; +$sidebar-content: 300px; + +$main-size: $main-content / $content-area * 100%; +$sidebar-size: $sidebar-content / $content-area * 100%; +$gutter: 100% - ($main-size + $sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: $main-size; +} + +.sidebar { + width: $sidebar-size; +} + +.gutter { + width: $gutter; +} + +/* Compiles to: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + +``` + +## SASS oder Sass? +Hast du dich jemals gefragt, ob Sass ein Akronym ist oder nicht? Hast du wahrscheinlich nicht, aber ich sage es dir trotzdem. Der Name der Sprache ist ein Wort, "Sass", und kein Akronym. +Da die Leute durchgehend "SASS" geschrieben haben, hat der Ersteller der Sprache es scherzhaft "Syntactically Awesome StyleSheets" genannt. + +## Sass üben +Wenn du mit Sass in deinem Browser spielen willst, schau dir [SassMeister](http://sassmeister.com/) an. +Du kannst beide Syntax-Optionen benutzen, gehe einfach in die Einstellungen und wähle entweder Sass oder SCSS. + +## Kompatibilität +Sass kann in jedem Projekt verwendet werden, solange du ein Programm hast, um es in CSS zu kompilieren. +Du solltest verifizieren, dass das CSS, was du verwendest, mit deinen Ziel-Browsern kompatibel ist. + +[QuirksMode CSS](http://www.quirksmode.org/css/) und [CanIUse](http://caniuse.com) sind gute Resourcen um die Kompatibilät zu überpüfen. + + +## Literaturhinweise +* [Offizielle Dokumentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) bietet Tutorials (Anfänger bis Fortgeschritten) und Artikel. diff --git a/dynamic-programming.html.markdown b/dynamic-programming.html.markdown new file mode 100644 index 00000000..95f774bf --- /dev/null +++ b/dynamic-programming.html.markdown @@ -0,0 +1,50 @@ +--- +category: Algorithms & Data Structures +name: Dynamic Programming +contributors: + - ["Akashdeep Goel", "http://github.com/akashdeepgoel"] +--- + +# Dynamic Programming + +## Introduction + +Dynamic Programming is a powerful technique used for solving a particular class of problems as we will see.The idea is very simple, If you have solved a problem with the given input, then save the result for future reference, so as to avoid solving the same problem again. + +Always remember!! +"Those who can't remember the past are condemned to repeat it" + +## Ways of solving such Problems + +1.) Top-Down : Start solving the given problem by breaking it down. If you see that the problem has been solved already, then just return the saved answer. If it has not been solved, solve it and save the answer. This is usually easy to think of and very intuitive. This is referred to as Memoization. + +2.) Bottom-Up : Analyze the problem and see the order in which the sub-problems are solved and start solving from the trivial subproblem, up towards the given problem. In this process, it is guaranteed that the subproblems are solved before solving the problem. This is referred to as Dynamic Programming. + +## Example of Dynamic Programming + +The Longest Increasing Subsequence problem is to find the longest increasing subsequence of a given sequence. Given a sequence S= {a1 , a2 , a3, a4, ............., an-1, an } we have to find a longest subset such that for all j and i, j<i in the subset aj<ai. +First of all we have to find the value of the longest subsequences(LSi) at every index i with last element of sequence being ai. Then largest LSi would be the longest subsequence in the given sequence. To begin LSi is assigned to be one since ai is element of the sequence(Last element). Then for all j such that j<i and aj<ai ,we find Largest LSj and add it to LSi. Then algorithm take O(n2) time. +Pseudo-code for finding the length of the longest increasing subsequence: +This algorithms complexity could be reduced by using better data structure rather than array. Storing predecessor array and variable like largest_sequences_so_far and its index would save a lot time. +Similar concept could be applied in finding longest path in Directed acyclic graph. +--------------------------------------------------------------------------- + for i=0 to n-1 + LS[i]=1 + for j=0 to i-1 + if (a[i] > a[j] and LS[i]<LS[j]) + LS[i] = LS[j]+1 + for i=0 to n-1 + if (largest < LS[i]) + +### Some Famous DP Problems +``` +Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code + +Integer Knapsack Problem - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem + + +Longest Common Subsequence - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence + +## Online Resources + +* [codechef](https://www.codechef.com/wiki/tutorial-dynamic-programming) diff --git a/elixir.html.markdown b/elixir.html.markdown index eb708576..26a547c3 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -3,6 +3,7 @@ language: elixir contributors: - ["Joao Marques", "http://github.com/mrshankly"] - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Ryan Plant", "https://github.com/ryanplant-au"] filename: learnelixir.ex --- @@ -96,6 +97,14 @@ string. lower..upper = 1..10 # Can use pattern matching on ranges as well [lower, upper] #=> [1, 10] +# Maps are key-value pairs +genders = %{"david" => "male", "gillian" => "female"} +genders["david"] #=> "male" + +# Maps with atom keys can be used like this +genders = %{david: "male", gillian: "female"} +genders.gillian #=> "female" + ## --------------------------- ## -- Operators ## --------------------------- @@ -407,6 +416,23 @@ send pid, {:circle, 2} # The shell is also a process, you can use `self` to get the current pid self() #=> #PID<0.27.0> + +## --------------------------- +## -- Agents +## --------------------------- + +# An agent is a process that keeps track of some changing value + +# Create an agent with `Agent.start_link`, passing in a function +# The initial state of the agent will be whatever that function returns +{ok, my_agent} = Agent.start_link(fn -> ["red, green"] end) + +# `Agent.get` takes an agent name and a `fn` that gets passed the current state +# Whatever that `fn` returns is what you'll get back +Agent.get(my_agent, fn colors -> colors end) #=> ["red, "green"] + +# Update the agent's state the same way +Agent.update(my_agent, fn colors -> ["blue" | colors] end) ``` ## References diff --git a/elm.html.markdown b/elm.html.markdown index fa10671f..dab2ab34 100644 --- a/elm.html.markdown +++ b/elm.html.markdown @@ -156,6 +156,7 @@ List.map (\a -> a * 2) [1..4] -- [2, 4, 6, 8] -- You can pattern match in function definitions when there's only one case. -- This function takes one tuple rather than two arguments. +-- This is the way you'll usually unpack/extract values from tuples. area (width, height) = width * height diff --git a/es-es/c-es.html.markdown b/es-es/c-es.html.markdown index 5d3aae0c..8bc1eabb 100644 --- a/es-es/c-es.html.markdown +++ b/es-es/c-es.html.markdown @@ -418,8 +418,18 @@ typedef void (*my_fnp_type)(char *); ## Otras lecturas -Lo mejor que puedes en contrar es una copia de [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language) +Lo mejor que puedes encontrar es una copia de [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language). Es *el* +libro de C, escrito por Dennis Ritchie, creador de C y Brian Kernighan. Aún así, +se cuidadoso, es antiguo, contiene algunas inexactitudes, y algunas prácticas +han cambiado. -Otro buen recurso es [Learn C the hard way](http://c.learncodethehardway.org/book/) +Otro buen recurso es [Learn C the hard way](http://c.learncodethehardway.org/book/). + +Si tienes una pregunta, lee [compl.lang.c Frequently Asked Questions](http://c-faq.com). + +Es muy importante utilizar el espaciado y la sangría apropiados y ser coherente +con su estilo de codificación en general. El código legible es mejor que el +código rápido. Para adoptar un buen estilo de codificación, vea el +[Estilo de codificación del kernel Linux] (https://www.kernel.org/doc/Documentation/CodingStyle). Aparte de eso, Google es tu amigo. diff --git a/es-es/css-es.html.markdown b/es-es/css-es.html.markdown index 31000785..6395f5fd 100644 --- a/es-es/css-es.html.markdown +++ b/es-es/css-es.html.markdown @@ -233,12 +233,21 @@ en todos los navegadores y dispositivos. Pero siempre es vital tener en mente la compatibilidad y disponibilidad del CSS que uses con respecto a los navegadores y dispositivos para los que desarrolles. - [QuirksMode CSS](http://www.quirksmode.org/css/) es una excelente referencia para esto. -## Referencias +## Recursos + +* Para ejecutar un test de compatibilidad, revisa [CanIUse](http://caniuse.com). +* CSS Playground [Dabblet](http://dabblet.com/). +* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS). +* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/). + +## Otras lecturas -* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) -* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/). +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/). +* [QuirksMode CSS](http://www.quirksmode.org/css/). * [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) y [LESS](http://lesscss.org/) para preprocesamiento CSS. +* [CSS-Tricks](https://css-tricks.com). diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown index 4e1e68ba..1a8e275a 100644 --- a/es-es/git-es.html.markdown +++ b/es-es/git-es.html.markdown @@ -398,6 +398,10 @@ $ git rm /directorio/del/archivo/FooBar.c * [tryGit - Una forma entretenida y rapida de aprender Git.](http://try.github.io/levels/1/challenges/1) +* [Udemy tutorial de Git: Una guía completa](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) + +* [Inmersión Git - Una visita guiada caminando a través de los fundamentos de git](http://gitimmersion.com/) + * [git-scm - Video-tutoriales](http://git-scm.com/videos) * [git-scm - Documentacion](http://git-scm.com/book/es) @@ -407,3 +411,9 @@ $ git rm /directorio/del/archivo/FooBar.c * [SalesForce Chuleta](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) * [GitGuys](http://www.gitguys.com/) + +* [Git - La guía simple](http://rogerdudler.github.io/git-guide/index.html) + +* [Pro Git](http://www.git-scm.com/book/en/v2) + +* [Una introducción a Git y Github para principiantes (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) diff --git a/es-es/haskell-es.html.markdown b/es-es/haskell-es.html.markdown new file mode 100644 index 00000000..babb1060 --- /dev/null +++ b/es-es/haskell-es.html.markdown @@ -0,0 +1,437 @@ +--- +language: Haskell +contributors: + - ["Adit Bhargava", "http://adit.io"] +translators: + - ["Jorge Antonio Atempa", "http://www.twitter.com/atempa09"] +filename: haskell-es.md +lang: es-es +--- + +Haskell fue diseñado como lenguaje de programación funcional práctico y puro. Es famoso por sus mónadas y su sistema de tipos, pero siempre regreso a él debido a su elegancia. Haskell hace la codificación una verdadera alegría para mí. + +```haskell +-- Para comentar una sola línea utiliza dos guiones. +{- Para comentar múltiples líneas puedes encerrarlas +en un bloque como este. +-} + +---------------------------------------------------- +-- 1. Tipos de datos primitivos y Operadores +---------------------------------------------------- + +-- Tienes números a tu disposición +3 -- 3 + +-- Matématicas, es lo que esperas +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 +35 / 5 -- 7.0 + +-- Por defecto la división no devuelve un entero +35 / 4 -- 8.75 + +-- Para la división entera utiliza +35 `div` 4 -- 8 + +-- Valores booleanos +True +False + +-- Operaciones booleanas +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- En los ejemplos superiores, `not` es una función que toma un valor. +-- Haskell no necesita paréntisis para las llamadas a funciones...todos los argumentos +-- son enlistados después de la función. Entonces el patrón general es: +-- func arg1 arg2 arg3... +-- Observa la sección de funciones para obtener información de como escribir tu propia función. + +-- Cadenas y caracteres +"Esto es una cadena." +'a' -- caracter +'No puedes utilizar comillas simples para cadenas.' -- ¡error! + +-- Concatenación de cadenas +"¡Hola " ++ "mundo!" -- "¡Hola mundo!" + +-- Una cadena es una lista de caracteres +['H', 'o', 'l', 'a'] -- "Hola" +"Esto es una cadena" !! 0 -- 'E' + + +---------------------------------------------------- +-- Listas y Tuplas +---------------------------------------------------- + +-- Cada elemento en una lista debe ser del mismo tipo. +-- Estas dos listas son iguales: +[1, 2, 3, 4, 5] +[1..5] + +-- Los rangos son versátiles. +['A'..'F'] -- "ABCDEF" + +-- Puedes crear un paso en un rango. +[0,2..10] -- [0, 2, 4, 6, 8, 10] +[5..1] -- Esto no funciona debido a que Haskell incrementa por defecto. +[5,4..1] -- [5, 4, 3, 2, 1] + +-- indexación en una lista +[0..] !! 5 -- 5 + +-- También tienes listas infinitas en Haskell! +[1..] -- una lista de todos los números naturales + +-- Las listas infinitas funcionan porque Haskell tiene "lazy evaluation". Esto significa +-- que Haskell solo evalúa las cosas cuando lo necesita. Así que puedes pedir +-- el elemento 1000 de tú lista y Haskell te devolverá: + +[1..] !! 999 -- 1000 + +-- Y ahora Haskell ha evaluado elementos 1 - 1000 de esta lista...pero el +-- resto de los elementos de esta lista "infinita" ¡no existen todavía! Haskell no lo hará +-- en realidad los evalúa hasta que los necesita. + +-- uniendo dos listas +[1..5] ++ [6..10] + +-- añadiendo a la cabeza de la lista +0:[1..5] -- [0, 1, 2, 3, 4, 5] + +-- más operaciones con listas +head [1..5] -- 1 +tail [1..5] -- [2, 3, 4, 5] +init [1..5] -- [1, 2, 3, 4] +last [1..5] -- 5 + +-- Listas por comprensión +[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] + +-- Listas por comprensión utilizando condicionales +[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] + +-- Cada elemento en una tupla puede ser de diferente tipo, pero una tupla tiene +-- longitud fija. +-- Ejemplo de una tupla: +("haskell", 1) + +-- acceder a los elementos (por ejemplo una tupla de longitud 2) +fst ("haskell", 1) -- "haskell" +snd ("haskell", 1) -- 1 + +---------------------------------------------------- +-- 3. Funciones +---------------------------------------------------- +-- Una función simple que recibe dos variables +add a b = a + b + +-- Nota: Si estas utilizando ghci (el interprete de Haskell) +-- Necesitas utilizar `let`, por ejemplo +-- let add a b = a + b + +-- Utilizando la función +add 1 2 -- 3 + +-- También puedes llamar a la función enmedio de dos argumentos +-- con acentos abiertos: +1 `add` 2 -- 3 + +-- ¡También puedes definir funciones sin tener que utilizar letras! De este modo +-- ¡Tú defines tus propios operadores! Aquí esta un operador que realiza +-- una división entera +(//) a b = a `div` b +35 // 4 -- 8 + +-- Guardas: son una manera fácil para ramificar funciones +fib x + | x < 2 = 1 + | otherwise = fib (x - 1) + fib (x - 2) + +-- La coincidencia de patrones es similar. Aquí hemos dado tres diferentes +-- definiciones para fib. Haskell llamará automáticamente la primer +-- función que coincide con el patrón del valor. +fib 1 = 1 +fib 2 = 2 +fib x = fib (x - 1) + fib (x - 2) + +-- Coincidencia de patrones en tuplas: +foo (x, y) = (x + 1, y + 2) + +-- Coincidencia de patrones en listas. Aquí `x` es el primer elemento +-- en una lista, y `xs` es el resto de la lista. Podemos escribir +-- nuestra propia función map: +myMap func [] = [] +myMap func (x:xs) = func x:(myMap func xs) + +-- Funciones anónimas son creadas con una diagonal invertida seguido de +-- todos los argumentos. +myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] + +-- utilizando pliegues (llamado `inject` en algunos lenguajes) con una función +-- anónima. foldl1 significa pliegue por la izquierda, y usa el primer valor +-- en la lista como el valor inicial para el acumulador. +foldl1 (\acc x -> acc + x) [1..5] -- 15 + +---------------------------------------------------- +-- 4. Más funciones +---------------------------------------------------- + +-- aplicación parcial: si no quieres pasar todos los argumentos a una función, +-- esta es "parcialmente aplicada". Esto significa que retorna una función que toma +-- el resto de los argumentos. + +add a b = a + b +foo = add 10 -- foo es actualmente una función que toma un número y suma 10 a esta +foo 5 -- 15 + +-- Otra manera de escribir los mismo +foo = (+10) +foo 5 -- 15 + +-- composición de funciones +-- el (.) encadena funciones. +-- Por ejemplo, aquí foo es una función que toma un valor. Y se le suma 10, +-- posteriormente multiplica el resultado por 5, y devuelve el resultado final. +foo = (*5) . (+10) + +-- (5 + 10) * 5 = 75 +foo 5 -- 75 + +-- fijación de precedencia +-- Haskell tiene otro operador llamado `$`. Este operador aplica a una función +-- para un parámetro dado. En contraste a la aplicación de función estándar, +-- la cúal tiene prioridad más alta posible de 10 y es asociativa por la izquierda, +-- el operador `$` tiene prioridad de 0 y es asociativa por la derecha. Tal que +-- una baja prioridad significa que la expresión a su derecha es aplicada como parámetro a la función a su izquierda. + +-- antes +even (fib 7) -- false + +-- equivalentemente +even $ fib 7 -- false + +-- composición de funciones +even . fib $ 7 -- false + + +---------------------------------------------------- +-- 5. Firma de tipos +---------------------------------------------------- + +-- Haskell tiene un fuerte sistema de tipado, y cada cosa tiene una firma de tipo. + +-- Algunos tipos básicos: +5 :: Integer +"hola" :: String +True :: Bool + +-- Las funciones tienen muchos tipos. +-- `not` toma un booleano y devuelve un booleano: +-- not :: Bool -> Bool + +-- Aquí, esta función toma dos argumentos: +-- add :: Integer -> Integer -> Integer + +-- Cuando defines un valor, es una buena práctica escribir su tipo en una línea superior: +double :: Integer -> Integer +double x = x * 2 + +---------------------------------------------------- +-- 6. Control de flujo y Expresiones If +---------------------------------------------------- + +-- expressiones if en una sola línea +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- expressiones if en múltiples líneas, la identación es importante +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- expressiones case: Aquí se muestra como analizar los argumentos +-- desde línea de comandos +case args of + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + +-- Haskell no tiene ciclos; en lugar de esto utiliza recursión. +-- map aplica una función sobre cada elemento en un arreglo + +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +-- tú puedes crear una función utilizando map +for array func = map func array + +-- y entonces utilizarla +for [0..5] $ \i -> show i + +-- también podríamos haberlo escrito de esta manera: +for [0..5] show + +-- Puedes utilizar foldl o foldr para reducir una lista +-- foldl <fn> <valor inicial> <lista> +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- Esto es lo mismo que +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- foldl es izquierda, foldr es derecha +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- Esto es los mismo que +(2 * 1 + (2 * 2 + (2 * 3 + 4))) + +---------------------------------------------------- +-- 7. Tipos de datos +---------------------------------------------------- + +-- Por ejemplo, para crear tu propio tipo de dato en Haskell + +data Color = Rojo | Azul | Verde + +-- Ahora puedes utilizarlo en una función: + + +say :: Color -> String +say Rojo = "¡Es Rojo!" +say Azul = "¡Es Azul!" +say Verde = "¡Es Verde!" + +-- Tus tipos de datos pueden tener parámetros también: + +data Maybe a = Nothing | Just a + +-- Estos son todos de tipo Maybe +Just "hello" -- de tipo `Maybe String` +Just 1 -- de tipo `Maybe Int` +Nothing -- de tipo `Maybe a` para cualquier `a` + +---------------------------------------------------- +-- 8. Haskell IO +---------------------------------------------------- + +-- Mientras que IO no puede ser explicado plenamente sin explicar las mónadas, +-- no es difícil explicar lo suficiente para ponerse en marcha. + +-- Cuando un programa en Haskell se ejecuta, `main` es +-- llamado. Este debe devolver un valor de tipo `IO ()`. Por ejemplo: + +main :: IO () +main = putStrLn $ "¡Hola, cielo! " ++ (say Blue) +-- putStrLn tiene tipo String -> IO () + +-- Es más fácil de hacer IO si puedes implementar tu programa como +-- una función de String a String. La función +-- interact :: (String -> String) -> IO () +-- recibe como entrada un texto, ejecuta una función e imprime +-- una salida. + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- Puedes pensar en el valor de tipo `IO ()` como la representación +-- de una secuencia de acciones que la computadora hace, al igual que +-- un programa escrito en un lenguaje imperativo. Podemos utilizar +-- la notación `do` para encadenar acciones. Por ejemplo: + +sayHello :: IO () +sayHello = do + putStrLn "¿Cual es tu nombre?" + name <- getLine -- obtenemos un valor y lo proporcionamos a "name" + putStrLn $ "Hola, " ++ name + +-- Ejercicio: escribe tu propia version de `interact` que solo lea +-- una linea como entrada. + +-- Nunca se ejecuta el código en `sayHello`, sin embargo. La única +-- acción que siempre se ejecuta es el valor de `main`. +-- Para ejecutar `sayHello` comenta la definición anterior de `main` +-- y sustituyela por: +-- main = sayHello + +-- Vamos a entender mejor como funciona la función `getLine` cuando +-- la utilizamos. Su tipo es: +-- getLine :: IO String +-- Puedes pensar en el valor de tipo `IO a` como la representación +-- programa que generará un valor de tipo `a` +-- cuando es ejecutado (además de cualquier otra cosa que haga). Podemos +-- almacenar y reutilizar el valor usando `<-`. También podemos +-- crear nuestra propia acción de tipo `IO String`: + +action :: IO String +action = do + putStrLn "Esta es una linea." + input1 <- getLine + input2 <- getLine + -- El tipo de la sentencia `do` es la de su última línea. + -- `return` no es una palabra clave, sino simplemente una función + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- Podemos usar esto sólo como usabamos `getLine`: + +main'' = do + putStrLn "¡Volveré a repetir dos líneas!" + result <- action + putStrLn result + putStrLn "Esto es todo, ¡amigos!" + +-- El tipo `IO` es un ejemplo de una "mónada". La forma en que Haskell utiliza una monada +-- permite que sea un lenguaje puramente funcional. Cualquier función que +-- interactue con el mundo exterior (por ejemplo usar IO) obtiene una marca `IO` +-- como su firma de tipo. Esto nos permite pensar qué funciones son "puras" +-- (que no interactuan con el mundo exterior o modifican el estado) y que funciones no lo son. + +-- Esta es una poderosa característica, porque es una manera fácil de ejecutar funciones puras +-- concurrentemente; entonces, la concurrencia en Haskell es muy fácil. + + +---------------------------------------------------- +-- 9. El interprete de comandos de Haskell +---------------------------------------------------- + +-- Para comenzar escribe desde la terminal `ghci`. +-- Ahora puede escribir código en Haskell. Para cualquier valor nuevo +-- que necesites crear utiliza `let`: + +let foo = 5 + +-- Puedes inspeccionar el tipo de cualquier valor con `:t`: + +>:t foo +foo :: Integer + +-- Puedes ejecutar acciones de tipo `IO ()` + +> sayHello +¿Cual es tu nombre? +Amigo +Hola, Amigo + +``` + +Existe mucho más de Haskell, incluyendo clases de tipos y mónadas. Estas son +las grandes ideas que hacen a Haskell divertido. Te dejamos un ejemplo final +de Haskell: una implementación del algoritmo QuickSort: + +```haskell +qsort [] = [] +qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater + where lesser = filter (< p) xs + greater = filter (>= p) xs +``` + +Haskell es fácil de instalar. Obtenlo [aquí](http://www.haskell.org/platform/). + +Usted puede encontrar más información en: +[Learn you a Haskell](http://learnyouahaskell.com/) o +[Real World Haskell](http://book.realworldhaskell.org/) o +[Aprende Haskell por el bien de todos](http://aprendehaskell.es/) diff --git a/fr-fr/git-fr.html.markdown b/fr-fr/git-fr.html.markdown new file mode 100644 index 00000000..510459fe --- /dev/null +++ b/fr-fr/git-fr.html.markdown @@ -0,0 +1,583 @@ +--- +category: tool +tool: git +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Leo Rudberg" , "http://github.com/LOZORD"] + - ["Betsy Lorton" , "http://github.com/schbetsy"] + - ["Bruno Volcov", "http://github.com/volcov"] +translators: + - ["Xuan-thi Nguyen", "http://github.com/mellenguyen"] +filename: LearnGit-fr.txt +lang: fr-fr +--- + +Git est un logiciel de contrôle de versions distribué et un système de gestion +du code source. + +Il effectue sa tâche via des séries d'instantanés (snapshots) du projet, et +travaille avec ces instantanés afin de fournir les fonctionnalités de gestion +de version et de code source. + +## Concepts du versionnage + +### Qu'est ce que le contrôle de version ? + +Le contrôle de version est un système qui enregistre les changements faits sur +un ou plusieurs fichiers au fil du temps. + +### Versionnage centralisé VS Versionnage distribué + +* Le contrôle de version centralisé se concentre sur la synchronisation, le +suivi et la sauvegarde des fichiers. +* Le contrôle de version distribué se focalise sur l'échange des changements. +Chaque changement a un identifiant unique. +* Les systèmes distribués n'ont pas de structure définie. Vous pouvez aisément +avoir un système centralisé de type SVN, avec Git. + +[Informations additionnelles](http://git-scm.com/book/fr/v1/D%C3%A9marrage-rapide-%C3%80-propos-de-la-gestion-de-version) + +### Pourquoi utiliser Git ? + +* Fonctionne hors ligne. +* Travailler avec les autres devient facile ! +* Ramifier le travail (créer des branches différentes) est facile ! +* Fusionner le travail est facile ! +* Git est rapide. +* Git est flexible. + +## Architecture Git + + +### Dépôt ("repository") + +Un ensemble de fichiers, dossiers, historiques de modifications, commits +(validations de changements) et de heads (état courant, "tête"). +Représentez-vous ceci comme une structure de données de code source, avec la +particularité que chaque "élement" vous donne, entre autres, accès à son +historique des révisions. + +Un dépôt Git comprend un répertoire .git et "l'arbre de travail" (working tree). + +### Répertoire .git (composant du dépôt) + +Le répertoire .git contient toutes les configurations, logs (journaux), +branches, HEAD et plus. +[Liste détaillée (EN)](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) + +### Arbre de travail (composant du dépôt) + +Il s'agit de l'ensemble des répertoires et fichiers de votre dépôt. Il est +souvent qualifié de répertoire de travail ("working directory"). + +### Index (composant du répertoire .git) + +L'index est la zone de transit ("staging area") dans Git. Il s'agit d'une couche +séparant votre arbre de travail de votre dépôt Git. Ceci donne aux développeurs +plus de pouvoir sur ce qu'ils envoient au dépôt. + +### Commit + +Un "commit" (validation de changements) est un instantané d'un ensemble de +modifications de votre arbre de travail. Par exemple, si vous avez rajouté 5 +fichiers et enlevé 2 autres, ces changements seront contenus dans un commit +(ou "snapshot", instantané). Ce commit peut ensuite être poussé ("pushed") dans +d'autres dépôts, ou non ! + +### Branches + +Une branche consiste essentiellement en un pointeur vers le dernier commit que +vous avez fait. Au fur et à mesure de vos commits, ce pointeur se mettra +automatiquement à jour pour pointer vers le dernier commit. + +### Etiquette ("tag") + +Une étiquette est une marque sur un point spécifique de l'historique. +Typiquement, on utilise cette fonctionnalité pour marquer les états de +publication (v1.0, et ainsi de suite). + +### HEAD and head (composant du répertoire .git) + +HEAD est un pointeur pointant vers la branche courante. Un dépôt ne peut avoir +qu'un seul HEAD *actif*. +head est un pointeur pouvant pointer sur n'importe quel commit. Un dépôt peut +avoir un nombre illimité de heads. + +### Les états dans Git +* Modifié - Des changements on été faits à un fichier mais ce dernier n'a pas +encore été rajouté à l'ensemble des fichiers Git +* Indexé ("staged") - Indique qu'un fichier modifié ira dans le prochain commit +* Validé ("committed") - Les fichiers ont été validés dans l'ensemble de +fichiers + +### Ressources conceptuelles + +* [Git pour les informaticiens (EN)](http://eagain.net/articles/git-for-computer-scientists/) +* [Git pour les designers (EN)](http://hoth.entp.com/output/git_for_designers.html) + + +## Commandes + + +### init + +Créé un dépôt Git vide. Les paramètres du dépôt Git, les informations stockées +et plus sont dans un répertoire (un dossier) nommé ".git". + +```bash +$ git init +``` + +### config + +Configuration des paramètres. Que ce soit pour le dépôt, le système lui-même, +ou la configuration globale (le fichier de configuration globale +est `~/.gitconfig`). + + +```bash +# Lit et assigne quelques variables (globales) de configuration de base +$ git config --global user.email "monEmail@foo.com" +$ git config --global user.name "Mon nom" +``` + +[Apprenez-en plus à propos de git config.](https://git-scm.com/book/fr/v1/Personnalisation-de-Git-Configuration-de-Git) + +### help + +Vous donne un accès rapide à un guide extrêmement détaillé de chaque commande. +Ou juste vous donner un rappel rapide de la sémantique. + +```bash +# Vérifie rapidement les commandes disponibles +$ git help + +# Vérifie toutes les commandes disponibles +$ git help -a + +# Aide pour une commande spécifique - manuel utilisateur +# git help <command_here> +$ git help add +$ git help commit +$ git help init +# ou git <command_here> --help +$ git add --help +$ git commit --help +$ git init --help +``` + +### ignorer des fichiers + +Ne plus suivre certains fichiers et dossiers de Git. +Habituellement fait pour les fichiers privés et temporaires qui seraient, +autrement, partagés dans le dépôt. +```bash +$ echo "temp/" >> .gitignore +$ echo "cle_privee" >> .gitignore +``` + +### status + +Montre les différences entre le fichier indexé (typiquement votre copie/dépôt +de travail) et le HEAD actuel. + + +```bash +# Affiche la branche, les fichiers non suivis, les changements et autres +différences +$ git status + +# Pour en apprendre plus sur git status +$ git help status +``` + +### add + +Rajoute des fichiers à la zone d'index. Si vous ne faites pas `git add` sur les +nouveaux fichiers, ils ne seront pas inclus dans les commits ! + +```bash +# rajoute un fichier dans votre répertoire de travail actuel +$ git add HelloWorld.java + +# rajoute un fichier dans un répertoire imbriqué +$ git add /path/to/file/HelloWorld.c + +# Gestion des expressions régulières ! +$ git add ./*.java +``` + +On ne fait que rajouter des fichiers dans la zone d'index, on ne valide pas +les changements au répertoire/dépôt de travail. + +### branch + +Gère vos branches. Vous pouvez voir, éditer, créer et supprimer des branches en +utilisant cette commande. + +```bash +# Liste les branches existantes et distantes +$ git branch -a + +# Créé une nouvelle branche +$ git branch maNouvelleBranche + +# Supprime une branche +$ git branch -d maBranche + +# Renomme une branche +# git branch -m <anciennom> <nouveaunom> +$ git branch -m nomDeMaBranche nouveauNomDeMaBranche + +# Edite la description d'une branche +$ git branch nomDeMaBranche --edit-description +``` + +### tag + +Gère vos étiquettes + +```bash +# Liste les étiquettes +$ git tag + +# Créé une étiquette annotée +# L'option -m spécifie un message qui sera stockée dans l'étiquette. +# Si vous ne spécifiez pas de message pour une étiquette annotée, +# Git lance votre éditeur pour que vous puissiez le saisir. +$ git tag -a v2.0 -m 'ma version 2.0' + +# Affiche des informations à propos de l'étiquette +# comprenant des informations sur l'auteur, la date du commit correspondant, +# et le message d'annotation avant d'afficher les informations du commit. +$ git show v2.0 + +# Pousse une seule étiquette dans le dépôt distant +$ git push origin v2.0 + +# Pousse beaucoup d'étiquettes dans le dépôt distant +$ git push origin --tags +``` + +### checkout + +Met à jour tous les fichiers dans l'arbre de travail afin de correspondre à la +version de la zone d'index ou de l'arbre spécifié. + +```bash +# Obtenir une copie de travail du dépôt - par défaut on prend la branche master +$ git checkout + +# Bascule vers une branche spéficiée +$ git checkout nomDeLaBranche + +# Créé une nouvelle branche et bascule sur celle-ci +# Revient à faire "git branch <name>; git checkout <name>" +$ git checkout -b nouvelleBranche +``` + +### clone + +Clone (ou copie) un dépôt existant dans un nouveau répertoire. Rajoute +également les branches distantes pour chaque branche du dépôt clôné, ce qui +vous permet de pousser vers une branche distante. + +```bash +# Clone learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git + +# Clone superficiel ("shallow clone") - clone plus rapide qui récupère +seulement le dernier instantané ("snapshot") +$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git + +# Clone seulement une branche spécifique +$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch +``` + +### commit + +Conserve le contenu actuel de la zone d'index dans un nouveau "commit." Ce +commit contient les changements faits, accompagnés d'un message écrit par son +auteur. + +```bash +# Commit avec un message +$ git commit -m "Ajout de la fonction multiplierNombres() dans HelloWorld.c" + +# Rajoute automatiquement dans l'index les fichiers modifiés ou supprimés, +# à l'exception des nouveaux fichiers, puis commit +$ git commit -a -m "Modification de foo.php et suppression de bar.php" + +# Change le dernier commit (ceci supprime le commit précédent avec un +# nouveau commit) +$ git commit --amend -m "Message corrigé" +``` + +### diff + +Montre les différences entre un fichier dans le répertoire de travail, la zone +d'index and les commits. + +```bash +# Affiche les différences entre votre répertoire de travail et l'index +$ git diff + +# Affiche les différences entre l'index et le plus récent commit. +$ git diff --cached + +# Affiche les différences entre votre répertoire de travail et le plus récent +# commit +$ git diff HEAD +``` + +### grep + +Permet de faire une recherche rapide dans le dépôt. + +Configurations optionnelles : + +```bash +# Merci à Travis Jeffery pour ce qui suit +# Affiche les numéros des lignes dans les résultats de la recherche grep +$ git config --global grep.lineNumber true + +# Rend les résultats de recherche plus lisibles, en incluant les groupements +$ git config --global alias.g "grep --break --heading --line-number" +``` + +```bash +# Recherche de "nomDeVariable" dans tous les fichiers java +$ git grep 'nomDeVariable' -- '*.java' + +# Recherche une ligne contenant "nomDeTableau", et "rajouter" ou "enlever" +$ git grep -e 'nomDeTableau' --and \( -e rajouter -e enlever \) +``` + +Google est votre ami; pour plus d'exemples : +[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) + +### log + +Affiche les commits d'un dépôt. + +```bash +# Montre tous les commits +$ git log + +# Montre seulement les messages de commits et leur référence +$ git log --oneline + +# Montre seulement les commits commits des merges (fusions) +$ git log --merges +``` + +### merge + +Fusionne les changements provenant de commits externes dans la branche +courante. + +```bash +# Fusionne la branche spécifiée dans la branche courante. +$ git merge nomDeBranche + +# Génère toujours un commit quand on fusionne +$ git merge --no-ff branchName +``` + +### mv + +Renomme ou déplace un fichier + +```bash +# Renomme un fichier +$ git mv HelloWorld.c HelloNewWorld.c + +# Déplace un fichier +$ git mv HelloWorld.c ./new/path/HelloWorld.c + +# Force le renommage ou le déplacement +# Si "fichierExistant" existe déjà dans le répertoire, il sera écrasé +$ git mv -f monFichier fichierExistant +``` + +### pull + +Récupère la version d'un dépôt et la fusionne avec une autre branche. + +```bash +# Met à jour votre dépôt local en y intégrant les changements +# depuis la branche "master" du dépôt distant "origin". +# git pull <remote> <branch> +$ git pull origin master + +# Par défaut, git pull mettra à jour votre branche actuelle +# en y intégrant les nouveaux changements venant de sa branche distante suivie +$ git pull + +# Intègre les changements de la branche distante et "rebase" +# les commits de la branche dans votre dépôt local, comme ceci: +#"git pull <remote> <branch>, git rebase <branch>" +$ git pull origin master --rebase +``` + +### push + +Pousse et fusionne les changements d'une dépôt local vers une branche distante. + +```bash +# Pousse et fusionne les changements d'un dépôt local vers la branche +# appelée "master" du dépôt distant "master". +# git push <remote> <branch> +$ git push origin master + +# Par défaut, git push poussera et fusionnera les changements de la branche +# courante vers sa branche distante suivie. +$ git push + +# Pour faire le lien entre la branche locale courante et sa branche distante, +# rajouter l'option -u : +$ git push -u origin master +# Dorénavant, à chaque fois que vous voulez pousser depuis cette même branche +# locale, utilisez ce raccourci : +$ git push +``` + +### stash + +Sauvegarde ("stash") l'état actuel de votre espace de travail et le garde dans +pile de changements non finis que vous pouvez réappliquer n'importe quand. + +Supposons que vous avez effectué du travail dans votre dépôt git, mais que vous +voulez récupérer la version de la branche distante. Depuis que vous avez des +changements "malpropres" (non commités) à quelques fichiers, vous ne pouvez pas +faire de `git pull`. A la place, vous pouvez utiliser `git stash` afin de +sauvegarder votre travail dans la pile ! + +```bash +$ git stash +Saved working directory and index state \ + "WIP on master: 049d078 added the index file" + HEAD is now at 049d078 added the index file + (To restore them type "git stash apply") +``` + +Vous pouvez maintenant pull ! + +```bash +git pull +``` +`...changes apply...` + +Vérifiez maintenant que tout est OK + +```bash +$ git status +# On branch master +nothing to commit, working directory clean +``` + +Vous pouvez constater quels "morceaux" vous avez stash jusque là en +utilisant `git stash list`. +Puisque les changements sont gardés dans une pile Last-In-First-Out, notre +changement le plus récent sera en premier. + +```bash +$ git stash list +stash@{0}: WIP on master: 049d078 rajout du fichier index +stash@{1}: WIP on master: c264051 annulation de "rajout de la taille_fichier" +stash@{2}: WIP on master: 21d80a5 ajout des chiffres aux logs +``` + +Appliquons maintenant les changements en les enlevant de notre pile. + +```bash +$ git stash pop +# On branch master +# Changes not staged for commit: +# (use "git add <file>..." to update what will be committed) +# +# modified: index.html +# modified: lib/simplegit.rb +# +``` + +`git stash apply` effectue le même travail + +Vous êtes maintenant prêt à retourner sur vos tâches de travail ! + +[Lecture additionelle.](https://git-scm.com/book/fr/v1/Utilitaires-Git-Le-remisage) + +### rebase (attention) + +Prend tous les changements qui ont été commités sur une branche, et les +ré-applique sur une autre branche. +*Ne rebasez pas les commits que vous avez poussés sur un dépôt publique*. + +```bash +# Expérimentation d'un rebase dans la branche "master" +# git rebase <basebranch> <topicbranch> +$ git rebase master brancheExperience +``` + +[Lecture additionelle.](https://git-scm.com/book/fr/v1/Les-branches-avec-Git-Rebaser) + +### reset (attention) + +Réinitialise le pointeur HEAD courant à l'état spécifié. Ceci vous permet +d'annuler des fusions, des pulls, commits, ajouts et autres. C'est une commande +puissante mais également dangereuse si vous ne savez pas ce que vous faites. + +```bash +# Réinitialise la zone d'index afin de correspondre au dernier commit (laisse +# le répertoire inchangé). +$ git reset + +# Réinitialise la zone d'index afin de correspondre au dernier commit et +# réécrit le répertoire de travail. +$ git reset --hard + +# Déplace le pointeur de la branche courante au commit spécifié (laisse +# le répertoire inchangé). Tous les changements existents toujours dans +# le répertoire. +$ git reset 31f2bb1 + +# Déplace le pointeur de la branche courante en arrière, au commit spécifié +# et fait correspondre le répertoire de travail (supprime les changements +# non commités et tous les commits après le commit spécifié). +$ git reset --hard 31f2bb1 +``` + +### rm + +Le contraire de git add, git rm supprime les fichiers de l'arbre de travail +courant. + +```bash +# Supprime HelloWorld.c +$ git rm HelloWorld.c + +# Enlève un fichier d'un répertoire imbriqué. +$ git rm /chemin/vers/le/fichier/HelloWorld.c +``` + +## Informations complémentaires + +* [tryGit - A fun interactive way to learn Git (EN)](http://try.github.io/levels/1/challenges/1) + +* [Udemy Git Tutorial: A Comprehensive Guide (EN)](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) + +* [git-scm - Tutoriaux vidéos](http://git-scm.com/videos) + +* [git-scm - Documentation](http://git-scm.com/docs) + +* [Atlassian Git - Tutoriaux et Workflows](https://www.atlassian.com/git/) + +* [SalesForce Cheat Sheet (EN)](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) + +* [GitGuys (EN)](http://www.gitguys.com/) + +* [Git - the simple guide (EN)](http://rogerdudler.github.io/git-guide/index.html) + +* [Livre Pro Git](http://www.git-scm.com/book/fr/v1) + +* [Une introduction à Git et GitHub pour les débutants (tutoriel) (EN)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) diff --git a/fr-fr/ruby-ecosystem-fr.html.markdown b/fr-fr/ruby-ecosystem-fr.html.markdown new file mode 100644 index 00000000..9b52069a --- /dev/null +++ b/fr-fr/ruby-ecosystem-fr.html.markdown @@ -0,0 +1,154 @@ +--- +category: tool +tool: ruby ecosystem +contributors: + - ["Jon Smock", "http://github.com/jonsmock"] + - ["Rafal Chmiel", "http://github.com/rafalchmiel"] +translators: + - ["Xuan-thi Nguyen", "http://github.com/mellenguyen"] +lang: fr-fr + +--- + +Les gens utilisant Ruby adoptent généralement un gestionnaire pour installer +différentes versions de Ruby, gérer leurs paquets (ou gems), et gérer les +dépendances des gems. + +## Ruby Managers + +Quelques plateformes possèdent Ruby pré-installé ou disponible en tant que +paquet. La plupart des rubyists ne les utilisent pas, ou si c'est le cas, ne +les utilise que pour faire démarrer un autre installateur ou implémentation de +Ruby. Les rubyists tendent plutôt à installer un manager Ruby pour installer +et changer entre les différentes et nombreuses versions de Ruby et les +environnements de leurs projets Ruby. + +Les gestionnaires d'environnement Ruby les plus populaires sont : + +* [RVM](https://rvm.io/) - Installe et navigue entre les rubies. RVM possède + églement le concept des gemsets pour isoler les environnements de projets + complètement. +* [ruby-build](https://github.com/sstephenson/ruby-build) - Installe seulement + les rubies. Utilisez-le pour un contrôle plus fin des installations des + rubies. +* [rbenv](https://github.com/sstephenson/rbenv) - Navigue seulement entre les + rubies. Utilisé avec ruby-build. Utilisez-le pour un contrôle plus fin des + chargements des rubies. +* [chruby](https://github.com/postmodern/chruby) - Navigue seulement entre les + rubies. Similaire à rbenv. Neutre sur comment les rubies sont installés. + +## Versions de Ruby + +Ruby a été créé par Yukihiro "Matz" Matsumoto, qui reste quelque peu un +[BDFL](https://fr.wikipedia.org/wiki/Benevolent_Dictator_for_Life), bien que +cela soit récemment en changement. Jusqu'à la standardisation du langage en +2011, l'implémentation de référence de Ruby était appelé MRI (Matz' Reference +Implementation). + +Les trois versions majeures de Ruby actuellement utilisées sont : + +* 2.0.0 - Sortie en février 2013. La plupart des librairies et frameworks + gèrent la versions 2.0.0. +* 1.9.3 - Sortie en octobre 2011. Il s'agit de la version que la majorité des + rubyists utilisent actuellement. [Fin de vie](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) +* 1.8.7 - Sortie en juin 2006. [Fin de vie](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). + +Les changements entre 1.8.7 à 1.9.x sont bien plus grands qu'entre 1.9.3 +jusqu'à 2.0.0. Par exemple, les versions 1.9 ont introduit le support des +encodages et d'une VM bytecode ([YARV](https://fr.wikipedia.org/wiki/YARV)). +Il y a toujours des projets sur 1.8.7, mais ils deviennent minoritaires, étant +donné que la majorité de la communauté a migré vers au moins 1.9.2 ou 1.9.3. + +## Implémentations Ruby + +L'écosystème Ruby comprend de nombreuses implémentations de Ruby, chacune avec +des points forts uniques et différents degrés de compatibilité. Les différentes +implémentations sont écrites dans différents languages. +Chaque implémentation a des "hooks" et des fonctionnalités spécifiques, elles +exécutent cependant très bien des fichiers Ruby classiques. +Par exemple, JRuby est écrit en Java, mais vous n'avez pas besoin de connaître +le Java pour l'utiliser. + +Très mature/compatible: + +* [MRI](https://github.com/ruby/ruby) - Ecrite en C, c'est l'implémentation de + référence de Ruby. Elle est par définition 100% compatible (avec elle-même). + Tous les autres rubies maintiennent la compatibilité avec MRI + (voir [RubySpec](#rubyspec) à la suite). +* [JRuby](http://jruby.org/) - Écrite en Java et Ruby, cette robuste + implémentation est assez rapide. + La force de JRuby réside surtout sur l'interopérabilité JVM/Java, faisant + levier sur des outils JVM, des projets et des langages existants. +* [Rubinius](http://rubini.us/) - Ecrite principalement en Ruby avec une VM + bytecode en C++. Egalement mature et rapide. Etant donné qu'elle est + implémentée en Ruby, elle couvre beaucoup de fonctionnalités de la + VM dans Ruby. + +Mpyennement mature/compatible: + +* [Maglev](http://maglev.github.io/) - Basée sur Gemstone, une VM Smalltalk. + Smalltalk possède quelques outils impressionnants, et ce projet tente + de les apporter dans le développement Ruby. +* [RubyMotion](http://www.rubymotion.com/) - Ruby pour développement iOS. +* [Opal](http://opalrb.org/) - Compile le Ruby en Javascript + +Les implémentations de Ruby peuvent avoir leurs propres numéros de versions, +mais elles ciblent toujours une versions spéficique de MRI pour la +compatibilité. +Beaucoup d'implémentations ont la capacité d'entrer dans différents modes +(par exemple, la version 1.8 ou 1.9) afin de spécifier quelle version de MRI +cibler. + +Une liste non exhaustive d'implémentations peut être trouvée [ici (EN)](https://github.com/cogitator/ruby-implementations/wiki/List-of-Ruby-implementations). + +## RubySpec + +La plupart des implémentations Ruby s'appuient fortement sur [RubySpec](http://rubyspec.org/). +Ruby n'a pas de spécification officielle, c'est pourquoi la commaunité a écrit +des spécifications exécutables en Ruby pour tester la compatibilité de leur +implémentation avec MRI. + +## RubyGems + +[RubyGems](http://rubygems.org/) est un gestionnaire de paquets communautaire +pour Ruby. +RubyGems est livré avec Ruby, il n'y a donc pas besoin de le télécharger +séparément. + +Les paquets Ruby sont appelés des "gems", et peuvent être hébergés par la +communauté à RubyGems.org. Chaque gem contient son code source et quelques +métadatas, includant des choses comme la version, les dépendances, +l(es) auteur(s) et la/les licence(s). + +## Bundler + +[Bundler](http://bundler.io/) est un résolveur de dépendances des gems. Il +utilise le Gemfile d'un projet ppur trouver les dépendances, et récupère +ensuite les dépendances de ces dépendances récursivement. Il déroule cet +algorithme jusqu'à ce que toutes les dépendances soient résolues et +téléchargées, ou s'arrête si un conflit est trouvé. + +Bundler lèvera une erreur s'il trouve des conflits de dépendances. Par exemple, +si la gem A recquiert la version 3 ou plus de gem Z, mais que gem B recquiert +seulement la version 2, Bundler vous notifiera ce conflict. Cela devient +extrêmement utile, étant donné que beaucoup de gems font référence à d'autres +gems (qui se réfèrent à d'autres gems), ce qui peut former un large graphe de +dépendance à résoudre. + +# Les tests + +Tester fait partie intégrante de la culture Ruby. Ruby fournit son propre +framework de tests unitaires appelé minitest (ou TestUnit pour Ruby +version 1.8.x). Il existe beaucoup de librairies de tests avec des buts +différents. + +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - Framework de tests intégré de Ruby version 1.8 style "Unit" +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - Framework de tests intégré de Ruby version 1.9/2.0 +* [RSpec](http://rspec.info/) - Un framework de tests qui se focalise sur l'expressivité +* [Cucumber](http://cukes.info/) - Un framework de tests BDD ([behaviour-driven development](https://fr.wikipedia.org/wiki/Behavior_driven_development)) qui parse les tests formatés de Gherkin. + +## Soyez gentil + +La communauté Ruby est fière d'être une communauté ouverte, riche et +accueillante. Matz lui-même est extrêmement sociable, et la générosité des +rubyists est généralement remarquable. diff --git a/fr-fr/tmux-fr.html.markdown b/fr-fr/tmux-fr.html.markdown new file mode 100644 index 00000000..d353af3b --- /dev/null +++ b/fr-fr/tmux-fr.html.markdown @@ -0,0 +1,261 @@ +--- +category: tool +tool: tmux +contributors: + - ["mdln", "https://github.com/mdln"] +translators: + - ["Xuan-thi Nguyen", "https://github.com/mellenguyen"] +filename: LearnTmux-fr.txt +lang: fr-fr +--- + + +[Tmux](http://tmux.sourceforge.net) est un multiplexeur de terminal: il permet +de créer plusieurs terminaux, accédés et contrôlés depuis un seul écran. Tmux +peut être détaché de l'écran tout en continuant de fonctionner en tâche de +fond, puis rattaché de nouveau. + + +``` + + tmux [command] # Exécute une commande + # 'tmux' sans commande créé une nouvelle session + + new # Créé une nouvelle session + -s "Session" # Créé une session nommée "Session" + -n "Window" # Créé une fenêtre nommée "Window" + -c "/dir" # Démarre dans le dossier cible "/dir" + + attach # S'attache à la dernière session ou la session disponible + -t "#" # S'attache à la session cible + -d # Détache la session des autres instances + + ls # Liste les sessions ouvertes + -a # Liste toutes les sessions ouvertes + + lsw # Liste les fenêtres de la session courante + -a # Liste toutes les fenêtres + -s # Liste toutes les fenêtres en session + + lsp # Liste les panels + -a # Liste tous les panels + -s # Liste tous les panels en session + -t # Liste tous les panels dans la cible + + kill-window # Tue la fenêtre courante + -t "#" # Tue la fenêtre cible + -a # Tue toutes les fenêtres + -a -t "#" # Tue toutes les fenêtres sauf la cible + + kill-session # Tue la session courante + -t "#" # Tue la session cible + -a # Tue toutes les sessions + -a -t "#" # Tue toutes les sessions sauf la cible + +``` + + +### Raccourcis clavier + +Afin de contrôler une session tmux attachée, on utilise une combinaison de +touches appelées 'Préfixe'. Elle doit être pressée afin d'utiliser les +raccourcis. + +``` +-------------------------------------------------------------------------------- + (C-b) = Ctrl + b # Combinaison 'Préfixe' requise pour utiliser les raccourcis + + (M-1) = Meta + 1 -ou- Alt + 1 +-------------------------------------------------------------------------------- + + ? # Liste tous les raccourcis + : # Entre dans l'invite de commande de tmux + r # Force la redéfinition du client attaché + c # Créé une nouvelle fenêtre + + ! # Sépare le panel courant de sa fenêtre + % # Sépare le panel courant en deux, gauche et droite + " # Sépare le panel courant en deux, haut et bas + + n # Changer vers la fenêtre suivante + p # Changer vers la fenêtre précédente + { # Echange le panel courant avec le panel précédent + } # Echange le panel courant avec le panel suivant + + s # Sélectionne une nouvelle session pour le client attaché + # de manière interactive + w # Choisi la fenêtre courante de manière interactive + 0 to 9 # Sélectionne la fenêtre de 0 à 9 + + d # Détache le client courant + D # Choisi un client à détacher + + & # Tue la fenêtre courante + x # Tue le panel courant + + Up, Down # Change vers le panel au dessus, en dessous, à gauche + Left, Right # ou à droite + + M-1 to M-5 # Arrange les panels: + # 1) égaliser sur l'horizontale + # 2) égaliser sur la verticale + # 3) panel principal en haut et le reste en bas + # de gauche à droite + # 4) panel principal à gauche et le reste à droite + # de haut en bas + # 5) "tiled" : égalise les panels + # sur la hauteur et la largeur + + C-Up, C-Down # Redimensionne le panel courant par pas de une cellule + C-Left, C-Right + + M-Up, M-Down # Redimensionne le panel courant par pas de cinq cellules + M-Left, M-Right + +``` + + +### Configuration de ~/.tmux.conf + +tmux.conf peut être utilisé pour fixer les options automatiquement au +démarrage, comme .vimrc ou init.el. + +``` +# Exemple de tmux.conf +# 2014.10 + + +### Général +########################################################################### + +# Active UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Limite de l'historique +set -g history-limit 2048 + +# Indice de début du nombre de panels +set -g base-index 1 + +# Souris +set-option -g mouse-select-pane on + +# Force le rechargement du fichier de configuration +unbind r +bind r source-file ~/.tmux.conf + + +### Raccourcis clavier +########################################################################### + +# Annule C-b en tant que préfixe par défaut +unbind C-b + +# Définit un nouveau préfixe par défaut +set-option -g prefix ` + +# Retourne à la fenêtre précédente quand le préfixe est pressé deux fois +bind C-a last-window +bind ` last-window + +# Permet d'échanger C-a et ` en utilisant F11/F12 +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` + +# Préférences de raccourcis clavier +setw -g mode-keys vi +set-option -g status-keys vi + +# Navigue entre les panels avec les raccourcis clavier de vim +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R + +# Navigation entre les fenêtres +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +# Commandes simples de séparation des panels +bind = split-window -h +bind - split-window -v +unbind '"' +unbind % + +# Active la session la plus imbriquée (en faisant de l'imbrication sous tmux) +# pour envoyer des commandes +bind a send-prefix + + +### Thème +########################################################################### + +# Palette de couleurs pour la barre de statuts +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +# Palette de couleurs pour les bordures des panels +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +# Palette de couleurs pour les messages +set-option -g message-fg black +set-option -g message-bg green + +# Palette de couleurs pour les fenêtres +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +# Notification +setw -g monitor-activity on +set -g visual-activity on +set-option -g bell-action any +set-option -g visual-bell off + +# Définir automatiquement des titres de fenêtres +set-option -g set-titles on +# Numéro de fenêtre, nom du programme, actif (ou non) +set-option -g set-titles-string '#H:#S.#I.#P #W #T' + +# Réglages de la barre de statuts +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" + +# Présente des indicateurs de performance dans la barre de statuts +# Recquiert https://github.com/thewtex/tmux-mem-cpu-load/ +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + + +### Références + +[Tmux | Home](http://tmux.sourceforge.net) + +[Page du manuel Tmux](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) + +[Montrer le pourcentage CPU/MEM dans la barre de statuts](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) + +[tmuxinator - Gère des sessions tmux complexes](https://github.com/tmuxinator/tmuxinator) diff --git a/go.html.markdown b/go.html.markdown index dc684227..7b007bab 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -221,7 +221,8 @@ func learnFlowControl() { xBig := func() bool { return x > 10000 // References x declared above switch statement. } - fmt.Println("xBig:", xBig()) // true (we last assigned e^10 to x). + x = 99999 + fmt.Println("xBig:", xBig()) // true x = 1.3e3 // This makes x == 1300 fmt.Println("xBig:", xBig()) // false now. diff --git a/hd-hd/amd.html.markdown b/hd-hd/amd.html.markdown new file mode 100644 index 00000000..0a6581d6 --- /dev/null +++ b/hd-hd/amd.html.markdown @@ -0,0 +1,207 @@ +--- +category: tool +tool: amd +contributors: + - ["Frederik Ring", "https://github.com/m90"] +filename: learnamd-hd.js +lang: hd +--- +## एएमडी के साथ प्रारंभ करना + +एपीआई को परिभाषित करने के लिए एक तंत्र को निर्दिष्ट ** ** अतुल्यकालिक मॉड्यूल परिभाषा +जावास्क्रिप्ट मॉड्यूल ऐसे मॉड्यूल और इसकी अतुल्यकालिक निर्भरता से भरा हुआ है। यह ब्राउज़र पर्यावरण जहां के लिए विशेष रूप से अच्छी तरह से अनुकूल है, और प्रदर्शन , प्रयोज्य, डीबगिंग, और क्रॉस-डोमेन जैसे मॉड्यूल्स को जल्दी सिंक्रनाइज़ लोडिंग करता hai। + +### मूल अवधारणा +```javascript +// बुनियादी एएमडी एपीआई दो तरीकों लेकिन कुछ भी नहीं होते : ` define` और` require` +// और सभी मॉड्यूल परिभाषा और खपत के बारे में है : +// `define` एक मॉड्यूल को परिभाषित करता है +// ` require` निर्भरता का एक सेट का आयात करता है और +// पारित कर दिया कॉलबैक में उन्हें सेवन करती है + +// एक नया नाम देकर हम मॉड्यूल को परिभाषित करने का उपयोग करके शुरू करते हैं +// जिसकी कोई निर्भरता है । हम एक नाम से गुजर रहा है ऐसा करेंगे +// और एक कारखाने समारोह को परिभाषित करने के लिए : +define('awesomeAMD', function(){ + var isAMDAwesome = function(){ + return true; + }; +// एक मॉड्यूल के कारखाने समारोह की मान है + // जब प्राप्त होगा क्या अन्य मॉड्यूल या आवश्यकता कॉल + // हमारे ` awesomeAMD` मॉड्यूल की आवश्यकता होती है । + // निर्यात मूल्य कुछ भी हो सकता है, (निर्माता ) काम करता है, + // वस्तुओं, पुरातन, (जो कि बहुत ज्यादा मदद नहीं करेगा , हालांकि) भी अपरिभाषित । + return isAMDAwesome; +}); + +// अब, हमारे ` awesomeAMD` मॉड्यूल पर निर्भर करता है कि किसी अन्य मॉड्यूल परिभाषित करते हैं। +// हमारे परिभाषित करने के लिए एक अतिरिक्त तर्क है कि नोटिस +अब // मॉड्यूल की निर्भरता : +define('loudmouth', ['awesomeAMD'], function(awesomeAMD){ +// निर्भरता कारखाने के तर्कों को पारित हो जाएगा + // क्रम में वे निर्दिष्ट कर रहे हैं + var tellEveryone = function(){ + if (awesomeAMD()){ + alert('This is sOoOo rad!'); + } else { + alert('Pretty dull, isn\'t it?'); + } + }; + return tellEveryone; +}); + +// हम अब परिभाषित का उपयोग करने के लिए कैसे जानते हैं के रूप में, के लिए ` require` का उपयोग करते हैं +// हमारे कार्यक्रम बंद किक । ` require` के हस्ताक्षर है :(arrayOfDependencies, callback)`. +require(['loudmouth'], function(loudmouth){ + loudmouth(); +}); + +// इस ट्यूटोरियल रन कोड बनाने के लिए है, चलो एक बहुत ही बुनियादी लागू करते हैं +// (गैर अतुल्यकालिक ) की मौके पर यहीं एएमडी के संस्करण: +function define(name, deps, factory){ +// निर्भरता के बिना मॉड्यूल नियंत्रित किया जाता है कैसे नोटिस + define[name] = require(factory ? deps : [], factory || deps); +} + +function require(deps, callback){ + var args = []; + // पहले की जरूरत है सभी निर्भरता पुनः प्राप्त करते हैं + // आवश्यकता कॉल द्वारा + for (var i = 0; i < deps.length; i++){ + args[i] = define[deps[i]]; + } +// सभी कॉलबैक की निर्भरता को संतुष्ट + return callback.apply(null, args); +} +// आप यहाँ कार्रवाई में इस कोड को देख सकते हैं: http://jsfiddle.net/qap949pd/ +``` + +### Require.js के साथ वास्तविक दुनिया के उपयोग + +परिचयात्मक उदाहरण के विपरीत, ` require.js` (सबसे लोकप्रिय एएमडी पुस्तकालय ) वास्तव में लागू करता है ** ** Amd ** में *A * **, आप XHR के माध्यम से मॉड्यूल और उनकी निर्भरता लोड करने के लिए सक्षम करने के लिए : +```javascript +/* file: app/main.js */ +require(['modules/someClass'], function(SomeClass){ + // निर्भरता लोड होने तक कॉलबैक टाल दिया गया है + var thing = new SomeClass(); +}); +console.log('So here we are, waiting!'); // this will run first +``` + +परंपरा के अनुसार , आप आमतौर पर एक फाइल में एक मॉड्यूल में ही रखते है । ` require.js` फ़ाइल पथ पर आधारित मॉड्यूल नाम को हल कर सकते हैं , तो आप अपने मॉड्यूल के नाम करने की जरूरत नहीं है , लेकिन बस उनके स्थान का उपयोग कर उन्हें संदर्भित कर सकते हैं । उदाहरण के `में someClass` आपके विन्यास की ` baseUrl` के सापेक्ष ` modules` फ़ोल्डर में माना गया है : + +* app/ + * main.js + * modules/ + * someClass.js + * someHelpers.js + * ... + * daos/ + * things.js + * ... + +इसका मतलब यह है कि हम एक मॉड्यूल आईडी निर्दिष्ट किए बिना ` someClass` परिभाषित कर सकते हैं : + +```javascript +/* file: app/modules/someClass.js */ +define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){ + // module definition, of course, will also happen asynchronously + function SomeClass(){ + this.method = function(){/**/}; + // ... + } + return SomeClass; +}); +``` +अपने ` main.js` में डिफ़ॉल्ट पथ मानचित्रण व्यवहार का उपयोग ` requirejs.config ( configObj ) ` में परिवर्तन करने के लिए: + +```javascript +/* file: main.js */ +requirejs.config({ + baseUrl : 'app', + paths : { + // आप भी अन्य स्थानों से मॉड्यूल लोड कर सकते हैं + jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}); +require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolLib, helpers){ + //एक ` main` फ़ाइल में कम से कम एक बार की आवश्यकता को फोन करने की जरूरत है, + // अन्यथा कोई कोड कभी चलेंगे + coolLib.doFancyStuffWith(helpers.transform($('#foo'))); +}); +``` +` require.js` आधारित क्षुधा आमतौर पर एक डाटा विशेषता के रूप में ` require.js` स्क्रिप्ट टैग को पारित कर दिया है कि एक एकल प्रवेश बिंदु (` main.js` ) होगा। यह स्वचालित रूप से भरी हुई है और pageload पर क्रियान्वित किया जाएगा : + +```html +<!DOCTYPE html> +<html> +<head> + <title>A hundred script tags? Never again!</title> +</head> +<body> + <script src="require.js" data-main="app/main"></script> +</body> +</html> +``` + +### R.js का उपयोग कर एक पूरी परियोजना का अनुकूलन + +कई लोगों को विकास के दौरान समझदार कोड संगठन के लिए एएमडी का उपयोग कर पसंद करते हैं, लेकिन अभी भी पेज लोड पर XHRs के सैकड़ों करने के बजाय उत्पादन में एक भी स्क्रिप्ट फ़ाइल जहाज करने के लिए चाहते हैं। + +(राइनो भी समर्थन किया है, तो आप शायद Node.js में चलेगा ) ` require.js` ( अपनी परियोजना की निर्भरता ग्राफ का विश्लेषण , और अपने सभी मॉड्यूल युक्त एक एकल फाइल निर्माण कर सकते हैं कि ` r.js` नामक एक स्क्रिप्ट के साथ आता है ठीक से minified और उपभोग के लिए तैयार है, ) नाम दिया है। +Install it using `npm`: +```shell +$ npm install requirejs -g +``` + +अब आप एक विन्यास फाइल के साथ फ़ीड कर सकते हैं: +```shell +$ r.js -o app.build.js +``` + +हमारे ऊपर के उदाहरण के लिए विन्यास की तरह लग सकता है: +```javascript +/* file : app.build.js */ +({ + name : 'main', // प्रवेश बिंदु के नाम + out : 'main-built.js', // फ़ाइल का नाम करने के लिए उत्पादन में लिखने के लिए + baseUrl : 'app', + paths : { + // ` empty :` का उपयोग कर , यह अभी भी समन्वय से लोड किया जाना चाहिए कि r.js बताता है + // main.js में निर्दिष्ट स्थान + jquery : 'empty:', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}) +``` + +उत्पादन में बनाया फ़ाइल का उपयोग करने के लिए, बस ` Data-main` स्वैप: +```html +<script src="require.js" data-main="app/main-built"></script> +``` + +एक अविश्वसनीय रूप से विस्तृत [निर्माण विकल्पों में से अवलोकन] (https://github.com/jrburke/r.js/blob/master/build/example.build.js) GitHub रेपो में उपलब्ध है। + +### विषय इस ट्यूटोरियल में शामिल नहीं +* [लोडर प्लगइन्स / रूपांतरण] (http://requirejs.org/docs/plugins.html) +* [CommonJS शैली लोड हो रहा है और निर्यात] (http://requirejs.org/docs/commonjs.html) +* [उन्नत विन्यास] (http://requirejs.org/docs/api.html#config) +* [शिम विन्यास (गैर एएमडी मॉड्यूल लोडिंग)] (http://requirejs.org/docs/api.html#config-shim) +* [सीएसएस लदान और require.js साथ अनुकूलन] (http://requirejs.org/docs/optimization.html#onecss) +* (Https://github.com/jrburke/almond) [बनाता है के लिए almond.js का प्रयोग] + +### अग्रिम पठन: + +* [सरकारी कल्पना] (https://github.com/amdjs/amdjs-api/wiki/AMD) +* [क्यों एएमडी?] (Http://requirejs.org/docs/whyamd.html) +* [यूनिवर्सल मॉड्यूल परिभाषा] (https://github.com/umdjs/umd) + +### कार्यान्वयन: + +* [Require.js] (http://requirejs.org) +* [डोजो टूलकिट] (http://dojotoolkit.org/documentation/tutorials/1.9/modules/) +* [Cujo.js] (http://cujojs.com/) +* [Curl.js] (https://github.com/cujojs/curl) +* [Lsjs] (https://github.com/zazl/lsjs) +* [एमडी] (https://github.com/alexlawrence/mmd) diff --git a/hd-hd/d.html.markdown b/hd-hd/d.html.markdown new file mode 100644 index 00000000..96274e2b --- /dev/null +++ b/hd-hd/d.html.markdown @@ -0,0 +1,256 @@ +--- +language: D +filename: learnd-hd.d +contributors: + - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] +lang: hd +--- + +```c +//क्या आ रहा है पता है ... +module hello; + +import std.stdio; + +void main(string[] args) { + writeln("Hello, World!"); +} +``` + +अगर आप मेरे जैसे हैं और इंटरनेट पर समय बहुत अधिक समय खर्च करते हैं, तो आप बाधाओं के बारे में सुना है +के बारे में [डी ] ( http://dlang.org/ )। डी प्रोग्रामिंग भाषा में एक आधुनिक, सामान्य प्रयोजन है , +सब कुछ के लिए समर्थन कम स्तर की सुविधाओं से करने के साथ बहु - प्रतिमान भाषा +अर्थपूर्ण उच्च स्तरीय चीजें । + +D सक्रिय रूप से सुपर स्मार्ट लोगों का एक बड़ा समूह द्वारा विकसित की है और नेतृत्व द्वारा किया जाता है +[ वाल्टर ब्राइट ] ( https://en.wikipedia.org/wiki/Walter_Bright ) और +[ आंद्रेई Alexandrescu ] ( https://en.wikipedia.org/wiki/Andrei_Alexandrescu )। +जिस तरह की है कि सभी के साथ बाहर, चलो कुछ उदाहरणों पर गौर करते हैं! + + +```c +import std.stdio; + +void main() { + + for(int i = 0; i < 10000; i++) { + writeln(i); + } + + // 'auto' can be used for inferring types. + auto n = 1; + + // संख्यात्मक literals स्पष्टता के लिए एक अंकों विभाजक के रूप में '_' का उपयोग कर सकते हैं। + while(n < 10_000) { + n += n; + } + + do { + n -= (n / 2); + } while(n > 0); + // लिए और जब तक अच्छा कर रहे हैं, लेकिन D में हम 'foreach' छोरों पसंद करते हैं। + // '..' पहला मान सहित एक सतत श्रृंखला बनाता है, + // लेकिन पिछले छोड़कर। + foreach(i; 1..1_000_000) { + if(n % 2 == 0) + writeln(i); + } + + // वहाँ भी 'foreach_reverse' आप पीछे की ओर पाश करना चाहते हैं। + foreach_reverse(i; 1..int.max) { + if(n % 2 == 1) { + writeln(i); + } else { + writeln("No!"); + } + } +} +``` + +हम ' struct`, `class`,` union`, और `` enum` साथ नए प्रकार परिभाषित कर सकते हैं। Structs और unions +मूल्य से कार्य करने के लिए पारित कर रहे हैं (यानी नकल) और वर्गों के संदर्भ द्वारा पारित कर रहे हैं। इसके अलावा, +हम प्रकारों और मानों दोनों पर करने के लिए टेम्पलेट का उपयोग कर सकते हैं! + +```c +// इधर, 'T' एक प्रकार पैरामीटर है। लगता है कि '<+T>' C++ / C/ Java से। +struct LinkedList(T) { + T data = null; + + // '!'का प्रयोग करें , एक पैरामिट्रीकृत प्रकार इन्स्तांत । फिर, '<T >' लगता है। + LinkedList!(T)* next; +} + +class BinTree(T) { + T data = null; + +// केवल एक टेम्पलेट पैरामीटर नहीं है, तो , हम कोष्ठकों छोड़ सकते हैं। + BinTree!T left; + BinTree!T right; +} + +enum Day { + Sunday, + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, +} + +// उपयोग उर्फ प्रकार (alias) के लिए संक्षिप्त बनाने के लिए। +alias IntList = LinkedList!int; +alias NumTree = BinTree!double; + +//हम के रूप में अच्छी तरह से कार्य टेम्पलेट्स बना सकते हैं! +T max(T)(T a, T b) { + if(a < b) + return b; + + return a; +} + +// संदर्भ द्वारा पारित सुनिश्चित करने के लिए रेफरी कीवर्ड का प्रयोग करें । यही कारण है कि यहां तक कि 'A' और 'B' , तो है +//मान प्रकार वे हमेशा ' swap()' के संदर्भ द्वारा पारित हो जाएगा हैं । +void swap(T)(ref T a, ref T b) { + auto temp = a; + + a = b; + b = temp; +} + +// टेम्पलेट्स के साथ, हम भी मूल्यों पर परमेटेराइज़ कर सकते हैं , न सिर्फ types.With टेम्पलेट्स, हम भी नहीं है, बस प्रकार , मूल्यों पर parameterize कर सकते हैं। +class Matrix(uint m, uint n, T = int) { + T[m] rows; + T[n] columns; +} + +auto mat = new Matrix!(3, 3); + +``` + +Classes की बात हो रही है , एक दूसरे के लिए गुणों के बारे में बात करते हैं। एक संपत्ति +एक value की तरह कार्य कर सकते हैं कि एक समारोह में मोटे तौर पर है, इसलिए हम कर सकते हैं +के शब्दों के साथ पॉड संरचनाओं की वाक्य रचना (` structure.x = 7` ) है +मनुष्य और सेटर तरीकों ( ` object.setX (7) `) ! + +```c +// Consider a class parameterized on types 'T' & 'U'. +class MyClass(T, U) { + T _data; + U _other; +} + +// And "getter" and "setter" methods like so: +class MyClass(T, U) { + T _data; + U _other; + + // भवन निर्माताओं हमेशा नामित कर रहे हैं 'this'. + this(T t, U u) { + //यह नीचे सेटर तरीकों से मुलाकात करेंगे। + data = t; + other = u; + } + + // getters + @property T data() { + return _data; + } + + @property U other() { + return _other; + } + + // setters + @property void data(T t) { + _data = t; + } + + @property void other(U u) { + _other = u; + } +} + +//और हम इस तरह से उन का उपयोग करें : +void main() { + auto mc = new MyClass!(int, string)(7, "seven"); + + करने के लिए लिखने के लिए मानक पुस्तकालय से + // आयात ' stdio ' मॉड्यूल + // सांत्वना (आयात एक गुंजाइश के लिए स्थानीय हो सकता है) । + import std.stdio; + + // Call the getters to fetch the values. + writefln("Earlier: data = %d, str = %s", mc.data, mc.other); + + // Call the setters to assign new values. + mc.data = 8; + mc.other = "eight"; + + // Call the getters again to fetch the new values. + writefln("Later: data = %d, str = %s", mc.data, mc.other); +} +``` + +गुणों के साथ, हम तर्क की किसी भी राशि को जोड़ सकते हैं +हमारे मनुष्य और सेटर तरीकों, और की साफ वाक्य रचना रखना +सीधे सदस्यों तक पहुँचने ! + +हमारे निपटान पर अन्य वस्तु उन्मुख उपहार +` interface`s , ` सार class`es शामिल +और ` तरीकों override`ing । डी सिर्फ जावा की तरह विरासत करता है: +आप कृपया के रूप में कई इंटरफेस को लागू करने, एक वर्ग का विस्तार । + +हम डी एस OOP सुविधाओं देखा , लेकिन स्विच गियर छोड़ दिया । डी प्रस्तावों +प्रथम श्रेणी के कार्यों के साथ कार्यात्मक प्रोग्रामिंग, ` pure` +काम करता है, और अपरिवर्तनीय डेटा । इसके अलावा, अपने पसंदीदा के सभी +कार्यात्मक एल्गोरिदम ( नक्शा, फिल्टर , कम करने और मित्र हो सकते हैं) +अद्भुत ` std.algorithm` मॉड्यूल में पाया! + +```c +import std.algorithm : map, filter, reduce; +import std.range : iota; // builds an end-exclusive range + +void main() { + // हम भी ints के वर्गों की एक सूची का योग मुद्रित करना चाहते हैं + // 1 से 100 के लिए आसान करने के लिए! + + // बस टेम्पलेट पैरामीटर के रूप में लैम्ब्डा भाव के पास! + // आप आप की तरह किसी भी पुराने समारोह पारित कर सकते हैं , लेकिन lambdas यहाँ सुविधाजनक हैं। + auto num = iota(1, 101).filter!(x => x % 2 == 0) + .map!(y => y ^^ 2) + .reduce!((a, b) => a + b); + + writeln(num); +} +``` + +हम NUM गणना करने के लिए एक अच्छा Haskellian पाइपलाइन का निर्माण करने के लिए मिला सूचना कैसे ? +यही कारण है कि एक डी नवाचार करने के लिए धन्यवाद वर्दी समारोह कॉल सिंटेक्स के रूप में जानते हैं। +UFCS के साथ, हम एक विधि के रूप में एक समारोह कॉल लिखने के लिए चुन सकते हैं +या मुफ्त समारोह कॉल ! वाल्टर इस पर एक अच्छा लेख लिखा था +[यहाँ ।] ( http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394 ) +संक्षेप में, आप जिनकी पहली पैरामीटर कार्यों कॉल कर सकते हैं +एक विधि के रूप में ग्रुप ए की किसी भी अभिव्यक्ति पर कुछ प्रकार एक की है । + +मैं समानता चाहते । समानता की तरह कोई और? ज़रूर तुम करना। चलो कुछ करते हैं! +```c +import std.stdio; +import std.parallelism : parallel; +import std.math : sqrt; + +void main() { + // हम हमारे सरणी में वर्गमूल हर नंबर ले जाना चाहता हूँ , + // हम उपलब्ध है के रूप में और के रूप में कई कोर का लाभ ले। + auto arr = new double[1_000_000]; + + // संदर्भ के द्वारा एक सूचकांक , और एक सरणी तत्व का प्रयोग + // और सिर्फ सरणी पर समानांतर फोन! + foreach(i, ref elem; parallel(arr)) { + ref = sqrt(i + 1.0); + } +} + + +``` diff --git a/hu-hu/typescript-hu.html.markdown b/hu-hu/typescript-hu.html.markdown new file mode 100644 index 00000000..aedd5a64 --- /dev/null +++ b/hu-hu/typescript-hu.html.markdown @@ -0,0 +1,175 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: + - ["Tamás Diószegi", "https://github.com/ditam"] +filename: learntypescript-hu.ts +lang: hu-hu +--- + +A TypeScript nyelv a JavaScript nyelven írt nagy méretű alkalmazások fejlesztését kívánja megkönnyíteni. +A TypeScript olyan, más nyelvekből ismert gyakori fogalmakat ad hozzá a JavaScripthez, mint például osztályok, interfészek, generikusság, és (opcionális) statikus típusosság. +A JavaScript egy befoglaló halmazát képzi: minden JavaScript kód érvényes TypeScript kód, így könnyen hozzáadható meglévő projektekhez. A TypeScript fordító kimenetként JavaScript kódot állít elő. + +Ez a dokumentum a TypeScript által hozzáadott új szintaxissal foglalkozik, nem pedig a [Javascripttel](../javascript/). + +Hogy kipróbáld a TypeScript fordítót, látogass el a [Játszótérre avagy Playground-ra](http://www.typescriptlang.org/Playground) ahol kódot írhatsz automatikus kódkiegészítéssel, és közvetlenül láthatod az előállított JavaScript kódot. + +```js +// 3 alapvető típus létezik TypeScriptben +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Anders"; + +// Amikor nem lehet a típust előre tudni, használható az "Any" típus +var notSure: any = 4; +notSure = "talán mégis sztring lesz"; +notSure = false; // tévedtem, mégis boolean + +// Kollekciókból létezik típusos és generikus tömb +var list: number[] = [1, 2, 3]; +// ugyanez a generikus típus használatával +var list: Array<number> = [1, 2, 3]; + +// Enumerált típusok: +enum Color {Red, Green, Blue}; +var c: Color = Color.Green; + +// Végül, "void" használható a visszatérési értékkel nem bíró függvényeknél +function bigHorribleAlert(): void { + alert("Kis idegesítő doboz vagyok!"); +} + +// A függvények elsőrangú (first-class) típusok, használható a vastag nyilas +// lambda szintaxis, +// a compiler pedig kikövetkezteti a típusokat (inferred types) + +// A következők egyenértékűek, ugyanaz a szignatúra kerül kikövetkeztetésre, és +// így ugyanaz a JavaScript kód lesz előállítva +var f1 = function(i: number): number { return i * i; } +// Következtetett visszatérési értékkel +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +// Következtetett visszatérési értékkel +var f4 = (i: number) => { return i * i; } +// Következtetett visszatérési értékkel, +// ebben az egysoros formában nem szükséges a return kulcsszó +var f5 = (i: number) => i * i; + +// Az interfészek szerkezeti alapon működnek, vagyis minden objektum, ahol +// jelen vannak a megfelelő mezők kompatibilis az interfésszel +interface Person { + name: string; + // Az opcionális tagokat "?" jelöli + age?: number; + // És persze függvények is: + move(): void; +} + +// Egy objektum, ami megvalósítja a "Person" interfészt +// Tekinthető Personnek, hiszen van name és move mezője +var p: Person = { name: "Bobby", move: () => {} }; +// Egy objektum, ahol az opcionális mező is jelen van: +var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; +// Ez viszont nem Person, mert az age mező típusa nem szám! +var invalidPerson: Person = { name: "Bobby", age: true }; + +// Az interfészekkel függvény típusok is leírhatóak: +interface SearchFunc { + (source: string, subString: string): boolean; +} +// Csak a paraméterek típusai számítanak, a neveik nem. +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// Osztályok - a mezők alapértelmezésben publikusak +class Point { + // Mezők + x: number; + + // Konstruktor - a public/private kulcsszavak ebben a kontextusban + // legenerálják a mezőkhöz szükséges kódot a konstruktorban. + // Ebben a példában az "y" ugyanúgy definiálva lesz, mint az "x", csak + // kevesebb kóddal. + // Alapértelmezett (default) értékek is megadhatóak. + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Metódusok + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Statikus mezők + static origin = new Point(0, 0); +} + +var p1 = new Point(10 ,20); +var p2 = new Point(25); //y itt 0 lesz + +// Öröklés +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Szükséges az ősosztály konstruktorának explicit hívása + } + + // Felülírás + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Modulok +// ("." használható az almodulok számára) +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +// Új lokális név definiálása a module számára +import G = Geometry; + +var s2 = new G.Square(10); + +// Generikus típusok +// Osztályok +class Tuple<T1, T2> { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interfészek +interface Pair<T> { + item1: T; + item2: T; +} + +// és függvények +var pairToTuple = function<T>(p: Pair<T>) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); + +// definíciós fájl hivatkozása: +/// <reference path="jquery.d.ts" /> + +``` + +## További források + * [TypeScript hivatalos weboldala] (http://www.typescriptlang.org/) + * [TypeScript nyelv specifikációja (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Forráskód GitHubon] (https://github.com/Microsoft/TypeScript) + * [Definitely Typed - típusdefiníciók gyűjteménye] (http://definitelytyped.org/) diff --git a/id-id/java-id.html.markdown b/id-id/java-id.html.markdown new file mode 100644 index 00000000..a5455952 --- /dev/null +++ b/id-id/java-id.html.markdown @@ -0,0 +1,801 @@ +--- +language: java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Jakukyo Friel", "http://weakish.github.io"] + - ["Madison Dickson", "http://github.com/mix3d"] + - ["Simon Morgan", "http://sjm.io/"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] + - ["Rachel Stiyer", "https://github.com/rstiyer"] +filename: LearnJava-id.java +translators: + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] +lang: id-id +--- + +Java adalah bahasa pemrograman yang memiliki tujuan umum dan berorientasi kelas dan objek. +[Baca lebih lanjut.](http://docs.oracle.com/javase/tutorial/java/) + +```java +// Komentar satu baris diawali dengan // (dua garis miring) +/* +Ini adalah contoh komentar banyak-baris. +*/ +/** +Ini adalah contoh komentar JavaDoc. Digunakan untuk mendeskripsikan sebuah kelas, +atau beberapa sifat dari kelas tersebut. +*/ + +// Menyertakan kelas ArrayList dalam paket java.util +import java.util.ArrayList; +// Menyertakan semua kelas yang ada dalam paket java.security +import java.security.*; + +// Setiap dokumen .java sebuah kelas publik dengan nama yang sama dengan nama kelas. +public class BelajarJava { + + // Untuk menjalankan program java, program harus memiliki sebuah method utama (main) sebagai awalan. + public static void main (String[] args) { + + // System.out.println() digunakan untuk menampilkan satu baris teks. + System.out.println("Halo Dunia!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // System.out.print() hanya menampilkan teks tanpa baris baru. + System.out.print("Halo "); + System.out.print("Dunia"); + + // System.out.printf() memudahkan dalam mengatur format penampilan. + System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159 + + /////////////////////////////////////// + // Variabel + /////////////////////////////////////// + + /* + * Deklarasi Variabel + */ + // Deklarasi variabel menggunakan format <tipe> <nama> + int nilai; + // Deklarasi banyak variabel menggunakan format yang sama <tipe> <nama1>, <tipe> <nama2>, <tipe> <nama3> + int nilai1, nilai2, nilai3; + + /* + * Inisialisasi Variabel + */ + + // Inisialisasi sebuah variabel menggunakan <tipe> <nama> = <nilai> + int nilai = 1; + // Inisialisasi banyak variabel menggunakan format yang sama <tipe> <nama1>, <nama2>, <nama3> = <nilai> + int nilai1, nilai2, nilai3; + nilai1 = nilai2 = nilai3 = 1; + + /* + * Tipe Variabel + */ + // Byte - 8 bit signed untuk bilangan bulat komplemen 2 + // (-128 <= byte <= 127) + byte nilaiByte = 100; + + // Short - 8 bit signed untuk bilangan bulat komplemen 2 + // (-32,768 <= short <= 32,767) + short nilaiShort = 10000; + + // Integer - 32 bit signed untuk bilangan bulat komplemen 2 + // (-2,147,483,648 <= int <= 2,147,483,647) + int nilaiInt = 1; + + // Long - 64 bit signed untuk bilangan bulat komplemen 2 + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long nilaiLong = 100000L; + // Karakter "L" pada akhir nilai menyatakan tipe Long; + // selainnya akan dianggap sebagai nilai bilangan bulat. + + // Catatan: Java tidak memiliki tipe unsigned. + + // Float - Presisi-satu 32-bit standar IEEE 754 untuk Floating Point + // 2^-149 <= float <= (2-2^-23) * 2^127 + float nilaiFloat = 234.5f; + // Karakter "f" atau "F" pada akhir nilai menyatakan tipe Float; + // selainnya akan dianggap sebagai nilai double. + + // Double - Presisi-dua 64-bit standar IEEE 754 untuk Floating Point + // 2^-1074 <= x <= (2-2^-52) * 2^1023 + double nilaiDouble = 123.4; + + // Boolean - true & false + boolean nilaiBoolean = true; + boolean nilaiBoolean = false; + + // Char - Sebuah karakter Unicode 16-bit + char nilaiChar = 'A'; + + // Variabel "final" tidak dapat di-set kembali nilainya pada objek lain, + final int WAKTU_SAYA_BEKERJA_TIAP_MINGGU = 9001; + // tapi dapat dilakukan inisialisasi diwaktu yang lain. + final double E; + E = 2.71828; + + + // BigInteger - Bilangan bulat yang memiliki presisi dinamis + // + // BigInteger adalah tipe data yang memungkinkan pembuat program untuk memanipulasi + // bilangan bulat lebih panjang dari 64-bit. Bilangan bulat tersebut tersimpan dalam + // bentuk kumpulan byte (array) dan dimanipulasi menggunakan fungsi yang sudah tersedia + // pada BigInteger + // + // BigInteger dapat diinisialisasi menggunakan kumpulan byte atau teks. + + BigInteger nilaiBigInteger = new BigInteger(kumpulanByte); + + + // BigDecimal - Bilangan signed desimal yang memiliki presisi dinamis + // + // Tipe BigDecimal memiliki dua bagian: sebuah bilangan bulat dengan nilai presisi + // dinamis tanpa skala dan sebuah bilangan bulat skala 32-bit. + + // BigDecimal memungkinkan pembuat program untuk memegang kontrol penuh + // terhadap batas desimal. BigDecimal baik digunakan untuk nilai tukar mata uang + // dimana sangat mementingkan presisi nilai desimal. + // + // BigDecimal dapat diinisialisasi dengan int, long, double, String, + // atau dengan melakukan inisialisasi nilai tanpa skala (BigInteger) + // dan nilai dengan skala (int). + + BigDecimal nilaiBigDecimal = new BigDecimal(nilaiBigInteger, nilaiInt); + + // Perlu diperhatikan konstruktor yang digunakan apakah float atau double + // karena dapat mengakibatkan ketidak-akurasian float/double yang akan digunakan + // dalam BigDecimal. Sebaiknya gunakan nilai String pada konstruktor + // jika membutuhkan nilai pasti. + + BigDecimal sepuluhSen = new BigDecimal("0.1"); + + + // Strings + String nilaiString1 = "Ini adalah contoh String!"; + + // Karakter \n berfungsi untuk membuat baris baru + String nilaiString2 = "Menampilkan baris baru?\nTidak masalah!"; + // Karakter \t berfungsi untuk membuat tab antar karakter + String nilaiString3 = "Ingin menambahkan sebuah tab?\tTidak masalah!"; + System.out.println(nilaiString1); + System.out.println(nilaiString2); + System.out.println(nilaiString3); + + // Larik (array) + // Ukuran array harus ditentukan ketika instansiasi + // Format berikut adalah beberapa cara deklarasi array + // <tipe data>[] <nama variabel> = new <tipe data>[<ukuran array>]; + // <tipe data> <nama variabel>[] = new <tipe data>[<ukuran array>]; + int[] barisAngka = new int[10]; + String[] barisString = new String[1]; + boolean barisBoolean[] = new boolean[100]; + + // Cara lain untuk mendeklarasikan dan menginisialisasi sebuah array + int[] y = {9000, 1000, 1337}; + String nama[] = {"Andi", "Budi", "Agus"}; + boolean bools[] = new boolean[] {true, false, false}; + + // Indeks sebuah array - Mengakses sebuah elemen + System.out.println("barisAngka @ 0: " + barisAngka[0]); + + // Array menggunakan indeks 0 yang tetap. + barisAngka[1] = 1; + System.out.println("barisAngka @ 1: " + barisAngka[1]); // => 1 + + // Lainnya yang perlu diketahui + // ArrayLists - Sama seperti array biasa, namum penggunaannya sudah ditentukan, + // dan ukurannya dapat berubah-ubah. + // LinkedLists - Implementasi dari doubly-linked list. Semua operasi yang digunakan + // hampir sama dengan operasi yang dimiliki oleh sebuah doubly-linked list. + // Maps - Sebuah kumpulan objek yang menyatakan hubungan antara kunci dan nilai. Map merupakan + // sebuah interface sehingga tidak dapat diinstansiasi. Jenis kunci dan nilai yang digunakan + // pada Map harus spesifik pada saat instansiasi ketika diimplementasikan pada sebuah kelas. + // Setiap kunci hanya memiliki sebuah nilai, dan hanya muncul sekali. + // HashMaps - Kelas ini menggunakan tabel-hash untuk mengimplementasikan interface Map. + // Hal ini memungkinkan waktu eksekusi ketika melakukan operasi dasar (mengakses + // dan menambahkan elemen) menjadi konstan, meskipun memiliki banyak set data. + + /////////////////////////////////////// + // Operator + /////////////////////////////////////// + System.out.println("\n->Operator"); + + int i1 = 1, i2 = 2; // Cara singkat untuk deklarasi banyak nilai + + // Kemudahan dalam artimatika + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int menghasilkan int juga) + System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 + + // Modulus + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Operator Perbandingan + System.out.println("3 == 2? " + (3 == 2)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // Operator Boolean + System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false + System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true + System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true + + // Operator Bitwise + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed/Arithmetic right shift + >>> Unsigned/Logical right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR + */ + + // Peningkatan + int i = 0; + System.out.println("\n->Pengurangan/Peningkatan"); + // Operator ++ dan -- masing-masing melakukan peningkatan dan penurunan 1 nilai. + // Jika diletakkan sebelum variabel, maka akan di tambah/kurang 1 sebelum dilakukan perintah lainnya; + // jika setelah variabel, maka akan ditambah/kurang 1 setelah dilakukan perintah lainnya; + System.out.println(i++); // i = 1, prints 0 (peningkatan setelahnya) + System.out.println(++i); // i = 2, prints 2 (peningkatan sebelumnya) + System.out.println(i--); // i = 1, prints 2 (pengurangan setelahnya) + System.out.println(--i); // i = 0, prints 0 (pengurangan sebelumnya) + + /////////////////////////////////////// + // Struktur Kontrol + /////////////////////////////////////// + System.out.println("\n->Struktur Kontrol"); + + // Perintah "if" hampir sama dengan bahasa C + int j = 10; + if (j == 10) { + System.out.println("Saya ditampilkan"); + } else if (j > 10) { + System.out.println("Saya tidak ditampilkan"); + } else { + System.out.println("Saya juga tidak ditampilkan"); + } + + // Perulangan "while" + int fooWhile = 0; + while(fooWhile < 100) { + System.out.println(fooWhile); + // Tingkatkan penghitung + // 100 kali iterasi, fooWhile 0,1,3,...,99 + fooWhile++; + } + System.out.println("Nilai fooWhile: " + fooWhile); + + // Perulangan "do...while" + int fooDoWhile = 0; + do { + System.out.println(fooDoWhile); + // Tingkatkan penghitung + // 99 kali iterasi, fooDoWhile 0->99 + fooDoWhile++; + } while(fooDoWhile < 100); + System.out.println("Nilai fooDoWhile: " + fooDoWhile); + + // Perulangan "for" + // Struktur perulangan "for" => for(<awal_pernyataan>; <kondisi>; <langkah/tahapan>) + for (int fooFor = 0; fooFor < 10; fooFor++) { + System.out.println(fooFor); + // 10 kali iterasi, foofor 0-9 + } + System.out.println("Nilai fooFor: " + fooFor); + + // Perulangan "for" bertingkat dengan label "exit" + outer: + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // Menghentikan semua perulangan, tidak hanya perulangan bagian dalam saja + } + } + } + + // Perulangan "for each" + // Perulangan "for" juga dapat melakukan iterasi terhadap larik (array) dari objek + // yang mana mengimplementasikan interface Ieterable. + int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + // Struktur perulangan "for each" => for (<objek> : <iterable>) + // dibaca: setiap elemen dalam iterable + // catatan: tipe objek harus sama dengan tipe iterable + + for (int bar : fooList) { + System.out.println(bar); + // Melakukan interasi sebanyak 9 kali dan menampilkan 1-9 tiap baris + } + + // "switch case" + // "switch" dapat digunakan pada byte, short, char, dan tipe data bilangan bulat (int). + // "switch" juga dapat digunakan pada tipe "enum" (dijelaskan nanti), kelas String, + // dan beberapa kelas khusus yang mengandung tipe data primitif: + // Character, Byte, Short, dan Integer. + int bulan = 3; + String bulanString; + switch (bulan) { + case 1: bulanString = "Januari"; + break; + case 2: bulanString = "Februari"; + break; + case 3: bulanString = "Maret"; + break; + default: bulanString = "Bulan lainnya"; + break; + } + System.out.println("Hasil switch case: " + bulanString); + + // Mulai dari Java 7 keatas, "switch" memiliki format: + String jawabanSaya = "mungkin"; + switch(jawabanSaya) { + case "ya": + System.out.println("Anda menjawab ya."); + break; + case "tidak": + System.out.println("Anda menjawab tidak."); + break; + case "mungkin": + System.out.println("Anda menjawab mungkin."); + break; + default: + System.out.println("Anda menjawab " + jawabanSaya); + break; + } + + // Pengkondisian dengan cara singkat + // Karakter '?' dapat digunakan untuk penilaian atau logika secara cepat antara dua pernyataan. + // Dibaca "Jika (pernyataan) adalah benar, gunakan <nilai pertama>, sisanya gunakan <nilai kedua> + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println(bar); // Menampilkan A, karena pernyataannya benar + + + //////////////////////////////////////// + // Konversi Data dan Tipe Data (Typecasting) + //////////////////////////////////////// + + // Konversi Data + + // Konversi String ke Integer + Integer.parseInt("123"); // menghasilkan nilai versi Integer dari "123" + + // Konversi Integer ke String + Integer.toString(123); // menghasilkan nilai versi String dari 123 + + // Untuk konversi lainnya silakan coba kelas berikut: + // Double + // Long + // String + + // Typecasting + // Objek dalam Java juga dapat dikonversi, banyak penjelasan dan aturan + // dengan beberapa konsep sederhana. Silakan cek di alamat berikut: + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Kelas dan Fungsi + /////////////////////////////////////// + + System.out.println("\n->Kelas & Fungsi"); + + // (penjelasan mengenai kelas "Sepeda" ada dibawah) + + // Gunakan "new" untuk melakukan instansiasi pada kelas + Sepeda laju = new Sepeda(); + + // Memanggil method objek + laju.tambahKecepatan(3); // Dapat juga digunakan "setter" dan "getter" method + laju.setIrama(100); + + // Method "toString()" menghasilkan representasi string dari objek. + System.out.println("informasi jalur: " + laju.toString()); + + // Dua Pasang Inisialisasi + // Bahasa Java tidak memiliki sintaks untuk membuat koleksi dari "static" sekaligus + // dengan mudah, kecuali dengan cara berikut: + + private static final Set<String> NEGARA = new HashSet<String>(); + static { + validCodes.add("INDONESIA"); + validCodes.add("MALAYSIA"); + validCodes.add("SINGAPURA"); + } + + // Terdapat cara yang baik untuk menulis skrip dengan mudah, + // dengan menggunakan Dua-Kurung Kurawal Inisialisasi (Double Brace Initialization) + + private static final Set<String> NEGARA = new HashSet<String>() {{ + add("INDONESIA"); + add("MALAYSIA"); + add("SINGAPURA"); + }} + + // Kurung kurawal yang pertama membuat sebuah AnonymousInnerClas + // dan kurung kurawal yang kedua mendeklarasikan instance dari blok + // inisialisasi. Blok ini kemudian dipanggil ketika InnerClass dibentuk. + // Cara ini tidak hanya berfungsi pada koleksi data, juga dapat digunakan + // pada semua kelas bukan-"final". + + } // Akhir dari method utama +} // Akhir dari kelas BelajarJava + + +// Kelas bukan-"public" lainnya dapat dimasukkan kedalam satu dokumen .java, +// namun tidak dianjurkan, sebaiknya memisahkan menjadi beberapa dokumen terpisah. + +// Sintaks pendeklarasian kelas: +//<public/private/protected> class <nama kelas> { +// // isi data, konstruktor, dan fungsi. +// // dalam Java, fungsi biasa disebut juga "method" +// } + +class Sepeda { + + // Variabel dari kelas Sepeda + public int irama; // Public: dapat diakses dari manapun + private int kecepatan; // Private: hanya dapat diakses dari dalam kelas + protected int rodaGigi; // Protected: dapat diakses dari dalam kelas dan turunan kelas + String nama; // Default: hanya dapat diakses kelas yang berada dalam paket yang sama + + static String namaKelas; // Variabel "static" + + // Blok Static + // Java tidak memiliki implementasi untuk konstruktor "static", namun + // memiliki blok status yang dapat digunakan untuk inisialisasi variabel + // dalam kelas (variabel "static"). + // Blok ini akan dipanggil secara otomatis ketika kelas dijalankan. + static { + namaKelas = "Sepeda"; + } + + // Konstruktor adalah salah satu cara untuk membuat kelas + // Ini adalah bagian konstruktor + public Sepeda() { + // Dapat juga dipanggil konstruktor lainnya: + // this(1, 50, 5, "Bontrager"); + rodaGigi = 1; + irama = 50; + kecepatan = 5; + nama = "Bontrager"; + } + + // Ini adalah bagian konstruktor yang menggunakan argumen (parameter) + public Sepeda(int iramaAwal, int kecepatanAwal, int rodaGigiAwal, + String nama) { + this.rodaGigi = rodaGigiAwal; + this.irama = iramaAwal; + this.kecepatan = kecepatanAwal; + this.nama = nama; + } + + // Sintaks untuk method: + // <public/private/protected> <tipe kembalian> <nama fungsi>(<args>) + + // Kelas Java terkadang mengimplementasikan "getters" dan "setters" untuk data. + + // Sintaks untuk deklarasi method: + // <public/private/protected> <tipe kembalian> <nama fungsi>(<args>) + public int getIrama() { + return irama; + } + + // Tipe "void" tidak memiliki kembalian (return) nilai + public void setIrama(int nilaiBaru) { + irama = nilaiBaru; + } + + public void setRodaGigi(int nilaiBaru) { + rodaGigi = nilaiBaru; + } + + public void tambahKecepatan(int nilaiTambahan) { + kecepatan += nilaiTambahan; + } + + public void kurangiKecepatan(int nilaiPengurangan) { + kecepatan -= nilaiPengurangan; + } + + public void setNama(String namaBaru) { + nama = namaBaru; + } + + public String getNama() { + return nama; + } + + // Method untuk menampilkan nilai dari tiap atribut yang dimiliki objek Sepeda. + @Override // Diturunkan dari kelas "Object" (Pustaka Java). + public String toString() { + return "roda gigi: " + rodaGigi + " irama: " + irama + " kecepatan: " + kecepatan + + " nama: " + nama; + } +} // akhir dari kelas Sepeda + +// PennyFarthing adalah kelas turunan dari Sepeda +class PennyFarthing extends Sepeda { + // (Penny Farthings adalah sepeda dengan roda depan yang besar, + // dan tidak memiliki roda gigi.) + // (Penny Farthings are those bicycles with the big front wheel. + // They have no gears.) + + public PennyFarthing(int startCadence, int startSpeed) { + // Call the parent constructor with super + super(startCadence, startSpeed, 0, "PennyFarthing"); + } + + // You should mark a method you're overriding with an @annotation. + // To learn more about what annotations are and their purpose check this + // out: http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setRodaGigi(int rodaGigi) { + roda rodaGigi = 0; + } +} + +// Interfaces +// Sintaks untuk deklarasi Interface +// <level akses> interface <nama interface> extends <interface induk> { +// // Konstan +// // Deklarasi method +// } + +// Contoh - Makanan: +public interface dapatDimakan { + public void makan(); // Setiap kelas yang menggunakan interface "dapatDimakan", + // harus mengimplementasikan method "makan". +} + +public interface dapatDicerna { + public void cerna(); +} + + +// Membuat kelas dengan mengimplementasikan dua interface dalam satu waktu. +public class Buah implements dapatDimakan, dapatDicerna { + + @Override + public void makan() { + // ... + } + + @Override + public void cerna() { + // ... + } +} + +// Dalam Java, kelas hanya dapat diturunkan sekali, tapi dapat mengimplementasikan +// banyak interface. Contoh: +public class ContohKelas extends ContohKelasInduk implements InterfaceSatu, + InterfaceDua { + + @Override + public void MethodInterfaceSatu() { + } + + @Override + public void MethodInterfaceDua() { + } + +} + +// Kelas Abstrak (Abstract) +// Sintaks untuk deklarasi kelas abstrak +// Abstract Class declaration syntax +// <level akses> abstract <nama kelas abstrak> extends <induk kelas abstrak> { +// // Konstan dan variabel +// // Deklarasi method + +// Menjadikan kelas sebagai abstrak adalah memungkinkan kelas berisi method abstrak +// yang harus didefinisikan pada kelas turunannya. Mirip dengan Interface, kelas abstrak +// tidak dapat dilakukan instansiasi, namun harus diturunkan pada kelas lain dan method abstrak +// harus didefinisikan. Perbedaannya dengan Interface ialah kelas abstrak dapat berisi method +// kongkrit dan method abstrak. Pada Interface method tidak dapat memiliki isi, artinya hanya +// method statis, dan variabel langsung ditentukan menjadi final, tidak seperti kelas abstrak. +// Kelas abstrak juga dapat memiliki method "main". + +public abstract class Hewan +{ + public abstract void bersuara(); + + // Method biasa dapat memiliki isi + public void makan() + { + System.out.println("Saya adalah hewan dan Saya makan."); + // Catatan: Kita dapat mengakses variabel private yang ada disini. + umur = 30; + } + + // Tidak perlu dilakukan inisialisasi, berbeda dengan Interface + // sebuah variabel adalah final dan harus dilakukan inisialisasi. + protected int umur; + + public void tampilkanUmur() + { + System.out.println(umur); + } + + // Kelas abstrak dapat memiliki fungsi utama (main). + public static void main(String[] args) + { + System.out.println("Saya adalah kelas abstrak!"); + } +} + +class Kucing extends Hewan +{ + // Catatan: kelas ini harus melakukan override method abstrak + // yang ada pada kelas abstrak (induk). + @Override + public void bersuara() + { + System.out.println("Moe"); + // umur = 30; ==> ERROR! umur merupakan variabel private pada abstrak Hewan + } + + // CATATAN: Akan muncul error jika menggunakan + // keterangan @Override pada method utama (main), + // Java tidak mengizinkan hal tersebut. + // Kejadian ini sering disebut sebagai METHOD HIDING. + // Pertanyaan-jawaban yang menarik dapat dilihat: http://stackoverflow.com/questions/16313649/ + public static void main(String[] args) + { + Kucing moe = new Kucing(); + noe.bersuara(); + moe.makan(); + moe.tampilkanUmur(); + } +} + +// Kelas Final + +// Sintaks untuk deklarasi kelas Final +// <level akses> final <nama kelas final> { +// // Konstann dan variabel +// // Deklarasi method +// } + +// Kelas Final merupakan kelas yang tidak dapat diturunkan sehingga menjadikan +// method tersebut turunan method terakhir. Disisi lain, kelas final merupakan +// lawan dari kelas abstrak karena kelas abstrak dapat diturunkan lagi, sedangkan +// kelas final tidak dapat diturunkan lagi. +public final class Serigala extends Hewan +{ + // Catatan: method abstrak harus di-override pada kelas abstrak. + @Override + public void bersuara() + { + System.out.println("Auuww"); + } +} + +// Method Final +public abstract class Mamalia() +{ + // Sintaks untuk method final: + // <level akses> final <tipe kembalian> <nama fungsi>(<args>) + + // Method final, seperti kelas final tidak dapat di-override oleh kelas turunan, + // sehingga menjadikannya implementasi terakhir dari method. + public final boolean apakahBerdarahDingin() + { + return true; + } +} + + +// Tipe Enum +// +// Tipe Enum merupakan tipe data spesial yang memungkinkan sebuah nilai dijadikan +// konstan awal (predefined). Variabel setidaknya harus memiliki nilai yang sama +// dengan salah satu dari enum-enum yang telah ditentukan. Karena nilainya merupakan +// konstan, untuk itu penamaannya menggunakan huruf kapital (uppercase). Dalam Java, +// Enum didefinisikan dengan kata kunci "enum". Contohnya nama-nama hari dalam semunggu: + +public enum Hari { + SENIN, SELASA, RABU, KAMIS, + JUMAT, SABTU, MUNGGU +} + +// Cara menggunakan Enum: +public class CobaEnum { + + // Variabel Enum + Hari hari; + + // Konstruktor + public CobaEnum(Hari hari) { + this.hari = hari; + } + + public void tampilkanKeterangan() { + switch (day) { + case SENIN: + System.out.println("Senin adalah hari yang menyebalkan."); + break; + + case JUMAT: + System.out.println("Jumat adalah hari yang singkat."); + break; + + case SABTU: + case MINGGU: + System.out.println("Akhir pekan adalah hari yang menyenangkan."); + break; + + default: + System.out.println("Hari kerja yang biasa saja."); + break; + } + } + + public static void main(String[] args) { + CobaEnum hariPertama = new CobaEnum(Hari.SENIN); + hariPertama.tampilkanKeterangan(); // Senin adalah hari yang menyebalkan. + CobaEnum hariKetiga = new CobaEnum(Hari.RABU); + hariPertama.tampilkanKeterangan(); // Hari kerja yang biasa saja. + } +} + +// Tipe enum memiliki banyak kegunaan selain yang dicontohkan diatas. +// Tipe enum dapat memiliki isi seperti method dan variabel. +// Penjelasan lebih detail di https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html + +``` + +## Referensi Lainnya + +Link-link berikut hanya menyediakan pemahaman lebih lanjut mengenai topik diatas. +Tip, trik, dan contoh lainnya dapat melakukan pencarian melalui Google atau mesin pencari yang lain. + +**Panduan resmi Oracle** + +* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) + +**Tutorial dan Praktik Online** + +* [Learneroo.com - Learn Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Buku**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Thinking in Java](http://www.mindview.net/Books/TIJ/) + +* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) diff --git a/id-id/json-id.html.markdown b/id-id/json-id.html.markdown index ca346f6c..eef48c63 100644 --- a/id-id/json-id.html.markdown +++ b/id-id/json-id.html.markdown @@ -1,20 +1,32 @@ --- language: json -filename: learnjson-id.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] -translators: +filename: learnjson-id.json +translators - ["Rizky Luthfianto", "https://github.com/rilut"] + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] lang: id-id --- -JSON adalah format pertukaran data yang sangat simpel, kemungkinan besar, -ini adalah "Learn X in Y Minutes" yang paling singkat. +JSON adalah format pertukaran data yang sangat sederhana. Sebagaimana dikutip dari [json.org](http://json.org), JSON mudah untuk dibaca atau ditulis oleh manusia, dan mudah diuraikan dan diproses oleh mesin. + +Sebuah format JSON setidaknya memiliki: +* Sebuah pasangan nama atau nilai dinyatakan dengan karakter (`{ }`). Dibeberapa bahasa pemrograman, karakter ini sering digunakan sebagai object, record, struct, dictionary, hash table, keyed list, atau associative array. +* Daftar nilai dinyatakan dengan karakter (`[ ]`). Dibeberapa bahasa pemrograman, karakter ini sering digunakan sebagai array, vector, list, atau sequence. + +Format JSON murni tidak memiliki komentar, namun beberapa pengurai (parser) dapat mengenali komentar seperti yang digunakan oleh bahasa C (`//`, `/**/`). Beberapa pengurai lainnya juga memiliki toleransi terhadap akhiran sisa koma (seperti koma yang terdapat pada akhir elemen dari larik atau properti terakhir dari objek), tapi koma tersebut memang seharusnya diabaikan untuk dukungan yang lebih baik. -Murninya, JSON tidak mempunyai fitur komentar, tapi kebanyakan parser akan -menerima komentar bergaya bahasa C (`//`, `/* */`). Namun, pada halaman ini, -hanya dicontohkan JSON yang 100% valid. +Dalam tutorial ini, semuanya menggunakan format JSON murni. + +Tipe data yang didukung oleh JSON: + +* Teks: `"halo"`, `"\"tanda petik.\""`, `"\u0abe"`, `"baris baru.\n"` +* Angka: `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4` +* Objek: `{ "kunci": "nilai" }` +* Larik: `["nilai"]` +* Lainnya: `true`, `false`, `null` ```json { @@ -59,3 +71,7 @@ hanya dicontohkan JSON yang 100% valid. "singkat": "Dan Anda selesai! Sekarang Anda tahu apa saja yang disediakan oleh JSON." } ``` + +## Referensi lebih labjut + +* [JSON.org](http://json.org/json-id.html) semua keindahan JSON dijelaskan dalam bentuk alur-grafis (bahasa indonesia). diff --git a/id-id/markdown.html.markdown b/id-id/markdown.html.markdown new file mode 100644 index 00000000..9a7c18cc --- /dev/null +++ b/id-id/markdown.html.markdown @@ -0,0 +1,263 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Tasya Aditya Rukmana", "http://github.com/tadityar"] +filename: markdown-id.md +--- + +Markdown dibuat oleh John Gruber pada tahun 2004. Tujuannya untuk menjadi syntax yang mudah dibaca dan ditulis yang dapat berubah menjadi HTML (dan sekarang berbagai format lainnya) dengan mudah. + +Beri masukan sebanyak-banyaknya! / Jangan sungkan untuk melakukan fork dan pull request! + + +```markdown +<!-- Markdown adalah superset dari HTML, jadi setiap berkas HTML adalah markdown yang +valid, ini berarti kita dapat menggunakan elemen HTML dalam markdown, seperti elemen +komentar, dan ia tidak akan terpengaruh parser markdown. Namun, jika Anda membuat +elemen HTML di berkas markdown Anda, Anda tidak dapat menggunakan syntax markdown +di dalam konten elemen tersebut. --> + +<!-- Markdown juga bervariasi dalam implementasinya dari berbagai parser. Panduan ini +akan mencoba untuk mengklarifikasikan kapan suatu fitur universal atau spesifik +terhadap parser tertentu --> + +<!-- Header --> +<!-- Anda dapat membuat elemen HTML <h1> sampai <h6> dengan mudah dengan mendahului +teks yang diinginkan untuk elemen tersebut oleh sejumlah tanda pagar (#) --> +# Ini adalah <h1> +## Ini adalah <h2> +### Ini adalah <h3> +#### Ini adalah <h4> +##### Ini adalah <h5> +###### Ini adalah <h6> + +<!-- Markdown juga menyediakan dua cara alternatif untuk menandai h1 and h2 --> +Ini adalah h1 +============= + +Ini adalah h2 +------------- + +<!-- Ragam teks simpel --> +<!-- Teks dapat diubah menjadi miring atau tebal dengan mudah menggunakan markdown --> + +*Ini adalah teks miring.* +_Dan juga teks ini._ + +**Ini adalah teks tebal.** +__Dan juga teks ini.__ + +***Ini adalah teks dengan keduanya.*** +**_Dan juga ini!_** +*__Dan ini!__* + +<!-- Di markdown ala Github, yang digunakan untuk me-render berkas markdown pada +Github, kita juga punya coretan: --> + +~~Teks ini dirender dengan coretan.~~ + +<!-- Paragraf adalah satu atau beberapa baris teks yang dipisahkan oleh satu atau +beberapa baris kosong. --> + +Ini adalah paragraf. Saya mengetik dalam paragraf, bukankah ini menyenangkan? + +Sekarang saya ada di paragraf 2. +Saya juga masih ada dalam paragraf 2! + + +Saya ada di paragraf 3! + +<!-- Jika Anda ingin memasukkan tag HTML <br />, Anda dapat mengakhiri sebuah +paragraf dengan dua atau lebih spasi lalu memulai paragraf yang baru. --> + +Aku diakhiri dua spasi (soroti aku untuk melihatnya). + +Ada sebuah <br /> diatasku! + +<!-- Kutipan mudah dibuat dengan karakter >. --> + +> Ini adalah kutipan. Anda dapat +> membungkusnya secara manual dan meletakkan `>` sebelum tiap baris atau Anda dapat membuat baris yang sangat panjang dan membuatnya membungkus secara otomatis. +> Tidak ada masalah selama ia diawali dengan `>`. + +> Anda juga dapat menggunakan lebih dari satu level +>> indentasi! +> Sangat rapi bukan? + +<!-- Daftar --> +<!-- Daftar tak beraturan dapat dibuat dengan bintang, plus, atau strip --> + +* Item +* Item +* Item lainnya + +atau + ++ Item ++ Item ++ Satu lagi item + +or + +- Item +- Item +- Item terakhir + +<!-- List beraturan dibuat dengan angka diikuti titik --> + +1. Item satu +2. Item dua +3. Item tiga + +<!-- Anda tidak diharuskan melabeli item dengan benar dan markdown akan tetap +me-render angka sesuai urutan, namun mungkin hal ini kurang baik --> + +1. Item satu +1. Item dua +1. Item tida +<!-- (Ini dirender sama seperti contoh di atas) --> + +<!-- Anda juga dapat menggunakan sublist --> + +1. Item satu +2. Item dua +3. Item tiga + * Sub-item + * Sub-item +4. Item empat + +<!-- Bahkan ada daftar tugas. Ini membuat kotak centang HTML. --> + +Kotak di bawah tanpa 'x' adalah kotak centang HTML yang belum diisi. +- [ ] Tugas pertama selesai. +- [ ] Tugas kedua yang harus diselesaikan +Kotak centang HTML berikut telah diisi. +- [x] Tugas ini telah diselesaikan + +<!-- Blok kode --> +<!-- Anda dapat menandai blok kode (yang menggunakan elemen <code>) dengan mengindentasi +sebuah garis dengan empat spasi atau tab --> + + Ini adalah kode + Dan ini juga + +<!-- Anda juga dapat me-re-tab (atau menambahkan empat spasi tambahan) untuk indentasi +di dalam kode Anda --> + + array_ku.each do |item| + puts item + end + +<!-- Sebaris kode dapat dibuat dengan karakter backtick ` --> + +John bahkan tidak tahu apa fungsi dari `go_to()` ! + +<!-- Di Markdown ala Github, Anda dapat menggunakan syntax spesial untuk kode --> + +\`\`\`ruby <!-- kecuali hapus backlash tersebut ketika melakukannya, hanya ```ruby ! --> +def foobar + puts "Halo Dunia!" +end +\`\`\` <!-- Disini juga, tidak ada backslashes, hanya ``` --> + +<!-- Teks di atas tidak membutuhkan indentasi, plus Github akan menggunakan syntax +highlighting dari bahasa yang digunakan setelah ``` --> + +<!-- Horizontal rule (<hr />) --> +<!-- Horizontal rules ditambahkan dengan mudah oleh beberapa bintang atau strip, +dengan atau tanpa spasi. --> + +*** +--- +- - - +**************** + +<!-- Tautan --> +<!-- Salah satu hal terbaik dari markdown adalah mudahnya membuat tautan. Letakkan +teks yang akan di tampilkan di dalam kurung siku [] diikuti oleh url-nya dalam kurung () --> + +[Klik aku!](http://test.com/) + +<!-- Anda juga dapat menambahkan judul link dengan tanda kutip di dalam kurung --> + +[Klik aku!](http://test.com/ "Link to Test.com") + +<!-- Path relatif juga bisa. --> + +[Pergi ke musik](/music/). + +<!-- Markdown juga mendukung tautan gara referal --> + +[Klik link ini][link1] untuk info lebih banyak! +[Juga cek link ini][foobar] jika Anda mau. + +[link1]: http://test.com/ "Keren!" +[foobar]: http://foobar.biz/ "OK!" + +<!-- Judulnya juga bisa dalam kutip satu atau kurung, atau dihilangkan sepenuhnya. +Referensinya juga bisa di mana saja di dokumen anda dan IF referensinya bisa jadi +apa saja selama ia unik. --> + +<!-- Ada juga "penamaan implisit" yang membuat Anda dapat menggunakan teks tautan sebagai id --> + +[Ini][] adalah tautan. + +[ini]: http://thisisalink.com/ + +<!-- Tapi ia tidak lazim digunakan. --> + +<!-- Gambar --> +<!-- Gambar digunakan sama seperti tautan namun dengan tanda seru di depannya! --> + +![Ini adalah atribut alt dari gambar saya](http://imgur.com/myimage.jpg "Judul opsional") + +<!-- Dan gaya referensi juga bekerja seperti yang diharapkan --> + +![Ini adalah atribut alt.][myimage] + +[myimage]: relative/urls/cool/image.jpg "jika Anda membutuhkan judul, disini" + +<!-- Lain-lain --> +<!-- Tautan otomatis --> + +<http://testwebsite.com/> sama dengan +[http://testwebsite.com/](http://testwebsite.com/) + +<!-- Tautan otomatis untuk email --> + +<foo@bar.com> + +<!-- Melewati karakter --> + +Saya ingin mengetik *teks ini dikelilingi tanda bintang* tapi saya tidak mau teksnya menjadi +miring, jadi saya melakukan: \*teks ini dikelilingi tanda bintang\*. + +<!-- Tombol keyboard --> +<!-- Pada Markdown ala Github, Anda dapat menggunakan tag <kbd> untuk merepresentasikan tombol +keyboard --> + +Komputer Anda hang? Coba kirim sebuah +<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd> + +<!-- Tabel --> +<!-- Tabel hanya tersedia pada Markdown ala Github dan sedikit merepotkan, namun jika Anda +sangat menginginkannya: --> + +| Kol1 | Kol2 | Kol3 | +| :----------- | :------: | ------------: | +| Rata-kiri | Tengah | Rata-Kanan | +| blah | blah | blah | + +<!-- atau, untuk hasil yang sama --> + +Kol 1 | Kol2 | Kol3 +:-- | :-: | --: +Ugh ini sangat jelek | buat ia | berhenti + +<!-- Selesai! --> + +``` + +Untuk info lebih lanjut, cek post syntax resmi John Gruber [di sini](http://daringfireball.net/projects/markdown/syntax) dan contekan hebat Adam Pritchard's [di sini](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). diff --git a/it-it/go-it.html.markdown b/it-it/go-it.html.markdown new file mode 100644 index 00000000..e005f2dc --- /dev/null +++ b/it-it/go-it.html.markdown @@ -0,0 +1,453 @@ +--- +name: Go +language: Go +filename: learngo-it.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] + - ["Christopher Bess", "https://github.com/cbess"] + - ["Jesse Johnson", "https://github.com/holocronweaver"] + - ["Quint Guvernator", "https://github.com/qguv"] + - ["Jose Donizetti", "https://github.com/josedonizetti"] + - ["Alexej Friesen", "https://github.com/heyalexej"] + - ["Clayton Walker", "https://github.com/cwalk"] +translators: + - ["Tommaso Pifferi","http://github.com/neslinesli93"] +lang: it-it +--- + +Go è stato creato per avere tra le mani uno strumento in grado di arrivare +al punto, nel modo più veloce ed efficiente possibile. Non è all'ultima +moda tra i linguaggi di programmazione, ma è una delle migliori soluzioni +per risolvere in maniera efficace i problemi di tutti i giorni. + +Go presenta alcuni concetti già presenti nei linguaggi imperativi con +tipizzazione statica. Compila velocemente ed esegue altrettanto veloce. +Aggiunge la concorrenza in maniera diretta e semplice da capire, per far +forza sulle CPU multi-core di oggigiorno. Presenta caratteristiche utili +per la programmazione in larga scala. + +Go comes with a great standard library and an enthusiastic community. + +```go +// Commento su riga singola +/* Commento + su riga multipla */ + +// In cima a ogni file è necessario specificare il package. +// Main è un package speciale che identifica un eseguibile anziché una libreria. +package main + +// Con import sono dichiarate tutte le librerie a cui si fa riferimento +// all'interno del file. +import ( + "fmt" // Un package nella libreria standard di Go. + "io/ioutil" // Implementa alcune funzioni di utility per l'I/O. + m "math" // Libreria matematica, con alias locale m + "net/http" // Sì, un web server! + "strconv" // Package per la conversione di stringhe. +) + +// Una definizione di funzione. Il main è speciale: è il punto di ingresso +// per il programma. Amalo o odialo, ma Go usa le parentesi graffe. +func main() { + // Println stampa una riga a schermo. + // Questa funzione è all'interno del package fmt. + fmt.Println("Ciao mondo!") + + // Chiama un'altra funzione all'interno di questo package. + oltreIlCiaoMondo() +} + +// Le funzioni ricevono i parametri all'interno di parentesi tonde. +// Se la funzione non riceve parametri, vanno comunque messe le parentesi (vuote). +func oltreIlCiaoMondo() { + var x int // Dichiarazione di una variabile. Ricordati di dichiarare sempre le variabili prima di usarle! + x = 3 // Assegnazione di una variabile. + // E' possibile la dichiarazione "rapida" := per inferire il tipo, dichiarare e assegnare contemporaneamente. + y := 4 + // Una funzione che ritorna due valori. + somma, prod := imparaMoltepliciValoriDiRitorno(x, y) + fmt.Println("somma:", somma, "prodotto:", prod) // Semplice output. + imparaTipi() // < y minuti, devi imparare ancora! +} + +/* <- commento su righe multiple +Le funzioni possono avere parametri e ritornare (molteplici!) valori. +Qua, x e y sono gli argomenti, mentre somma e prod sono i valori ritornati. +Da notare il fatto che x e somma vengono dichiarati come interi. +*/ +func imparaMoltepliciValoriDiRitorno(x, y int) (somma, prod int) { + return x + y, x * y // Ritorna due valori. +} + +// Ecco alcuni tipi presenti in Go +func imparaTipi() { + // La dichiarazione rapida di solito fa il suo lavoro. + str := "Impara il Go!" // Tipo stringa. + + s2 := `Una stringa letterale +puo' includere andata a capo.` // Sempre di tipo stringa. + + // Stringa letterale non ASCII. I sorgenti Go sono in UTF-8. + g := 'Σ' // Il tipo runa, alias per int32, è costituito da un code point unicode. + + f := 3.14195 // float64, un numero in virgola mobile a 64-bit (IEEE-754) + + c := 3 + 4i // complex128, rappresentato internamente con due float64. + + // Inizializzare le variabili con var. + var u uint = 7 // Senza segno, ma la dimensione dipende dall'implementazione (come l'int) + var pi float32 = 22. / 7 + + // Sintassi per la conversione. + n := byte('\n') // Il tipo byte è un alias per uint8. + + // I vettori hanno dimensione fissa, stabilita durante la compilazione. + var a4 [4]int // Un vettore di 4 interi, tutti inizializzati a 0. + a3 := [...]int{3, 1, 5} // Un vettore inizializzato con una dimensione fissa pari a 3, i cui elementi sono 3, 1 e 5. + + // Gli slice hanno dimensione variabile. Vettori e slice hanno pro e contro, + // ma generalmente si tende a usare più spesso gli slice. + s3 := []int{4, 5, 9} // La differenza con a3 è che qua non ci sono i 3 punti all'interno delle parentesi quadre. + s4 := make([]int, 4) // Alloca uno slice di 4 interi, tutti inizializzati a 0. + var d2 [][]float64 // Semplice dichiarazione, non vengono fatte allocazioni. + bs := []byte("uno slice") // Sintassi per la conversione. + + // Poiché gli slice sono dinamici, è possibile aggiungere elementi + // quando è necessario. Per farlo, si usa la funzione append(). Il primo + // argomento è lo slice a cui stiamo aggiungendo elementi. Di solito + // lo slice viene aggiornato, senza fare una copia, come nell'esempio: + s := []int{1, 2, 3} // Il risultato è uno slice di dimensione 3. + s = append(s, 4, 5, 6) // Aggiunge 3 elementi: lo slice ha dimensione 6. + fmt.Println(s) // Lo slice aggiornato è [1 2 3 4 5 6] + // Per aggiungere un altro slice, invece che elencare gli elementi uno ad + // uno, è possibile passare alla funzione append un riferimento ad uno + // slice, oppure uno slice letterale: in questo caso si usano i tre punti, + // dopo lo slice, a significare "prendi ciascun elemento dello slice": + s = append(s, []int{7, 8, 9}...) // Il secondo argomento è uno slice letterale. + fmt.Println(s) // Lo slice aggiornato è [1 2 3 4 5 6 7 8 9] + + p, q := imparaLaMemoria() // Dichiara due puntatori a intero: p e q. + fmt.Println(*p, *q) // * dereferenzia un puntatore. Questo stampa due interi. + + // Una variabile di tipo map è un vettore associativo di dimensione variabile, + // e funzionano come le tabelle di hash o i dizionari in altri linguaggi. + m := map[string]int{"tre": 3, "quattro": 4} + m["uno"] = 1 + + // Le variabili dichiarate e non usate sono un errore in Go. + // L'underscore permette di "usare" una variabile, scartandone il valore. + _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs + // Stampare a schermo ovviamente significa usare una variabile. + fmt.Println(s, c, a4, s3, d2, m) + + imparaControlloDiFlusso() // Torniamo in carreggiata. +} + +// In Go è possibile associare dei nomi ai valori di ritorno di una funzione. +// Assegnare un nome al tipo di dato ritornato permette di fare return in vari +// punti all'interno del corpo della funzione, ma anche di usare return senza +// specificare in modo esplicito che cosa ritornare. +func imparaValoriDiRitornoConNome(x, y int) (z int) { + z = x * y + return // z è implicito, perchè compare nella definizione di funzione. +} + +// Go è dotato di garbage collection. Ha i puntatori, ma non l'aritmetica dei +// puntatori. Puoi fare errori coi puntatori a nil, ma non puoi direttamente +// incrementare un puntatore. +func imparaLaMemoria() (p, q *int) { + // I valori di ritorno (con nome) p e q sono puntatori a int. + p = new(int) // La funzione new si occupa di allocare memoria. + // L'int allocato viene inizializzato a 0, dunque p non è più nil. + s := make([]int, 20) // Alloca 20 int come un singolo blocco di memoria. + s[3] = 7 // Ne assegna uno. + r := -2 // Dichiara un'altra variabile locale + return &s[3], &r // & "prende" l'indirizzo di un oggetto. +} + +func calcoloCostoso() float64 { + return m.Exp(10) +} + +func imparaControlloDiFlusso() { + // L'istruzione if richiede parentesi graffe per il corpo, mentre non ha + // bisogno di parentesi tonde per la condizione. + if true { + fmt.Println("te l'ho detto") + } + // Eseguendo "go fmt" da riga di comando, il codice viene formattato + // in maniera standard. + if false { + // :( + } else { + // :D + } + // L'istruzione switch serve ad evitare tanti if messi in cascata. + x := 42.0 + switch x { + case 0: + case 1: + case 42: + // Quando è soddisfatta la condizione all'interno di un case, il + // programma esce dal switch senza che siano specificate istruzioni + // di tipo "break". In Go infatti di default non è presente il + // cosiddetto "fall through" all'interno dell'istruzione switch. + // Tuttavia, il linguaggio mette a disposizione la parola chiave + // fallthrough per permettere, in casi particolari, questo comportamento. + case 43: + // Non si arriva qua. + default: + // Il caso di default è opzionale. + } + // Come l'if, anche il for non usa parentesi tonde per la condizione. + // Le variabili dichiarate all'interno di if/for sono locali al loro scope. + for x := 0; x < 3; x++ { // ++ è un'istruzione! + fmt.Println("ciclo numero", x) + } + // x == 42 qua. + + // Il for è l'unica istruzione per ciclare in Go, ma ha varie forme. + for { // Ciclo infinito. + break // Scherzavo. + continue // Non si arriva qua. + } + + // Puoi usare range per ciclare su un vettore, slice, stringa, mappa o canale. + // range ritorna uno (per i canali) o due valori (vettore, slice, stringa, mappa). + for chiave, valore := range map[string]int{"uno": 1, "due": 2, "tre": 3} { + // per ogni coppia dentro la mappa, stampa chiave e valore + fmt.Printf("chiave=%s, valore=%d\n", chiave, valore) + } + + // Come nel for, := dentro la condizione dell'if è usato per dichiarare + // e assegnare y, poi testare se y > x. + if y := calcoloCostoso(); y > x { + x = y + } + // Le funzioni letterali sono closure. + xGrande := func() bool { + return x > 10000 // Si riferisce a x dichiarata sopra al switch (vedi sopra). + } + fmt.Println("xGrande:", xGrande()) // true (abbiamo assegnato e^10 a x). + x = 1.3e3 // Adesso x == 1300 + fmt.Println("xGrande:", xGrande()) // false ora. + + // Inoltre le funzioni letterali possono essere definite e chiamate + // inline, col ruolo di parametri di funzione, a patto che: + // a) la funzione letterale venga chiamata subito (), + // b) il valore ritornato è in accordo con il tipo dell'argomento. + fmt.Println("Somma e raddoppia due numeri: ", + func(a, b int) int { + return (a + b) * 2 + }(10, 2)) // Chiamata con argomenti 10 e 2 + // => Somma e raddoppia due numeri: 24 + + // Quando ti servirà, lo amerai. + goto amore +amore: + + imparaFabbricaDiFunzioni() // Una funzione che ritorna un'altra funzione è divertente! + imparaDefer() // Un tour veloce di una parola chiave importante. + imparaInterfacce() // Arriva la roba buona! +} + +func imparaFabbricaDiFunzioni() { + // Questi due blocchi di istruzioni sono equivalenti, ma il secondo è più semplice da capire. + fmt.Println(fabbricaDiFrasi("estate")("Una bella giornata", "giornata!")) + + d := fabbricaDiFrasi("estate") + fmt.Println(d("Una bella", "giornata!")) + fmt.Println(d("Un pigro", "pomeriggio!")) +} + +// I decoratori sono comuni in alcuni linguaggi. Si può fare lo stesso in Go +// con le funzioni letterali che accettano argomenti. +func fabbricaDiFrasi(miaStringa string) func(prima, dopo string) string { + return func(prima, dopo string) string { + return fmt.Sprintf("%s %s %s", prima, miaStringa, dopo) // Nuova stringa + } +} + +func imparaDefer() (ok bool) { + // Le istruzioni dette "deferred" (rinviate) sono eseguite + // appena prima che la funzione ritorni. + defer fmt.Println("le istruzioni 'deferred' sono eseguite in ordine inverso (LIFO).") + defer fmt.Println("\nQuesta riga viene stampata per prima perché") + // defer viene usato di solito per chiudere un file, così la funzione che + // chiude il file viene messa vicino a quella che lo apre. + return true +} + +// Definisce Stringer come un'interfaccia con un metodo, String. +type Stringer interface { + String() string +} + +// Definisce coppia come una struct con due campi interi, chiamati x e y. +type coppia struct { + x, y int +} + +// Definisce un metodo sul tipo coppia, che adesso implementa Stringer. +func (p coppia) String() string { // p viene definito "ricevente" + // Sprintf è un'altra funzione del package ftm. + // La notazione con il punto serve per richiamare i campi di p. + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func imparaInterfacce() { + // Brace syntax is a "struct literal". It evaluates to an initialized + // struct. The := syntax declares and initializes p to this struct. + // Le parentesi graffe sono usate per le cosiddette "struct letterali". + // Con :=, p viene dichiarata e inizializzata a questa struct. + p := coppia{3, 4} + fmt.Println(p.String()) // Chiama il metodo String di p, che è di tipo coppia. + var i Stringer // Dichiara i come interfaccia Stringer. + i = p // Valido perchè coppia implementa Stringer. + // Chiama il metodo String di i, che è di tipo Stringer. Output uguale a sopra. + fmt.Println(i.String()) + + // Functions in the fmt package call the String method to ask an object + // for a printable representation of itself. + // Le funzioni dentro al package fmt chiamano il metodo String per + // chiedere ad un oggetto una rappresentazione in stringhe di sé stesso. + fmt.Println(p) // Output uguale a sopra. Println chiama il metodo String. + fmt.Println(i) // Output uguale a sopra. + + imparaParametriVariadici("grande", "imparando", "qua!") +} + +// Le funzioni possono avere parametri variadici (ovvero di lunghezza variabile). +func imparaParametriVariadici(mieStringhe ...interface{}) { + // Cicla su ogni valore variadico. + // L'underscore serve a ignorare l'indice del vettore. + for _, param := range mieStringhe { + fmt.Println("parametro:", param) + } + + // Passa un valore variadico come parametro variadico. + fmt.Println("parametri:", fmt.Sprintln(mieStringhe...)) + + imparaGestioneErrori() +} + +func imparaGestioneErrori() { + // La sintassi ", ok" è usata per indicare se qualcosa ha funzionato o no. + m := map[int]string{3: "tre", 4: "quattro"} + if x, ok := m[1]; !ok { // ok sarà false perchè 1 non è dentro la mappa. + fmt.Println("qua non c'è nessuno!") + } else { + fmt.Print(x) // x sarebbe il valore che corrisponde alla chiave 1, se fosse nella mappa. + } + // Un errore non riporta soltanto "ok" ma è più specifico riguardo al problema. + if _, err := strconv.Atoi("non_intero"); err != nil { // _ scarta il valore + // stampa 'strconv.ParseInt: parsing "non_intero": invalid syntax' + fmt.Println(err) + } + // Approfondiremo le interfacce un'altra volta. Nel frattempo, + imparaConcorrenza() +} + +// c è un canale, un oggetto per comunicare in modo concorrente e sicuro. +func inc(i int, c chan int) { + c <- i + 1 // <- è l'operatore di "invio" quando un canale sta a sinistra. +} + +// Useremo inc per incrementare alcuni numeri in modo concorrente. +func imparaConcorrenza() { + // Stessa funzione usata prima per creare uno slice. Make alloca e + // inizializza slice, mappe e canali. + c := make(chan int) + // Lancia tre goroutine. I numeri saranno incrementati in modo concorrente, + // forse in parallelo se la macchina lo supporta. Tutti e tre inviano dati + // sullo stesso canale. + go inc(0, c) // go è un'istruzione che avvia una goroutine. + go inc(10, c) + go inc(-805, c) + // Legge tre risultati dal canale e li stampa a schermo. + // Non si conosce a priori l'ordine in cui i risultati arriveranno! + fmt.Println(<-c, <-c, <-c) // <- è l'operatore di "ricevuta" quando + // un canale sta a destra. + + cs := make(chan string) // Un altro canale, gestisce le stringhe. + ccs := make(chan chan string) // Un canale che gestisce canali di stringhe. + go func() { c <- 84 }() // Lancia una goroutine, solo per inviare un valore. + go func() { cs <- "parolina" }() // Stessa cosa ma per cs. + // select è simile a switch, ma ogni case riguarda un'operazione su un + // canale. Seleziona, in modo random, uno tra i canali che sono pronti + // a comunicare. + select { + case i := <-c: // Il valore ricevuto può essere assegnato a una variabile, + fmt.Printf("E' un %T", i) + case <-cs: // oppure il valore ricevuto può essere scartato. + fmt.Println("E' una stringa.") + case <-ccs: // Canale vuoto, non pronto per comunicare. + fmt.Println("Non succede niente.") + } + // A questo punto un valore è stato preso da c o cs. Una delle tue goroutine + // cominciate sopra ha completato l'esecuzione, l'altra rimarrà bloccata. + + imparaProgrammazioneWeb() // Se lo fa Go, lo puoi fare anche tu. +} + +// Una funzione all'interno del package http avvia un webserver. +func imparaProgrammazioneWeb() { + + // Il primo parametro di ListenAndServe è l'indirizzo TCP su cui ascoltare. + // Il secondo parametro è un'interfaccia, precisamente http.Handler. + go func() { + err := http.ListenAndServe(":8080", coppia{}) + fmt.Println(err) // Non ignorare gli errori. + }() + + richiediServer() +} + +// Per rendere coppia un http.Handler basta implementare il metodo ServeHTTP. +func (p coppia) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Il server fornisce dati con un metodo di http.ResponseWriter. + w.Write([]byte("Hai imparato Go in Y minuti!")) +} + +func richiediServer() { + risposta, err := http.Get("http://localhost:8080") + fmt.Println(err) + defer risposta.Body.Close() + corpo, err := ioutil.ReadAll(risposta.Body) + fmt.Printf("\nIl webserver dice: `%s`", string(corpo)) +} +``` + +## Letture consigliate + +La risorsa più importante per imparare il Go è il [sito ufficiale di Go](http://golang.org/). +Qui puoi seguire i tutorial, scrivere codice in modo interattivo, e leggere tutti i dettagli. +Oltre al tour, [la documentazione](https://golang.org/doc/) contiene informazioni su +come scrivere ottimo codice in Go, documentazione sui package e sui comandi, e +la cronologia delle release. + +Anche il documento che definisce il linguaggio è un'ottima lettura. E' semplice +da leggere e incredibilmente corto (rispetto ad altri documenti riguardanti +la creazione di linguaggi). + +Puoi giocare con il codice visto finora nel [Go playground](https://play.golang.org/p/Am120Xe7qf). +Prova a cambiarlo e ad eseguirlo dal browser! +Osserva che puoi usare [https://play.golang.org](https://play.golang.org) come +una [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) per scrivere +codice all'interno del browser, senza neanche installare Go! + +Una lettura importante per capire Go in modo più profondo è il [codice +sorgente della libreria standard](http://golang.org/src/pkg/). Infatti è +molto ben documentato e costituisce quanto più chiaro e conciso ci sia riguardo +gli idiomi e le buone pratiche del Go. Inoltre, clickando sul nome di una +funzione [nella documentazione](http://golang.org/pkg/) compare il relativo +codice sorgente! + +Un'altra ottima risorsa per imparare è [Go by example](https://gobyexample.com/). + +Go Mobile aggiunge il supporto per lo sviluppo mobile (Android e iOS). +In questo modo è possibile scrivere un'app mobile nativa in Go, oppure +una libreria che contiene binding da un package scritto in Go, e che può +essere richiamata da Java(Android) e Objective-C(iOS). Visita la pagina di +[Go Mobile](https://github.com/golang/go/wiki/Mobile) per maggiori informazioni. diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown new file mode 100644 index 00000000..b006dbb4 --- /dev/null +++ b/it-it/markdown.html.markdown @@ -0,0 +1,244 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Jacopo Andrea Giola", "http://geekpanda.net"] +filename: markdown-it.md +lang: it-it +--- + +Markdown è stato creato da John Gruber nel 2004. Il suo scopo è quello di essere una sintassi facile da leggere e scrivere, e che può essere convertita in HTML (ad oggi anche in molti altri formati). + +Mandate tutto il feedback che volete! / Sentitevi liberi di forkare o di mandare pull request! + + +```markdown +<!-- Markdown è un superset di HTML, quindi ogni file HTML è a sua volta un file Markdown valido. Questo significa che possiamo usare elementi di HTML in Markdown, come per esempio i commenti, e questi non saranno modificati dal parser di Markdown. State attenti però, se inserite un elemento HTML nel vostro file Markdown, non potrete usare la sua sintassi all'interno del contenuto dell'elemento. --> + +<!-- L'implementazione di Markdown inoltre cambia da parser a parser. In questa guida cercheremo di indicare quando una feature è universale e quando sono specifiche ad un certo parser. --> + +<!-- Titoli --> +<!-- Potete creare gli elementi HTML da <h1> ad <h6> facilmente, basta che inseriate un egual numero di caratteri cancelletto (#) prima del testo che volete all'interno dell'elemento --> +# Questo è un <h1> +## Questo è un <h2> +### Questo è un <h3> +#### Questo è un <h4> +##### Questo è un <h5> +###### Questo è un <h6> + +<!-- Markdown inoltre fornisce due alternative per indicare gli elementi h1 e h2 --> +Questo è un h1 +============== + +Questo è un h2 +-------------- + +<!-- Stili di testo semplici --> +<!-- Il testo può essere stilizzato in corsivo o grassetto usando markdown --> + +*Questo testo è in corsivo.* +_Come pure questo._ + +**Questo testo è in grassetto.** +__Come pure questo.__ + +***Questo testo è stilizzato in entrabmi i modi.*** +**_Come questo!_** +*__E questo!__* + +<!-- In Github Flavored Markdown, che è utilizzato per renderizzare i file markdown su +Github, è presente anche lo stile barrato --> + +~~Questo testo è barrato.~~ + +<!-- I paragrafi sono uno o più linee di testo addiacenti separate da una o più righe vuote. --> + +Qeusto è un paragrafo. Sto scrivendo in un paragrafo, non è divertente? + +Ora sono nel paragrafo 2. +Anche questa linea è nel paragrafo 2! + + +Qui siamo nel paragrafo 3! + +<!-- Se volete inserire l'elemento HTML <br />, potete terminare la linea con due o più spazi e poi iniziare un nuovo paragrafo. --> + +Questa frase finisce con due spazi (evidenziatemi per vederli). + +C'è un <br /> sopra di me! + +<!-- Le citazioni sono semplici da inserire, basta usare il carattere >. --> + +> Questa è una citazione. Potete +> mandare a capo manualmente le linee e inserire un `>` prima di ognuna, oppure potete usare una sola linea e lasciare che vada a capo automaticamente. +> Non c'è alcuna differenza, basta che iniziate ogni riga con `>`. + +> Potete utilizzare anche più di un livello +>> di indentazione! +> Quanto è comodo? + +<!-- Liste --> +<!-- Le liste non ordinate possono essere inserite usando gli asterischi, il simbolo più o dei trattini --> + +* Oggetto +* Oggetto +* Altro oggetto + +oppure + ++ Oggetto ++ Oggetto ++ Un altro oggetto + +oppure + +- Oggetto +- Oggetto +- Un ultimo oggetto + +<!-- Le liste ordinate invece, sono inserite con un numero seguito da un punto. --> + +1. Primo oggetto +2. Secondo oggetto +3. Terzo oggetto + +<!-- Non dovete nemmeno mettere i numeri nell'ordine giusto, markdown li visualizzerà comunque nell'ordine corretto, anche se potrebbe non essere una buona idea. --> + +1. Primo oggetto +1. Secondo oggetto +1. Terzo oggetto +<!-- (Questa lista verrà visualizzata esattamente come quella dell'esempio prima) --> + +<!-- Potete inserire anche sotto liste --> + +1. Primo oggetto +2. Secondo oggetto +3. Terzo oggetto + * Sotto-oggetto + * Sotto-oggetto +4. Quarto oggetto + +<!-- Sono presenti anche le task list. In questo modo è possibile creare checkbox in HTML. --> + +I box senza la 'x' sono checkbox HTML ancora da completare. +- [ ] Primo task da completare. +- [ ] Secondo task che deve essere completato. +Il box subito sotto è una checkbox HTML spuntata. +- [x] Questo task è stato completato. + +<!-- Estratti di codice --> +<!-- Potete inserire un estratto di codice (che utilizza l'elemento <code>) indentando una linea con quattro spazi oppure con un carattere tab --> + + Questa è una linea di codice + Come questa + +<!-- Potete inoltre inserire un altro tab (o altri quattro spazi) per indentare il vostro codice --> + + my_array.each do |item| + puts item + end + +<!-- Codice inline può essere inserito usando il carattere backtick ` --> + +Giovanni non sapeva neppure a cosa servisse la funzione `go_to()`! + +<!-- In Github Flavored Markdown, potete inoltre usare una sintassi speciale per il codice --> + +\`\`\`ruby <!-- In realtà dovete rimuovere i backslash, usate solo ```ruby ! --> +def foobar + puts "Hello world!" +end +\`\`\` <!-- Anche qui, niente backslash, solamente ``` --> + +<!-- Se usate questa sintassi, il testo non richiederà di essere indentanto, inoltre Github userà la syntax highlighting del linguaggio specificato dopo i ``` iniziali --> + +<!-- Linea orizzontale (<hr />) --> +<!-- Le linee orizzontali sono inserite facilemtne usanto tre o più asterischi o trattini senza spazi consecutivi e senza spazi. --> + +*** +--- +- - - +**************** + +<!-- Link --> +<!-- Una delle funzionalità migliori di markdown è la facilità con cui si possono inserire i link. Mettete il testo da visualizzare fra parentesi quadre [] seguite dall'url messo fra parentesi tonde () --> + +[Cliccami!](http://test.com/) + +<!-- Potete inoltre aggiungere al link un titolo mettendolo fra doppie apici dopo il link --> + +[Cliccami!](http://test.com/ "Link a Test.com") + +<!-- La sintassi funziona anche i path relativi. --> + +[Vai a musica](/music/). + +<!-- Markdown supporta inoltre anche la possibilità di aggiungere i link facendo riferimento ad altri punti del testo --> + +[Apri questo link][link1] per più informazioni! +[Guarda anche questo link][foobar] se ti va. + +[link1]: http://test.com/ "Bello!" +[foobar]: http://foobar.biz/ "Va bene!" + +<!-- Il titolo può anche essere inserito in apici singoli o in parentesi, oppure omesso interamente. Il riferimento può essere inserito in un punto qualsiasi del vostro documento e l'identificativo del riferimento può essere lungo a piacere a patto che sia univoco. --> + +<!-- Esiste anche un "identificativo implicito" che vi permette di usare il testo del link come id --> + +[Questo][] è un link. + +[Questo]: http://thisisalink.com/ + +<!-- Ma non è comunemente usato. --> + +<!-- Immagini --> +<!-- Le immagini sono inserite come i link ma con un punto esclamativo inserito prima delle parentesi quadre! --> + +![Qeusto è il testo alternativo per l'immagine](http://imgur.com/myimage.jpg "Il titolo opzionale") + +<!-- E la modalità a riferimento funziona esattamente come ci si aspetta --> + +![Questo è il testo alternativo.][myimage] + +[myimage]: relative/urls/cool/image.jpg "Se vi serve un titolo, lo mettete qui" + +<!-- Miscellanea --> +<!-- Auto link --> + +<http://testwebsite.com/> è equivalente ad +[http://testwebsite.com/](http://testwebsite.com/) + +<!-- Auto link per le email --> + +<foo@bar.com> + +<!-- Caratteri di escaping --> + +Voglio inserire *questo testo circondato da asterischi* ma non voglio che venga renderizzato in corsivo, quindi lo inserirò così: \*questo testo è circondato da asterischi\*. + +<!-- Combinazioni di tasti --> +<!-- In Github Flavored Markdown, potete utilizzare il tag <kbd> per raffigurare i tasti della tastiera --> + +Il tuo computer è crashato? Prova a premere +<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Canc</kbd> + +<!-- Tabelle --> +<!-- Le tabelle sono disponibili solo in Github Flavored Markdown e sono leggeremente complesse, ma se proprio volete inserirle fate come segue: --> + +| Col1 | Col2 | Col3 | +| :------------------- | :------: | -----------------: | +| Allineato a sinistra | Centrato | Allineato a destra | +| blah | blah | blah | + +<!-- oppure, per lo stesso risultato --> + +Col 1 | Col2 | Col3 +:-- | :-: | --: +È una cosa orrenda | fatela | finire in fretta + +<!-- Finito! --> + +``` + +Per altre informazioni, leggete il post ufficiale di John Gruber sulla sintassi [qui](http://daringfireball.net/projects/markdown/syntax) e il magnifico cheatsheet di Adam Pritchard [qui](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). diff --git a/it-it/matlab-it.html.markdown b/it-it/matlab-it.html.markdown new file mode 100644 index 00000000..aeb42658 --- /dev/null +++ b/it-it/matlab-it.html.markdown @@ -0,0 +1,526 @@ +--- +language: Matlab +contributors: + - ["mendozao", "http://github.com/mendozao"] + - ["jamesscottbrown", "http://jamesscottbrown.com"] + - ["Colton Kohnke", "http://github.com/voltnor"] +translators: + - ["Samuele Gallerani", "http://github.com/fontealpina"] +lang: it-it +filename: matlab-it.md +--- + +MATLAB sta per MATrix LABoratory ed è un potente linguaggio per il calcolo numerico comunemente usato in ingegneria e matematica. + +```matlab +% I commenti iniziano con il segno percentuale. + +%{ +I commenti multilinea +assomigliano a +qualcosa +del genere +%} + +% i comandi possono essere spezzati su più linee, usando '...': + a = 1 + 2 + ... + + 4 + +% i comandi possono essere passati al sistema operativo +!ping google.com + +who % Mostra tutte le variabili in memoria +whos % Mostra tutte le variabili in memoria, con i loro tipi +clear % Cancella tutte le tue variabili dalla memoria +clear('A') % Cancella una particolare variabile +openvar('A') % Apre la variabile in un editor di variabile + +clc % Cancella il contenuto della Command Window +diary % Attiva il log della Command Window su file +ctrl-c % Interrompe il calcolo corrente + +edit('myfunction.m') % Apre la funzione/script nell'editor +type('myfunction.m') % Stampa il codice della funzione/script sulla Command Window + +profile on % Attiva la profilazione del codice +profile off % Disattiva la profilazione del codice +profile viewer % Apre il profilatore + +help comando % Mostra la documentazione di comando sulla Command Window +doc comando % Mostra la documentazione di comando sulla Help Window +lookfor comando % Cerca comando nella prima linea di commento di tutte le funzioni +lookfor comando -all % Cerca comando in tutte le funzioni + + +% Formattazione dell'output +format short % 4 decimali in un numero float +format long % 15 decimali +format bank % Solo due cifre decimali - per calcoli finaziari +fprintf('text') % Stampa "text" a terminale +disp('text') % Stampa "text" a terminale + +% Variabili ed espressioni +miaVariabile = 4 % Il pannello Workspace mostra la nuova variabile creata +miaVariabile = 4; % Il punto e virgola evita che l'output venga stampato sulla Command Window +4 + 6 % ans = 10 +8 * myVariable % ans = 32 +2 ^ 3 % ans = 8 +a = 2; b = 3; +c = exp(a)*sin(pi/2) % c = 7.3891 + +% La chiamata di funzioni può essere fatta in due modi differenti: +% Sintassi standard di una funzione: +load('myFile.mat', 'y') % argomenti tra parentesi, separati da virgole +% Sintassi di tipo comando: +load myFile.mat y % Non ci sono parentesi e gli argometi sono separati da spazi +% Notare la mancanza di apici nella sintassi di tipo comando: gli input sono sempre passati come +% testo letterale - non è possibile passare valori di variabili. Inoltre non può ricevere output: +[V,D] = eig(A); % Questa non ha una forma equivalente con una sintassi di tipo comando +[~,D] = eig(A); % Se si vuole solo D e non V + + + +% Operatori logici +1 > 5 % ans = 0 +10 >= 10 % ans = 1 +3 ~= 4 % Not equal to -> ans = 1 +3 == 3 % equal to -> ans = 1 +3 > 1 && 4 > 1 % AND -> ans = 1 +3 > 1 || 4 > 1 % OR -> ans = 1 +~1 % NOT -> ans = 0 + +% Gli operatori logici possono essere applicati alle matrici: +A > 5 +% Per ogni elemento, se la condizione è vera, quell'elemento vale 1 nella matrice risultante +A( A > 5 ) +% Restituisce un vettore contenente gli elementi in A per cui la condizione è vera + +% Stringhe +a = 'MyString' +length(a) % ans = 8 +a(2) % ans = y +[a,a] % ans = MyStringMyString + + +% Celle +a = {'one', 'two', 'three'} +a(1) % ans = 'one' - ritorna una cella +char(a(1)) % ans = one - ritorna una stringa + +% Strutture +A.b = {'one','two'}; +A.c = [1 2]; +A.d.e = false; + +% Vettori +x = [4 32 53 7 1] +x(2) % ans = 32, gli indici in Matlab iniziano da 1, non da 0 +x(2:3) % ans = 32 53 +x(2:end) % ans = 32 53 7 1 + +x = [4; 32; 53; 7; 1] % Vettore colonna + +x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 + +% Matrici +A = [1 2 3; 4 5 6; 7 8 9] +% Le righe sono separate da punto e virgola, mentre gli elementi sono separati da spazi +% A = + +% 1 2 3 +% 4 5 6 +% 7 8 9 + +A(2,3) % ans = 6, A(row, column) +A(6) % ans = 8 +% (implicitamente concatena le colonne in un vettore, e quindi gli indici sono riferiti al vettore) + + +A(2,3) = 42 % Aggiorna riga 2 colonna 3 con 42 +% A = + +% 1 2 3 +% 4 5 42 +% 7 8 9 + +A(2:3,2:3) % Crea una nuova matrice a partire da quella precedente +%ans = + +% 5 42 +% 8 9 + +A(:,1) % Tutte le righe nella colonna 1 +%ans = + +% 1 +% 4 +% 7 + +A(1,:) % Tutte le colonne in riga 1 +%ans = + +% 1 2 3 + +[A ; A] % Concatenazione di matrici (verticalmente) +%ans = + +% 1 2 3 +% 4 5 42 +% 7 8 9 +% 1 2 3 +% 4 5 42 +% 7 8 9 + +% è equivalente a +vertcat(A,A); + + +[A , A] % Concatenazione di matrici (orrizontalmente) + +%ans = + +% 1 2 3 1 2 3 +% 4 5 42 4 5 42 +% 7 8 9 7 8 9 + +% è equivalente a +horzcat(A,A); + + +A(:, [3 1 2]) % Ripristina le colonne della matrice originale +%ans = + +% 3 1 2 +% 42 4 5 +% 9 7 8 + +size(A) % ans = 3 3 + +A(1, :) =[] % Rimuove la prima riga della matrice +A(:, 1) =[] % Rimuove la prima colonna della matrice + +transpose(A) % Traspone la matrice, equivale a: +A one +ctranspose(A) % Trasposizione hermitiana della matrice +% (ovvero il complesso coniugato di ogni elemento della matrice trasposta) + + + + +% Aritmetica Elemento per Elemento vs. Artimetica Matriciale +% Gli operatori aritmetici da soli agliscono sull'intera matrice. Quando sono preceduti +% da un punto, allora agiscono su ogni elemento. Per esempio: +A * B % Moltiplicazione matriciale +A .* B % Moltiplica ogni elemento di A per il corrispondente elemento di B + +% Ci sono diverse coppie di funzioni, in cui una agisce su ogni elemento, e +% l'altra (il cui nome termina con m) agisce sull'intera matrice. +exp(A) % Calcola l'esponenziale di ogni elemento +expm(A) % Calcola la matrice esponenziale +sqrt(A) % Calcola la radice quadrata di ogni elementotake the square root of each element +sqrtm(A) % Trova la matrice di cui A nè è la matrice quadrata + + +% Plot di grafici +x = 0:.10:2*pi; % Crea un vettore che inizia a 0 e termina 2*pi con incrementi di .1 +y = sin(x); +plot(x,y) +xlabel('x axis') +ylabel('y axis') +title('Plot of y = sin(x)') +axis([0 2*pi -1 1]) % x range da 0 a 2*pi, y range da -1 a 1 + +plot(x,y1,'-',x,y2,'--',x,y3,':') % Per stampare più funzioni in unico plot +legend('Line 1 label', 'Line 2 label') % Aggiunge un etichetta con il nome delle curve + +% Metodo alternativo per stampare funzioni multiple in un unico plot. +% mentre 'hold' è on, i comandi sono aggiunti al grafico esistene invece di sostituirlo +plot(x, y) +hold on +plot(x, z) +hold off + +loglog(x, y) % Un plot di tipo log-log +semilogx(x, y) % Un plot con asse x logaritmico +semilogy(x, y) % Un plot con asse y logaritmico + +fplot (@(x) x^2, [2,5]) % Stampa la funzione x^2 da x=2 a x=5 + +grid on % Mostra la griglia, disattivare con 'grid off' +axis square % Rende quadrata la regione individuata dagli assi +axis equal % Iposta l'aspetto del grafico in modo che le unità degli assi siano le stesse + +scatter(x, y); % Scatter-plot +hist(x); % Istogramma + +z = sin(x); +plot3(x,y,z); % Stampa una linea 3D + +pcolor(A) % Heat-map di una matrice: stampa una griglia di rettangoli, colorati in base al valore +contour(A) % Contour plot di una matrice +mesh(A) % Stampa come una superfice di mesh + +h = figure % Crea un nuovo oggetto figura, con handle f +figure(h) % Rende la figura corrispondente al handle h la figura corrente +close(h) % Chiude la figura con handle h +close all % Chiude tutte le figure +close % Chiude la figura corrente + +shg % Riutilizza una finestra grafica già esistente, o se necessario ne crea una nuova +clf clear % Pulisce la figura corrente, e resetta le proprietà della figura + +% Le proprietà possono essere impostate e modificate attraverso l'handle della figura. +% Si può salvare l'handle della figura quando viene creata. +% La funzione gcf restituisce un handle alla figura attuale. +h = plot(x, y); % Si può salvare un handle della figura quando viene creata +set(h, 'Color', 'r') +% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black +set(h, 'LineStyle', '--') + % '--' linea continua, '---' tratteggiata, ':' puntini, '-.' trattino-punto, 'none' nessuna linea +get(h, 'LineStyle') + + +% La funzione gca restituisce un handle degli assi della figura corrente +set(gca, 'XDir', 'reverse'); % Inverte la direzione dell'asse x + +% Per creare una figura che contiene diverse sottofigure, usare subplot +subplot(2,3,1); % Seleziona la prima posizione in una griglia 2 per 3 di sottofigure +plot(x1); title('First Plot') % Stampa qualcosa in questa posizione +subplot(2,3,2); % Seleziona la seconda posizione nella griglia +plot(x2); title('Second Plot') % Stampa qualcosa in questa posizione + + +% Per usare funzioni o script, devono essere nel tuo path o nella directory corrente +path % Mostra il path corrente +addpath /path/to/dir % Aggiunge al path +rmpath /path/to/dir % Rimuove dal path +cd /path/to/move/into % Cambia directory + + +% Le variabili possono essere salvate in file .mat +save('myFileName.mat') % Salva le variabili nel tuo Workspace +load('myFileName.mat') % Carica variabili salvate nel tuo Workspace + +% M-file Scripts +% I file di script sono file esterni che contengono una sequenza di istruzioni. +% Permettono di evitare di scrivere ripetutamente lo stesso codice nella Command Window +% Hanno estensione .m + +% M-file Functions +% Come gli script, hanno la stessa estensione .m +% Ma possono accettare argomenti di input e restituire un output. +% Inoltre, hanno un proprio workspace (differente scope delle variabili). +% Il nome della funzione dovrebbe coincidere con il nome del file (quindi salva questo esempio come double_input.m). +% 'help double_input.m' restituisce i commenti sotto alla linea iniziale della funzione +function output = double_input(x) + %double_input(x) restituisce il doppio del valore di x + output = 2*x; +end +double_input(6) % ans = 12 + + +% Si possono anche avere sottofunzioni e funzioni annidate. +% Le sottofunzioni sono nello stesso file della funzione primaria, e possono solo essere +% chiamate da funzioni nello stesso file. Le funzioni annidate sono definite dentro ad altre +% funzioni, e hanno accesso ad entrambi i workspace. + +% Se si vuole creare una funzione senza creare un nuovo file si può usare una +% funzione anonima. Utile quando si vuole definire rapidamente una funzione da passare ad +% un'altra funzione (es. stampa con fplot, valutare un integrale indefinito +% con quad, trovare le radici con fzenzro, o trovare il minimo con fminsearch). +% Esempio che restituisce il quadrato del proprio input, assegnato all'handle sqr: +sqr = @(x) x.^2; +sqr(10) % ans = 100 +doc function_handle % scopri di più + +% Input dell'utente +a = input('Enter the value: ') + +% Ferma l'esecuzione del file e cede il controllo alla tastiera: l'utente può esaminare +% o cambiare variabili. Digita 'return' per continuare l'esecuzione, o 'dbquit' per uscire +keyboard + +% Importarare dati (anche xlsread/importdata/imread per excel/CSV/image file) +fopen(filename) + +% Output +disp(a) % Stampa il valore della variabile a +disp('Hello World') % Stampa una stringa +fprintf % Stampa sulla Command Window con più controllo + +% Istruzioni condizionali (le parentesi sono opzionali, ma un buon stile) +if (a > 15) + disp('Maggiore di 15') +elseif (a == 23) + disp('a è 23') +else + disp('nessuna condizione verificata') +end + +% Cicli +% NB. Ciclare su elementi di vettori/matrici è lento! +% Dove possibile, usa funzioni che agiscono sull'intero vettore/matrice +for k = 1:5 + disp(k) +end + +k = 0; +while (k < 5) + k = k + 1; +end + +% Misurare la durata dell'esecuzione del codice: 'toc' stampa il tempo trascorso da quando 'tic' è stato chiamato +tic +A = rand(1000); +A*A*A*A*A*A*A; +toc + +% Connessione a un Database MySQL +dbname = 'database_name'; +username = 'root'; +password = 'root'; +driver = 'com.mysql.jdbc.Driver'; +dburl = ['jdbc:mysql://localhost:8889/' dbname]; +javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); +% xx dipende dalla versione, download disponibile all'indirizzo http://dev.mysql.com/downloads/connector/j/ +conn = database(dbname, username, password, driver, dburl); +sql = ['SELECT * from table_name where id = 22'] % Esempio istruzione sql +a = fetch(conn, sql) % conterra i tuoi dati + + +% Funzioni matematiche comuni +sin(x) +cos(x) +tan(x) +asin(x) +acos(x) +atan(x) +exp(x) +sqrt(x) +log(x) +log10(x) +abs(x) +min(x) +max(x) +ceil(x) +floor(x) +round(x) +rem(x) +rand % Numeri pseudocasuali uniformemente distribuiti +randi % Numeri interi pseudocasuali uniformemente distrubuiti +randn % Numeri pseudocasuali distrbuiti normalmente + +% Costanti comuni +pi +NaN +inf + +% Risolvere equazioni matriciali +% Gli operatori \ e / sono equivalenti alle funzioni mldivide e mrdivide +x=A\b % Risolve Ax=b. Più veloce e più accurato numericamente rispetto ad usare inv(A)*b. +x=b/A % Risolve xA=b + +inv(A) % Calcola la matrice inversa +pinv(A) % Calcola la matrice pseudo-inversa + +% Funzioni comuni su matrici +zeros(m,n) % Matrice m x n di zeri +ones(m,n) % Matrice m x n di uni +diag(A) % Estrae gli elementi della diagonale della matrice A +diag(x) % Costruisce una matrice con elementi diagonali uguali agli elementi di x, e zero negli altri elementi +eye(m,n) % Matrice identità +linspace(x1, x2, n) % Ritorna n punti equamente distanziati, con minimo x1 e massimo x2 +inv(A) % Matrice inversa di A +det(A) % Determinante di A +eig(A) % Autovalori e autovettori di A +trace(A) % Traccia della matrice - equivalente a sum(diag(A)) +isempty(A) % Verifica se l'array è vuoto +all(A) % Verifica se tutti gli elementi sono nonzero o veri +any(A) % Verifica se almento un elemento è nonzero o vero +isequal(A, B) % Verifica l'uguaglianza di due array +numel(A) % Numero di elementi nella matrice +triu(x) % Ritorna la parte triangolare superiore di x +tril(x) % Ritorna la parte triangolare inferiore di x +cross(A,B) % Ritorna il prodotto vettoriale dei vettori A e B +dot(A,B) % Ritorna il prodotto scalare di due vettori (devono avere la stessa lunghezza) +transpose(A) % Ritorna la trasposta di A +fliplr(A) % Capovolge la matrice da sinistra a destra +flipud(A) % Capovolge la matrice da sopra a sotto + +% Fattorizzazione delle matrici +[L, U, P] = lu(A) % Decomposizione LU: PA = LU, L è il triangolo inferiore, U è il triangolo superiore, P è la matrice di permutazione +[P, D] = eig(A) % Auto-decomposizione: AP = PD, le colonne di P sono autovettori e gli elementi sulle diagonali di D sono autovalori +[U,S,V] = svd(X) % SVD: XV = US, U e V sono matrici unitarie, S ha gli elementi della diagonale non negativi in ordine decrescente + +% Funzioni comuni su vettori +max % elemento più grande +min % elemento più piccolo +length % lunghezza del vettore +sort % ordina in modo crescente +sum % somma degli elementi +prod % prodotto degli elementi +mode % valore moda +median % valore mediano +mean % valore medio +std % deviazione standard +perms(x) % lista tutte le permutazioni di elementi di x + + +% Classi +% Matlab supporta la programmazione orientata agli oggetti. +% La classe deve essere messa in un file con lo stesso nome della classe e estensione .m +% Per iniziare, creiamo una semplice classe per memorizzare waypoint GPS +% Inizio WaypointClass.m +classdef WaypointClass % Il nome della classe. + properties % Le proprietà della classe funzionano come Strutture + latitude + longitude + end + methods + % Questo metodo che ha lo stesso nome della classe è il costruttore + function obj = WaypointClass(lat, lon) + obj.latitude = lat; + obj.longitude = lon; + end + + % Altre funzioni che usano l'oggetto Waypoint + function r = multiplyLatBy(obj, n) + r = n*[obj.latitude]; + end + + % Se si vuole aggiungere due oggetti Waypoint insieme senza chiamare + % una funzione speciale si può sovradefinire una funzione aritmetica di Matlab come questa: + function r = plus(o1,o2) + r = WaypointClass([o1.latitude] +[o2.latitude], ... + [o1.longitude]+[o2.longitude]); + end + end +end +% End WaypointClass.m + +% Si può creare un oggetto della classe usando un costruttore +a = WaypointClass(45.0, 45.0) + +% Le proprietà della classe si comportano esattamente come una Struttura Matlab. +a.latitude = 70.0 +a.longitude = 25.0 + +% I metodi possono essere chiamati allo stesso modo delle funzioni +ans = multiplyLatBy(a,3) + +% Il metodo può anche essere chiamato usando una notazione con punto. In questo caso, l'oggetto +% non necessita di essere passato al metodo. +ans = a.multiplyLatBy(a,1/3) + +% Le funzioni Matlab possono essere sovradefinite per gestire oggetti. +% Nel metodo sopra, è stato sovradefinito come Matlab gestisce +% l'addizione di due oggetti Waypoint. +b = WaypointClass(15.0, 32.0) +c = a + b + +``` + +## Di più su Matlab + +* Sito ufficiale [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) +* Forum ufficiale di MATLAB: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) diff --git a/java.html.markdown b/java.html.markdown index a025bbba..1f7d4115 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -8,6 +8,7 @@ contributors: - ["Zachary Ferguson", "http://github.com/zfergus2"] - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] - ["Rachel Stiyer", "https://github.com/rstiyer"] + - ["Michael Dähnert", "http://github.com/JaXt0r"] filename: LearnJava.java --- @@ -23,8 +24,17 @@ Multi-line comments look like this. */ /** -JavaDoc comments look like this. Used to describe the Class or various -attributes of a Class. + * JavaDoc comments look like this. Used to describe the Class or various + * attributes of a Class. + * Main attributes: + * + * @author Name (and contact information such as email) of author(s). + * @version Current version of the program. + * @since When this part of the program was first added. + * @param For describing the different parameters for a method. + * @return For describing what the method returns. + * @deprecated For showing the code is outdated or shouldn't be used. + * @see Links to another part of documentation. */ // Import ArrayList class inside of the java.util package @@ -162,6 +172,29 @@ public class LearnJava { System.out.println(barString); System.out.println(bazString); + // String Building + // #1 - with plus operator + // That's the basic way to do it (optimized under the hood) + String plusConcatenated = "Strings can " + "be concatenated " + "via + operator."; + System.out.println(plusConcatenated); + // Output: Strings can be concatenated via + operator. + + // #2 - with StringBuilder + // This way doesn't create any intermediate strings. It just stores the string pieces, and ties them together + // when toString() is called. + // Hint: This class is not thread safe. A thread-safe alternative (with some impact on performance) is StringBuffer. + StringBuilder builderConcatenated = new StringBuilder(); + builderConcatenated.append("You "); + builderConcatenated.append("can use "); + builderConcatenated.append("the StringBuilder class."); + System.out.println(builderConcatenated.toString()); // only now is the string built + // Output: You can use the StringBuilder class. + + // #3 - with String formatter + // Another alternative way to create strings. Fast and readable. + String.format("%s may prefer %s.", "Or you", "String.format()"); + // Output: Or you may prefer String.format(). + // Arrays // The array size must be decided upon instantiation // The following formats work for declaring an array @@ -199,6 +232,9 @@ public class LearnJava { // interface. This allows the execution time of basic // operations, such as get and insert element, to remain // constant even for large sets. + // TreeMap - This class is a sorted tree structure. It implements a red + // black tree and sorts the entries based on the key value or + // the comparator provided while creating the object /////////////////////////////////////// // Operators diff --git a/julia.html.markdown b/julia.html.markdown index 23d834f4..5b3f6fd8 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -255,7 +255,7 @@ e, d = d, e # => (5,4) # d is now 5 and e is now 4 empty_dict = Dict() # => Dict{Any,Any}() # You can create a dictionary using a literal -filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] +filled_dict = Dict("one"=> 1, "two"=> 2, "three"=> 3) # => Dict{ASCIIString,Int64} # Look up values with [] @@ -305,7 +305,7 @@ in(10, filled_set) # => false other_set = Set([3, 4, 5, 6]) # => Set{Int64}(6,4,5,3) intersect(filled_set, other_set) # => Set{Int64}(3,4,5) union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6) -setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) +setdiff(Set([1,2,3,4]),Set([2,3,5])) # => Set{Int64}(1,4) #################################################### @@ -346,7 +346,7 @@ end # cat is a mammal # mouse is a mammal -for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] +for a in Dict("dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal") println("$(a[1]) is a $(a[2])") end # prints: @@ -354,7 +354,7 @@ end # cat is a mammal # mouse is a mammal -for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] +for (k,v) in Dict("dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal") println("$k is a $v") end # prints: @@ -445,7 +445,7 @@ end # You can define functions that take keyword arguments function keyword_args(;k1=4,name2="hello") # note the ; - return ["k1"=>k1,"name2"=>name2] + return Dict("k1"=>k1,"name2"=>name2) end keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] diff --git a/kotlin.html.markdown b/kotlin.html.markdown index 7b1475a8..605b1a63 100644 --- a/kotlin.html.markdown +++ b/kotlin.html.markdown @@ -5,7 +5,7 @@ contributors: filename: LearnKotlin.kt --- -Kotlin is a Statically typed programming language for the JVM, Android and the +Kotlin is a statically typed programming language for the JVM, Android and the browser. It is 100% interoperable with Java. [Read more here.](https://kotlinlang.org/) @@ -72,7 +72,7 @@ fun helloWorld(val name : String) { A variable can be specified as nullable by appending a ? to its type. We can access a nullable variable by using the ?. operator. We can use the ?: operator to specify an alternative value to use - if a variable is null + if a variable is null. */ var fooNullable: String? = "abc" println(fooNullable?.length) // => 3 @@ -137,7 +137,7 @@ fun helloWorld(val name : String) { println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}") } - //The "class" keyword is used to declare classes. + // The "class" keyword is used to declare classes. class ExampleClass(val x: Int) { fun memberFunction(y: Int) : Int { return x + y @@ -194,7 +194,7 @@ fun helloWorld(val name : String) { println(fooList.size) // => 3 println(fooList.first()) // => a println(fooList.last()) // => c - // elements can be accessed by index + // Elements of a list can be accessed by their index. println(fooList[1]) // => b // A mutable list can be created using the "mutableListOf" function. @@ -213,12 +213,37 @@ fun helloWorld(val name : String) { // Map values can be accessed by their key. println(fooMap["a"]) // => 8 + /* + Sequences represent lazily-evaluated collections. + We can create a sequence using the "generateSequence" function. + */ + val fooSequence = generateSequence(1, {it + 1}) + val x = fooSequence.take(10).toList() + println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + + // An example of using a sequence to generate Fibonacci numbers: + fun fibonacciSequence() : Sequence<Long> { + var a = 0L + var b = 1L + + fun next() : Long { + val result = a + b + a = b + b = result + return a + } + + return generateSequence(::next) + } + val y = fibonacciSequence().take(10).toList() + println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] + // Kotlin provides higher-order functions for working with collections. - val x = (1..9).map {it * 3} + val z = (1..9).map {it * 3} .filter {it < 20} .groupBy {it % 2 == 0} .mapKeys {if (it.key) "even" else "odd"} - println(x) // => {odd=[3, 9, 15], even=[6, 12, 18]} + println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]} // A "for" loop can be used with anything that provides an iterator. for (c in "hello") { diff --git a/lua.html.markdown b/lua.html.markdown index 2cd4d7bb..1e2d4366 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -190,7 +190,7 @@ end -------------------------------------------------------------------------------- -- A table can have a metatable that gives the table operator-overloadish --- behaviour. Later we'll see how metatables support js-prototypey behaviour. +-- behaviour. Later we'll see how metatables support js-prototype behaviour. f1 = {a = 1, b = 2} -- Represents the fraction a/b. f2 = {a = 2, b = 3} diff --git a/matlab.html.markdown b/matlab.html.markdown index ddc0cb40..51b7bd4e 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -25,6 +25,23 @@ like this %} +% Two percent signs denote the start of a new code section +% Individual code sections can be run by moving the cursor to the section followed by +% either clicking the "Run Section" button +% or using Ctrl+Shift+Enter (Windows) or Cmd+Shift+Return (OS X) + +%% This is the start of a code section +% One way of using sections is to separate expensive but unchanging start-up code like loading data +load myFile.mat y + +%% This is another code section +% This section can be edited and run repeatedly on its own, and is helpful for exploratory programming and demos +A = A * 2; +plot(A); + +%% Code sections are also known as code cells or cell mode (not to be confused with cell arrays) + + % commands can span multiple lines, using '...': a = 1 + 2 + ... + 4 diff --git a/nl-nl/bash-nl.html.markdown b/nl-nl/bash-nl.html.markdown new file mode 100644 index 00000000..da47e2a9 --- /dev/null +++ b/nl-nl/bash-nl.html.markdown @@ -0,0 +1,235 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] +translators: + - ["Jeroen Deviaene", "https://www.github.com/jerodev"] +lang: nl-nl +filename: LearnBash-nl.sh +--- + +Bash is de naam van den unix shell, deze wordt gebruikt voor het GNU operating system en is de standaard shell op Linux en Mac OS X. +Bijna alle voorbeelden hier onder kunnen deel uitmaken van een shell script of kunnen uitgevoerd worden in de shell. + +[Lees er meer over hier.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# De eerste lijn in het schript is shebang, deze laat het systeem weten hoe +# het script uitgevoerd moet worden: http://en.wikipedia.org/wiki/Shebang_(Unix) +# Zoals je kan zien wordt # gebruikt om een commentaar lijn te starten. + +# Simpel hello world voorbeeld: +echo Hello world! + +# Elke command start op een nieuwe lijn, of achter een puntkomma (;): +echo 'Dit is de eerste lijn'; echo 'Dit is de tweede lijn' + +# Een varialbe declareren gebeurt op volgende manier: +Variabele="Een string" + +# Maar niet op deze manier: +Variabele = "Een string" +# Bash ziet variable als een commando en zal een error geven omdat dit commando +# niet bestaat. + +# Of op deze manier: +Variabele= 'Een string' +# Bash zal 'Een string' zien als een commanda en een error geven omdat het niet +# gevonden kan worden. + +# Variabelen gebruiken: +echo $Variabele +echo "$Variabele" +echo '$Variabele' +# Wanneer je een variable wil toekennen, exporteren of nog anders gebruik je +# de naam zonder '$'. Als je de waarde van de variabele wilt, gebruik je een +# '$' voor de naam. + +# Strings vervangen in variables +echo ${Variabele/Een/De} +# Dit zal 'Een' vervangen door 'De' in de string + +# Substring +Length=7 +echo ${Variabele:0:Length} +# Dit zal de eerste 7 tekens van de string weergeven. + +# Standaard waarde voor variabele +echo ${Foo:-"StandaardwaardeAlsFooLeegIsOfNietBestaat"} +# Dit werkt voor null en lege strings (Foo=""). Dit werkt niet voor 0 (Foo=0). +# Merk op dat dit enkel de waarde retourneerd en de variable niet aanpast. + + +# Ingebouwde variabelen: +# Er zijn enkele zeer handige ingebouwde variabelen, zoals: +echo "Return waarde van laatste programma: $?" +echo "PID van dit script: $$" +echo "Aantal argumenten voor dit script: $#" +echo "Alle argumenten voor dit script: $@" +echo "Argumenten voor dit script in apparte variabelen: $1 $2..." + +# Een waarde lezen via input: +echo "Wat is uw naam?" +read Naam # Merk op dat we geen variabele gedeclareerd hebben +echo Hallo, $Naam! + +# We hebben ook if structuren +# Gebruik 'man test' voor meer informatie over condities. +if [ $Naam -ne $USER ] +then + echo "Uw naam is niet gelijk aan de gebruikersnaam" +else + echo "Uw naam is de gebruikersnaam" +fi + +# MERK OP: als $Naam leeg is ziet bash het bovenstaande als volgt: +if [ -ne $USER ] +# dit is ongeldige syntax +# Dus de beter manier om dit te schrijven is +if [ "$Naam" -ne $USER ] ... +# Als naam nu leeg is, ziet bash nu nog steeds +if [ "" -ne $USER ] ... +# Dit werkt wel zoals het hoort + +# Er is ook conditionele executie +echo "Altijd uitvoeren" || echo "Enkel uitvoeren als vorige command mislukt" +echo "Altijd uitvoeren" && echo "Enkel uitvoeren als vorige command NIET mislukt" + +# Om && en || te gebruiken in if structuren moeten vierkante haken gebruikt worden: +if [ "$Naam" == "Steve" ] && [ "$Leeftijd" -eq 15 ] +then + echo "Dit wordt uitgevoerd als $Naam Steve is en $Leeftijd 15 is." +fi + +# Expressies worden gemaakt met volgende syntax: +echo $(( 10 + 5 )) + +# Bash werkt steeds in de context van een huidige map in het bestandssysteem. +# Bestanden en mappen in de huidige map kunnen weergegeven worden met het ls +# commando. +ls + +# Commandos hebben opties die de uitvoer beinvloeden +ls -l # Lijst elk bestand en map op een nieuwe lijn. + +# Resultaten van een vorig commando kunnen doorgegeven worden aan een volgend +# commando als input. +# Het grep commando filter de input met een bepaald patroon. Op deze manier kunnen +# we alle .txt bestanden weergeven in de huidige map. +ls -l | grep "\.txt" + +# Commando's kunnen gekoppeld worden met andere commando's door gebruik te maken van +# $( ): +# Het volgende commando geeft het aantal bestanden weer in de huidige map +echo "Er zijn hier $(ls | wc -l) bestanden." + +# Het zelfde kan gedaan worden met `, maar die kunnen niet genest worden. De methode +# bij voorkeur is om $( ) te gebruiken. +echo "Er zijn hier `ls | wc -l` bestanden." + +# Bash heeft een case statement dat werkt zoals in Java en C++ +case "$Variabele" in + 0) echo "Er is een 0";; + 1) echo "Er is een 1";; + *) echo "Er is iets";; +esac + +# For lussen itereren over de gegeven argumenten +# De waarde van $Variabele wordt hier drie keer afgeprint +for Variable in {1..3} +do + echo "$Variabele" +done + +# Of schrijf een traditionele for loop op deze manier +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Lussen kunnen ook gebruikt worden met bestanden +# Deze lus voert het cat commando uit op file1 en file2 +for Variable in file1 file2 +do + cat "$Variable" +done + +# Of met het output commando +for Output in $(ls) +do + cat "$Output" +done + +# while lus: +while [ true ] +do + echo "body van de lus..." + break +done + +# Je kan ook functies aanmaken +# Defenitie: +function foo () +{ + echo "Alle argumenten: $@" + echo "Apparte argumenten: $1 $2..." + echo "Dit is een functie" + return 0 +} + +# Of simpeler +bar () +{ + echo "Dit is een andere manier om functies te maken." + return 0 +} + +# Functies oproepen +foo "Mijn naam is" $Naam + +# Enkele zeer handige commando's die je moet kennen +# print de laatste 10 lijnen van file.txt +tail -n 10 file.txt +# print de eerste 10 lijnen van file.txt +head -n 10 file.txt +# Sorteer de lijnen in file.txt +sort file.txt +# Vind dubbele lijnen in file.txt +uniq -d file.txt +# Print de eerste kolom voor het ',' karakter +cut -d ',' -f 1 file.txt +# Vervang elke 'okay' met 'great' in file.txt (werkt ook met regex) +sed -i 's/okay/great/g' file.txt +# Print alle lijnen die voldoen aan de regex naar stdout +grep "^foo.*bar$" file.txt + + +# Gebruik de ingebouwde help functies door het help commando te gebruiken: +help +help help +help for +help return +help source +help . + +# Lees de bash documentatie met het man commando: +apropos bash +man 1 bash +man bash + +# Lees bash info documentatie: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` diff --git a/nl-nl/markdown-nl-html.markdown b/nl-nl/markdown-nl-html.markdown new file mode 100644 index 00000000..0f954715 --- /dev/null +++ b/nl-nl/markdown-nl-html.markdown @@ -0,0 +1,256 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +filename: learnmarkdown-nl.md +translators: + - ["Niels van Velzen", "https://nielsvanvelzen.me"] +lang: nl-nl +--- + +Markdown is gemaakt door John Gruber in 2004. De bedoeling was om een simpel te +lezen en schrijven syntax te creëren wat makkelijk om te zetten is naar +HTML (en tegenwoordig ook vele andere formaten). + +```markdown +<!-- Markdown is een superset van HTML, ofterwijl: een HTML bestand is +geldige Markdown code. Daardoor kunnen we dus HTML elementen in Markdown gebruiken. +Let wel op dat je geen markdown syntax in een HTML element kan gebruiken. --> + +<!-- Markdown verschilt ook in implementatie tussen verschillende parsers. In dit +artikel wordt aangegeven of iets overal werkt of alleen bij specifieke implementaties --> + +<!-- Koppen --> +<!-- Je kan HTML koppen (<h1 - 6>) makkelijk maken met markdown door +een aantal hekjes te gebruiken (#) --> +# Dit is een <h1> +## Dit is een <h2> +### Dit is een <h3> +#### Dit is een <h4> +##### Dit is een <h5> +###### Dit is een <h6> + +<!-- Voor h1 en h2 zijn er ook nog alternatieve methodes --> +Dit is een h1 +============= + +Dit is een h2 +------------- + +<!-- Simpele text stijlen --> +<!-- Tekst kan makkelijk vet of shuin gedrukt worden --> + +*Deze tekst staat schuin.* +_Net als deze tekst._ + +**Deze tekst is dikgedrukt.** +__Net als deze tekst.__ + +***En deze tekst is dik en schuin.*** +**_Net als dit!_** +*__En dit!__* + +<!-- In Github's markdown stijl is er ook een doorhaal mogelijkheid --> + +~~Deze tekst is doorgehaald.~~ + +<!-- Paragraphs are a one or multiple adjacent lines of text separated by one or +multiple blank lines. --> +<!-- Paragrafen zijn een of meerdere aan elkaar lopende lijnen gescheiden door +een of meerdere lege lijnen --> + +Dit is een paragraaf. Ik typ in een paragraaf, is dat niet leuk? + +Nu ben ik in paragraaf 2. +Nog steeds in paragraaf 2! + +Dit is paragraaf drie! + +<!-- Wil je een nieuwe regel starten zonder de <br /> tag van HTML te gebruiken? +Je kunt een paragraaf eindigen met twee of meer spaties en dan een nieuwe paragraaf +beginnen --> + +Ik eindig met twee spaties (selecteer mij om het te zien). + +Er is een nieuwe regel boven mij! + +<!-- Citaten zijn makkelijk en worden gemaakt met het >. --> + +> Dit is een citaat. Je kan +> handmatig je lijnen laten vormen of je kan je lijnen lang laten worden en vanzelf op nieuwe regels verder laten gaan. +> Het maakt niet uit zolang je maar begint met een `>`. + +> Je kunt ook meer dan 1 level +>> uitlijning gebruiken. +> Hoe handig is dat? + +<!-- Lijsten --> +<!-- Ongesorteerde lijsten kanje maken met sterretjes, plussen of koppeltekens --> + +* Item +* Item +* Nog een item + +of + ++ Item ++ Item ++ Nog een item + +of + +- Item +- Item +- Nog een item + +<!-- Geordende lijsten maak je met een nummer gevolgt door een punt --> + +1. Item een +2. Item twee +3. Item drie + +<!-- Je hoeft niet een correct getal te gebruiken en markdown zal nogsteeds werken, +ondanks dat het werkt is het niet aangeraden --> + +1. Item een +1. Item twee +1. Item drie + +<!-- (Dit is getzelfde als het voorbeeld hierboven) --> + +<!-- Je kan ook lijsten in lijsten gebruiken --> + +1. Item een +2. Item twee +3. Item drie + * Sub-item een + * Sub-item twee +4. Item vier + +<!-- Er zijn ook taken lijsten. Hier worden HTML checkboxes gebruikt --> + +Checkboxes hieronder zonder de 'x' zijn leeg. +- [ ] Eerste taak. +- [ ] Tweede taak +Checkboxes met een 'x' zijn klaar. +- [x] Deze taak is klaar. + +<!-- Code blokken --> +<!-- Je kunt een code blok maken door te inspringen met vier spaties fo een tab --> + + Dit is code + net als dit + +<!-- Je kan ook extra tabs (of spaties) gebruiken voor het inspringen in je code --> + + mijn_array.each do |item| + puts item + end + +<!-- Inline code kan worden gemaakt met het backtick karakter ` --> + +John wist niet eens wat de `go_to()` functie deed! + +<!-- In Github's markdown stijl is er een speciale syntax voor code --> + +\`\`\`ruby <!-- alleen moet je de backslashes weghalen als je dit doet, gewoon ```ruby dus! --> +def foobar + puts "Hallo wereld!" +end +\`\`\` <!-- hier ook, geen backslashes ``` --> + +<!-- Voor de bovenstaande syntax hoef je niet te inspringen. Daarnaast kan Github "syntax highlighting" geven. --> + +<!-- Horizontale regel (<hr />) --> +<!-- Horizontale regel zijn makkelijk toegevoegd met drie of meer sterretjes of +koppeltekens, met of zonder spaties. --> + +*** +--- +- - - +**************** + +<!-- Links --> +<!-- Een van de beste dingen van markdown is het maken van links. +De tekst om te weergeven plaats je tussen harde brackets [] gevolgd door de link tussen haakjes. --> + +[Klik op mij!](http://test.com/) + +<!-- Je kunt ook een titel aan de link defineren met quotes --> + +[Klik op mij!](http://test.com/ "Link naar Test.com") + +<!-- Relative paden werken ook. --> + +[Ga naar de muziek](/music/). + +<!-- Markdown support ook ankers --> + +[Klik op deze link][link1] vor meer informatie erover! +[Bekijk deze ook eens][foobar] als je wilt. + +[link1]: http://test.com/ "Cool!" +[foobar]: http://foobar.biz/ "In orde!" + +<!-- De titel kan ook in enkele quotes, tussen haakjes of gewoon zonder iets. +De refferentie kan overal in het document geplaats worden en zo lang als je wilt. +Zolang het maar uniek blijft --> + +<!-- Er is ook "impliciete naamgeving" wat de tekst en de link hetzelfde maakt --> + +[Dit][] is een link. + +[dit]: http://ditiseenlink.nl/ + +<!-- Dat is wel weinig gebruikt. --> + +<!-- Plaatjes --> +<!-- Plaatjes werken nar als links maar dan met een uitroepteken --> + +![Dit is de alt attribuut van het plaatje](http://imgur.com/myimage.jpg "Een optionele titel") + +<!-- En refferentie stijl werkt zoals verwacht --> + +![Dit is de alt attribuut.][mijnplaatje] + +[mijnplaatje]: relative/urls/cool/image.jpg "Hier is de titel" + +<!-- Diverse --> +<!-- Auto-links --> + +<http://testwebsite.com/> is hetzelfde als +[http://testwebsite.com/](http://testwebsite.com/) + +<!-- Auto-links voor emails --> + +<foo@bar.com> + +<!-- Escaping --> + +Ik wil *deze tekst met sterretjes typen* maar ik wil het niet schuin, dus ik doe dit: \*deze tekst met sterretjes typen\*. + +<!-- Toetsenbord toetsen --> +<!-- In Github's markdown stijl kan je de <kbd> tag gebruiken --> + +Computer gecrashed? Gebruik eens +<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd> + +<!-- Tabellen --> +<!-- Tabellen werken alleen in Github's stijl: --> + +| kolom1 | kolom2 |kolom3 | +| :--------------- | :---------: | ----------------: | +| Links-uitgelijnd | Gecentreerd | Rechts-uitgelijnd | +| blah | blah | blah | + +<!-- of, voor dezelfde resultaten --> + +Kolom 1 | Kolom 2 | Kolom 3 +:-- | :-: | --: +Dit is zo lelijk | stop | er mee + +<!-- Einde! --> + +``` + +Voor meer informatie, bekijk Josn Gruber's officiele post over de syntax [hier](http://daringfireball.net/projects/markdown/syntax). Of bekijk Adam Pritchard's grote cheatsheet [hier](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) (beide Engels). diff --git a/nl-nl/markdown-nl.html.markdown b/nl-nl/markdown-nl.html.markdown new file mode 100644 index 00000000..35cc67c5 --- /dev/null +++ b/nl-nl/markdown-nl.html.markdown @@ -0,0 +1,242 @@ +--- +language: markdown +filename: markdown-nl.md +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Jeroen Deviaene", "https://www.github.com/jerodev"] +lang: nl-nl +--- + +Markdown is gecreëerd door John Gruber in 2004. Het is bedoeld om met een gemakkelijke te lezen en +schrijven syntax te zijn die gemakkelijk omgevormd kan worden naar HTML (en op heden verschillende +andere formaten) + +```markdown +<!-- Markdown erft over van HTML, dus ieder HTML bestand is een geldig Markdown +bestand. Dit betekend ook dat html elementen gebruikt kunnen worden in Markdown +zoals het commentaar element. Echter, als je een html element maakt in een Markdown +document kan je geen markdown gebruiken voor de waarde van dat element. --> + +<!-- Markdown varieert ook van implementatie tot implementatie en per parser. Deze +tutorial zal de universele functies van Markdown --> + +<!-- Headers --> +<!-- Je kan de HTML elementen <h1> tot <h6> gemakkelijk maken door voor de titel +een aantal hashes (#) te plaatsen gelijk aan het level van de header. +# Dit is een <h1> +## Dit is een <h2> +### Dit is een <h3> +#### Dit is een <h4> +##### Dit is een <h5> +###### Dit is een <h6> + +<!-- Markdown heeft ook een alternatieve manier om h1 en h2 te maken --> +Dit is een h1 +============= + +Dit is een h2 +------------- + +<!-- Simpele tekst stijlen --> +<!-- Tekst kan heel gemakelijk gestyled worden cursief of bold met markdown --> + +*Deze tekst is cursief* +_Deze tekst ook_ + +**Deze tekst is vet gedrukt** +__En deze tekst ook!__ + +***Deze tekst is zowel bold als schuin gedrukt*** +**_Deze ook!_** +*__En zelfs deze!__* + +<!-- In de github versie van markdown, die gebruikt wordt om markdown te renderen +op Github, is er ook doorstrepen --> + +~~Deze tekst wordt doorstreept.~~ + +<!-- Paragrafen worden onderscheiden door een of meerdere lege lijnen --> + +Dit is een paragraaf. + +Dit is paragraaf 2. +Dit is nog steeds paragraaf 2! + + +Hallo, ik ben paragraaf 3. + +<!-- Citaten zijn gemakkelijk te maken met het '>' karakter. --> + +> Dit is een citaat. Je kan alle lijnen manueel starten met een '>'. +> Of je kan de lijn heel heel, heel, lang laten worden zodat de parser deze automatisch zal afbreken en op een nieuwe lijn plaatsen. +> Het maakt niet uit, zolang je start met een '>'. + +> Je kan ook in niveaus werken +>> Niveau 2 +> Hoe leuk is dat? + +<!-- Lijsten --> +<!-- Niet geordende lijsten kunnen gemaakt worden met sterretjes, plussen of streepjes --> + +* Item +* Item +* Nog een item + +of + ++ Item ++ Item ++ Nog een item + +of + +- Item +- Item +- Een laatste item + +<!-- Geordende lijsten kunnen gemaakt wroden met cijfers --> + +1. Item een +2. Item twee +3. Item drie + +<!-- Het getal moet zelfs niet overeen komen met het item in de lijst, markdown zal +automatisch de nummers aanpassen --> + +1. Item een +1. Item twe +1. Item drie +<!-- (De output is gelijk aan de vorige lijst) --> + +<!-- Je kan ook gebruik maken van sub lijsten --> + +1. Item een +2. Item twee +3. Item drie + * Sub-item + * Sub-item +4. Item vier + +<!-- Er zijn zelfs todo lijsten. Dit genereert HTML checkboxen. --> + +Boxen zonder een 'x' zijn niet aangevinkt +- [ ] Eerste to-do item. +- [ ] Tweede to-do item +Dit item zal aangevinkt zijn in de gerenderde html. +- [x] Deze taak is uitgevoerd + +<!-- Code blokken --> +<!-- Een code block kan aangeduid worden door vier spaties of een tab --> + + Dit is code + En dit ook + +<!-- Extra tabs kunnen gebruikt worden om tabs in de code aan te geven --> + + my_array.each do |item| + puts item + end + +<!-- Inline code kan aangeduid worden met ` --> + +John wist zelfs niet dat de `go_to()` functie bestond! + +<!-- In Github Markdown kan je een speciale syntax gebruiken die aangeeft welke +taal gebruikt wordt in het code blok. --> + +\`\`\`ruby <!-- Wis de backslashes om dit te doen, juist ```ruby ! --> +def foobar + puts "Hello world!" +end +\`\`\` <!-- Hier ook, geen backslashes, juist ``` --> + +<!-- Voor bovenstaande tekst moet geen tab gebruikt worden. Plus, Github zal syntax +highlighting gebruiken voor deze specifieke taal. Hier, Ruby. + +<!-- Horizontale lijn (<hr />) --> +<!-- Horizontale lijnen kunnen gemakkelijk toegevoegd worden door drie of meer +sterretjes, of streepjes te plaatsen --> + +*** +--- +- - - +**************** + +<!-- Links --> +<!-- Een van de beste dingen in Markdown is hoe simpel het is om links te maken. +plaats de tekst om weer te geven tussen [ en ] gevolgd door de link tussen ( en ) --> + +[Klik mij!](http://test.com/) + +<!-- Een titel kan ook toegevoegd worden aan de link met aanhalingstekens --> + +[Klik mij!](http://test.com/ "Titel voor de link") + +<!-- Relative paden werken ook --> + +[Naar de muziek](/music/). + +<!-- Links kunnen ook gelegd worden met referenties --> + +[Klik deze link][link1] voor meer info! +[Beijk ook dit][foobar] als je echt wil. + +[link1]: http://test.com/ "Cool!" +[foobar]: http://foobar.biz/ "Tof!" + + +<!-- Afbeeldingen --> +<!-- Afbeeldingen worden toegevoegd op exact de zelfde manier als links maar met een +uitroepteken aan het begin van de lijn. --> + +![Dit is de alt waarde van een afbeelding](http://imgur.com/myimage.jpg "Optionele titel") + +<!-- Referenties werkt ook zals bij links --> + +![Dit is de alt waarde][myimage] + +[myimage]: relative/urls/cool/image.jpg "als een titel nodig is, staat deze hier" + +<!-- Varia --> +<!-- Auto-links --> + +<http://testwebsite.com/> is gelijk aan +[http://testwebsite.com/](http://testwebsite.com/) + +<!-- Auto-links for emails --> + +<foo@bar.com> + +<!-- Karakters escapen --> + +Als je sterretjes wil gebruiken in je tekst zoals *dit* dan zal dit schuingedrukt weergegeven +worden. +Dit kan je oplossen met backslashes: \*dit\* staat tussen sterretjes + +<!-- Toetsenbord toetsen --> +<!-- In Github Markdown, kan je <kbd> gebruiken om toetsenbord toetsen weer te geven --> + +Loopt je computer vast? Probeer volgende toetsen combinatie: +<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd> + +<!-- Tabellen --> +<!-- Tabellen zijn momenteel enkel beschikbaar in Github Markdown en zijn redelijk omslachtig. +Maar als je er echt wilt toevoegen: --> + +| Col1 | Col2 | Col3 | +| :--------------- | :---------: | ----------------: | +| Links uitgelijnt | Gecentreerd | Rechts uitgelijnt | +| blah | blah | blah | + +<!-- of, Voor het zelfde resultaat --> + +Col 1 | Col2 | Col3 +:-- | :-: | --: +Zeer | Lelijke | Code! + +<!-- The end! --> + +``` + +Voor meer info, bekijk de officiële post van John Gruber [hier](http://daringfireball.net/projects/markdown/syntax) en de handige cheatsheet van Adam Pritchard [hier](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). diff --git a/nl-nl/yaml-nl.html.markdown b/nl-nl/yaml-nl.html.markdown index a4a9d5fc..11af784f 100644 --- a/nl-nl/yaml-nl.html.markdown +++ b/nl-nl/yaml-nl.html.markdown @@ -5,21 +5,22 @@ contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] translators: - ["Niels van Velzen", "https://nielsvanvelzen.me"] + - ["Sam van Kampen", "http://tehsvk.net"] lang: nl-nl --- -YAML is een data serialisatie taal ontworpen om snel te kunnen worden begrepen door mensen. +YAML is een dataserialisatietaal ontworpen om snel te kunnen worden begrepen door mensen. -Het is een strikte superset van JSON en bevat nieuwe regels en een stricte manier van inspringen, zoals bij Python. In tegenstelling tot Python kan je alleen geen tab tekens gebruiken. +Het is een strikte superset van JSON en bevat nieuwe regels en een strikte manier van inspringen die lijkt op de manier van Python. In tegenstelling tot Python kan je alleen geen tabtekens gebruiken. ```yaml # Commentaar in YAML ziet er zo uit -################ -# SCALAR TYPES # -################ +################## +# SCALAIRE TYPES # +################## -# Ons hoofd object (Wat in het hele document gebruikt wordt) is een map, +# Ons hoofdobject (Wat in het hele document gebruikt wordt) is een map; # dit staat gelijk aan een dictionary, hash of object in andere talen. sleutel: waarde nog_een_sleutel: Een andere waarde @@ -35,10 +36,10 @@ quote_waarde: "Een string in quotes" # Tekst over meerdere lijnen kan je schrijven als een 'letterlijk blok' (met |) # Of een 'gevouwen blok' (met >) letterlijk_blok: | - Dit hele blok met tekst is de waarde van de 'letterlijk_blok' sleutel, + Dit hele blok met tekst is de waarde van de 'letterlijk_blok'-sleutel, met nieuwe lijnen behouden. - Het blok blijft door gaan tot het geeindigd wordt door korter te inspringen. + Het blok blijft door gaan tot het geeindigd wordt door korter in te springen. Lijnen die groter zijn ingesprongen behouden dit. gevouwen_stijl: > @@ -50,9 +51,9 @@ gevouwen_stijl: > Meer ingesprongen lijnen zullen hun nieuwe lijnen ook behouden, deze tekst zal over 2 lijnen te zien zijn. -#################### -# COLLECTION TYPES # -#################### +################## +# COLLECTIETYPES # +################## # Nesten wordt bereikt met inspringen. geneste_map: @@ -61,7 +62,7 @@ geneste_map: andere_geneste_map: hallo: wereld -# In een map is een sleutel niet verplicht om een string te gebruiken +# In een map hoeft de sleutel geen string te zijn. 0.25: een float als sleutel # Sleutels kunnen ook meerdere lijnen gebruiken met behulp van het vraagteken @@ -70,14 +71,14 @@ geneste_map: met meerdere lijnen : en dit is de waarde -# YAML staat ook collection types toe in sleutels, maar veel programmeertalen +# YAML staat ook collectietypes toe in sleutels, maar veel programmeertalen # zullen hierover klagen. # Sequences (gelijk aan lijsten of arrays) zien er zo uit: een_sequence: - Item 1 - Item 2 - - 0.5 # sequences kunnen meerdere type waardes bevatten. + - 0.5 # sequences kunnen meerdere typen waardes bevatten. - Item 4 - sleutel: waarde andere_sleutel: andere waarde @@ -85,13 +86,13 @@ een_sequence: - Dit is een sequence - in een andere sequence -# Doordat YAML een superset van JSON is kan je ook JSON-stijl mappen en -# sequences maken: +# Doordat YAML een superset van JSON is kan je ook mappen en +# sequences volgens de JSON-stijl maken: json_map: {"sleutel": "waarde"} json_seq: [3, 2, 1, "takeoff"] ####################### -# EXTRA YAML FUNCTIES # +# EXTRA YAML-FUNCTIES # ####################### # YAML heeft ook een handige functie genaamd 'anchors' (ankers), deze laten je @@ -102,16 +103,16 @@ andere_anker: *anker_naam # YAML heeft ook tags, deze gebruik je om een expliciet type te verklaren expliciete_string: !!str 0.5 -# Sommige parsers gebruiken taal specifieke tags, zoals deze voor Python's -# complexe nummer type: +# Sommige parsers gebruiken taalspecifieke tags, zoals deze voor Python's +# complexe nummertype: python_complex_nummer: !!python/complex 1+2j -#################### -# EXTRA YAML TYPES # -#################### +####################### +# EXTRA TYPES IN YAML # +####################### -# Strings en nummer zijn niet de enige types die YAML begrijpt. -# ISO opgemaakte datum en datumtijd notaties werken ook: +# Strings en nummers zijn niet de enige types die YAML begrijpt. +# ISO opgemaakte datum- en datumtijdnotaties werken ook: datumtijd: 2001-12-15T02:59:43.1Z datumtijd_met_spaties: 2001-12-14 21:59:43.10 -5 datum: 2002-12-14 @@ -124,13 +125,13 @@ gif_bestand: !!binary | +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= -# YAML heeft ook een set type, dat ziet er zo uit: +# YAML heeft ook een settype, dat ziet er zo uit: set: ? item1 ? item2 ? item3 -# Zoals in Python zijn sets gewoon mappen met null waardes; +# Zoals in Python zijn sets gewoon mappen met nulwaarden; # bovenstaand is gelijk aan: set2: item1: null diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 0dbb3ae3..2b599378 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -133,6 +133,8 @@ int main (int argc, const char * argv[]) NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; NSLog(@"Third number = %@", thirdNumber); // prints => "Third number = 3" + // Since Xcode 7, NSArray objects can be typed (Generics) + NSArray<NSString *> *stringArray = @[@"hello", @"world"]; // NSMutableArray is a mutable version of NSArray, allowing you to change // the items in the array and to extend or shrink the array object. // Convenient, but not as efficient as NSArray. @@ -146,6 +148,8 @@ int main (int argc, const char * argv[]) NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; NSObject *valueObject = aDictionary[@"A Key"]; NSLog(@"Object = %@", valueObject); // prints => "Object = (null)" + // Since Xcode 7, NSDictionary objects can be typed (Generics) + NSDictionary<NSString *, NSNumber *> *numberDictionary = @{@"a": @1, @"b": @2}; // NSMutableDictionary also available as a mutable dictionary object NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; [mutableDictionary setObject:@"value1" forKey:@"key1"]; @@ -161,6 +165,8 @@ int main (int argc, const char * argv[]) // Set object NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order) + // Since Xcode 7, NSSet objects can be typed (Generics) + NSSet<NSString *> *stringSet = [NSSet setWithObjects:@"hello", @"world", nil]; // NSMutableSet also available as a mutable set object NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2]; [mutableSet addObject:@"Hello"]; diff --git a/pcre.html.markdown b/pcre.html.markdown new file mode 100644 index 00000000..0b61653d --- /dev/null +++ b/pcre.html.markdown @@ -0,0 +1,82 @@ +--- +language: PCRE +filename: pcre.txt +contributors: + - ["Sachin Divekar", "http://github.com/ssd532"] + +--- + +A regular expression (regex or regexp for short) is a special text string for describing a search pattern. e.g. to extract domain name from a string we can say `/^[a-z]+:/` and it will match `http:` from `http://github.com/`. + +PCRE (Perl Compatible Regular Expressions) is a C library implementing regex. It was written in 1997 when Perl was the de-facto choice for complex text processing tasks. The syntax for patterns used in PCRE closely resembles Perl. PCRE syntax is being used in many big projects including PHP, Apache, R to name a few. + + +There are two different sets of metacharacters: +* Those that are recognized anywhere in the pattern except within square brackets +``` + \ general escape character with several uses + ^ assert start of string (or line, in multiline mode) + $ assert end of string (or line, in multiline mode) + . match any character except newline (by default) + [ start character class definition + | start of alternative branch + ( start subpattern + ) end subpattern + ? extends the meaning of ( + also 0 or 1 quantifier + also quantifier minimizer + * 0 or more quantifier + + 1 or more quantifier + also "possessive quantifier" + { start min/max quantifier +``` + +* Those that are recognized within square brackets. Outside square brackets. They are also called as character classes. + +``` + + \ general escape character + ^ negate the class, but only if the first character + - indicates character range + [ POSIX character class (only if followed by POSIX syntax) + ] terminates the character class + +``` + +PCRE provides some generic character types, also called as character classes. +``` + \d any decimal digit + \D any character that is not a decimal digit + \h any horizontal white space character + \H any character that is not a horizontal white space character + \s any white space character + \S any character that is not a white space character + \v any vertical white space character + \V any character that is not a vertical white space character + \w any "word" character + \W any "non-word" character +``` + +## Examples + +We will test our examples on following string `66.249.64.13 - - [18/Sep/2004:11:07:48 +1000] "GET /robots.txt HTTP/1.0" 200 468 "-" "Googlebot/2.1"`. It is a standard Apache access log. + +| Regex | Result | Comment | +| :---- | :-------------- | :------ | +| GET | GET | GET matches the characters GET literally (case sensitive) | +| \d+.\d+.\d+.\d+ | 66.249.64.13 | `\d+` match a digit [0-9] one or more times defined by `+` quantifier, `\.` matches `.` literally | +| (\d+\.){3}\d+ | 66.249.64.13 | `(\d+\.){3}` is trying to match group (`\d+\.`) exactly three times. | +| \[.+\] | [18/Sep/2004:11:07:48 +1000] | `.+` matches any character (except newline), `.` is any character | +| ^\S+ | 66.249.64.13 | `^` means start of the line, `\S+` matches any number of non-space characters | +| \+[0-9]+ | +1000 | `\+` matches the character `+` literally. `[0-9]` character class means single number. Same can be achieved using `\+\d+` | + +All these examples can be tried at https://regex101.com/ + +1. Copy the example string in `TEST STRING` section +2. Copy regex code in `Regular Expression` section +3. The web application will show the matching result + + +## Further Reading + + diff --git a/php-composer.html.markdown b/php-composer.html.markdown new file mode 100644 index 00000000..16fed582 --- /dev/null +++ b/php-composer.html.markdown @@ -0,0 +1,167 @@ +--- +category: tool +tool: composer +contributors: + - ["Brett Taylor", "https://github.com/glutnix"] +filename: LearnComposer.sh +--- + +[Composer](https://getcomposer.org/) is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. + +# Installing + +```sh +# Installs the composer.phar binary into the current directory +curl -sS https://getcomposer.org/installer | php +# If you use this approach, you will need to invoke composer like this: +php composer.phar about + +# Installs the binary into ~/bin/composer +# Note: make sure ~/bin is in your shell's PATH environment variable +curl -sS https://getcomposer.org/installer | php -- --install-dir=~/bin --filename=composer +``` + +Windows users should follow the [Windows installation instructions](https://getcomposer.org/doc/00-intro.md#installation-windows) + +## Confirming installation + +```sh +# Check version and list options +composer + +# Get more help for options +composer help require + +# Check if Composer is able to do the things it needs, and if it's up to date +composer diagnose +composer diag # shorthand + +# Updates the Composer binary to the latest version +composer self-update +composer self # shorthand +``` + +# Usage + +Composer stores your project dependencies in `composer.json`. You can edit this file, but it is best to let Composer manage it for you. + +```sh +# Create a new project in the current folder +composer init +# runs an interactive questionnaire asking you for details about your project. Leaving them blank is fine unless you are making other projects dependent on this one. + +# If a composer.json file already exists, download the dependencies +composer install + +# To download the just the production dependencies, i.e. excluding development dependencies +composer install --no-dev + +# Add a production dependency to this project +composer require guzzlehttp/guzzle +# will figure out what the latest version of guzzlehttp/guzzle is, download it, and add the new dependency to composer.json's require field. + +composer require guzzlehttp/guzzle:6.0.* +# will download the latest version matching the pattern (eg. 6.0.2) and add the dependency to composer.json's require field + +composer require --dev phpunit/phpunit:~4.5.0 +# will require as a development dependency. Will use the latest version >=4.5.0 and < 4.6.0 + +composer require-dev phpunit/phpunit:^4.5.0 +# will require as a development dependency. Will use the latest version >=4.5.0 and < 5.0 + +# For more information on Composer version matching, see [Composer's documentation on Versions](https://getcomposer.org/doc/articles/versions.md) for more details + +# To see what packages are available to install and currently installed +composer show + +# To see what packages are currently installed +composer show --installed + +# To find a package with 'mailgun' in its name or description +composer search mailgun +``` + +[Packagist.org](https://packagist.org/) is the main repository for Composer packages. Search there for existing third-party packages. + +## `composer.json` vs `composer.lock` + +The `composer.json` file stores your project's floating version preferences for each dependency, along with other information. + +The `composer.lock` file stores exactly which version it has downloaded for each dependency. Never edit this file. + +If you include the `composer.lock` file in your git repository, every developer will install the currently used version of the dependency. Even when a new version of a dependency is released, Composer will continue to download the version recorded in the lock file. + +```sh +# If you want to update all the dependencies to their newest version still matching your version preferences +composer update + +# If you want the new version of a particular dependency: +composer update phpunit/phpunit + +# If you wish to migrate a package to a newer version preference, you may need to remove the older package and its dependencies first. +composer remove --dev phpunit/phpunit +composer require --dev phpunit/phpunit:^5.0 + +``` + +## Autoloader + +Composer creates an autoloader class you can require from your application. You can make instances of classes via their namespace. + +```php +require __DIR__ . '/vendor/autoload.php'; + +$mailgun = new Mailgun\Mailgun("key"); +``` + +### PSR-4 Autoloader + +You can add your own namespaces to the autoloader. + +In `composer.json`, add a 'autoload' field: + +```json +{ + "autoload": { + "psr-4": {"Acme\\": "src/"} + } +} +``` +This will tell the autoloader to look for anything in the `\Acme\` namespace within the `src` folder. + +You can also [use PSR-0, a Classmap or just a list of files to include](https://getcomposer.org/doc/04-schema.md#autoload). There is also the `autoload-dev` field for development-only namespaces. + +When adding or modifying the autoload key, you will need to rebuild the autoloader: + +```sh +composer dump-autoload +composer dump # shorthand + +# Optimizes PSR0 and PSR4 packages to be loaded with classmaps too. Slow to run, but improves performance on production. +composer dump-autoload --optimize --no-dev +``` + +# Composer's Cache + +```sh +# Composer will retain downloaded packages to use in the future. Clear it with: +composer clear-cache +``` + +# Troubleshooting + +```sh +composer diagnose +composer self-update +composer clear-cache +``` + +## Topics not (yet) covered in this tutorial + +* Creating and distributing your own packages on Packagist.org or elsewhere +* Pre- and post- script hooks: run tasks when certain composer events take place + +### References + +* [Composer - Dependency Manager for PHP](https://getcomposer.org/) +* [Packagist.org](https://packagist.org/) diff --git a/php.html.markdown b/php.html.markdown index 6c2b38c8..24d656fa 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -88,6 +88,8 @@ $escaped = "This contains a \t tab character."; $unescaped = 'This just contains a slash and a t: \t'; // Enclose a variable in curly braces if needed +$apples = "I have {$number} apples to eat."; +$oranges = "I have ${number} oranges to eat."; $money = "I have $${number} in the bank."; // Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners diff --git a/pl-pl/json-pl.html.markdown b/pl-pl/json-pl.html.markdown new file mode 100644 index 00000000..872455de --- /dev/null +++ b/pl-pl/json-pl.html.markdown @@ -0,0 +1,85 @@ +--- +language: json +filename: learnjson-pl.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] + - ["Michael Neth", "https://github.com/infernocloud"] +translators: + - ["Michał Mitrosz", "https://github.com/Voltinus"] +lang: pl-pl +--- + +JSON to bardzo prosty format wymiany danych. Jak jest napisane na [json.org](http://json.org), jest łatwy do pisania i czytania dla ludzi i do parsowania i generowania dla maszyn. + +Kod JSON musi zawierać któreś z poniższych: +* Zbiór par nazwa/wartość (`{ }`). W różnych językach jest to obiekt, rekord, struktura, słownik, tablica mieszająca, lista z kluczami, lub tablica asocjacyjna. +* Uporządkowana lista wartości (`[ ]`). W różnych językach jest to tablica, wektor, lista, lub sekwencja. + tablica/lista/sekwencja (`[ ]`) lub słownik/obiekt/tablica asocjacyjna (`{ }`). + +JSON w swojej czystej postaci nie ma komentarzy, ale większość parserów akceptuje komentarze w stylu C (`//`, `/* */`). Niektóre parsery pozwalają także na końcowy przecinek (np. przecinek po ostatnim elemencie w tablicy lub po ostatiej własności obiektu), ale powinien on być omijany dla lepszej kompatybilności. + +Dla celów tego poradnika wszystko będzie 100% kodem JSON. Na szczęście, to samo mówi za siebie. + +Wspierane typy danych: + +* Łańcuchy znaków: `"witaj"`, `"\"Cytat.\""`, `"\u0abe"`, `"Nowa linia.\n"` +* Liczby: `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4` +* Obiekty: `{ "klucz": "wartość" }` +* Tablice: `["Wartości"]` +* Inne: `true`, `false`, `null` + +```json +{ + "klucz": "wartość", + + "klucze": "muszą być zawsze zamknięte w podwójnych cudzysłowach", + "liczby": 0, + "łańcuchy": "Hellø, wørld. Wszystkie znaki unicode są dozwolone, razem z \"sekwencjami escape\".", + "wartości logiczne?": true, + "nic": null, + + "duża liczba": 1.2e+100, + + "obiekty": { + "komentarz": "Większość twojej struktury będzie zbudowana z obiektów.", + + "tablica": [0, 1, 2, 3, "Tablice mogą mieć wewnątrz cokolwiek", 5], + + "inny obiekt": { + "komentarz": "Elementy mogą się w sobie zawierać, bardzo użyteczne" + } + }, + + "głupota": [ + { + "źródła potasu": ["banany"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "styl alternatywny": { + "komentarz": "sprawdź to!" + , "pozycja przecinka": "nie ma znaczenia, o ile jest przed następnym kluczem, jest poprawnie" + , "następny komentarz": "jak ładnie" + }, + + + + "znaki białe": "nie mają znaczenia", + + + + "to było krótkie": "I gotowe. Wiesz już wszystko o formacie JSON." +} +``` + +## Dalsza lektura + +* [JSON.org](http://json.org) Cały JSON pięknie wytłumaczony na podstawie grafik przypominających schematy blokowe. diff --git a/pt-br/asymptoticnotation-pt.html.markdown b/pt-br/asymptoticnotation-pt.html.markdown new file mode 100644 index 00000000..c5299a11 --- /dev/null +++ b/pt-br/asymptoticnotation-pt.html.markdown @@ -0,0 +1,161 @@ +--- +category: Algorithms & Data Structures +name: Asymptotic Notation +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] +translators: + - ["Carolina Knoll", "http://github.com/carolinaknoll"] +lang: pt-br +--- + +# Aprenda X em Y minutos +## Onde X=Notação Assintótica + +# Notações Assintóticas +## O que são? + +Notações assintóticas são notações matemáticas que nos permitem analisar tempo de execução +de um algoritmo, identificando o seu comportamento de acordo como o tamanho de entrada para +o algoritmo aumenta. Também é conhecido como taxa de "crescimento" de um algoritmo. O algoritmo +simplesmente se torna incrivelmente lento conforme o seu tamanho aumenta? Será que pode-se na +maior parte manter o seu tempo de execução rápido mesmo quando o tamanho de entrada aumenta? +A notação assintótica nos dá a capacidade de responder a essas perguntas. + +## Além desta, existem outras alternativas para responder a essas perguntas? + +Uma forma seria a de contar o número de operações primitivas em diferentes tamanhos de entrada. +Embora esta seja uma solução válida, a quantidade de trabalho necessário, mesmo para algoritmos +simples, não justifica a sua utilização. + +Outra maneira é a de medir fisicamente a quantidade de tempo que leva para se executar um algoritmo +de diferentes tamanhos. No entanto, a precisão e a relatividade (já que tempos obtidos só teriam +relação à máquina em que eles foram testados) deste método estão ligadas a variáveis ambientais, +tais como especificações de hardware, poder de processamento, etc. + +## Tipos de Notação Assintótica + +Na primeira seção deste documento nós descrevemos como uma notação assintótica identifica o comportamento +de um algoritmo como as alterações de tamanho de entrada (input). Imaginemos um algoritmo como uma função +f, n como o tamanho da entrada, e f (n) sendo o tempo de execução. Assim, para um determinado algoritmo f, +com tamanho de entrada n você obtenha algum tempo de execução resultante f (n). Isto resulta num gráfico, +em que o eixo Y representa o tempo de execução, o eixo X é o tamanho da entrada, e os pontos marcados são +os resultantes da quantidade de tempo para um dado tamanho de entrada. + +Pode-se rotular uma função ou algoritmo com uma notação assintótica de diversas maneiras diferentes. +Dentre seus exemplos, está descrever um algoritmo pelo seu melhor caso, pior caso, ou caso equivalente. +O mais comum é o de analisar um algoritmo pelo seu pior caso. Isso porque você normalmente não avaliaria +pelo melhor caso, já que essas condições não são as que você está planejando. Um bom exemplo disto é o de +algoritmos de ordenação; especificamente, a adição de elementos a uma estrutura de tipo árvore. O melhor +caso para a maioria dos algoritmos pode ser tão simples como uma única operação. No entanto, na maioria +dos casos, o elemento que você está adicionando terá de ser ordenado de forma adequada através da árvore, +o que poderia significar a análise de um ramo inteiro. Este é o pior caso, e é por ele que precisamos seguir. + +### Tipos de funções, limites, e simplificação + +``` +Função Logaritmica - log n +Função Linear - an + b +Função Quadrática - an^2 + bn + c +Função Polinomial - an^z + . . . + an^2 + a*n^1 + a*n^0, onde z é uma constante +Função Exponencial - a^n, onde a é uma constante +``` + +Estas são algumas classificações básicas de crescimento de função usados em várias notações. A lista +começa com a função crescimento mais lento (logarítmica, com tempo de execução mais rápido) e vai até +a mais rápida (exponencial, com tempo de execução mais lento). Observe que 'n', ou nossa entrada, +cresce em cada uma dessas funções, e o resultado claramente aumenta muito mais rapidamente em função +quadrática, polinomial e exponencial, em comparação com a logarítmica e a linear. + +Uma observação de boa importância é que, para as notações a serem discutidas, deve-se fazer o melhor +para utilizar termos mais simples. Isto significa desrespeitar constantes, e simplificar termos de +ordem, porque, como o tamanho da entrada (ou n no nosso f (n) exemplo) aumenta infinitamente (limites +matemáticos), os termos em ordens mais baixas e constantes são de pouca ou nenhuma importância. Dito +isto, se você possui constantes com valor 2^9001, ou alguma outra quantidade ridícula, inimaginável, +perceberá que a simplificação distorcerá a precisão de sua notação. + +Já que nós queremos a forma mais simples, vamos modificar nossas funções um pouco. + +``` +Logaritmica - log n +Linear - n +Quadrática - n^2 +Polinomial - n^z, onde z é uma constante +Exponencial - a^n, onde a é uma constante +``` + +### O Grande-O + +Grande-O, geralmente escrita como O, é uma Notação Assintótica para o pior caso para uma dada função. Digamos +que `f(n)` é o tempo de execução de seu algoritmo, e `g(n)` é uma complexidade de tempo arbitrário que você está +tentando se relacionar com o seu algoritmo. `f(n)` será O(g(n)), se, por qualquer constante real c (c > 0), +`f(n)` <= `c g(n)` para cada tamanho de entrada n (n > 0). + +*Exemplo 1* + +``` +f(n) = 3log n + 100 +g(n) = log n +``` + +É `f(n)` um O(g(n))? +É 3 `log n + 100` igual a O(log n)? +Vamos checar na definição de Grande-O. + +``` +3log n + 100 <= c * log n +``` + +Existe alguma constante c que satisfaça isso para todo n? + +``` +3log n + 100 <= 150 * log n, n > 2 (indefinido em n = 1) +``` + +Sim! A definição de Grande-O foi satisfeita. Sendo assim, `f(n)` é O(g(n)). + +*Exemplo 2* + +``` +f(n) = 3 * n^2 +g(n) = n +``` + +É `f(n)` um O(g(n))? +É `3 * n^2` um O(n)? +Vamos ver na definição de Grande-O. + +``` +3 * n^2 <= c * n +``` + +Existe alguma constante que satisfaça isso para todo n? +Não, não existe. `f(n)` NÃO É O(g(n)). + +### Grande-Omega + +Grande-Omega, comumente escrito como Ω, é uma Notação Assintótica para o melhor caso, ou +uma taxa de crescimento padrão para uma determinada função. + +`f(n)` é Ω(g(n)), se, por qualquer constante c real (c > 0), `f(n)` é >= `c g(n)` para cada +tamanho de entrada n (n > 0). + +Sinta-se livre para pesquisar recursos adicionais e obter mais exemplos sobre este assunto! +Grande-O é a notação primária utilizada para tempo de execução de algoritmos, de modo geral. + +### Notas de Finalização + +É complicado exibir este tipo de assunto de forma tão curta, então é definitivamente recomendado +pesquisar além dos livros e recursos on-line listados. Eles serão capazes de analisar o assunto com +uma profundidade muito maior, além de ter definições e exemplos. Mais sobre onde X="Algoritmos e +Estruturas de Dados" está a caminho: Haverá conteúdo focado na análise de exemplos de códigos reais +em breve. + +## Livros + +* [Algorithms] (http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X) +* [Algorithm Design] (http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651) + +## Recursos Online + +* [MIT] (http://web.mit.edu/16.070/www/lecture/big_o.pdf) +* [KhanAcademy] (https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation) diff --git a/pt-br/bash-pt.html.markdown b/pt-br/bash-pt.html.markdown index a604e7b8..ae18435a 100644 --- a/pt-br/bash-pt.html.markdown +++ b/pt-br/bash-pt.html.markdown @@ -161,11 +161,11 @@ echo "#helloworld" > output.out echo "#helloworld" | cat > output.out echo "#helloworld" | tee output.out > /dev/null -# Limpa os arquivos temporarios detalhando quais foram deletados (use '-i' para confirmar exlusão) +# Limpa os arquivos temporários detalhando quais foram deletados (use '-i' para confirmar exclusão) rm -v output.out error.err output-and-error.log -# Comando podem ser substituidos por outros comandos usando $( ): -# O comand oa seguir mostra o número de arquivos e diretórios no diretorio atual +# Comando podem ser substituídos por outros comandos usando $( ): +# O comando a seguir mostra o número de arquivos e diretórios no diretorio atual echo "Existem $(ls | wc -l) itens aqui." # O mesmo pode ser feito usando crase `` mas elas não podem ser aninhadas - dá se diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown index 31a3110c..e2e95268 100644 --- a/pt-br/c++-pt.html.markdown +++ b/pt-br/c++-pt.html.markdown @@ -490,7 +490,7 @@ bool doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); // Abra o arquivo em modo de leitura if (fh == nullptr) // O ponteiro retornado é nulo em caso de falha. - reuturn false; // Relate o fracasso para o chamador. + return false; // Relate o fracasso para o chamador. // Suponha cada função retorne false, se falhar if (!doSomethingWithTheFile(fh)) { @@ -511,7 +511,7 @@ bool doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); if (fh == nullptr) - reuturn false; + return false; if (!doSomethingWithTheFile(fh)) goto failure; diff --git a/pt-br/elixir.html.markdown b/pt-br/elixir.html.markdown new file mode 100644 index 00000000..b4ca8a52 --- /dev/null +++ b/pt-br/elixir.html.markdown @@ -0,0 +1,411 @@ +--- +language: elixir +contributors: + - ["Joao Marques", "http://github.com/mrshankly"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] +translators: + - ["Rodrigo Muniz", "http://github.com/muniz95"] +filename: learnelixir-pt.ex +--- + +Elixir é uma linguagem funcional moderna construída no topo da Erlang VM. +É totalmente compatível com Erlang, porém conta com uma sintaxe mais padronizada +e muitos outros recursos. + +```elixir + +# Comentários de linha única começam com um símbolo de número. + +# Não há comentários de múltiplas linhas, +# mas você pode empilhar os comentários. + +# Para usar o shell do elixir use o comando `iex`. +# Compile seus módulos com o comando `elixirc`. + +# Ambos devem estar em seu path se você instalou o Elixir corretamente. + +## --------------------------- +## -- Tipos Básicos +## --------------------------- + +# Há números +3 # integer +0x1F # integer +3.0 # float + +# Atoms, que são literais, uma constante com nome. Elas começam com `:`. +:hello # atom + +# Tuplas que são guardadas contiguamente em memória. +{1,2,3} # tupla + +# Podemos acessar um elemento de uma tupla om a função `elem`: +elem({1, 2, 3}, 0) #=> 1 + +# Listas que são implementadas como listas ligadas. +[1,2,3] # lista + +# Podemos acessar a primeira posição (head) e o resto (tail) de uma lista como a seguir: +[head | tail] = [1,2,3] +head #=> 1 +tail #=> [2,3] + +# Em elixir, bem como em Erlang, o sinal `=` denota pattern match, +# e não uma atribuição. +# +# Isto significa que o que estiver à esquerda (pattern) é comparado com o que +# estiver à direita. +# +# É assim que o exemplo acima de acesso à head e tail de uma lista funciona. + +# Um pattern match retornará erro quando os lados não conferem, como neste exemplo +# onde as tuplas tem diferentes tamanhos. +# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} + +# Também há binários +<<1,2,3>> # binary + +# Strings e char lists +"hello" # string +'hello' # char list + +# Strings de múltiplas linhas +""" +Strings +de múltiplas +linhas. +""" +#=> "Strings\nde múltiplas\nlinhas" + +# Strings são sempre codificadas em UTF-8: +"héllò" #=> "héllò" + +# Strings são de fato apenas binários, e char lists apenas listas. +<<?a, ?b, ?c>> #=> "abc" +[?a, ?b, ?c] #=> 'abc' + +# `?a` em elixir retorna o valor ASCII para a letra `a` +?a #=> 97 + +# Para concatenar listas use `++`, para binários use `<>` +[1,2,3] ++ [4,5] #=> [1,2,3,4,5] +'hello ' ++ 'world' #=> 'hello world' + +<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> +"hello " <> "world" #=> "hello world" + +# Ranges são representados como `início..fim` (ambos inclusivos) +1..10 #=> 1..10 +menor..maior = 1..10 # Pattern matching pode ser usada em ranges também +[lower, upper] #=> [1, 10] + +## --------------------------- +## -- Operadores +## --------------------------- + +# Matemática básica +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 + +# Em elixir o operador `/` sempre retorna um float. + +# Para divisão de inteiros use `div` +div(10, 2) #=> 5 + +# Para obter o resto da divisão use `rem` +rem(10, 3) #=> 1 + +# Há também operadores booleanos: `or`, `and` e `not`. +# Estes operadores esperam um booleano como primeiro argumento. +true and true #=> true +false or true #=> true +# 1 and true #=> ** (ArgumentError) argument error + +# Elixir também fornece `||`, `&&` e `!` que aceitam argumentos de qualquer tipo. +# Todos os valores exceto `false` e `nil` serão avaliados como true. +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil +!true #=> false + +# Para comparações temos: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` e `>` +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true + +# `===` e `!==` são mais estritos ao comparar integers e floats: +1 == 1.0 #=> true +1 === 1.0 #=> false + +# Podemos comparar também dois tipos de dados diferentes: +1 < :hello #=> true + +# A regra de ordenação no geral é definida abaixo: +# number < atom < reference < functions < port < pid < tuple < list < bit string + +# Ao citar Joe Armstrong nisto: "A ordem de fato não é importante, +# mas que uma ordem total esteja bem definida é importante." + +## --------------------------- +## -- Fluxo de Controle +## --------------------------- + +# expressão `if` +if false do + "Isso nunca será visto" +else + "Isso será" +end + +# Também há `unless` +unless true do + "Isso nunca será visto" +else + "Isso será" +end + +# Lembra do patter matching? Muitas estruturas de fluxo de controle em elixir contam com ela. + +# `case` nos permite comparar um valor com muitos patterns: +case {:um, :dois} do + {:quatro, :cinco} -> + "Isso não corresponde" + {:um, x} -> + "Isso corresponde e vincula `x` a `:dois`" + _ -> + "Isso corresponde a qualquer valor" +end + +# É comum vincular o valor a `_` se não precisamos dele. +# Por exemplo, se apenas a head de uma lista nos interessa: +[head | _] = [1,2,3] +head #=> 1 + +# Para melhor legibilidade podemos fazer o seguinte: +[head | _tail] = [:a, :b, :c] +head #=> :a + +# `cond` nos permite verificar várias condições ao mesmo tempo. +# Use `cond` em vez de aninhar vários `if`'s. +cond do + 1 + 1 == 3 -> + "Nunca serei visto" + 2 * 5 == 12 -> + "Nem eu" + 1 + 2 == 3 -> + "Mas eu serei" +end + +# É comum definir a última condição igual a `true`, que sempre irá corresponder. +cond do + 1 + 1 == 3 -> + "Nunca serei visto" + 2 * 5 == 12 -> + "Nem eu" + true -> + "Mas eu serei (isso é essencialmente um else)" +end + +# `try/catch` é usado para capturar valores que são lançados, também suporta uma +# cláusula `after` que é invocada havendo um valor capturado ou não. +try do + throw(:hello) +catch + message -> "Deu #{mensagem}." +after + IO.puts("Sou o after.") +end +#=> Sou o after +# "Deu :hello" + +## --------------------------- +## -- Módulos e Funções +## --------------------------- + +# Funções Anônimas (repare o ponto) +square = fn(x) -> x * x end +square.(5) #=> 25 + +# Elas também aceitam várias cláusulas e guards. +# Guards permitem ajustes finos de pattern matching, +# sendo indicados pela palavra `when`: +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# Elixir também fornece várias funções embutidas. +# Estas estão disponíveis no escopo atual. +is_number(10) #=> true +is_list("ola") #=> false +elem({1,2,3}, 0) #=> 1 + +# Você pode agrupar algumas funções em um módulo. Dentro de um módulo use `def` +# para definir suas funções. +defmodule Math do + def sum(a, b) do + a + b + end + + def square(x) do + x * x + end +end + +Math.sum(1, 2) #=> 3 +Math.square(3) #=> 9 + +# Para compilar o módulo Math salve-o como `math.ex` e use `elixirc` +# em seu terminal: elixirc math.ex + +# Dentro de um módulo podemos definir funções com `def` e funções privadas com `defp`. +# Uma função definida com `def` pode ser invocada por outros módulos, +# já uma função privada pode ser invocada apenas localmente. +defmodule PrivateMath do + def sum(a, b) do + do_sum(a, b) + end + + defp do_sum(a, b) do + a + b + end +end + +PrivateMath.sum(1, 2) #=> 3 +# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) + +# Declarações de funções também suportam guards cláusulas múltiplas: +defmodule Geometry do + def area({:rectangle, w, h}) do + w * h + end + + def area({:circle, r}) when is_number(r) do + 3.14 * r * r + end +end + +Geometry.area({:rectangle, 2, 3}) #=> 6 +Geometry.area({:circle, 3}) #=> 28.25999999999999801048 +# Geometry.area({:circle, "not_a_number"}) +#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1 + +# Devido à imutabilidade, recursão é uma grande parte do elixir +defmodule Recursion do + def sum_list([head | tail], acc) do + sum_list(tail, acc + head) + end + + def sum_list([], acc) do + acc + end +end + +Recursion.sum_list([1,2,3], 0) #=> 6 + +# Módulos do elixir suportam atributos, hpa atributos embutidos e você +# pode também adicionar os seus próprios. +defmodule MyMod do + @moduledoc """ + Este é um atributo embutido em um módulo de exemplo. + """ + + @my_data 100 # Este é um atributo customizado. + IO.inspect(@my_data) #=> 100 +end + +## --------------------------- +## -- Structs e Exceptions +## --------------------------- + +# Structs são extensões no topo de mapas que trazem valores padrão, +# garantias em tempo de compilação e polimorfismo para o Elixir. +defmodule Pessoa do + defstruct nome: nil, idade: 0, peso: 0 +end + +joe_info = %Pessoa{ nome: "Joe", idade: 30, peso: 180 } +#=> %Pessoa{idade: 30, peso: 180, nome: "Joe"} + +# Acessa o valor de nome +joe_info.name #=> "Joe" + +# Atualiza o valor de idade +older_joe_info = %{ joe_info | idade: 31 } +#=> %Pessoa{idade: 31, peso: 180, nome: "Joe"} + +# O bloco `try` com a palavra `rescue` é usado para manipular exceções +try do + raise "algum erro" +rescue + RuntimeError -> "resgatado um erro em tempo de execução" + _error -> "isso resgatará qualquer erro" +end + +# Toda exceção possui uma mensagem +try do + raise "algum erro" +rescue + x in [RuntimeError] -> + x.message +end + +## --------------------------- +## -- Concorrência +## --------------------------- + +# Elixir conta com o modelo de ator para concorrência. Tudo o que precisamos para +# escrever programas concorrentes em elixir são três primitivos: spawning processes, +# sending messages e receiving messages. + +# Para iniciar um novo processo usamos a função `spawn`, a qual leva uma função +# como argumento. +f = fn -> 2 * 2 end #=> #Function<erl_eval.20.80484245> +spawn(f) #=> #PID<0.40.0> + +# `spawn` retorna um pid (process identifier), você pode usar esse pid para enviar +# mensagens ao processo. Para envio de mensagens usamos o operador `send`. +# Para tudo isso ser útil precisamos estar aptos a receber mensagens. Isto é +# realizado com o mecanismo `receive`: +defmodule Geometry do + def area_loop do + receive do + {:rectangle, w, h} -> + IO.puts("Area = #{w * h}") + area_loop() + {:circle, r} -> + IO.puts("Area = #{3.14 * r * r}") + area_loop() + end + end +end + +# Compile o módulo e crie um processo que avalie `area_loop` no shell +pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> + +# Envia uma mensagem ao `pid` correspondente a um pattern na declaração de recebimento +send pid, {:rectangle, 2, 3} +#=> Area = 6 +# {:rectangle,2,3} + +send pid, {:circle, 2} +#=> Area = 12.56000000000000049738 +# {:circle,2} + +# O shell também é um processo, você pode usar `self` para obter o pid atual +self() #=> #PID<0.27.0> +``` + +## Referências + +* [Getting started guide](http://elixir-lang.org/getting_started/1.html) da [página do elixir](http://elixir-lang.org) +* [Elixir Documentation](http://elixir-lang.org/docs/master/) +* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) por Dave Thomas +* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) +* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) por Fred Hebert +* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) por Joe Armstrong diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown index ea3570d6..907892b1 100644 --- a/pt-br/git-pt.html.markdown +++ b/pt-br/git-pt.html.markdown @@ -32,7 +32,7 @@ a um arquivo ou conjunto de arquivos ao longo do tempo. de arquivos. * Controle de versão distribuído foca em compartilhar alterações. Cada alteração é associada a um *id* único. -* Sistemas distribuídos não tem estrutura definida. É possivel ter um sistema +* Sistemas distribuídos não têm estrutura definida. É possivel ter um sistema centralizado ao estilo SVN usando git. [Informação adicional (EN)](http://git-scm.com/book/en/Getting-Started-About-Version-Control) @@ -56,7 +56,7 @@ referências. Pode ser descrito como uma estrutura de dados de código fonte com a particularidade de cada elemento do código fonte permitir acesso ao histórico das suas alterações, entre outras coisas. -Um repositório git é constituido pelo diretório .git e a *working tree* +Um repositório git é constituído pelo diretório .git e a *working tree* ### Diretório .git (componente do repositório) @@ -140,10 +140,10 @@ Para visualizar rapidamente o detalhamento de cada comando ou apenas lembrar da # Ver rapidamente os comandos disponiveis $ git help -# Ver todos os comandos disponiveis +# Ver todos os comandos disponíveis $ git help -a -# Usar o *help* para um comando especifico +# Usar o *help* para um comando específico # git help <comando_aqui> $ git help add $ git help commit @@ -158,7 +158,7 @@ do repositório) e o *commit* da *HEAD* atual. ```bash # Apresenta o *branch*, arquivos não monitorados, alterações e outras -# difereças +# diferenças $ git status # Para aprender mais detalhes sobre git *status* @@ -400,7 +400,7 @@ perigoso quando não há certeza do que se está fazendo. ```bash # Restabelece a camada intermediária de registo para o último -# commit (o directório fica sem alterações) +# commit (o diretório fica sem alterações) $ git reset # Restabelece a camada intermediária de registo para o último commit, e diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index 59c6890e..e337f4bc 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -197,7 +197,6 @@ myObj.myFourthKey; // = undefined // A sintaxe para essa seção é quase idêntica a maioria das linguagens. -// The `if` structure works as you'd expect. // A estrutura `if` funciona como deveria ser. var count = 1 if (count == 3){ @@ -219,9 +218,6 @@ do { input = getInput(); } while (!isValid(input)) -// The `for` loop is the same as C and Java: -// initialisation; continue condition; iteration. - // O loop `for` é o mesmo de C e Java: // inicialização, condição para continuar; iteração for (var i = 0; i < 5; i++){ diff --git a/pt-br/php-pt.html.markdown b/pt-br/php-pt.html.markdown index 0e710742..8a1c956e 100644 --- a/pt-br/php-pt.html.markdown +++ b/pt-br/php-pt.html.markdown @@ -7,7 +7,7 @@ translators: - ["Abdala Cerqueira", "http://abda.la"] - ["Raquel Diniz", "http://twitter.com/raquelrdiniz"] lang: pt-br -filename: learnphp-pt.php +filename: php-pt.html.markdown --- Este documento descreve PHP 5+. @@ -20,21 +20,23 @@ Este documento descreve PHP 5+. // Duas barras iniciam o comentário de uma linha. -# O hash (aka pound symbol) também inicia, mas // é mais comum +# O hash (aka pound symbol) também inicia, mas // é mais comum. /* O texto envolto por barra-asterisco e asterisco-barra - faz um comentário de múltiplas linhas + faz um comentário de múltiplas linhas. */ -// Utilize "echo" ou "print" para imprimir a saída -print('Olá '); // Imprime "Olá " sem quebra de linha +// Utilize "echo" ou "print" para imprimir a saída. +print('Olá '); // Imprime "Olá " sem quebra de linha. +print 'Olá '; // Não tem a necessidade de utilizar as chaves. // () são opcionais para print e echo -echo "Mundo\n"; // Imprime "Mundo" com quebra de linha -// (Todas as declarações devem terminar com um ponto e vírgula) +echo "Mundo\n"; // Imprime "Mundo" com quebra de linha. +echo ("Mundo\n"); // Podemos tambem utilizar com chaves no echo. +// (Todas as declarações devem terminar com um ponto e vírgula.) -// Qualquer coisa fora da tag <?php é impresso automaticamente +// Qualquer coisa fora da tag <?php é impresso automaticamente. ?> Olá mundo novamente! <?php @@ -48,7 +50,7 @@ Olá mundo novamente! // Um nome de variável válido se inicia com uma letra ou sublinhado, // seguido por qualquer quantidade de letras, números ou sublinhados. -// Valores booleanos não diferenciam maiúsculo de minúsculo (case-insensitive) +// Valores booleanos não diferenciam maiúsculo de minúsculo (case-insensitive). $boolean = true; // ou TRUE ou True $boolean = false; // ou FALSE ou False @@ -63,8 +65,8 @@ $float = 1.234; $float = 1.2e3; $float = 7E-10; -// Excluir variável -unset($int1) +// Excluir variável. +unset($int1); // Aritmética $soma = 1 + 1; // 2 @@ -79,17 +81,19 @@ echo $numero++; // Imprime 1 (incrementa após a avaliação) echo ++$numero; // Imprime 3 (incrementa antes da avaliação) $numero /= $float; // Divide e atribui o quociente de $numero -// Strings podem ser colocadas entre aspas simples +// Strings podem ser colocadas entre aspas simples. $sgl_quotes = '$String'; // => '$String' // Evite o uso de aspas duplas, exceto para incorporar outras variáveis $dbl_quotes = "Esta é uma $sgl_quotes."; // => 'Esta é uma $String.' -// Os caracteres especiais só são escapados entre aspas duplas -$escapado = "Este contém um \t caractere tab."; -$naoescapado = 'Este contém somente a barra e o t: \t'; +// Os caracteres especiais só são escapados entre aspas duplas. +$escapado = "Este contém um \t caractere tab."; +echo $escapado; //Imprime: Este contém um caractere tab. +$naoescapado = 'Este contém somente a barra e o t: \t'; +echo $naoescapado; //Imprime: Este contém somente a barra e o t: \t -// Coloque uma variável entre chaves se necessário +// Coloque uma variável entre chaves se necessário. $dinheiro = "Eu tenho $${numero} no banco."; // Desde o PHP 5.3, nowdocs podem ser usados para múltiplas linhas sem análise @@ -105,7 +109,7 @@ $sgl_quotes FIM; // Concatenação de string é feita com . -echo 'Esta string ' . 'é concatenada'; +echo 'Esta string ' . 'é concatenada'; //Imprime: 'Esta string é concatenada' /******************************** @@ -120,7 +124,7 @@ echo 'Esta string ' . 'é concatenada'; define("FOO", "alguma coisa"); // Acesso a uma constante é possível usando diretamente o nome escolhido -echo 'Isto sairá '.FOO; +echo 'Isto sairá '.FOO; //Imprime: Isto sairá alguma coisa /******************************** @@ -135,16 +139,16 @@ $associativo = array('Um' => 1, 'Dois' => 2, 'Tres' => 3); // PHP 5.4 introduziu uma nova sintaxe $associativo = ['Um' => 1, 'Dois' => 2, 'Tres' => 3]; -echo $associativo['Um']; // imprime 1 +echo $associativo['Um']; // Imprime 1. // Uma lista de literais atribui chaves inteiras implicitamente $array = ['Um', 'Dois', 'Tres']; -echo $array[0]; // => "Um" +echo $array[0]; // Imprime => "Um" // Adiciona um elemento no final do array $array[] = 'Quatro'; -// Remove um elemento do array +// Remove um elemento do array. unset($array[3]); /******************************** @@ -155,12 +159,12 @@ echo('Olá Mundo!'); // Imprime Olá Mundo! para stdout. // Stdout é uma página web se executado em um navegador. -print('Olá Mundo!'); // O mesmo que o echo +print('Olá Mundo!'); // O mesmo que o echo. // echo é atualmente um construtor de linguagem, então você pode // remover os parênteses. -echo 'Olá Mundo!'; -print 'Olá Mundo!'; // O print também é +echo 'Olá Mundo!'; // Imprime: Olá Mundo! +print 'Olá Mundo!'; // O print também é - Imprime: Olá Mundo! $paragrafo = 'parágrafo'; @@ -181,11 +185,11 @@ $z = &$y; // $z irá mudar o valor de $y também, e vice-versa. // $x irá permanecer inalterado com o valor original de $y -echo $x; // => 2 -echo $z; // => 2 +echo $x; // Imprime => 2 +echo $z; // Imprime => 2 $y = 0; -echo $x; // => 2 -echo $z; // => 0 +echo $x; // Imprime => 2 +echo $z; // Imprime => 0 // Despeja tipos e valores de variável para o stdout var_dump($z); // imprime int(0) @@ -222,13 +226,13 @@ assert(1 !== '1'); // As variáveis podem ser convertidas entre tipos, dependendo da sua utilização. $inteiro = 1; -echo $inteiro + $inteiro; // => 2 +echo $inteiro + $inteiro; // Imprime => 2 $string = '1'; -echo $string + $string; // => 2 (strings são coagidas para inteiros) +echo $string + $string; // Imprime => 2 (strings são coagidas para inteiros) $string = 'one'; -echo $string + $string; // => 0 +echo $string + $string; // Imprime => 0 // Imprime 0 porque o operador + não pode fundir a string 'um' para um número // Tipo de fundição pode ser utilizado para tratar uma variável diff --git a/pt-br/python3-pt.html.markdown b/pt-br/python3-pt.html.markdown new file mode 100644 index 00000000..c5a3c020 --- /dev/null +++ b/pt-br/python3-pt.html.markdown @@ -0,0 +1,746 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] +translators: + - ["Paulo Henrique Rodrigues Pinheiro", "http://www.sysincloud.it"] +language: pt-br +filename: learnpython3-pt.py +--- + +Python foi criado por Guido Van Rossum nos anos 1990. Ele é atualmente uma +das mais populares linguagens em existência. Eu fiquei morrendo de amor +pelo Python por sua clareza sintática. É praticamente pseudocódigo executável. + +Suas opiniões são grandemente apreciadas. Você pode encontrar-me em +[@louiedinh](http://twitter.com/louiedinh) ou louiedinh [em] +[serviço de e-mail do google]. + +Observação: Este artigo trata de Python 3 especificamente. Verifique +[aqui](http://learnxinyminutes.com/docs/pt-br/python-pt/) se você pretende +aprender o velho Python 2.7. + +```python + +# Comentários em uma única linha começam com uma cerquilha (também conhecido por sustenido). + +""" Strings de várias linhas podem ser escritas + usando três ", e são comumente usadas + como comentários. +""" + +#################################################### +## 1. Tipos de dados primitivos e operadores +#################################################### + +# Você usa números normalmente +3 # => 3 + +# Matemática é como você espera que seja +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Números inteiros por padrão, exceto na divisão, que retorna número +# de ponto flutuante (float). +35 / 5 # => 7.0 + +# O resultado da divisão inteira arredonda para baixo tanto para números +# positivos como para negativos. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # funciona em float também +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Quando você usa um float, o resultado é float. +3 * 2.0 # => 6.0 + +# operador módulo +7 % 3 # => 1 + +# Exponenciação (x**y, x elevado à potência y) +2**4 # => 16 + +# Determine a precedência usando parêntesis +(1 + 3) * 2 # => 8 + +# Valores lógicos são primitivos (Atenção à primeira letra maiúscula) +True +False + +# negação lógica com not +not True # => False +not False # => True + +# Operadores lógicos +# Observe que "and" e "or" são sensíveis a maiúsculas e minúsculas +True and False # => False +False or True # => True + +# Observe a utilização de operadores lógicos com números inteiros +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# Igualdade é == +1 == 1 # => True +2 == 1 # => False + +# Diferença é != +1 != 1 # => False +2 != 1 # => True + +# Mais comparações +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Comparações podem ser agrupadas +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (operador 'is' e operador '==') is verifica se duas referenciam um +# mesmo objeto, mas == verifica se as variáveis apontam para o +# mesmo valor. +a = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4] +b = a # b referencia o que está referenciado por a +b is a # => True, a e b referenciam o mesmo objeto +b == a # => True, objetos a e b tem o mesmo conteúdo +b = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4] +b is a # => False, a e b não referenciam o mesmo objeto +b == a # => True, objetos a e b tem o mesmo conteúdo + +# Strings são criadas com " ou ' +"Isto é uma string." +'Isto também é uma string.' + +# Strings também podem ser somadas! Mas tente não fazer isso. +"Olá " + "mundo!" # => "Olá mundo!" +# Strings podem ser somadas sem usar o '+' +"Olá " "mundo!" # => "Olá mundo!" + +# Uma string pode ser manipulada como se fosse uma lista de caracteres +"Isso é uma string"[0] # => 'I' + +# .format pode ser usado para formatar strings, dessa forma: +"{} podem ser {}".format("Strings", "interpoladas") # => "Strings podem ser interpoladas" + +# Você pode repetir os argumentos para digitar menos. +"Seja ágil {0}, seja rápido {0}, salte sobre o {1} {0}".format("Jack", "castiçal") +# => "Seja ágil Jack, seja rápido Jack, salte sobre o castiçal Jack." + +# Você pode usar palavras-chave se quiser contar. +"{nome} quer comer {comida}".format(nome="Beto", comida="lasanha") # => "Beto quer comer lasanha" + +# Se você precisa executar seu código Python3 com um interpretador Python 2.5 ou acima, você pode usar a velha forma para formatação de texto: +"%s podem ser %s da forma %s" % ("Strings", "interpoladas", "antiga") # => "Strings podem ser interpoladas da forma antiga" + + +# None é um objeto +None # => None + +# Não use o operador de igualdade "==" para comparar objetos com None +# Use "is" para isso. Ele checará pela identidade dos objetos. +"etc" is None # => False +None is None # => True + +# None, 0, e strings/listas/dicionários vazios todos retornam False. +# Qualquer outra coisa retorna True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False + + +#################################################### +## 2. Variáveis e coleções +#################################################### + +# Python tem uma função print +print("Eu sou o Python. Prazer em conhecer!") # => Eu sou o Python. Prazer em conhecer! + +# Por padrão a função print também imprime o caractere de nova linha ao final. +# Use o argumento opcional end para mudar o caractere final. +print("Olá, Mundo", end="!") # => Olá, Mundo! + +# Forma simples para capturar dados de entrada via console +input_string_var = input("Digite alguma coisa: ") # Retorna o que foi digitado em uma string +# Observação: Em versões antigas do Python, o método input() era chamado raw_input() + +# Não é necessário declarar variáveis antes de iniciá-las +# È uma convenção usar letras_minúsculas_com_sublinhados +alguma_variavel = 5 +alguma_variavel # => 5 + +# Acessar uma variável que não tenha sido inicializada gera uma exceção. +# Veja Controle de Fluxo para aprender mais sobre tratamento de exceções. +alguma_variavel_nao_inicializada # Gera a exceção NameError + +# Listas armazenam sequencias +li = [] +# Você pode iniciar com uma lista com alguns valores +outra_li = [4, 5, 6] + +# Adicionar conteúdo ao fim da lista com append +li.append(1) # li agora é [1] +li.append(2) # li agora é [1, 2] +li.append(4) # li agora é [1, 2, 4] +li.append(3) # li agora é [1, 2, 4, 3] +# Remover do final da lista com pop +li.pop() # => 3 e agora li é [1, 2, 4] +# Vamos colocá-lo lá novamente! +li.append(3) # li agora é [1, 2, 4, 3] novamente. + +# Acessar uma lista da mesma forma que você faz com um array +li[0] # => 1 +# Acessa o último elemento +li[-1] # => 3 + +# Acessando além dos limites gera um IndexError +li[4] # Gera o IndexError + +# Você pode acessar vários elementos com a sintaxe de limites +# (É um limite fechado, aberto pra você que gosta de matemática.) +li[1:3] # => [2, 4] +# Omitindo o final +li[2:] # => [4, 3] +# Omitindo o início +li[:3] # => [1, 2, 4] +# Selecione cada segunda entrada +li[::2] # => [1, 4] +# Tenha uma cópia em ordem invertida da lista +li[::-1] # => [3, 4, 2, 1] +# Use qualquer combinação dessas para indicar limites complexos +# li[inicio:fim:passo] + +# Faça uma cópia profunda de um nível usando limites +li2 = li[:] # => li2 = [1, 2, 4, 3] mas (li2 is li) resultará em False. + +# Apague elementos específicos da lista com "del" +del li[2] # li agora é [1, 2, 3] + +# Você pode somar listas +# Observação: valores em li e other_li não são modificados. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concatene listas com "extend()" +li.extend(other_li) # Agora li é [1, 2, 3, 4, 5, 6] + +# Verifique se algo existe na lista com "in" +1 in li # => True + +# Examine tamanho com "len()" +len(li) # => 6 + + +# Tuplas são como l istas, mas imutáveis. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Gera um TypeError + +# Observe que uma tupla de tamanho um precisa ter uma vírgula depois do +# último elemento mas tuplas de outros tamanhos, mesmo vazias, não precisa,. +type((1)) # => <class 'int'> +type((1,)) # => <class 'tuple'> +type(()) # => <class 'tuple'> + +# Você pode realizar com tuplas a maior parte das operações que faz com listas +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Você pode desmembrar tuplas (ou listas) em variáveis. +a, b, c = (1, 2, 3) # a é 1, b é 2 e c é 3 +# Por padrão, tuplas são criadas se você não coloca parêntesis. +d, e, f = 4, 5, 6 +# Veja como é fácil permutar dois valores +e, d = d, e # d é 5, e é 4 + +# Dicionários armazenam mapeamentos +empty_dict = {} +# Aqui está um dicionário preenchido na definição da referência +filled_dict = {"um": 1, "dois": 2, "três": 3} + +# Observe que chaves para dicionários devem ser tipos imutáveis. Isto é para +# assegurar que a chave pode ser convertida para uma valor hash constante para +# buscas rápidas. +# Tipos imutáveis incluem inteiros, flotas, strings e tuplas. +invalid_dict = {[1,2,3]: "123"} # => Gera um TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Já os valores, podem ser de qualquer tipo. + +# Acesse valores com [] +filled_dict["um"] # => 1 + +# Acesse todas as chaves como um iterável com "keys()". É necessário encapsular +# a chamada com um list() para transformá-las em uma lista. Falaremos sobre isso +# mais adiante. Observe que a ordem de uma chave de dicionário não é garantida. +# Por isso, os resultados aqui apresentados podem não ser exatamente como os +# aqui apresentados. +list(filled_dict.keys()) # => ["três", "dois", "um"] + + +# Acesse todos os valores de um iterável com "values()". Novamente, é +# necessário encapsular ele com list() para não termos um iterável, e sim os +# valores. Observe que, como foi dito acima, a ordem dos elementos não é +# garantida. +list(filled_dict.values()) # => [3, 2, 1] + + +# Verifique a existência de chaves em um dicionário com "in" +"um" in filled_dict # => True +1 in filled_dict # => False + +# Acessar uma chave inexistente gera um KeyError +filled_dict["quatro"] # KeyError + +# Use o método "get()" para evitar um KeyError +filled_dict.get("um") # => 1 +filled_dict.get("quatro") # => None +# O método get permite um parâmetro padrão para quando não existir a chave +filled_dict.get("um", 4) # => 1 +filled_dict.get("quatro", 4) # => 4 + +# "setdefault()" insere em dicionário apenas se a dada chave não existir +filled_dict.setdefault("cinco", 5) # filled_dict["cinco"] tem valor 5 +filled_dict.setdefault("cinco", 6) # filled_dict["cinco"] continua 5 + +# Inserindo em um dicionário +filled_dict.update({"quatro":4}) # => {"um": 1, "dois": 2, "três": 3, "quatro": 4} +#filled_dict["quatro"] = 4 #outra forma de inserir em um dicionário + +# Remova chaves de um dicionário com del +del filled_dict["um"] # Remove a chave "um" de filled_dict + + +# Armazenamento em sets... bem, são conjuntos +empty_set = set() +# Inicializa um set com alguns valores. Sim, ele parece um dicionário. Desculpe. +some_set = {1, 1, 2, 2, 3, 4} # some_set agora é {1, 2, 3, 4} + +# Da mesma forma que chaves em um dicionário, elementos de um set devem ser +# imutáveis. +invalid_set = {[1], 1} # => Gera um TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# Pode definir novas variáveis para um conjunto +filled_set = some_set + +# Inclua mais um item no set +filled_set.add(5) # filled_set agora é {1, 2, 3, 4, 5} + +# Faça interseção de conjuntos com & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Faça união de conjuntos com | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Faça a diferença entre conjuntos com - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Verifique a existência em um conjunto com in +2 in filled_set # => True +10 in filled_set # => False + + + +#################################################### +## 3. Controle de fluxo e iteráveis +#################################################### + +# Iniciemos um variável +some_var = 5 + +# Aqui está uma expressão if. Indentação é significante em python! +# imprime "somevar é menor que10" +if some_var > 10: + print("some_var é absolutamente maior que 10.") +elif some_var < 10: # Esta cláusula elif é opcional. + print("some_var é menor que 10.") +else: # Isto também é opcional. + print("some_var é, de fato, 10.") + + +""" +Laços for iteram sobre listas +imprime: + cachorro é um mamífero + gato é um mamífero + rato é um mamífero +""" +for animal in ["cachorro", "gato", "rato"]: + # Você pode usar format() para interpolar strings formatadas + print("{} é um mamífero".format(animal)) + +""" +"range(número)" retorna um iterável de números +de zero até o número escolhido +imprime: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(menor, maior)" gera um iterável de números +começando pelo menor até o maior +imprime: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(menor, maior, passo)" retorna um iterável de números +começando pelo menor número até o maior númeno, pulando de +passo em passo. Se o passo não for indicado, o valor padrão é um. +imprime: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) +""" + +Laços while executam até que a condição não seja mais válida. +imprime: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Maneira mais curta para for x = x + 1 + +# Lide com exceções com um bloco try/except +try: + # Use "raise" para gerar um erro + raise IndexError("Isto é um erro de índice") +except IndexError as e: + pass # Pass é um não-operador. Normalmente você usa algum código de recuperação aqui. +except (TypeError, NameError): + pass # Varias exceções podem ser gerenciadas, se necessário. +else: # Cláusula opcional para o bloco try/except. Deve estar após todos os blocos de exceção. + print("Tudo certo!") # Executa apenas se o código em try não gera exceção +finally: # Sempre é executado + print("Nós podemos fazer o código de limpeza aqui.") + +# Ao invés de try/finally para limpeza você pode usar a cláusula with +with open("myfile.txt") as f: + for line in f: + print(line) + +# Python provê uma abstração fundamental chamada Iterável. +# Um iterável é um objeto que pode ser tratado como uma sequência. +# O objeto retornou a função range, um iterável. + +filled_dict = {"um": 1, "dois": 2, "três": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => range(1,10). Esse é um objeto que implementa nossa interface iterável. + +# Nós podemos percorrê-la. +for i in our_iterable: + print(i) # Imprime um, dois, três + +# Mas não podemos acessar os elementos pelo seu índice. +our_iterable[1] # Gera um TypeError + +# Um iterável é um objeto que sabe como criar um iterador. +our_iterator = iter(our_iterable) + +# Nosso iterador é um objeto que pode lembrar o estado enquanto nós o percorremos. +# Nós acessamos o próximo objeto com "next()". +next(our_iterator) # => "um" + +# Ele mantém o estado enquanto nós o percorremos. +next(our_iterator) # => "dois" +next(our_iterator) # => "três" + +# Após o iterador retornar todos os seus dados, ele gera a exceção StopIterator +next(our_iterator) # Gera StopIteration + +# Você pode capturar todos os elementos de um iterador aplicando list() nele. +list(filled_dict.keys()) # => Retorna ["um", "dois", "três"] + + +#################################################### +## 4. Funções +#################################################### + +# Use "def" para criar novas funções. +def add(x, y): + print("x é {} e y é {}".format(x, y)) + return x + y # Retorne valores com a cláusula return + +# Chamando funções com parâmetros +add(5, 6) # => imprime "x é 5 e y é 6" e retorna 11 + +# Outro meio de chamar funções é com argumentos nomeados +add(y=6, x=5) # Argumentos nomeados podem aparecer em qualquer ordem. + +# Você pode definir funções que pegam um número variável de argumentos +# posicionais +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# Você pode definir funções que pegam um número variável de argumentos nomeados +# também +def keyword_args(**kwargs): + return kwargs + +# Vamos chamá-lo para ver o que acontece +keyword_args(peh="grande", lago="ness") # => {"peh": "grande", "lago": "ness"} + + +# Você pode fazer ambos simultaneamente, se você quiser +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) imprime: + (1, 2) + {"a": 3, "b": 4} +""" + +# Quando chamar funções, você pode fazer o oposto de args/kwargs! +# Use * para expandir tuplas e use ** para expandir dicionários! +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalente a foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalente a foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4) + +# Retornando múltiplos valores (com atribuição de tuplas) +def swap(x, y): + return y, x # Retorna múltiplos valores como uma tupla sem os parêntesis. + # (Observação: os parêntesis foram excluídos mas podem estar + # presentes) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Novamente, os parêntesis foram excluídos mas podem estar presentes. + +# Escopo de função +x = 5 + +def setX(num): + # A variável local x não é a mesma variável global x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # variável global x agora é 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python tem funções de primeira classe +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Também existem as funções anônimas +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# TODO - Fix for iterables +# Existem funções internas de alta ordem +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Nós podemos usar compreensão de lista para interessantes mapas e filtros +# Compreensão de lista armazena a saída como uma lista que pode ser uma lista +# aninhada +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. Classes +#################################################### + + +# Nós usamos o operador "class" para ter uma classe +class Human: + + # Um atributo de classe. Ele é compartilhado por todas as instâncias dessa + # classe. + species = "H. sapiens" + + # Construtor básico, é chamado quando esta classe é instanciada. + # Note que dois sublinhados no início e no final de uma identificados + # significa objetos ou atributos que são usados pelo python mas vivem em + # um namespace controlado pelo usuário. Métodos (ou objetos ou atributos) + # como: __init__, __str__, __repr__, etc. são chamados métodos mágicos (ou + # algumas vezes chamados métodos dunder - "double underscore") + # Você não deve usar nomes assim por sua vontade. + def __init__(self, name): + @ Atribui o argumento ao atributo da instância + self.name = name + + # Um método de instância. Todos os métodos tem "self" como primeiro + # argumento + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Um método de classe é compartilhado por todas as instâncias + # Eles são chamados com a classe requisitante como primeiro argumento + @classmethod + def get_species(cls): + return cls.species + + # Um método estático é chamado sem uma referência a classe ou instância + @staticmethod + def grunt(): + return "*grunt*" + + +# Instancie uma classe +i = Human(name="Ian") +print(i.say("oi")) # imprime "Ian: oi" + +j = Human("Joel") +print(j.say("olá")) # imprime "Joel: olá" + +# Chama nosso método de classe +i.get_species() # => "H. sapiens" + +# Altera um atributo compartilhado +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Chama o método estático +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. Módulos +#################################################### + +# Você pode importar módulos +import math +print(math.sqrt(16)) # => 4 + +# Você pode importar apenas funções específicas de um módulo +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Você pode importar todas as funções de um módulo para o namespace atual +# Atenção: isso não é recomendado +from math import * + +# Você pode encurtar o nome dos módulos +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Módulos python são apenas arquivos python comuns. Você +# pode escrever os seus, e importá-los. O nome do +# módulo é o mesmo nome do arquivo. + +# Você pode procurar que atributos e funções definem um módulo. +import math +dir(math) + + +#################################################### +## 7. Avançado +#################################################### + +# Geradores podem ajudar você a escrever código "preguiçoso" +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Um gerador cria valores conforme necessário. +# Ao invés de gerar e retornar todos os valores de uma só vez ele cria um em +# cada interação. Isto significa que valores maiores que 15 não serão +# processados em double_numbers. +# Nós usamos um sublinhado ao final do nome das variáveis quando queremos usar +# um nome que normalmente colide com uma palavra reservada do python. +range_ = range(1, 900000000) +# Multiplica por 2 todos os números até encontrar um resultado >= 30 +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Decoradores +# Neste exemplo beg encapsula say +# beg irá chamar say. Se say_please é verdade então ele irá mudar a mensagem +# retornada +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Por favor! Eu sou pobre :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Você me paga uma cerveja?" + return msg, say_please + + +print(say()) # Você me paga uma cerveja? +print(say(say_please=True)) # Você me paga uma cerveja? Por favor! Eu sou pobre :( +``` + +## Pronto para mais? + +### Free Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) + +### Dead Tree + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown index 668cd25f..eeb51bec 100644 --- a/pt-br/ruby-pt.html.markdown +++ b/pt-br/ruby-pt.html.markdown @@ -101,7 +101,7 @@ caminho_para_a_raiz_do_projeto = '/bom/nome/' caminho = '/nome/ruim/' # Símbolos (são objetos) -# Símbolos são imutáveis, são constantes reutilizáveis representadadas +# Símbolos são imutáveis, são constantes reutilizáveis representados # internamente por um valor inteiro. Eles são frequentemente usados no # lugar de strings para transmitir com eficiência os valores específicos # e significativos @@ -260,7 +260,7 @@ somar 3, 4 #=> 7 somar(3,4), 5 #=> 12 # yield -# Todos os métodos possuem implicitamente um paramêntro opcional que é um bloco +# Todos os métodos possuem implicitamente um paramêtro opcional que é um bloco # ele pode ser chamado com a palavra chave 'yield' def ao_redor @@ -285,7 +285,7 @@ class Humano # Inicialização básica (contructor) def initialize(nome, idade=0) - # Atribui o argumento para a variável de instancia "nome" do objeto + # Atribui o argumento para a variável de instância "nome" do objeto @nome = nome # Se a idade não for passada, nós definimos um valor padrão na lista de argumentos @idade = idade @@ -301,7 +301,7 @@ class Humano @nome end - # Um método de classe usa a palavra chave self para se defenciar dos métodos de instância. + # Um método de classe usa a palavra chave self para se diferenciar dos métodos de instância. # Ele só pode ser chamado na classe, não na instancia def self.diz(msg) puts "#{msg}" @@ -362,7 +362,7 @@ Trabalhador.foo # 0 Humano.foo = 2 # 2 Trabalhador.foo # 2 -# Uma variável de instância não é compartilhada por suas classes decendentes. +# Uma variável de instância não é compartilhada por suas classes descendentes. class Humano @bar = 0 diff --git a/pt-br/typescript-pt.html.markdown b/pt-br/typescript-pt.html.markdown new file mode 100644 index 00000000..f072b257 --- /dev/null +++ b/pt-br/typescript-pt.html.markdown @@ -0,0 +1,179 @@ +--- +language: TypeScript +filename: learntypescript-pt.ts +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: + - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"] +lang: pt-br +--- + +TypeScript is a language that aims at easing development of large scale applications written in JavaScript. +TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. +It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emits JavaScript. + +This article will focus only on TypeScript extra syntax, as opposed to [JavaScript] (../javascript/). + + +Typescript é uma linguagem que visa facilitar o desenvolvimento de aplicações em grande escala escritos em JavaScript. +Typescript acrescenta conceitos comuns como classes, módulos, interfaces, genéricos e (opcional) tipagem estática para JavaScript. +É um super conjunto de JavaScript: todo o código JavaScript é o código do texto dactilografado válido para que possa ser adicionados diretamente a qualquer projeto. O compilador emite typescript JavaScript. + +Este artigo irá se concentrar apenas em texto datilografado sintaxe extra, ao contrário de [JavaScript](javascript-pt.html.markdown). + +Para testar compilador do texto datilografado, de cabeça para o [Parque](http://www.typescriptlang.org/Playground), onde você vai ser capaz de escrever código, ter auto conclusão e ver diretamente o JavaScript emitida. + +```js +// Existem 3 tipos básicos no TypeScript +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Anders"; + +// Quando é impossível saber, há o "Qualquer" tipo +var notSure: any = 4; +notSure = "maybe a string instead"; +notSure = false; // Ok, definitivamente um boolean + +// Para coleções, não são matrizes e matrizes genéricas digitado +var list: number[] = [1, 2, 3]; +// Como alternativa, usando o tipo de matriz genérica +var list: Array<number> = [1, 2, 3]; + +// Para enumerações: +enum Color {Red, Green, Blue}; +var c: Color = Color.Green; + +// Por último, "vazio" é utilizado no caso especial de uma função que não retorna nada +function bigHorribleAlert(): void { + alert("I'm a little annoying box!"); +} + +// Funções são cidadãos de primeira classe, apoiar a sintaxe lambda "seta gordura" e +// Tipo de uso inferência + +// A seguir são equivalentes, a mesma assinatura será inferido pelo +// Compilador, e mesmo JavaScript será emitido +var f1 = function(i: number): number { return i * i; } +// Tipo de retorno inferida +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +// Tipo de retorno inferida +var f4 = (i: number) => { return i * i; } +// Tipo de retorno inferido, one-liner significa nenhuma palavra-chave retorno necessário +var f5 = (i: number) => i * i; + +// Interfaces são estruturais, qualquer coisa que tenha as propriedades é compatível com +// A interface +interface Person { + name: string; + // Propriedades opcionais, marcado com um "?" + age?: number; + // E de funções curso + move(): void; +} + +// Objeto que implementa a "Pessoa" Interface +// Pode ser tratado como uma pessoa desde que tem o nome e mover propriedades +var p: Person = { name: "Bobby", move: () => {} }; +// Os objetos que têm a propriedade opcional: +var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; +// Não é uma pessoa porque a idade não é um número +var invalidPerson: Person = { name: "Bobby", age: true }; + +// Interfaces também pode descrever um tipo de função +interface SearchFunc { + (source: string, subString: string): boolean; +} +// Somente tipos dos parâmetros são importantes, os nomes não são importantes. +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// Classes - membros são públicos por padrão +class Point { + // Propriedades + x: number; + + // Construtor - the public/private keywords in this context will generate + // o código clichê para a propriedade e a inicialização no + // construtor. + // Neste exemplo, "y" será definida como "X" é, mas com menos código + // Os valores padrão também são suportados. + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Funções + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Membros Estáticos + static origin = new Point(0, 0); +} + +var p1 = new Point(10 ,20); +var p2 = new Point(25); //y será 0 + +// Herança +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Chamada explícita para o construtor da super classe é obrigatória + } + + // Sobrescrever + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Módulos, "." pode ser utilizado como separador de sub módulos +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +// Alias no local para fazer referência a um módulo +import G = Geometry; + +var s2 = new G.Square(10); + +// Genericos +// Classes +class Tuple<T1, T2> { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interfaces +interface Pair<T> { + item1: T; + item2: T; +} + +// e funções +var pairToTuple = function<T>(p: Pair<T>) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); + +// Incluindo referências a um arquivo de definição: +/// <reference path="jquery.d.ts" /> + +``` + +## Leitura adicional + * [TypeScript site oficial](http://www.typescriptlang.org/) + * [TypeScript especificações de idioma (pdf)](http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Apresentando texto datilografado no Canal 9](http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Código fonte no GitHub](https://github.com/Microsoft/TypeScript) + * [Definitivamente datilografado - repositório de definições de tipo](http://definitelytyped.org/) diff --git a/pt-pt/swift.html.markdown b/pt-pt/swift.html.markdown new file mode 100644 index 00000000..2a964bde --- /dev/null +++ b/pt-pt/swift.html.markdown @@ -0,0 +1,609 @@ +--- +language: swift +filename: learnswift-pt.swift +contributors: + - ["Grant Timmerman", "http://github.com/grant"] + - ["Christopher Bess", "http://github.com/cbess"] + - ["Joey Huang", "http://github.com/kamidox"] + - ["Anthony Nguyen", "http://github.com/anthonyn60"] + - ["Clayton Walker", "https://github.com/cwalk"] +translators: + - ["João Costa", "https://github.com/joaofcosta"] +lang: pt-pt +--- + +Swift é uma linguagem de programação criada pela Apple para o desenvolvimento em iOS e OS X. +Desenhada de forma a coexistir com Objective-C e ser mais resiliente contra código errôneo, a linguagem Swift foi introduzida em 2014 na conferência para desenvolvedores WWDC da Apple. +Swift usa o compilador LLVM incluido no XCode 6+. + +O livro oficial [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) da Apple está agora disponivel via iBooks. + +Consulta também o [guia de iniciação](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/) da Apple, que contêm um tutorial completo em Swift. + +```swift +// importar um módulo +import UIKit + +// +// MARK: Básico +// + +// O Xcode suporta landmarks para anotação de código e lista-as na jump bar +// MARK: Marco de secção (MARK) +// TODO: Algo a fazer em breve +// FIXME: Reparar este código + +// Em Swift 2, println e print foram unidos num só método print. O print automaticamente acrescenta uma nova linha. +print("Hello, world") // println mudou para print +print("Hello, world", appendNewLine: false) // imprimir sem acrescentar uma nova linha + +// variáveis (var) podem ser modificadas depois de inicializadas +// constantes (let) NÂO podem ser modificadas depois de inicializadas + +var myVariable = 42 +let øπΩ = "value" // nomes de variáveis em unicode +let π = 3.1415926 +let convenience = "keyword" // nome de variável contextual +let weak = "keyword"; let override = "another keyword" // expressões podem ser separadas com ';' +let `class` = "keyword" // plicals permitem que keywords sejam usadas como nomes de vartiáveis +let explicitDouble: Double = 70 +let intValue = 0007 // 7 +let largeIntValue = 77_000 // 77000 +let label = "some text " + String(myVariable) // Casting +let piText = "Pi = \(π), Pi 2 = \(π * 2)" // interpolação de Strings + +// Valores especificos à build +// usam a configuração de build -D +#if false + print("Not printed") + let buildValue = 3 +#else + let buildValue = 7 +#endif +print("Build value: \(buildValue)") // Build value: 7 + +/* + Optionals são um dos recursos de Swift, Optionals tanto podem conter + um valor ou conter nil (sem valor) que indica que não existe um valor. + Adicionar um ponto de exclamção (?) após definir o tipo declara + esse valor como um Optional. + + Como Swift requere que todas as propriedades tenham um valor, até nil + tem que ser explicitamente guardado como um valor Optional. + + Optional<T> é uma enumeração. +*/ +var someOptionalString: String? = "optional" // Pode assumir o valor nil +// Igual ao de cima, mas ? é um operando pósfixo (açúcar sintático) +var someOptionalString2: Optional<String> = "optional" + +if someOptionalString != nil { + // Não sou nil + if someOptionalString!.hasPrefix("opt") { + print("has the prefix") + } + + let empty = someOptionalString?.isEmpty +} +someOptionalString = nil + +/* + Tentar usar ! para aceder a Optional com valor não existente, ou seja, nil, + causa em erro de execução. + É necessário ter sempre a certeza que um Optional não tem valor nil + antes de usar ! para fazer 'force-unwrap' ao seu valor. +*/ + +// Optional implicitamente desembrulhado +var unwrappedString: String! = "Value is expected." +// O mesmo de cima, mas ! é um operando pósfixo (mais açúcar sintático) +var unwrappedString2: ImplicitlyUnwrappedOptional<String> = "Value is expected." + +if let someOptionalStringConstant = someOptionalString { + // Tem um valor diferente de nil + if !someOptionalStringConstant.hasPrefix("ok") { + // Não tem o prefixo + } +} + +// Swift tem suporte para guardar valores de qualquer tipo. +// AnyObject == id +// Ao contrátio do `id` de Objective-C, AnyObject funciona com qualquer valor (Class, Int, struct, etc.) +var anyObjectVar: AnyObject = 7 +anyObjectVar = "Changed value to a string, not good practice, but possible." + +/* + Comentar aqui + + /* + Também é possível fazer comentários aninhados + */ +*/ + +// +// MARK: Coleções (Collections) +// + +/* + Os tipos Array e Dictionary são structs e, portanto, `let` e `var` + também indicam se eles são mutáveis (var) or imutáveis (let) + na altura em que se declaram estes tipos. +*/ + +// Array +var shoppingList = ["catfish", "water", "lemons"] +shoppingList[1] = "bottle of water" +let emptyArray = [String]() // let == imutável +let emptyArray2 = Array<String>() // mesmo de cima +var emptyMutableArray = [String]() // var == mutável + + +// Dictionary +var occupations = [ + "Malcolm": "Captain", + "kaylee": "Mechanic" +] +occupations["Jayne"] = "Public Relations" +let emptyDictionary = [String: Float]() // let == imutável +let emptyDictionary2 = Dictionary<String, Float>() // mesmo de cima +var emptyMutableDictionary = [String: Float]() // var == mutável + + +// +// MARK: Controlo de Fluxo (Control Flow) +// + +// for loop (array) +let myArray = [1, 1, 2, 3, 5] +for value in myArray { + if value == 1 { + print("One!") + } else { + print("Not one!") + } +} + +// for loop (dictionary) +var dict = ["one": 1, "two": 2] +for (key, value) in dict { + print("\(key): \(value)") +} + +// ciclo for (limite) +for i in -1...shoppingList.count { + print(i) +} +shoppingList[1...2] = ["steak", "peacons"] +// usar ..< para excluir o último número + +// ciclo while +var i = 1 +while i < 1000 { + i *= 2 +} + +// ciclo do-whie +do { + print("hello") +} while 1 == 2 + +// Switch +// Muito poderoso, imagine `if`s com açúcar sintático +// Funciona para String, instâncias de objectos e primitivas (Int, Double, etc.) +let vegetable = "red pepper" +switch vegetable { +case "celery": + let vegetableComment = "Add some raisins and make ants on a log." +case "cucumber", "watercress": + let vegetableComment = "That would make a good tea sandwich." +case let localScopeValue where localScopeValue.hasSuffix("pepper"): + let vegetableComment = "Is it a spicy \(localScopeValue)?" +default: // obrigatório (de forma a cobrir todos os possíveis inputs) + let vegetableComment = "Everything tastes good in soup." +} + + +// +// MARK: Funções (Functions) +// + +// Funções são tipos de primeira classe, o que significa que podem ser +// aninhadas dentro de outras funções e passadas como argumento + +// Função em Swift com documentação no header + +/** + Função de cumprimento. + + - Um ponto em documentação + - Outro ponto na documentação + + :param: nome Um nome + :param: dia Um dia + :returns: Uma string com um cumprimento contendo o nome e o dia. +*/ +func greet(nome: String, dia: String) -> String { + return "Hello \(nome), today is \(dia)." +} +greet("Bob", "Tuesday") + +// Semelhante ao método de cima excepto ao comportamento dos argumentos +func greet2(#nomeObrigatório: String, nomeArgumentoExterno nomeArgumentoLocal: String) -> String { + return "Hello \(nomeObrigatório), the day is \(nomeArgumentoLocal)" +} +greet2(nomeObrigatório:"John", nomeArgumentoExterno: "Sunday") + +// Função que devolve vários itens num tuplo +func getGasPrices() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} +let pricesTuple = getGasPrices() +let price = pricesTuple.2 // 3.79 +// Ignorar tuplos ou outros valores usando _ (underscore) +let (_, price1, _) = pricesTuple // price1 == 3.69 +print(price1 == pricesTuple.1) // true +print("Gas price: \(price)") + +// Argumentos variáveis +func setup(numbers: Int...) { + // é um array + let number = numbers[0] + let argCount = numbers.count +} + +// Passar e devolver funções +func makeIncrementer() -> (Int -> Int) { + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne +} +var increment = makeIncrementer() +increment(7) + +// Passar por referência (inout) +func swapTwoInts(inout a: Int, inout b: Int) { + let tempA = a + a = b + b = tempA +} +var someIntA = 7 +var someIntB = 3 +swapTwoInts(&someIntA, &someIntB) +print(someIntB) // 7 + + +// +// MARK: Closures +// +var numbers = [1, 2, 6] + +// Funções são casos especiais de closures ({}) + +// Exemplo de um Closure. +// `->` separa o argumento e o tipo de retorno. +// `in` separa o cabeçalho do closure do corpo do closure. +numbers.map({ + (number: Int) -> Int in + let result = 3 * number + return result +}) + +// Quando o tipo é conhecido, como em cima, podemos fazer o seguinte +numbers = numbers.map({ number in 3 * number }) +// Ou até mesmo isto +//numbers = numbers.map({ $0 * 3 }) + +print(numbers) // [3, 6, 18] + +// Closure à direita (Trailing closure) +numbers = sorted(numbers) { $0 > $1 } + +print(numbers) // [18, 6, 3] + +// Super curto, pois o operador < consegue inferir o tipo + +numbers = sorted(numbers, < ) + +print(numbers) // [3, 6, 18] + +// +// MARK: Estruturas (Structures) +// + +// Estruturas (struct) e classes (class) têm capacidades muito semelhantes +struct NamesTable { + let names = [String]() + + // Custom subscript + subscript(index: Int) -> String { + return names[index] + } +} + +// Estruturas têm um inicializador implicito que é automaticamente gerado +let namesTable = NamesTable(names: ["Me", "Them"]) +let name = namesTable[1] +print("Name is \(name)") // Name is Them + +// +// MARK: Classes +// + +// Classes, estruturas e os seus membros têm três níveis de controlo de acesso +// Nomeadamente: interno (predefinição)(internal) , público (public), privado (private) + +public class Shape { + public func getArea() -> Int { + return 0; + } +} + +// Todos os métodos e propriedades de uma classe são públicos. +// Se só for necessário guarda dados num +// objecto estruturado, então é melhor usar uma `struct` + +internal class Rect: Shape { + var sideLength: Int = 1 + + // Propriedade getter e setter personalizado + private var perimeter: Int { + get { + return 4 * sideLength + } + set { + // `newValue` é uma variável implicita disponível aos setters + sideLength = newValue / 4 + } + } + + // Carregar preguiçosamente uma propriedade + // subShape permanece a nil (unintialized) até o getter ser invocado + lazy var subShape = Rect(sideLength: 4) + + // Se não for necessário um getter e setter personalizado, + // mas se quiser correr o código antes e depois de modificar ou aceder + // uma propriedade, é possível usar `willSet` e `didSet` + var identifier: String = "defaultID" { + // o argumento de `willSet` é o nome da variável para o novo valor + willSet(someIdentifier) { + print(someIdentifier) + } + } + + init(sideLength: Int) { + self.sideLength = sideLength + // invocar super.init no final do método de inicialização + super.init() + } + + func shrink() { + if sideLength > 0 { + --sideLength + } + } + + override func getArea() -> Int { + return sideLength * sideLength + } +} + +// A class `Square` estende (extends) a classe `Rect` (hierarquia) +class Square: Rect { + convenience init() { + self.init(sideLength: 5) + } +} + +var mySquare = Square() +print(mySquare.getArea()) // 25 +mySquare.shrink() +print(mySquare.sideLength) // 4 + +// Cast de uma instância de `Square` para `Shape` +let aShape = mySquare as Shape + +// Compara instâncias, não é igual a == , visto que == compara objects (igual a) +if mySquare === mySquare { + print("Yep, it's mySquare") +} + +// Inicializador (init) com Optional +class Circle: Shape { + var radius: Int + override func getArea() -> Int { + return 3 * radius * radius + } + + // Colocar um ponto de interrpgação depois de `init` cria um inicializador + // Optional, o qual pode retornar nil + init?(radius: Int) { + self.radius = radius + super.init() + + if radius <= 0 { + return nil + } + } +} + +var myCircle = Circle(radius: 1) +print(myCircle?.getArea()) // Optional(3) +print(myCircle!.getArea()) // 3 +var myEmptyCircle = Circle(radius: -1) +print(myEmptyCircle?.getArea()) // "nil" +if let circle = myEmptyCircle { + // Não vai executar pois a variável myEmptyCircle é igual a nil + print("circle is not nil") +} + + +// +// MARK: Enumerações (Enums) +// + +// Enums pode opcionalmente ser um tipo especifico ou não. +// Enums podem conter métodos tal como as classes. + +enum Suit { + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } + } +} + +// Os valores de Enum permitem syntax reduzida, não é preciso escrever o tipo do enum +// quando a variável é explicitamente definida. +var suitValue: Suit = .Hearts + +// Enums que não sejam inteiros obrigam a atribuições valor bruto (raw value) diretas +enum BookName: String { + case John = "John" + case Luke = "Luke" +} +print("Name: \(BookName.John.rawValue)") + +// Enum com valores associados +enum Furniture { + // Associar com um inteiro (Int) + case Desk(height: Int) + // Associar com uma String e um Int + case Chair(String, Int) + + func description() -> String { + switch self { + case .Desk(let height): + return "Desk with \(height) cm" + case .Chair(let brand, let height): + return "Chair of \(brand) with \(height) cm" + } + } +} + +var desk: Furniture = .Desk(height: 80) +print(desk.description()) // "Desk with 80 cm" +var chair = Furniture.Chair("Foo", 40) +print(chair.description()) // "Chair of Foo with 40 cm" + + +// +// MARK: Protocolos (Protocols) +// + +// Protocolos (`protcol`s) obrigam a que os tipos tenham +// propriedades de instância, métodos de instância, métodos de tipo, +// operadores e subscripts específicos. + +protocol ShapeGenerator { + var enabled: Bool { get set } + func buildShape() -> Shape +} + +// Protocolos definidos com @objc permitem funções com optional +// que permitem verificar se existem conformidade +@objc protocol TransformShape { + optional func reshaped() + optional func canReshape() -> Bool +} + +class MyShape: Rect { + var delegate: TransformShape? + + func grow() { + sideLength += 2 + + // Coloca um ponto de interrogação após uma propriedade opcional, método + // ou subscript para graciosamente ignorar um valor nil e retornar nil + // em vez de provoar um erro em tempo de execução ("optional chaining"). + if let allow = self.delegate?.canReshape?() { + // testar o delegate e depois o método + self.delegate?.reshaped?() + } + } +} + + +// +// MARK: Outro +// + +// extensões (`extension`s): Adiciona funcionalidade extra a um tipo já existente. + +// Square agora "conforma" com o protocolo `Printable` +extension Square: Printable { + var description: String { + return "Area: \(self.getArea()) - ID: \(self.identifier)" + } +} + +print("Square: \(mySquare)") + +// Também é possível extender tipos já embutidos +extension Int { + var customProperty: String { + return "This is \(self)" + } + + func multiplyBy(num: Int) -> Int { + return num * self + } +} + +print(7.customProperty) // "This is 7" +print(14.multiplyBy(3)) // 42 + +// Generics: Semelhante a Java e C#. Usa a palavra-chave `where` para +// especificar requisitos do `generics`. + +func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? { + for (index, value) in enumerate(array) { + if value == valueToFind { + return index + } + } + return nil +} +let foundAtIndex = findIndex([1, 2, 3, 4], 3) +print(foundAtIndex == 2) // true + +// Operadores: +// Operadores personalizados podem começar com caracteres: +// / = - + * % < > ! & | ^ . ~ +// ou +// Caracteres Unicode matemáticos, símbolos, setas, dingbat e +// caracteres de desenho linha/caixa. +operador prefixo !!! {} + +// Um operador prefixo que triplica o comprimento do lado quando usado +prefix func !!! (inout shape: Square) -> Square { + shape.sideLength *= 3 + return shape +} + +// valor atual +print(mySquare.sideLength) // 4 + +// muda o comprimento deste lado usando o operador personalizado !!!, aumenta +// o comprimento 3x +!!!mySquare +print(mySquare.sideLength) // 12 + +// Operadores também podem ser generics +infix operator <-> {} +func <-><T: Equatable> (inout a: T, inout b: T) { + let c = a + a = b + b = c +} + +var foo: Float = 10 +var bar: Float = 20 + +foo <-> bar +print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0" +``` diff --git a/python.html.markdown b/python.html.markdown index 28b0a7ae..55f56071 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -8,21 +8,21 @@ contributors: filename: learnpython.py --- -Python was created by Guido Van Rossum in the early 90s. It is now one of the -most popular languages in existence. I fell in love with Python for its +Python was created by Guido Van Rossum in the early 90s. It is now one of the +most popular languages in existence. I fell in love with Python for its syntactic clarity. It's basically executable pseudocode. -Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) +Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] -Note: This article applies to Python 2.7 specifically, but should be applicable -to Python 2.x. Python 2.7 is reaching end of life and will stop being -maintained in 2020, it is though recommended to start learning Python with +Note: This article applies to Python 2.7 specifically, but should be applicable +to Python 2.x. Python 2.7 is reaching end of life and will stop being +maintained in 2020, it is though recommended to start learning Python with Python 3. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). -It is also possible to write Python code which is compatible with Python 2.7 +It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same time, using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports -allow you to write Python 3 code that will run on Python 2, so check out the +allow you to write Python 3 code that will run on Python 2, so check out the Python 3 tutorial. ```python @@ -126,6 +126,9 @@ not False # => True # A string can be treated like a list of characters "This is a string"[0] # => 'T' +# You can find the length of a string +len("This is a string") # => 16 + #String formatting with % #Even though the % string operator will be deprecated on Python 3.1 and removed #later at some time, it may still be good to know how it works. @@ -298,6 +301,9 @@ filled_dict.keys() # => ["three", "two", "one"] filled_dict.values() # => [3, 2, 1] # Note - Same as above regarding key ordering. +# Get all key-value pairs as a list of tuples with "items()" +filled_dicts.items() # => [("one", 1), ("two", 2), ("three", 3)] + # Check for existence of keys in a dictionary with "in" "one" in filled_dict # => True 1 in filled_dict # => False @@ -543,6 +549,10 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] +# You can construct set and dict comprehensions as well. +{x for x in 'abcddeef' if x in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + #################################################### ## 5. Classes @@ -662,39 +672,66 @@ import math dir(math) # If you have a Python script named math.py in the same -# folder as your current script, the file math.py will -# be loaded instead of the built-in Python module. +# folder as your current script, the file math.py will +# be loaded instead of the built-in Python module. # This happens because the local folder has priority -# over Python's built-in libraries. +# over Python's built-in libraries. #################################################### ## 7. Advanced #################################################### -# Generators help you make lazy code +# Generators +# A generator "generates" values as they are requested instead of storing +# everything up front + +# The following method (*NOT* a generator) will double all values and store it +# in `double_arr`. For large size of iterables, that might get huge! def double_numbers(iterable): + double_arr = [] + for i in iterable: + double_arr.append(i + i) + +# Running the following would mean we'll double all values first and return all +# of them back to be checked by our condition +for value in double_numbers(range(1000000)): # `test_non_generator` + print value + if value > 5: + break + +# We could instead use a generator to "generate" the doubled value as the item +# is being requested +def double_numbers_generator(iterable): for i in iterable: yield i + i -# A generator creates values on the fly. -# Instead of generating and returning all values at once it creates one in each -# iteration. This means values bigger than 15 wont be processed in -# double_numbers. -# Note xrange is a generator that does the same thing range does. -# Creating a list 1-900000000 would take lot of time and space to be made. -# xrange creates an xrange generator object instead of creating the entire list -# like range does. -# We use a trailing underscore in variable names when we want to use a name that -# would normally collide with a python keyword -xrange_ = xrange(1, 900000000) - -# will double all numbers until a result >=30 found -for i in double_numbers(xrange_): - print i - if i >= 30: +# Running the same code as before, but with a generator, now allows us to iterate +# over the values and doubling them one by one as they are being consumed by +# our logic. Hence as soon as we see a value > 5, we break out of the +# loop and don't need to double most of the values sent in (MUCH FASTER!) +for value in double_numbers_generator(xrange(1000000)): # `test_generator` + print value + if value > 5: break +# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`? +# Just as `double_numbers_generator` is the generator version of `double_numbers` +# We have `xrange` as the generator version of `range` +# `range` would return back and array with 1000000 values for us to use +# `xrange` would generate 1000000 values for us as we request / iterate over those items + +# Just as you can create a list comprehension, you can create generator +# comprehensions as well. +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 to console/terminal + +# You can also cast a generator comprehension directly to a list. +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + # Decorators # in this example beg wraps say diff --git a/python3.html.markdown b/python3.html.markdown index 2e37fccb..6b3486a6 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -119,6 +119,9 @@ b == a # => True, a's and b's objects are equal # A string can be treated like a list of characters "This is a string"[0] # => 'T' +# You can find the length of a string +len("This is a string") # => 16 + # .format can be used to format strings, like this: "{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" @@ -598,10 +601,51 @@ list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] +# You can construct set and dict comprehensions as well. +{x for x in 'abcddeef' if x in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + #################################################### -## 5. Classes +## 5. Modules #################################################### +# You can import modules +import math +print(math.sqrt(16)) # => 4.0 + +# You can get specific functions from a module +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# You can import all functions from a module. +# Warning: this is not recommended +from math import * + +# You can shorten module names +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Python modules are just ordinary python files. You +# can write your own, and import them. The name of the +# module is the same as the name of the file. + +# You can find out which functions and attributes +# defines a module. +import math +dir(math) + +# If you have a Python script named math.py in the same +# folder as your current script, the file math.py will +# be loaded instead of the built-in Python module. +# This happens because the local folder has priority +# over Python's built-in libraries. + + +#################################################### +## 6. Classes +#################################################### # We use the "class" operator to get a class class Human: @@ -624,7 +668,11 @@ class Human: # An instance method. All methods take "self" as the first argument def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) + print ("{name}: {message}".format(name=self.name, message=msg)) + + # Another instance method + def sing(self): + return 'yo... yo... microphone check... one two... one two...' # A class method is shared among all instances # They are called with the calling class as the first argument @@ -655,99 +703,161 @@ class Human: del self._age -# Instantiate a class -i = Human(name="Ian") -print(i.say("hi")) # prints out "Ian: hi" +# When a Python interpreter reads a source file it executes all its code. +# This __name__ check makes sure this code block is only executed when this +# module is the main program. +if __name__ == '__main__': + # Instantiate a class + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # i and j are instances of type Human, or in other words: they are Human objects + + # Call our class method + i.say(i.get_species()) # "Ian: H. sapiens" + # Change the shared attribute + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # Call the static method + print(Human.grunt()) # => "*grunt*" + print(i.grunt()) # => "*grunt*" + + # Update the property for this instance + i.age = 42 + # Get the property + i.say(i.age) # => 42 + j.say(j.age) # => 0 + # Delete the property + del i.age + # i.age # => this would raise an AttributeError -j = Human("Joel") -print(j.say("hello")) # prints out "Joel: hello" -# Call our class method -i.get_species() # => "H. sapiens" +#################################################### +## 6.1 Multiple Inheritance +#################################################### -# Change the shared attribute -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" +# Another class definition +class Bat: -# Call the static method -Human.grunt() # => "*grunt*" + species = 'Baty' -# Update the property -i.age = 42 + def __init__(self, can_fly=True): + self.fly = can_fly -# Get the property -i.age # => 42 + # This class also has a say method + def say(self, msg): + msg = '... ... ...' + return msg -# Delete the property -del i.age -i.age # => raises an AttributeError + # And its own method as well + def sonar(self): + return '))) ... (((' +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) -#################################################### -## 6. Modules -#################################################### +# from "filename-without-extension" import "function-or-class" +from human import Human +from bat import Bat -# You can import modules -import math -print(math.sqrt(16)) # => 4.0 +# Batman inherits from both Human and Bat +class Batman(Human, Bat): -# You can get specific functions from a module -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 + # Batman has its own value for the species class attribute + species = 'Superhero' -# You can import all functions from a module. -# Warning: this is not recommended -from math import * + def __init__(self, *args, **kwargs): + # Typically to inherit attributes you have to call super: + #super(Batman, self).__init__(*args, **kwargs) + # However we are dealing with multiple inheritance here, and super() + # only works with the next base class in the MRO list. + # So instead we explicitly call __init__ for all ancestors. + # The use of *args and **kwargs allows for a clean way to pass arguments, + # with each parent "peeling a layer of the onion". + Human.__init__(self, 'anonymous', *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # override the value for the name attribute + self.name = 'Sad Affleck' -# You can shorten module names -import math as m -math.sqrt(16) == m.sqrt(16) # => True + def sing(self): + return 'nan nan nan nan nan batman!' -# Python modules are just ordinary python files. You -# can write your own, and import them. The name of the -# module is the same as the name of the file. -# You can find out which functions and attributes -# defines a module. -import math -dir(math) +if __name__ == '__main__': + sup = Batman() + + # Instance type checks + if isinstance(sup, Human): + print('I am human') + if isinstance(sup, Bat): + print('I am bat') + if type(sup) is Batman: + print('I am Batman') + + # Get the Method Resolution search Order used by both getattr() and super(). + # This attribute is dynamic and can be updated + print(Batman.__mro__) # => (<class '__main__.Batman'>, <class 'human.Human'>, <class 'bat.Bat'>, <class 'object'>) + + # Calls parent method but uses its own class attribute + print(sup.get_species()) # => Superhero + + # Calls overloaded method + print(sup.sing()) # => nan nan nan nan nan batman! + + # Calls method from Human, because inheritance order matters + sup.say('I agree') # => Sad Affleck: I agree + + # Call method that exists only in 2nd ancestor + print(sup.sonar()) # => ))) ... ((( + + # Inherited class attribute + sup.age = 100 + print(sup.age) + + # Inherited attribute from 2nd ancestor whose default value was overridden. + print('Can I fly? ' + str(sup.fly)) + -# If you have a Python script named math.py in the same -# folder as your current script, the file math.py will -# be loaded instead of the built-in Python module. -# This happens because the local folder has priority -# over Python's built-in libraries. #################################################### ## 7. Advanced #################################################### -# Generators help you make lazy code +# Generators help you make lazy code. def double_numbers(iterable): for i in iterable: yield i + i -# A generator creates values on the fly. -# Instead of generating and returning all values at once it creates one in each -# iteration. This means values bigger than 15 wont be processed in -# double_numbers. -# We use a trailing underscore in variable names when we want to use a name that -# would normally collide with a python keyword -range_ = range(1, 900000000) -# will double all numbers until a result >=30 found -for i in double_numbers(range_): +# Generators are memory-efficient because they only load the data needed to +# process the next value in the iterable. This allows them to perform +# operations on otherwise prohibitively large value ranges. +# NOTE: `range` replaces `xrange` in Python 3. +for i in double_numbers(range(1, 900000000)): # `range` is a generator. print(i) if i >= 30: break +# Just as you can create a list comprehension, you can create generator +# comprehensions as well. +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 to console/terminal + +# You can also cast a generator comprehension directly to a list. +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + # Decorators -# in this example beg wraps say -# Beg will call say. If say_please is True then it will change the returned -# message +# In this example `beg` wraps `say`. If say_please is True then it +# will change the returned message. from functools import wraps diff --git a/qt.html.markdown b/qt.html.markdown new file mode 100644 index 00000000..71d12909 --- /dev/null +++ b/qt.html.markdown @@ -0,0 +1,157 @@ +--- +category: tool +tool: Qt Framework +language: c++ +filename: learnqt.cpp +contributors: + - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"] +lang: en +--- + +**Qt** is a widely-known framework for developing cross-platform software that can be run on various software and hardware platforms with little or no change in the code, while having the power and speed of native applications. Though **Qt** was originally written in *C++*, there are its ports to other languages: *PyQt*, *QtRuby*, *PHP-Qt*, etc. + +**Qt** is beautiful for creating applications with graphical user interface (GUI). This tutorial is how to do it in *C++*. + +```c++ +/* + * Let's start clasically + */ + +// all headers from Qt framework start with capital letter 'Q' +#include <QApplication> +#include <QLineEdit> + +int main(int argc, char *argv[]) { + // create an object to manage application-wide resources + QApplication app(argc, argv); + + // create line edit widget and show it on screen + QLineEdit lineEdit("Hello world!"); + lineEdit.show(); + + // start the application's event loop + return app.exec(); +} +``` + +GUI-related part of **Qt** is all about *widgets* and *connections* between them. + +[READ MORE ABOUT WIDGETS](http://doc.qt.io/qt-5/qtwidgets-index.html) + +```c++ +/* + * Let's create a label and a button. + * A label should appear when a button is pressed. + * + * Qt code is speaking for itself. + */ + +#include <QApplication> +#include <QDialog> +#include <QVBoxLayout> +#include <QPushButton> +#include <QLabel> + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + + QDialog dialogWindow; + dialogWindow.show(); + + // add vertical layout + QVBoxLayout layout; + dialogWindow.setLayout(&layout); + + QLabel textLabel("Thanks for pressing that button"); + layout.addWidget(&textLabel); + textLabel.hide(); + + QPushButton button("Press me"); + layout.addWidget(&button); + + // show hidden label when the button is pressed + QObject::connect(&button, &QPushButton::pressed, + &textLabel, &QLabel::show); + + return app.exec(); +} +``` + +Notice that *QObject::connect* part. This method is used to connect *SIGNALS* of one objects to *SLOTS* of another. + +**Signals** are being emited when certain things happen with objects, like *pressed* signal is emited when user presses on QPushButton object. + +**Slots** are *actions* that might be performed in response to received signals. + +[READ MORE ABOUT SLOTS AND SIGNALS](http://doc.qt.io/qt-4.8/signalsandslots.html) + + +Next, let's learn that we can not only use standard widgets but also extend their behaviour using inheritance. Let's create a button and count how many times it was pressed. For this purpose we define our own class *CounterLabel*. It must be declared in separate file because of specific Qt architecture. + +```c++ +// counterlabel.hpp + +#ifndef COUNTERLABEL +#define COUNTERLABEL + +#include <QLabel> + +class CounterLabel : public QLabel { + Q_OBJECT // Qt-defined macros that must be present in every custom widget + +public: + CounterLabel() : counter(0) { + setText("Counter has not been increased yet"); // method of QLabel + } + +public slots: + // action that will be called in response to button press + void increaseCounter() { + setText(QString("Counter value: %1").arg(QString::number(++counter))); + } + +private: + int counter; +}; + +#endif // COUNTERLABEL +``` + +```c++ +// main.cpp +// Almost the same as in previous example + +#include <QApplication> +#include <QDialog> +#include <QVBoxLayout> +#include <QPushButton> +#include <QString> +#include "counterlabel.hpp" + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + + QDialog dialogWindow; + dialogWindow.show(); + + QVBoxLayout layout; + dialogWindow.setLayout(&layout); + + CounterLabel counterLabel; + layout.addWidget(&counterLabel); + + QPushButton button("Push me once more"); + layout.addWidget(&button); + QObject::connect(&button, &QPushButton::pressed, + &counterLabel, &CounterLabel::increaseCounter); + + return app.exec(); +} +``` + +## Furter reading +That's it! Of course Qt framework is much much larger than the part that was covered in this tutorial, so be ready to read and practice. + +[READ MORE ABOUT QT](http://doc.qt.io/qt-4.8/tutorials.html) + +Good luck and have fun diff --git a/racket.html.markdown b/racket.html.markdown index 0fe3f030..96dcaf25 100644 --- a/racket.html.markdown +++ b/racket.html.markdown @@ -114,18 +114,42 @@ some-var ; => 5 "Alice" me) ; => "Bob" +;; let* is like let, but allows you to use previous bindings in creating later bindings +(let* ([x 1] + [y (+ x 1)]) + (* x y)) + +;; finally, letrec allows you to define recursive and mutually recursive functions +(letrec ([is-even? (lambda (n) + (or (zero? n) + (is-odd? (sub1 n))))] + [is-odd? (lambda (n) + (and (not (zero? n)) + (is-even? (sub1 n))))]) + (is-odd? 11)) + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 3. Structs and Collections ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Structs +; By default, structs are immutable (struct dog (name breed age)) (define my-pet (dog "lassie" "collie" 5)) my-pet ; => #<dog> +; returns whether the variable was constructed with the dog constructor (dog? my-pet) ; => #t +; accesses the name field of the variable constructed with the dog constructor (dog-name my-pet) ; => "lassie" +; You can explicitly declare a struct to be mutable with the #:mutable option +(struct rgba-color (red green blue alpha) #:mutable) +(define burgundy + (rgba-color 144 0 32 1.0)) +(set-color-green! burgundy 10) +(color-green burgundy) ; => 10 + ;;; Pairs (immutable) ;; `cons' constructs pairs, `car' and `cdr' extract the first ;; and second elements @@ -143,6 +167,16 @@ my-pet ; => #<dog> ;; and a quote can also be used for a literal list value '(1 2 3) ; => '(1 2 3) +;; Racket has predefined functions on top of car and cdr, to extract parts of a list +(cadr (list 1 2 3)) ; => 2 +(car (cdr (list 1 2 3))) ; => 2 + +(cddr (list 1 2 3)) ; => '(3) +(cdr (cdr (list 1 2 3))) ; => '(3) + +(caddr (list 1 2 3)) ; => 3 +(car (cdr (cdr (list 1 2 3)))) ; => 3 + ;; Can still use `cons' to add an item to the beginning of a list (cons 4 '(1 2 3)) ; => '(4 1 2 3) diff --git a/ro-ro/bf-ro.html.markdown b/ro-ro/bf-ro.html.markdown index 61b555ed..686dd39d 100644 --- a/ro-ro/bf-ro.html.markdown +++ b/ro-ro/bf-ro.html.markdown @@ -1,10 +1,11 @@ --- -language: brainfuck +language: bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] translators: - ["Petru Dimitriu", "http://petru-dimitriu.github.io"] +filename: bf-ro.html lang: ro-ro --- @@ -87,4 +88,4 @@ Așadar acesta este limbajul brainfuck. Nu e atât de greu, nu? Pentru amuzament, puteți să scrieți propriile dumneavoastră limbaje, sau puteți scrie un interpretor pentru brainfuck într-un alt limbaj. Interpretorul este destul de ușor de implementat, dar dacă sunteți masochist, încercați -să implementați un interpretor de brainfuck… în brainfuck.
\ No newline at end of file +să implementați un interpretor de brainfuck… în brainfuck. diff --git a/rst.html.markdown b/rst.html.markdown new file mode 100644 index 00000000..161a0610 --- /dev/null +++ b/rst.html.markdown @@ -0,0 +1,107 @@ +--- +language: restructured text +contributors: + - ["DamienVGN", "https://github.com/martin-damien"] +filename: restructuredtext.rst +--- + +RST is file format formely created by Python community to write documentation (and so, is part of Docutils). + +RST files are simple text files with lightweight syntaxe (comparing to HTML). + + +## Installation + +To use Restructured Text, you will have to install [Python](http://www.python.org) and the `docutils` package. + +`docutils` can be installed using the commandline: + +```bash +$ easy_install docutils +``` + +If your system have `pip`, you can use it too: + +```bash +$ pip install docutils +``` + + +## File syntaxe + +A simple example of the file syntax: + +```rst +.. Line with two dotes are special commands. But if no command can be found, the line is considered as a comment + +========================================================= +Main titles are written using equals signs over and under +========================================================= + +Note that theire must be as many equals signs as title characters. + +Title are underlined with equals signs too +========================================== + +Subtitles with dashes +--------------------- + +And sub-subtitles with tilde +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can put text in *italic* or in **bold**, you can "mark" text as code with double backquote ``: ``print()``. + +Lists are as simple as markdown: + +- First item +- Second item + - Sub item + +or + +* First item +* Second item + * Sub item + +Tables are really easy to write: + +=========== ======== +Country Capital +=========== ======== +France Paris +Japan Tokyo +=========== ======== + +More complexe tabless can be done easily (merged columns and/or rows) but I suggest you to read the complete doc for this :) + +Their is multiple ways to make links: + +- By adding an underscore after a word : Github_ and by adding the target after the text (this have the advantage to not insert un-necessary URL inside the readed text). +- By typing a full comprehensible URL : https://github.com/ (will be automatically converted in link) +- By making a more "markdown" link: `Github <https://github.com/>`_ . + +.. _Github https://github.com/ + +``` + + +## How to use it + +RST comes with docutils in which you have `rst2html` for exemple: + +```bash +$ rst2html myfile.rst output.html +``` + +*Note : On some systems the command could be rst2html.py* + +But their is more complexe applications that uses RST file format: + +- [Pelican](http://blog.getpelican.com/), a static site generator +- [Sphinx](http://sphinx-doc.org/), a documentation generator +- and many others + + +## Readings + +- [Official quick reference](http://docutils.sourceforge.net/docs/user/rst/quickref.html) diff --git a/ruby.html.markdown b/ruby.html.markdown index adf5ce81..a1532855 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -210,7 +210,7 @@ array.push(6) #=> [1, 2, 3, 4, 5, 6] # Check if an item exists in an array array.include?(1) #=> true -# Hashes are Ruby's primary dictionary with keys/value pairs. +# Hashes are Ruby's primary dictionary with key/value pairs. # Hashes are denoted with curly braces: hash = { 'color' => 'green', 'number' => 5 } @@ -612,7 +612,7 @@ Something.new.qux # => 'qux' - [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. - [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Learn Ruby through a series of interactive tutorials. -- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) +- [Official Documentation](http://ruby-doc.org/core) - [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) - [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. - [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. diff --git a/rust.html.markdown b/rust.html.markdown index f82f7785..f1b62ef4 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -27,8 +27,15 @@ concepts that are generally found in higher-level languages. This makes Rust not only fast, but also easy and efficient to code in. ```rust -// This is a comment. Single-line look like this... -/* ...and multi-line comment look like this */ +// This is a comment. Line comments look like this... +// and extend multiple lines like this. + +/// Documentation comments look like this and support markdown notation. +/// # Examples +/// +/// ``` +/// let five = 5 +/// ``` /////////////// // 1. Basics // @@ -282,7 +289,7 @@ fn main() { println!("{}", var); // Unlike `box`, `var` can still be used println!("{}", *ref_var); // var = 5; // this would not compile because `var` is borrowed - // *ref_var = 6; // this would not too, because `ref_var` is an immutable reference + // *ref_var = 6; // this would not either, because `ref_var` is an immutable reference // Mutable reference // While a value is mutably borrowed, it cannot be accessed at all. @@ -290,8 +297,9 @@ fn main() { let ref_var2: &mut i32 = &mut var2; *ref_var2 += 2; // '*' is used to point to the mutably borrowed var2 - println!("{}", *ref_var2); // 6 , //var2 would not compile. //ref_var2 is of type &mut i32, so //stores a reference to an i32 not the value. - // var2 = 2; // this would not compile because `var2` is borrowed + println!("{}", *ref_var2); // 6 , // var2 would not compile. + // ref_var2 is of type &mut i32, so stores a reference to an i32, not the value. + // var2 = 2; // this would not compile because `var2` is borrowed. } ``` diff --git a/sass.html.markdown b/sass.html.markdown index 4d4ece71..802b40f4 100644 --- a/sass.html.markdown +++ b/sass.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Laura Kyle", "https://github.com/LauraNK"] - ["Sean Corrales", "https://github.com/droidenator"] - ["Kyle Mendes", "https://github.com/pink401k"] + - ["Keith Miyake", "https://github.com/kaymmm"] --- Sass is a CSS extension language that adds features such as variables, nesting, mixins and more. @@ -52,16 +53,161 @@ body { font-family: 'Roboto', sans-serif; } - /* This is much more maintainable than having to change the color each time it appears throughout your stylesheet. */ -/* Mixins +/* Control Directives ============================== */ +/* Sass lets you use @if, @else, @for, @while, and @each to control the + compilation of your code to CSS. */ + +/* @if/@else blocks behave exactly as you might expect */ + +$debug: true !default; + +@mixin debugmode { + @if $debug { + @debug "Debug mode enabled"; + + display: inline-block; + } + @else { + display: none; + } +} + +.info { + @include debugmode; +} + +/* If $debug is set to true, .info is displayed; if it's set to false then +.info is not displayed. + +Note: @debug will output debugging information to the command line. +Useful for checking variables while debugging your SCSS. */ + +.info { + display: inline-block; +} + +/* @for is a control loop that iterates through a range of values. +Particularly useful for setting styles on a collection of items. +There are two forms, "through" and "to." The former includes the last value, +the latter stops at the last value. */ + +@for $c from 1 to 4 { + div:nth-of-type(#{$c}) { + left: ($c - 1) * 900 / 3; + } +} + +@for $c from 1 through 3 { + .myclass-#{$c} { + color: rgb($c * 255 / 3, $c * 255 / 3, $c * 255 / 3); + } +} + +/* Will compile to: */ +div:nth-of-type(1) { + left: 0; +} + +div:nth-of-type(2) { + left: 300; +} + +div:nth-of-type(3) { + left: 600; +} + +.myclass-1 { + color: #555555; +} + +.myclass-2 { + color: #aaaaaa; +} + +.myclass-3 { + color: white; +// SASS automatically converts #FFFFFF to white +} + +/* @while is very straightforward: */ + +$columns: 4; +$column-width: 80px; + +@while $columns > 0 { + .col-#{$columns} { + width: $column-width; + left: $column-width * ($columns - 1); + } + + $columns: $columns - 1; +} + +/* Will output the following CSS: */ + +.col-4 { + width: 80px; + left: 240px; +} + +.col-3 { + width: 80px; + left: 160px; +} + +.col-2 { + width: 80px; + left: 80px; +} + +.col-1 { + width: 80px; + left: 0px; +} + +/* @each functions like @for, except using a list instead of ordinal values +Note: you specify lists just like other variables, with spaces as +delimiters. */ + +$social-links: facebook twitter linkedin reddit; + +.social-links { + @each $sm in $social-links { + .icon-#{$sm} { + background-image: url("images/#{$sm}.png"); + } + } +} + +/* Which will output: */ + +.social-links .icon-facebook { + background-image: url("images/facebook.png"); +} + +.social-links .icon-twitter { + background-image: url("images/twitter.png"); +} + +.social-links .icon-linkedin { + background-image: url("images/linkedin.png"); +} + +.social-links .icon-reddit { + background-image: url("images/reddit.png"); +} + + +/*Mixins +==============================*/ /* If you find you are writing the same code for more than one element, you might want to store that code in a mixin. @@ -93,7 +239,6 @@ div { background-color: #A3A4FF; } - /* You can use mixins to create a shorthand property. */ @mixin size($width, $height) { @@ -139,7 +284,7 @@ body { } .footer { - background-color: fade_out(#000000, 0.25) + background-color: fade_out(#000000, 0.25); } /* Compiles to: */ diff --git a/scala.html.markdown b/scala.html.markdown index 745605ed..7f5f0ec3 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -88,6 +88,7 @@ true == false // false 6 / 2 // 3 6 / 4 // 1 6.0 / 4 // 1.5 +6 / 4.0 // 1.5 // Evaluating an expression in the REPL gives you the type and value of the result diff --git a/sk-sk/bash.html.markdown b/sk-sk/bash.html.markdown new file mode 100644 index 00000000..e9d1490c --- /dev/null +++ b/sk-sk/bash.html.markdown @@ -0,0 +1,286 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] +translators: + - ["Juraj Kostolanský", "http://www.kostolansky.sk"] +lang: sk-sk +filename: LearnBash-sk.sh +--- + +Bash je pomenovanie pre unix shell (príkazový interpreter), ktorý bol +tiež distribuovaný ako shell pre GNU operačné systémy a ako predvolený +shell pre Linux a Mac OS X. +Takmer všetky príklady uvedené nižšie môžu byť súčasťou shell skriptu alebo +vykonané priamo v shelli. + +[Viac informácií tu.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# Prvý riadok skriptu je tzv. shebang, ktorý systému povie ako skript vykonať: +# http://en.wikipedia.org/wiki/Shebang_(Unix) +# Komentáre začínajú znakom #. Shebang je tiež komentár. + +# Jednoduchý príklad: +echo Ahoj svet! + +# Každý príkaz začína na novom riadku alebo za bodkočiarkou: +echo 'Toto je prvý riadok'; echo 'Toto je druhý riadok' + +# Deklarácia premenných vyzerá takto: +Premenna="Nejaky retazec" + +# Ale nie takto: +Premenna = "Nejaky retazec" +# Bash si bude myslieť, že Premenna je príkaz, ktorý musí vykonať. +# Výsledkom bude chyba, pretože taký príkaz nenájde. + +# Alebo takto: +Premenna= 'Nejaky retazec' +# Bash zistí, že 'Nejaky retazec' je príkaz, ktorý musí vykonať. +# Výsledkom je opäť chyba, lebo taký príkaz neexistuje. + +# Používanie premenných: +echo $Premenna +echo "$Premenna" +echo '$Premenna' +# Keď je premenná použitá samostatne - priradenie, exportovanie a pod. - jej +# meno sa píše bez znaku $. Keď sa používa hodnota premennej, pred názov sa +# dáva znak $. Pozor však pri použití ' (apostrof), ktorý nenahradí premennú +# hodnotou! + +# Nahradenie reťazca v premennej +echo ${Premenna/Nieco/A} +# Toto nahradí prvý výskyt reťazca "Nieco" za "A" + +# Podreťazec z premennej +Dlzka=7 +echo ${Premenna:0:Dlzka} +# Toto vráti iba prvých 7 znakov z hodnoty premennej + +# Predvolená hodnota premennej +echo ${Foo:-"PredvolenaHodnotaAkFooChybaAleboJePrazdna"} +# Toto funguje pre null (Foo=) a prázdny reťazec (Foo=""); +# nula (Foo=0) vráti 0. Všimni si, že toto iba vráti predvolenú hodnotu, +# ale nezmení hodnotu premennej. + +# Štandardné premenné: +# Existujú aj užitočné "vstavané" premenné, ako +echo "Hodnota vrátená posledným programom: $?" +echo "PID skriptu: $$" +echo "Počet argumentov: $#" +echo "Argumeny skriptu: $@" +echo "Argumeny skriptu oddelené do rôznych premenných: $1 $2..." + +# Čítanie hodnoty zo vstupu: +echo "Ako sa voláš?" +read Meno # Premenná nemusí byť deklarovaná skôr +echo Ahoj, $Meno! + +# Klasická if štruktúra: +# použi 'man test' Pre viac informácií o podmienkach +if [ $Meno -ne $USER ] +then + echo "Meno nie je tvoje používateľské meno" +else + echo "Meno je tvoje používateľské meno" +fi + +# Existuje aj podmienené vykonanie +echo "Vykonané vždy" || echo "Vykonané iba ak prvý príkaz zlyhá" +echo "Vykonané vždy" && echo "Vykonané iba ak prvý príkaz uspeje" + +# Pre použitie && a || s if-podmienkou je potrebné použiť zátvorky: +if [ $Meno == "Steve" ] && [ $Vek -eq 15 ] +then + echo "Toto sa spustí ak $Meno je Steve a $Vek je 15." +fi + +if [ $Meno == "Daniya" ] || [ $Meno == "Zach" ] +then + echo "Toto sa spustí ak $Meno je Daniya alebo Zach." +fi + +# Pre výrazy sa používa nasledovný formát: +echo $(( 10 + 5 )) + +# Na rozdiel od programovacích jazykov shell pracuje v kontexte aktuálneho +# adresára. Môžeš si prehliadať súbory a adresáre v aktuálnom adresári pomocou +# príkazu ls: +ls + +# Tieto príkazy majú aj argumenty pre úpravu ich správania: +ls -l # Vypíše zoznam súborov a priečinkov, každý na samostatnom riadku + +# Výsledok predchádzajúceho príkazu môže byť využitý priamo ako vstup pre +# ďalší príkaz. +# Príkaz grep filtruje vstupvyužitím poskytnutého vzoru. Takto môžeme vypísať +# iba .txt súbory: +ls -l | grep "\.txt" + +# Vstup a výstup príkazu (stdin, stdout, stderr) môžu byť presmerované. +# Toto číta stdin až po ^EOF$ a prepíše hello.py riadkami medzi "EOF": +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ import print_function +import sys +print("#stdout", file=sys.stdout) +print("#stderr", file=sys.stderr) +for line in sys.stdin: + print(line, file=sys.stdout) +EOF + +# Spustí hello.py s rôznymi presmerovaniami pre stdin, stdout a stderr: +python hello.py < "vstup.in" +python hello.py > "vystup.out" +python hello.py 2> "chyby.err" +python hello.py > "vystup-a-chyby.log" 2>&1 +python hello.py > /dev/null 2>&1 +# Chybový výstup prepíše uvedený súbor, ak už existuje. +# Ak chceš výstup pridať za existujúci obsah, použi ">>": +python hello.py >> "vystup.out" 2>> "chyby.err" + +# Prepíše vystup.out, pripojí k chyby.err a spočíta riadky: +info bash 'Basic Shell Features' 'Redirections' > vystup.out 2>> chyby.err +wc -l vystup.out chyby.err + +# Spustí príkaz a vypíše deskriptor súboru (napr. /dev/fd/123) +# pozri: man fd +echo <(echo "#ahojsvet") + +# Prepíše vystup.out s "#ahojsvet": +cat > vystup.out <(echo "#ahojsvet") +echo "#ahojsvet" > vystup.out +echo "#ahojsvet" | cat > vystup.out +echo "#ahojsvet" | tee vystup.out >/dev/null + +# Potichu odstráni dočasné súbory (pridaj '-i' pre interaktivitu) +rm -v vystup.out chyby.err vystup-a-chyby.log + +# Príkazy môžu byť nahradené v iných príkazoch použitím $( ): +# Nasledujúci príkaz vypíše počet súborov a adresárov v aktuálnom adresári +echo "Je tu $(ls | wc -l) súborov a priečinkov." + +# To isté sa dá spraviť pomocou spätného apostrofu ``, tie však nemôžu byť +# vhniezdené - preferovaný spôsob je preto $( ). +echo "Je tu `ls | wc -l` súborov a priečinkov." + +# Bash používa case, ktorý funguje podobne ako switch v Jave a C++: +case "$Premenna" in + #Zoznam vzorov pre podmienky + 0) echo "Je to nula.";; + 1) echo "Je to jednotka.";; + *) echo "Nie je to null.";; +esac + +# for-cyklus iteruje cez všetky argumenty: +# Obsah premennej $Premenna sa vypíše trikrát. +for Premenna in {1..3} +do + echo "$Premenna" +done + +# Alebo "tradičným" spôsobom: +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Môžu sa použiť aj na súbory.. +# Toto spustí príkaz 'cat' na subor1 a subor2 +for Premenna in subor1 subor2 +do + cat "$Premenna" +done + +# ..alebo na výstup príkazu. +# Toto použije príkaz cat na výstup z ls. +for Vystup in $(ls) +do + cat "$Vystup" +done + +# while-cykklus: +while [ true ] +do + echo "telo cyklu..." + break +done + +# Môžeš tiež definovať funkice +# Definícia: +function foo () +{ + echo "Argumenty fungujú rovnako ako pri skriptoch: $@" + echo "A: $1 $2..." + echo "Toto je funkcia" + return 0 +} + +# alebo jednoducho +bar () +{ + echo "Iný spôsob definície funkcií" + return 0 +} + +# Volanie funkcie +foo "Moje meno je" $Meno + +# Existuje veľa užitočných príkazov, ktoré sa oplatí naučiť: +# vypíše posledných 10 riadkov zo subor.txt +tail -n 10 subor.txt +# vypíše prvých 10 riadkov zo subor.txt +head -n 10 subor.txt +# zotriedi riadky zo subor.txt +sort subor.txt +# vypíše alebo vynechá opakované riadky, použitím -d ich vypíše +uniq -d subor.txt +# vypíše iba prvý stĺpecpred znakom ',' +cut -d ',' -f 1 subor.txt +# nahradí každý výskyt 'oukej' za 'super' v subor.txt (možnosť použiť regex) +sed -i 's/oukej/super/g' subor.txt +# vypíše všetky riadky zo subor.txt ktoré vyhovujú regexu +# ukážka vypíše riadky ktoré začínajú s "foo" a končia s "bar" +grep "^foo.*bar$" subor.txt +# pre výpis počtu riadkov vyhovujúcich regexu slúži "-c" +grep -c "^foo.*bar$" subor.txt +# pre vyhľadávanie reťazca bez regexu slúži fgrep (alebo grep -F) +fgrep "^foo.*bar$" subor.txt + + +# Prečítaj si dokumentáciu k Bash shellu použitím príkazu 'help': +help +help help +help for +help return +help source +help . + +# Prečítaj si Bash manpage dokumentáciu príkazom 'man' +apropos bash +man 1 bash +man bash + +# Prečítaj si info dokumentáciu pomocou 'info' (? pre help) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# Prečítaj si bash info dokumentáciu: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` diff --git a/sk-sk/coffeescript.html.markdown b/sk-sk/coffeescript.html.markdown new file mode 100644 index 00000000..30bbceec --- /dev/null +++ b/sk-sk/coffeescript.html.markdown @@ -0,0 +1,108 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Juraj Kostolanský", "http://www.kostolansky.sk"] +lang: sk-sk +filename: coffeescript-fr.coffee +--- + +CoffeeScript je jazyk, ktorý sa kompiluje do ekvivalentného JavaScriptu, +neexistuje peňho interpretácia počas behu programu (runtime). +CoffeeScript sa snaží vytvárať čitateľný, pekne formátovaný a optimalizovaný +JavaScriptový kód pracujúci pod každým JavaScriptovým prostredím. + +Pozri tiež [stránku CoffeeScript](http://coffeescript.org/), ktoré obsahuje kompletný tutoriál o CoffeeScripte. + +```coffeescript +# CoffeeScript je jazyk hipsterov. +# Ide s trendom mnohých moderných jazykov. +# Komentáre sú podobné tým v Ruby a Pythone, používajú symbol #. + +### +Blokové komentáre vyzerajú takto, prekladajú sa priamo do '/ * ... * /' +pre výsledný kód JavaScriptu. + +Predtým, než budeš pokračovať, mal by si rozumieť sémantike JavaScriptu. +### + +# Priradenia: +cislo = 42 #=> var cislo = 42; +opak = true #=> var opak = true; + +# Podmienky: +cislo = -42 if opak #=> if(opak) { cislo = -42; } + +# Funkcie: +stvorec = (x) -> x * x #=> var stvorec = function(x) { return x * x; } + +vypln = (nadoba, tekutina = "káva") -> + "#{nadoba} sa napĺňa tekutinou #{tekutina}..." +#=>var vypln; +# +#vypln = function(nadoba, tekutina) { +# if (tekutina == null) { +# tekutina = "káva"; +# } +# return nadoba + " sa napĺňa tekutinou " + tekutina + "..."; +#}; + +# Rozsahy: +zoznam = [1..5] #=> var zoznam = [1, 2, 3, 4, 5]; + +# Objekty: +matika = + zaklad: Math.sqrt + stvorec: square + kocka: (x) -> x * square x +#=> var matika = { +# "zaklad": Math.sqrt, +# "stvorec": square, +# "kocka": function(x) { return x * square(x); } +#} + +# Splat operátor: +zavod = (vitaz, bezci...) -> + print vitaz, bezci +#=>zavod = function() { +# var vitaz, bezci; +# vitaz = arguments[0], +# bezci = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(vitaz, bezci); +#}; + +# Existencia: +alert "Vedel som to!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) +# { alert("Vedel som to!"); } + +# Pole: +kocky = (matika.kocka cislo for cislo in zoznam) +#=>kocky = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = zoznam.length; _i < _len; _i++) { +# cislo = zoznam[_i]; +# _results.push(matika.kocka(cislo)); +# } +# return _results; +# })(); + +jedla = ['brokolica', 'špenát', 'čokoláda'] +zjedz jedlo for jedlo in jedla when jedlo isnt 'čokoláda' +#=>jedla = ['brokolica', 'špenát', 'čokoláda']; +# +#for (_k = 0, _len2 = jedla.length; _k < _len2; _k++) { +# jedlo = jedla[_k]; +# if (jedlo !== 'čokoláda') { +# zjedz(jedlo); +# } +#} +``` + +## Ďalšie zdroje + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) diff --git a/sk-sk/json.html.markdown b/sk-sk/json.html.markdown new file mode 100644 index 00000000..2b1fbb58 --- /dev/null +++ b/sk-sk/json.html.markdown @@ -0,0 +1,61 @@ +--- +language: json +filename: learnjson-sk.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Juraj Kostolanský", "http://www.kostolansky.sk"] +lang: sk-sk +--- + +Nakoľko je JSON extrémne jednoduchý formát na výmenu dát, toto bude +pravdepodobne najjednoduchšie "Learn X in Y Minutes". + +JSON v jeho základnej forme nemá komentáre, ale veľa parserov akceptuje +komentáre v štýle C (`//`, `/* */`). V tomto návode však bude všetko +100% valídny JSON. + +```json +{ + "kľúč": "hodnota", + + "kľúč": "musí byť vždy uzavretý v dvojitých uvodzovkách", + "čísla": 0, + "reťazce": "Ahøj, svet. Unicode je povolený pri použití \"únikovej sekvencie (escaping)\".", + "boolean?": true, + "nič": null, + + "veľké číslo": 1.2e+100, + + "objekty": { + "komentár": "Väčšina štruktúry bude pochádzať z objektov.", + + "pole": [0, 1, 2, 3, "Pole môže obsahovať čokoľvek.", 5], + + "iný objekt": { + "komentár": "Môžu byť vhniezdené, čo môže byť užitočné." + } + }, + + "nezmysly": [ + { + "zdroje draslíka": ["banány"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternatívny štýl": { + "komentár": "sleduj toto!" + , "pozícia čiarky": "nezáleží na nej - pokiaľ je pred hodnotou, všetko je ok" + , "iný komentár": "pekné, že?" + }, + + "to bolo rýchle": "A už sme aj na konci. Teraz ovládš všetko, čo ti JSON môže ponúknuť." +} +``` diff --git a/smallbasic.html.markdown b/smallbasic.html.markdown new file mode 100644 index 00000000..9244525e --- /dev/null +++ b/smallbasic.html.markdown @@ -0,0 +1,131 @@ +--- +language: SmallBASIC +filename: learnsmallbasic.bas +contributors: + - ["Chris Warren-Smith", "http://smallbasic.sourceforge.net"] +--- + +## About + +SmallBASIC is a fast and easy to learn BASIC language interpreter ideal for everyday calculations, scripts and prototypes. SmallBASIC includes trigonometric, matrices and algebra functions, a built in IDE, a powerful string library, system, sound, and graphic commands along with structured programming syntax. + +## Development + +SmallBASIC was originally developed by Nicholas Christopoulos in late 1999 for the Palm Pilot. Project development has been continued by Chris Warren-Smith since around 2005. + +Versions of SmallBASIC have been made for a number of early hand held devices including Franklin eBookman and the Nokia 770. Also various desktop versions have been released based on a variety of GUI tool-kits, some of which have become defunct. The current supported platforms are Linux and Windows based on SDL2 and Android based on NDK. A desktop command line version is also available, although not typically released in binary form. + +In around 2008 a large corporation released a BASIC like programming environment with a similar sounding name. SmallBASIC is not related to this other project. + +``` +REM This is a comment +' and this is also a comment + +REM print text +print "hello" +? "? is short for PRINT" + +REM Control structures +FOR index = 0 TO 10 STEP 2 + ? "This is line number "; index +NEXT +J=0 +REPEAT + J++ +UNTIL J=10 +WHILE J>0 + J-- +WEND + +REM Select case statement +Select Case "Cool" + Case "null", 1,2,3,4,5,6,7,8,"Cool","blah" + Case "Not cool" + PRINT "Epic fail" + Case Else + PRINT "Fail" +End Select + +REM catching errors with TRY/CATCH +Try + fn = Freefile + Open filename For Input As #fn +Catch err + Print "failed to open" +End Try + +REM User defined subs and functions +func add2(x,y) + ' variables may be declared as local within the scope of a SUB or FUNC + local K + k = "k will cease to exist when this FUNC returns" + add2=x+y +end +Print add2(5,5) +sub print_it(it) + print it +end +print_it "IT...." + +REM Display lines and pixels +At 0,ymax/2+txth("Q") +Color 1: ? "sin(x)": +Color 8: ? "cos(x)": +Color 12: ? "tan(x)" +Line 0,ymax/2,xmax,ymax/2 +For i=0 to xmax + Pset i,ymax/2-sin(i*2*pi/ymax)*ymax/4 color 1 + Pset i,ymax/2-cos(i*2*pi/ymax)*ymax/4 color 8 + Pset i,ymax/2-tan(i*2*pi/ymax)*ymax/4 color 12 +Next +showpage + +REM SmallBASIC is great for experimenting with fractals and other interesting effects +Delay 3000 +Randomize +ff = 440.03 +For j = 0 to 20 + r = rnd * 1000 % 255 + b = rnd * 1000 % 255 + g = rnd * 1000 % 255 + c = rgb(r,b,g) + ff += 9.444 + for i=0 to 25000 + f += ff + x = min(xmax, -x + cos(f*i)) + y = min(ymax, -y + sin(f*i)) + pset x, y color c + if (i%1000==0) then + showpage + fi + next +Next j + +REM For computer historians, SmallBASIC can run programs +REM found in early computer books and magazines, for example: +10 LET A=9 +20 LET B=7 +30 PRINT A*B +40 PRINT A/B + +REM SmallBASIC also has support for a few modern concepts such as JSON +aa = array("{\"cat\":{\"name\":\"harry\"},\"pet\":\"true\"}") +If (ismap(aa) == false) Then + throw "not an map" +End If +Print aa + +PAUSE + +``` + +## Articles + +* [Getting started](http://smallbasic.sourceforge.net/?q=node/1573) +* [Welcome to SmallBASIC](http://smallbasic.sourceforge.net/?q=node/838) + +## GitHub + +* [Source code](https://github.com/smallbasic/SmallBASIC) +* [Reference snapshot](http://smallbasic.github.io/) + diff --git a/solidity.html.markdown b/solidity.html.markdown index a511bbb3..9bf5bf4d 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -8,7 +8,7 @@ contributors: Solidity lets you program on [Ethereum](https://www.ethereum.org/), a blockchain-based virtual machine that allows the creation and -execution of smart contracts, without needing centralized or trusted parties. +execution of smart contracts, without requiring centralized or trusted parties. Solidity is a statically typed, contract programming language that has similarities to Javascript and C. Like objects in OOP, each contract contains @@ -18,8 +18,17 @@ global variables. Some Ethereum contract examples include crowdfunding, voting, and blind auctions. +There is a high risk and high cost of errors in Solidity code, so you must be very careful to test +and slowly rollout. WITH THE RAPID CHANGES IN ETHEREUM, THIS DOCUMENT IS UNLIKELY TO STAY UP TO +DATE, SO YOU SHOULD FOLLOW THE SOLIDITY CHAT ROOM AND ETHEREUM BLOG FOR THE LATEST. ALL CODE HERE IS +PROVIDED AS IS, WITH SUBSTANTIAL RISK OF ERRORS OR DEPRECATED CODE PATTERNS. + +Unlike other code, you may also need to add in design patterns like pausing, deprecation, and +throttling usage to reduce risk. This document primarily discusses syntax, and so excludes many +popular design patterns. + As Solidity and Ethereum are under active development, experimental or beta -features are explicitly marked, and subject to change. Pull requests welcome. +features are typically marked, and subject to change. Pull requests welcome. ```javascript // First, a simple Bank contract @@ -40,6 +49,7 @@ contract SimpleBank { // CamelCase // Declare state variables outside function, persist through life of contract // dictionary that maps addresses to balances + // always be careful about overflow attacks with numbers mapping (address => uint) private balances; // "private" means that other contracts can't directly query balances @@ -49,7 +59,7 @@ contract SimpleBank { // CamelCase // 'public' makes externally readable (not writeable) by users or contracts // Events - publicize actions to external listeners - event DepositMade(address accountAddress, uint amount); + event LogDepositMade(address accountAddress, uint amount); // Constructor, can receive one or many variables here; only one allowed function AcmeBank() { @@ -65,7 +75,7 @@ contract SimpleBank { // CamelCase // no "this." or "self." required with state variable // all values set to data type's initial value by default - DepositMade(msg.sender, msg.value); // fire event + LogDepositMade(msg.sender, msg.value); // fire event return balances[msg.sender]; } @@ -76,11 +86,14 @@ contract SimpleBank { // CamelCase /// @return The balance remaining for the user function withdraw(uint withdrawAmount) public returns (uint remainingBal) { if(balances[msg.sender] >= withdrawAmount) { + // Note the way we deduct the balance right away, before sending - due to + // the risk of a recursive call that allows the caller to request an amount greater + // than their balance balances[msg.sender] -= withdrawAmount; if (!msg.sender.send(withdrawAmount)) { - // to be safe, may be sending to contract that - // has overridden 'send' which may then fail + // increment back only on fail, as may be sending to contract that + // has overridden 'send' on the receipt end balances[msg.sender] += withdrawAmount; } } @@ -150,8 +163,10 @@ address public owner; // All addresses can be sent ether owner.send(SOME_BALANCE); // returns false on failure -if (owner.send) {} // typically wrap in 'if', as contract addresses have -// functions have executed on send and can fail +if (owner.send) {} // REMEMBER: wrap in 'if', as contract addresses have +// functions executed on send and these can fail +// Also, make sure to deduct balances BEFORE attempting a send, as there is a risk of a recursive +// call that can drain the contract // can override send by defining your own @@ -351,8 +366,11 @@ function b() { // access events from outside blockchain (with lightweight clients) // typically declare after contract parameters +// Typically, capitalized - and add Log in front to be explicit and prevent confusion +// with a function call + // Declare -event Sent(address from, address to, uint amount); // note capital first letter +event LogSent(address indexed from, address indexed to, uint amount); // note capital first letter // Call Sent(from, to, amount); @@ -396,7 +414,10 @@ onlyIfState(State.A) modifier checkValue(uint amount) { _ if (msg.value > amount) { - msg.sender.send(amount - msg.value); + uint amountToRefund = amount - msg.value; + if (!msg.sender.send(amountToRefund)) { + throw; + } } } @@ -409,6 +430,21 @@ modifier checkValue(uint amount) { // Syntax same as javascript, but no type conversion from non-boolean // to boolean (comparison operators must be used to get the boolean val) +// For loops that are determined by user behavior, be careful - as contracts have a maximal +// amount of gas for a block of code - and will fail if that is exceeded +// For example: +for(uint x = 0; x < refundAddressList.length; x++) { + if (!refundAddressList[x].send(SOME_AMOUNT)) { + throw; + } +} + +// Two errors above: +// 1. A failure on send stops the loop from completing, tying up money +// 2. This loop could be arbitrarily long (based on the amount of users who need refunds), and +// therefore may always fail as it exceeds the max gas for a block +// Instead, you should let people withdraw individually from their subaccount, and mark withdrawn + // 7. OBJECTS/CONTRACTS @@ -587,13 +623,13 @@ contract CrowdFunder { address public fundRecipient; // creator may be different than recipient uint public minimumToRaise; // required to tip, else everyone gets refund string campaignUrl; + byte constant version = 1; // Data structures enum State { Fundraising, - ExpiredRefundPending, - Successful, - ExpiredRefundComplete + ExpiredRefund, + Successful } struct Contribution { uint amount; @@ -604,11 +640,11 @@ contract CrowdFunder { State public state = State.Fundraising; // initialize on create uint public totalRaised; uint public raiseBy; + uint public completeAt; Contribution[] contributions; - event fundingReceived(address addr, uint amount, uint currentTotal); - event allRefundsSent(); - event winnerPaid(address winnerAddress); + event LogFundingReceived(address addr, uint amount, uint currentTotal); + event LogWinnerPaid(address winnerAddress); modifier inState(State _state) { if (state != _state) throw; @@ -620,10 +656,13 @@ contract CrowdFunder { _ } + // Wait 6 months after final contract state before allowing contract destruction modifier atEndOfLifecycle() { - if(state != State.ExpiredRefundComplete && state != State.Successful) { + if(!((state == State.ExpiredRefund || state == State.Successful) && + completeAt + 6 months < now)) { throw; } + _ } function CrowdFunder( @@ -651,9 +690,10 @@ contract CrowdFunder { ); totalRaised += msg.value; - fundingReceived(msg.sender, msg.value, totalRaised); + LogFundingReceived(msg.sender, msg.value, totalRaised); checkIfFundingCompleteOrExpired(); + return contributions.length - 1; // return id } function checkIfFundingCompleteOrExpired() { @@ -663,9 +703,9 @@ contract CrowdFunder { // could incentivize sender who initiated state change here } else if ( now > raiseBy ) { - state = State.ExpiredRefundPending; - refundAll(); + state = State.ExpiredRefund; // backers can now collect refunds by calling getRefund(id) } + completeAt = now; } function payOut() @@ -676,22 +716,27 @@ contract CrowdFunder { throw; } - winnerPaid(fundRecipient); + + LogWinnerPaid(fundRecipient); } - function refundAll() + function getRefund(id) public - inState(State.ExpiredRefundPending) + inState(State.ExpiredRefund) { - uint length = contributions.length; - for (uint i = 0; i < length; i++) { - if(!contributions[i].contributor.send(contributions[i].amount)) { - throw; - } + if (contributions.length <= id || id < 0 || contributions[id].amount == 0 ) { + throw; + } + + uint amountToRefund = contributions[id].amount; + contributions[id].amount = 0; + + if(!contributions[id].contributor.send(amountToSend)) { + contributions[id].amount = amountToSend; + return false; } - allRefundsSent(); - state = State.ExpiredRefundComplete; + return true; } function removeContract() @@ -700,13 +745,13 @@ contract CrowdFunder { atEndOfLifecycle() { selfdestruct(msg.sender); + // creator gets all money that hasn't be claimed } function () { throw; } } // ** END EXAMPLE ** - // 10. OTHER NATIVE FUNCTIONS // Currency units @@ -732,8 +777,14 @@ sha3("ab", "cd"); ripemd160("abc"); sha256("def"); +// 11. SECURITY + +// Bugs can be disastrous in Ethereum contracts - and even popular patterns in Solidity, +// may be found to be antipatterns -// 11. LOW LEVEL FUNCTIONS +// See security links at the end of this doc + +// 12. LOW LEVEL FUNCTIONS // call - low level, not often used, does not provide type safety successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2'); @@ -742,7 +793,7 @@ successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2'); someContractAddress.callcode('function_name'); -// 12. STYLE NOTES +// 13. STYLE NOTES // Based on Python's PEP8 style guide // Quick summary: @@ -753,7 +804,7 @@ someContractAddress.callcode('function_name'); // else should be placed on own line -// 13. NATSPEC COMENTS +// 14. NATSPEC COMENTS // used for documentation, commenting, and external UIs // Contract natspec - always above contract definition @@ -773,9 +824,8 @@ someContractAddress.callcode('function_name'); - [Solidity Docs](https://solidity.readthedocs.org/en/latest/) - [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. - [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) -- [Gitter Chat room](https://gitter.im/ethereum/solidity) +- [Gitter Solidity Chat room](https://gitter.im/ethereum/solidity) - [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/) -- Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc)) ## Sample contracts - [Dapp Bin](https://github.com/ethereum/dapp-bin) @@ -783,13 +833,24 @@ someContractAddress.callcode('function_name'); - [ConsenSys Contracts](https://github.com/ConsenSys/dapp-store-contracts) - [State of Dapps](http://dapps.ethercasts.com/) +## Security +- [Thinking About Smart Contract Security](https://blog.ethereum.org/2016/06/19/thinking-smart-contract-security/) +- [Smart Contract Security](https://blog.ethereum.org/2016/06/10/smart-contract-security/) +- [Hacking Distributed Blog](http://hackingdistributed.com/) + ## Information purposefully excluded - Libraries ## Style - Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy +## Editors +- [Vim Solidity](https://github.com/tomlion/vim-solidity) +- Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc)) + ## Future To Dos - New keywords: protected, inheritable +- List of common design patterns (throttling, RNG, version upgrade) +- Common security anti patterns Feel free to send a pull request with any edits - or email nemild -/at-/ gmail diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index 143980e7..133e4f54 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -24,6 +24,12 @@ val phone_no = 5551337 val pi = 3.14159 val negative_number = ~15 (* Yeah, unary minus uses the 'tilde' symbol *) +(* Optionally, you can explicitly declare types. This is not necessary as + ML will automatically figure out the types of your values. *) +val diameter = 7926 : int +val e = 2.718 : real +val name = "Bobby" : string + (* And just as importantly, functions: *) fun is_large(x : int) = if x > 37 then true else false @@ -31,6 +37,8 @@ fun is_large(x : int) = if x > 37 then true else false val tau = 2.0 * pi (* You can multiply two reals *) val twice_rent = 2 * rent (* You can multiply two ints *) (* val meh = 1.25 * 10 *) (* But you can't multiply an int and a real *) +val yeh = 1.25 * (Real.fromInt 10) (* ...unless you explicitly convert + one or the other *) (* +, - and * are overloaded so they work for both int and real. *) (* The same cannot be said for division which has separate operators: *) diff --git a/tcl.html.markdown b/tcl.html.markdown index 4ff1d3cc..9118081d 100644 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -253,7 +253,7 @@ proc greet {greeting name} { # As noted earlier, braces do not construct a code block. Every value, even # the third argument of the "proc" command, is a string. The previous command # rewritten to not use braces at all: -proc greet greeting\ name return\ \"Hello,\ \$name! +proc greet greeting\ name return\ \"\$greeting,\ \$name!\" diff --git a/tmux.html.markdown b/tmux.html.markdown index c9e3db6b..ae73d912 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -122,10 +122,6 @@ like how .vimrc or init.el are used. ### General ########################################################################### -# Enable UTF-8 -setw -g utf8 on -set-option -g status-utf8 on - # Scrollback/History limit set -g history-limit 2048 diff --git a/typescript.html.markdown b/typescript.html.markdown index 21f1ce7d..1d712369 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -9,7 +9,7 @@ TypeScript is a language that aims at easing development of large scale applicat TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emits JavaScript. -This article will focus only on TypeScript extra syntax, as opposed to [JavaScript] (../javascript/). +This article will focus only on TypeScript extra syntax, as opposed to [JavaScript](javascript.html.markdown). To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the emitted JavaScript. diff --git a/zh-cn/kotlin-cn.html.markdown b/zh-cn/kotlin-cn.html.markdown new file mode 100644 index 00000000..1fd12f5b --- /dev/null +++ b/zh-cn/kotlin-cn.html.markdown @@ -0,0 +1,346 @@ +--- +language: kotlin +contributors: + - ["S Webber", "https://github.com/s-webber"] +translators: + - ["Jimin Lu", "https://github.com/lujimin"] +filename: LearnKotlin-cn.kt +lang: zh-cn +--- + +Kotlin是一门适用于JVM、Android和浏览器的静态类型编程语言。它100%兼容Java。 +[了解更多。](https://kotlinlang.org/) + +```java +// 单行注释从 // 开始 +/* +多行注释看起来像这样。 +*/ + +// "package" 关键字的工作方式与Java相同。 +package com.learnxinyminutes.kotlin + +/* +Kotlin程序的入口点是一个"main"函数 +该函数传递一个包含任何命令行参数的数组。 +*/ +fun main(args: Array<String>) { + /* + 使用"var"或"val"来声明一个值。 + "val"声明的值不能被重新赋值,而"var"声明的值可以。 + */ + val fooVal = 10 // 以后我们不能再次给fooVal赋值 + var fooVar = 10 + fooVar = 20 // fooVar可以被再次赋值 + + /* + 在大多数情况下,Kotlin可以确定变量的类型是什么, + 所以我们不必要每次都去明确指定它。 + 我们可以像这样明确地声明一个变量的类型: + */ + val foo : Int = 7 + + /* + 可以采取和Java类似的方法来表示一个字符串。 + 用反斜杠来转义字符。 + */ + val fooString = "My String Is Here!"; + val barString = "Printing on a new line?\nNo Problem!"; + val bazString = "Do you want to add a tab?\tNo Problem!"; + println(fooString); + println(barString); + println(bazString); + + /* + 原始字符串用三重引号(""")来定义。 + 原始字符串可以包含换行符以及其他任何字符。 + */ + val fooRawString = """ +fun helloWorld(val name : String) { + println("Hello, world!") +} +""" + println(fooRawString) + + /* + 字符串可以包含模板表达式。 + 模板表达式从一个美元符号($)开始。 + */ + val fooTemplateString = "$fooString has ${fooString.length} characters" + println(fooTemplateString) + + /* + 当某个变量的值可以为 null 的时候,我们必须被明确指定它是可为空的。 + 在变量声明处的类型后面加上?来标识它是可为空的。 + 我们可以用?.操作符来访问可为空的变量。 + 我们可以用?:操作符来指定一个在变量为空时使用的替代值。 + */ + var fooNullable: String? = "abc" + println(fooNullable?.length) // => 3 + println(fooNullable?.length ?: -1) // => 3 + fooNullable = null + println(fooNullable?.length) // => null + println(fooNullable?.length ?: -1) // => -1 + + /* + 使用"fun"关键字来声明一个函数。 + 函数的参数在函数名后面的括号内指定。 + 函数的参数可以设定一个默认值。 + 如果需要的话,函数的返回值类型可以在参数后面指定。 + */ + fun hello(name: String = "world") : String { + return "Hello, $name!" + } + println(hello("foo")) // => Hello, foo! + println(hello(name = "bar")) // => Hello, bar! + println(hello()) // => Hello, world! + + /* + 用"vararg"关键字来修饰一个函数的参数来允许可变参数传递给该函数 + */ + fun varargExample(vararg names: Int) { + println("Argument has ${names.size} elements") + } + varargExample() // => Argument has 0 elements + varargExample(1) // => Argument has 1 elements + varargExample(1, 2, 3) // => Argument has 3 elements + + /* + 当函数只包含一个单独的表达式时,大括号可以被省略。 + 函数体可以被指定在一个=符号后面。 + */ + fun odd(x: Int): Boolean = x % 2 == 1 + println(odd(6)) // => false + println(odd(7)) // => true + + // 如果返回值类型可以被推断,那么我们不需要指定它。 + fun even(x: Int) = x % 2 == 0 + println(even(6)) // => true + println(even(7)) // => false + + // 函数可以用函数作为参数并且可以返回函数。 + fun not(f: (Int) -> Boolean) : (Int) -> Boolean { + return {n -> !f.invoke(n)} + } + // 命名函数可以用::运算符被指定为参数。 + val notOdd = not(::odd) + val notEven = not(::even) + // 匿名函数可以被指定为参数。 + val notZero = not {n -> n == 0} + /* + 如果一个匿名函数只有一个参数 + 那么它的声明可以被省略(连同->)。 + 这个参数的名字是"it"。 + */ + val notPositive = not {it > 0} + for (i in 0..4) { + println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}") + } + + // "class"关键字用来声明类。 + class ExampleClass(val x: Int) { + fun memberFunction(y: Int) : Int { + return x + y + } + + infix fun infixMemberFunction(y: Int) : Int { + return x * y + } + } + /* + 我们调用构造方法来创建一个新的实例。 + 注意,Kotlin没有"new"关键字。 + */ + val fooExampleClass = ExampleClass(7) + // 可以使用一个点号来调用成员函数。 + println(fooExampleClass.memberFunction(4)) // => 11 + /* + 如果使用"infix"关键字来标记一个函数 + 那么可以使用中缀表示法来调用该函数。 + */ + println(fooExampleClass infixMemberFunction 4) // => 28 + + /* + 数据类是创建只包含数据的类的一个简洁的方法。 + "hashCode"、"equals"和"toString"方法将被自动生成。 + */ + data class DataClassExample (val x: Int, val y: Int, val z: Int) + val fooData = DataClassExample(1, 2, 4) + println(fooData) // => DataClassExample(x=1, y=2, z=4) + + // 数据类有一个"copy"函数 + val fooCopy = fooData.copy(y = 100) + println(fooCopy) // => DataClassExample(x=1, y=100, z=4) + + // 对象可以被解构成为多个变量 + val (a, b, c) = fooCopy + println("$a $b $c") // => 1 100 4 + + // "with"函数类似于JavaScript中的"with"用法。 + data class MutableDataClassExample (var x: Int, var y: Int, var z: Int) + val fooMutableDate = MutableDataClassExample(7, 4, 9) + with (fooMutableDate) { + x -= 2 + y += 2 + z-- + } + println(fooMutableDate) // => MutableDataClassExample(x=5, y=6, z=8) + + /* + 我们可以使用"listOf"函数来创建一个list。 + 这个list是不可变的 - 元素不可以被添加或删除。 + */ + val fooList = listOf("a", "b", "c") + println(fooList.size) // => 3 + println(fooList.first()) // => a + println(fooList.last()) // => c + // 可以通过索引来访问list中的元素。 + println(fooList[1]) // => b + + // 可以使用"mutableListOf"函数来创建一个可变的list。 + val fooMutableList = mutableListOf("a", "b", "c") + fooMutableList.add("d") + println(fooMutableList.last()) // => d + println(fooMutableList.size) // => 4 + + // 我们可以使用"setOf"函数来创建一个set。 + val fooSet = setOf("a", "b", "c") + println(fooSet.contains("a")) // => true + println(fooSet.contains("z")) // => false + + // 我们可以使用"mapOf"函数来创建一个map。 + val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9) + // 可以通过键来访问map中的值。 + println(fooMap["a"]) // => 8 + + /* + 序列表示惰性求值集合。 + 我们可以使用"generateSequence"函数来创建一个序列。 + */ + val fooSequence = generateSequence(1, {it + 1}) + val x = fooSequence.take(10).toList() + println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + + // 一个用序列来生成斐波那契数列的例子。 + fun fibonacciSequence() : Sequence<Long> { + var a = 0L + var b = 1L + + fun next() : Long { + val result = a + b + a = b + b = result + return a + } + + return generateSequence(::next) + } + val y = fibonacciSequence().take(10).toList() + println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] + + // Kotlin为集合提供高阶函数。 + val z = (1..9).map {it * 3} + .filter {it < 20} + .groupBy {it % 2 == 0} + .mapKeys {if (it.key) "even" else "odd"} + println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]} + + // 任何提供迭代器的都可以使用"for"循环。 + for (c in "hello") { + println(c) + } + + // "while"循环的用法和其他语言一样。 + var ctr = 0 + while (ctr < 5) { + println(ctr) + ctr++ + } + do { + println(ctr) + ctr++ + } while (ctr < 10) + + // "when"可以用来替代"if-else if"链。 + val i = 10 + when { + i < 7 -> println("first block") + fooString.startsWith("hello") -> println("second block") + else -> println("else block") + } + + // "when"可以带参数。 + when (i) { + 0, 21 -> println("0 or 21") + in 1..20 -> println("in the range 1 to 20") + else -> println("none of the above") + } + + // "when"可以作为一个函数,提供返回值。 + var result = when (i) { + 0, 21 -> "0 or 21" + in 1..20 -> "in the range 1 to 20" + else -> "none of the above" + } + println(result) + + /* + 我们可以通过使用"is"操作符来检查一个对象是否是某个类型的。 + 如果对象通过了类型检查那么它可以作为该类型使用而不需要强制转换它。 + */ + fun smartCastExample(x: Any) : Boolean { + if (x is Boolean) { + // x自动转换为Boolean + return x + } else if (x is Int) { + // x自动转换为Int + return x > 0 + } else if (x is String) { + // x自动转换为String + return x.isNotEmpty() + } else { + return false + } + } + println(smartCastExample("Hello, world!")) // => true + println(smartCastExample("")) // => false + println(smartCastExample(5)) // => true + println(smartCastExample(0)) // => false + println(smartCastExample(true)) // => true + + /* + 扩展是用来给一个类添加新的功能的。 + 它类似于C#的扩展方法。 + */ + fun String.remove(c: Char): String { + return this.filter {it != c} + } + println("Hello, world!".remove('l')) // => Heo, word! + + println(EnumExample.A) // => A + println(ObjectExample.hello()) // => hello +} + +// 枚举类和Java的枚举类型类似。 +enum class EnumExample { + A, B, C +} + +/* +"object"关键字用来创建单例对象。 +我们不能把它赋给一个变量,但我们可以通过它的名字引用它。 +这类似于Scala的单例对象。 +*/ +object ObjectExample { + fun hello() : String { + return "hello" + } +} + +``` + +### 进一步阅读 + +* [Kotlin教程](https://kotlinlang.org/docs/tutorials/) +* [在您的浏览器中使用Kotlin](http://try.kotlinlang.org/) +* [Kotlin资源列表](http://kotlin.link/) diff --git a/zh-cn/zfs-cn.html.markdown b/zh-cn/zfs-cn.html.markdown new file mode 100644 index 00000000..fdf5277e --- /dev/null +++ b/zh-cn/zfs-cn.html.markdown @@ -0,0 +1,397 @@ +--- +category: tool +tool: zfs +contributors: + - ["sarlalian", "http://github.com/sarlalian"] +translators: + - ["Alan Cheng", "https://github.com/kedaio"] +filename: LearnZfs-cn.txt +lang: zh-cn +--- + +[ZFS](http://open-zfs.org/wiki/Main_Page) +是重新思考与储存相关技术的结果,它把传统的文件系统和卷管理器集成到一个工具当中. +ZFS不但有把它和传统存储系统分开来的特有术语,也有很多聚焦于可用性的功能。 + + +## ZFS概念 + +### 虚拟设备(Virtual Devices,VDEV) + +对于操作系统来说,VDEV和传统的RAID阵列卡所呈现的raid设备类似。VDEV有几种不同的类型,每种类型 +都有自己的优势,包括冗余和速度。一般来说,VDEV的可靠性和安全性比阵列卡要好。因此使用ZFS时不 +建议使用阵列卡。让ZFS直接管理磁盘。 + +VDEV的类型 +* stripe (条带。单个磁盘,没有冗余) +* mirror (镜像。支持n-way镜像) +* raidz + * raidz1 (一个奇偶校验磁盘, 类似于RAID 5) + * raidz2 (两个奇偶校验磁盘, 类似于RAID 6) + * raidz3 (三个奇偶校验磁盘, 没有类似RAID等级) +* disk (磁盘) +* file (文件。不推荐在生产环境中使用,因为中间又多了一层不必要的文件系统) + +数据会以条带方式存储于存储池中的所有VDEV上。因此一个存储池中的VDEV越多,IOPS就越高。 + +### storage pool (存储池) + +ZFS 使用存储池来作为底层存储提供者(VDEV)的抽象。这样可以把用户可见的文件系统和底层的物理磁盘 +布局分离开来。 + +### ZFS 数据集(Dataset) + +ZFS 数据集类似于传统的文件系统(译者注:或者说是目录),但是提供了更多的功能。ZFS的很多优势也是 +在这一层体现出来的。数据集支持 [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write) +快照, 配额, 压缩和重复消除(de-duplication). + + +### 限制 + +一个目录最多可包含 2^48个文件, 每个文件最大可以是16 exabytes. 一个存储池最大可包含256 zettabytes 、 +(2^78) 的空间, 可以条带化地分布于2^64 设备上. 单一主机最多可以创建2^64个存储池。这些限制可以说是相 +当大。 + + +## 命令 + +### 存储池 + +Actions: (存储池操作) +* List (列举) +* Status (查看状态) +* Destroy (删除) +* Get/Set properties (获取/设置属性) + +List zpools (列举存储池(也叫zpool)) + +```bash +# 创建一个raidz类型的存储池(名称为bucket) +$ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 + +# 列出所有存储池 +$ zpool list +NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT +zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - + +# 列出某一存储池的详细信息 +$ zpool list -v zroot +NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT +zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 141G 106G 35.2G - 43% 75% +``` + +Status of zpools (存储池状态) + +```bash +# 获取全部zpool状态信息 +$ 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 + +# 用scrub来更正存储池错误信息 +$ 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 + +# 获取某一存储池的全部属性。属性可能是系统提供,也可能是用户设置 +$ zpool get all zroot +NAME PROPERTY VALUE SOURCE +zroot size 141G - +zroot capacity 75% - +zroot altroot - default +zroot health ONLINE - +... + +# 设置存储池属性,下例这是设置comment(备注)属性 +$ 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 +# 创建数据集 +$ zfs create tank/root/data +$ mount | grep data +tank/root/data on /data (zfs, local, nfsv4acls) + +# 创建子数据集 +$ 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) + + +# 创建卷 +$ 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 +# 列出所有数据集 +$ zfs list +NAME USED AVAIL REFER MOUNTPOINT +zroot 106G 30.8G 144K none +zroot/ROOT 18.5G 30.8G 144K none +zroot/ROOT/10.1 8K 30.8G 9.63G / +zroot/ROOT/default 18.5G 30.8G 11.2G / +zroot/backup 5.23G 30.8G 144K none +zroot/home 288K 30.8G 144K none +... + +# 列举某一数据集的信息 +$ zfs list zroot/home +NAME USED AVAIL REFER MOUNTPOINT +zroot/home 288K 30.8G 144K none + +# 列出快照 +$ zfs list -t snapshot +zroot@daily-2015-10-15 0 - 144K - +zroot/ROOT@daily-2015-10-15 0 - 144K - +zroot/ROOT/default@daily-2015-10-15 0 - 24.2G - +zroot/tmp@daily-2015-10-15 124K - 708M - +zroot/usr@daily-2015-10-15 0 - 144K - +zroot/home@daily-2015-10-15 0 - 11.9G - +zroot/var@daily-2015-10-15 704K - 1.42G - +zroot/var/log@daily-2015-10-15 192K - 828K - +zroot/var/tmp@daily-2015-10-15 0 - 152K - +``` + +Rename datasets (重命名数据集) + +```bash +$ zfs rename tank/root/home tank/root/old_home +$ zfs rename tank/root/new_home tank/root/home +``` + +Delete dataset (删除数据集) + +```bash +# 数据集如果有快照则无法删除 +zfs destroy tank/root/home +``` + +Get / set properties of a dataset (获取/设置数据集属性) + +```bash +# 获取数据集全部属性 +$ 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 - +... + +# 获取数据集属性 +$ zfs get compression zroot/usr/home +NAME PROPERTY VALUE SOURCE +zroot/home compression off default + +# 设置数据集属性(下例为设置压缩属性compression) +$ zfs set compression=gzip-9 mypool/lamb + +# 列举所有数据集的名称、配额和预留属性 +$ zfs list -o name,quota,reservation +NAME QUOTA RESERV +zroot none none +zroot/ROOT none none +zroot/ROOT/default none none +zroot/tmp none none +zroot/usr none none +zroot/home none none +zroot/var none none +... +``` + + +### Snapshots (快照) + +快照是ZFS 的一个非常重要的功能 + +* 快照占用的空间等于它和原始数据的差异量 +* 创建时间以秒计 +* 恢复时间和写入速度相同 +* 易于自动化 + +Actions: (快照相关操作) +* Create (创建) +* Delete (删除) +* Rename (重命名) +* Access snapshots (访问) +* Send / Receive (发送/接收) +* Clone (克隆。译者注:关于clone和快照的区别可参看[这里](http://docs.oracle.com/cd/E19253-01/819-5461/gbcxz/index.html)) + + +Create snapshots (创建快照) + +```bash +# 为单一数据集创建快照 +zfs snapshot tank/home/sarlalian@now + +# 为数据集及其子集创建快照 +$ 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 +# 如何删除快照 +$ zfs destroy tank/home/sarlalian@now + +# 删除某一数据集及其子集的快照 +$ zfs destroy -r tank/home/sarlalian@now + +``` + +Renaming Snapshots (重命名) + +```bash +# 重命名快照 +$ 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进入一个快照目录 +$ cd /home/.zfs/snapshot/ +``` + +Sending and Receiving + +```bash +# 备份快照到一个文件 +$ zfs send tank/home/sarlalian@now | gzip > backup_file.gz + +# 发送快照到另一个数据集 +$ zfs send tank/home/sarlalian@now | zfs recv backups/home/sarlalian + +# 发送快照到一个远程主机 +$ zfs send tank/home/sarlalian@now | ssh root@backup_server 'zfs recv tank/home/sarlalian' + +# 发送完整数据集及其快照到一个新主机 +$ zfs send -v -R tank/home@now | ssh root@backup_server 'zfs recv tank/home' +``` + +Cloneing Snapshots (克隆快照) + +```bash +# 克隆一个快照 +$ zfs clone tank/home/sarlalian@now tank/home/sarlalian_new + +# 提升克隆,让它不再依赖原始快照 +$ zfs promote tank/home/sarlalian_new +``` + +### 汇总 + +下面这个脚本使用了FreeBSD, jails和ZFS,来自动在一个mysql群集的热备主机上为一个mysq staging数据库 +创建一份纯净的拷贝。 + +```bash +#!/bin/sh + +echo "==== Stopping the staging database server ====" +jail -r staging + +echo "==== Cleaning up existing staging server and snapshot ====" +zfs destroy -r zroot/jails/staging +zfs destroy zroot/jails/slave@staging + +echo "==== Quiescing the slave database ====" +echo "FLUSH TABLES WITH READ LOCK;" | /usr/local/bin/mysql -u root -pmyrootpassword -h slave + +echo "==== Snapshotting the slave db filesystem as zroot/jails/slave@staging ====" +zfs snapshot zroot/jails/slave@staging + +echo "==== Starting the slave database server ====" +jail -c slave + +echo "==== Cloning the slave snapshot to the staging server ====" +zfs clone zroot/jails/slave@staging zroot/jails/staging + +echo "==== Installing the staging mysql config ====" +mv /jails/staging/usr/local/etc/my.cnf /jails/staging/usr/local/etc/my.cnf.slave +cp /jails/staging/usr/local/etc/my.cnf.staging /jails/staging/usr/local/etc/my.cnf + +echo "==== Setting up the staging rc.conf file ====" +mv /jails/staging/etc/rc.conf.local /jails/staging/etc/rc.conf.slave +mv /jails/staging/etc/rc.conf.staging /jails/staging/etc/rc.conf.local + +echo "==== Starting the staging db server ====" +jail -c staging + +echo "==== Makes the staging database not pull from the master ====" +echo "STOP SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging +echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging +``` + + +### 延伸阅读 + +* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) +* [FreeBSD Handbook on ZFS](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/zfs.html) +* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) +* [Oracle's Tuning Guide](http://www.oracle.com/technetwork/articles/servers-storage-admin/sto-recommended-zfs-settings-1951715.html) +* [OpenZFS Tuning Guide](http://open-zfs.org/wiki/Performance_tuning) +* [FreeBSD ZFS Tuning Guide](https://wiki.freebsd.org/ZFSTuningGuide) |