diff options
55 files changed, 5720 insertions, 478 deletions
diff --git a/README.markdown b/README.markdown index 28fa5093..94afbcbe 100644 --- a/README.markdown +++ b/README.markdown @@ -8,7 +8,7 @@ commented code and explained as they go. ... to write more inline code tutorials. Just grab an existing file from this repo and copy the formatting (don't worry, it's all very simple). -Make a new file, send a pull request, and if it passes master I'll get it up pronto. +Make a new file, send a pull request, and if it passes muster I'll get it up pronto. Remember to fill in the "contributors" fields so you get credited properly! @@ -18,7 +18,7 @@ All contributions are welcome, from the tiniest typo to a brand new article. Tra in all languages are welcome (or, for that matter, original articles in any language). Send a pull request or open an issue any time of day or night. -**Please tag your issues pull requests with [language/lang-code] at the beginning** +**Please tag your issues and pull requests with [language/lang-code] at the beginning** **(e.g. [python/en] for English Python).** This will help everyone pick out things they care about. diff --git a/bash.html.markdown b/bash.html.markdown index 191f916a..211d2944 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -90,17 +90,26 @@ else echo "Your name is your username" fi +# NOTE: if $Name is empty, bash sees the above condition as: +if [ -ne $USER ] +# which is invalid syntax +# so the "safe" way to use potentially empty variables in bash is: +if [ "$Name" -ne $USER ] ... +# which, when $Name is empty, is seen by bash as: +if [ "" -ne $USER ] ... +# which works as expected + # There is also conditional execution echo "Always executed" || echo "Only executed if first command fails" echo "Always executed" && echo "Only executed if first command does NOT fail" # To use && and || with if statements, you need multiple pairs of square brackets: -if [ $Name == "Steve" ] && [ $Age -eq 15 ] +if [ "$Name" == "Steve" ] && [ "$Age" -eq 15 ] then echo "This will run if $Name is Steve AND $Age is 15." fi -if [ $Name == "Daniya" ] || [ $Name == "Zach" ] +if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ] then echo "This will run if $Name is Daniya OR Zach." fi diff --git a/c++.html.markdown b/c++.html.markdown index 2bee51dc..d03092e5 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -310,6 +310,70 @@ basic_string(basic_string&& other); // constructor that "salvages" parts of that temporary string. You will see this // concept referred to as "move semantics". +///////////////////// +// Enums +///////////////////// + +// Enums are a way to assign a value to a constant most commonly used for +// easier visualization and reading of code +enum ECarTypes +{ + Sedan, + Hatchback, + SUV, + Wagon +}; + +ECarTypes GetPreferredCarType() +{ + return ECarTypes::Hatchback; +} + +// As of C++11 there is an easy way to assign a type to the enum which can be +// useful in serialization of data and converting enums back-and-forth between +// the desired type and their respective constants +enum ECarTypes : uint8_t +{ + Sedan, // 0 + Hatchback, // 1 + SUV = 254, // 254 + Hybrid // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Serialize the InputValue to a file +} + +void WritePreferredCarTypeToFile(ECarTypes InputCarType) +{ + // The enum is implicitly converted to a uint8_t due to its declared enum type + WriteByteToFile(InputCarType); +} + +// On the other hand you may not want enums to be accidentally cast to an integer +// type or to other enums so it is instead possible to create an enum class which +// won't be implicitly converted +enum class ECarTypes : uint8_t +{ + Sedan, // 0 + Hatchback, // 1 + SUV = 254, // 254 + Hybrid // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Serialize the InputValue to a file +} + +void WritePreferredCarTypeToFile(ECarTypes InputCarType) +{ + // Won't compile even though ECarTypes is a uint8_t due to the enum + // being declared as an "enum class"! + WriteByteToFile(InputCarType); +} + ////////////////////////////////////////// // Classes and object-oriented programming ////////////////////////////////////////// diff --git a/c.html.markdown b/c.html.markdown index 3339032f..a8f71057 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -6,8 +6,8 @@ contributors: - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"] - ["Marco Scannadinari", "https://marcoms.github.io"] + - ["Zachary Ferguson", "https://github.io/zfergus2"] - ["himanshu", "https://github.com/himanshu81494"] - --- Ah, C. Still **the** language of modern high-performance computing. @@ -54,6 +54,8 @@ int function_2(void); // Must declare a 'function prototype' before main() when functions occur after // your main() function. int add_two_ints(int x1, int x2); // function prototype +// although `int add_two_ints(int, int);` is also valid (no need to name the args), +// it is recommended to name arguments in the prototype as well for easier inspection // Your program's entry point is a function called // main with an integer return type. @@ -74,6 +76,9 @@ int main (int argc, char** argv) /////////////////////////////////////// // Types /////////////////////////////////////// + + // All variables MUST be declared at the top of the current block scope + // we declare them dynamically along the code for the sake of the tutorial // ints are usually 4 bytes int x_int = 0; @@ -232,7 +237,7 @@ int main (int argc, char** argv) 0 || 1; // => 1 (Logical or) 0 || 0; // => 0 - // Conditional expression ( ? : ) + // Conditional ternary expression ( ? : ) int e = 5; int f = 10; int z; @@ -302,6 +307,8 @@ int main (int argc, char** argv) for (i = 0; i <= 5; i++) { ; // use semicolon to act as the body (null statement) } + // Or + for (i = 0; i <= 5; i++); // branching with multiple choices: switch() switch (a) { @@ -678,8 +685,56 @@ typedef void (*my_fnp_type)(char *); // , | left to right // //---------------------------------------------------// -``` +/******************************* Header Files ********************************** + +Header files are an important part of c as they allow for the connection of c +source files and can simplify code and definitions by seperating them into +seperate files. + +Header files are syntaxtically similar to c source files but reside in ".h" +files. They can be included in your c source file by using the precompiler +command #include "example.h", given that example.h exists in the same directory +as the c file. +*/ + +/* A safe guard to prevent the header from being defined too many times. This */ +/* happens in the case of circle dependency, the contents of the header is */ +/* already defined. */ +#ifndef EXAMPLE_H /* if EXAMPLE_H is not yet defined. */ +#define EXAMPLE_H /* Define the macro EXAMPLE_H. */ + +/* Other headers can be included in headers and therefore transitively */ +/* included into files that include this header. */ +#include <string.h> +/* Like c source files macros can be defined in headers and used in files */ +/* that include this header file. */ +#define EXAMPLE_NAME "Dennis Ritchie" +/* Function macros can also be defined. */ +#define ADD(a, b) (a + b) + +/* Structs and typedefs can be used for consistency between files. */ +typedef struct node +{ + int val; + struct node *next; +} Node; + +/* So can enumerations. */ +enum traffic_light_state {GREEN, YELLOW, RED}; + +/* Function prototypes can also be defined here for use in multiple files, */ +/* but it is bad practice to define the function in the header. Definitions */ +/* should instead be put in a c file. */ +Node createLinkedList(int *vals, int len); + +/* Beyond the above elements, other definitions should be left to a c source */ +/* file. Excessive includeds or definitions should, also not be contained in */ +/* a header file but instead put into separate headers or a c file. */ + +#endif /* End of the if precompiler directive. */ + +``` ## Further Reading Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language) diff --git a/clojure.html.markdown b/clojure.html.markdown index a125d18f..58e835c9 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -264,6 +264,31 @@ keymap ; => {:a 1, :b 2, :c 3} (print "Saying hello to " name) (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") + +; Use the threading macros (-> and ->>) to express transformations of +; data more clearly. + +; The "Thread-first" macro (->) inserts into each form the result of +; the previous, as the first argument (second item) +(-> + {:a 1 :b 2} + (assoc :c 3) ;=> (assoc {:a 1 :b 2} :c 3) + (dissoc :b)) ;=> (dissoc (assoc {:a 1 :b 2} :c 3) :b) + +; This expression could be written as: +; (dissoc (assoc {:a 1 :b 2} :c 3) :b) +; and evaluates to {:a 1 :c 3} + +; The double arrow does the same thing, but inserts the result of +; each line at the *end* of the form. This is useful for collection +; operations in particular: +(->> + (range 10) + (map inc) ;=> (map inc (range 10) + (filter odd?) ;=> (filter odd? (map inc (range 10)) + (into [])) ;=> (into [] (filter odd? (map inc (range 10))) + ; Result: [1 3 5 7 9] + ; Modules ;;;;;;;;;;;;;;; diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index 11c8a654..6d2fd1eb 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -48,7 +48,7 @@ Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit sta -5 // 3 # => -2 -5.0 // 3.0 # => -2.0 -# Pokud použiteje desetinné číslo, výsledek je jím také +# Pokud použijete desetinné číslo, výsledek je jím také 3 * 2.0 # => 6.0 # Modulo @@ -420,7 +420,7 @@ next(iterator) # Vyhodí StopIteration ## 4. Funkce #################################################### -# Pro vytvoření nové funkce použijte def +# Pro vytvoření nové funkce použijte klíčové slovo def def secist(x, y): print("x je {} a y je {}".format(x, y)) return x + y # Hodnoty se vrací pomocí return @@ -520,7 +520,7 @@ class Clovek(object): # podtržítka na začátku a na konci značí, že se jedná o atribut nebo # objekt využívaný Pythonem ke speciálním účelům, ale můžete sami # definovat jeho chování. Metody jako __init__, __str__, __repr__ - # a další se nazývají "magické metody". Nikdy nepoužívejte toto + # a další se nazývají "magické metody". Nikdy nepoužívejte toto # speciální pojmenování pro běžné metody. def __init__(self, jmeno): # Přiřazení parametru do atributu instance jmeno diff --git a/csharp.html.markdown b/csharp.html.markdown index 28da9fe5..31c0417e 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] - ["Wouter Van Schandevijl", "http://github.com/laoujin"] - ["Jo Pearce", "http://github.com/jdpearce"] + - ["Chris Zimmerman", "https://github.com/chriszimmerman"] filename: LearnCSharp.cs --- @@ -160,7 +161,7 @@ on a new line! ""Wow!"", the masses cried"; // List<datatype> <var name> = new List<datatype>(); List<int> intList = new List<int>(); List<string> stringList = new List<string>(); - List<int> z = new List<int> { 9000, 1000, 1337 }; // intialize + List<int> z = new List<int> { 9000, 1000, 1337 }; // initialize // The <> are for generics - Check out the cool stuff section // Lists don't default to a value; @@ -394,6 +395,7 @@ on a new line! ""Wow!"", the masses cried"; ref int maxCount, // Pass by reference out int count) { + //the argument passed in as 'count' will hold the value of 15 outside of this function count = 15; // out param must be assigned before control leaves the method } @@ -460,7 +462,7 @@ on a new line! ""Wow!"", the masses cried"; { // OPTIONAL PARAMETERS MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); - MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones + MethodSignatures(3, another: 3); // explicitly set a parameter, skipping optional ones // BY REF AND OUT PARAMETERS int maxCount = 0, count; // ref params must have value @@ -481,7 +483,7 @@ on a new line! ""Wow!"", the masses cried"; // in case variable is null int notNullable = nullable ?? 0; // 0 - // ?. is an operator for null-propogation - a shorthand way of checking for null + // ?. is an operator for null-propagation - a shorthand way of checking for null nullable?.Print(); // Use the Print() extension method if nullable isn't null // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is: @@ -650,7 +652,7 @@ on a new line! ""Wow!"", the masses cried"; { return _cadence; } - set // set - define a method to set a proprety + set // set - define a method to set a property { _cadence = value; // Value is the value passed in to the setter } diff --git a/css.html.markdown b/css.html.markdown index e3ca94d9..d8f30ca3 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -106,6 +106,20 @@ selected:link { } /* or an element in focus */ selected:focus { } +/* any element that is the first child of its parent */ +selector:first-child {} + +/* any element that is the last child of its parent */ +selector:last-child {} + +/* Just like pseudo classes, pseudo elements allow you to style certain parts of a document */ + +/* matches a virtual first child of the selected element */ +selector::before {} + +/* matches a virtual last child of the selected element */ +selector::after {} + /* At appropriate places, an asterisk may be used as a wildcard to select every element */ * { } /* all elements */ diff --git a/d.html.markdown b/d.html.markdown index ba24b60f..80c1dc65 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -23,8 +23,10 @@ about [D](http://dlang.org/). The D programming language is a modern, general-pu multi-paradigm language with support for everything from low-level features to expressive high-level abstractions. -D is actively developed by Walter Bright and Andrei Alexandrescu, two super smart, really cool -dudes. With all that out of the way, let's look at some examples! +D is actively developed by a large group of super-smart people and is spearheaded by +[Walter Bright](https://en.wikipedia.org/wiki/Walter_Bright) and +[Andrei Alexandrescu](https://en.wikipedia.org/wiki/Andrei_Alexandrescu). +With all that out of the way, let's look at some examples! ```c import std.stdio; @@ -36,9 +38,10 @@ void main() { writeln(i); } - auto n = 1; // use auto for type inferred variables + // 'auto' can be used for inferring types. + auto n = 1; - // Numeric literals can use _ as a digit seperator for clarity + // Numeric literals can use '_' as a digit separator for clarity. while(n < 10_000) { n += n; } @@ -47,13 +50,15 @@ void main() { n -= (n / 2); } while(n > 0); - // For and while are nice, but in D-land we prefer foreach - // The .. creates a continuous range, excluding the end + // For and while are nice, but in D-land we prefer 'foreach' loops. + // The '..' creates a continuous range, including the first value + // but excluding the last. foreach(i; 1..1_000_000) { if(n % 2 == 0) writeln(i); } + // There's also 'foreach_reverse' when you want to loop backwards. foreach_reverse(i; 1..int.max) { if(n % 2 == 1) { writeln(i); @@ -69,16 +74,18 @@ are passed to functions by value (i.e. copied) and classes are passed by referen we can use templates to parameterize all of these on both types and values! ```c -// Here, T is a type parameter. Think <T> from C++/C#/Java +// Here, 'T' is a type parameter. Think '<T>' from C++/C#/Java. struct LinkedList(T) { T data = null; - LinkedList!(T)* next; // The ! is used to instaniate a parameterized type. Again, think <T> + + // Use '!' to instantiate a parameterized type. Again, think '<T>'. + LinkedList!(T)* next; } class BinTree(T) { T data = null; - // If there is only one template parameter, we can omit parens + // If there is only one template parameter, we can omit the parentheses. BinTree!T left; BinTree!T right; } @@ -93,13 +100,11 @@ enum Day { Saturday, } -// Use alias to create abbreviations for types - +// Use alias to create abbreviations for types. alias IntList = LinkedList!int; alias NumTree = BinTree!double; // We can create function templates as well! - T max(T)(T a, T b) { if(a < b) return b; @@ -107,9 +112,8 @@ T max(T)(T a, T b) { return a; } -// Use the ref keyword to ensure pass by referece. -// That is, even if a and b are value types, they -// will always be passed by reference to swap +// Use the ref keyword to ensure pass by reference. That is, even if 'a' and 'b' +// are value types, they will always be passed by reference to 'swap()'. void swap(T)(ref T a, ref T b) { auto temp = a; @@ -117,13 +121,13 @@ void swap(T)(ref T a, ref T b) { b = temp; } -// With templates, we can also parameterize on values, not just types +// With templates, we can also parameterize on values, not just types. class Matrix(uint m, uint n, T = int) { T[m] rows; T[n] columns; } -auto mat = new Matrix!(3, 3); // We've defaulted type T to int +auto mat = new Matrix!(3, 3); // We've defaulted type 'T' to 'int'. ``` @@ -133,21 +137,20 @@ have the syntax of POD structures (`structure.x = 7`) with the semantics of getter and setter methods (`object.setX(7)`)! ```c -// Consider a class parameterized on a types T, U - +// Consider a class parameterized on types 'T' & 'U'. class MyClass(T, U) { T _data; U _other; - } -// And "getter" and "setter" methods like so +// And "getter" and "setter" methods like so: class MyClass(T, U) { T _data; U _other; - // Constructors are always named `this` + // Constructors are always named 'this'. this(T t, U u) { + // This will call the setter methods below. data = t; other = u; } @@ -170,16 +173,24 @@ class MyClass(T, U) { _other = u; } } -// And we use them in this manner +// And we use them in this manner: void main() { - auto mc = MyClass!(int, string); + auto mc = new MyClass!(int, string)(7, "seven"); + + // Import the 'stdio' module from the standard library for writing to + // console (imports can be local to a scope). + import std.stdio; + + // Call the getters to fetch the values. + writefln("Earlier: data = %d, str = %s", mc.data, mc.other); - mc.data = 7; - mc.other = "seven"; + // Call the setters to assign new values. + mc.data = 8; + mc.other = "eight"; - writeln(mc.data); - writeln(mc.other); + // Call the getters again to fetch the new values. + writefln("Later: data = %d, str = %s", mc.data, mc.other); } ``` diff --git a/de-de/csharp-de.html.markdown b/de-de/csharp-de.html.markdown index 8ad7d71f..78bb0a6b 100644 --- a/de-de/csharp-de.html.markdown +++ b/de-de/csharp-de.html.markdown @@ -883,7 +883,7 @@ zur nächsten Zeile, ""Wahnsinn!"", die Massen waren kaum zu bändigen"; * [LINQ](http://shop.oreilly.com/product/9780596519254.do)
* [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx)
* [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials)
- * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials)
+ * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/overview/exploring-webmatrix)
* [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials)
* [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208)
diff --git a/de-de/latex-de.html.markdown b/de-de/latex-de.html.markdown new file mode 100644 index 00000000..2c18b8fd --- /dev/null +++ b/de-de/latex-de.html.markdown @@ -0,0 +1,235 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] +translators: + - ["Moritz Kammerer", "https://github.com/phxql"] +lang: de-de +filename: latex-de.tex +--- +``` +% Alle Kommentare starten fangen mit % an +% Es gibt keine Kommentare über mehrere Zeilen + +% LateX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B. +% MS Word oder OpenOffice Writer + +% Jedes LateX-Kommando startet mit einem Backslash (\) + +% LateX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen +% Weitere Dokumententypen sind z.B. book, report, presentations, etc. +% Optionen des Dokuments stehen zwischen den eckigen Klammern []. In diesem Fall +% wollen wir einen 12 Punkte-Font verwenden. +\documentclass[12pt]{article} + +% Als nächstes definieren wir die Pakete, die wir verwenden wollen. +% Wenn du z.B. Grafiken, farbigen Text oder Quelltext in dein Dokument einbetten möchtest, +% musst du die Fähigkeiten von Latex durch Hinzufügen von Paketen erweitern. +% Wir verwenden die Pakete float und caption für Bilder. +\usepackage{caption} +\usepackage{float} + +% Mit diesem Paket können leichter Umlaute getippt werden +\usepackage[utf8]{inputenc} + +% Es können durchaus noch weitere Optione für das Dokument gesetzt werden! +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} +\date{\today} +\title{Learn LaTeX in Y Minutes!} + +% Nun kann's losgehen mit unserem Dokument. +% Alles vor dieser Zeile wird die Preamble genannt. +\begin{document} +% Wenn wir den Autor, das Datum und den Titel gesetzt haben, kann +% LateX für uns eine Titelseite generieren +\maketitle + +% Die meisten Paper haben ein Abstract. LateX bietet dafür einen vorgefertigen Befehl an. +% Das Abstract sollte in der logischen Reihenfolge, also nach dem Titel, aber vor dem +% Inhalt erscheinen. +% Dieser Befehl ist in den Dokumentenklassen article und report verfügbar. +\begin{abstract} + LateX documentation geschrieben in LateX! Wie ungewöhnlich und garantiert nicht meine Idee! +\end{abstract} + +% Section Befehle sind intuitiv. +% Alle Titel der sections werden automatisch in das Inhaltsverzeichnis übernommen. +\section{Einleitung} +Hi, mein Name ist Moritz und zusammen werden wir LateX erforschen! + +\section{Noch eine section} +Das hier ist der Text für noch eine section. Ich glaube, wir brauchen eine subsection. + +\subsection{Das ist eine subsection} % Subsections sind auch ziemlich intuitiv. +Ich glaube, wir brauchen noch eine. + +\subsubsection{Pythagoras} +So ist's schon viel besser. +\label{subsec:pythagoras} + +% Wenn wir den Stern nach section schreiben, dann unterdrückt LateX die Nummerierung. +% Das funktioniert auch bei anderen Befehlen. +\section*{Das ist eine unnummerierte section} +Es müssen nicht alle sections nummeriert sein! + +\section{Ein paar Notizen} +LateX ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht. +Falls eine Zeile \\ mal \\ woanders \\ umgebrochen \\ werden \\ soll, füge +\textbackslash\textbackslash in den Code ein.\\ + +\section{Listen} +Listen sind eine der einfachsten Dinge in LateX. Ich muss morgen einkaufen gehen, +also lass uns eine Einkaufsliste schreiben: +\begin{enumerate} % Dieser Befehl erstellt eine "enumerate" Umgebung. + % \item bringt enumerate dazu, eins weiterzuzählen. + \item Salat. + \item 27 Wassermelonen. + \item einen Hasen. + % Wir können die Nummer des Eintrags durch [] überschreiben + \item[Wie viele?] Mittelgroße Wasserpistolen. + + Kein Listeneintrag, aber immer noch Teil von enumerate. + +\end{enumerate} % Alle Umgebungen müssen ein end haben. + +\section{Mathe} + +Einer der Haupteinsatzzwecke von LateX ist das Schreiben von akademischen +Artikeln oder Papern. Meistens stammen diese aus dem Bereich der Mathe oder +anderen Wissenschaften. Und deswegen müssen wir in der Lage sein, spezielle +Symbole zu unserem Paper hinzuzufügen! \\ + +Mathe kennt sehr viele Symbole, viel mehr als auf einer Tastatur zu finden sind; +Symbole für Mengen und relationen, Pfeile, Operatoren und Griechische Buchstaben, +um nur ein paar zu nennen.\\ + +Mengen und Relationen spielen eine sehr wichtige Rolle in vielen mathematischen +Papern. So schreibt man in LateX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\ + +% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LateX schreiben, +% geschieht dies standardmäßig im Textmodus. Die Mathe-Symbole existieren allerdings +% nur im Mathe-Modus. Wir können den Mathe-Modus durch das $ Zeichen aktivieren und +% ihn mit $ wieder verlassen. Variablen können auch im Mathe-Modus angezeigt werden. + +Mein Lieblingsbuchstabe im Griechischen ist $\xi$. Ich mag auch $\beta$, $\gamma$ und $\sigma$. +Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den LateX nicht kennt! + +Operatoren sind ebenfalls wichtige Bestandteile von mathematischen Dokumenten: +Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$), +Logarithmus und Exponenten ($\log$, $\exp$), +Grenzwerte ($\lim$), etc. haben vordefinierte Befehle. +Lass uns eine Gleichung schreiben: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$\\ + +Brüche (Zähler / Nenner) können so geschrieben werden: + +% 10 / 7 +$^{10}/_{7}$ + +% Komplexere Brüche können so geschrieben werden: +% \frac{Zähler}{Nenner} +$\frac{n!}{k!(n - k)!}$ \\ + +Wir können Gleichungen auch in einer equation Umgebung verwenden. + +% Dies zeigt Mathe in einer equation Umgebung an +\begin{equation} % Aktiviert automatisch den Mathe-Modus. + c^2 = a^2 + b^2. + \label{eq:pythagoras} % Pythagoras referenzieren +\end{equation} % Alle \begin Befehle müssen einen \end Befehl besitzen + +Wir können nun unsere Gleichung referenzieren! +Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in +Abschnitt ~\ref{subsec:pythagoras} behandelt. Es können sehr viele Sachen mit Labels versehen werden: +Grafiken, Gleichungen, Sections, etc. + +Summen und Integrale können mit den sum und int Befehlen dargestellt werden: + +% Manche LateX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Grafiken} + +Lass uns eine Grafik einfügen. Das Platzieren von Grafiken kann etwas trickreich sein. +Aber keine Sorge, ich muss auch jedes mal nachschauen, welche Option wie wirkt. + +\begin{figure}[H] % H ist die Platzierungsoption + \centering % Zentriert die Grafik auf der Seite + % Fügt eine Grafik ein, die auf 80% der Seitenbreite einnimmt. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Auskommentiert, damit es nicht im Dokument auftaucht. + \caption{Dreieck mit den Seiten $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} + +\subsection{Tabellen} +Wir können Tabellen genauso wie Grafiken einfügen. + +\begin{table}[H] + \caption{Überschrift der Tabelle.} + % Die {} Argumente geben an, wie eine Zeile der Tabelle dargestellt werden soll. + % Auch hier muss ich jedes Mal nachschauen. Jedes. einzelne. Mal. + \begin{tabular}{c|cc} + Nummer & Nachname & Vorname \\ % Spalten werden durch & getrennt + \hline % Eine horizontale Linie + 1 & Biggus & Dickus \\ + 2 & Monty & Python + \end{tabular} +\end{table} + +% \section{Links} % Kommen bald! + +\section{Verhindern, dass LateX etwas kompiliert (z.B. Quelltext)} +Angenommen, wir wollen Quelltext in unserem LateX-Dokument. LateX soll +in diesem Fall nicht den Quelltext als LateX-Kommandos interpretieren, +sondern es einfach ins Dokument schreiben. Um das hinzubekommen, verwenden +wir eine verbatim Umgebung. + +% Es gibt noch weitere Pakete für Quelltexte (z.B. minty, lstlisting, etc.) +% aber verbatim ist das simpelste. +\begin{verbatim} + print("Hello World!") + a%b; % Schau dir das an! Wir können % im verbatim verwenden! + random = 4; #decided by fair random dice roll +\end{verbatim} + +\section{Kompilieren} + +Ich vermute, du wunderst dich, wie du dieses tolle Dokument in ein PDF +verwandeln kannst. (Ja, dieses Dokument kompiliert wirklich!) \\ + +Dafür musst du folgende Schritte durchführen: + \begin{enumerate} + \item Schreibe das Dokument. (den LateX-Quelltext). + \item Kompiliere den Quelltext in ein PDF. + Das Kompilieren sieht so ähnlich wie das hier aus (Linux): \\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +Manche LateX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt +2 wird unsichtbar im Hintergrund ausgeführt. + +Alle Formatierungsoptionen werden in Schritt 1 in den Quelltext geschrieben. Schritt 2 verwendet +dann diese Informationen und kümmert sich drum, dass das Dokument korrekt erstellt wird. + +\section{Ende} + +Das war's erst mal! + +% Dokument beenden +\end{document} +``` +## Mehr Informationen über LateX + +* Das tolle LaTeX wikibook: [https://de.wikibooks.org/wiki/LaTeX-Kompendium](https://de.wikibooks.org/wiki/LaTeX-Kompendium) +* Ein Tutorial (englisch): [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) diff --git a/de-de/ruby-de.html.markdown b/de-de/ruby-de.html.markdown new file mode 100644 index 00000000..bdeaa30b --- /dev/null +++ b/de-de/ruby-de.html.markdown @@ -0,0 +1,613 @@ +--- +language: ruby +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] +translators: + - ["Christian Albrecht", "https://github.com/coastalchief"] +filename: ruby-de.rb +lang: de-de +--- + +# Dies ist ein Kommentar + +=begin +Dies sind multi-line +Kommentare. Niemand benutzt +die wirklich. +=end + +# Objekte - Alles ist ein Objekt + +## Zahlen sind Objekte +``` +3.class #=> Fixnum +3.to_s #=> "3" +``` + +### Simple Arithmetik +``` +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 +``` + +// Arithmetik ist aber eigentlich nur syntaktischer Zucker +// um eine Methode eines Objekt aufzurufen +``` +1.+(3) #=> 4 +10.* 5 #=> 50 +``` + +## Special values sind Objekte +``` +nil # Nothing to see here +true # truth +false # falsehood + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass +``` + +## Objektvergleiche +### Gleicheit +``` +1 == 1 #=> true +2 == 1 #=> false +``` +### Ungleichheit +``` +1 != 1 #=> false +2 != 1 #=> true +``` +### Neben false selbst, nil ist ein anderer 'falsey' Wert +``` +!nil #=> true +!false #=> true +!0 #=> false +``` +### Weitere Vergleiche +``` +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true +``` +### Logische Operatoren +``` +true && false #=> false +true || false #=> true +!true #=> false +``` + +Es gibt alternative Versionen der logischen Operatoren mit niedrigerer +Wertigkeit. Diese werden meistens bei Flow-Control eingesetzt, um +verschiedenen Ausdrücke zu verketten bis einer true oder false zurück +liefert. + +#### and +##### `do_something_else` wird nur ausgewertet wenn `do_something` true ist. +do_something() and do_something_else() + +#### or +#####`log_error` wird nur ausgewertet wenn `do_something` false ist. +do_something() or log_error() + +## Strings sind Objekte +``` +'I am a string'.class #=> String +"I am a string too".class #=> String + + +platzhalter = 'Ruby' +"Ich kann in #{placeholder} Platzhalter mit doppelten Anführungsstrichen füllen." +``` +Einfache Anführungszeichen sollten bevorzugt werden. +Doppelte Anführungszeichen führen interne Berechnungen durch. + +### Strings können verbunden werden, aber nicht mit Zahlen +``` +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +``` +#### Zahl muss in String konvertiert werden +``` +'hello ' + 3.to_s #=> "hello 3" +``` +### Text ausgeben +``` +puts "I'm printing!" +``` +# Variablen +## Zuweisungen +### Diese Zuweisung gibt den zugeordneten Wert zurück +``` +x = 25 #=> 25 +x #=> 25 +``` +### Damit funktionieren auch mehrfache Zuweisungen +``` +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 +``` +## Benennung +### Konvention ist snake_case +``` +snake_case = true +``` +### Benutze verständliche Variablennamen +``` +path_to_project_root = '/good/name/' +path = '/bad/name/' +``` +# Symbols (sind auch Objekte) +Symbols sind unveränderliche, wiederverwendbare Konstanten, welche intern +als integer repräsentiert werden. Sie werden häufig anstelle von Strings +verwendet, um sinnvoll Werte zu übermitteln. +Symbols werden mit dem Doppelpunkt gekennzeichnet. + +``` +:pending.class #=> Symbol +status = :pending +status == :pending #=> true +status == 'pending' #=> false +status == :approved #=> false +``` +# Arrays + +## Ein Array anlegen +``` +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] +``` + +## Array können verschiedene Typen beinhalten +``` +[1, 'hello', false] #=> [1, "hello", false] +``` + +## Wie bei arithmetischen Ausdrücken auch wird beim Zugriff auf +## [0] eigentlich die Methode [] des Array Objekts aufgerufen. +``` +array.[] 0 #=> 1 +array.[] 12 #=> nil +``` + +## Arrays können von vorne indiziert werden +``` +array[0] #=> 1 +array[12] #=> nil +``` + +## Arrays können von hinten indiziert werden +``` +array[-1] #=> 5 +``` + +## Arrays können mit Stard Index und Länge indiziert werden +``` +array[2, 3] #=> [3, 4, 5] +``` + +## Arrays können mit einer Range indiziert werden +``` +array[1..3] #=> [2, 3, 4] +``` + +## Einen Wert hinzufügen +``` +array << 6 #=> [1, 2, 3, 4, 5, 6] +array.push(6) #=> [1, 2, 3, 4, 5, 6] +``` + +## Testen, ob ein Element schon vorhanden ist +``` +array.include?(1) #=> true +``` + +# Hashes +Hashes sind das Hauptfeature um Key/Values zu speichern + +``` + +## Ein Hash anlegen +``` +hash = { 'color' => 'green', 'number' => 5 } +hash.keys #=> ['color', 'number'] +``` + +## Wert per key herausfinden +``` +hash['color'] #=> 'green' +hash['number'] #=> 5 +hash['nothing here'] #=> nil +// Asking a hash for a key that doesn't exist returns nil: +``` + +## Symbols können auch keys sein +``` +new_hash = { defcon: 3, action: true } +new_hash.keys #=> [:defcon, :action] +``` + +## Testen ob ein Key oder ein Value existiert +``` +new_hash.has_key?(:defcon) #=> true +new_hash.has_value?(3) #=> true +``` + +### Tip: Arrays und Hashes sind Enumerable +### Und haben gemeinsame, hilfreiche Methoden wie: +### each, map, count, and more + +# Kontrolstrukturen +## if +``` +if true + 'if statement' +elsif false + 'else if, optional' +else + 'else, also optional' +end +``` +## for - Allerdings werden for Schleifen nicht oft vewendet. +``` +for counter in 1..5 + puts "iteration #{counter}" +end +``` +## Stattdessen: "each" Methode und einen Bloch übergeben +Ein Block ist ein Codeteil, den man einer Methode übergeben kann +Ähnelt stark lambdas, anonymen Funktionen oder Closures in anderen +Programmiersprachen. + +``` +(1..5).each do |counter| + puts "iteration #{counter}" +end +``` + +Die each Methode einer Range führt den Block für jedes Element der Range aus. + +Dem Block wird ein "counter" parameter übergeben. + +### Den Block kann man auch in geschweiften Klammern schreiben +``` +(1..5).each { |counter| puts "iteration #{counter}" } +``` + +### Each kann auch über den Inhalt von Datenstrukturen iterieren +``` +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end +``` + +## case +``` +grade = 'B' + +case grade +when 'A' + puts 'Way to go kiddo' +when 'B' + puts 'Better luck next time' +when 'C' + puts 'You can do better' +when 'D' + puts 'Scraping through' +when 'F' + puts 'You failed!' +else + puts 'Alternative grading system, eh?' +end +=> "Better luck next time" +``` + +### Case können auch ranges +``` +grade = 82 +case grade +when 90..100 + puts 'Hooray!' +when 80...90 + puts 'OK job' +else + puts 'You failed!' +end +=> "OK job" +``` + +# exception handling: +``` +begin + # code here that might raise an exception + raise NoMemoryError, 'You ran out of memory.' +rescue NoMemoryError => exception_variable + puts 'NoMemoryError was raised', exception_variable +rescue RuntimeError => other_exception_variable + puts 'RuntimeError was raised now' +else + puts 'This runs if no exceptions were thrown at all' +ensure + puts 'This code always runs no matter what' +end +``` +# Funktionen +``` +def double(x) + x * 2 +end +``` +## Funktionen (und Blocks) +## geben implizit den Wert des letzten Statements zurück +``` +double(2) #=> 4 +``` + +### Klammern sind optional wenn das Ergebnis nicht mehdeutig ist +``` +double 3 #=> 6 +double double 3 #=> 12 +def sum(x, y) + x + y +end +``` + +### Methoden Parameter werden per Komma getrennt +``` +sum 3, 4 #=> 7 +sum sum(3, 4), 5 #=> 12 +``` + +## yield +### Alle Methoden haben einen impliziten, optionalen block Parameter +### Dieser wird mit dem Schlüsselword "yield" aufgerufen +``` +def surround + puts '{' + yield + puts '}' +end +surround { puts 'hello world' } +``` + +## Einen Block kann man auch einer Methoden übergeben +### "&" kennzeichnet die Referenz zum übergebenen Block +``` +def guests(&block) + block.call 'some_argument' +end +``` + +### Eine Liste von Parametern kann man auch übergeben, +### Diese wird in ein Array konvertiert +### "*" kennzeichnet dies. +``` +def guests(*array) + array.each { |guest| puts guest } +end +``` +# Klassen +## Werden mit dem class Schlüsselwort definiert +``` +class Human +``` + +### Konstruktor bzw. Initializer +``` + def initialize(name, age = 0) + # Assign the argument to the "name" instance variable for the instance + @name = name + # If no age given, we will fall back to the default in the arguments list. + @age = age + end +``` + +### setter Methode +``` + def name=(name) + @name = name + end +``` +### getter Methode +``` + def name + @name + end +``` + +#### getter können mit der attr_accessor Methode vereinfacht definiert werden +``` + attr_accessor :name + # Getter/setter methods can also be created individually like this + attr_reader :name + attr_writer :name + # A class method uses self to distinguish from instance methods. + # It can only be called on the class, not an instance. + def self.say(msg) + puts msg + end + def species + @@species + end +end +``` + +## Eine Klasse instanziieren +``` +jim = Human.new('Jim Halpert') +dwight = Human.new('Dwight K. Schrute') +``` + +## Methodenaufrufe +``` +jim.species #=> "H. sapiens" +jim.name #=> "Jim Halpert" +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.name #=> "Jim Halpert II" +dwight.species #=> "H. sapiens" +dwight.name #=> "Dwight K. Schrute" +``` + +## Eine Klassenmethode aufrufen +``` +Human.say('Hi') #=> "Hi" +``` + +## Variable Gültigkeit +### Variablen die mit "$" starten, gelten global +``` +$var = "I'm a global var" +defined? $var #=> "global-variable" +``` + +### Variablen die mit "@" starten, gelten für die Instanz +``` +@var = "I'm an instance var" +defined? @var #=> "instance-variable" +``` + +### Variablen die mit "@@" starten, gelten für die Klasse +``` +@@var = "I'm a class var" +defined? @@var #=> "class variable" +``` + +### Variablen die mit einem Großbuchstaben anfangen, sind Konstanten +``` +Var = "I'm a constant" +defined? Var #=> "constant" +``` + +## Class ist auch ein Objekt +### Hat also auch Instanzvariablen +### Eine Klassenvariable wird innerhalb der Klasse und Ableitungen geteilt. + +### Basis Klasse +``` +class Human + @@foo = 0 + def self.foo + @@foo + end + def self.foo=(value) + @@foo = value + end +end +``` + +### Abgeleitete Klasse +``` +class Worker < Human +end +Human.foo # 0 +Worker.foo # 0 +Human.foo = 2 # 2 +Worker.foo # 2 +``` + +### Eine Klasseninstanzvariable wird nicht geteilt +``` +class Human + @bar = 0 + def self.bar + @bar + end + def self.bar=(value) + @bar = value + end +end +``` +``` +class Doctor < Human +end +``` +``` +Human.bar # 0 +Doctor.bar # nil +``` +``` +module ModuleExample + def foo + 'foo' + end +end +``` +### Module einbinden, heisst ihre Methoden an die Instanzen der Klasse zu binden +### Module erweitern, heisst ihre Mothden an die Klasse selbst zu binden +``` +class Person + include ModuleExample +end +``` +``` +class Book + extend ModuleExample +end +``` +``` +Person.foo # => NoMethodError: undefined method `foo' for Person:Class +Person.new.foo # => 'foo' +Book.foo # => 'foo' +Book.new.foo # => NoMethodError: undefined method `foo' +``` +### Callbacks werden ausgeführt, wenn ein Modul eingebunden oder erweitert wird +``` + module ConcernExample + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + module ClassMethods + def bar + 'bar' + end + end + module InstanceMethods + def qux + 'qux' + end + end + end + class Something + include ConcernExample + end +``` +``` +Something.bar # => 'bar' +Something.qux # => NoMethodError: undefined method `qux' +Something.new.bar # => NoMethodError: undefined method `bar' +Something.new.qux # => 'qux' +``` + +## Weiterführende Hinweise + +//EN + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. +- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. diff --git a/de-de/ruby-ecosystem-de.html.markdown b/de-de/ruby-ecosystem-de.html.markdown new file mode 100644 index 00000000..a7e1f75f --- /dev/null +++ b/de-de/ruby-ecosystem-de.html.markdown @@ -0,0 +1,149 @@ +--- +category: tool +tool: ruby ecosystem +contributors: + - ["Jon Smock", "http://github.com/jonsmock"] + - ["Rafal Chmiel", "http://github.com/rafalchmiel"] +translators: + - ["Christian Albrecht", "https://github.com/coastalchief"] +filename: ruby-ecosystem-de.txt +lang: de-de +--- + +Hier gibt es einen Überblick über die gängigsten Tools zur Verwaltung +von verschiedenen Ruby Versionen, Gems und Dependencies. + +## Ruby Managers + +Einige Betriebssysteme haben bereits eine Ruby Version vorinstalliert +oder bieten sie als Package zum Download an. Die meisten Rubyisten +benutzen diese aber eher nicht und wenn, dann um damit einen Ruby +Manager zu installieren. Damit kann man komfortabel zwischen den +verschiedenen Versionen hin und herspringen. + +Dies sind die beliebtesten: + +* [RVM](https://rvm.io/) - Installiert und wechselt zwischen rubies + RVM kennt verschiedene Ruby Versionen und hat das Konzept der gemsets, + um gem Abhängigkeiten pro Projekt zu managen. +* [ruby-build](https://github.com/sstephenson/ruby-build) + Installiert nur rubies, kann diese aber sehr gut verwalten +* [rbenv](https://github.com/sstephenson/rbenv) - Wechselt Ruby Versionen. + Wird zusammen mit ruby-build benutzt. Hiermit kann man kontrollieren, + wie rubies laden. +* [chruby](https://github.com/postmodern/chruby) - Wechselt Ruby Versionen. + Ähnlich rbenv. + +## Ruby Versionen + +Ruby wurde von Yukihiro "Matz" Matsumoto vor gut 20 Jahren veröffentlicht. +Matz ist nach wie vor in die Entwicklung involviert. Daher kommt auch der +Name der Referenzimplementierung: MRI (Matz' Reference Implementation). + +Die aktuellste Version ist **2.2.3** und wurde im August 2015 veröffentlicht! + +Hier eine kurze Versionshistorie: + +* 2.0.0 - Release im Februar 2013 -- Release zum 20. Geburtstag der Sprache + [Rubies are forever](http://www.heise.de/developer/artikel/Ruby-2-0-als-Geschenk-zum-20-Geburtstag-1808109.html) +* 1.9.3 - Release im Oktober 2011 + [End of Life](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) +* 1.8.7 - Release im Juni 2006 + [End of Life](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). + +Die Veränderung zwischen 1.8.7 und 1.9.x war sehr groß und eine Migration +nicht so einfach möglich. Der Versionssprung auf 2.0.0 war verglichen dazu +weit weniger dramatisch. +Beispielsweise hat 1.9. Encodings und eine Bytecode VM eingeführt. +Es gibt immer noch Projekte die auf der stabilen Version 1.8.7 laufen, +aber diese sind mittlerweile in der Minderheit. Die meisten Projekte +laufen auf 1.9.x oder auf 2.x. + +## Ruby Implementierungen + +Das Ruby Ecosystem beinhaltet viele verschiedene Implementierungen von Ruby, +jedes mit seinen eigenen Vorteilen und verschiedenen Graden von +Kompatibilität. Auch wenn alle diese Implementierungen in verschiedenen +Sprachen geschrieben sind, sind sie doch **alle Ruby**. +Jede Implementierung bietet neben ihren speziellen Features immer auch +die Möglichkeit normale ruby Dateien auszuführen. + +Am ausgereiftesten und stabilsten: + +* [MRI](https://github.com/ruby/ruby) - Geschrieben in C, das ist die Referenz Implementierung. + Sie ist 100% kompatibel (mit sich selbst ;-). Alle anderen rubies + bleiben kompatibel mit MRI (siehe [RubySpec](#rubyspec) weiter unten). +* [JRuby](http://jruby.org/) - Geschrieben in Java and Ruby, Robust und ziemlich schnell. + Der größte Vorteil von JRuby ist die Interoperabilität mit JVM/Java und damit die + Benutzung von Ruby im Java Ecosystem. +* [Rubinius](http://rubini.us/) - Geschrieben in Ruby mit C++ bytecode VM. + Auch sehr ausgereift und schnell. + +Mittel ausgereift / kompatibel: + +* [Maglev](http://maglev.github.io/) - Baut auf Gemstone, ein Smalltalk VM. + Dieses Projekt versucht das großartige Smalltalk Tooling in die Ruby Welt + zu bringen. +* [RubyMotion](http://www.rubymotion.com/) - Ruby in der iOS Entwicklung. + +Weniger ausgereift/kompatibel: + +* [Topaz](http://topazruby.com/) - Geschrieben in RPython (via PyPy) + Topaz ist noch ziemlich jung und versucht die schnellste Implementierung + zu werden. +* [IronRuby](http://ironruby.net/) - Geschrieben in C# für die .NET Plaftform + Das letzte Release von IronRuby ist mittlerweile 5 Jahre her. + +Die Ruby Implementierungen haben ihre eigenen Versionsnummern, sind aber +trotzdem immer zu einer MRI Version kompatibel. +Viele können sogar zwischen verschiedenen Modi wechseln (1.8 mode -> 1.9 mode) + +## RubySpec + +Die meisten Ruby Implementierungen vertrauen der [RubySpec](http://rubyspec.org/). +sehr stark. Da Ruby keine offizielle Spezifikation hat, hat die +Community ausführbare Specs (in Ruby) geschrieben, um so die Kompatibilität +zur MRI testen zu können. + +## RubyGems + +[RubyGems](http://rubygems.org/) ist der Community Paket Manager von Ruby. +RubyGems kommt mit Ruby zusammen, so dass kein extra Tool nötig ist. + +Ruby Pakete werden "gems" genannt und könnten auf RubyGems.org +veröffentlicht werden. Jedes Gem enthält den Source Code und Meta Daten, +wie die Versionsnummer, weitere Abhängigkeiten, Autoren und Lizenzen. + +## Bundler + +[Bundler](http://bundler.io/) ist ein Tool um Abhängigkeiten zwischen +Gems aufzulösen und zu managen. Dazu werden diese in einem gemfile +zusammengefasst und Bundler kümmert sich darum die Abhängigkeiten +untereinander rekursiv aufzulösen. Entweder es klappt und alle gems +konnten runtergeladen werden, oder es wird abgebrochen und +der Konflikt gemeldet. +Zum Beispiel: +Wenn Gem A die Version 3 oder höher von Gem Z braucht, aber Gem B +von Gem Z die Version 2, dann ist das ein Konflikt. + +# Testing + +Test-Driven Development ist ein essentieller Teil der Ruby Kultur. +Ruby bringt sein eigenes Unit-Test framework mit, minitest. Darüberhinaus +gibt es noch viele weitere Testframeworks mit unterschiedlichsten Zielen: + +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - Eingebaut in Ruby 1.8 + "Unit-style" Testframework +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - Eingebaut in Ruby 1.9/2.0 + "Unit-style" Testframework +* [RSpec](http://rspec.info/) - Ein Testframework welches auf verständliche Testdefinition setzt +* [Cucumber](http://cukes.info/) - Ein BDD Testframework welches Gherkin tests parsen kann + +## Be Nice +Die Ruby Community ist stolz darauf eine offene, vielfältige und einladende +Community zu sein. Es gibt viele aktive Ruby User Gruppen und diverse +Ruby Konferenzen. Matz selbst ist so oft es geht dabei. + +* [Euruko](http://www.euruko2015.org) +* [User Groups](https://www.ruby-lang.org/de/community/user-groups/) + diff --git a/de-de/scala-de.html.markdown b/de-de/scala-de.html.markdown new file mode 100644 index 00000000..7fd299b4 --- /dev/null +++ b/de-de/scala-de.html.markdown @@ -0,0 +1,816 @@ +--- +language: Scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] + - ["Dominic Bou-Samra", "http://dbousamra.github.com"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Ha-Duong Nguyen", "http://reference-error.org"] +translators: + - ["Christian Albrecht", "https://github.com/coastalchief"] +filename: learnscala-de.scala +lang: de-de +--- + +Scala ist eine funktionale und objektorientierte Programmiersprache +für die Java Virtual Machine (JVM), um allgemeine Programmieraufgaben +zu erledigen. Scala hat einen akademischen Hintergrund und wurde an +der EPFL (Lausanne / Schweiz) unter der Leitung von Martin Odersky entwickelt. + + +# 0. Umgebung einrichten +Scala Umgebung einrichten: + +1. Scala binaries herunterladen- http://www.scala-lang.org/downloads +2. Unzip/untar in ein Verzeichnis +3. das bin Unterverzeichnis der `PATH` Umgebungsvariable hinzufügen +4. Mit dem Kommando `scala` wird die REPL gestartet und zeigt als Prompt: +``` +scala> +``` + +Die REPL (Read-Eval-Print Loop) ist der interaktive Scala Interpreter. +Hier kann man jeden Scala Ausdruck verwenden und das Ergebnis wird direkt +ausgegeben. +Als nächstes beschäftigen wir uns mit ein paar Scala Basics. + +# 1. Basics + +Einzeilige Kommentare beginnen mit zwei vorwärts Slash + +/* + Mehrzeilige Kommentare, werden starten + mit Slash-Stern und enden mit Stern-Slash +*/ + +// Einen Wert, und eine zusätzliche neue Zeile ausgeben +``` +println("Hello world!") +println(10) +``` + +// Einen Wert, ohne eine zusätzliche neue Zeile ausgeben +``` +print("Hello world") +``` + +// Variablen werden entweder mit var oder val deklariert. +// Deklarationen mit val sind immutable, also unveränderlich +// Deklarationen mit var sind mutable, also veränderlich +// Immutability ist gut. +``` +val x = 10 // x ist 10 +x = 20 // error: reassignment to val +var y = 10 +y = 20 // y ist jetzt 20 +``` + +Scala ist eine statisch getypte Sprache, auch wenn in dem o.g. Beispiel +keine Typen an x und y geschrieben haben. +In Scala ist etwas eingebaut, was sich Type Inference nennt. D.h. das der +Scala Compiler in den meisten Fällen erraten kann, von welchen Typ eine ist, +so dass der Typ nicht jedes mal angegeben werden soll. +Einen Typ gibt man bei einer Variablendeklaration wie folgt an: +``` +val z: Int = 10 +val a: Double = 1.0 +``` + +// Bei automatischer Umwandlung von Int auf Double wird aus 10 eine 10.0 +``` +val b: Double = 10 +``` + +// Boolean Werte +``` +true +false +``` + +// Boolean Operationen +``` +!true // false +!false // true +true == false // false +10 > 5 // true +``` + +// Mathematische Operationen sind wie gewohnt +``` +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 +6 / 4 // 1 +6.0 / 4 // 1.5 +``` + +// Die Auswertung eines Ausdrucks in der REPL gibt den Typ +// und das Ergebnis zurück. +``` + scala> 1 + 7 + res29: Int = 8 +``` + +Das bedeutet, dass das Resultat der Auswertung von 1 + 7 ein Objekt +von Typ Int ist und einen Wert 0 hat. +"res29" ist ein sequentiell generierter name, um das Ergebnis des +Ausdrucks zu speichern. Dieser Wert kann bei Dir anders sein... + + +"Scala strings werden in doppelten Anführungszeichen eingeschlossen" +'a' // A Scala Char +// 'Einzeln ge-quotete strings gibt es nicht!' <= This causes an error + +// Für Strings gibt es die üblichen Java Methoden +``` +"hello world".length +"hello world".substring(2, 6) +"hello world".replace("C", "3") +``` + +// Zusätzlich gibt es noch extra Scala Methoden +// siehe: scala.collection.immutable.StringOps +``` +"hello world".take(5) +"hello world".drop(5) +``` + +// String interpolation: prefix "s" +``` +val n = 45 +s"We have $n apples" // => "We have 45 apples" +``` + +// Ausdrücke im innern von interpolierten Strings gibt es auch +``` +val a = Array(11, 9, 6) +val n = 100 +s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." +s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." +s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" +``` + +// Formatierung der interpolierten Strings mit dem prefix "f" +``` +f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" +f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" +``` + +// Raw Strings, ignorieren Sonderzeichen. +``` +raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r." +``` + +// Manche Zeichen müssen "escaped" werden, z.B. +// ein doppeltes Anführungszeichen in innern eines Strings. +``` +"They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" +``` + +// Dreifache Anführungszeichen erlauben es, dass ein String über mehrere Zeilen geht +// und Anführungszeichen enthalten kann. +``` +val html = """<form id="daform"> + <p>Press belo', Joe</p> + <input type="submit"> + </form>""" +``` + +# 2. Funktionen + +// Funktionen werden so definiert +// +// def functionName(args...): ReturnType = { body... } +// +// Beachte: Es gibt kein return Schlüsselwort. In Scala ist der letzte Ausdruck +// in einer Funktion der Rückgabewert. +``` +def sumOfSquares(x: Int, y: Int): Int = { + val x2 = x * x + val y2 = y * y + x2 + y2 +} +``` + +// Die geschweiften Klammern können weggelassen werden, wenn +// die Funktion nur aus einem einzigen Ausdruck besteht: +``` +def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y +``` + +// Syntax für Funktionsaufrufe: +``` +sumOfSquares(3, 4) // => 25 +``` + +// In den meisten Fällen (mit Ausnahme von rekursiven Funktionen), können +// Rückgabetypen auch weggelassen werden, da dieselbe Typ Inference, wie bei +// Variablen, auch bei Funktionen greift: +``` +def sq(x: Int) = x * x // Compiler errät, dass der return type Int ist +``` + +// Funktionen können default parameter haben: +``` +def addWithDefault(x: Int, y: Int = 5) = x + y +addWithDefault(1, 2) // => 3 +addWithDefault(1) // => 6 +``` + +// Anonyme Funktionen sehen so aus: +``` +(x: Int) => x * x +``` + +// Im Gegensatz zu def bei normalen Funktionen, kann bei anonymen Funktionen +// sogar der Eingabetyp weggelassen werden, wenn der Kontext klar ist. +// Beachte den Typ "Int => Int", dies beschreibt eine Funktion, +// welche Int als Parameter erwartet und Int zurückgibt. +``` +val sq: Int => Int = x => x * x +``` + +// Anonyme Funktionen benutzt man ganz normal: +``` +sq(10) // => 100 +``` + +// Wenn ein Parameter einer anonymen Funktion nur einmal verwendet wird, +// bietet Scala einen sehr kurzen Weg diesen Parameter zu benutzen, +// indem die Parameter als Unterstrich "_" in der Parameterreihenfolge +// verwendet werden. Diese anonymen Funktionen werden sehr häufig +// verwendet. +``` +val addOne: Int => Int = _ + 1 +val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3) +addOne(5) // => 6 +weirdSum(2, 4) // => 16 +``` + +// Es gibt einen keyword return in Scala. Allerdings ist seine Verwendung +// nicht immer ratsam und kann fehlerbehaftet sein. "return" gibt nur aus +// dem innersten def, welches den return Ausdruck umgibt, zurück. +// "return" hat keinen Effekt in anonymen Funktionen: +``` +def foo(x: Int): Int = { + val anonFunc: Int => Int = { z => + if (z > 5) + return z // Zeile macht z zum return Wert von foo + else + z + 2 // Zeile ist der return Wert von anonFunc + } + anonFunc(x) // Zeile ist der return Wert von foo +} +``` + +# 3. Flow Control + +## Wertebereiche und Schleifen +``` +1 to 5 +val r = 1 to 5 +r.foreach(println) +r foreach println +(5 to 1 by -1) foreach (println) +``` +// Scala ist syntaktisch sehr grosszügig, Semikolons am Zeilenende +// sind optional, beim Aufruf von Methoden können die Punkte +// und Klammern entfallen und Operatoren sind im Grunde austauschbare Methoden + +// while Schleife +``` +var i = 0 +while (i < 10) { println("i " + i); i += 1 } +i // i ausgeben, res3: Int = 10 +``` + +// Beachte: while ist eine Schleife im klassischen Sinne - +// Sie läuft sequentiell ab und verändert die loop-Variable. +// While in Scala läuft schneller ab als in Java und die o.g. +// Kombinatoren und Zusammenlegungen sind einfacher zu verstehen +// und zu parellelisieren. + +// Ein do while Schleife +``` +do { + println("x ist immer noch weniger wie 10") + x += 1 +} while (x < 10) +``` + +// Endrekursionen sind ideomatisch um sich wiederholende +// Dinge in Scala zu lösen. Rekursive Funtionen benötigen explizit einen +// return Typ, der Compiler kann ihn nicht erraten. +// Unit, in diesem Beispiel. +``` +def showNumbersInRange(a: Int, b: Int): Unit = { + print(a) + if (a < b) + showNumbersInRange(a + 1, b) +} +showNumbersInRange(1, 14) +``` + +## Conditionals +``` +val x = 10 +if (x == 1) println("yeah") +if (x == 10) println("yeah") +if (x == 11) println("yeah") +if (x == 11) println ("yeah") else println("nay") +println(if (x == 10) "yeah" else "nope") +val text = if (x == 10) "yeah" else "nope" +``` + +# 4. Daten Strukturen (Array, Map, Set, Tuples) + +## Array +``` +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // Exception +``` + +## Map - Speichert Key-Value-Paare +``` +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // Exception +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") +``` +## Set - Speichert Unikate, unsortiert (sortiert -> SortedSet) +``` +val s = Set(1, 3, 7) +s(0) //false +s(1) //true +val s = Set(1,1,3,3,7) +s: scala.collection.immutable.Set[Int] = Set(1, 3, 7) +``` +## Tuple - Speichert beliebige Daten und "verbindet" sie miteinander +// Ein Tuple ist keine Collection. +``` +(1, 2) +(4, 3, 2) +(1, 2, "three") +(a, 2, "three") +``` + +// Hier ist der Rückgabewert der Funktion ein Tuple +// Die Funktion gibt das Ergebnis, so wie den Rest zurück. +``` +val divideInts = (x: Int, y: Int) => (x / y, x % y) +divideInts(10, 3) +``` + +// Um die Elemente eines Tuples anzusprechen, benutzt man diese +// Notation: _._n wobei n der index des Elements ist (Index startet bei 1) +``` +val d = divideInts(10, 3) +d._1 +d._2 +``` +# 5. Objekt Orientierte Programmierung + +Bislang waren alle gezeigten Sprachelemente einfache Ausdrücke, welche zwar +zum Ausprobieren und Lernen in der REPL gut geeignet sind, jedoch in +einem Scala file selten alleine zu finden sind. +Die einzigen Top-Level Konstrukte in Scala sind nämlich: + +- Klassen (classes) +- Objekte (objects) +- case classes +- traits + +Diesen Sprachelemente wenden wir uns jetzt zu. + +## Klassen + +// Zum Erstellen von Objekten benötigt man eine Klasse, wie in vielen +// anderen Sprachen auch. + +// erzeugt Klasse mit default Konstruktor +``` +class Hund +scala> val t = new Hund +t: Hund = Hund@7103745 +``` + +// Der Konstruktor wird direkt hinter dem Klassennamen deklariert. +``` +class Hund(sorte: String) +scala> val t = new Hund("Dackel") +t: Hund = Hund@14be750c +scala> t.sorte //error: value sorte is not a member of Hund +``` + +// Per val wird aus dem Attribut ein unveränderliches Feld der Klasse +// Per var wird aus dem Attribut ein veränderliches Feld der Klasse +``` +class Hund(val sorte: String) +scala> val t = new Hund("Dackel") +t: Hund = Hund@74a85515 +scala> t.sorte +res18: String = Dackel +``` + +// Methoden werden mit def geschrieben +``` +def bark = "Woof, woof!" +``` + +// Felder und Methoden können public, protected und private sein +// default ist public +// private ist nur innerhalb des deklarierten Bereichs sichtbar +``` +class Hund { + private def x = ... + def y = ... +} +``` + +// protected ist nur innerhalb des deklarierten und aller +// erbenden Bereiche sichtbar +``` +class Hund { + protected def x = ... +} +class Dackel extends Hund { + // x ist sichtbar +} +``` +## Object +Wird ein Objekt ohne das Schlüsselwort "new" instanziert, wird das sog. +"companion object" aufgerufen. Mit dem "object" Schlüsselwort wird so +ein Objekt (Typ UND Singleton) erstellt. Damit kann man dann eine Klasse +benutzen ohne ein Objekt instanziieren zu müssen. +Ein gültiges companion Objekt einer Klasse ist es aber erst dann, wenn +es genauso heisst und in derselben Datei wie die Klasse definiert wurde. +``` +object Hund { + def alleSorten = List("Pitbull", "Dackel", "Retriever") + def createHund(sorte: String) = new Hund(sorte) +} +``` +## Case classes +Fallklassen bzw. Case classes sind Klassen die normale Klassen um extra +Funktionalität erweitern. Mit Case Klassen bekommt man ein paar +Dinge einfach dazu, ohne sich darum kümmern zu müssen. Z.B. +ein companion object mit den entsprechenden Methoden, +Hilfsmethoden wie toString(), equals() und hashCode() und auch noch +Getter für unsere Attribute (das Angeben von val entfällt dadurch) +``` +class Person(val name: String) +class Hund(val sorte: String, val farbe: String, val halter: Person) +``` + +// Es genügt das Schlüsselwort case vor die Klasse zu schreiben. +``` +case class Person(name: String) +case class Hund(sorte: String, farbe: String, halter: Person) +``` + +// Für neue Instanzen brauch man kein "new" +``` +val dackel = Hund("dackel", "grau", Person("peter")) +val dogge = Hund("dogge", "grau", Person("peter")) + +``` +// getter +``` +dackel.halter // => Person = Person(peter) +``` + +// equals +``` +dogge == dackel // => false +``` + +// copy +// otherGeorge == Person("george", "9876") +``` +val otherGeorge = george.copy(phoneNumber = "9876") +``` +## Traits +Ähnlich wie Java interfaces, definiert man mit traits einen Objekttyp +und Methodensignaturen. Scala erlaubt allerdings das teilweise +implementieren dieser Methoden. Konstruktorparameter sind nicht erlaubt. +Traits können von anderen Traits oder Klassen erben, aber nur von +parameterlosen. +``` +trait Hund { + def sorte: String + def farbe: String + def bellen: Boolean = true + def beissen: Boolean +} +class Bernhardiner extends Hund{ + val sorte = "Bernhardiner" + val farbe = "braun" + def beissen = false +} +``` + +``` +scala> b +res0: Bernhardiner = Bernhardiner@3e57cd70 +scala> b.sorte +res1: String = Bernhardiner +scala> b.bellen +res2: Boolean = true +scala> b.beissen +res3: Boolean = false +``` + +// Traits können auch via Mixins (Schlüsselwort "with") eingebunden werden +``` +trait Bellen { + def bellen: String = "Woof" +} +trait Hund { + def sorte: String + def farbe: String +} +class Bernhardiner extends Hund with Bellen{ + val sorte = "Bernhardiner" + val farbe = "braun" +} +scala> val b = new Bernhardiner +b: Bernhardiner = Bernhardiner@7b69c6ba +scala> b.bellen +res0: String = Woof +``` + +# 6. Pattern Matching +Pattern matching in Scala ist ein sehr nützliches und wesentlich +mächtigeres Feature als Vergleichsfunktionen in Java. In Scala +benötigt ein case Statement kein "break", ein fall-through gibt es nicht. +Mehrere Überprüfungen können mit einem Statement gemacht werden. +Pattern matching wird mit dem Schlüsselwort "match" gemacht. +``` +val x = ... +x match { + case 2 => + case 3 => + case _ => +} +``` + +// Pattern Matching kann auf beliebige Typen prüfen +``` +val any: Any = ... +val gleicht = any match { + case 2 | 3 | 5 => "Zahl" + case "woof" => "String" + case true | false => "Boolean" + case 45.35 => "Double" + case _ => "Unbekannt" +} +``` + +// und auf Objektgleichheit +``` +def matchPerson(person: Person): String = person match { + case Person("George", nummer) => "George! Die Nummer ist " + number + case Person("Kate", nummer) => "Kate! Die Nummer ist " + nummer + case Person(name, nummer) => "Irgendjemand: " + name + ", Telefon: " + nummer +} +``` + +// Und viele mehr... +``` +val email = "(.*)@(.*)".r // regex +def matchEverything(obj: Any): String = obj match { + // Werte: + case "Hello world" => "Got the string Hello world" + // Typen: + case x: Double => "Got a Double: " + x + // Conditions: + case x: Int if x > 10000 => "Got a pretty big number!" + // Case Classes: + case Person(name, number) => s"Got contact info for $name!" + // RegEx: + case email(name, domain) => s"Got email address $name@$domain" + // Tuples: + case (a: Int, b: Double, c: String) => s"Got a tuple: $a, $b, $c" + // Strukturen: + case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c" + // Patterns kann man ineinander schachteln: + case List(List((1, 2, "YAY"))) => "Got a list of list of tuple" +} +``` + +// Jedes Objekt mit einer "unapply" Methode kann per Pattern geprüft werden +// Ganze Funktionen können Patterns sein +``` +val patternFunc: Person => String = { + case Person("George", number) => s"George's number: $number" + case Person(name, number) => s"Random person's number: $number" +} +``` + +# 7. Higher-order functions +Scala erlaubt, das Methoden und Funktion wiederum Funtionen und Methoden +als Aufrufparameter oder Return Wert verwenden. Diese Methoden heissen +higher-order functions +Es gibt zahlreiche higher-order functions nicht nur für Listen, auch für +die meisten anderen Collection Typen, sowie andere Klassen in Scala +Nennenswerte sind: +"filter", "map", "reduce", "foldLeft"/"foldRight", "exists", "forall" + +## List +``` +def isGleichVier(a:Int) = a == 4 +val list = List(1, 2, 3, 4) +val resultExists4 = list.exists(isEqualToFour) +``` + +## map +// map nimmt eine Funktion und führt sie auf jedem Element aus und erzeugt +// eine neue Liste + +// Funktion erwartet ein Int und returned ein Int +``` +val add10: Int => Int = _ + 10 +``` + +// add10 wird auf jedes Element angewendet +``` +List(1, 2, 3) map add10 // => List(11, 12, 13) +``` + +// Anonyme Funktionen können anstatt definierter Funktionen verwendet werden +``` +List(1, 2, 3) map (x => x + 10) +``` + +// Der Unterstrich wird anstelle eines Parameters einer anonymen Funktion +// verwendet. Er wird an die Variable gebunden. +``` +List(1, 2, 3) map (_ + 10) +``` + +// Wenn der anonyme Block und die Funtion beide EIN Argument erwarten, +// kann sogar der Unterstrich weggelassen werden. +``` +List("Dom", "Bob", "Natalia") foreach println +``` + +## filter +// filter nimmt ein Prädikat (eine Funktion von A -> Boolean) und findet +// alle Elemente die auf das Prädikat passen +``` +List(1, 2, 3) filter (_ > 2) // => List(3) +case class Person(name: String, age: Int) +List( + Person(name = "Dom", age = 23), + Person(name = "Bob", age = 30) +).filter(_.age > 25) // List(Person("Bob", 30)) +``` + +## reduce +// reduce nimmt zwei Elemente und kombiniert sie zu einem Element, +// und zwar solange bis nur noch ein Element da ist. + +## foreach +// foreach gibt es für einige Collections +``` +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println +``` +## For comprehensions +// Eine for-comprehension definiert eine Beziehung zwischen zwei Datensets. +// Dies ist keine for-Schleife. +``` +for { n <- s } yield sq(n) +val nSquared2 = for { n <- s } yield sq(n) +for { n <- nSquared2 if n < 10 } yield n +for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared +``` + +///////////////////////////////////////////////// +# 8. Implicits +///////////////////////////////////////////////// + +**ACHTUNG:** +Implicits sind ein sehr mächtiges Sprachfeature von Scala. Es sehr einfach +sie falsch zu benutzen und Anfänger sollten sie mit Vorsicht oder am +besten erst dann benutzen, wenn man versteht wie sie funktionieren. +Dieses Tutorial enthält Implicits, da sie in Scala an jeder Stelle +vorkommen und man auch mit einer Lib die Implicits benutzt nichts sinnvolles +machen kann. +Hier soll ein Grundverständnis geschaffen werden, wie sie funktionieren. + +// Mit dem Schlüsselwort implicit können Methoden, Werte, Funktion, Objekte +// zu "implicit Methods" werden. +``` +implicit val myImplicitInt = 100 +implicit def myImplicitFunction(sorte: String) = new Hund("Golden " + sorte) +``` + +// implicit ändert nicht das Verhalten eines Wertes oder einer Funktion +``` +myImplicitInt + 2 // => 102 +myImplicitFunction("Pitbull").sorte // => "Golden Pitbull" +``` + +// Der Unterschied ist, dass diese Werte ausgewählt werden können, wenn ein +// anderer Codeteil einen implicit Wert benötigt, zum Beispiel innerhalb von +// implicit Funktionsparametern + +// Diese Funktion hat zwei Parameter: einen normalen und einen implicit +``` +def sendGreetings(toWhom: String)(implicit howMany: Int) = + s"Hello $toWhom, $howMany blessings to you and yours!" +``` + +// Werden beide Parameter gefüllt, verhält sich die Funktion wie erwartet +``` +sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!" +``` + +// Wird der implicit Parameter jedoch weggelassen, wird ein anderer +// implicit Wert vom gleichen Typ genommen. Der Compiler sucht im +// lexikalischen Scope und im companion object nach einem implicit Wert, +// der vom Typ passt, oder nach einer implicit Methode mit der er in den +// geforderten Typ konvertieren kann. + +// Hier also: "myImplicitInt", da ein Int gesucht wird +``` +sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!" +``` + +// bzw. "myImplicitFunction" +// Der String wird erst mit Hilfe der Funktion in Hund konvertiert, und +// dann wird die Methode aufgerufen +``` +"Retriever".sorte // => "Golden Retriever" +``` + +# 9. Misc +## Importe +``` +import scala.collection.immutable.List +``` + +// Importiere alle Unterpackages +``` +import scala.collection.immutable._ +``` + +// Importiere verschiedene Klassen mit einem Statement +``` +import scala.collection.immutable.{List, Map} +``` + +// Einen Import kann man mit '=>' umbenennen +``` +import scala.collection.immutable.{List => ImmutableList} +``` + +// Importiere alle Klasses, mit Ausnahem von.... +// Hier ohne: Map and Set: +``` +import scala.collection.immutable.{Map => _, Set => _, _} +``` +## Main +``` +object Application { + def main(args: Array[String]): Unit = { + // stuff goes here. + } +} +``` + +## I/O +// Eine Datei Zeile für Zeile lesen +``` +import scala.io.Source +for(line <- Source.fromFile("myfile.txt").getLines()) + println(line) +``` + +// Eine Datei schreiben +``` +val writer = new PrintWriter("myfile.txt") +writer.write("Schreibe Zeile" + util.Properties.lineSeparator) +writer.write("Und noch eine Zeile" + util.Properties.lineSeparator) +writer.close() +``` + +## Weiterführende Hinweise + +// DE +* [Scala Tutorial](https://scalatutorial.wordpress.com) +* [Scala Tutorial](http://scalatutorial.de) + +// EN +* [Scala for the impatient](http://horstmann.com/scala/) +* [Twitter Scala school](http://twitter.github.io/scala_school/) +* [The scala documentation](http://docs.scala-lang.org/) +* [Try Scala in your browser](http://scalatutorials.com/tour/) +* [Neophytes Guide to Scala](http://danielwestheide.com/scala/neophytes.html) +* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) diff --git a/el-gr/css-gr.html.markdown b/el-gr/css-gr.html.markdown new file mode 100644 index 00000000..327dc1a0 --- /dev/null +++ b/el-gr/css-gr.html.markdown @@ -0,0 +1,243 @@ +--- +language: css +contributors: + - ["Kostas Bariotis", "http://kostasbariotis.com"] +filename: css-gr.html.markdown +lang: el-gr +--- + +Η αρχική μορφή του Παγκόσμιου Ιστού αποτελούταν απο καθαρό κείμενο, χωρίς οπτικά αντικείμενα. Με το πέρας +του χρόνου και την εξέλιξη των Φυλλομετρητών, οι πλούσιες σελίδες, σε οπτικά και πολυμεσικά αντικείμενα, +γίναν καθημερινότητα. + +Η CSS μας βοηθάει να διαχωρήσουμε το περιεχόμενο της σελίδας μας (HTML) απο την οπτική της περιγραφή. + +Με την CSS ορίζουμε οπτικές ιδιότητες (χρώμα, μέγεθος, κλπ) σε HTML αντικείμενα (H1, div, κλπ). + +```css +/* Σχόλια εμφανίζονται εντός καθέτου-αστερίσκου, όπως εδώ. + Δεν υπάρχουν σχόλια μια γραμμής και πολλών. */ + +/* #################### + ## ΚΑΝΟΝΕΣ + #################### */ + +/* ένας κανόνας χρησιμοποιείτε για να στοχεύσουμε ένα αντικείμενο (selector). +selector { property: value; /* περισσότερες ιδιότητες...*/ } + +/* +Αυτό είναι ενα παράδειγμα αντικειμένου¨ + +<div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' /> +*/ + +/* Μπορούμε να το στοχεύσουμε με την χρήση CSS κλάσεων */ +.class1 { } + +/* Ή και με τις δύο κλάσεις! */ +.class1.class2 { } + +/* Και με το όνομα του */ +div { } + +/* Ή με το id του */ +#anID { } + +/* Ή με το γεγονός ότι περιέχει ενα attribute */ +[attr] { font-size:smaller; } + +/* Ή οτι το attribute αυτό έχει μια συγκεκριμένη τιμή */ +[attr='value'] { font-size:smaller; } + +/* Ξεκινάει απο το λεκτικό (CSS 3) */ +[attr^='val'] { font-size:smaller; } + +/* Καταλήγει σε αυτο το λεκτικό (CSS 3) */ +[attr$='ue'] { font-size:smaller; } + +/* Περιέχει κάποιο λεκτικό */ +[otherAttr~='foo'] { } +[otherAttr~='bar'] { } + +/* περιέχει το λεκτικό σε λίστα χωρισμένη με παύλες, δηλαδή: "-" (U+002D) */ +[otherAttr|='en'] { font-size:smaller; } + + +/* Μπορούμε να προσθέσουμε μεταξύ τους selectors για να δημιουργήσουμε πιο αυστηρούς. + Δεν βάζουμε κενά ανάμεσα. */ +div.some-class[attr$='ue'] { } + +/* Μπορούμε να επιλέξουμε αντικείμενα που βρίσκονται μέσα σε άλλα. */ +div.some-parent > .class-name { } + +/* Ή κάποιο αντικείμενο απόγονο ανεξαρτήτου του βάθους της σχέσης τους. */ +div.some-parent .class-name { } + +/* ΠΡΟΣΟΧΗ: ο ίδιος selector χωρίς κενά έχει άλλο νόημα. (Άσκηση προς τον αναγνώστη) */ +div.some-parent.class-name { } + +/* Μπορούμε να επιλέξουμε αντικείμενα με βάση το αμέσως επόμενο αντικείμενο στο ίδιο επίπεδο. */ +.i-am-just-before + .this-element { } + +/* Ή οποιοδήποτε αντικείμενο που προηγείται */ +.i-am-any-element-before ~ .this-element { } + +/* Με την βοήθεια των ψευδο-κλάσεων μπορούμε να επιλέξουμε αντικείμενα που βρίσκονται σε μια + ορισμένη κατάασταση. */ + +/* π.χ. όταν ο κέρσορας είναι πάνω απο ένα αντικείμενο */ +selector:hover { } + +/* ή ένας υπερσύνδεσμος που πατήθηκε */ +selector:visited { } + +/* ή που δεν πατήθηκε */ +selected:link { } + +/* ή ένα αντικείμενο που επιλέχθηκε */ +selected:focus { } + +/* οποιοδήποτε αντικείμενο είναι το πρώτο παιδί των γονέων του */ +selector:first-child {} + +/* οποιοδήποτε αντικείμενο είναι το πρώτοτελευταίο παιδί των γονέων του */ +selector:last-child {} + +/* Όπως και με τις ψευδο-κλάσεις, τα ψευδο-αντικείμενα μας επιτρέπουν τα τροποοιήσουμε συγκεκριμένα + κομμάτια της σελίδας */ + +/* επιλέγει το ψευδο-αντικείμενο ακριβώς πριν απο το αντικείμενο */ +selector::before {} + +/* επιλέγει το ψευδο-αντικείμενο ακριβώς μετά απο τον αντικείμενο */ +selector::after {} + +/* Σε σωστά σημεία (όχι πολύ ψηλά στην ιεραρχία) ο αστερίσκος μπορείς να χρησιμοποιηθεί για να + επιλέξουμε όλα τα αντικείμενα */ +* { } /* όλα τα αντικείμενα της σελίδας */ +.parent * { } /* όλους τους απόγονους */ +.parent > * { } /* όλους τους απόγονους πρώτου επιπέδου */ + +/* #################### + ## Ιδιότητες + #################### */ + +selector { + + /* Οι μονάδες μπορούν να είναι είτε απόλυτες είτε σχετικές */ + + /* Σχετικές μονάδες */ + width: 50%; /* ποσοστό επί του πλάτους του γονέα */ + font-size: 2em; /* πολλαπλασιαστής της αρχικής τιμής του αντικειμένου */ + font-size: 2rem; /* ή της τιμής του πρώτου αντικειμένου στην ιεραρχία */ + font-size: 2vw; /* πολλαπλαστιαστής του 1% του οπτικού πλάτους */ + font-size: 2vh; /* ή τους ύψους */ + font-size: 2vmin; /* οποιοδήποτε απο αυτα τα δύο είναι το μικρότερο */ + font-size: 2vmax; /* ή το μεγαλύτερο */ + + /* Απόλυτες μονάδες */ + width: 200px; /* pixels */ + font-size: 20pt; /* στιγμες */ + width: 5cm; /* εκατοστά */ + min-width: 50mm; /* χιλιοστά */ + max-width: 5in; /* ίντσες */ + + /* Χρώματα */ + color: #F6E; /* σύντομη δεκαεξαδική μορφή */ + color: #FF66EE; /* δεκαεξαδική μορφή */ + color: tomato; /* χρώμα με το όνομα του (συγκεκριμένα χρώματα) */ + color: rgb(255, 255, 255); /* τιμή RGB */ + color: rgb(10%, 20%, 50%); /* τιμή RGB με ποσοστά */ + color: rgba(255, 0, 0, 0.3); /* τιμή RGBA (CSS3) σσ. 0 < a < 1 */ + color: transparent; /* όπως και το παραπάνω με a = 0 */ + color: hsl(0, 100%, 50%); /* τιμή hsl με ποσοστά (CSS 3) */ + color: hsla(0, 100%, 50%, 0.3); /* τιμή hsla με ποσοστά και a */ + + /* Εικόνες μπορούν να τοποθετηθούν στον φόντο ενός αντικειμένου */ + background-image: url(/img-path/img.jpg); + + /* Γραμματοσειρές */ + font-family: Arial; + /* εάν η γραμματοσειρα περιέχει κενά */ + font-family: "Courier New"; + /* εάν η πρώτη γραμματοσειρα δε βρεθεί εγκατεστημένη στο Λειτουργικό Σύστυμα, αυτόματα + επιλέγετε η δεύτερη, κ.κ.ε. */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; +} +``` + +## Χρήση + +Αποθηκεύουμε ένα αρχείο CSS με την επέκταση `.css`. + +```xml +<!-- Πρέπει να συμπεριλάβουμε το αρχείο στην επικεφαλίδα(head) ενος HTML αρχείου. + σσ. http://stackoverflow.com/questions/8284365 --> +<link rel='stylesheet' type='text/css' href='path/to/style.css' /> + +<!-- Μπορούμε να το ενσωματώσουμε --> +<style> + a { color: purple; } +</style> + +<!-- Ή απευθείας σε κάποιο αντικείμενο (inline) --> +<div style="border: 1px solid red;"> +</div> +``` + +## Ειδικότητα των κανόνων (Cascading απο το αγγλικό τίτλο Cascading Style Sheets) + +Ένα αντικείμενο μπορεί να στοχευθεί απο πολλούς κανόνες και μπορεί η ίδια ιδιότητα να +περιλαμβάνετε σε πολλούς κανόνες. Σε αυτές της περιπτώσεις υπερισχύει πάντα ο πιο ειδικός +κανόνας και απο αυτούς, αυτός που εμφανίζεται τελευταίος. + +```css +/* A */ +p.class1[attr='value'] + +/* B */ +p.class1 { } + +/* C */ +p.class2 { } + +/* D */ +p { } + +/* E */ +p { property: value !important; } +``` + +```xml +<p style='/*F*/ property:value;' class='class1 class2' attr='value' /> +``` + +Η σειρά θα είναι: + +* `E` έχει μεγαλύτερο βάρος λόγω του `!important`. Κάλες πρακτικές λένε να το αποφεύγουμε. +* `F` επόμενο λόγω του inline κανόνα. +* `A` επόμενο λόγω του το οτι είναι πιο ειδικό. Περιέχει τρεις selectors. +* `C` επόμενο, λόγω του οτι εμφανίζεται μετα το Β και ας έχει την ίδια ειδικότητα. +* `B` επόμενο. +* `D` τελευταίο. + +## Συμβατότητα + +Τα περισσότερα απο τα παραπάνω ήδη υποστηρίζονται απο τους γνωστούς φυλλομετρητές. Άλλα θα πρέπει +πάντα να ελέγχουμε πρωτου τους χρησιμοποιήσουμε. + +## Περισσότερα + +* Έλεγχος συμβατότητας, [CanIUse](http://caniuse.com). +* CSS Playground [Dabblet](http://dabblet.com/). +* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) +* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) + +## Μελέτη + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing +* [CSS-Tricks](https://css-tricks.com) diff --git a/el-gr/racket-gr.html.markdown b/el-gr/racket-gr.html.markdown index 4c4576bb..589adfeb 100644 --- a/el-gr/racket-gr.html.markdown +++ b/el-gr/racket-gr.html.markdown @@ -31,12 +31,12 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ ;; Τα σχόλια S-expression (εκφράσεις S) comments απορρίπτουν την ;; έκφραση που ακολουθεί, δυνατότητα που είναι χρήσιμη για να -;; κάνουμε σχόλια κάποιες εκφράσεις κατα τη διάρκεια του debugging +;; κάνουμε σχόλια κάποιες εκφράσεις κατά τη διάρκεια του debugging #; (αυτή η έκφραση δεν θα εκτελεστεί) ;; (Αν δεν καταλαβαίνεται τι είναι οι εκφράσεις , περιμένετε... Θα το μάθουμε -;; πολύ συντομα!) +;; πολύ σύντομα!) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -57,8 +57,8 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ ;; όπου το f είναι η συνάρτηση και τα x y z ;; είναι οι όροι που η συνάρτηση δέχεται ;; ως ορίσματα. Αν θέλουμε να δημιουργήσουμε -;; μια λίστα στην κυριολεξία απο δίαφορα δεδομένα, -;; χρησιμοποιούμε το ' για να το εμποδίσουμε απο το να +;; μια λίστα στην κυριολεξία από δίαφορα δεδομένα, +;; χρησιμοποιούμε το ' για να το εμποδίσουμε από το να ;; αξιολογηθεί σαν έκφραση. Για παράδειγμα: '(+ 1 2) ; => Παραμένει (+ 1 2) και δεν γίνεται η πράξη ;; Τώρα , ας κάνουμε μερικές πράξεις @@ -88,15 +88,15 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ ;;; Τα αλφαριθμητικά είναι πίνακες χαρακτήρων συγκεκριμένου μήκους "Hello, world!" "Benjamin \"Bugsy\" Siegel" ; Το backslash είναι χαρακτήρας διαφυγής -"Foo\tbar\41\x21\u0021\a\r\n" ; Συμπεριλαμβάνονται οι χαρακτήες διαφυγής της C, +"Foo\tbar\41\x21\u0021\a\r\n" ; Συμπεριλαμβάνονται οι χαρακτήρες διαφυγής της C, ; σε Unicode "λx:(μα.α→α).xx" ; Μπορούν να υπάρχουν και Unicode χαρακτήρες -;; Μπορούμε να εννώσουμε αλφαριθμητικά! +;; Μπορούμε να ενώσουμε αλφαριθμητικά! (string-append "Hello " "world!") ; => "Hello world!" -;; Ένα αλφαριθμητικό μπορούμε να το χρησιμοπιησουμε -;; όπως και μια λίστα απο χαρακτήρες +;; Ένα αλφαριθμητικό μπορούμε να το χρησιμοποιήσουμε +;; όπως και μια λίστα από χαρακτήρες (string-ref "Apple" 0) ; => #\A ;; Παίρνουμε το πρώτο στοιχείο ;; Η συνάρτηση format μπορεί να χρησιμοποιηθεί για @@ -117,18 +117,18 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ some-var ; => 5 ;; Μπορούμε επίσης να χρησιμοποιήσουμε unicode χαρακτήρες. -(define ⊆ subset?) ;; Εδώ ουστιαστικά δίνουμε στη ήδη ύπαρχουσα συνάρτηση subset? +(define ⊆ subset?) ;; Εδώ ουσιαστικά δίνουμε στη ήδη υπάρχουσα συνάρτηση subset? ;; ένα νέο όνομα ⊆ , και παρακάτω την καλούμε με το νέο της όνομα. (⊆ (set 3 2) (set 1 2 3)) ; => #t -;; Αν ζητήσουμε μια μεταβλητή που δεν έχει οριστεί πρίν π.χ +;; Αν ζητήσουμε μια μεταβλητή που δεν έχει οριστεί πριν π.χ. (printf name) ;; θα πάρουμε το παρακάτω μήνυμα ;name: undefined; ; cannot reference undefined identifier ; context...: -;; Η τοπική δέσμευση : `me' δευσμεύεται με το "Bob" μόνο μέσα στο (let ...) +;; Η τοπική δέσμευση : `me' δεσμεύεται με το "Bob" μόνο μέσα στο (let ...) (let ([me "Bob"]) "Alice" me) ; => "Bob" @@ -156,7 +156,7 @@ my-pet ; => #<dog> ;;; Λίστες ;; Οι λίστες είναι linked-list δομές δεδομένων, -;; που έχουν δημιουργηθεί απο ζευγάρια 'cons' +;; που έχουν δημιουργηθεί από ζευγάρια 'cons' ;; και τελειώνουν με 'null' (ή αλλιώς '()) για να ;; δηλώσουν ότι αυτό είναι το τέλος της λίστας (cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3) @@ -191,12 +191,12 @@ my-pet ; => #<dog> ;; Τα διανύσματα είναι πίνακες σταθερού μήκους #(1 2 3) ; => '#(1 2 3) -;; Χρησιμοποιύμε το `vector-append' για να προσθέσουμε διανύσματα +;; Χρησιμοποιούμε το `vector-append' για να προσθέσουμε διανύσματα (vector-append #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) ;;; Σύνολα -;; Δημιουργούμε ένα σύνολο απο μία λίστα +;; Δημιουργούμε ένα σύνολο από μία λίστα (list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3) ;; Προσθέτουμε έναν αριθμό στο σύνολο χρησιμοποιώντας το `set-add' @@ -214,10 +214,10 @@ my-pet ; => #<dog> ;; Δημιουργήστε ένα αμετάβλητο πίνακα κατακερματισμού (define m (hash 'a 1 'b 2 'c 3)) -;; Παίρνουμε μια τιμή απο τον πίνακα +;; Παίρνουμε μια τιμή από τον πίνακα (hash-ref m 'a) ; => 1 -;; Άν ζητήσουμε μια τιμή που δέν υπάρχει παίρνουμε μία εξαίρεση +;; Αν ζητήσουμε μια τιμή που δεν υπάρχει παίρνουμε μία εξαίρεση ; (hash-ref m 'd) => no value found for key ;; Μπορούμε να δώσουμε μια default τιμή για τα κλειδιά που λείπουν @@ -234,7 +234,7 @@ m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3)) m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' ;; Χρησιμοποιούμε το `hash-remove' για να αφαιρέσουμε -;; κλειδία +;; κλειδιά (hash-remove m 'a) ; => '#hash((b . 2) (c . 3)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -247,12 +247,12 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' ;; Μπορούμε επίσης να χρησιμοποιήσουμε το `λ' (λ () "Hello World") ; => Ίδια συνάρτηση -;; Χρησιμοποιύμε τις παρενθέσεις για να καλέσουμε όλες τις συναρτήσεις +;; Χρησιμοποιούμε τις παρενθέσεις για να καλέσουμε όλες τις συναρτήσεις ;; συμπεριλαμβανομένων και των εκφράσεων 'λάμδα' ((lambda () "Hello World")) ; => "Hello World" ((λ () "Hello World")) ; => "Hello World" -;; Εκχωρούμε σε μια μετάβλητη την συνάρτηση +;; Εκχωρούμε σε μια μεταβλητή την συνάρτηση (define hello-world (lambda () "Hello World")) (hello-world) ; => "Hello World" @@ -302,7 +302,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (lambda (name . args) (format "Hello ~a, you passed ~a extra args" name (length args)))) -;; Και με λέξεις κλειδία +;; Και με λέξεις κλειδιά (define (hello-k #:name [name "World"] #:greeting [g "Hello"] . args) (format "~a ~a, ~a extra args" g name (length args))) (hello-k) ; => "Hello World, 0 extra args" @@ -347,7 +347,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (eq? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f -;; Το `eqv?' υποστηρίζει την σύκριση αριθμών αλλα και χαρακτήρων +;; Το `eqv?' υποστηρίζει την σύγκριση αριθμών αλλά και χαρακτήρων ;; Για άλλα ήδη μεταβλητών το `eqv?' και το `eq?' επιστρέφουν το ίδιο. (eqv? 3 3.0) ; => #f (eqv? (expt 2 100) (expt 2 100)) ; => #t @@ -365,12 +365,12 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (equal? (list 3) (list 3)) ; => #t ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 5. Έλεχγος Ροής +;; 5. Έλεγχος Ροής ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Συνθήκες (conditionals) -(if #t ; έκφραση ελέχγου +(if #t ; έκφραση ελέγχου "this is true" ; έκφραση then "this is false") ; έκφραση else ; => "this is true" @@ -483,7 +483,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (values i (number->string i))) ; => '#hash((1 . "1") (2 . "2") (3 . "3")) -;; Υπάρχουν πολλά είδη απο προϋπάρχοντες τρόπους για να συλλέγουμε +;; Υπάρχουν πολλά είδη από προϋπάρχοντες τρόπους για να συλλέγουμε ;; τιμές από τους βρόχους (for/sum ([i 10]) (* i i)) ; => 285 @@ -491,7 +491,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (for/and ([i 10] [j (in-range 10 20)]) (< i j)) ; => #t (for/or ([i 10] [j (in-range 0 20 2)]) (= i j)) ; => #t -;; Και για να χρησιμοποιήσουμε ένα αφθαίρετο συνδιασμό χρησιμοποιούμε +;; Και για να χρησιμοποιήσουμε ένα αυθαίρετο συνδυασμό χρησιμοποιούμε ;; το 'for/fold' (for/fold ([sum 0]) ([i '(1 2 3 4)]) (+ sum i)) ; => 10 @@ -524,17 +524,17 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (set! n (add1 n)) n ; => 6 -;; Χρησιμοποιούμε τα boxes για να δηλώσουμε ρητά ότι μια μεταβητή -;; θα είναι mutable (θα μπορεί να αλλάξη η τιμή της) +;; Χρησιμοποιούμε τα boxes για να δηλώσουμε ρητά ότι μια μεταβλητή +;; θα είναι mutable (θα μπορεί να αλλάξει η τιμή της) ;; Αυτό είναι παρόμοιο με τους pointers σε άλλες γλώσσες (define n* (box 5)) (set-box! n* (add1 (unbox n*))) (unbox n*) ; => 6 -;; Πολλοί τύποι μεταβλητών στη Racket είναι αμετάβλητοι πχ τα ζεύγη, οι +;; Πολλοί τύποι μεταβλητών στη Racket είναι αμετάβλητοι π.χ. τα ζεύγη, οι ;; λίστες κτλ. Άλλοι υπάρχουν και σε μεταβλητή και σε αμετάβλητη μορφή -;; πχ αλφαριθμητικά, διανύσματα κτλ +;; π.χ. αλφαριθμητικά, διανύσματα κτλ. (define vec (vector 2 2 3 4)) (define wall (make-vector 100 'bottle-of-beer)) ;; Χρησιμοποιούμε το 'vector-set!' για να ανεώσουμε κάποια @@ -579,7 +579,7 @@ vec ; => #(1 2 3 4) (printf fmt (make-string n ch)) (newline))) -;; Χρησιμοποιομε το 'require' για να πάρουμε όλα τα +;; Χρησιμοποιουμε το 'require' για να πάρουμε όλα τα ;; παρεχόμενα ονόματα από μία ενότητα (require 'cake) ; το ' είναι για τοπική υποενότητα (print-cake 3) @@ -634,7 +634,7 @@ vec ; => #(1 2 3 4) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Οι μακροεντολές μας επιτρέπουν να επεκτείνουμε -;; το συντακτικό μιάς γλώσσας. +;; το συντακτικό μιας γλώσσας. ;; Ας προσθέσουμε έναν βρόχο while (define-syntax-rule (while condition body ...) @@ -664,20 +664,20 @@ vec ; => #(1 2 3 4) ;; (set! tmp other) ;; (set! other tmp_1)) -;; Αλλά ακόμα υπάρχουν ακόμη μετασχηματισμοί του κώδικα, π.χ: +;; Αλλά ακόμα υπάρχουν ακόμη μετασχηματισμοί του κώδικα, π.χ.: (define-syntax-rule (bad-while condition body ...) (when condition body ... (bad-while condition body ...))) -;; αυτή η μακροεντολή είναι χαλασμένη: δημιουγεί ατέρμονα βρόχο +;; αυτή η μακροεντολή είναι χαλασμένη: δημιουργεί ατέρμονα βρόχο ;; και αν προσπαθήσουμε να το χρησιμοποιήσουμε, ο μεταγλωττιστής -;; θα μπεί στον ατέρμονα βρόχο. +;; θα μπει στον ατέρμονα βρόχο. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 10. Συμβόλαια (Contracts) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; Τα συμβόλαια βάζουν περιορισμόυς σε τιμές που προέρχονται +;; Τα συμβόλαια βάζουν περιορισμούς σε τιμές που προέρχονται ;; από ενότητες (modules) (module bank-account racket (provide (contract-out @@ -719,7 +719,7 @@ vec ; => #(1 2 3 4) (displayln "Hola mundo" out-port) (close-output-port out-port) -;; Διαβάζουμε απο αρχείο ξανά +;; Διαβάζουμε από αρχείο ξανά (define in-port (open-input-file "/tmp/tmp.txt")) (displayln (read-line in-port)) ; => "Hello World" diff --git a/el-gr/scala-gr.html.markdown b/el-gr/scala-gr.html.markdown index e29c7e70..415fda5c 100644 --- a/el-gr/scala-gr.html.markdown +++ b/el-gr/scala-gr.html.markdown @@ -40,7 +40,7 @@ Scala - Η επεκτάσιμη γλώσσα /* Τα σχόλια που επεκτείνονται σε πολλές γραμμές , όπως μπορείτε - να δείτε , φαίνοται κάπως έτσι. + να δείτε , φαίνονται κάπως έτσι. */ // Εκτύπωση με νέα γραμμή στην επόμενη εκτύπωση @@ -59,12 +59,12 @@ var y = 10 y = 20 // το y είναι τώρα 20 /* - Η Scala είναι στατικού τύπου γλώσσα, εν τούτις προσέξτε ότι στις παραπάνω + Η Scala είναι στατικού τύπου γλώσσα, εν τούτοις προσέξτε ότι στις παραπάνω δηλώσεις , δεν προσδιορίσαμε κάποιον τύπο. Αυτό συμβαίνει λόγω ενός χαρακτηριστικού της Scala που λέγεται συμπερασματολογία τύπων. Στις περισσότερες των περιπτώσεων, ο μεταγλωττιστής της Scala μπορεί να - μαντέψει ποιός είναι ο τύπος μιας μεταβλητής. Μπορούμε να δηλώσουμε - αναλυτικά τον τύπο μιάς μεταβλητής ως εξής: + μαντέψει ποιος είναι ο τύπος μιας μεταβλητής. Μπορούμε να δηλώσουμε + αναλυτικά τον τύπο μιας μεταβλητής ως εξής: */ val z: Int = 10 val a: Double = 1.0 @@ -85,7 +85,7 @@ false true == false // false 10 > 5 // true -// Η αριθμιτική είναι όπως τα συνηθισμένα +// Η αριθμητική είναι όπως τα συνηθισμένα 1 + 1 // 2 2 - 1 // 1 5 * 3 // 15 @@ -117,14 +117,14 @@ true == false // false "Τα αλφαριθμητικά στην Scala περικλείονται από διπλά εισαγωγικά" 'a' // Ένας χαρακτήρας στην Scala // res30: Char = a -// 'Αλφαριθημτικά με μονά εισαγωγικά δεν υφίστανται <= Αυτό θα προκαλέσει σφάλμα. +// Αλφαριθημτικά με μονά εισαγωγικά δεν υφίστανται <= Αυτό θα προκαλέσει σφάλμα. // Τα αλφαριθμητικά έχουν τις συνηθισμένες μεθόδους της Java ορισμένες πάνω τους. "hello world".length "hello world".substring(2, 6) "hello world".replace("C", "3") -// Έχουν επίσης μερικές επιπλένον μεθόδους Scala. +// Έχουν επίσης μερικές επιπλέον μεθόδους Scala. // Δείτε επίσης : scala.collection.immutable.StringOps "hello world".take(5) "hello world".drop(5) @@ -253,7 +253,7 @@ r foreach println var i = 0 while (i < 10) { println("i " + i); i+=1 } -while (i < 10) { println("i " + i); i+=1 } // Ναι ξανά! Τι συνέβει; Γιατί; +while (i < 10) { println("i " + i); i+=1 } // Ναι ξανά! Τι συνέβη; Γιατί; i // Εμφάνισε την τιμή του i. Σημειώστε ότι ένας βρόχος while είναι βρόχος // με την κλασική έννοια - εκτελείται σειριακά καθώς αλλάζει η μεταβλητή @@ -268,8 +268,8 @@ do { } while (x < 10) // Η αναδρομή ουράς είναι ένας ιδιωματικός τρόπος να κάνεις επαναλαμβανόμενα -// πράγματα στην Scala. Οι αναδρομικές συναρτήσεις απαιτούν να γράφτεί -// ρητά ο τύπος που θα επιστρέψουν , αλλιώς ο μεταγλωττιστής δεν μπορεί +// πράγματα στην Scala. Οι αναδρομικές συναρτήσεις απαιτούν να γραφτεί +// ρητά ο τύπος που θα επιστρέψουν, αλλιώς ο μεταγλωττιστής δεν μπορεί // αλλιώς να τον συνάγει. Παρακάτω είναι μια συνάρτηση που επιστρέφει Unit. def showNumbersInRange(a:Int, b:Int):Unit = { print(a) @@ -332,7 +332,7 @@ s(1) val divideInts = (x:Int, y:Int) => (x / y, x % y) divideInts(10,3) // Η συνάρτηση divideInts επιστρέφει το αποτέλεσμα - // της ακαίρεας διαίρεσης και το υπόλοιπο. + // της ακέραιας διαίρεσης και το υπόλοιπο. // Για να έχουμε πρόσβαση στα στοιχεία μιας πλειάδας, χρησιμοποιούμε το _._n // όπου το n είναι ο δείκτης με βάση το 1 του στοιχείου. @@ -349,7 +349,7 @@ d._2 /* Ότι έχουμε κάνει ως τώρα σε αυτό το tutorial ήταν απλές εκφράσεις - (τιμές , συναρτήσεις , κτλ). Αυτές οι εκφράσεις βολεύουν όταν τις + (τιμές, συναρτήσεις, κτλ.). Αυτές οι εκφράσεις βολεύουν όταν τις γράφουμε στο REPL για γρήγορες δοκιμές, αλλά δεν μπορούν να υπάρχουν από μόνες τους σε ένα αρχείο Scala. Για παράδειγμα , δεν μπορούμε να έχουμε μόνο ένα "val x = 5" στο αρχείο Scala. Αντί αυτού , τα μόνα @@ -394,7 +394,7 @@ println(mydog.bark) // => "Woof, woof!" // αυτές καθ' αυτές, αλλά η συμπρεριφορά που σχετίζεται με όλα τα instances // της κλάσης πάνε μέσα στο object. Η διαφορά είναι παρόμοια με τις // μεθόδους κλάσεων σε σχέση με στατικές μεθόδους σε άλλες γλώσσες. -// Προσέξτε οτι τα objects και οι κλάσεις μπορούν να έχουν το ίδιο όνομα. +// Προσέξτε ότι τα objects και οι κλάσεις μπορούν να έχουν το ίδιο όνομα. object Dog { def allKnownBreeds = List("pitbull", "shepherd", "retriever") def createDog(breed: String) = new Dog(breed) @@ -402,7 +402,7 @@ object Dog { // Οι κλάσεις περίπτωσης (case classes) είναι που έχουν την επιπλέον // λειτουργικότητα ενσωματωμένη. Μιά συνήθης ερώτηση για αρχάριους στην -// Scala είναι πότε να χρησιμοπούνται κλάσεις και πότε case κλάσεις. +// Scala είναι πότε να χρησιμοποιούνται κλάσεις και πότε case κλάσεις. // Γενικά οι κλάσεις τείνουν να εστιάζουν στην ενθυλάκωση, τον // πολυμορφισμό και τη συμπεριφορά. Οι τιμές μέσα σε αυτές τις κλάσεις // τείνουν να είναι private , και μόνο οι μέθοδοι είναι εκτεθειμένες. @@ -411,7 +411,7 @@ object Dog { // έχουν παρενέργειες. case class Person(name: String, phoneNumber: String) -// Δημιουργία ενός instance. Πραρατηρήστε ότι τα case classes +// Δημιουργία ενός instance. Παρατηρήστε ότι τα case classes // δεν χρειάζονται την λέξη "new" . val george = Person("George", "1234") val kate = Person("Kate", "4567") @@ -419,7 +419,7 @@ val kate = Person("Kate", "4567") // Με τα case classes, παίρνεις μερικά προνόμια δωρεάν , όπως: george.phoneNumber // => "1234" -// Ελέχγεται η ισότητα για κάθε πεδίο (δεν χρειάζεται να +// Ελέγχεται η ισότητα για κάθε πεδίο (δεν χρειάζεται να // κάνουμε override στο .equals) Person("George", "1234") == Person("Kate", "1236") // => false @@ -509,7 +509,7 @@ List(1, 2, 3) map (x => x + 10) // ένα όρισμα στην ανώνυμη συνάρτηση. Έτσι δεσμεύεται ως η μεταβλητή. List(1, 2, 3) map (_ + 10) -// Αν το μπλόκ της ανώνυμης συνάρτησης ΚΑΙ η συνάρτηση που εφαρμόζεται +// Αν το μπλοκ της ανώνυμης συνάρτησης ΚΑΙ η συνάρτηση που εφαρμόζεται // (στην περίπτωσή μας το foreach και το println) παίρνουν ένα όρισμα // μπορείτε να παραλείψετε την κάτω παύλα. List("Dom", "Bob", "Natalia") foreach println diff --git a/elixir.html.markdown b/elixir.html.markdown index c8599838..eedeb227 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -369,6 +369,13 @@ spawn(f) #=> #PID<0.40.0> # messages to the process. To do message passing we use the `send` operator. # For all of this to be useful we need to be able to receive messages. This is # achieved with the `receive` mechanism: + +# The `receive do` block is used to listen for messages and process +# them when they are received. A `receive do` block will only +# process one received message. In order to process multiple +# messages, a function with a `receive do` block must recursively +# call itself to get into the `receive do` block again. + defmodule Geometry do def area_loop do receive do @@ -384,6 +391,8 @@ end # Compile the module and create a process that evaluates `area_loop` in the shell pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> +# Alternatively +pid = spawn(Geometry, :area_loop, []) # Send a message to `pid` that will match a pattern in the receive statement send pid, {:rectangle, 2, 3} diff --git a/es-es/amd-es.html.markdown b/es-es/amd-es.html.markdown new file mode 100644 index 00000000..7a59ddd6 --- /dev/null +++ b/es-es/amd-es.html.markdown @@ -0,0 +1,214 @@ +--- + +category: tool +tool: amd +contributors: + - ["Frederik Ring", "https://github.com/m90"] + +translators: + - ["Damaso Sanoja", "https://github.com/damasosanoja"] +filename: learnamd-es.js +lang: es-es +--- + +## Iniciando con AMD + +El API del **Módulo de Definición Asíncrono** especifica un mecanismo para definir módulos JavaScript de manera tal que tanto el módulo como sus dependencias puedan ser cargadas de manera asíncrona. Esto es particularmente adecuado para el entorno del navegador donde la carga sincronizada de los módulos genera problemas de rendimiento, usabilidad, depuración y acceso de multi-dominios. + +### Conceptos básicos +```javascript +// El API básico de AMD consiste en tan solo dos métodos: `define` y `require` +// y se basa en la definición y consumo de los módulos: +// `define(id?, dependencias?, fábrica)` define un módulo +// `require(dependencias, callback)` importa un conjunto de dependencias y +// las consume al invocar el callback + +// Comencemos usando define para definir un nuevo módulo +// que no posee dependencias. Lo haremos enviando un nombre +// y una función fábrica para definirla: +define('awesomeAMD', function(){ + var isAMDAwesome = function(){ + return true; + }; + // El valor que regresa la función fábrica del módulo será + // lo que los otros módulos o llamados require recibirán cuando + // soliciten nuestro módulo `awesomeAMD`. + // El valor exportado puede ser cualquier cosa, funciones (constructores), + // objetos, primitivos, incluso indefinidos (aunque eso no ayuda mucho). + return isAMDAwesome; +}); + +// Ahora definamos otro módulo que dependa de nuestro módulo `awesomeAMD`. +// Observe que ahora hay un argumento adicional que define +// las dependencias de nuestro módulo: +define('loudmouth', ['awesomeAMD'], function(awesomeAMD){ + // las dependencias serán enviadas a los argumentos de la fábrica + // en el orden que sean especificadas + var tellEveryone = function(){ + if (awesomeAMD()){ + alert('This is sOoOo rad!'); + } else { + alert('Pretty dull, isn\'t it?'); + } + }; + return tellEveryone; +}); + +// Como ya sabemos utilizar define usemos ahora `require` para poner en marcha +// nuestro programa. La firma de `require` es `(arrayOfDependencies, callback)`. +require(['loudmouth'], function(loudmouth){ + loudmouth(); +}); + +// Para hacer que este tutorial corra código, vamos a implementar una +// versión muy básica (no-asíncrona) de AMD justo aquí: +function define(name, deps, factory){ + // observa como son manejados los módulos sin dependencias + define[name] = require(factory ? deps : [], factory || deps); +} + +function require(deps, callback){ + var args = []; + // primero recuperemos todas las dependencias que necesita + // el llamado require + for (var i = 0; i < deps.length; i++){ + args[i] = define[deps[i]]; + } + // satisfacer todas las dependencias del callback + return callback.apply(null, args); +} +// puedes ver este código en acción aquí: http://jsfiddle.net/qap949pd/ +``` + +### Uso en el mundo real con require.js + +En contraste con el ejemplo introductorio, `require.js` (la librería AMD más popular) implementa la **A** de **AMD**, permitiéndote cargar los módulos y sus dependencias asincrónicamente via XHR: + +```javascript +/* file: app/main.js */ +require(['modules/someClass'], function(SomeClass){ + // el callback es diferido hasta que la dependencia sea cargada + var thing = new SomeClass(); +}); +console.log('So here we are, waiting!'); // esto correrá primero +``` + +Por convención, usualmente guardas un módulo en un fichero. `require.js` puede resolver los nombres de los módulos basados en rutas de archivo, de forma que no tienes que nombrar tus módulos, simplemente referenciarlos usando su ubicación. En el ejemplo `someClass` asumimos que se ubica en la carpeta `modules`, relativa a tu `baseUrl` configurada: + +* app/ + * main.js + * modules/ + * someClass.js + * someHelpers.js + * ... + * daos/ + * things.js + * ... + +Esto significa que podemos definir `someClass` sin especificar su id de módulo: + +```javascript +/* file: app/modules/someClass.js */ +define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){ + // definición de módulo, por supuesto, ocurrirá también asincrónicamente + function SomeClass(){ + this.method = function(){/**/}; + // ... + } + return SomeClass; +}); +``` + +Para alterar el comportamiento del mapeo de ruta usa `requirejs.config(configObj)` en tu `main.js`: + +```javascript +/* file: main.js */ +requirejs.config({ + baseUrl : 'app', + paths : { + // también puedes cargar módulos desde otras ubicaciones + jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}); +require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolLib, helpers){ + // un fichero `main` necesita llamar a require al menos una vez, + // de otra forma jamás correrá el código + coolLib.doFancyStuffWith(helpers.transform($('#foo'))); +}); +``` +Las aplicaciones basadas en `require.js` usualmente tendrán un solo punto de entrada (`main.js`) que se pasa a la etiqueta del script `require.js` como un atributo de datos. Será cargado y ejecutado automáticamente al cargar la página: + +```html +<!DOCTYPE html> +<html> +<head> + <title>Cien etiquetas de script? Nunca más!</title> +</head> +<body> + <script src="require.js" data-main="app/main"></script> +</body> +</html> +``` + +### Optimizar todo un proyecto usando r.js + +Muchas personas prefieren usar AMD para la organización del código durante el desarrollo, pero quieren enviar para producción un solo fichero en vez de ejecutar cientos de XHRs en las cargas de página. + +`require.js` incluye un script llamado `r.js` (el que probablemente correrás en node.js, aunque Rhino también es soportado) que puede analizar el gráfico de dependencias de tu proyecto, y armar un solo fichero que contenga todos tus módulos (adecuadamente nombrados), minificado y listo para consumo. + +Instálalo usando `npm`: +```shell +$ npm install requirejs -g +``` + +Ahora puedes alimentarlo con un fichero de configuración: +```shell +$ r.js -o app.build.js +``` + +Para nuestro ejemplo anterior el archivo de configuración luciría así: +```javascript +/* file : app.build.js */ +({ + name : 'main', // nombre del punto de entrada + out : 'main-built.js', // nombre del fichero donde se escribirá la salida + baseUrl : 'app', + paths : { + // `empty:` le dice a r.js que esto aún debe ser cargado desde el CDN, usando + // la ubicación especificada en `main.js` + jquery : 'empty:', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}) +``` + +Para usar el fichero creado en producción, simplemente intercambia `data-main`: +```html +<script src="require.js" data-main="app/main-built"></script> +``` + +Un increíblemente detallado [resumen de opciones de generación](https://github.com/jrburke/r.js/blob/master/build/example.build.js) está disponible en el repositorio de GitHub. + +### Tópicos no cubiertos en este tutorial +* [Cargador de plugins / transformaciones](http://requirejs.org/docs/plugins.html) +* [Cargando y exportando estilos CommonJS](http://requirejs.org/docs/commonjs.html) +* [Configuración avanzada](http://requirejs.org/docs/api.html#config) +* [Configuración de Shim (cargando módulos no-AMD)](http://requirejs.org/docs/api.html#config-shim) +* [Cargando y optimizando CSS con require.js](http://requirejs.org/docs/optimization.html#onecss) +* [Usando almond.js para construcciones](https://github.com/jrburke/almond) + +### Otras lecturas: + +* [Especificaciones oficiales](https://github.com/amdjs/amdjs-api/wiki/AMD) +* [¿Por qué AMD?](http://requirejs.org/docs/whyamd.html) +* [Definición Universal de Módulos](https://github.com/umdjs/umd) + +### Implementaciones: + +* [require.js](http://requirejs.org) +* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) +* [cujo.js](http://cujojs.com/) +* [curl.js](https://github.com/cujojs/curl) +* [lsjs](https://github.com/zazl/lsjs) +* [mmd](https://github.com/alexlawrence/mmd) diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index 036d7082..d475cf42 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -16,7 +16,7 @@ con Java para aplicaciones más complejas. Debido a su integracion estrecha con web y soporte por defecto de los navegadores modernos se ha vuelto mucho más común para front-end que Java. -JavaScript no sólo se limita a los navegadores web, aunque: Node.js, Un proyecto que proporciona un entorno de ejecución independiente para el motor V8 de Google Chrome, se está volviendo más y más popular. +Aunque JavaScript no sólo se limita a los navegadores web: Node.js, Un proyecto que proporciona un entorno de ejecución independiente para el motor V8 de Google Chrome, se está volviendo más y más popular. ¡La retroalimentación es bienvenida! Puedes encontrarme en: [@adambrenecki](https://twitter.com/adambrenecki), o @@ -124,7 +124,7 @@ undefined; // usado para indicar que un valor no está presente actualmente // (aunque undefined es un valor en sí mismo) // false, null, undefined, NaN, 0 y "" es false; todo lo demás es true. -// Note que 0 is false y "0" es true, a pesar de que 0 == "0". +// Note que 0 es false y "0" es true, a pesar de que 0 == "0". // Aunque 0 === "0" sí es false. /////////////////////////////////// diff --git a/es-es/tmux-es.html.markdown b/es-es/tmux-es.html.markdown new file mode 100644 index 00000000..a7354be1 --- /dev/null +++ b/es-es/tmux-es.html.markdown @@ -0,0 +1,253 @@ +--- +category: tool +tool: tmux +contributors: + - ["mdln", "https://github.com/mdln"] +filename: LearnTmux-es.txt +translators: + - ["Damaso Sanoja", "https://github.com/damasosanoja"] +lang: es-es +--- + + +[tmux](http://tmux.sourceforge.net) +es un terminal multiplexor: habilita la creación, acceso y control +de múltiples terminales controlados desde una sola pantalla. tmux +puede ser separado de una pantalla y continuar corriendo en el fondo +y luego ser insertado nuevamente. + + +``` + + tmux [command] # Corre un comando + # 'tmux' sin comandos creará una nueva sesión + + new # Crea una nueva sesión + -s "Session" # Crea sesión con nombre + -n "Window" # Crea ventana con nombre + -c "/dir" # Comienza en el directorio destino + + attach # Adjunta sesión última/disponible + -t "#" # Adjunta sesión destino + -d # Separa la sesión de otras instancias + + ls # Lista las sesiones abiertas + -a # Lista todas las sesiones abiertas + + lsw # Lista las ventanas + -a # Lista todas las ventanas + -s # Lista todas las ventanas en la sesión + + lsp # Lista los páneles + -a # Lista todos los páneles + -s # Lista todos los páneles de la sesión + -t # Lista los páneles de aplicación en el destino + + kill-window # Cierra la ventana actual + -t "#" # Cierra la ventana destino + -a # Cierra todas las ventanas + -a -t "#" # Cierra todas las ventanas menos el destino + + kill-session # Cierra la sesión actual + -t "#" # Cierra la sesión destino + -a # Cierra todas las sesiones + -a -t "#" # Cierra todas las sesiones menos el destino + +``` + + +### Atajos de Teclado + +El método para controlar una sesión adjunta tmux es mediante +combinaciones de teclas llamadas teclas 'Prefijo'. + +``` +---------------------------------------------------------------------- + (C-b) = Ctrl + b # combinación 'Prefijo' necesaria para usar atajos + + (M-1) = Meta + 1 -o- Alt + 1 +---------------------------------------------------------------------- + + ? # Lista todos los atajos de teclado + : # Entra en la línea de comandos tmux + r # Fuerza el redibujado del cliente adjuntado + c # Crea una nueva ventana + + ! # Separa el panel actual fuera de la ventana. + % # Separa el panel actual en dos, izquierdo y derecho + " # Separa el panel actual en dos, superior e inferior + + n # Cambia a la siguiente ventana + p # Cambia a la ventana previa + { # Intercambia el panel actual con el anterior + } # Intercambia el panel actual con el próximo + + s # Selecciona una nueva sesión para el cliente adjuntado + interactivamente + w # Elegir la ventana actual interactivamente + 0 al 9 # Seleccionar ventanas 0 al 9 + + d # Separa el cliente actual + D # Elige un cliente para separar + + & # Cierra la ventana actual + x # Cierra el panel actual + + Up, Down # Cambia al panel superior, inferior, izquierdo, o derecho + Left, Right + + M-1 to M-5 # Organizar páneles: + # 1) uniformes horizontales + # 2) uniformes verticales + # 3) principal horizontal + # 4) principal vertical + # 5) mozaico + + C-Up, C-Down # Redimensiona el panel actual en pasos de una celda + C-Left, C-Right + + M-Up, M-Down # Redimensiona el panel actual en pasos de cinco celdas + M-Left, M-Right + +``` + + +### Configurando ~/.tmux.conf + +tmux.conf puede usarse para establecer opciones automáticas al arrancar, parecido a como .vimrc o init.el hacen. + +``` +# Ejemplo de tmux.conf +# 2014.10 + + +### General +########################################################################### + +# Habilita UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Fuera de pantalla/Historia límite +set -g history-limit 2048 + +# Comienzo de índice +set -g base-index 1 + +# Ratón +set-option -g mouse-select-pane on + +# Forza recarga de fichero de configuración +unbind r +bind r source-file ~/.tmux.conf + + +### Atajos de teclado +########################################################################### + +# Desvincula C-b como el prefijo por defecto +unbind C-b + +# Establece el nuevo prefijo +set-option -g prefix ` + +# Regresa a la ventana previa cuando el prefijo es accionado dos veces +bind C-a last-window +bind ` last-window + +# Permite intercambiar C-a y ` usando F11/F12 +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` + +# Preferencias de atajos +setw -g mode-keys vi +set-option -g status-keys vi + +# Moviéndose entre paneles con movimientos de teclas vim +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R + +# Ciclo/Intercambio de Ventana +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +# División rápida de paneles +bind = split-window -h +bind - split-window -v +unbind '"' +unbind % + +# Activar sesión mas interna (cuando se anida tmux) para enviar comandos +bind a send-prefix + + +### Temas +########################################################################### + +# Paleta de Colores de la Barra de estado +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +# Paleta de Colores del Borde del Panel +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +# Paleta de Colores de Mensajes +set-option -g message-fg black +set-option -g message-bg green + +# Paleta de Colores de la Ventana +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +# Notificación +setw -g monitor-activity on +set -g visual-activity on +set-option -g bell-action any +set-option -g visual-bell off + +# Establece automáticamente títulos de ventanas +set-option -g set-titles on +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) + +# Ajustes de barra de estado +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" + +# Muestra indicadores de rendimiento en barra de estado +# Requiere https://github.com/thewtex/tmux-mem-cpu-load/ +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + + +### Referencias + +[Tmux | Inicio](http://tmux.sourceforge.net) + +[Tmux Manual](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) + +[Mostrar CPU/MEM % en barra de estado](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) diff --git a/fr-fr/clojure-fr.html.markdown b/fr-fr/clojure-fr.html.markdown index d3c5a67b..63bc25b5 100644 --- a/fr-fr/clojure-fr.html.markdown +++ b/fr-fr/clojure-fr.html.markdown @@ -248,7 +248,7 @@ keymap ; => {:a 1, :b 2, :c 3} ; Il y a encore d'autres fonctions dans l'espace de nom clojure.sets. -; Formes utiles +; Formes et macros utiles ;;;;;;;;;;;;;;; ; Les constructions logiques en Clojure sont juste des macros, et @@ -275,6 +275,33 @@ ressemblent à toutes les autres formes: (let [name "Urkel"] (print "Saying hello to " name) (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") + +; Utilisez les Threading Macros (-> et ->>) pour exprimer plus +; clairement vos transformations, en y pensant de manière multi-niveaux. + +; La "flèche simple" ou "Thread-first", insère, à chaque niveau +; de la transformation, la forme courante en la seconde position +; de la forme suivante, constituant à chaque fois un nouvel étage +; de transformation. Par exemple: +(-> + {:a 1 :b 2} + (assoc :c 3) ;=> Génère ici (assoc {:a 1 :b 2} :c 3) + (dissoc :b)) ;=> Génère ici (dissoc (assoc {:a 1 :b 2} :c 3) :b) + +; Cette expression est ré-écrite en: +; (dissoc (assoc {:a 1 :b 2} :c 3) :b) +; et est évaluée en : {:a 1 :c 3} + +; La "flèche double" ou "Thread-last" procède de la même manière +; que "->", mais insère le résultat de la réécriture de chaque +; étage en dernière position. Par exemple: +(->> + (range 10) + (map inc) ;=> Génère ici (map inc (range 10) + (filter odd?) ;=> Génère ici (filter odd? (map inc (range 10)) + (into [])) ;=> Génère ici (into [] (filter odd? (map inc (range 10))), ce qui est évalué au final à; + ; [1 3 5 7 9] + ; Modules ;;;;;;;;;;;;;;; diff --git a/fr-fr/haml-fr.html.markdown b/fr-fr/haml-fr.html.markdown index 0267a380..24be8bf9 100644 --- a/fr-fr/haml-fr.html.markdown +++ b/fr-fr/haml-fr.html.markdown @@ -4,6 +4,7 @@ filename: learnhaml.haml contributors: - ["Simon Neveu", "https://github.com/sneveu"] - ["Thibault", "https://github.com/iTech-"] +lang: fr-fr --- Haml est un langage de balisage utilisé majoritairement avec Ruby, qui décrit de manière simple et propre le HTML de n'importe quelle page web sans l'utilisation des traditionnelles lignes de code. Le langage est une alternative très populaire au langage de templates Rails (.erb) et permet d'intégrer du code en Ruby dans votre balisage. diff --git a/git.html.markdown b/git.html.markdown index 72079f6c..f678f9d1 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -5,6 +5,7 @@ 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"] filename: LearnGit.txt --- @@ -76,6 +77,11 @@ other repositories, or not! A branch is essentially a pointer to the last commit you made. As you go on committing, this pointer will automatically update to point the latest commit. +### Tag + +A tag is a mark on specific point in history. Typically people use this +functionality to mark release points (v1.0, and so on) + ### HEAD and head (component of .git dir) HEAD is a pointer that points to the current branch. A repository only has 1 *active* HEAD. @@ -206,6 +212,28 @@ $ git branch -m myBranchName myNewBranchName $ git branch myBranchName --edit-description ``` +### tag + +Manage your tags + +```bash +# List tags +$ git tag +# Create a annotated tag +# The -m specifies a tagging message,which is stored with the tag. +# If you don’t specify a message for an annotated tag, +# Git launches your editor so you can type it in. +$ git tag -a v2.0 -m 'my version 2.0' +# Show info about tag +# That shows the tagger information, the date the commit was tagged, +# and the annotation message before showing the commit information. +$ git show v2.0 +# Push a single tag to remote +$ git push origin v2.0 +# Push a lot of tags to remote +$ git push origin --tags +``` + ### checkout Updates all files in the working tree to match the version in the index, or specified tree. @@ -499,3 +527,6 @@ $ git rm /pather/to/the/file/HelloWorld.c * [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) * [Pro Git](http://www.git-scm.com/book/en/v2) + +* [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) + diff --git a/go.html.markdown b/go.html.markdown index 646a5650..a857a76c 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -423,3 +423,5 @@ idioms. Or you can click on a function name in [the documentation](http://golang.org/pkg/) and the source code comes up! Another great resource to learn Go is [Go by example](https://gobyexample.com/). + +Go Mobile adds support for mobile platforms (Android and iOS). You can write all-Go native mobile apps or write a library that contains bindings from a Go package, which can be invoked via Java (Android) and Objective-C (iOS). Check out the [Go Mobile page](https://github.com/golang/go/wiki/Mobile) for more information. diff --git a/it-it/bash-it.html.markdown b/it-it/bash-it.html.markdown index f892845f..af8823c4 100644 --- a/it-it/bash-it.html.markdown +++ b/it-it/bash-it.html.markdown @@ -13,13 +13,14 @@ contributors: filename: LearnBash.sh translators: - ["Robert Margelli", "http://github.com/sinkswim/"] + - ["Tommaso Pifferi", "http://github.com/neslinesli93/"] lang: it-it --- Bash è il nome della shell di unix, la quale è stata distribuita anche come shell del sistema oprativo GNU e la shell di default su Linux e Mac OS X. Quasi tutti gli esempi sottostanti possono fare parte di uno shell script o eseguiti direttamente nella shell. -[Per saperne di piu'.](http://www.gnu.org/software/bash/manual/bashref.html) +[Per saperne di più.](http://www.gnu.org/software/bash/manual/bashref.html) ```bash #!/bin/bash @@ -34,32 +35,34 @@ echo Ciao mondo! echo 'Questa è la prima riga'; echo 'Questa è la seconda riga' # Per dichiarare una variabile: -VARIABILE="Una stringa" +Variabile="Una stringa" # Ma non così: -VARIABILE = "Una stringa" -# Bash stabilirà che VARIABILE è un comando da eseguire e darà un errore +Variabile = "Una stringa" +# Bash stabilirà che Variabile è un comando da eseguire e darà un errore # perchè non esiste. # Usare la variabile: -echo $VARIABILE -echo "$VARIABILE" -echo '$VARIABILE' +echo $Variabile +echo "$Variabile" +echo '$Variabile' # Quando usi la variabile stessa - assegnala, esportala, oppure — scrivi # il suo nome senza $. Se vuoi usare il valore della variabile, devi usare $. # Nota che ' (singolo apice) non espande le variabili! # Sostituzione di stringhe nelle variabili -echo ${VARIABILE/Una/A} +echo ${Variabile/Una/A} # Questo sostituirà la prima occorrenza di "Una" con "La" # Sottostringa di una variabile -echo ${VARIABILE:0:7} +Lunghezza=7 +echo ${Variabile:0:Lunghezza} # Questo ritornerà solamente i primi 7 caratteri # Valore di default per la variabile -echo ${FOO:-"ValoreDiDefaultSeFOOMancaOÈ Vuoto"} -# Questo funziona per null (FOO=), stringa vuota (FOO=""), zero (FOO=0) ritorna 0 +echo ${Foo:-"ValoreDiDefaultSeFooMancaOppureÈVuoto"} +# Questo funziona per null (Foo=), stringa vuota (Foo=""), zero (Foo=0) ritorna 0 +# Nota: viene ritornato il valore di default, il contenuto della variabile pero' non cambia. # Variabili builtin: # Ci sono delle variabili builtin molto utili, come @@ -71,31 +74,40 @@ echo "Argomenti dello script separati in variabili distinte: $1 $2..." # Leggere un valore di input: echo "Come ti chiami?" -read NOME # Nota che non abbiamo dovuto dichiarare una nuova variabile -echo Ciao, $NOME! +read Nome # Nota che non abbiamo dovuto dichiarare una nuova variabile +echo Ciao, $Nome! # Classica struttura if: # usa 'man test' per maggiori informazioni sulle condizionali -if [ $NOME -ne $USER ] +if [ $Nome -ne $USER ] then echo "Il tuo nome non è lo username" else echo "Il tuo nome è lo username" fi +# Nota: se $Name è vuoto, la condizione precedente viene interpretata come: +if [ -ne $USER ] +# che genera un errore di sintassi. Quindi il metodo sicuro per usare +# variabili che possono contenere stringhe vuote è il seguente: +if [ "$Name" -ne $USER ] ... +# che viene interpretato come: +if [ "" -ne $USER ] ... +# e dunque funziona correttamente. + # C'è anche l'esecuzione condizionale echo "Sempre eseguito" || echo "Eseguito solo se la prima condizione fallisce" echo "Sempre eseguito" && echo "Eseguito solo se la prima condizione NON fallisce" # Per usare && e || con l'if, c'è bisogno di piu' paia di parentesi quadre: -if [ $NOME == "Steve" ] && [ $ETA -eq 15 ] +if [ "$Nome" == "Steve" ] && [ "$Eta" -eq 15 ] then - echo "Questo verrà eseguito se $NOME è Steve E $ETA è 15." + echo "Questo verrà eseguito se $Nome è Steve E $Eta è 15." fi -if [ $NOME == "Daniya" ] || [ $NOME == "Zach" ] +if [ "$Nome" == "Daniya" ] || [ "$Nome" == "Zach" ] then - echo "Questo verrà eseguito se $NAME è Daniya O Zach." + echo "Questo verrà eseguito se $Nome è Daniya O Zach." fi # Le espressioni sono nel seguente formato: @@ -137,7 +149,7 @@ python hello.py > /dev/null 2>&1 # se invece vuoi appendere usa ">>": python hello.py >> "output.out" 2>> "error.err" -# Sovrascrivi output.txt, appendi a error.err, e conta le righe: +# Sovrascrivi output.out, appendi a error.err, e conta le righe: info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err wc -l output.out error.err @@ -145,7 +157,7 @@ wc -l output.out error.err # vedi: man fd echo <(echo "#ciaomondo") -# Sovrascrivi output.txt con "#helloworld": +# Sovrascrivi output.out con "#helloworld": cat > output.out <(echo "#helloworld") echo "#helloworld" > output.out echo "#helloworld" | cat > output.out @@ -164,7 +176,7 @@ echo "Ci sono $(ls | wc -l) oggetti qui." echo "Ci sono `ls | wc -l` oggetti qui." # Bash utilizza uno statemente case che funziona in maniera simile allo switch in Java e C++: -case "$VARIABILE" in +case "$Variabile" in #Lista di pattern per le condizioni che vuoi soddisfare 0) echo "C'è uno zero.";; 1) echo "C'è un uno.";; @@ -172,10 +184,10 @@ case "$VARIABILE" in esac # I cicli for iterano per ogni argomento fornito: -# I contenuti di $VARIABILE sono stampati tre volte. -for VARIABILE in {1..3} +# I contenuti di $Variabile sono stampati tre volte. +for Variabile in {1..3} do - echo "$VARIABILE" + echo "$Variabile" done # O scrivilo con il "ciclo for tradizionale": @@ -186,16 +198,16 @@ done # Possono essere usati anche per agire su file.. # Questo eseguirà il comando 'cat' su file1 e file2 -for VARIABILE in file1 file2 +for Variabile in file1 file2 do - cat "$VARIABILE" + cat "$Variabile" done # ..o dall'output di un comando # Questo eseguirà cat sull'output di ls. -for OUTPUT in $(ls) +for Output in $(ls) do - cat "$OUTPUT" + cat "$Output" done # while loop: @@ -223,7 +235,7 @@ bar () } # Per chiamare la funzione -foo "Il mio nome è" $NOME +foo "Il mio nome è" $Nome # Ci sono un sacco di comandi utili che dovresti imparare: # stampa le ultime 10 righe di file.txt @@ -245,7 +257,7 @@ grep "^foo.*bar$" file.txt grep -c "^foo.*bar$" file.txt # se vuoi letteralmente cercare la stringa, # e non la regex, usa fgrep (o grep -F) -fgrep "^foo.*bar$" file.txt +fgrep "^foo.*bar$" file.txt # Leggi la documentazione dei builtin di bash con il builtin 'help' di bash: diff --git a/it-it/brainfuck-it.html.markdown b/it-it/brainfuck-it.html.markdown index 4999d7e6..08d2ede9 100644 --- a/it-it/brainfuck-it.html.markdown +++ b/it-it/brainfuck-it.html.markdown @@ -1,75 +1,72 @@ --- - language: brainfuck contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] translators: - ["Ivan Sala", "http://slavni96.github.io/"] + - ["Christian Grasso", "http://chris54721.net"] lang: it-it - --- -Brainfuck è un linguaggio di programmazione estremamente minimale, -ma è ingrado di rappresentare completamente una macchina di turnig, -e sfrutta solo 8 caratteri. -[Per saperne di più](http://it.wikipedia.org/wiki/Brainfuck) +Brainfuck è un linguaggio di programmazione +[Turing equivalente](https://it.wikipedia.org/wiki/Turing_equivalenza) +estremamente minimale, composto da solo 8 comandi. + +Puoi provarlo nel tuo browser utilizzando +[brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). ``` -Qualsiasi carattere che non sia "><+-.,[]" (escludendo gli apici) +Qualsiasi carattere diverso da "><+-.,[]" (escludendo gli apici) viene ignorato. -Branfuck è caratterizzato da un array (vettore) di 30,000 celle -inizializzare a zero, e un puntatore che punta alla cella corrente. +Branfuck è caratterizzato da un array di 30,000 celle inizializzate a zero +e da un puntatore che punta alla cella corrente. -Vi sono solo otto comando: +Vi sono otto comandi: + : Incrementa il valore della cella attuale di uno. - : Decrementa il valore della cella attuale di uno. -> : Sposta il puntatore sulla cella seguente (prossima a destra). -< : Sposta il puntatore sulla cella precendete (precedente a sinistra). -. : Stampa il valore in ASCII della cella corrente. (es: 65 = 'A') -, : Legge un singolo carattere come input per la cella corrente. -[ : Se il valore della cella corrente è zero, conclude il ciclo - andando alla sua corrispondente ]. +> : Sposta il puntatore sulla cella seguente (sulla destra). +< : Sposta il puntatore sulla cella precendete (sulla sinistra). +. : Stampa il valore ASCII della cella corrente. (es. 65 = 'A') +, : Legge un singolo carattere come input e lo salva nella cella corrente. +[ : Se il valore della cella corrente è zero, prosegue fino alla ] corrispondente. Altrimenti, passa alla prossima istruzione. ] : Se il valore della cella corrente è zero, passa alla prossima istruzione. - Altrimenti torna indetro fino alla [ corrispondente. + Altrimenti, torna indietro fino alla [ corrispondente. -[ e ] creano un loop (while). Ovviamente dovranno essere bilanciati. -Per ogni [ dovrà corrispondere una ] +[ e ] formano un ciclo while. Ovviamente dovranno essere bilanciati. +(Ad ogni [ dovrà corrispondere una ]) -Alcuni semplici esempi di programmi scritti in Brainfuck: +Ecco alcuni semplici esempi di programmi scritti in Brainfuck: ++++++ [ > ++++++++++ < - ] > +++++ . -Questo programma stampa in output la lettera 'A'. Priam incrementa -la cella #1 fino a 6, Quindi la cella #1 viene usata per crare un ciclo. -Poi, entra in un loop ([) e si sposta alla cella #2. -Incrementa la cella #2 10 volte, e torna alla cella #1, e la decrementa. -Questo avviene 6 volte (servono che la cella #1 venga decrementata 6 volte -per raggiungere lo 0. Quindi passa alla corrispondente ] e prosegue). +Questo programma stampa in output la lettera 'A'. Prima di tutto, incrementa +la cella #1 fino al valore 6. La cella #1 verrà utilizzata per il ciclo. +Poi, entra nel ciclo ([) e si sposta alla cella #2. Incrementa la cella #2 10 +volte, torna alla cella #1, e decrementa quest'ultima. +Il ciclo si ripete 6 volte (la cella #1 viene decrementata 6 volte prima di +raggiungere lo 0, quindi prosegue oltre la corrispondente ]). -A questo punto, siamo sulla cella #1, che ha valore 0, -la cella #2 ha valore 60 (6*10). Ci spostiamo sulla cella #2, incrementiamo -per 5 volte, e otteniamo il valore 65, quindi stampaimo il valore della cella -#2 (.). -65 è 'A' in ASCII, quindi alla fine viene stampata 'A'. +A questo punto, siamo sulla cella #1, che ha valore 0, mentre la cella #2 ha +valore 60. Ci spostiamo sulla cella #2, la incrementiamo per 5 volte, ottenendo +il valore 65, quindi stampiamo il valore della cella #2. +Il valore 65 equivale ad 'A' in ASCII, per cui viene stampato 'A' nel terminale. , [ > + < - ] > . -Questo programma legge un carattere come input dall'utente, -quindi salva il carattere dentro la cella #1. -In seguito, incominca a ciclare. -Si sposta alla cella #², e increementa il valore della cella (#2). -Quindi torna alla cella #1, e decrementa il valore della cella (#1). -Questo continua fino a quando la cella #²1 diventa 0, e quindi la cella #2 -avrà il valore iniziale della cella #1. -Infine, visto che ci troviamo sulla cella #1 alla fine del ciclo, si sposta -sulla cella #2 e stampa il valore in ASCII. +Questo programma legge un carattere come input dall'utente, quindi salva il +carattere nella cella #1. Dopodichè entra in un ciclo. Si sposta alla cella #2, +incrementa quest'ultima, torna alla cella #1, e decrementa quest'ultima. +Il ciclo continua fino a quando la cella #1 diventa 0, e quindi la cella #2 +avrà il valore iniziale della cella #1. Infine, visto che ci troviamo sulla +cella #1 alla fine del ciclo, si sposta sulla cella #2 e stampa il valore in +ASCII. -Gli spazi nel codice sovrastante, sono presenti solo a scopo di ottenere -una maggiore leggibilità, si poteva anche scrivere senza: +Gli spazi nel codice sovrastante sono presenti solo a scopo di ottenere +una maggiore leggibilità. Lo stesso programma poteva essere scritto senza spazi: ,[>+<-]>. @@ -77,25 +74,19 @@ Proviamo, adesso, a capire cosa fa invece questo programma: ,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> -Prende due numeri in input e quindi li moltiplica. +Il programma legge 2 numeri come input dall'utente, e li moltiplica. -Prima prende in input i due numeri (,>,<), quindi inizia un cilclo -basandosi sulla cella #1. -Quindi si sposta sulla cella #2, e inizia un altro ciclo condizionato -dal valore della cella #2, incrementando la cella #3. +Innanzitutto, legge in input i due numeri. Poi entra nel ciclo più esterno +basandosi sulla cella #1. Quindi si sposta sulla cella #2, e inizia il ciclo +più interno basandosi sul valore della cella #2, incrementando la cella #3. Arrivati a questo punto abbiamo un problema: alla fine del ciclo interno -la cella #2 ha valore 0. In questo caso, quando il ciclo esterno rifarà -partire il ciclo interno, non funzionerà più perchè la cella #2 ha valore 0. -Per ovviare a questo problema, oltre alla cella 3, incrementiamo anche la cella -#4, e alla fine di ogni ciclo interno copiala il valore della cella #4 -nella cella #2, in modo che il ciclo interno -possa essere eseguito una altra volta. -Alla fine la cella #3 contiene il risultato. +la cella #2 avrà valore 0. Ciò impedirà di eseguire nuovamente il ciclo interno. +Per ovviare a questo problema, incrementiamo anche la cella #4, e copiamo il +valore di quest'ultima nella cella #2. +Il risultato sarà infine contenuto nella cella #3. ``` -E questo è brainfuck...Non è difficele, vero? -Per divertimento adesso puoi scrivere i tuoi programmi in brainfuck, -oppure puoi scrivere un interprete brainfuck in un altro linguaggio. -L'interprete è abbastanza semplice da implementare, ma se sei veramente -masochista prova ad implementare un interprete brainfuck in... -brainfuck. +E questo è brainfuck. Non è così difficile, eh? Se vuoi, ora puoi scrivere per +divertimento altri programmi in brainfuck, oppure scrivere un interprete +brainfuck in un altro linguaggio. L'interprete è abbastanza semplice da +implementare, ma se sei veramente masochista, prova ad implementare un interprete brainfuck... in brainfuck. diff --git a/it-it/java-it.html.markdown b/it-it/java-it.html.markdown index 6eabd61f..54602cff 100644 --- a/it-it/java-it.html.markdown +++ b/it-it/java-it.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Madison Dickson", "http://github.com/mix3d"] translators: - ["Ivan Sala","http://github.com/slavni96"] + - ["Tommaso Pifferi","http://github.com/neslinesli93"] lang: it-it --- @@ -31,9 +32,9 @@ import java.security.*; // Ogni file .java contiene una classe pubblica, con lo stesso nome del file public class LearnJava { - // Un programma deve avere un metodo main come punto di partenza - // Ma si possono creare anche file senza main, che però per essere usati - // devono essere richiamati da altri file. + // Un programma deve avere un metodo main come punto di partenza. + // Tuttavia si possono creare anche file senza main, che però + // per essere usati devono essere richiamati da altri file. public static void main (String[] args) { // Per stampare a schermo si usa System.out.println @@ -47,88 +48,157 @@ public class LearnJava { System.out.print("Ciao "); System.out.print("Mondo "); + // Per stampare del testo formattato, si puo' usare System.out.printf + System.out.printf("pi greco = %.5f", Math.PI); // => pi greco = 3.14159 /////////////////////////////////////// - // Tipi e Variabili + // Variabili /////////////////////////////////////// - // Si dichiara una variabile usando <tipo> <nome> - // Byte - variabile intera da 8 bit con segno + + /* + * Dichiarazione delle Variabili + */ + // Per dichiarare una variabile basta fare <tipoDato> <nomeVariabile> + int fooInt; + // Per dichiarare piu' di una variabile dello lo stesso tipo si usa: + // <tipoDato> <nomeVariabile1>, <nomeVariabile2>, <nomeVariabile3> + int fooInt1, fooInt2, fooInt3; + + /* + * Inizializzazione delle Variabili + */ + + // Per inizializzare una variabile si usa + // <tipoDato> <nomeVariabile> = <valore> + int fooInt = 1; + // Per inizializzare piu' di una variabile dello lo stesso tipo + // si usa <tipoDato> <nomeVariabile1>, <nomeVariabile2>, <nomeVariabile3> = <valore> + int fooInt1, fooInt2, fooInt3; + fooInt1 = fooInt2 = fooInt3 = 1; + + /* + * Tipi di Variabili + */ + // Byte - intero con segno a 8 bit (in complemento a 2) // (-128 <= byte <= 127) byte fooByte = 100; - // Short - variabile intera da 18 bit con segno + // Short - intero con segno a 16 bit (in complemento a 2) // (-32,768 <= short <= 32,767) short fooShort = 10000; - // Integer - variabile intera da 32 bit con segno + // Integer - intero con segno a 32 bit (in complemento a 2) // (-2,147,483,648 <= int <= 2,147,483,647) int fooInt = 1; - // Long - variabile da 64 bit intera con segno + // Long - intero con segno a 64 bit (in complemento a 2) // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) long fooLong = 100000L; - // L viene usato per specificare che il valore dalla variabile - // e' di tipo "Long", qualsiasi variabile che non viene contrassegnata - // e' trattata di base come un intero. + // L viene usato per indicare che il valore e' di tipo Long; + // altrimenti il valore viene considerato come intero. - // Nota: Java non dispone di variabili senza segno + // Nota: Java non dispone di interi senza segno. - // Float - variabile piu' precisa, con virgola [numeri reali] - // di grandezza 32 bit + // Float - Numero in virgola mobile a 32 bit con precisione singola (IEEE 754) + // 2^-149 <= float <= (2-2^-23) * 2^127 float fooFloat = 234.5f; - // f e' usato per specificare che la variabile e'' di tipo "float" - // altrimenti di default viene trattata come un "dobule" + // f o F indicano the la variabile e' di tipo float; + // altrimenti il valore viene considerato come double. - // Double - ancora piu' precisione la si puo' ottenere con una variabile - // Double, con granzezza di 64 bit. + // Double - Numero in virgola mobile a 64 bit con precisione doppia (IEEE 754) + // 2^-1074 <= x <= (2-2^-52) * 2^1023 double fooDouble = 123.4; - // Boolean - vero & falso + // Boolean - Puo' assumere il valore vero (true) o falso (false) boolean fooBoolean = true; boolean barBoolean = false; - // Char - un singolo carattere con grandezza 16 bit + // Char - Un singolo carattere Unicode a 16-bit char fooChar = 'A'; - // final - Costanti, non possono essere riassegnate ad un altro oggetto - final int ORE_LAVORATIVE_DI_UNA_SETTIMANA = 9001; - - // String - Stringhe, array di caratteri - String fooString = "Ecco una stringa!"; - - // \n e' un carattere speciale che permette di andare a capo. - String barString = "Andare a capo?\nNessun problema!"; - // \t e' un carattere speciale che permette di aggiungere un 'Tab' - String bazString = "Vuoi inserire tab?\tNessun problema"; + // Le variabili precedute da final possono essere inizializzate una volta sola, + final int HOURS_I_WORK_PER_WEEK = 9001; + // pero' e' possibile dichiararle e poi inizializzarle in un secondo momento. + final double E; + E = 2.71828; + + + // BigInteger - Interi a precisione arbitraria + // + // BigInteger e' un tipo di dato che permette ai programmatori di + // gestire interi piu' grandi di 64 bit. Internamente, le variabili + // di tipo BigInteger vengono memorizzate come un vettore di byte e + // vengono manipolate usando funzioni dentro la classe BigInteger. + // + // Una variabile di tipo BigInteger puo' essere inizializzata usando + // un array di byte oppure una stringa. + + BigInteger fooBigInteger = new BigDecimal(fooByteArray); + + // BigDecimal - Numero con segno, immutabile, a precisione arbitraria + // + // Una variabile di tipo BigDecimal e' composta da due parti: un intero + // a precisione arbitraria detto 'non scalato', e un intero a 32 bit + // che rappresenta la 'scala', ovvero la potenza di 10 con cui + // moltiplicare l'intero non scalato. + // + // I BigDecimal permettono un controllo completo sull'arrotondamento + // dei numeri. Essi sono molto usati in ambito finanziario, nella + // gestione delle valute, e in ogni altro posto in cui serve + // precisione esatta. + // + // Le variabili di tipo BigDecimal possono essere inizializzate con un + // int, long, double o String, oppure con un intero non scalato + // (di tipo BigInteger) e una scala (int). + + BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); + + + + // Stringhe + String fooString = "Questa e' la mia stringa!"; + + // \n e' un carattere di escape che rappresenta l'andare a capo + String barString = "Stampare su una nuova riga?\nNessun problema!"; + // \t e' un carattere di escape che aggiunge un tab + String bazString = "Vuoi aggiungere un tab?\tNessun problema!"; System.out.println(fooString); System.out.println(barString); System.out.println(bazString); - // Vettori [array] - //La lunghezza del vettore deve essere decisa quando viene istanziato - //Si puo' dichiarare come segue: - //<tipodato> [] <nomevariabile> = new <tipodato>[<grandezza vettore>]; - //<tipodato> <nomevariabile>[] = new <tipodato>[<grandezza vettore>]; - int [] intArray = new int[10]; - String [] stringArray = new String[1]; - boolean boolArray [] = new boolean[100]; - - // Un altro modo per dichiarare & inizializzare un vettore - int [] y = {9000, 1000, 1337}; - String nomi [] = {"Andrea", "Bob", "Pippo", "Susan"}; + // Vettori + // La dimensione di un array deve essere decisa in fase di + // istanziazione. Per dichiarare un array si puo' fare in due modi: + // <tipoDato>[] <nomeVariabile> = new <tipoDato>[<dimensioneArray>]; + // <tipoDato> <nomeVariabile>[] = new <tipoDato>[<dimensioneArray>]; + int[] intArray = new int[10]; + String[] stringArray = new String[1]; + boolean boolArray[] = new boolean[100]; + + // Un altro modo per dichiarare ed insieme inizializzare un vettore. + int[] y = {9000, 1000, 1337}; + String names[] = {"Gianni", "Anna", "Luca", "Cristina"}; boolean bools[] = new boolean[] {true, false, false}; - - // I vettori vengono indicizzati a parire dallo 0 + + // Per accedere ad un elemento di un vettore System.out.println("intArray @ 0: " + intArray[0]); - // e' possibile un accesso diretto ad un elemento + // I vettori non sono immutabili (ma la loro dimensione si!) + // e gli indici partono da 0. intArray[1] = 1; System.out.println("intArray @ 1: " + intArray[1]); // => 1 - // Altro da vedere: - // Liste di array - come i vettori ma piu' funzionali - // e la loro grandezza puo' variare in corso di esecuzione - // Liste concatenate di memoria + // Ci sono altri tipo di dato interessanti. + // ArrayList - Simili ai vettori, pero' offrono altre funzionalita', + // e la loro dimensione puo' essere modificata. + // LinkedList - Si tratta di una lista linkata doppia, e come tale + // implementa tutte le operazioni del caso. + // Map - Un insieme di oggetti che fa corrispondere delle chiavi + // a dei valori. Non permette l'inserimento di chiavi uguali. + // HashMap - Questa classe usa una tabella di hash per implementare + // l'interfaccia di tipo Map. Questo permette di effettuare + // operazioni basilari, come inserimento e cancellazione, + // in tempo costante anche su insiemi molto grandi. /////////////////////////////////////// // Operatori diff --git a/it-it/json-it.html.markdown b/it-it/json-it.html.markdown index 0c401753..379bad73 100644 --- a/it-it/json-it.html.markdown +++ b/it-it/json-it.html.markdown @@ -1,29 +1,36 @@ --- - language: json contributors: - - ["Anna Harren", "https://github.com/iirelu"] - - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] translators: - ["Robert Margelli", "http://github.com/sinkswim/"] + - ["Christian Grasso", "http://chris54721.net"] lang: it-it - --- -Dato che JSON è un formato per lo scambio di dati estremamente semplice, questo sarà con molta probabilità -il più semplice Learn X in Y Minutes. +JSON è un formato per l'interscambio di dati estremamente semplice, per cui questo sarà +con molta probabilità il più semplice Learn X in Y Minutes. Nella sua forma più pura JSON non ha commenti, ma molti parser accettano commenti in stile C (//, /\* \*/). Per lo scopo prefissato, tuttavia, tutto sarà 100% JSON valido. Fortunatamente, si spiega da sè. +I tipi supportati da JSON comprendono: numeri, stringhe, boolean, array, oggetti e null. +I browser supportati sono: Firefox (Mozilla) 3.5+, Internet Explorer 8+, Google Chrome, +Opera 10+, Safari 4+. +I file JSON sono salvati nel formato ".json". Il MIME type per documenti JSON è +"application/json". Gli svantaggi del JSON includono l'assenza di una definizione dei tipi +e di una sorta di [DTD](https://it.wikipedia.org/wiki/Document_Type_Definition). + ```json { "chiave": "valore", "chiavi": "devono sempre essere racchiuse tra doppi apici", "numeri": 0, - "stringhe": "Ciaø, møndø. Tutti gli unicode sono permessi, assieme con l \"escaping\".", + "stringhe": "Ciaø, møndø. Tutti i caratteri Unicode sono permessi, insieme all'\"escaping\".", "ha booleani?": true, "il nulla": null, @@ -52,8 +59,8 @@ commenti in stile C (//, /\* \*/). Per lo scopo prefissato, tuttavia, tutto sar ], "stile alternativo": { - "commento": "Guarda quà!" - , "posizione della virgola": "non conta - fintantochè è prima del valore, allora è valida" + "commento": "Guarda qua!" + , "posizione della virgola": "non conta - se è prima della chiave successiva, allora è valida" , "un altro commento": "che bello" }, diff --git a/java.html.markdown b/java.html.markdown index 35ec57d8..c2c1a18b 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -250,7 +250,7 @@ public class LearnJava { // If statements are c-like int j = 10; - if (j == 10){ + if (j == 10) { System.out.println("I get printed"); } else if (j > 10) { System.out.println("I don't"); @@ -285,7 +285,18 @@ public class LearnJava { // Iterated 10 times, fooFor 0->9 } System.out.println("fooFor Value: " + fooFor); - + + // Nested For Loop Exit with Label + outer: + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // breaks out of outer loop instead of only the inner one + } + } + } + // For Each Loop // The for loop is also able to iterate over arrays as well as objects // that implement the Iterable interface. @@ -320,7 +331,7 @@ public class LearnJava { // Starting in Java 7 and above, switching Strings works like this: String myAnswer = "maybe"; - switch(myAnswer){ + switch(myAnswer) { case "yes": System.out.println("You answered yes."); break; diff --git a/javascript.html.markdown b/javascript.html.markdown index 6ea0b0bb..937354eb 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -54,6 +54,11 @@ doStuff() // Including uneven division. 5 / 2; // = 2.5 +// And modulo division. +10 % 2; // = 0 +30 % 4; // = 2 +18.5 % 7; // = 4.5 + // Bitwise operations also work; when you perform a bitwise operation your float // is converted to a signed int *up to* 32 bits. 1 << 2; // = 4 @@ -104,7 +109,7 @@ null == undefined; // = true // ...unless you use === "5" === 5; // = false -null === undefined; // = false +null === undefined; // = false // ...which can result in some weird behaviour... 13 + !0; // 14 @@ -220,15 +225,15 @@ for (var i = 0; i < 5; i++){ //The For/In statement loops iterates over every property across the entire prototype chain var description = ""; -var person = {fname:"Paul", lname:"Ken", age:18}; +var person = {fname:"Paul", lname:"Ken", age:18}; for (var x in person){ description += person[x] + " "; } -//If only want to consider properties attached to the object itself, +//If only want to consider properties attached to the object itself, //and not its prototypes use hasOwnProperty() check var description = ""; -var person = {fname:"Paul", lname:"Ken", age:18}; +var person = {fname:"Paul", lname:"Ken", age:18}; for (var x in person){ if (person.hasOwnProperty(x)){ description += person[x] + " "; @@ -413,7 +418,7 @@ var doubler = product.bind(this, 2); doubler(8); // = 16 // When you call a function with the `new` keyword, a new object is created, and -// made available to the function via the this keyword. Functions designed to be +// made available to the function via the `this` keyword. Functions designed to be // called like that are called constructors. var MyConstructor = function(){ diff --git a/json.html.markdown b/json.html.markdown index b5e36090..060e9c3d 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -58,7 +58,7 @@ Drawbacks of JSON include lack of type definition and some sort of DTD. "alternative style": { "comment": "check this out!" - , "comma position": "doesn't matter - as long as it's before the value, then it's valid" + , "comma position": "doesn't matter - as long as it's before the next key, then it's valid" , "another comment": "how nice" }, diff --git a/latex.html.markdown b/latex.html.markdown index 146e8d45..9b7b4feb 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -6,13 +6,15 @@ contributors: - ["Sricharan Chiruvolu", "http://sricharan.xyz"] filename: learn-latex.tex --- + +```tex % All comment lines start with % % There are no multi-line comments % LaTeX is NOT a "What You See Is What You Get" word processing software like % MS Word, or OpenOffice Writer -% Every Latex command starts with a backslash (\) +% Every LaTeX command starts with a backslash (\) % LaTeX documents start with a defining the type of document it's compiling % Other document types include book, report, presentations, etc. @@ -45,7 +47,7 @@ filename: learn-latex.tex % but before the main sections of the body. % This command is available in the document classes article and report. \begin{abstract} - LaTex documentation written as LaTex! How novel and totally not my idea! + LaTeX documentation written as LaTeX! How novel and totally not my idea! \end{abstract} % Section commands are intuitive. @@ -63,8 +65,8 @@ I think we need another one Much better now. \label{subsec:pythagoras} -% By using the asterisk we can suppress Latex's inbuilt numbering. -% This works for other Latex commands as well. +% By using the asterisk we can suppress LaTeX's inbuilt numbering. +% This works for other LaTeX commands as well. \section*{This is an unnumbered section} However not all sections have to be numbered! @@ -74,7 +76,7 @@ a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash to the source code. \\ \section{Lists} -Lists are one of the easiest things to create in Latex! I need to go shopping +Lists are one of the easiest things to create in LaTeX! I need to go shopping tomorrow, so let's make a grocery list. \begin{enumerate} % This creates an "enumerate" environment. % \item tells the enumerate to increment @@ -106,7 +108,7 @@ Here's how you state all y that belong to X, $\forall$ x $\in$ X. \\ % The opposite also holds true. Variable can also be rendered in math-mode. My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. -I haven't found a Greek letter that yet that Latex doesn't know about! +I haven't found a Greek letter that yet that LaTeX doesn't know about! Operators are essential parts of a mathematical document: trigonometric functions ($\sin$, $\cos$, $\tan$), @@ -126,7 +128,7 @@ $^{10}/_{7}$ % \frac{numerator}{denominator} $\frac{n!}{k!(n - k)!}$ \\ -We can also insert equations in an "equation environment." +We can also insert equations in an "equation environment". % Display math with the equation 'environment' \begin{equation} % enters math-mode @@ -141,7 +143,7 @@ figures, equations, sections, etc. Summations and Integrals are written with sum and int commands: -% Some latex compilers will complain if there are blank lines +% Some LaTeX compilers will complain if there are blank lines % In an equation environment. \begin{equation} \sum_{i=0}^{5} f_{i} @@ -181,9 +183,9 @@ We can also insert Tables in the same way as figures. % \section{Hyperlinks} % Coming soon -\section{Getting Latex to not compile something (i,e, Source Code)} -Let's say we want to include some code into our Latex document, -we would then need Latex to not try and interpret that text and +\section{Getting LaTeX to not compile something (i.e. Source Code)} +Let's say we want to include some code into our LaTeX document, +we would then need LaTeX to not try and interpret that text and instead just print it to the document. We do this we a verbatim environment. @@ -198,7 +200,7 @@ environment. \section{Compiling} By now you're probably wondering how to compile this fabulous document -and look at the glorious glory that is a Latex pdf. +and look at the glorious glory that is a LaTeX pdf. (yes, this document actually does compiles). \\ Getting to the final document using LaTeX consists of the following steps: \begin{enumerate} @@ -225,6 +227,7 @@ That's all for now! % end the document \end{document} ``` + ## More on LaTeX * The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) diff --git a/nl-nl/yaml-nl.html.markdown b/nl-nl/yaml-nl.html.markdown new file mode 100644 index 00000000..a4a9d5fc --- /dev/null +++ b/nl-nl/yaml-nl.html.markdown @@ -0,0 +1,139 @@ +--- +language: yaml +filename: learnyaml-nl.yaml +contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +translators: + - ["Niels van Velzen", "https://nielsvanvelzen.me"] +lang: nl-nl +--- + +YAML is een data serialisatie taal ontworpen om snel te kunnen worden begrepen door mensen. + +Het is een strikte superset van JSON en bevat nieuwe regels en een stricte manier van inspringen, zoals bij Python. In tegenstelling tot Python kan je alleen geen tab tekens gebruiken. + +```yaml +# Commentaar in YAML ziet er zo uit + +################ +# SCALAR TYPES # +################ + +# Ons hoofd object (Wat in het hele document gebruikt wordt) is een map, +# dit staat gelijk aan een dictionary, hash of object in andere talen. +sleutel: waarde +nog_een_sleutel: Een andere waarde +nummer_waarde: 100 +wetenschappelijke_waarde: 1e+12 +boolean_waarde: true +null_waarde: null +sleutel met spaties: waarde +# Merk op dat strings niet verplicht in quotes moeten, maar dit kan wel. +quote_waarde: "Een string in quotes" +"Ook sleutels kunnen in quotes": "Dit is bijvoorbeeld handig als je een dubbelepunt wilt gebruiken in je key" + +# Tekst over meerdere lijnen kan je schrijven als een 'letterlijk blok' (met |) +# Of een 'gevouwen blok' (met >) +letterlijk_blok: | + Dit hele blok met tekst is de waarde van de 'letterlijk_blok' sleutel, + met nieuwe lijnen behouden. + + Het blok blijft door gaan tot het geeindigd wordt door korter te inspringen. + + Lijnen die groter zijn ingesprongen behouden dit. +gevouwen_stijl: > + Dit blok met tekst zal de waarde zijn van 'gevouwen_stijl', + maar deze keer zullen alle nieuwe lijnen worden vervangen met een spatie. + + Lege lijnen, zoals hierboven, zullen worden vertaald naar een nieuwe lijn. + + Meer ingesprongen lijnen zullen hun nieuwe lijnen ook behouden, + deze tekst zal over 2 lijnen te zien zijn. + +#################### +# COLLECTION TYPES # +#################### + +# Nesten wordt bereikt met inspringen. +geneste_map: + sleutel: waarde + andere_sleutel: andere waarde + andere_geneste_map: + hallo: wereld + +# In een map is een sleutel niet verplicht om een string te gebruiken +0.25: een float als sleutel + +# Sleutels kunnen ook meerdere lijnen gebruiken met behulp van het vraagteken +? | + Dit is een sleutel + met meerdere lijnen +: en dit is de waarde + +# YAML staat ook collection types toe in sleutels, maar veel programmeertalen +# zullen hierover klagen. + +# Sequences (gelijk aan lijsten of arrays) zien er zo uit: +een_sequence: + - Item 1 + - Item 2 + - 0.5 # sequences kunnen meerdere type waardes bevatten. + - Item 4 + - sleutel: waarde + andere_sleutel: andere waarde + - + - Dit is een sequence + - in een andere sequence + +# Doordat YAML een superset van JSON is kan je ook JSON-stijl mappen en +# sequences maken: +json_map: {"sleutel": "waarde"} +json_seq: [3, 2, 1, "takeoff"] + +####################### +# EXTRA YAML FUNCTIES # +####################### + +# YAML heeft ook een handige functie genaamd 'anchors' (ankers), deze laten je +# makkelijk de waarde van ergens anders in je document kopieëren. Beide sleutels +# krijgen dezelfde waarde: +geankert_content: &anker_naam Deze string zal verschijnen als waarde voor de twee sleutels +andere_anker: *anker_naam + +# YAML heeft ook tags, deze gebruik je om een expliciet type te verklaren +expliciete_string: !!str 0.5 +# Sommige parsers gebruiken taal specifieke tags, zoals deze voor Python's +# complexe nummer type: +python_complex_nummer: !!python/complex 1+2j + +#################### +# EXTRA YAML TYPES # +#################### + +# Strings en nummer zijn niet de enige types die YAML begrijpt. +# ISO opgemaakte datum en datumtijd notaties werken ook: +datumtijd: 2001-12-15T02:59:43.1Z +datumtijd_met_spaties: 2001-12-14 21:59:43.10 -5 +datum: 2002-12-14 + +# De !!binary tag geeft aan dat de string een base64-gecodeerde +# binary blob is. +gif_bestand: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + +# YAML heeft ook een set type, dat ziet er zo uit: +set: + ? item1 + ? item2 + ? item3 + +# Zoals in Python zijn sets gewoon mappen met null waardes; +# bovenstaand is gelijk aan: +set2: + item1: null + item2: null + item3: null +``` diff --git a/ocaml.html.markdown b/ocaml.html.markdown index 02435e4d..8faab297 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -196,7 +196,7 @@ let (~/) x = 1.0 /. x ;; ~/4.0 (* = 0.25 *) -(*** Built-in datastructures ***) +(*** Built-in data structures ***) (* Lists are enclosed in square brackets, items are separated by semicolons. *) @@ -341,10 +341,10 @@ let say x = say (Cat "Fluffy") ;; (* "Fluffy says meow". *) -(** Traversing datastructures with pattern matching **) +(** Traversing data structures with pattern matching **) (* Recursive types can be traversed with pattern matching easily. - Let's see how we can traverse a datastructure of the built-in list type. + Let's see how we can traverse a data structure of the built-in list type. Even though the built-in cons ("::") looks like an infix operator, it's actually a type constructor and can be matched like any other. *) let rec sum_list l = diff --git a/perl6.html.markdown b/perl6.html.markdown index 0f015b45..45b15f05 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -11,9 +11,7 @@ Perl 6 is a highly capable, feature-rich programming language made for at least the next hundred years. The primary Perl 6 compiler is called [Rakudo](http://rakudo.org), which runs on -the JVM and [the MoarVM](http://moarvm.com) and -[prior to March 2015](http://pmthium.com/2015/02/suspending-rakudo-parrot/), -[the Parrot VM](http://parrot.org/). +the JVM and [the MoarVM](http://moarvm.com). Meta-note : the triple pound signs are here to denote headlines, double paragraphs, and single notes. diff --git a/php.html.markdown b/php.html.markdown index 39ec5aef..13cc83eb 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -12,7 +12,7 @@ This document describes PHP 5+. <?php // PHP code must be enclosed with <?php tags // If your php file only contains PHP code, it is best practice -// to omit the php closing tag. +// to omit the php closing tag to prevent accidental output. // Two forward slashes start a one-line comment. @@ -103,6 +103,8 @@ END; // String concatenation is done with . echo 'This string ' . 'is concatenated'; +// Strings can be passed in as parameters to echo +echo 'Multiple', 'Parameters', 'Valid'; /******************************** * Constants @@ -141,6 +143,8 @@ echo $array[0]; // => "One" // Add an element to the end of an array $array[] = 'Four'; +// or +array_push($array, 'Five'); // Remove element from array unset($array[3]); @@ -379,7 +383,7 @@ for ($i = 0; $i < 5; $i++) { // Define a function with "function": function my_function () { - return 'Hello'; + return 'Hello'; } echo my_function(); // => "Hello" @@ -388,8 +392,8 @@ echo my_function(); // => "Hello" // number of letters, numbers, or underscores. function add ($x, $y = 1) { // $y is optional and defaults to 1 - $result = $x + $y; - return $result; + $result = $x + $y; + return $result; } echo add(4); // => 5 @@ -400,21 +404,21 @@ echo add(4, 2); // => 6 // Since PHP 5.3 you can declare anonymous functions; $inc = function ($x) { - return $x + 1; + return $x + 1; }; echo $inc(2); // => 3 function foo ($x, $y, $z) { - echo "$x - $y - $z"; + echo "$x - $y - $z"; } // Functions can return functions function bar ($x, $y) { - // Use 'use' to bring in outside variables - return function ($z) use ($x, $y) { - foo($x, $y, $z); - }; + // Use 'use' to bring in outside variables + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; } $bar = bar('A', 'B'); @@ -426,6 +430,21 @@ echo $function_name(1, 2); // => 3 // Useful for programatically determining which function to run. // Or, use call_user_func(callable $callback [, $parameter [, ... ]]); + +// You can get the all the parameters passed to a function +function parameters() { + $numargs = func_num_args(); + if ($numargs > 0) { + echo func_get_arg(0) . ' | '; + } + $args_array = func_get_args(); + foreach ($args_array as $key => $arg) { + echo $key . ' - ' . $arg . ' | '; + } +} + +parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | + /******************************** * Includes */ diff --git a/pl-pl/python-pl.html.markdown b/pl-pl/python-pl.html.markdown index c3e8287a..ade1d7ca 100644 --- a/pl-pl/python-pl.html.markdown +++ b/pl-pl/python-pl.html.markdown @@ -125,7 +125,7 @@ not False # => True # Ta metoda jest obecnie polecana: "{0} są {1}".format("napisy", "fajne") # Jeśli nie chce ci się liczyć użyj słów kluczowych. -"{imie} chce zjeść {jadlo}".format(imie="Bob", jasno="lasagne") +"{imie} chce zjeść {jadlo}".format(imie="Bob", jadlo="makaron") # None jest obiektem None # => None @@ -158,7 +158,7 @@ print "Jestem Python. Miło poznać!" print("Ja też jestem Python! ") # Nie trzeba deklarować zmiennych przed przypisaniem. -jakas_zmienna = 5 # Konwencja mówi: używaj małych znaków i podłogi _ +jakas_zmienna = 5 # Konwencja mówi: używaj małych znaków i kładki _ jakas_zmienna # => 5 # Próba dostępu do niezadeklarowanej zmiennej da błąd. diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown index 451df4f3..43688724 100644 --- a/pt-br/c-pt.html.markdown +++ b/pt-br/c-pt.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] translators: - ["João Farias", "https://github.com/JoaoGFarias"] + - ["Elton Viana", "https://github.com/eltonvs"] lang: pt-br filename: c-pt.el --- @@ -139,13 +140,13 @@ int main() { int var_length_array[size]; // declara o VLA printf("sizeof array = %zu\n", sizeof var_length_array); - //Uma possível saída para esse programa seria: - // > Entre o tamanho do array:: 10 + // Uma possível saída para esse programa seria: + // > Entre o tamanho do array: 10 // > sizeof array = 40 // String são apenas arrays de caracteres terminados por um - // byte NUL (0x00), representado em string pelo caracter especial '\0'. - // (Não precisamos incluir o byte NUL em literais de string; o compilador + // byte nulo (0x00), representado em string pelo caracter especial '\0'. + // (Não precisamos incluir o byte nulo em literais de string; o compilador // o insere ao final do array para nós.) char uma_string[20] = "Isto é uma string"; // Observe que 'é' não está na tabela ASCII @@ -153,8 +154,8 @@ int main() { // Porém, comentários podem conter acentos printf("%s\n", uma_string); // %s formata a string - printf("%d\n", uma_string[16]); // => 0 - // i.e., byte #17 é 0 (assim como 18, 19, e 20) + printf("%d\n", uma_string[17]); // => 0 + // i.e., byte #18 é 0 (assim como o 19°, 20°, 21°...) // Se temos caracteres entre aspas simples, temos um caracter literal. // Seu tipo é `int`, *não* `char` (por razões históricas). @@ -220,11 +221,11 @@ int main() { 0 || 1; // => 1 (Ou lógico) 0 || 0; // => 0 - //Expressão condicional ( ? : ) + //Expressão condicional ternária ( ? : ) int a = 5; int b = 10; int z; - z = (a > b) ? a : b; // => 10 "se a > b retorne a, senão retorne b." + z = (a > b) ? a : b; // => 10 "se a > b retorne a, senão retorne b." //Operadores de incremento e decremento: char *s = "iLoveC"; @@ -290,6 +291,8 @@ int main() { for (i = 0; i <= 5; i++) { ; // Use ponto e vírgula para agir como um corpo (declaração nula) } + // Ou + for (i = 0; i <= 5; i++); // Criando branchs com escolhas múltiplas: switch() switch (alguma_expressao_integral) { diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown new file mode 100644 index 00000000..ed6f6c4c --- /dev/null +++ b/pt-br/css-pt.html.markdown @@ -0,0 +1,257 @@ +--- +language: css +filename: learncss-pt.css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Geoffrey Liu", "https://github.com/g-liu"] + - ["Connor Shea", "https://github.com/connorshea"] + - ["Deepanshu Utkarsh", "https://github.com/duci9y"] +translators: + - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"] +lang: pt-br +--- + +Nos primeiros dias da web não havia elementos visuais, apenas texto puro. Mas com maior desenvolvimento de navegadores da web, páginas web totalmente visuais também se tornou comum. + +CSS ajuda a manter a separação entre o conteúdo (HTML) e o look-and-feel de uma página web. + +CSS permite atingir diferentes elementos em uma página HTML e atribuir diferentes propriedades visuais para eles. + +Este guia foi escrito para CSS2, embora CSS3 está rapidamente se tornando popular. + +**NOTA:** Porque CSS produz resultados visuais, a fim de aprender, você precisa tentar de tudo em um playground CSS como [dabblet](http://dabblet.com/). +O foco principal deste artigo é sobre a sintaxe e algumas dicas gerais. + +```css +/* Comentários aparecem dentro do slash-asterisk, tal como esta linha! + não há "comentários de uma linha"; este é o único estilo de comentário * / + +/* #################### + ## SELETORES + #################### */ + +/* O seletor é usado para direcionar um elemento em uma página. + seletor { propriedade: valor; / * Mais propriedades ... * / } + +/* +Abaixo um elemento de exemplo: + +<div class='class1 class2' id='anID' attr='value' otherAttr='pt-br foo bar' /> +*/ + +/* Você pode direciona-lo usando uma das suas classes CSS */ +.class1 { } + +/* ou ambas as classes! */ +.class1.class2 { } + +/* ou o seu nome */ +div { } + +/* ou o seu id */ +#anID { } + +/* ou utilizando o fator de que tem um atributo!*/ +[attr] { font-size:smaller; } + +/* ou que o atributo tem um valor específico */ +[attr='value'] { font-size:smaller; } + +/* começa com um valor (CSS 3) */ +[attr^='val'] { font-size:smaller; } + +/* ou terminando com um valor (CSS 3) */ +[attr$='ue'] { font-size:smaller; } + + +/* Ou contém um valor em uma lista separada por espaços */ +[otherAttr ~ = 'foo'] {} +[otherAttr ~ = 'bar'] {} + +/* Ou contém um valor em uma lista separada por hífen, ou seja, "-" (U + 002D) */ +[otherAttr | = 'en'] {font-size: smaller; } + + +/* Você pode concatenar diferentes seletores para criar um seletor mais estreito. Não + colocar espaços entre eles. */ +classe div.some [attr $ = 'ue'] {} + +/* Você pode selecionar um elemento que é filho de outro elemento */ +div.some-parent> .class-name {} + +/* Ou um descendente de um outro elemento. As crianças são os descendentes diretos de + seu elemento pai, apenas um nível abaixo da árvore. Pode ser qualquer descendentes + nivelar por baixo da árvore. */ +div.some-parent class-name {} + +/* Atenção: o mesmo seletor sem espaço tem um outro significado. + Você consegue adivinhar o que? */ +div.some-parent.class-name {} + +/* Você também pode selecionar um elemento com base em seu irmão adjacente */ +.i am just-antes + .Este elemento {} + +/* Ou qualquer irmão que o precede */ +.i am-qualquer-elemento antes ~ .Este elemento {} + +/* Existem alguns selectores chamado pseudo classes que podem ser usados para selecionar um + elemento quando ele está em um determinado estado */ + +/* Por exemplo, quando o cursor passa sobre um elemento */ +seletor:hover {} + +/* Ou um link foi visitado */ +seletor:visited {} + +/* Ou não tenha sido visitado */ +seletor:link {} + +/* Ou um elemento em foco */ +seletor:focus {} + +/* Qualquer elemento que é o primeiro filho de seu pai */ +seletor:first-child {} + +/* Qualquer elemento que é o último filho de seu pai */ +seletor:last-child {} + +/* Assim como pseudo classes, pseudo elementos permitem que você estilo certas partes de um documento */ + +/* Corresponde a um primeiro filho virtual do elemento selecionado */ +seletor::before {} + +/* Corresponde a um último filho virtual do elemento selecionado */ +seletor::after {} + +/* Nos locais apropriados, um asterisco pode ser utilizado como um curinga para selecionar todos + elemento */ +* {} /* */ Todos os elementos +.parent * {} /* */ todos os descendentes +.parent> * {} /* */ todas as crianças + +/* #################### + ## PROPRIEDADES + #################### */ + +seletor { + + /* Unidades de comprimento pode ser absoluta ou relativa. */ + + /* Unidades relativas */ + width: 50%; /* Percentagem de largura elemento pai */ + font-size: 2em; /* Múltiplos de font-size original de elemento */ + font-size: 2rem; /* Ou do elemento raiz font-size */ + font-size: 2vw; /* Múltiplos de 1% da largura da janela de exibição (CSS 3) */ + font-size: 2vh; /* Ou a sua altura */ + font-size: 2vmin; /* Qualquer um de VH ou um VW é menor */ + font-size: 2vmax; /* Ou superior */ + + /* Unidades absolutas */ + width: 200px; /* píxeis */ + font-size: 20pt; /* Pontos */ + width: 5cm; /* Centímetros */ + min-width: 50mm; /* Milímetros */ + max-width: 5 polegadas; /* Polegadas */ + + /* Cores */ + color: # F6E; /* Formato hexadecimal curto */ + color: # FF66EE; /* Formato hexadecimal longo */ + color: tomato; /* Uma cor nomeada */ + color: rgb (255, 255, 255); /* Como valores rgb */ + cor: RGB (10%, 20%, 50%); /* Como porcentagens rgb */ + cor: rgba (255, 0, 0, 0,3); /* Como valores RGBA (CSS 3) NOTA: 0 <a <1 */ + color: transparent; /* Equivale a definir o alfa a 0 */ + cor: HSL (0, 100%, 50%); /* Como porcentagens HSL (CSS 3) */ + cor: HSLA (0, 100%, 50%, 0,3); /* Como porcentagens HSLA com alfa */ + + /* Imagens como fundos de elementos */ + background-image: url (/img-path/img.jpg); /* Citações dentro url () opcional */ + + /* Fontes */ + font-family: Arial; + /* Se o nome da família de fonte tem um espaço, deve ser citado */ + font-family: "Courier New"; + /* Se o primeiro não for encontrada, o navegador usa o próximo, e assim por diante */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; +} +``` + +## Uso + +Guardar uma folha de estilo CSS com a extensão `.css`. + +```xml +<!-- Você precisa incluir o arquivo css no da sua página <head>. Isto é o + método recomendado. Consulte http://stackoverflow.com/questions/8284365 --> +<link rel='stylesheet' type='text/css' href='path/to/style.css' /> + +<!-- Você também pode incluir alguns CSS inline na sua marcação. --> +<style> + a { color: purple; } +</style> + +<!-- Ou diretamente definir propriedades CSS no elemento. --> +<div style="border: 1px solid red;"> +</div> +``` + +## Precedência ou Cascata + +Um elemento pode ser alvo de vários seletores e pode ter um conjunto de propriedades em que mais de uma vez. Nestes casos, uma das regras tem precedência sobre os outros. Geralmente, uma regra em um seletor mais específico têm precedência sobre um menos específico, e uma regra que ocorre mais tarde na folha de estilo substitui uma anterior. + +Este processo é chamado de cascata, portanto, as Fichas de nome de estilo em cascata. + +Dado o seguinte CSS: + +```css +/* UMA */ +p.class1[attr="value"] + +/* B */ +p.class1 {} + +/* C */ +p.class2 {} + +/* D */ +p { } + +/* E */ +p { property: value !important; } +``` + +e a seguinte marcação: + +```xml +<p style='/*F*/ property:value;' class='class1 class2' attr='value' /> +``` + +A precedência de estilo é a seguinte. Lembre-se, a precedência é para cada **propriedade**, não para todo o bloco. + +* `E` tem a precedência mais alta por causa de uma palavra-chave`!important`. É recomendável que você evitar seu uso. +* `F` é a próxima, porque é um estilo interno. +* `A` é a próxima, porque é mais" específico "do que qualquer outra coisa. Tem 3 especificadores: O nome do elemento `p`, o seu `class1` classe, um atributo `attr='value'`. +* `C` está próximo, mesmo que ele tenha a mesma especificidade que `B`. Isso é porque ele aparece depois de `B`. +* `B` é o próximo. +* `D` é a última. + +## Compatibilidade + +A maior parte dos recursos do CSS 2 (e muitos em CSS 3) estão disponíveis em todos os navegadores e dispositivos. Mas é sempre boa prática para verificar antes de usar um novo recurso. + +## Recursos + +* Para executar uma verificação de compatibilidade rápida, [CanIUse](http://caniuse.com). +* CSS Playground [Dabblet](http://dabblet.com/). +* [Documentação CSS Mozilla Developer Rede](https://developer.mozilla.org/en-US/docs/Web/CSS) +* [Codrops 'Referência CSS](http://tympanus.net/codrops/css_reference/) + +## Leitura adicional + +* [Entendendo Estilo Precedência em CSS: Especificidade, Herança, eo Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecionando elementos usando atributos](https://css-tricks.com/almanac/selectors/a/attribute/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - O empilhamento context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) e [menos](http://lesscss.org/) para CSS pré-processamento +* [CSS-Tricks](https://css-tricks.com) diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown index fc63b126..e4f10a61 100644 --- a/pt-br/json-pt.html.markdown +++ b/pt-br/json-pt.html.markdown @@ -35,7 +35,7 @@ tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si. "array": [0, 1, 2, 3, "Arrays podem ter qualquer coisa em si.", 5], "outro objeto": { - "ccomentário": "Estas coisas podem ser aninhadas, muito úteis." + "comentário": "Estas coisas podem ser aninhadas, muito úteis." } }, diff --git a/pt-br/sass-pt.html.markdown b/pt-br/sass-pt.html.markdown new file mode 100644 index 00000000..105896b2 --- /dev/null +++ b/pt-br/sass-pt.html.markdown @@ -0,0 +1,477 @@ +--- +language: sass +filename: learnsass-pt.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] + - ["Sean Corrales", "https://github.com/droidenator"] +translators: + - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"] +lang: pt-br +--- + +Sass é uma linguagem de extensão CSS que adiciona recursos, como variáveis, aninhamento, mixins e muito mais. +Sass (e outros pré-processadores, como [Less](http://lesscss.org/)) ajudam os desenvolvedores a escrever código de fácil manutenção e DRY (Do not Repeat Yourself). + +Sass tem duas opções de sintaxe diferentes para escolher. SCSS, que tem a mesma sintaxe de CSS, mas com os recursos adicionais de Sass. Ou Sass (a sintaxe original), que usa o recuo, em vez de chaves e ponto e vírgula. +Este tutorial é escrito usando SCSS. + +Se você já está familiarizado com CSS3, você será capaz de pegar Sass de forma relativamente rápida. Ele não fornece quaisquer novas opções de estilo, mas sim as ferramentas para escrever sua CSS de forma mais eficiente e fazer a manutenção mais fácilmente. + +```scss + + +// Comentários de linha única são removidos quando Sass é compilado para CSS. + +/* Comentários multi-line são preservados. */ + + + +/*Variáveis +==============================*/ + + + +/* É possível armazenar um valor CSS (tais como a cor) de uma variável. +Use o símbolo "$" para criar uma variável. */ + +$primary-color: #A3A4FF; +$secondary-color: #51527F; +$body-font: 'Roboto', sans-serif; + +/* Você pode usar as variáveis em toda a sua folha de estilo. +Agora, se você quer mudar a cor, você só tem que fazer a mudança uma vez. */ + +body { + background-color: $primary-color; + color: $secondary-color; + font-family: $body-font; +} + +/* Quando compilar ficaria assim: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/ * Este é muito mais fácil de manter do que ter de mudar a cor +cada vez que aparece em toda a sua folha de estilo. * / + + + + +/*Mixins +==============================*/ + + + +/* Se você achar que você está escrevendo o mesmo código para mais de um +elemento, você pode querer armazenar esse código em um mixin. + +Use a diretiva '@mixin', além de um nome para o seu mixin. */ + +@mixin center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Você pode usar o mixin com '@include' e o nome mixin. */ + +div { + @include center; + background-color: $primary-color; +} + +/* Apoś compilar ficaria assim: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + + +/* Você pode usar mixins para criar uma propriedade estenográfica. */ + +@mixin size($width, $height) { + width: $width; + height: $height; +} + +/* O que você pode invocar passando argumentos de largura e altura. */ + +.rectangle { + @include size(100px, 60px); +} + +.square { + @include size(40px, 40px); +} + +/* Isso compilado ficará assim: */ +.rectangle { + width: 100px; + height: 60px; +} + +.square { + width: 40px; + height: 40px; +} + + + +/*Funções +==============================*/ + + + +/* Sass fornece funções que podem ser utilizados para realizar uma variedade de + tarefas. Considere o seguinte */ + +/* Funções pode ser chamado usando seu nome e passando o + argumentos necessários */ +body { + width: round(10.25px); +} + +.footer { + background-color: fade_out(#000000, 0.25) +} + +/* Compiles to: */ + +body { + width: 10px; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* You may also define your own functions. Functions are very similar to + mixins. When trying to choose between a function or a mixin, remember + that mixins are best for generating CSS while functions are better for + logic that might be used throughout your Sass code. The examples in + the Math Operators' section are ideal candidates for becoming a reusable + function. */ + +/* This function will take a target size and the parent size and calculate + and return the percentage */ + +/* Você também pode definir suas próprias funções. As funções são muito semelhantes aos + mixins. Ao tentar escolher entre uma função ou um mixin, lembre- + que mixins são os melhores para gerar CSS enquanto as funções são melhores para + lógica que pode ser usado em todo o seu código Sass. Os exemplos + seção Operadores Math 'são candidatos ideais para se tornar um reutilizável + função. */ + +/* Esta função terá um tamanho de destino eo tamanho do pai e calcular + e voltar a percentagem */ + +@function calculate-percentage($target-size, $parent-size) { + @return $target-size / $parent-size * 100%; +} + +$main-content: calculate-percentage(600px, 960px); + +.main-content { + width: $main-content; +} + +.sidebar { + width: calculate-percentage(300px, 960px); +} + +/* Compila para: */ + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + + + +/* Extend (Herança) +============================== */ + + + +/*Extend é uma maneira de compartilhar as propriedades de um seletor com outro. */ + +.display { + @include size(5em, 5em); + border: 5px solid $secondary-color; +} + +.display-success { + @extend .display; + border-color: #22df56; +} + +/* Compiles to: */ +.display, .display-success { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.display-success { + border-color: #22df56; +} + +/* Ampliando uma declaração CSS é preferível a criação de um mixin + por causa da maneira agrupa as classes que todos compartilham + o mesmo estilo base. Se isso for feito com um mixin, a largura, + altura, e a borda seria duplicado para cada instrução que + o chamado mixin. Enquanto isso não irá afetar o seu fluxo de trabalho, será + adicionar inchaço desnecessário para os arquivos criados pelo compilador Sass. */ + + + +/*Assentamento +==============================*/ + + + +/ * Sass permite seletores ninhos dentro seletores * / + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* '&' será substituído pelo selector pai. */ +/* Você também pode aninhar pseudo-classes. */ +/* Tenha em mente que o excesso de nidificação vai fazer seu código menos sustentável. +Essas práticas também recomendam não vai mais de 3 níveis de profundidade quando nidificação. +Por exemplo: */ + + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Compila para: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/*Parciais e Importações +==============================*/ + + +/* Sass permite criar arquivos parciais. Isso pode ajudar a manter seu Sass + código modularizado. Arquivos parciais deve começar com um '_', por exemplo, _reset.css. + Parciais não são geradas em CSS. */ + + + +/* Considere o seguinte CSS que nós vamos colocar em um arquivo chamado _reset.css */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Sass offers @import which can be used to import partials into a file. + This differs from the traditional CSS @import statement which makes + another HTTP request to fetch the imported file. Sass takes the + imported file and combines it with the compiled code. */ + +/* Sass oferece @import que pode ser usado para importar parciais em um arquivo. + Isso difere da declaração CSS @import tradicional, que faz + outra solicitação HTTP para buscar o arquivo importado. Sass converte os + importadas arquivo e combina com o código compilado. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Compiles to: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/*Placeholder Selectors +==============================*/ + + + +/* Placeholders are useful when creating a CSS statement to extend. If you + wanted to create a CSS statement that was exclusively used with @extend, + you can do so using a placeholder. Placeholders begin with a '%' instead + of '.' or '#'. Placeholders will not appear in the compiled CSS. */ + +/* Os espaços reservados são úteis na criação de uma declaração CSS para ampliar. Se você + queria criar uma instrução CSS que foi usado exclusivamente com @extend, + Você pode fazer isso usando um espaço reservado. Espaços reservados começar com um '%' em vez + de '.' ou '#'. Espaços reservados não aparece no CSS compilado. * / + +%content-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + @extend %content-window; + background-color: #0000ff; +} + +/* Compilado para: */ + +.message-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + background-color: #0000ff; +} + + + +/*Operações Math +============================== * / + + +/* Sass provides the following operators: +, -, *, /, and %. These can + be useful for calculating values directly in your Sass files instead + of using values that you've already calculated by hand. Below is an example + of a setting up a simple two column design. */ + +/* Sass fornece os seguintes operadores: +, -, *, /, e %. estes podem + ser úteis para calcular os valores diretamente no seu Sass arquivos em vez + de usar valores que você já calculados pela mão. Abaixo está um exemplo + de uma criação de um projeto simples de duas colunas. * / + +$content-area: 960px; +$main-content: 600px; +$sidebar-content: 300px; + +$main-size: $main-content / $content-area * 100%; +$sidebar-size: $sidebar-content / $content-area * 100%; +$gutter: 100% - ($main-size + $sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: $main-size; +} + +.sidebar { + width: $sidebar-size; +} + +.gutter { + width: $gutter; +} + +/* Compiles to: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + + +``` + + + +## SASS ou Sass? +Alguma vez você já se perguntou se Sass é um acrônimo ou não? Você provavelmente não tem, mas vou dizer-lhe de qualquer maneira. O nome do idioma é uma palavra, "Sass", e não uma sigla. +Porque as pessoas estavam constantemente a escrevê-lo como "SASS", o criador da linguagem de brincadeira chamou de "StyleSheets Sintaticamente Incríveis". + + +## Prática Sass +Se você quiser jogar com Sass em seu navegador, vá para [SassMeister](http://sassmeister.com/). +Você pode usar uma sintaxe, basta ir para as configurações e selecionar Sass ou SCSS. + + +## Compatibilidade + +Sass pode ser usado em qualquer projeto, desde que você tenha um programa para compilá-lo +em CSS. Você vai querer verificar se o CSS que você está usando é compatível +com os seus navegadores de destino. + +[QuirksMode CSS](http://www.quirksmode.org/css/) e [CanIUse](http://caniuse.com) são ótimos recursos para verificação de compatibilidade. + + +## Leitura +* [Official Documentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) fornece tutoriais (iniciante avançados) e artigos. diff --git a/pt-br/tmux-pt.html.markdown b/pt-br/tmux-pt.html.markdown new file mode 100644 index 00000000..9d5bf292 --- /dev/null +++ b/pt-br/tmux-pt.html.markdown @@ -0,0 +1,254 @@ +--- +category: tool +tool: tmux +contributors: + - ["mdln", "https://github.com/mdln"] +translators: + - ["Luis Custodio", "http://luiscustodio.com"] +lang: pt-br +filename: LearnTmux-pt.txt +--- + +O [tmux](http://tmux.sourceforge.net) +é um multiplexador de terminal, ele permite que terminais sejam criados, +acessados e controlados a partir de uma unica instância. tmux pode ser separado +de uma tela e continuar rodando no plano de fundo e depois ser reacoplado à +instância (ou tela original). + +``` + + tmux [command] # Roda um [comando] + # 'tmux' sem comandos irá criar uma nova seção + + new # Cria uma nova seção + -s "Nome" # Cria uma nova seção com nome "Nome" + -n "Janela" # Cria uma janela com o nome "Janela" + -c "/dir" # Inícia em uma pasta específica + + attach # Reacopla a última seção disponível + -t "#" # Reacopla a seção com nome "#" + -d # Separa (Desacopla) a sessaão de outras instâncias. + + ls # Lista todas as seções + -a # Lista todas as seções abertas + + lsw # Lista as janelas + -a # Lista todas as janelas + -s # Lista todas janleas em uma seção + + lsp # Lista os painéis + -a # Lista todos os painéis + -s # Lista todos os painéis em uma seção + -t "#" # Lista os painéis baseado no nome "#" + + kill-window # Encerrar a janela corrente + -t "#" # Encerrar a janela baseado no nome "#" + -a # Encerrar todas as janelas + -a -t "#" # Encerrar todas as janelas exceto a com nome "#" + + kill-session # Encerrar seção corrente + -t "#" # Encerrar seção com nome "#" + -a # Encerrar todas as seções + -a -t "#" # Encerrar todas as seções exceto a com nome "#" + +``` + + +### Teclas de atalhos (comandos) + +A maneira de controllar uma seção tmux acoplada é através de uma +combinação de teclas de prefixo. + +``` +---------------------------------------------------------------------- + (C-b) = Ctrl + b # Combinação de prefixos para usar comandos(atalhos). + + (M-1) = Meta + 1 -or- Alt + 1 +---------------------------------------------------------------------- + + ? # Lista todos os comandos. + : # Acessa o lugar (prompt command) para receber comandos do tmux + r # Força a redefiniçao do cliente acoplado. + c # Cria uma nova janela. + + ! # Retira o painel corrente da janela. + % # Divide o painel corrente em dois para a esquerda e direita. + " # Divide o painel corrente em dois para cima e para baixo. + + n # Move para a próxima janela. + p # Move para a janela anterior. + { # Troca o painel corrente pelo anterior. + } # Troca o painel corrent pelo posterior. + + s # Seleciona uma nova seção para o cliente acoplado iterativamente. + w # Seleciona a janela corrente iterativamente. + 0 to 9 # Seleciona a janela de 0 à 9. + + d # Separa o cliente atual. + D # Seleciona um cliente a ser separado. + + & # Encerra a janela corrente. + x # Encerra o painel corrente. + + Up, Down # Move para o painel acima, abaixo, a esquerda ou a direita. + Left, Right + + M-1 to M-5 # Organiza os paines: + # 1) Horizontalmente de maneira igual + # 2) Verticalmente de maineira igual. + # 3) Principal horizontalmente + # 4) Principal verticamente. + # 5) Mosaico + + C-Up, C-Down # Altera o tamanho do painel corrente baseado em uma célula. + C-Left, C-Right + + M-Up, M-Down # Altera o tamanho do painel corrente baseado em cinco células. + M-Left, M-Right + +``` + + +### Configurando ~/.tmux.conf + +Existe um arquivo chamado tmux.conf, ele pode ser usado para definir opções no + momento de inicialização, da mesma maneira que .vimrc, init.el, .bash_profile são usados. + + +``` +# Exemplo de tmux.conf +# 2014.10 + + +### General +########################################################################### + +# Habilita UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Limite da história de comandos +set -g history-limit 2048 + +# Indíce de inicialização +set -g base-index 1 + +# Mouse +set-option -g mouse-select-pane on + +# Recarregar o arquivo de configuração sem a necessidade de reiniciar o programa +unbind r +bind r source-file ~/.tmux.conf + + +### Teclas de atalho +########################################################################### + +# Desvincular C-b como prefixo padrão. +unbind C-b + +# Define um novo prefixo padrão. +set-option -g prefix ` + +# Definir prefixos que podem ser usados para voltar para a janela anterior. +bind C-a last-window +bind ` last-window + +# Fazer com que F11 e F12 alterem o comportamento de C-a e ` +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` + +# Preferencia de teclas de atalho +setw -g mode-keys vi +set-option -g status-keys vi + +# Mover enter paineis com teclas de orientaçao do vim +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R + +# Iterar entre as Janelas +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +# Iterar entre os painéis +bind = split-window -h +bind - split-window -v +unbind '"' +unbind % + +# Habilitar a sub-seção a enviar comandos. +bind a send-prefix + + +### Theme +########################################################################### + +# Paleta de cores para a barra de status +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +# Paleta de cores para bordas do painel +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +# Palta de cores para mensagem +set-option -g message-fg black +set-option -g message-bg green + +# Paleta de cores para janela de status +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +# Notificações +setw -g monitor-activity on +set -g visual-activity on +set-option -g bell-action any +set-option -g visual-bell off + +# Definir automaticamente o título de janelas +set-option -g set-titles on +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) + +# Ajustes na barra de status +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" + +# Mostrar indicativos de performance na barra de status +# Requires https://github.com/thewtex/tmux-mem-cpu-load/ +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + + +### Referências + +[Tmux | Início](http://tmux.sourceforge.net) + +[Manual Tmux (em inglês)](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) + +[Mostrar CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) + +Possui uma sugestão? Uma correção, talvez? Abra um issue no Repositório GitHub, ou então faça um pull request. diff --git a/purescript.html.markdown b/purescript.html.markdown index a006cdff..6d8cfbb9 100644 --- a/purescript.html.markdown +++ b/purescript.html.markdown @@ -2,40 +2,49 @@ language: purescript contributors: - ["Fredrik Dyrkell", "http://www.lexicallyscoped.com"] + - ["Thimoteus", "https://github.com/Thimoteus"] --- PureScript is a small strongly, statically typed language compiling to Javascript. * Learn more at [http://www.purescript.org/](http://www.purescript.org/) -* Documentation: [http://docs.purescript.org/en/latest/](http://docs.purescript.org/en/latest/) +* Documentation: [http://pursuit.purescript.org/](http://pursuit.purescript.org/) * Book: Purescript by Example, [https://leanpub.com/purescript/](https://leanpub.com/purescript/) +All the noncommented lines of code can be run in the PSCI REPL, though some will +require the `--multi-line-mode` flag. + ```haskell -- -- 1. Primitive datatypes that corresponds to their Javascript -- equivalents at runtime. +import Prelude -- Numbers -1 + 7*5 :: Number -- 36 +1.0 + 7.2*5.5 :: Number -- 40.6 +-- Ints +1 + 2*5 :: Int -- 11 -- Types are inferred, so the following works fine -9 / 2.5 + 4.4 -- 8 +9.0/2.5 + 4.4 -- 8.0 +-- But Ints and Numbers don't mix, so the following won't +5/2 + 2.5 -- Expression 2.5 does not have type Int -- Hexadecimal literals 0xff + 1 -- 256 -- Unary negation 6 * -3 -- -18 6 * negate 3 -- -18 --- Modulus -3 % 2 -- 1 -4 % 2 -- 0 +-- Modulus, from purescript-math (Math) +3.0 % 2.0 -- 1.0 +4.0 % 2.0 -- 0.0 -- Inspect the type of an expression in psci -:t 9 / 2.5 + 4.4 -- Prim.Number +:t 9.5/2.5 + 4.4 -- Prim.Number -- Booleans true :: Boolean -- true false :: Boolean -- false -- Negation -not true --false +not true -- false 23 == 23 -- true 1 /= 4 -- true 1 >= 4 -- false @@ -49,19 +58,22 @@ true && (9 >= 19 || 1 < 2) -- true -- Strings "Hellow" :: String -- "Hellow" --- Multiline string +-- Multiline string without newlines, to run in psci use the --multi-line-mode flag "Hellow\ \orld" -- "Helloworld" +-- Multiline string with newlines +"""Hello +world""" -- "Hello\nworld" -- Concatenate "such " ++ "amaze" -- "such amaze" -- -- 2. Arrays are Javascript arrays, but must be homogeneous -[1,1,2,3,5,8] :: [Number] -- [1,1,2,3,5,8] -[true, true, false] :: [Boolean] -- [true,true,false] +[1,1,2,3,5,8] :: Array Number -- [1,1,2,3,5,8] +[true, true, false] :: Array Boolean -- [true,true,false] -- [1,2, true, "false"] won't work --- `Cannot unify Prim.Number with Prim.Boolean` +-- `Cannot unify Prim.Int with Prim.Boolean` -- Cons (prepend) 1 : [2,4,3] -- [1,2,4,3] @@ -84,91 +96,95 @@ append [1,2,3] [4,5,6] -- [1,2,3,4,5,6] -- -- 3. Records are Javascript objects, with zero or more fields, which --- can have different types +-- can have different types. +-- In psci you have to write `let` in front of the function to get a +-- top level binding. let book = {title: "Foucault's pendulum", author: "Umberto Eco"} -- Access properties book.title -- "Foucault's pendulum" -getTitle b = b.title +let getTitle b = b.title -- Works on all records with a title (but doesn't require any other field) getTitle book -- "Foucault's pendulum" getTitle {title: "Weekend in Monaco", artist: "The Rippingtons"} -- "Weekend in Monaco" +-- Can use underscores as shorthand +_.title book -- "Foucault's pendulum" -- Update a record -changeTitle b t = b {title = t} -changeTitle book "Ill nome della rosa" -- {title: "Ill nome della - -- rosa", author: "Umberto Eco"} +let changeTitle b t = b {title = t} +getTitle (changeTitle book "Ill nome della rosa") -- "Ill nome della rosa" -- -- 4. Functions -sumOfSquares x y = x*x+y*y +-- In psci's multiline mode +let sumOfSquares :: Int -> Int -> Int + sumOfSquares x y = x*x + y*y sumOfSquares 3 4 -- 25 --- In psci you have to write `let` in front of the function to get a --- top level binding -mod x y = x % y -mod 3 2 -- 1 +let myMod x y = x % y +myMod 3.0 2.0 -- 1.0 -- Infix application of function 3 `mod` 2 -- 1 --- function application have higher precedence than all other +-- function application has higher precedence than all other -- operators sumOfSquares 3 4 * sumOfSquares 4 5 -- 1025 -- Conditional -abs' n = if n>=0 then n else -n +let abs' n = if n>=0 then n else -n abs' (-3) -- 3 -- Guarded equations -abs n | n >= 0 = n - | otherwise = -n +let abs'' n | n >= 0 = n + | otherwise = -n -- Pattern matching --- Note the type signature, input is an array of numbers The pattern --- matching destructures and binds the array into parts -first :: [Number] -> Number -first (x:_) = x -first [3,4,5] -- 3 -second :: [Number] -> Number -second (_:y:_) = y -second [3,4,5] -- 4 -sumTwo :: [Number] -> [Number] -sumTwo (x:y:rest) = (x+y) : rest -sumTwo [2,3,4,5,6] -- [5,4,5,6] - --- sumTwo doesn't handle when the array is empty or just have one --- element in which case you get an error +-- Note the type signature, input is a list of numbers. The pattern matching +-- destructures and binds the list into parts. +-- Requires purescript-lists (Data.List) +let first :: forall a. List a -> a + first (Cons x _) = x +first (toList [3,4,5]) -- 3 +let second :: forall a. List a -> a + second (Cons _ (Cons y _)) = y +second (toList [3,4,5]) -- 4 +let sumTwo :: List Int -> List Int + sumTwo (Cons x (Cons y rest)) = x + y : rest +fromList (sumTwo (toList [2,3,4,5,6])) :: Array Int -- [5,4,5,6] + +-- sumTwo doesn't handle when the list is empty or there's only one element in +-- which case you get an error. sumTwo [1] -- Failed pattern match -- Complementing patterns to match -- Good ol' Fibonacci -fib 1 = 1 -fib 2 = 2 -fib x = fib (x-1) + fib (x-2) +let fib 1 = 1 + fib 2 = 2 + fib x = fib (x-1) + fib (x-2) fib 10 -- 89 -- Use underscore to match any, where you don't care about the binding name -isZero 0 = true -isZero _ = false +let isZero 0 = true + isZero _ = false -- Pattern matching on records -ecoTitle {author = "Umberto Eco", title = t} = Just t -ecoTitle _ = Nothing +let ecoTitle {author = "Umberto Eco", title = t} = Just t + ecoTitle _ = Nothing ecoTitle book -- Just ("Foucault's pendulum") ecoTitle {title: "The Quantum Thief", author: "Hannu Rajaniemi"} -- Nothing -- ecoTitle requires both field to type check: -ecoTitle {title: "The Quantum Thief"} -- Object does not have property author +ecoTitle {title: "The Quantum Thief"} -- Object lacks required property "author" -- Lambda expressions (\x -> x*x) 3 -- 9 (\x y -> x*x + y*y) 4 5 -- 41 -sqr = \x -> x*x +let sqr = \x -> x*x -- Currying -add x y = x + y -- is equivalent with -add = \x -> (\y -> x+y) -add3 = add 3 -:t add3 -- Prim.Number -> Prim.Number +let myAdd x y = x + y -- is equivalent with +let myAdd' = \x -> \y -> x + y +let add3 = myAdd 3 +:t add3 -- Prim.Int -> Prim.Int -- Forward and backward function composition -- drop 3 followed by taking 5 @@ -177,9 +193,9 @@ add3 = add 3 (drop 3 <<< take 5) (1..20) -- [4,5] -- Operations using higher order functions -even x = x % 2 == 0 +let even x = x `mod` 2 == 0 filter even (1..10) -- [2,4,6,8,10] -map (\x -> x+11) (1..5) -- [12,13,14,15,16] +map (\x -> x + 11) (1..5) -- [12,13,14,15,16] -- Requires purescript-foldable-traversabe (Data.Foldable) diff --git a/python.html.markdown b/python.html.markdown index 5b36083d..b939ebbe 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -14,7 +14,13 @@ executable pseudocode. Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] Note: This article applies to Python 2.7 specifically, but should be applicable -to Python 2.x. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). +to Python 2.x. Python 2.7 is reachong end of life and will stop beeign maintained in 2020, +it is though recommended to start learnign Python with Python 3. +For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). + +It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same time, +using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports +allow you to write Python 3 code that will run on Python 2, so check out the Python 3 tutorial. ```python @@ -144,6 +150,12 @@ bool("") # => False # Python has a print statement print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! +# Simple way to get input data from console +input_string_var = raw_input("Enter some data: ") # Returns the data as a string +input_var = input("Enter some data: ") # Evaluates the data as python code +# Warning: Caution is recommended for input() method usage +# Note: In python 3, input() is deprecated and raw_input() is renamed to input() + # No need to declare variables before assigning to them. some_var = 5 # Convention is to use lower_case_with_underscores some_var # => 5 diff --git a/python3.html.markdown b/python3.html.markdown index 87fa0b70..a1125c73 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -33,27 +33,27 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea 3 # => 3 # Math is what you would expect -1 + 1 # => 2 -8 - 1 # => 7 +1 + 1 # => 2 +8 - 1 # => 7 10 * 2 # => 20 # Except division which returns floats, real numbers, by default 35 / 5 # => 7.0 # Result of integer division truncated down both for positive and negative. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # works on floats too --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 # When you use a float, results are floats -3 * 2.0 # => 6.0 +3 * 2.0 # => 6.0 # Modulo operation -7 % 3 # => 1 +7 % 3 # => 1 # Exponentiation (x**y, x to the yth power) -2**4 # => 16 +2**4 # => 16 # Enforce precedence with parentheses (1 + 3) * 2 # => 8 @@ -63,20 +63,20 @@ True False # negate with not -not True # => False +not True # => False not False # => True # Boolean Operators # Note "and" and "or" are case-sensitive -True and False #=> False -False or True #=> True +True and False # => False +False or True # => True # Note using Bool operators with ints -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True # Equality is == 1 == 1 # => True @@ -98,13 +98,13 @@ False or True #=> True # (is vs. ==) is checks if two variable refer to the same object, but == checks # if the objects pointed to have the same values. -a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] -b = a # Point b at what a is pointing to -b is a # => True, a and b refer to the same object -b == a # => True, a's and b's objects are equal -b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] -b is a # => False, a and b do not refer to the same object -b == a # => True, a's and b's objects are equal +a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] +b = a # Point b at what a is pointing to +b is a # => True, a and b refer to the same object +b == a # => True, a's and b's objects are equal +b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] +b is a # => False, a and b do not refer to the same object +b == a # => True, a's and b's objects are equal # Strings are created with " or ' "This is a string." @@ -113,24 +113,24 @@ b == a # => True, a's and b's objects are equal # Strings can be added too! But try not to do this. "Hello " + "world!" # => "Hello world!" # Strings can be added without using '+' -"Hello " "world!" # => "Hello world!" +"Hello " "world!" # => "Hello world!" # A string can be treated like a list of characters "This is a string"[0] # => 'T' # .format can be used to format strings, like this: -"{} can be {}".format("strings", "interpolated") +"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" # You can repeat the formatting arguments to save some typing. "{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" # You can use keywords if you don't want to count. -"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" +"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" # If your Python 3 code also needs to run on Python 2.5 and below, you can also # still use the old style of formatting: -"%s can be %s the %s way" % ("strings", "interpolated", "old") +"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" # None is an object @@ -139,14 +139,14 @@ None # => None # Don't use the equality "==" symbol to compare objects to None # Use "is" instead. This checks for equality of object identity. "etc" is None # => False -None is None # => True +None is None # => True # None, 0, and empty strings/lists/dicts all evaluate to False. # All other values are True -bool(0) # => False +bool(0) # => False bool("") # => False -bool([]) #=> False -bool({}) #=> False +bool([]) # => False +bool({}) # => False #################################################### @@ -154,11 +154,15 @@ bool({}) #=> False #################################################### # Python has a print function -print("I'm Python. Nice to meet you!") +print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! # By default the print function also prints out a newline at the end. # Use the optional argument end to change the end character. -print("Hello, World", end="!") # => Hello, World! +print("Hello, World", end="!") # => Hello, World! + +# Simple way to get input data from console +input_string_var = input("Enter some data: ") # Returns the data as a string +# Note: In earlier versions of Python, input() method was named as raw_input() # No need to declare variables before assigning to them. # Convention is to use lower_case_with_underscores @@ -185,7 +189,7 @@ li.pop() # => 3 and li is now [1, 2, 4] li.append(3) # li is now [1, 2, 4, 3] again. # Access a list like you would any array -li[0] # => 1 +li[0] # => 1 # Look at the last element li[-1] # => 3 @@ -194,61 +198,61 @@ li[4] # Raises an IndexError # You can look at ranges with slice syntax. # (It's a closed/open range for you mathy types.) -li[1:3] # => [2, 4] +li[1:3] # => [2, 4] # Omit the beginning -li[2:] # => [4, 3] +li[2:] # => [4, 3] # Omit the end -li[:3] # => [1, 2, 4] +li[:3] # => [1, 2, 4] # Select every second entry li[::2] # =>[1, 4] # Return a reversed copy of the list -li[::-1] # => [3, 4, 2, 1] +li[::-1] # => [3, 4, 2, 1] # Use any combination of these to make advanced slices # li[start:end:step] # Make a one layer deep copy using slices -li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. +li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. # Remove arbitrary elements from a list with "del" -del li[2] # li is now [1, 2, 3] +del li[2] # li is now [1, 2, 3] # You can add lists # Note: values for li and for other_li are not modified. -li + other_li # => [1, 2, 3, 4, 5, 6] +li + other_li # => [1, 2, 3, 4, 5, 6] # Concatenate lists with "extend()" -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] # Check for existence in a list with "in" -1 in li # => True +1 in li # => True # Examine the length with "len()" -len(li) # => 6 +len(li) # => 6 # Tuples are like lists but are immutable. tup = (1, 2, 3) -tup[0] # => 1 +tup[0] # => 1 tup[0] = 3 # Raises a TypeError # Note that a tuple of length one has to have a comma after the last element but # tuples of other lengths, even zero, do not. -type((1)) # => <class 'int'> -type((1,)) # => <class 'tuple'> -type(()) # => <class 'tuple'> +type((1)) # => <class 'int'> +type((1,)) # => <class 'tuple'> +type(()) # => <class 'tuple'> # You can do most of the list operations on tuples too -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True # You can unpack tuples (or lists) into variables -a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 # Tuples are created by default if you leave out the parentheses d, e, f = 4, 5, 6 # Now look how easy it is to swap two values -e, d = d, e # d is now 5 and e is now 4 +e, d = d, e # d is now 5 and e is now 4 # Dictionaries store mappings @@ -259,45 +263,45 @@ filled_dict = {"one": 1, "two": 2, "three": 3} # Note keys for dictionaries have to be immutable types. This is to ensure that # the key can be converted to a constant hash value for quick look-ups. # Immutable types include ints, floats, strings, tuples. -invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list' -valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. +invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. # Look up values with [] -filled_dict["one"] # => 1 +filled_dict["one"] # => 1 # Get all keys as an iterable with "keys()". We need to wrap the call in list() # to turn it into a list. We'll talk about those later. Note - Dictionary key # ordering is not guaranteed. Your results might not match this exactly. -list(filled_dict.keys()) # => ["three", "two", "one"] +list(filled_dict.keys()) # => ["three", "two", "one"] # Get all values as an iterable with "values()". Once again we need to wrap it # in list() to get it out of the iterable. Note - Same as above regarding key # ordering. -list(filled_dict.values()) # => [3, 2, 1] +list(filled_dict.values()) # => [3, 2, 1] # Check for existence of keys in a dictionary with "in" -"one" in filled_dict # => True -1 in filled_dict # => False +"one" in filled_dict # => True +1 in filled_dict # => False # Looking up a non-existing key is a KeyError -filled_dict["four"] # KeyError +filled_dict["four"] # KeyError # Use "get()" method to avoid the KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None # The get method supports a default argument when the value is missing filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 +filled_dict.get("four", 4) # => 4 # "setdefault()" inserts into a dictionary only if the given key isn't present filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 # Adding to a dictionary -filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} -#filled_dict["four"] = 4 #another way to add to dict +filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 #another way to add to dict # Remove keys from a dictionary with del del filled_dict["one"] # Removes the key "one" from filled dict @@ -306,31 +310,31 @@ del filled_dict["one"] # Removes the key "one" from filled dict # Sets store ... well sets empty_set = set() # Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. -some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} +some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} # Similar to keys of a dictionary, elements of a set have to be immutable. -invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list' +invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list' valid_set = {(1,), 1} # Can set new variables to a set filled_set = some_set # Add one more item to the set -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} # Do set intersection with & other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} +filled_set & other_set # => {3, 4, 5} # Do set union with | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} +filled_set | other_set # => {1, 2, 3, 4, 5, 6} # Do set difference with - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} # Check for existence in a set with in 2 in filled_set # => True -10 in filled_set # => False +10 in filled_set # => False @@ -416,12 +420,12 @@ try: # Use "raise" to raise an error raise IndexError("This is an index error") except IndexError as e: - pass # Pass is just a no-op. Usually you would do recovery here. + pass # Pass is just a no-op. Usually you would do recovery here. except (TypeError, NameError): - pass # Multiple exceptions can be handled together, if required. -else: # Optional clause to the try/except block. Must follow all except blocks + pass # Multiple exceptions can be handled together, if required. +else: # Optional clause to the try/except block. Must follow all except blocks print("All good!") # Runs only if the code in try raises no exceptions -finally: # Execute under all circumstances +finally: # Execute under all circumstances print("We can clean up resources here") # Instead of try/finally to cleanup resources you can use a with statement @@ -435,11 +439,11 @@ with open("myfile.txt") as f: filled_dict = {"one": 1, "two": 2, "three": 3} our_iterable = filled_dict.keys() -print(our_iterable) #=> range(1,10). This is an object that implements our Iterable interface +print(our_iterable) # => range(1,10). This is an object that implements our Iterable interface # We can loop over it. for i in our_iterable: - print(i) # Prints one, two, three + print(i) # Prints one, two, three # However we cannot address elements by index. our_iterable[1] # Raises a TypeError @@ -449,17 +453,17 @@ our_iterator = iter(our_iterable) # Our iterator is an object that can remember the state as we traverse through it. # We get the next object with "next()". -next(our_iterator) #=> "one" +next(our_iterator) # => "one" # It maintains state as we iterate. -next(our_iterator) #=> "two" -next(our_iterator) #=> "three" +next(our_iterator) # => "two" +next(our_iterator) # => "three" # After the iterator has returned all of its data, it gives you a StopIterator Exception -next(our_iterator) # Raises StopIteration +next(our_iterator) # Raises StopIteration # You can grab all the elements of an iterator by calling list() on it. -list(filled_dict.keys()) #=> Returns ["one", "two", "three"] +list(filled_dict.keys()) # => Returns ["one", "two", "three"] #################################################### @@ -469,20 +473,20 @@ list(filled_dict.keys()) #=> Returns ["one", "two", "three"] # Use "def" to create new functions def add(x, y): print("x is {} and y is {}".format(x, y)) - return x + y # Return values with a return statement + return x + y # Return values with a return statement # Calling functions with parameters -add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 +add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 # Another way to call functions is with keyword arguments -add(y=6, x=5) # Keyword arguments can arrive in any order. +add(y=6, x=5) # Keyword arguments can arrive in any order. # You can define functions that take a variable number of # positional arguments def varargs(*args): return args -varargs(1, 2, 3) # => (1, 2, 3) +varargs(1, 2, 3) # => (1, 2, 3) # You can define functions that take a variable number of # keyword arguments, as well @@ -490,7 +494,7 @@ def keyword_args(**kwargs): return kwargs # Let's call it to see what happens -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} # You can do both at once, if you like @@ -507,33 +511,33 @@ all_the_args(1, 2, a=3, b=4) prints: # Use * to expand tuples and use ** to expand kwargs. args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalent to foo(1, 2, 3, 4) -all_the_args(**kwargs) # equivalent to foo(a=3, b=4) -all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) +all_the_args(*args) # equivalent to foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalent to foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) # Returning multiple values (with tuple assignments) def swap(x, y): - return y, x # Return multiple values as a tuple without the parenthesis. - # (Note: parenthesis have been excluded but can be included) + return y, x # Return multiple values as a tuple without the parenthesis. + # (Note: parenthesis have been excluded but can be included) x = 1 y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included. +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included. # Function Scope x = 5 def setX(num): # Local var x not the same as global variable x - x = num # => 43 - print (x) # => 43 + x = num # => 43 + print (x) # => 43 def setGlobalX(num): global x - print (x) # => 5 - x = num # global var x is now set to 6 - print (x) # => 6 + print (x) # => 5 + x = num # global var x is now set to 6 + print (x) # => 6 setX(43) setGlobalX(6) @@ -549,20 +553,20 @@ add_10 = create_adder(10) add_10(3) # => 13 # There are also anonymous functions -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 # TODO - Fix for iterables # There are built-in higher order functions -map(add_10, [1, 2, 3]) # => [11, 12, 13] -map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] +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] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # We can use list comprehensions for nice maps and filters # List comprehension stores the output as a list which can itself be a nested list -[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] +[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 @@ -609,15 +613,15 @@ j = Human("Joel") print(j.say("hello")) # prints out "Joel: hello" # Call our class method -i.get_species() # => "H. sapiens" +i.get_species() # => "H. sapiens" # Change the shared attribute Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" # Call the static method -Human.grunt() # => "*grunt*" +Human.grunt() # => "*grunt*" #################################################### @@ -630,8 +634,8 @@ print(math.sqrt(16)) # => 4 # 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 +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 @@ -639,7 +643,7 @@ from math import * # You can shorten module names import math as m -math.sqrt(16) == m.sqrt(16) # => True +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 @@ -698,7 +702,7 @@ def say(say_please=False): return msg, say_please -print(say()) # Can you buy me a beer? +print(say()) # Can you buy me a beer? print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ``` @@ -715,6 +719,9 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [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 diff --git a/pythonstatcomp.markdown.html b/pythonstatcomp.markdown.html new file mode 100644 index 00000000..78b62e33 --- /dev/null +++ b/pythonstatcomp.markdown.html @@ -0,0 +1,234 @@ +--- +language: Statistical computing with Python +contributors: + - ["e99n09", "https://github.com/e99n09"] +filename: pythonstatcomp.py +--- + +This is a tutorial on how to do some typical statistical programming tasks using Python. It's intended for people basically familiar with Python and experienced at statistical programming in a language like R, Stata, SAS, SPSS, or MATLAB. + +```python + +# 0. Getting set up ==== + +""" Get set up with IPython and pip install the following: numpy, scipy, pandas, + matplotlib, seaborn, requests. + Make sure to do this tutorial in the IPython notebook so that you get + the inline plots and easy documentation lookup. +""" + +# 1. Data acquisition ==== + +""" One reason people choose Python over R is that they intend to interact a lot + with the web, either by scraping pages directly or requesting data through + an API. You can do those things in R, but in the context of a project + already using Python, there's a benefit to sticking with one language. +""" + +import requests # for HTTP requests (web scraping, APIs) +import os + +# web scraping +r = requests.get("https://github.com/adambard/learnxinyminutes-docs") +r.status_code # if 200, request was successful +r.text # raw page source +print(r.text) # prettily formatted +# save the page source in a file: +os.getcwd() # check what's the working directory +f = open("learnxinyminutes.html","wb") +f.write(r.text.encode("UTF-8")) +f.close() + +# downloading a csv +fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/" +fn = "pets.csv" +r = requests.get(fp + fn) +print(r.text) +f = open(fn,"wb") +f.write(r.text.encode("UTF-8")) +f.close() + +""" for more on the requests module, including APIs, see + http://docs.python-requests.org/en/latest/user/quickstart/ +""" + +# 2. Reading a CSV file ==== + +""" Wes McKinney's pandas package gives you 'DataFrame' objects in Python. If + you've used R, you will be familiar with the idea of the "data.frame" already. +""" + +import pandas as pd, numpy as np, scipy as sp +pets = pd.read_csv(fn) +pets +# name age weight species +# 0 fluffy 3 14 cat +# 1 vesuvius 6 23 fish +# 2 rex 5 34 dog + +""" R users: note that Python, like most normal programming languages, starts + indexing from 0. R is the unusual one for starting from 1. +""" + +# two different ways to print out a column +pets.age +pets["age"] + +pets.head(2) # prints first 2 rows +pets.tail(1) # prints last row + +pets.name[1] # 'vesuvius' +pets.species[0] # 'cat' +pets["weight"][2] # 34 + +# in R, you would expect to get 3 rows doing this, but here you get 2: +pets.age[0:2] +# 0 3 +# 1 6 + +sum(pets.age)*2 # 28 +max(pets.weight) - min(pets.weight) # 20 + +""" If you are doing some serious linear algebra and number-crunching, you may + just want arrays, not DataFrames. DataFrames are ideal for combining columns + of different types. +""" + +# 3. Charts ==== + +import matplotlib as mpl, matplotlib.pyplot as plt +%matplotlib inline + +# To do data vizualization in Python, use matplotlib + +plt.hist(pets.age); + +plt.boxplot(pets.weight); + +plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); + +# seaborn sits atop matplotlib and makes plots prettier + +import seaborn as sns + +plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); + +# there are also some seaborn-specific plotting functions +# notice how seaborn automatically labels the x-axis on this barplot +sns.barplot(pets["age"]) + +# R veterans can still use ggplot +from ggplot import * +ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") +# source: https://pypi.python.org/pypi/ggplot + +# there's even a d3.js port: https://github.com/mikedewar/d3py + +# 4. Simple data cleaning and exploratory analysis ==== + +""" Here's a more complicated example that demonstrates a basic data + cleaning workflow leading to the creation of some exploratory plots + and the running of a linear regression. + The data set was transcribed from Wikipedia by hand. It contains + all the Holy Roman Emperors and the important milestones in their lives + (birth, death, coronation, etc.). + The goal of the analysis will be to explore whether a relationship + exists between emperor birth year and emperor lifespan. + data source: https://en.wikipedia.org/wiki/Holy_Roman_Emperor +""" + +# load some data on Holy Roman Emperors +url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" +r = requests.get(url) +fp = "hre.csv" +f = open(fp,"wb") +f.write(r.text.encode("UTF-8")) +f.close() + +hre = pd.read_csv(fp) + +hre.head() +""" + Ix Dynasty Name Birth Death Election 1 +0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN +1 NaN Carolingian Louis I 778 20 June 840 NaN +2 NaN Carolingian Lothair I 795 29 September 855 NaN +3 NaN Carolingian Louis II 825 12 August 875 NaN +4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN + + Election 2 Coronation 1 Coronation 2 Ceased to be Emperor +0 NaN 25 December 800 NaN 28 January 814 +1 NaN 11 September 813 5 October 816 20 June 840 +2 NaN 5 April 823 NaN 29 September 855 +3 NaN Easter 850 18 May 872 12 August 875 +4 NaN 29 December 875 NaN 6 October 877 + + Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 +0 NaN NaN NaN NaN +1 Charles I son NaN NaN +2 Louis I son NaN NaN +3 Lothair I son NaN NaN +4 Louis I son NaN NaN +""" + +# clean the Birth and Death columns + +import re # module for regular expressions + +rx = re.compile(r'\d+$') # match trailing digits + +""" This function applies the regular expression to an input column (here Birth, + Death), flattens the resulting list, converts it to a Series object, and + finally converts the type of the Series object from string to integer. For + more information into what different parts of the code do, see: + - https://docs.python.org/2/howto/regex.html + - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list + - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html +""" +def extractYear(v): + return(pd.Series(reduce(lambda x,y: x+y,map(rx.findall,v),[])).astype(int)) + +hre["BirthY"] = extractYear(hre.Birth) +hre["DeathY"] = extractYear(hre.Death) + +# make a column telling estimated age +hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int) + +# simple scatterplot, no trend line, color represents dynasty +sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False); + +# use scipy to run a linear regression +from scipy import stats +(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge) +# code source: http://wiki.scipy.org/Cookbook/LinearRegression + +# check the slope +slope # 0.0057672618839073328 + +# check the R^2 value: +rval**2 # 0.020363950027333586 + +# check the p-value +pval # 0.34971812581498452 + +# use seaborn to make a scatterplot and plot the linear regression trend line +sns.lmplot("BirthY", "EstAge", data=hre); + +""" For more information on seaborn, see + - http://web.stanford.edu/~mwaskom/software/seaborn/ + - https://github.com/mwaskom/seaborn + For more information on SciPy, see + - http://wiki.scipy.org/SciPy + - http://wiki.scipy.org/Cookbook/ + To see a version of the Holy Roman Emperors analysis using R, see + - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R +""" +``` + +If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial. + +You can also find plenty of interactive IPython tutorials on subjects specific to your interests, like Cam Davidson-Pilon's <a href="http://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/" Title="Probabilistic Programming and Bayesian Methods for Hackers">Probabilistic Programming and Bayesian Methods for Hackers</a>. + +Some more modules to research: + - text analysis and natural language processing: nltk, http://www.nltk.org + - social network analysis: igraph, http://igraph.org/python/ diff --git a/ru-ru/css-ru.html.markdown b/ru-ru/css-ru.html.markdown new file mode 100644 index 00000000..2e2d40b7 --- /dev/null +++ b/ru-ru/css-ru.html.markdown @@ -0,0 +1,250 @@ +--- +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Geoffrey Liu", "https://github.com/g-liu"] +filename: learncss-ru.css +lang: ru-ru +--- + +В свои ранние дни веб состоял в основном из чистого текста. С развитием браузеров +веб-страницы с графическими элементами стали обычным делом. +CSS - язык, разграничивающий содержимое (HTML) и внешний вид веб-страниц. + +Если коротко, то CSS предоставляет синтаксис, позволяющий выбирать различные +HTML элементы и определять их внешний вид. + +Как и у других языков, у CSS много версий. Мы описываем CSS2.0 - не самую новую, +но самую поддерживаемую и распространенную версию. + +**ВАЖНО:** Так как результатом применения CSS является изменение внешнего вида +элементов, постарайтесь использовать CSS-песочницы при изучении языка. +Например [dabblet](http://dabblet.com/). +В данной статье рассматриваются в первую очередь синтаксис и общие рекомендации. + + +```css +/* Для комментариев используется слеш-астериск, как на этой строчке. + В CSS нет однострочных комментариев; все комментарии записываются таким способом */ + +/* #################### + ## СЕЛЕКТОРЫ + #################### */ + +/* Выражения в CSS очень просты */ +селектор { атрибут: значение; /* другие атрибуты...*/ } + +/* селекторы используются для выбора элементов на странице + +Чтобы выбрать все элементы, используйте астериск: */ +* { color:red; } + +/* +Если на странице присутствует такой элемент: + +<div class='some-class class2' id='someId' attr='value' otherAttr='en-us foo bar' /> +*/ + +/* его можно выбрать по одному классу */ +.some-class { } + +/* или по обоим классам */ +.some-class.class2 { } + +/* по названию тега */ +div { } + +/* по идентификатору */ +#someId { } + +/* по имеющемуся атрибуту */ +[attr] { font-size:smaller; } + +/* или по атрибуту с определенным значением */ +[attr='value'] { font-size:smaller; } + +/* можно выбрать атрибуты, начинающиеся с определенного значения (CSS3) */ +[attr^='val'] { font-size:smaller; } + +/* или заканчивающиеся определенным значением (CSS3) */ +[attr$='ue'] { font-size:smaller; } + +/* содержащие отделенное пробелами значение в названии атрибута (CSS3) */ +[otherAttr~='foo'] { font-size:smaller; } + +/* можно выбрать атрибут как с точным, так и со стоящим после значения “-” (U+002D) */ +[otherAttr|='en'] { font-size:smaller; } + + +/* Более того, все это можно использовать вместе - между разными частями +не должно быть пробелов, иначе селектор будет иметь совершенно иное значение */ +div.some-class[attr$='ue'] { } + +/* Вы можете выбрать элемент по его родителю */ + +/* прямой потомок другого элемента (выбранного с помощью селектора) */ +div.some-parent > .class-name {} + +/* потомок любого родителя в дереве элементов + следующая строка означает: "любой элемент класса "class-name", + являющийся потомком div-элемента класса "some-parent" + НЕЗАВИСИМО ОТ УРОВНЯ ВЛОЖЕННОСТИ" */ +div.some-parent .class-name {} + +/* важно: этот же селектор без пробелов имеет иное значение + можете догадаться, какое? */ +div.some-parent.class-name {} + +/* вы можете выбрать элемент по первому предшествующему + родственному элементу */ +.i-am-before + .this-element { } + +/* или любому предшествующему родственнику перед элементом */ +.i-am-any-before ~ .this-element {} + + +/* Существуют псевдо-классы, позволяющие изменять внешний вид элемента + в зависимости от событий, произошедших с элементом */ + +/* например, когда курсор наведен на элемент */ +element:hover {} + +/* когда пользователь проходил по ссылке ранее */ +element:visited {} + +/* или еще не проходил по ней */ +element:link {} + +/* выбранное поле воода (input) */ +element:focus {} + + +/* #################### + ## АТРИБУТЫ + #################### */ + +selector { + + /* Единицы измерения */ + width: 50%; /* проценты */ + font-size: 2em; /* умножается на высоту шрифта (2em - в два раза больше) */ + width: 200px; /* пиксели */ + font-size: 20pt; /* пункты */ + width: 5cm; /* сантиметры */ + min-width: 50mm; /* милиметры */ + max-width: 5in; /* дюймы */ + height: 0.2vh; /* умножается на высоту окна браузера (CSS3) */ + width: 0.4vw; /* умножается на ширину окна браузера (CSS3) */ + min-height: 0.1vmin; /* наименьшее из vh и vw (CSS3) */ + max-width: 0.3vmax; /* наибольшее из vh и vw (CSS3) */ + + /* Цвета */ + background-color: #F6E; /* сокращенная запись шестнадцатеричного кода */ + background-color: #F262E2; /* стандартная запись шестнадцатеричного кода */ + background-color: tomato; /* название цвета */ + background-color: rgb(255, 255, 255); /* цветовая модель rgb */ + background-color: rgb(10%, 20%, 50%); /* цветовая модель rgb в процентах */ + background-color: rgba(255, 0, 0, 0.3); /* цветовая модель rgb (последний аргумент отвечает за прозрачность цвета) (CSS3) */ + background-color: transparent; /* прозрачный цвет */ + background-color: hsl(0, 100%, 50%); /* в формате hsl (CSS3) */ + background-color: hsla(0, 100%, 50%, 0.3); /* в формате hsl (последний аргумент отвечает за непрозрачность цвета) (CSS3) */ + + + /* Изображения */ + background-image: url(/path-to-image/image.jpg); /* кавычки внутри url() опциональны */ + + /* Шрифты */ + font-family: Arial; + font-family: "Courier New"; /* если в названии есть пробелы, заключите его в кавычки */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; /* если шрифт не найден, + будет использован следующий за ним в списке */ +} + +``` + +## Использование + +Сохраните готовый файл с расширением .css + +```xml +<!-- добавьте css файл в тег <head> на странице: --> +<link rel='stylesheet' type='text/css' href='path/to/style.css' /> + +<!-- Можно использовать встроенные стили. Рекомендуется избегать подобного подхода. --> +<body> + <style> + a { color: purple; } + </style> +</body> + +<!-- Можно установить стиль элемента напрямую. +Используйте этот способ только в случае крайней необходимости. --> +<div style="border: 1px solid red;"> +</div> + +``` + +## Приоритет + +Как вы заметили, внешний вид элемента может определяться несколькими селекторами, +а значение атрибута элемента может быть установлено больше одного раза. +В подобных случаях одно из значений оказывается приоритетнее остальных. + +Если взять следующую таблицу стилей: + +```css +/*A*/ +p.class1[attr='value'] + +/*B*/ +p.class1 {} + +/*C*/ +p.class2 {} + +/*D*/ +p {} + +/*E*/ +p { property: value !important; } + +``` + +и следующую разметку: + +```xml +<p style='/*F*/ property:value;' class='class1 class2' attr='value'> +</p> +``` + +Приоритет стилей будет таким: +Помните: приоритет выставляется для **атрибута**, а не для всего блока стилей. + +* `E` имеет наивысший приоритет благодаря ключевому слову `!important`. + Используйте только в случае крайней необходимости. +* `F` идет следующим, так как является встроенным стилем. +* `A` следующий, как самый конкретизированный. + конкретизированный == большее количество определителей. + В этом примере 3 определителя: 1 тег `p` + + название класса `class1` + 1 атрибут `attr='value'` +* `C` следующий. Несмотря на одинаковое с `B` количество определителей, + `C` определен позже. +* Затем `B` +* И последний `D`. + +## Совместимость + +Несмотря на то, что большая часть функций CSS2 (а также CSS3) подеррживается всеми +браузерами и устройствами, не забывайте проверять совместимость CSS-правил +с современными браузерами. + +[QuirksMode CSS](http://www.quirksmode.org/css/) замечательно подходит для этого. + +To run a quick compatibility check, [CanIUse](http://caniuse.com) is a great resource. + +## Ресурсы для самостоятельного изучения + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown index a0e2b474..3852a550 100644 --- a/ru-ru/python-ru.html.markdown +++ b/ru-ru/python-ru.html.markdown @@ -167,6 +167,10 @@ li = [] # Можно сразу начать с заполненного списка other_li = [4, 5, 6] +# строка разделена в список +a="adambard" +list(a) #=> ['a','d','a','m','b','a','r','d'] + # Объекты добавляются в конец списка методом append li.append(1) # [1] li.append(2) # [1, 2] @@ -238,7 +242,6 @@ d, e, f = 4, 5, 6 # Обратите внимание, как легко поменять местами значения двух переменных e, d = d, e # теперь d == 5, а e == 4 - # Словари содержат ассоциативные массивы empty_dict = {} # Вот так описывается предзаполненный словарь diff --git a/ruby.html.markdown b/ruby.html.markdown index c10255d8..4e9f8aee 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -12,8 +12,8 @@ contributors: - ["Dzianis Dashkevich", "https://github.com/dskecse"] - ["Levi Bostian", "https://github.com/levibostian"] - ["Rahil Momin", "https://github.com/iamrahil"] - - ["Gabriel Halley", https://github.com/ghalley] - + - ["Gabriel Halley", "https://github.com/ghalley"] + - ["Persa Zula", "http://persazula.com"] --- ```ruby @@ -108,6 +108,12 @@ placeholder = 'use string interpolation' 'hello ' + 3 #=> TypeError: can't convert Fixnum into String 'hello ' + 3.to_s #=> "hello 3" +# Combine strings and operators +'hello ' * 3 #=> "hello hello hello " + +# Append to string +'hello' << ' world' #=> "hello world" + # print to the output with a newline at the end puts "I'm printing!" #=> I'm printing! @@ -285,7 +291,7 @@ end #=> iteration 4 #=> iteration 5 -# There are a bunch of other helpful looping functions in Ruby, +# There are a bunch of other helpful looping functions in Ruby, # for example "map", "reduce", "inject", the list goes on. Map, # for instance, takes the array it's looping over, does something # to it as defined in your block, and returns an entirely new array. diff --git a/sass.html.markdown b/sass.html.markdown index 509aee9b..02bec47f 100644 --- a/sass.html.markdown +++ b/sass.html.markdown @@ -3,6 +3,7 @@ language: sass filename: learnsass.scss contributors: - ["Laura Kyle", "https://github.com/LauraNK"] + - ["Sean Corrales", "https://github.com/droidenator"] --- Sass is a CSS extension language that adds features such as variables, nesting, mixins and more. @@ -11,6 +12,7 @@ Sass (and other preprocessors, such as [Less](http://lesscss.org/)) help develop Sass has two different syntax options to choose from. SCSS, which has the same syntax as CSS but with the added features of Sass. Or Sass (the original syntax), which uses indentation rather than curly braces and semicolons. This tutorial is written using SCSS. +If you're already familiar with CSS3, you'll be able to pick up Sass relatively quickly. It does not provide any new styling options but rather the tools to write your CSS more efficiently and make maintenance much easier. ```scss @@ -121,6 +123,69 @@ div { +/*Functions +==============================*/ + + + +/* Sass provides functions that can be used to accomplish a variety of + tasks. Consider the following */ + +/* Functions can be invoked by using their name and passing in the + required arguments */ +body { + width: round(10.25px); +} + +.footer { + background-color: fade_out(#000000, 0.25) +} + +/* Compiles to: */ + +body { + width: 10px; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* You may also define your own functions. Functions are very similar to + mixins. When trying to choose between a function or a mixin, remember + that mixins are best for generating CSS while functions are better for + logic that might be used throughout your Sass code. The examples in + the Math Operators' section are ideal candidates for becoming a reusable + function. */ + +/* This function will take a target size and the parent size and calculate + and return the percentage */ + +@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); +} + +/* Compiles to: */ + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + + /*Extend (Inheritance) ==============================*/ @@ -150,6 +215,12 @@ div { border-color: #22df56; } +/* Extending a CSS statement is preferable to creating a mixin + because of the way it groups together the classes that all share + the same base styling. If this was done with a mixin, the width, + height, and border would be duplicated for each statement that + called the mixin. While it won't affect your workflow, it will + add unnecessary bloat to the files created by the Sass compiler. */ @@ -172,6 +243,7 @@ ul { /* '&' will be replaced by the parent selector. */ /* You can also nest pseudo-classes. */ /* Keep in mind that over-nesting will make your code less maintainable. +Best practices recommend going no more than 3 levels deep when nesting. For example: */ ul { @@ -212,6 +284,140 @@ ul li a { +/*Partials and Imports +==============================*/ + + + +/* Sass allows you to create partial files. This can help keep your Sass + code modularized. Partial files should begin with an '_', e.g. _reset.css. + Partials are not generated into CSS. */ + +/* Consider the following CSS which we'll put in a file called _reset.css */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Sass offers @import which can be used to import partials into a file. + This differs from the traditional CSS @import statement which makes + another HTTP request to fetch the imported file. Sass takes the + imported file and combines it with the compiled code. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Compiles to: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/*Placeholder Selectors +==============================*/ + + + +/* Placeholders are useful when creating a CSS statement to extend. If you + wanted to create a CSS statement that was exclusively used with @extend, + you can do so using a placeholder. Placeholders begin with a '%' instead + of '.' or '#'. Placeholders will not appear in the compiled CSS. */ + +%content-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + @extend %content-window; + background-color: #0000ff; +} + +/* Compiles to: */ + +.message-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + background-color: #0000ff; +} + + + +/*Math Operations +==============================*/ + + + +/* Sass provides the following operators: +, -, *, /, and %. These can + be useful for calculating values directly in your Sass files instead + of using values that you've already calculated by hand. Below is an example + of a setting up a simple two column design. */ + +$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%; +} + ``` @@ -226,6 +432,15 @@ Because people were constantly writing it as "SASS", the creator of the language If you want to play with Sass in your browser, check out [SassMeister](http://sassmeister.com/). You can use either syntax, just go into the settings and select either Sass or SCSS. + +## Compatibility + +Sass can be used in any project as long as you have a program to compile it +into CSS. You'll want to verify that the CSS you're using is compatible +with your target browsers. + +[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility. + ## Further reading * [Official Documentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) diff --git a/tmux.html.markdown b/tmux.html.markdown index c11da5fc..49d1bba6 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -249,3 +249,7 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | [Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) [Display CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) + +[tmuxinator - Manage complex tmux sessions](https://github.com/tmuxinator/tmuxinator) + + diff --git a/vi-vn/json-vi.html.markdown b/vi-vn/json-vi.html.markdown new file mode 100644 index 00000000..257216ff --- /dev/null +++ b/vi-vn/json-vi.html.markdown @@ -0,0 +1,76 @@ +--- +language: json +filename: learnjson-vi.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] +translators: + - ["Thanh Phan", "https://github.com/thanhpd"] +lang: vi-vn +--- + +Do JSON là một ngôn ngữ trao đổi dữ liệu hết sức đơn giản, đây có thể sẽ là bài +đơn giản nhất của Học X trong Y phút (Learn X in Y Minutes) từ trước tới nay. + +JSON ở dạng thuần túy nhất không có chú thích cho câu lệnh (comment) nào, nhưng +hầu hết các trình phân tích cú pháp (parser) đều chấp nhận chú thích theo phong +cách của ngôn ngữ C (`//`, `/* */`). Một số trình phân tích cú pháp còn chấp +nhận dấu phẩy cuối cùng (vd: một dấu phẩy sau phần tử cuối cùng của một mảng +hoặc sau thuộc tính cuối cùng của một object), nhưng những trường hợp này nên +tránh để có sự tương thích tốt hơn. + +Để phục vụ cho mục đích bài học này, tất cả cú pháp JSON ở đây sẽ đều là 100% hợp lệ. +May mắn thay, chúng cũng tự trình bày cho chính mình mà không cần thêm giải thích. + +Các kiểu dữ liệu được JSON hỗ trợ bao gồm: số (*numbers*), chuỗi kí tự +(*string*), toán tử đúng/sai (*boolean*), mảng (*array*), *object* và *null*. +Các trình duyệt hỗ trợ bao gồm: Mozilla Firefox phiên bản 3.5 trở lên, +Internet Explorer 8 trở lên, Google Chrome, Opera 10 trở lên, Safari 4 trở lên. +Kiểu tệp JSON có dạng ".json". Kiểu MIME (Multipurpose Internet Mail Extensions) +cho JSON là "application/json". Điểm yếu của JSON đó là thiếu các định dạng cho +kiểu dữ liệu cũng như quy chuẩn cú pháp chặt chẽ sử dụng DTD. + +```json +{ + "khóa": "dữ liệu", + + "các khóa": "phải luôn được đặt trong dấu ngoặc kép", + "số": 0, + "chuỗi kí tự": "Xin chàø. Tất cả kí tự unicode đều được chấp nhận, sử dụng với dạng \"kí tự\"." + "có đúng không?": true, + "không có gì": null, + + "số rất lớn": 1.2e+100, + + "objects": { + "chú thích": "Hầu hết các cấu trúc dữ liệu bạn sẽ dùng sẽ sử dụng object.", + + "mảng": [0, 1, 2, 3, "Mảng có thể chứa bất kì thứ gì bên trong.", 5], + + "một object khác": { + "chú thích": "Những thứ này có thể lồng vào nhau, rất tiện." + } + }, + + "ngớ ngẩn": [ + { + "nguồn cung cấp kali": ["chuối"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "phong cách khác": { + "chú thích": "kiểm tra cái này xem!" + , "vị trí dấu phẩy": "không quan trọng - chỉ cần nó ở trước khóa tiếp theo là được" + , "chú thích khác": "tiện phải không" + }, + + "nó rất ngắn": "Và bạn đã xong rồi đấy. Bạn đã biết tất cả những thứ mà JSON có thể cung cấp." +} +``` diff --git a/xml.html.markdown b/xml.html.markdown index 4d33e614..efc2340f 100644 --- a/xml.html.markdown +++ b/xml.html.markdown @@ -7,7 +7,7 @@ contributors: XML is a markup language designed to store and transport data. -Unlike HTML, XML does not specify how to display or to format data, just carry it. +Unlike HTML, XML does not specify how to display or to format data, it just carries it. * XML Syntax @@ -83,7 +83,7 @@ With this tool, you can check the XML data outside the application logic. <!DOCTYPE note SYSTEM "Bookstore.dtd"> <bookstore> <book category="COOKING"> - <title >Everyday Italian</title> + <title>Everyday Italian</title> <price>30.00</price> </book> </bookstore> @@ -121,7 +121,7 @@ With this tool, you can check the XML data outside the application logic. <bookstore> <book category="COOKING"> - <title >Everyday Italian</title> + <title>Everyday Italian</title> <price>30.00</price> </book> </bookstore> diff --git a/zfs.html.markdown b/zfs.html.markdown new file mode 100644 index 00000000..74487e35 --- /dev/null +++ b/zfs.html.markdown @@ -0,0 +1,400 @@ +--- +category: tool +tool: zfs +contributors: + - ["sarlalian", "http://github.com/sarlalian"] +filename: LearnZfs.txt +--- + + +[ZFS](http://open-zfs.org/wiki/Main_Page) +is a rethinking of the storage stack, combining traditional file systems as well as volume +managers into one cohesive tool. ZFS has some specific teminology that sets it appart from +more traditional storage systems, however it has a great set of features with a focus on +usability for systems administrators. + + +## ZFS Concepts + +### Virtual Devices + +A VDEV is similar to a raid device presented by a RAID card, there are several different +types of VDEV's that offer various advantages, including redundancy and speed. In general +VDEV's offer better reliability and safety than a RAID card. It is discouraged to use a +RAID setup with ZFS, as ZFS expects to directly manage the underlying disks. + +Types of VDEV's +* stripe (a single disk, no redundancy) +* mirror (n-way mirrors supported) +* raidz + * raidz1 (1-disk parity, similar to RAID 5) + * raidz2 (2-disk parity, similar to RAID 6) + * raidz3 (3-disk parity, no RAID analog) +* disk +* file (not recommended for production due to another filesystem adding unnecessary layering) + +Your data is striped across all the VDEV's present in your Storage Pool, so more VDEV's will +increase your IOPS. + +### Storage Pools + +ZFS uses Storage Pools as an abstraction over the lower level storage provider (VDEV), allow +you to separate the user visable file system from the physcal layout. + +### ZFS Dataset + +ZFS datasets are analagous to traditional filesystems but with many more features. They +provide many of ZFS's advantages. Datasets support [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write) +snapshots, quota's, compression and deduplication. + + +### Limits + +One directory may contain up to 2^48 files, up to 16 exabytes each. A single storage pool +can contain up to 256 zettabytes (2^78) of space, and can be striped across 2^64 devices. A +single host can have 2^64 storage pools. The limits are huge. + + +## Commands + +### Storage Pools + +Actions: +* List +* Status +* Destroy +* Get/Set properties + +List zpools + +```bash +# Create a raidz zpool +$ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 + +# List ZPools +$ zpool list +NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT +zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - + +# List detailed information about a specific zpool +$ zpool list -v zroot +NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT +zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 141G 106G 35.2G - 43% 75% +``` + +Status of zpools + +```bash +# Get status information about zpools +$ zpool status + pool: zroot + state: ONLINE + scan: scrub repaired 0 in 2h51m with 0 errors on Thu Oct 1 07:08:31 2015 +config: + + NAME STATE READ WRITE CKSUM + zroot ONLINE 0 0 0 + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0 + +errors: No known data errors + +# Scrubbing a zpool to correct any errors +$ zpool scrub zroot +$ zpool status -v zroot + pool: zroot + state: ONLINE + scan: scrub in progress since Thu Oct 15 16:59:14 2015 + 39.1M scanned out of 106G at 1.45M/s, 20h47m to go + 0 repaired, 0.04% done +config: + + NAME STATE READ WRITE CKSUM + zroot ONLINE 0 0 0 + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0 + +errors: No known data errors +``` + +Properties of zpools + +```bash + +# Getting properties from the pool properties can be user set or system provided. +$ zpool get all zroot +NAME PROPERTY VALUE SOURCE +zroot size 141G - +zroot capacity 75% - +zroot altroot - default +zroot health ONLINE - +... + +# Setting a zpool property +$ zpool set comment="Storage of mah stuff" zroot +$ zpool get comment +NAME PROPERTY VALUE SOURCE +tank comment - default +zroot comment Storage of mah stuff local +``` + +Remove zpool + +```bash +$ zpool destroy test +``` + + +### Datasets + +Actions: +* Create +* List +* Rename +* Delete +* Get/Set properties + +Create datasets + +```bash +# Create dataset +$ zfs create tank/root/data +$ mount | grep data +tank/root/data on /data (zfs, local, nfsv4acls) + +# Create child dataset +$ zfs create tank/root/data/stuff +$ mount | grep data +tank/root/data on /data (zfs, local, nfsv4acls) +tank/root/data/stuff on /data/stuff (zfs, local, nfsv4acls) + + +# Create Volume +$ zfs create -V zroot/win_vm +$ zfs list zroot/win_vm +NAME USED AVAIL REFER MOUNTPOINT +tank/win_vm 4.13G 17.9G 64K - +``` + +List datasets + +```bash +# List all datasets +$ zfs list +NAME USED AVAIL REFER MOUNTPOINT +zroot 106G 30.8G 144K none +zroot/ROOT 18.5G 30.8G 144K none +zroot/ROOT/10.1 8K 30.8G 9.63G / +zroot/ROOT/default 18.5G 30.8G 11.2G / +zroot/backup 5.23G 30.8G 144K none +zroot/home 288K 30.8G 144K none +... + +# List a specific dataset +$ zfs list zroot/home +NAME USED AVAIL REFER MOUNTPOINT +zroot/home 288K 30.8G 144K none + +# List snapshots +$ zfs list -t snapshot +zroot@daily-2015-10-15 0 - 144K - +zroot/ROOT@daily-2015-10-15 0 - 144K - +zroot/ROOT/default@daily-2015-10-15 0 - 24.2G - +zroot/tmp@daily-2015-10-15 124K - 708M - +zroot/usr@daily-2015-10-15 0 - 144K - +zroot/home@daily-2015-10-15 0 - 11.9G - +zroot/var@daily-2015-10-15 704K - 1.42G - +zroot/var/log@daily-2015-10-15 192K - 828K - +zroot/var/tmp@daily-2015-10-15 0 - 152K - +``` + +Rename datasets + +```bash +$ zfs rename tank/root/home tank/root/old_home +$ zfs rename tank/root/new_home tank/root/home +``` + +Delete dataset + +```bash +# Datasets cannot be deleted if they have any snapshots +zfs destroy tank/root/home +``` + +Get / set properties of a dataset + +```bash +# Get all properties +$ zfs get all zroot/usr/home │157 # Create Volume +NAME PROPERTY VALUE SOURCE │158 $ zfs create -V zroot/win_vm +zroot/home type filesystem - │159 $ zfs list zroot/win_vm +zroot/home creation Mon Oct 20 14:44 2014 - │160 NAME USED AVAIL REFER MOUNTPOINT +zroot/home used 11.9G - │161 tank/win_vm 4.13G 17.9G 64K - +zroot/home available 94.1G - │162 ``` +zroot/home referenced 11.9G - │163 +zroot/home mounted yes - +... + +# Get property from dataset +$ zfs get compression zroot/usr/home +NAME PROPERTY VALUE SOURCE +zroot/home compression off default + +# Set property on dataset +$ zfs set compression=gzip-9 mypool/lamb + +# Get a set of properties from all datasets +$ zfs list -o name,quota,reservation +NAME QUOTA RESERV +zroot none none +zroot/ROOT none none +zroot/ROOT/default none none +zroot/tmp none none +zroot/usr none none +zroot/home none none +zroot/var none none +... +``` + + +### Snapshots + +ZFS snapshots are one of the things about zfs that are a really big deal + +* The space they take up is equal to the difference in data between the filesystem and its snapshot +* Creation time is only seconds +* Recovery is as fast as you can write data. +* They are easy to automate. + +Actions: +* Create +* Delete +* Rename +* Access snapshots +* Send / Receive +* Clone + + +Create snapshots + +```bash +# Create a snapshot of a single dataset +zfs snapshot tank/home/sarlalian@now + +# Create a snapshot of a dataset and its children +$ zfs snapshot -r tank/home@now +$ zfs list -t snapshot +NAME USED AVAIL REFER MOUNTPOINT +tank/home@now 0 - 26K - +tank/home/sarlalian@now 0 - 259M - +tank/home/alice@now 0 - 156M - +tank/home/bob@now 0 - 156M - +... + +Destroy snapshots + +```bash +# How to destroy a snapshot +$ zfs destroy tank/home/sarlalian@now + +# Delete a snapshot on a parent dataset and its children +$ zfs destroy -r tank/home/sarlalian@now + +``` + +Renaming Snapshots + +```bash +# Rename a snapshot +$ zfs rename tank/home/sarlalian@now tank/home/sarlalian@today +$ zfs rename tank/home/sarlalian@now today + +# zfs rename -r tank/home@now @yesterday +``` + +Accessing snapshots + +```bash +# CD Into a snapshot directory +$ cd /home/.zfs/snapshot/ +``` + +Sending and Receiving + +```bash +# Backup a snapshot to a file +$ zfs send tank/home/sarlalian@now | gzip > backup_file.gz + +# Send a snapshot to another dataset +$ zfs send tank/home/sarlalian@now | zfs recv backups/home/sarlalian + +# Send a snapshot to a remote host +$ zfs send tank/home/sarlalian@now | ssh root@backup_server 'zfs recv tank/home/sarlalian' + +# Send full dataset with snapshos to new host +$ zfs send -v -R tank/home@now | ssh root@backup_server 'zfs recv tank/home' +``` + +Cloneing Snapshots + +```bash +# Clone a snapshot +$ zfs clone tank/home/sarlalian@now tank/home/sarlalian_new + +# Promoting the clone so it is no longer dependent on the snapshot +$ zfs promote tank/home/sarlalian_new +``` + +### Putting it all together + +This following a script utilizing FreeBSD, jails and ZFS to automate +provisioning a clean copy of a mysql staging database from a live replication +slave. + +```bash +#!/bin/sh + +echo "==== Stopping the staging database server ====" +jail -r staging + +echo "==== Cleaning up existing staging server and snapshot ====" +zfs destroy -r zroot/jails/staging +zfs destroy zroot/jails/slave@staging + +echo "==== Quiescing the slave database ====" +echo "FLUSH TABLES WITH READ LOCK;" | /usr/local/bin/mysql -u root -pmyrootpassword -h slave + +echo "==== Snapshotting the slave db filesystem as zroot/jails/slave@staging ====" +zfs snapshot zroot/jails/slave@staging + +echo "==== Starting the slave database server ====" +jail -c slave + +echo "==== Cloning the slave snapshot to the staging server ====" +zfs clone zroot/jails/slave@staging zroot/jails/staging + +echo "==== Installing the staging mysql config ====" +mv /jails/staging/usr/local/etc/my.cnf /jails/staging/usr/local/etc/my.cnf.slave +cp /jails/staging/usr/local/etc/my.cnf.staging /jails/staging/usr/local/etc/my.cnf + +echo "==== Setting up the staging rc.conf file ====" +mv /jails/staging/etc/rc.conf.local /jails/staging/etc/rc.conf.slave +mv /jails/staging/etc/rc.conf.staging /jails/staging/etc/rc.conf.local + +echo "==== Starting the staging db server ====" +jail -c staging + +echo "==== Make sthe staging database not pull from the master ====" +echo "STOP SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging +echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging +``` + + +### Additional Reading + +* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) +* [FreeBSD Handbook on ZFS](https://wiki.freebsd.org/ZF://wiki.freebsd.org/ZFS) +* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) +* [Oracle's Tuning Guide](http://www.oracle.com/technetwork/articles/servers-storage-admin/sto-recommended-zfs-settings-1951715.html) +* [OpenZFS Tuning Guide](http://open-zfs.org/wiki/Performance_tuning) +* [FreeBSD ZFS Tuning Guide](https://wiki.freebsd.org/ZFSTuningGuide) |