diff options
31 files changed, 2580 insertions, 425 deletions
diff --git a/bash.html.markdown b/bash.html.markdown index 856db706..59aeaaf4 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -88,6 +88,11 @@ echo ${Variable: -5} # => tring  # String length  echo ${#Variable} # => 11 +# Indirect expansion +OtherVariable="Variable" +echo ${!OtherVariable} # => Some String +# This will expand the value of OtherVariable +  # Default value for variable  echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"}  # => DefaultValueIfFooIsMissingOrEmpty @@ -225,7 +230,9 @@ cat file.txt  # We can also read the file using `cat`:  Contents=$(cat file.txt) -echo "START OF FILE\n$Contents\nEND OF FILE" # "\n" prints a new line character +# "\n" prints a new line character +# "-e" to interpret the newline escape characters as escape characters  +echo -e "START OF FILE\n$Contents\nEND OF FILE"  # => START OF FILE  # => [contents of file.txt]  # => END OF FILE diff --git a/c++.html.markdown b/c++.html.markdown index f3dc8e20..59aad210 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -202,7 +202,7 @@ int main()     cout << "Your favorite number is " << myInt << "\n";     // prints "Your favorite number is <myInt>" -    cerr << "Used for error messages"; +   cerr << "Used for error messages";  }  ////////// diff --git a/dart.html.markdown b/dart.html.markdown index 2672dc6a..ee695d33 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -6,7 +6,7 @@ contributors:    - ["Vince Ramces Oliveros", "https://github.com/ram231"]  --- -**Dart** is a single threaded, general puprose programming languages. +**Dart** is a single threaded, general purpose programming language.  It borrows a lot from other mainstream languages.  It supports Streams, Futures(known as Promises in JavaScript), Generics, First-class functions(closures) and static type checking.  Dart can run in any platform such as Web, CLI, Desktop, Mobile and IoT devices. diff --git a/de-de/clojure-macros-de.html.markdown b/de-de/clojure-macros-de.html.markdown new file mode 100644 index 00000000..088a29a8 --- /dev/null +++ b/de-de/clojure-macros-de.html.markdown @@ -0,0 +1,161 @@ +--- +language: "clojure macros" +filename: learnclojuremacros-de.clj +contributors: +    - ["Adam Bard", "http://adambard.com/"] +translators: +    - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- + +Wie mit allen Lisps besitzt auch Clojure die inhärente [Homoikonizität](https://en.wikipedia.org/wiki/Homoiconic), +die dir den vollen Zugang der Sprache gibt, um + Code-Generierungsroutinen zu schreiben. Diese werden "Macros" genannt. +Macros geben dir eine leistungsarke Möglichkeit, die Sprache +an deine Bedürfnisse anzupassen. + +Sei aber vorsichtig, es wird als schlechter Stil angesehen, wenn du +ein Macro schreibst, obwohl eine Funktion genausogut funktionieren würde. +Verwende nur dann ein Macro, wenn du Kontrolle darüber brauchst, wann oder ob Argumente in einer Form evaluiert werden. + +Wenn du mit Clojure vertraut sein möchtest, stelle sicher, dass du alles in [Clojure in Y Minutes](/docs/clojure/) verstehst. + +```clojure +;; Definiere ein Macro mit defmacro. Dein Macro sollte eine Liste zurückgeben, +;; die als Clojure Code evaluiert werden kann. +;; +;; Dieses Macro ist das Gleiche, als ob du (reverse "Hallo Welt") geschrieben +;; hättest +(defmacro my-first-macro [] +  (list reverse "Hallo Welt")) + +;; Inspiziere das Ergebnis eines Macros mit macroexpand oder macroexpand-1. +;; +;; Beachte, dass der Aufruf zitiert sein muss. +(macroexpand '(my-first-macro)) +;; -> (#<core$reverse clojure.core$reverse@xxxxxxxx> "Hallo Welt") + +;; Du kannst das Ergebnis von macroexpand direkt auswerten. +(eval (macroexpand '(my-first-macro))) +; -> (\t \l \e \W \space \o \l \l \a \H) + +;; Aber du solltest diese prägnante und funktionsähnliche Syntax verwenden: +(my-first-macro)  ; -> (\t \l \e \W \space \o \l \l \a \H) + +;; Du kannst es dir leichter machen, indem du die Zitiersyntax verwendest +;; um Listen in ihren Makros zu erstellen: +(defmacro my-first-quoted-macro [] +  '(reverse "Hallo Welt")) + +(macroexpand '(my-first-quoted-macro)) +;; -> (reverse "Hallo Welt") +;; Beachte, dass reverse nicht mehr ein Funktionsobjekt ist, sondern ein Symbol + +;; Macros können Argumente haben. +(defmacro inc2 [arg] +  (list + 2 arg)) + +(inc2 2) ; -> 4 + +;; Aber wenn du versuchst das mit einer zitierten Liste zu machen wirst du +;; einen Fehler bekommen, weil das Argument auch zitiert sein wird. +;; Um dies zu umgehen, bietet Clojure einee Art und Weise Macros zu zitieren: ` +;; In ` kannst du ~ verwenden um in den äußeren Bereich zu kommen. +(defmacro inc2-quoted [arg] +  `(+ 2 ~arg)) + +(inc2-quoted 2) + +;; Du kannst die normalen destruktuierungs Argumente verwenden. Expandiere +;; Listenvariablen mit ~@. +(defmacro unless [arg & body] +  `(if (not ~arg) +     (do ~@body))) ; Erinnere dich an das do! + +(macroexpand '(unless true (reverse "Hallo Welt"))) +;; -> +;; (if (clojure.core/not true) (do (reverse "Hallo Welt"))) + +;; (unless) evaluiert und gibt body zurück, wenn das erste Argument falsch ist. +;; Andernfalls gibt es nil zurück + +(unless true "Hallo") ; -> nil +(unless false "Hallo") ; -> "Hallo" + +;; Die Verwendung Macros ohne Sorgfalt kann viel Böses auslösen, indem es +;; deine Variablen überschreibt +(defmacro define-x [] +  '(do +     (def x 2) +     (list x))) + +(def x 4) +(define-x) ; -> (2) +(list x) ; -> (2) + +;; Um das zu verhindern kannst du gensym verwenden um einen eindeutigen +;; Identifikator zu bekommen +(gensym 'x) ; -> x1281 (oder etwas Ähnliches) + +(defmacro define-x-safely [] +  (let [sym (gensym 'x)] +    `(do +       (def ~sym 2) +       (list ~sym)))) + +(def x 4) +(define-x-safely) ; -> (2) +(list x) ; -> (4) + +;; Du kannst # innerhalb von ` verwenden um für jedes Symbol automatisch +;; ein gensym zu erstellen +(defmacro define-x-hygienically [] +  `(do +     (def x# 2) +     (list x#))) + +(def x 4) +(define-x-hygienically) ; -> (2) +(list x) ; -> (4) + +;; Es ist üblich, Hilfsfunktionen mit Macros zu verwenden. Lass uns einige +;; erstellen, die uns helfen , eine (dumme) arithmetische Syntax +;; zu unterstützen +(declare inline-2-helper) +(defn clean-arg [arg] +  (if (seq? arg) +    (inline-2-helper arg) +    arg)) + +(defn apply-arg +  "Bekomme die Argumente [x (+ y)], gebe (+ x y) zurück" +  [val [op arg]] +  (list op val (clean-arg arg))) + +(defn inline-2-helper +  [[arg1 & ops-and-args]] +  (let [ops (partition 2 ops-and-args)] +    (reduce apply-arg (clean-arg arg1) ops))) + +;; Wir können es sofort testen, ohne ein Macro zu erstellen +(inline-2-helper '(a + (b - 2) - (c * 5))) ; -> (- (+ a (- b 2)) (* c 5)) + +; Allerdings, brauchen wir ein Macro, wenn wir es zur Kompilierungszeit +; ausführen wollen +(defmacro inline-2 [form] +  (inline-2-helper form)) + +(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1))) +; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1) + +(inline-2 (1 + (3 / 2) - (1 / 2) + 1)) +; -> 3 (eigentlich, 3N, da die Zahl zu einem rationalen Bruch mit / umgewandelt wird) +``` + +### Weiterführende Literatur + +[Macros schreiben](http://www.braveclojure.com/writing-macros/) + +[Offiziele Docs](http://clojure.org/macros) + +[Wann verwendet man Macros?](https://lispcast.com/when-to-use-a-macro/) diff --git a/de-de/elm-de.html.markdown b/de-de/elm-de.html.markdown new file mode 100644 index 00000000..08832327 --- /dev/null +++ b/de-de/elm-de.html.markdown @@ -0,0 +1,376 @@ +--- +language: Elm +filename: learnelm.elm +contributors: +  - ["Max Goldstein", "http://maxgoldste.in/"] +translators: +  - ["waynee95", "https://waynee95.me"] +lang: de-de +--- + +Elm ist eine pure funktionale Programmiersprache. Mit Elm werden GUIs +(grafische Benutzeroberfläche) für Webanwendungen erstellt. Durch die statische +Typisierung kann Elm viele Fehler schon bei der Kompilierung abfangen. Ein +Hauptmerkmal von Elm sind die ausführlichen und gut erklärten Fehlermeldungen. + +```haskell +-- Einzeilige Kommentare beginnen mit 2 Bindestrichen. +{- So wird ein mehrzeiliger Kommentar angelegt. +{- Diese können auch verschachtelt werden. -} +-} + +{-- Die Grundlagen --} + +-- Arithmetik +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 + +-- Zahlen ohne Punkt sind entweder vom Typ Int oder Float. +33 / 2 -- 16.5 mit Division von Gleitkommazahlen +33 // 2 -- 16  mit ganzzahliger Division + +-- Exponenten +5 ^ 2 -- 25 + +-- Boolsche Werte +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- Strings (Zeichenketten) und Zeichen +"Das hier ist ein String." +'a' -- Zeichen + +-- Strings können konkateniert werden. +"Hello " ++ "world!" -- "Hello world!" + +{-- Listen und Tupel --} + +-- Jedes Element einer Liste muss vom gleichen Typ sein. Listen sind homogen. +["the", "quick", "brown", "fox"] +[1, 2, 3, 4, 5] +-- Das zweite Beispiel kann man auch mit Hilfe der "range" Funktion schreiben. +List.range 1 5 + +-- Listen werden genauso wie Strings konkateniert. +List.range 1 5 ++ List.range 6 10 == List.range 1 10 -- True + +-- Mit dem "cons" Operator lässt sich ein Element an den Anfang einer Liste anfügen. +0 :: List.range 1 5 -- [0, 1, 2, 3, 4, 5] + +-- Die Funktionen "head" und "tail" haben als Rückgabewert den "Maybe" Typ. +-- Dadurch wird die Fehlerbehandlung von fehlenden Elementen explizit, weil +-- man immer mit jedem möglichen Fall umgehen muss. +List.head (List.range 1 5) -- Just 1 +List.tail (List.range 1 5) -- Just [2, 3, 4, 5] +List.head [] -- Nothing +-- List.funktionsName bedeutet, dass diese Funktion aus dem "List"-Modul stammt. + +-- Tupel sind heterogen, jedes Element kann von einem anderen Typ sein. +-- Jedoch haben Tupel eine feste Länge. +("elm", 42) + +-- Das Zugreifen auf Elemente eines Tupels geschieht mittels den Funktionen +-- "first" und "second". +Tuple.first ("elm", 42) -- "elm" +Tuple.second ("elm", 42) -- 42 + +-- Das leere Tupel, genannt "Unit",  wird manchmal als Platzhalter verwendet. +-- Es ist das einzige Element vom Typ "Unit". +() + +{-- Kontrollfluss --} + +-- Eine If-Bedingung hat immer einen Else-Zweig und beide Zweige müssen den +-- gleichen Typ haben. +if powerLevel > 9000 then +  "WHOA!" +else +  "meh" + +-- If-Bedingungen können verkettet werden. +if n < 0 then +  "n is negative" +else if n > 0 then +  "n is positive" +else +  "n is zero" + +-- Mit dem Mustervergleich (pattern matching) kann man bestimmte Fälle direkt +-- behandeln. +case aList of +  [] -> "matches the empty list" +  [x]-> "matches a list of exactly one item, " ++ toString x +  x::xs -> "matches a list of at least one item whose head is " ++ toString x +-- Mustervergleich geht immer von oben nach unten. Würde man [x] als letztes +-- platzieren, dann würde dieser Fall niemals getroffen werden, weil x:xs diesen +-- Fall schon mit einschließt (xs ist in dem Fall die leere Liste). + +-- Mustervergleich an einem Maybe Typ. +case List.head aList of +  Just x -> "The head is " ++ toString x +  Nothing -> "The list was empty." + +{-- Funktionen --} + +-- Die Syntax für Funktionen in Elm ist minimal. Hier werden Leerzeichen anstelle +-- von runden oder geschweiften Klammern verwendet. Außerdem gibt es kein "return" +-- Keyword. + +-- Eine Funktion wird durch ihren Namen, einer Liste von Parametern gefolgt von +-- einem Gleichheitszeichen und dem Funktionskörper angegeben. +multiply a b = +  a * b + +-- Beim Aufruf der Funktion (auch Applikation genannt) werden die Argumente ohne +-- Komma übergeben. +multiply 7 6 -- 42 + +-- Partielle Applikation einer Funktion (Aufrufen einer Funktion mit fehlenden +-- Argumenten). Hierbei entsteht eine neue Funktion, der wir einen Namen geben. +double = +  multiply 2 + +-- Konstanten sind Funktionen ohne Parameter. +answer = +  42 + +-- Funktionen, die Funktionen als Parameter haben, nennt man Funktionen höherer +-- Ordnung. In funktionalen Programmiersprachen werden Funktionen als "first-class" +-- behandelt. Man kann sie als Argument übergeben, als Rückgabewert einer Funktion +-- zurückgeben oder einer Variable zuweisen. +List.map double (List.range 1 4) -- [2, 4, 6, 8] + +-- Funktionen können auch als anonyme Funktion (Lambda-Funktionen) übergeben werden. +-- Diese werden mit einem Blackslash eingeleitet, gefolgt von allen Argumenten. +-- Die Funktion "\a -> a * 2" beschreibt die Funktion f(x) = x * 2. +List.map (\a -> a * 2) (List.range 1 4) -- [2, 4, 6, 8] + +-- Mustervergleich kann auch in der Funktionsdefinition verwendet werden. +-- In diesem Fall hat die Funktion ein Tupel als Parameter. (Beachte: Hier +-- werden die Werte des Tupels direkt ausgepackt. Dadurch kann man auf die +-- Verwendung von "first" und "second" verzichten.) +area (width, height) = +  width * height + +area (6, 7) -- 42 + +-- Mustervergleich auf Records macht man mit geschweiften Klammern. +-- Bezeichner (lokale Variablen) werden mittels dem "let" Keyword angelegt. +-- (Mehr zu Records weiter unten!) +volume {width, height, depth} = +  let +    area = width * height +  in +    area * depth + +volume { width = 3, height = 2, depth = 7 } -- 42 + +-- Rekursive Funktion +fib n = +  if n < 2 then +    1 +  else +    fib (n - 1) + fib (n - 2) + +List.map fib (List.range 0 8) -- [1, 1, 2, 3, 5, 8, 13, 21, 34] + +-- Noch eine rekursive Funktion (Nur ein Beispiel, verwende stattdessen immer +-- List.length!) +listLength aList = +  case aList of +    [] -> 0 +    x::xs -> 1 + listLength xs + +-- Funktionsapplikation hat die höchste Präzedenz, sie binden stärker als Operatoren. +-- Klammern bietet die Möglichkeit der Bevorrangung. +cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1 +-- Als erstes wird die Funktion "degrees" mit dem Wert 30 aufgerufen. +-- Danach wird das Ergenis davon den Funktionen "cos", bzw. "sin" übergeben. +-- Dann wird das Ergebnis davon mit 2 quadriert und als letztes werden diese +-- beiden Werte dann addiert. + +{-- Typen und Typ Annotationen --} + +-- Durch Typinferenz kann der Compiler jeden Typ genau bestimmen. Man kann diese +-- aber auch manuell selber angeben (guter Stil!). +-- Typen beginnen immer mit eine Großbuchstaben. Dabei liest man "x : Typ" als +-- "x" ist vom Typ "Typ". +-- Hier ein paar übliche Typen: +5 : Int +6.7 : Float +"hello" : String +True : Bool + +-- Funktionen haben ebenfalls einen Typ. Dabei ist der ganz rechte Typ der +-- Rückgabetyp der Funktion und alle anderen sind die Typen der Parameter. +not : Bool -> Bool +round : Float -> Int + +-- Es ist guter Stil immer den Typ anzugeben, da diese eine Form von Dokumentation +-- sind. Außerdem kann so der Compiler genauere Fehlermeldungen geben. +double : Int -> Int +double x = x * 2 + +-- Funktionen als Parameter werden durch Klammern angegeben. Die folgende Funktion +-- ist nicht auf einen Typ festgelegt, sondern enthält Typvariablen (beginnend +-- mit Kleinbuchstaben). Die konkreten Typen werden erst bei Anwendung der +-- Funktion festgelegt. "List a" bedeutet, dass es sich um eine Liste mit +-- Elementen vom Typ "a" handelt. +List.map : (a -> b) -> List a -> List b + +-- Es gibt drei spezielle kleingeschriebene Typen: "number", "comparable" und +-- "appendable". +add : number -> number -> number +add x y = x + y -- funktioniert mit Ints und Floats. + +max :: comparable -> comparable -> comparable +max a b = if a > b then a else b -- funktioniert mit Typen, die vergleichbar sind. + +append :: appendable -> appendable -> appendable +append xs ys = xs ++ ys -- funktioniert mit Typen, die konkatenierbar sind. + +append "hello" "world"  -- "helloworld" +append [1,1,2] [3,5,8] -- [1,1,2,3,5,8] + +{-- Eigene Datentypen erstellen --} + +-- Ein "Record" ist ähnlich wie ein Tupel, nur das jedes Feld einen Namne hat. +-- Dabei spielt die Reihenfolge keine Rolle. +{ x = 3, y = 7 } + +-- Um auf Werte eines Records zuzugreifen, benutzt man einen Punkt gefolgt +-- von dem Namen des Feldes. +{ x = 3, y = 7 }.x -- 3 + +-- Oder mit einer Zugriffsfunktion, welche aus einem Punkt und dem Feldnamen besteht. +.y { x = 3, y = 7 } -- 7 + +-- Wert eines Feldes ändern. (Achtung: Das Feld muss aber vorher schon vorhanden sein!) +{ person | +  name = "George" } + +-- Mehrere Felder aufeinmal ändern unter Verwendung des alten Wertes. +{ particle | +  position = particle.position + particle.velocity, +  velocity = particle.velocity + particle.acceleration } + +-- Du kannst ein Record auch als Typ Annotation verwenden. +-- (Beachte: Ein Record Typ benutzt einen Doppelpunkt und ein Record Wert benutzt +-- ein Gleichheitszeichen!) +origin : { x : Float, y : Float, z : Float } +origin = +  { x = 0, y = 0, z = 0 } + +-- Durch das "type" Keyword kann man einem existierenden Typen einen Namen geben. +type alias Point3D = +  { x : Float, y : Float, z : Float } + +-- Der Name kann dann als Konstruktor verwendet werden. +otherOrigin : Point3D +otherOrigin = +  Point3D 0 0 0 + +-- Aber es ist immernoch der selbe Typ, da es nur ein Alias ist! +origin == otherOrigin -- True + +-- Neben den Records gibt es auch noch so genannte Summentypen. +-- Ein Summentyp hat mehrere Konstruktoren. +type Direction = +  North | South | East | West + +-- Ein Konstruktor kann außerdem noch andere Typen enthalten. Rekursion ist +-- auch möglich. +type IntTree = +  Leaf | Node Int IntTree IntTree + +-- Diese können auch als Typ Annotation verwendet werden. +root : IntTree +root = +  Node 7 Leaf Leaf + +-- Außerdem können auch Typvariablen verwendet werden in einem Konstruktor. +type Tree a = +  Leaf | Node a (Tree a) (Tree a) + +-- Beim Mustervergleich kann man auf die verschiedenen Konstruktoren matchen. +leftmostElement : Tree a -> Maybe a +leftmostElement tree = +  case tree of +    Leaf -> Nothing +    Node x Leaf _ -> Just x +    Node _ subtree _ -> leftmostElement subtree + +{-- Module und Imports --} + +-- Die Kernbibliotheken und andere Bibliotheken sind in Module aufgeteilt. +-- Für große Projekte können auch eigene Module erstellt werden. + +-- Eine Modul beginnt mit ganz oben. Ohne diese Angabe befindet man sich +-- automatisch im Modul "Main". +module Name where + +-- Ohne genaue Angabe von Exports wird alles exportiert. Es können aber alle +-- Exporte explizit angegeben werden. +module Name (MyType, myValue) where + +-- Importiert das Modul "Dict". Jetzt kann man Funktionen mittels "Dict.insert" +-- aufrufen. +import Dict + +-- Importiert das "Dict" Modul und den "Dict" Typ. Dadurch muss man nicht "Dict.Dict" +-- verwenden. Man kann trotzdem noch Funktionen des Moduls aufrufen, wie "Dict.insert". +import Dict exposing (Dict) + +-- Abkürzung für den Modulnamen. Aufrufen der Funktionen mittels "C.funktionsName". +import Graphics.Collage as C + +{-- Kommandozeilen Programme --} + +-- Eine Elm-Datei kompilieren. +$ elm make MyFile.elm + +-- Beim ersten Aufruf wird Elm die "core" Bibliotheken installieren und eine +-- "elm-package.json"-Datei anlegen, die alle Informationen des Projektes +-- speichert. + +-- Der Reactor ist ein Server, welche alle Dateinen kompiliert und ausführt. +$ elm reactor + +-- Starte das REPL (read-eval-print-loop). +$ elm repl + +-- Bibliotheken werden durch den Github-Nutzernamen und ein Repository identifiziert. +-- Installieren einer neuen Bibliothek. +$ elm package install elm-lang/html +-- Diese wird der elm-package.json Datei hinzugefügt. + +-- Zeigt alle Veränderungen zwischen zwei bestimmten Versionen an. +$ elm package diff elm-lang/html 1.1.0 2.0.0 +-- Der Paketmanager von Elm erzwingt "semantic versioning"! +``` + +Elm ist eine besonders kleine Programmiersprache. Jetzt hast du genug Wissen an +deiner Seite, um dich in fast jedem Elm Code zurecht zu finden. + +Noch ein paar weitere hilfreiche Ressourcen (in Englisch): + +- Die [Elm Homepage](http://elm-lang.org/). Dort findest du: + +  - [Anleitung zur Installierung von Elm](http://elm-lang.org/install) +  - [Dokumentation](http://elm-lang.org/docs), sowie eine [Referenz zur Syntax](http://elm-lang.org/docs/syntax) +  - Viele hilfreiche [Beispiele](http://elm-lang.org/examples) + +- Dokumentation der [Elm Kernbibliotheken](http://package.elm-lang.org/packages/elm-lang/core/latest/). Insbesondere: + +  - [Basics](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics) (standardmäßig importiert) +  - [Maybe](http://package.elm-lang.org/packages/elm-lang/core/latest/Maybe) sowie [Result](http://package.elm-lang.org/packages/elm-lang/core/latest/Result) (benutzt für Fehlerbehandlung) +  - Datenstrukturen, wie [List](http://package.elm-lang.org/packages/elm-lang/core/latest/List), [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict), und [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set) +  - JSON [encoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Encode) und [decoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode) + +- [Die Elm Architektur](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). + +- Die [Elm mailing list](https://groups.google.com/forum/#!forum/elm-discuss). diff --git a/de-de/pug-de.html.markdown b/de-de/pug-de.html.markdown new file mode 100644 index 00000000..c86494ce --- /dev/null +++ b/de-de/pug-de.html.markdown @@ -0,0 +1,208 @@ +--- +language: Pug +contributors: +  - ["Michael Warner", "https://github.com/MichaelJGW"] +filename: lernepug-de.pug +translators: +    - ["denniskeller", "https://github.com/denniskeller"] +lang: de-de +--- + +## Erste Schritte mit Pug + +Pug ist eine kleine Sprache, die zu HTML kompiliert. Sie hat eine +saubere Syntax mit zusätzlichen Funktionen wie if Anweisungen und Schleifen. +Sie kann auch als serverseitige Templatingsprache für Serversprachen +wie NodeJS verwendet werden. + +### Die Sprache +```pug + +//- Einzeilenkommentar + +//- Mehrzeiliger +    Kommentar + +//- ---TAGS--- +//- Grundlagen +div +//- <div></div> +h1 +//- <h1></h1> +mein-benutzerdefiniertesTag +//- <mein-benutzerdefiniertesTag></mein-benutzerdefiniertesTag> + +//- Geschwister +div +div +//- <div></div> +    <div></div> + +//- Kind +div +  div +//- <div> +      <div></div> +    </div> + +//- Text +h1 Hallo Welt +//- <h1>Hallo Welt</h1> + +//- Multizeilentext +div. +  Hallo +  Welt +//- <div> +      Hallo +      Welt +    </div> + +//- ---ATTRIBUTE--- +div(class="meine-klasse" id="meine-id" mein-benutzerdefiniertes-attr="data" enabled) +//- <div class="meine-klasse" id="meine-id" mein-benutzerdefiniertes-attr="data" enabled></div> + +//- Kurzhand +span.meine-klasse +//- <span class="meine-klasse"></span> +.meine-klasse +//- <div class="meine-klasse"></div> +div#meine-id +//- <div id="meine-id"></div> +div#meine-id.meine-klasse +//- <div class="meine-klasse" id="meine-id"></div> + + +//- ---JS--- +- const sprache = "pug"; + +//- Multizeilen JS +- +  const srache = "pug"; +  const cool = true; + +//- JS Klassen +- const meineKlasse = ['class1', 'class2', 'class3'] +div(class=meineKlasse) +//- <div class="class1 class2 class3"></div> + +//- JS Stil +- const meineStile = {'color':'white', 'background-color':'blue'} +div(styles=meineStile) +//- <div styles="{"color":"white","background-color":"blue"}"></div> + +//- JS Attributte +- const meineAttribute = {"src": "foto.png", "alt": "meine Bilder"} +img&attributes(meineAttribute) +//- <img src="foto.png" alt="meine Bilder"> +- let deaktiviert = false +input(type="text" disabled=deaktiviert) +//- <input type="text"> +- deaktiviert = true +input(type="text" disabled=deaktiviert) +//- <input type="text" disabled> + +//- JS Templating +- const name = "Bob"; +h1 Hi #{name} +h1= name +//- <h1>Hi Bob</h1> +//- <h1>Bob</h1> + +//- ---Schleifen--- + +//- 'each' und 'for' machen das Selbe. Wir werden nur 'each' verwenden. + +each value, i in [1,2,3] +  p=value +//- +  <p>1</p> +  <p>2</p> +  <p>3</p> + +each value, index in [1,2,3] +  p=value + '-' + index +//- +  <p>1-0</p> +  <p>2-1</p> +  <p>3-2</p> + +each value in [] +  p=value +//- + +each value in [] +  p=value +else +  p Keine Werte sind hier + +//- <p>Keine Werte sind hier</p> + +//- ---BEDINGUNGEN--- + +- const zahl = 5 +if zahl < 5 +  p zahl ist kleiner als 5 +else if zahl > 5 +  p zahl ist größer als  5 +else +  p zahl ist 5 +//- <p>zahl ist 5</p> + +- const bestellungsStatus = "Ausstehend"; +case bestellungsStatus +  when "Ausstehend" +    p.warn Deine Bestellung steht noch aus +  when "Abgeschlossen" +    p.success Bestellung ist abgeschlossen. +  when -1 +    p.error Ein Fehler ist aufgetreten +  default +    p kein Bestellprotokoll gefunden +//- <p class="warn">Deine Bestellung steht noch aus</p> + +//- --INCLUDE-- +//- File path -> "includes/nav.png" +h1 Firmenname +nav +  a(href="index.html") Home +  a(href="about.html") Über uns + +//- Dateipfad -> "index.png" +html +  body +    include includes/nav.pug +//- +  <html> +    <body> +      <h1>Firmenname</h1> +      <nav><a href="index.html">Home</a><a href="about.html">Über uns</a></nav> +    </body> +  </html> + +//- Importiere JS und CSS +script +  include scripts/index.js +style +  include styles/theme.css + +//- ---MIXIN--- +mixin basic() +  div Hallo ++basic("Bob") +//- <div>Hallo</div> + +mixin comment(name, kommentar) +  div +    span.comment-name= name +    div.comment-text= kommentar ++comment("Bob", "Das ist super") +//- <div>Hallo</div> + +``` + + +### Zusätzliche Ressourcen +- [The Site](https://pugjs.org/) +- [The Docs](https://pugjs.org/api/getting-started.html) +- [Github Repo](https://github.com/pugjs/pug) diff --git a/de-de/ruby-de.html.markdown b/de-de/ruby-de.html.markdown index e14603cd..8025a8c0 100644 --- a/de-de/ruby-de.html.markdown +++ b/de-de/ruby-de.html.markdown @@ -1,5 +1,6 @@  ---  language: ruby +filename: ruby-de.rb  contributors:    - ["David Underwood", "http://theflyingdeveloper.com"]    - ["Joel Walden", "http://joelwalden.net"] @@ -11,602 +12,677 @@ 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"] +  - ["Persa Zula", "http://persazula.com"] +  - ["Jake Faris", "https://github.com/farisj"] +  - ["Corey Ward", "https://github.com/coreyward"] +  - ["Jannik Siebert", "https://github.com/janniks"] +  - ["Keith Miyake", "https://github.com/kaymmm"]  translators:    - ["Christian Albrecht", "https://github.com/coastalchief"]    - ["Dennis Keller", "https://github.com/denniskeller"] -filename: ruby-de.rb +  - ["Paul Götze", "https://gitub.com/paulgoetze"]  lang: de-de  --- -# Dies ist ein Kommentar +```ruby +# Das ist ein Kommentar  =begin -Dies sind multi-line -Kommentare. Niemand benutzt -die wirklich. +Das ist ein mehrzeiliger Kommentar. +Die Anfangszeile muss mit "=begin" beginnen +und die Endzeile muss mit "=end" beginnen.  + +Alternativ kannst du jede Zeile in einem  +mehrzeiligen Kommentar mit dem # Zeichen beginnen.   =end -# Objekte - Alles ist ein Objekt +# In Ruby ist (fast) alles ein Objekt. +# Das schließt Zahlen ein... +3.class #=> Integer -## Zahlen sind Objekte -``` -3.class #=> Fixnum -3.to_s #=> "3" -``` +# ...und Zeichenketten (Strings)... +"Hallo".class #=> String -### Simple Arithmetik -``` +# ...und sogar Methoden! +"Hallo".method(:class).class #=> Method + +# Simple Arithmetik  1 + 1 #=> 2  8 - 1 #=> 7  10 * 2 #=> 20  35 / 5 #=> 7 -2**5 #=> 32 -``` +2 ** 5 #=> 32 +5 % 3 #=> 2 -// Arithmetik ist aber eigentlich nur syntaktischer Zucker -// um eine Methode eines Objekt aufzurufen -``` +# Bitweise Operatoren +3 & 5 #=> 1 +3 | 5 #=> 7 +3 ^ 5 #=> 6 + +# Arithmetik ist aber eigentlich nur syntaktischer Zucker +# um eine Methode eines Objekts aufzurufen  1.+(3) #=> 4  10.* 5 #=> 50 -``` +100.methods.include?(:/) #=> true -## Special values sind Objekte -``` -nil # Nothing to see here -true # truth -false # falsehood +## Spezielle Werte sind Objekte +nil # Equivalent zu null in anderen Sprachen +true # Wahrheitswert +false # Falschheitswert  nil.class #=> NilClass  true.class #=> TrueClass  false.class #=> FalseClass -``` -## Objektvergleiche -### Gleicheit -``` +# Gleicheit  1 == 1 #=> true  2 == 1 #=> false -``` -### Ungleichheit -``` + +# Ungleichheit  1 != 1 #=> false  2 != 1 #=> true -``` -### Neben false selbst, nil ist ein anderer 'falsey' Wert -``` -!nil   #=> true -!false #=> true -!0     #=> false -``` -### Weitere Vergleiche -``` + +# Neben false selbst, ist nil der einzige andere  +# zu Falsch evaluierende Wert + +!!nil   #=> false +!!false #=> false +!!0     #=> true +!!""    #=> true + +# Weitere Vergleiche  1 < 10 #=> true  1 > 10 #=> false  2 <= 2 #=> true  2 >= 2 #=> true -``` + +# Kombinierter Vergleichsoperator (gibt `1` zurück wenn das erste Argument  +# größer ist, und `-1`, wenn das zweite Argument größer ist, sonst `0`) +1 <=> 10 #=> -1 (1 < 10) +10 <=> 1 #=> 1 (10 > 1) +1 <=> 1 #=> 0 (1 == 1) +  ### 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. +# Es gibt alternative Versionen der logischen Operatoren mit niedrigerer +# Wertigkeit. Diese werden meistens zur Flusskontrolle 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_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. +# `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 +# String Interpolation +placeholder = 'Ruby' +"Ich kann in #{placeholder} Platzhalter mit doppelten Anführungszeichen füllen." +#=> "Ich kann in Ruby Platzhalter mit doppelten Anführungszeichen füllen." -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. +# Du kannst Strings mit `+` verbinden, nicht jedoch mit anderen Typen +'hallo ' + 'Welt'  #=> "hallo Welt" +'Hallo ' + 3 #=> TypeError: no implicit conversion of Integer into String +'hallo ' + 3.to_s #=> "hallo 3" +"hallo #{3}" #=> "hallo 3" + +# ...oder Strings mit Operatoren kombinieren +'hallo ' * 3 #=> "hallo hallo hallo " + +# ...oder Strings an andere Strings anhängen +'hallo' << ' Welt' #=> "hallo Welt" + +# Du kannst Text mit einer neuen Zeile am Ende ausgeben +puts "Ich gebe Text aus!" +#=> Ich gebe Text aus! +#=> nil + +# ...oder Text ohne einen Zeilenumbruch ausgeben +print "Ich gebe Text aus!" +#=> "Ich gebe Text aus!" => nil -### 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 -``` + +# Beachte, dass Zuweisungen den zugewiesenen Wert zurückgeben. +# D.h. du kannst mehrfache Zuweisungen machen. +  x = y = 10 #=> 10  x #=> 10  y #=> 10 -``` -## Benennung -### Konvention ist snake_case -``` + +# Nutze snake_case für Variablennamen.  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. -``` +# Nutze verständliche Variablennamen. +path_to_project_root = '/guter/Name/' +m = '/schlechter/Name/' + + +# Symbole sind unveränderliche, wiederverwendbare Konstanten, welche intern +# als Integer repräsentiert werden. Sie werden häufig anstelle von Strings +# verwendet, um semantisch sinnvoll Werte zu übermitteln. +# Symbols werden mit dem Doppelpunkt gekennzeichnet. +  :pending.class #=> Symbol +  status = :pending +  status == :pending #=> true +  status == 'pending' #=> false +  status == :approved #=> false -``` + +# Strings können in Symbole konvertiert werden und umgekehrt. +status.to_s #=> "pending" +"argon".to_sym #=> :argon +  # Arrays -## Ein Array anlegen -``` +# Das ist ein Array.  array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] -``` -## Array können verschiedene Typen beinhalten -``` +# 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önnenindiziert werden. -## Arrays können von vorne indiziert werden -``` +# Von vorne...  array[0] #=> 1 +array.first #=> 1  array[12] #=> nil -``` -## Arrays können von hinten indiziert werden -``` +# ...oder von hinten...  array[-1] #=> 5 -``` +array.last #=> 5 -## Arrays können mit Start Index und Länge indiziert werden -``` +# ...oder mit einem Startindex und einer Länge...  array[2, 3] #=> [3, 4, 5] -``` -## Arrays können mit einer Range indiziert werden -``` +# ...oder mit einem Range...  array[1..3] #=> [2, 3, 4] -``` -## Einen Wert hinzufügen -``` +# Du kanns ein Array umkehren. +# Gib ein neues Array mit umgkehrten Werten zurück +[1,2,3].reverse #=> [3,2,1] + +# Kehre ein Array an Ort und Stelle um, um die Variable mit den  +# umgekehrten Werten zu aktualisieren. +a = [1,2,3] +a.reverse! #=> a==[3,2,1] wegen des Aufrufs von reverse mit Ausrufezeichens ('!') + +# Wie bei der Arithmetik, ist Zugriff mit [index] nur  +# syntaktischer Zucker für den Aufruf der `[]` Methode auf dem Objekt. +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# Du kannst Werte zu einem Array hinzufügen...  array << 6 #=> [1, 2, 3, 4, 5, 6] +# Oder so  array.push(6) #=> [1, 2, 3, 4, 5, 6] -``` -## Testen, ob ein Element schon vorhanden ist -``` +# ...und testen ob ein Element schon vorhanden ist  array.include?(1) #=> true -``` -# Hashes -Hashes sind das Hauptfeature um Key/Values zu speichern +# Hashes sind Rubys Hauptdatenstruktur for Schlüssel/Wert Paare. +# Hashes werden durch geschweifte Klammern gekennzeichnet. +hash = { 'Farbe' => 'grün', 'Nummer' => 5 } -## Ein Hash anlegen -``` -hash = { 'color' => 'green', 'number' => 5 } -hash.keys #=> ['color', 'number'] -``` +hash.keys #=> ['farbe', 'nummer'] -## Wert per key herausfinden -``` -hash['color'] #=> 'green' -hash['number'] #=> 5 -hash['nothing here'] #=> nil -// Fragen an einen Hash nach einem Schlüssel, der nicht existiert, ruft nil hervor: -``` +# Hashes can be quickly looked up by key. +hash['Farbe'] #=> "grün" +hash['Nummer'] #=> 5 -##  Symbols können auch keys sein -``` -new_hash = { defcon: 3, action: true } -new_hash.keys #=> [:defcon, :action] -``` +# Abfragen eines nicht vorhandenen Schlüssels, gibt nil zurück.  +hash['nicht vorhanden'] #=> nil -## Testen ob ein Key oder ein Value existiert -``` -new_hash.has_key?(:defcon) #=> true -new_hash.has_value?(3) #=> true -``` +# Wenn du Symbole als Schlüssel in einem Hash verwendest, kannst du +# eine alternative Syntax verwenden. +hash = { :defcon => 3, :action => true } +hash.keys #=> [:defcon, :action] -### Tipp:  Arrays und Hashes sind Enumerable -### Und haben gemeinsame, hilfreiche Methoden wie: -### each, map, count, and more +hash = { defcon: 3, action: true } +hash.keys #=> [:defcon, :action] + +# Testen ob ein Schlüssel oder Wert im Hash existiert +hash.key?(:defcon) #=> true +hash.value?(3) #=> true + +# Tipp: Arrays und Hashes sind Enumerables! +# Sie haben viele nützliche Methoden gemein, wie each, map, count, und andere.  # Kontrolstrukturen -## if -``` + +# Bedingungen  if true -  'if statement' +  'wenn Bedingung'  elsif false -  'else if, optional' +  'sonst wenn, optional'  else -  'else, also optional' +  'sonst, auch 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. -``` +# Wenn eine Kontrollstruktur keinen Code-Block, sondern einen einzigen  +# Ausdruck ausführt, dann kannst du die nachgestellte if-Notation verwenden +warnings = ['Nachname fehlt', 'Adresse zu kurz'] +puts("Vorhandene Warnungen:\n" + warnings.join("\n"))  if !warnings.empty? + +# Formuliere die Bedingung um, wenn sich `unless` besser liest als `if` +puts("Vorhandene Warnungen:\n" + warnings.join("\n")) unless warnings.empty? + +# Schleifen +# Traditionell ist das Benutzen von `for` Schleifen in Ruby eher unüblich. +# Stattdessen werden diese mit Hilfe von Enumerables implementiert, was mit +# dem Aufrufen von `each` einhergeht.  (1..5).each do |counter| -  puts "iteration #{counter}" +  puts "Iteration #{counter}" +end + +# Was in etwa das selbe ist wie Folgendes (selten in Ruby zu sehen). +for counter in 1..5 +  puts "Iteration #{counter}"  end -``` -Die each Methode einer Range führt den Block für jedes Element der Range aus. +# Das `do |variable| ... end` Konstrukt wird `block` genannt.  +# Blocks sind vergleichbar mit Lambdas, anonymen Funktionen  +# oder Closures in anderen Programmiersprachen. +# Sie können als Objekte übergeben, aufgerufen oder als Methoden  +# zugewiesen werden. -Dem Block wird ein "counter" parameter übergeben. +# Die `each` Methode eines Ranges führt den Block einmal für jedes  +# Element des Ranges aus.  +# Dem Block wird eine counter Variable als Parameter übergeben. -### Den Block kann man auch in geschweiften Klammern schreiben -``` -(1..5).each { |counter| puts "iteration #{counter}" } -``` +# Du kannst einen Block auch mit geschweiften Klammern schreiben. +(1..5).each { |counter| puts "Iteration #{counter}" } -### Each kann auch über den Inhalt von Datenstrukturen iterieren -``` +# Each kann auch über den Inhalt von Datenstrukturen iterieren.  array.each do |element| -  puts "#{element} is part of the array" +  puts "#{element} is Teil des Arrays"  end +  hash.each do |key, value| -  puts "#{key} is #{value}" +  puts "#{key} ist #{value}" +end + +# Um auf den Laufindex zuzugreifen kannst du `each_with_index` verwenden +# und eine index Variable definieren.  +array.each_with_index do |element, index| +  puts "#{element} ist Nummer #{index} im Array"  end  counter = 1  while counter <= 5 do -  puts "iteration #{counter}" +  puts "Iteration #{counter}"    counter += 1  end -``` +#=> Iteration 1 +#=> Iteration 2 +#=> Iteration 3 +#=> Iteration 4 +#=> Iteration 5 + +# Es gibt einige andere hilfreiche Schleifenfunktionen in Ruby. +# Wie etwa 'map', 'reduce', 'inject' und viele andere mehr.  +# Map zum Beispiel iteriert über das Array, führt für jedes Element  +# die Anweisungen aus,  +# die im Block definiert sind und gibt ein völlig neues Array zurück. +array = [1,2,3,4,5] +doubled = array.map do |element| +  element * 2 +end +puts doubled +#=> [2,4,6,8,10] +puts array +#=> [1,2,3,4,5] -## case -``` +# Case Konstruct  grade = 'B'  case grade  when 'A' -  puts 'Way to go kiddo' +  puts 'So wird’s gemacht'  when 'B' -  puts 'Better luck next time' +  puts 'Viel Glück beim nächsten Mal'  when 'C' -  puts 'You can do better' +  puts 'Das kannst du besser'  when 'D' -  puts 'Scraping through' +  puts 'Gerade so durch'  when 'F' -  puts 'You failed!' +  puts 'Durchgefallen!'  else -  puts 'Alternative grading system, eh?' +  puts 'Anderes Bewertungssystem, was?'  end -=> "Better luck next time" -``` +#=> "Viel Glück beim nächsten Mal" -### Case können auch ranges -``` +# Case kann auch Ranges benutzen  grade = 82  case grade  when 90..100 -  puts 'Hooray!' +  puts 'Hurra!'  when 80...90 -  puts 'OK job' +  puts 'OK gemacht'  else -  puts 'You failed!' +  puts 'Durchgefallen!'  end -=> "OK job" -``` +#=> "OK gemacht" -# Exception handling: -``` +# Fehlerbehandlung  begin -  # code here that might raise an exception -  raise NoMemoryError, 'You ran out of memory.' +  # Code der einen Fehler wirft... +  raise NoMemoryError, 'Dein Speicher ist voll.'  rescue NoMemoryError => exception_variable -  puts 'NoMemoryError was raised', exception_variable +  puts 'NoMemoryError ist aufgetreten', exception_variable  rescue RuntimeError => other_exception_variable -  puts 'RuntimeError was raised now' +  puts 'RuntimeError ist aufgetreten'  else -  puts 'This runs if no exceptions were thrown at all' +  puts 'Das wird ausgeführt, wenn keine Fehler geworfen wurden'  ensure -  puts 'This code always runs no matter what' +  puts 'Dieser Code wird immer ausgeführt, egal was vorher passiert'  end -``` -# Funktionen -``` + +# Methoden +  def double(x)    x * 2  end -``` -## Funktionen (und Blocks) -## geben implizit den Wert des letzten Statements zurück -``` + +# Methoden (und Blocks) geben implizit den Wert des letzten Anweisung zurück.  double(2) #=> 4 -``` -### Klammern sind optional wenn das Ergebnis nicht mehrdeutig ist -``` +# Klammern sind optional wenn die Anweisung dadurch nicht mehrdeutig wird.  double 3 #=> 6 +  double double 3 #=> 12 +  def sum(x, y)    x + y  end -``` -### Methoden Parameter werden per Komma getrennt -``` +# Die Argumente einer Methode werden durch ein 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 -``` +# yield +# Alle Methoden haben implizit einen optionalen block Parameter. +# Dieser kann durch das Schlüsselwort 'yield' ausgeführt werden.  def surround    puts '{'    yield    puts '}'  end -surround { puts 'hello world' } -``` -## Einen Block kann man auch einer Methoden übergeben -### "&" kennzeichnet die Referenz zum übergebenen Block -``` +surround { puts 'hallo Welt' } + +#=> { +#=> hallo Welt +#=> } + +# Blocks können in ein 'Proc' Objekt umgewandelt werden.  +# Dieses ist eine Art Container um den Block und erlaubt ihn an eine  +# andere Methode zu übergeben, ihn in einen anderen Gültigkeitsbereicht  +# einzubinden oder ihn andersweitig zu verändern. +# Am häufigsten findet man dies bei Parameterlisten von Methoden, in Form  +# eines letzten '&block' Parameters, der den Block – wenn es einen gibt –  +# entgegen nimmt und ihn in ein 'Proc' umwandelt. Die Benennung '&block' ist  +# hier nur eine Konvention; es würde genauso mit '&pineapple' funktionieren.   def guests(&block) -  block.call 'some_argument' +  block.class #=> Proc +  block.call(4)  end -``` -### Eine Liste von Parametern kann man auch übergeben, -### Diese wird in ein Array konvertiert -### "*" kennzeichnet dies. -``` +# Die 'call' Methode eines Proc ist ganz ähnlich zum Aufruf von 'yield', wenn  +# ein Block vorhanden ist. Die Argumente, die 'call' übergeben werden, werden  +# als Argumente and den Block weitergereicht. + +guests { |n| "Du hast #{n} Gäste." } +# => "Du hast 4 Gäste." + +# Du kannst eine Liste von Argumenten übergeben, die dann in ein Array  +# umgewandelt werden. Dafür gibt es den splat-Operator (`*`).  def guests(*array)    array.each { |guest| puts guest }  end -``` + +# Destrukturierung + +# Ruby destrukturiert Arrays automatisch beim Zuweisen mehrerer Variablen. +a, b, c = [1, 2, 3] +a #=> 1 +b #=> 2 +c #=> 3 + +# In manchen Fällen will man den splat-Operator (`*`) verwenden um ein Array in +# eine Liste zu destrukturieren. +ranked_competitors = ["John", "Sally", "Dingus", "Moe", "Marcy"] + +def best(first, second, third) +  puts "Gewinner sind #{first}, #{second} und #{third}." +end + +best *ranked_competitors.first(3) #=> Gewinner sind John, Sally and Dingus. + +# Der splat-Operator kann auch in Parametern verwendet werden. +def best(first, second, third, *others) +  puts "Gewinner sind #{first}, #{second} und #{third}." +  puts "Es gab #{others.count} andere Teilnehmer." +end + +best *ranked_competitors  +#=> Gewinner sind John, Sally und Dingus. +#=> Es gab 2 andere Teilnehmer. + +# Per Konvention enden alle Methoden, die einen Wahrheitswert zurück geben, mit einem +# Fragezeichen. +5.even? #=> false +5.odd? #=> true + +# Wenn ein Methodenname mit einem Ausrufezeichen endet, dann tut diese Methode  +# per Konvention etwas Destruktives, wie z.B. das aufrufende Objekt zu  +# verändern. +# Viele Mehtoden haben eine !-Version um eine direkte Änderung zu machen und  +# eine Nicht-!-Version, die ein neues Objekt mit den Veränderungen zurück gibt. +company_name = "Dunder Mifflin" +company_name.upcase #=> "DUNDER MIFFLIN" +company_name #=> "Dunder Mifflin" +# Diesmal verändern wir company_name direkt. +company_name.upcase! #=> "DUNDER MIFFLIN" +company_name #=> "DUNDER MIFFLIN" +  # Klassen -## Werden mit dem class Schlüsselwort definiert -``` + +# Du kannst eine Klasse mit dem Schlüsselwort 'class' definieren.  class Human -``` -### Konstruktor bzw. Initializer -``` +  # Eine Klassenvariable. Sie wird von allen Instanzen einer Klasse geteilt. +  @@species = 'H. sapiens' + +  # Konstruktor bzw. Initializer    def initialize(name, age = 0) -    # Assign the argument to the "name" instance variable for the instance +    # Weise das Argument der Instanzvariable 'name' zu.      @name = name -    # If no age given, we will fall back to the default in the arguments list. +    # Wenn kein 'age' angegeben wurde wird der Standartwert aus der Argumentenlist verwendet.      @age = age    end -``` -### setter Methode -``` +  # Setter Methode    def name=(name)      @name = name    end -``` -### getter Methode -``` + +  # Getter Methode    def name      @name    end -``` -#### getter können mit der attr_accessor Methode vereinfacht definiert werden -``` +  # Getter & Setter können auch kürzer mit der attr_accessor Methode erstellt werden.    attr_accessor :name -  # Getter/setter methods can also be created individually like this + +  # Getter & Setter Methoden können auch einzeln erstellt werden.    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. + +  # Eine Klassenmethode unterscheidet sich durch ein 'self' von einer  +  # Instanzmethode. +  # Sie kann nur auf der Klasse und nicht auf einer Instanz der Klasse  +  # aufgerufen werden.      def self.say(msg)      puts msg    end +    def species      @@species    end  end -``` -## Eine Klasse instanziieren -``` +# Instanziieren einer Klasse  jim = Human.new('Jim Halpert')  dwight = Human.new('Dwight K. Schrute') -``` -## Methodenaufrufe -``` +# Du kannst die Methoden des erstellten Objekts aufrufen.  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 -``` +# Aufrufen einer Klassenmethode  Human.say('Hi') #=> "Hi" -``` -## Variable Gültigkeit -### Variablen die mit "$" starten, gelten global -``` -$var = "I'm a global var" +# Der Gültigkeitsbereich einer Variablen wird durch ihren Namen definiert. +# Variablen, die mit $ beginnen sind global gültig. +$var = "Ich bin eine globale Variable"  defined? $var #=> "global-variable" -``` -### Variablen die mit "@" starten, gelten für die Instanz -``` -@var = "I'm an instance var" +# Variablen, die mit @ beginnen, sind innerhalb einer Instanz gültig. +@var = "Ich bin eine Instanzvariable"  defined? @var #=> "instance-variable" -``` -### Variablen die mit "@@" starten, gelten für die Klasse -``` -@@var = "I'm a class var" +# Variablen, die mit @@ beginnen, sind für die Klasse gültig. +@@var = "Ich bin eine Klassenvariable"  defined? @@var #=> "class variable" -``` -### Variablen die mit einem Großbuchstaben anfangen, sind Konstanten -``` -Var = "I'm a constant" +# Variablen, die mit einem Großbuchstaben beginnen, sind Konstanten +Var = "Ich bin eine Konstante"  defined? Var #=> "constant" -``` -## Class ist auch ein Objekt -### Hat also auch Instanzvariablen -### Eine Klassenvariable wird innerhalb der Klasse und Ableitungen geteilt. +# Class ist in Ruby auch ein Objekt. Deshalb kann eine Klasse Instanzvariablen +# haben. Eine Klassenvariable wird zwischen der Klasse und all ihren  +# Ableitungen geteilt. -### Basis Klasse -``` +# Basis Klasse  class Human    @@foo = 0 +    def self.foo      @@foo    end +    def self.foo=(value)      @@foo = value    end  end -``` -### Abgeleitete Klasse -``` +# Abgeleitete Klasse  class Worker < Human  end -Human.foo # 0 -Worker.foo # 0 -Human.foo = 2 # 2 -Worker.foo # 2 -``` -### Eine Klasseninstanzvariable wird nicht geteilt -``` +Human.foo #=> 0 +Worker.foo #=> 0 + +Human.foo = 2 +Worker.foo #=> 2 + +# Ableitungen einer Klasse haben keinen Zugriff auf eine Eine Klassen-Instanzvariable.  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 -``` -``` + +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 -``` + +# Ein Einbinden (include) eines Moduls bindet seine Methoden an die Instanzen  +# der Klasse. +# Ein Erweitern (extend) eines Moduls bindet seine Methoden an die Klasse  +# selbst.  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 + +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 -  class Something -    include ConcernExample + +  module InstanceMethods +    def qux +      'qux' +    end    end -``` -``` -Something.bar     # => 'bar' -Something.qux     # => NoMethodError: undefined method `qux' -Something.new.bar # => NoMethodError: undefined method `bar' -Something.new.qux # => 'qux' +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 +## Weitere Links -//EN +_(z.T. auf Englisch)_ -- [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/) +- [Offizielle Ruby Website](https://www.ruby-lang.org/de/) +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - Eine Variante dieses Dokuments mit in-Browser Challenges. +- [RubyMonk](https://rubymonk.com/) - Lerne Ruby mit einer Reihe interaktiver Tutorials. +- [Offizielle Dokumentation](http://ruby-doc.org/core)  - [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) -- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. -- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Eine ältere [freie Ausgabe](http://ruby-doc.com/docs/ProgrammingRuby/) ist online verfügbar. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Ein von der Community erstellter Ruby coding style guide. +- [Try Ruby](http://tryruby.org) - Lerne die Grundlagen der Ruby Programmiersprache, interaktiv im Browser. diff --git a/el-gr/vim-gr.html.markdown b/el-gr/vim-gr.html.markdown new file mode 100644 index 00000000..679a5488 --- /dev/null +++ b/el-gr/vim-gr.html.markdown @@ -0,0 +1,267 @@ +--- +category: tool +tool: vim +contributors: +    - ["RadhikaG", "https://github.com/RadhikaG"] +filename: LearnVim.txt +lang: el-gr +--- + + +[Vim](http://www.vim.org) +To (Vi IMproved) είναι ένας κλώνος του δημοφιλούς vi editor για Unix. +Είναι ένας text editor σχεδιασμένος για ταχύτητα και αυξημένη παραγωγικότητα, +και υπάρχει σχεδόν σε όλα τα Unix-based συστήματα. Έχει διάφορα keybindings +(συντομεύσεις πλήκτρων) για να πλοηγούμαστε γρήγορα σε συγκεκριμένα σημεία ενός αρχείου, +καθώς και για γρήγορη επεξεργασία. + +## Τα βασικά της πλοήγησης στον Vim + +``` +    vim <filename>   # Άνοιξε το <filename> στον vim +    :help <topic>    # Άνοιξε το built-in βοήθημα για το <topic> αν υπάρχει +    :q               # Βγες από τον vim +    :w               # Αποθήκευσε το τρέχον αρχείο +    :wq              # Αποθήκευσε το τρέχον αρχείο και βγες από τον vim +    ZZ               # Αποθήκευσε το τρέχον αρχείο και βγες από τον vim +    :q!              # Βγες χωρίς αποθήκευση +                     # ! *αναγκάζει* το :q να εκτελεστεί, γι αυτό βγαίνει χωρίς saving +    :x               # Ίδιο με το wq αλλά πιο σύντομο + +    u                # Undo +    CTRL+R           # Redo + +    h                # Μετακινήσου κατά ένα χαρακτήρα αριστερά +    j                # Μετακινήσου μια γραμμή κάτω +    k                # Μετακινήσου μια γραμμή πάνω +    l                # Μετακινήσου μια γραμμή δεξιά + +    Ctrl+B 	         # Πήγαινε μία οθόνη πίσω +    Ctrl+F 	         # Πήγαινε μία οθόνη μπροστά +    Ctrl+U           # Πήγαινε μισή οθόνη πίσω +    Ctrl+D 	         # Πήγαινε μισή οθόνη μπροστά + +    # Μετακινήσεις στην ίδια γραμμή + +    0                # Πήγαινε στην αρχή της γραμμής +    $                # Πήγαινε στο τέλος της γραμμής +    ^                # Πήγαινε στον πρώτο μη κενό χαρακτήρα της γραμμής + +    # Αναζήτηση στο κείμενο + +    /word            # Υπογραμμίζει όλες τις εμφανίσεις της λέξης μετά τον cursor +    ?word            # Υπογραμμίζει όλες τις εμφανίσεις της λέξης πριν τον cursor +    n                # Μετακινεί τον cursor στην επόμενη εμφάνιση της λέξης +    N                # Μετακινεί τον cursor στην προηγούμενη εμφάνιση της λέξης + +    :%s/foo/bar/g    # άλλαξε το 'foo' σε 'bar' σε κάθε γραμμή του αρχείου +    :s/foo/bar/g     # άλλαξε το 'foo' σε 'bar' στην τρέχουσα γραμμή + +    # Άλματα σε χαρακτήρες + +    f<character>     # Άλμα μπροστά και προσγείωση στο επόμενο <character> +    t<character>     # Άλμα μπροστά και προσγείωση αμέσως πριν το προηγούμενο <character> + +    # Για παράδειγμα, +    f<               # Άλμα μπροστά και προσγείωση σε < +    t<               # Άλμα μπροστά και προσγείωση αμέσως πριν < + +    # Μετακινήσεις κατά λέξεις + +    w                # Πήγαινε μια λέξη μπροστά +    b                # Πήγαινε μια λέξη πίσω +    e                # Πήγαινε στο τέλος της λέξης στην οποία είσαι + +    # Άλλοι χαρακτήρες για να τριγυρνάμε + +    gg               # Πήγαινε στην αρχή του αρχείου +    G                # Πήγαινε στο τέλος του αρχείου +    :NUM             # Πήγαινε στη γραμμή με αριθμό NUM (οποιοσδήποτε αριθμός) +    H                # Πήγαινε στην κορυφή της σελίδας +    M                # Πήγαινε στην μέση της σελίδας +    L                # Πήγαινε στο κάτω άκρο της σελίδας +``` + +## Help docs: +Το Vim έχει built-in help documentation που μπορείς να δεις με `:help <topic>`. +Για παράδειγμα το `:help navigation` θα σου εμφανίσει documentation σχετικό με +το πως να πλοηγείσαι στο αρχείο! + +To `:help` μπορεί να χρησιμοποιηθεί και χωρίς option. Αυτό θα εμφανίσει το default +help dialog που σκοπεύει να κάνει το vim πιο προσιτό σε αρχάριους! + +## Modes: + +O Vim στηρίζεται στο concept των **modes**. + +- Command Mode -  ο vim εκκινεί σε αυτό mode, χρησιμοποιείται για πλοήγηση και εντολές +- Insert Mode  - χρησιμοποιείται για να κάνουμε αλλαγές στα αρχεία +- Visual Mode  - χρησιμοποιείται για να υπογραμμίζουμε κείμενα και να κάνουμε διάφορα σε αυτά +- Ex Mode      - χρησιμοποιείται για να πάμε στο κάτω μέρος με το ':' που δίνουμε εντολές + +``` +    i                # Βάζει το vim σε insert mode, πριν τη θέση cursor +    a                # Βάζει το vim σε insert mode, μετά τη θέση cursor +    v                # βάζει τον vim σε visual mode +    :                # Βάζει τον vim σε ex mode +    <esc>            # φεύγει από όποιο mode είμαστε και πάει σε command mode + +    # Αντιγραφή-Επικόληση κειμένου + +    y                # Yank (κάνε copy) ό,τι είναι επιλεγμένο +    yy               # Yank την γραμμή στην οποία είσαι +    d                # διάγραψε ό,τι είναι επιλεγμένο +    dd               # Διάγραψε τη γραμμή στην οποία είσαι +    p                # Κάνε Paste το αντεγραμένο κείμενο μετά την θέση του cursor +    P                # Κάνε Paste το αντεγραμένο κείμενο πριν την θέση του cursor +    x                # Διάγραψε τον χαρακτήρα που είναι κάτω από τον cursor +``` + +## Η 'γραμματική' του Vim + +Μπορείς να σκεφτείς τον Vim ως ένα σύνολο εντολών +σε μορφή 'Verb-Modifier-Noun', όπου + +- Verb     - η ενέργεια που θες να κάνεις +- Modifier - πώς κάνεις την ενέργεια +- Noun     - το αντικείμενο που δέχεται την ενέργεια + +Μερικά παραδείγματα ''Ρημάτων', 'Modifiers' και 'Ουσιαστικών': + +``` +    # 'Ρήματα' + +    d                # Διάγραψε +    c                # Άλλαξε +    y                # Yank (αντίγραψε) +    v                # Επίλεξε οπτικά + +    # 'Modifiers' + +    i                # Μέσα +    a                # Γύρω +    NUM              # Αριθμός (NUM = οποιοσδήποτε αριθμός) +    f                # Ψάξε κάτι και πήγαινε εκεί που βρίσκεται +    t                # Ψάξε κάτι και πήγαινε πριν από εκεί που βρίσκεται +    /                # Βρες κάποιο string μετά από τον cursor +    ?                # Βρες κάποιο string πριν τον cursor + +    # 'Ουσιαστικά' + +    w                # Λέξη +    s                # Πρόταση +    p                # Παράγραφος +    b                # Block + +    # Δείγματα 'προτάσεων' ή εντολών + +    d2w              # Διάγραψε 2 λέξεις +    cis              # Άλλαξε μέσα στην πρώταση +    yip              # Αντίγραψε την παράγραφο στην οποία βρίσκεσαι +    ct<              # Άλλαξε σε < +                     # Άλλαξε το κείμενο από το οποίο είσαι πριν το επόμενο bracketChange the text from where you are to the next open bracket +    d$               # Διάγραψε μέχρι το τέλος της γραμμής +``` + +## Μερικά shortcuts και κόλπα + +        <!--TODO: Βάλτε κι άλλα!--> +``` +    >                # Στοίχισε προς τα δεξιά την επιλογή σου κατά ένα block +    <                # Στοίχισε προς τα αριστερά την επιλογή σου κατά ένα block +    :earlier 15m     # Κάνε το αρχείο όπως ήταν πριν 15 λεπτά +    :later 15m       # Ακύρωση για την παραπάνω εντολή +    ddp              # Αντάλλαξε τις θέσεις διαδοχικών γραμμών +    .                # Επανάλαβε την προηγούμενη ενέργεια +    :w !sudo tee %   # Σώσε το τρέχον αρχείο ως root +    :set syntax=c    # Κάνε syntax highlighting για τη γλώσσα c +    :sort            # Ταξινόμησε όλες τις γραμμές +    :sort!           # Ταξινόμησε ανάποδα όλες τις γραμμές (αύξουσα σειρά) +    :sort u          # Ταξινόμησε όλες τις γραμμές και διάγραψε τις διπλές γραμμές +    ~                # Άλλαξε τα κεφαλαία σε μικρά στο επιλεγμένο κείμενο +    u                # Το επιλεγμένο κείμενο να γίνει πεζά γράμματα +    U                # Το επιλεγμένο κείμενο να γίνει κεφαλαία γράμματα + +    # Fold text +    zf               # Διπλώνει (συμπιέζει τις γραμμές σε μία) το επιλεγμένο κείμενο +    zo               # Ξεδιπλώνει το επιλεγμένο fold +    zc               # Κλείνει το επιλεγμένο fold +    zR               # Ανοίγει όλα τα folds +    zM               # Κλείνει όλα τα folds +``` + +## Macros + +Τα macros βασικά είναι καταγραφή ενεργειών. +Όταν ξεικάς να καταγράφεις ένα macro καταγράφονται **όλες** οι ενέργεις και οι +εντολές που χρησιμοποιείς, μέχρι να σταματήσεις την καταγραφή. Όταν καλείς ένα macro, +εκτελείται πάλι η ίδια σειρά από ενέργειες και εντολές στο επιλεγμένο κείμενο. + +``` +    qa               # Ξεκίνα να καταγράφεις ένα macro που θα ονομαστεί 'a' +    q                # Σταμάτα την καταγραφή +    @a               # Τρέξε το macro +``` + +### Configuring ~/.vimrc + +Το αρχείο .vimrc μπορεί να χρησιμοποιηθεί για να κάνεις configure το Vim στο startup. + +Εδώ βλέπουμε δείγμα ενός ~/.vimrc file: + +``` +" Example ~/.vimrc +" 2015.10 + +" Required for vim to be iMproved +set nocompatible + +" Determines filetype from name to allow intelligent auto-indenting, etc. +filetype indent plugin on + +" Enable syntax highlighting +syntax on + +" Better command-line completion +set wildmenu + +" Use case insensitive search except when using capital letters +set ignorecase +set smartcase + +" When opening a new line and no file-specific indenting is enabled, +" keep same indent as the line you're currently on +set autoindent + +" Display line numbers on the left +set number + +" Indentation options, change according to personal preference + +" Number of visual spaces per TAB +set tabstop=4 + +" Number of spaces in TAB when editing +set softtabstop=4 + +" Number of spaces indented when reindent operations (>> and <<) are used +set shiftwidth=4 + +" Convert TABs to spaces +set expandtab + +" Enable intelligent tabbing and spacing for indentation and alignment +set smarttab +``` + +### Αναφορές + +[Vim | Home](http://www.vim.org/index.php) + +`$ vimtutor` + +[A vim Tutorial and Primer](https://danielmiessler.com/study/vim/) + +[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about) + +[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim) diff --git a/elixir.html.markdown b/elixir.html.markdown index 0b717ca6..0226ecaf 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -457,3 +457,4 @@ Agent.update(my_agent, fn colors -> ["blue" | colors] end)  * [Elixir Cheat Sheet](https://media.pragprog.com/titles/elixir/ElixirCheat.pdf)  * ["Learn You Some Erlang for Great Good!"](https://learnyousomeerlang.com/) by Fred Hebert  * ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) by Joe Armstrong +* [Introduction to Elixir](https://learn-elixir.com/) diff --git a/git.html.markdown b/git.html.markdown index aa96c90a..a40ef01b 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -82,12 +82,12 @@ pushed to other repositories, or not!  ### Branch  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. +committing, this pointer will automatically update to point to 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) +functionality to mark release points (v1.0, and so on).  ### HEAD and head (component of .git dir) diff --git a/groovy.html.markdown b/groovy.html.markdown index 89ca973a..0d589c10 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -184,7 +184,7 @@ class Foo {    Methods with optional parameters  */ -// A mthod can have default values for parameters +// A method can have default values for parameters  def say(msg = 'Hello', name = 'world') {      "$msg $name!"  } diff --git a/it-it/sql-it.html.markdown b/it-it/sql-it.html.markdown new file mode 100644 index 00000000..7db2eec1 --- /dev/null +++ b/it-it/sql-it.html.markdown @@ -0,0 +1,112 @@ +--- +language: SQL +filename: learnsql-it.sql +contributors: +  - ["Bob DuCharme", "http://bobdc.com/"] +translators: +  - ["Christian Grasso", "https://grasso.io"] +lang: it-it +--- + +Structured Query Language (SQL) è un linguaggio standard ISO per la creazione e la gestione +di database organizzati in un insieme di tabelle. Le diverse implementazioni aggiungono +spesso le proprie estensioni al linguaggio base ([confronto tra le diverse implementazioni](http://troels.arvin.dk/db/rdbms/)) + +Le diverse implementazioni forniscono inoltre un prompt per inserire in modo interattivo i comandi +o eseguire il contenuto di uno script. + +I comandi di seguito lavorano sul [database di esempio MySQL](https://dev.mysql.com/doc/employee/en/) +disponibile su [GitHub](https://github.com/datacharmer/test_db). I file .sql contengono liste di comandi +simili a quelli mostrati di seguito, che creano e riempiono delle tabelle con dati di un'azienda fittizia. +Il comando per eseguire questi script può variare in base all'implementazione in uso. + + +```sql +-- I commenti iniziano con due trattini. Ogni comando va terminato con il punto e virgola + +-- SQL è case-insensitive per quanto riguarda i comandi; in genere si +-- preferisce scriverli in maiuscolo per distinguerli dai nomi di  +-- database, tabelle e colonne + +-- Crea ed elimina un database. I nomi di database e tabelle sono case-sensitive +CREATE DATABASE someDatabase; +DROP DATABASE someDatabase; + +-- Lista dei database disponibili +SHOW DATABASES; + +-- Attiva uno specifico database +USE employees; + +-- Seleziona tutte le righe e le colonne dalla tabella departments +SELECT * FROM departments; + +-- Seleziona tutte le righe della tabella departments,  +-- ma solo le colonne dept_no e dept_name.  +-- È possibile suddividere i comandi su più righe. +SELECT dept_no, +       dept_name FROM departments; + +-- Seleziona solo le prime 5 righe della tabella departments.  +SELECT * FROM departments LIMIT 5; + +-- Ottiene la colonna dept_name della tabella departments +-- solo per le righe il cui valore di dept_name contiene 'en'.  +SELECT dept_name FROM departments WHERE dept_name LIKE '%en%'; + +-- Ottiene tutte le colonne della tabella departments +-- solo per le righe che hanno un dept_name formato da una 'S' +-- seguita esattamente da altri 4 caratteri +SELECT * FROM departments WHERE dept_name LIKE 'S____'; + +-- Seleziona i valori di title dalla tabella titles eliminando i duplicati +SELECT DISTINCT title FROM titles; + +-- Come sopra, ma i valori sono ordinati alfabeticamente +SELECT DISTINCT title FROM titles ORDER BY title; + +-- Mostra il numero di righe della tabella departments +SELECT COUNT(*) FROM departments; + +-- Mostra il numero di righe della tabella departments +-- il cui valore di dept_name contiene 'en'. +SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%'; + +-- Un JOIN tra più tabelle: la tabella titles contiene gli  +-- incarichi lavorativi associati ad un certo numero di impiegato. +-- Con il JOIN utilizziamo il numero di impiegato per ottenere +-- le informazioni ad esso associate nella tabella employees. +-- (Inoltre selezioniamo solo le prime 10 righe) + +SELECT employees.first_name, employees.last_name, +       titles.title, titles.from_date, titles.to_date +FROM titles INNER JOIN employees ON +       employees.emp_no = titles.emp_no LIMIT 10; + +-- Mostra tutte le tabelle di tutti i database. +-- Spesso le implementazioni forniscono degli shortcut per questo comando +SELECT * FROM INFORMATION_SCHEMA.TABLES +WHERE TABLE_TYPE='BASE TABLE'; + +-- Crea una tabella tablename1, con due colonne, per il database in uso. +-- Per le colonne specifichiamo il tipo di dato (stringa di max 20 caratteri) +CREATE TABLE tablename1 (fname VARCHAR(20), lname VARCHAR(20)); + +-- Inserisce una riga nella tabella tablename1. I valori devono essere +-- appropriati per la definizione della tabella +INSERT INTO tablename1 VALUES('Richard','Mutt'); + +-- In tablename1, modifica il valore di fname a 'John' +-- in tutte le righe che hanno come lname 'Mutt'.  +UPDATE tablename1 SET fname='John' WHERE lname='Mutt'; + +-- Elimina tutte le righe di tablename1 +-- il cui lname inizia per 'M'. +DELETE FROM tablename1 WHERE lname like 'M%'; + +-- Elimina tutte le righe della tabella tablename1 +DELETE FROM tablename1; + +-- Elimina la tabella tablename1 +DROP TABLE tablename1; +``` diff --git a/it-it/zfs-it.html.markdown b/it-it/zfs-it.html.markdown new file mode 100644 index 00000000..c1307e67 --- /dev/null +++ b/it-it/zfs-it.html.markdown @@ -0,0 +1,361 @@ +--- +category: tool +tool: zfs +contributors: +    - ["sarlalian", "http://github.com/sarlalian"] +translators: +    - ["Christian Grasso","https://grasso.io"] +filename: LearnZfs-it.txt +lang: it-it +--- + + +[ZFS](http://open-zfs.org/wiki/Main_Page) è un sistema di storage che combina file system +tradizionali e volume manager in un unico strumento. ZFS utilizza della terminologia +specifica, diversa da quella usata da altri sistemi di storage, ma le sue funzioni lo +rendono un ottimo tool per gli amministratori di sistema. + + +## Concetti base di ZFS + +### Virtual Device + +Un VDEV è simile a un dispositivo gestito da una scheda RAID. Esistono diversi tipi di +VDEV che offrono diversi vantaggi, tra cui ridondanza e velocità. In generale, +i VDEV offrono una maggiore affidabilità rispetto alle schede RAID. Si sconsiglia di +utilizzare ZFS insieme a RAID, poichè ZFS è fatto per gestire direttamente i dischi fisici. + +Tipi di VDEV: + +* stripe (disco singolo, senza ridondanza) +* mirror (mirror su più dischi) +* raidz +	* raidz1 (parity a 1 disco, simile a RAID 5) +	* raidz2 (parity a 2 dischi, simile a RAID 6) +	* raidz3 (parity a 3 dischi) +* disk +* file (non consigliato in production poichè aggiunge un ulteriore filesystem) + +I dati vengono distribuiti tra tutti i VDEV presenti nella Storage Pool, per cui un maggior +numero di VDEV aumenta le operazioni al secondo (IOPS). + +### Storage Pool + +Le Storage Pool di ZFS sono un'astrazione del livello inferiore (VDEV) e consentono di +separare il filesystem visibile agli utenti dal layout reale dei dischi. + +### Dataset + +I dataset sono simili ai filesystem tradizionali, ma con molte più funzioni che rendono +vantaggioso l'utilizzo di ZFS. I dataset supportano il [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write) +gli snapshot, la gestione delle quota, compressione e deduplicazione. + + +### Limiti + +Una directory può contenere fino a 2^48 file, ognuno dei quali di 16 exabyte. +Una storage pool può contenere fino a 256 zettabyte (2^78), e può essere distribuita +tra 2^64 dispositivi. Un singolo host può avere fino a 2^64 storage pool. + + +## Comandi + +### Storage Pool + +Azioni: + +* List (lista delle pool) +* Status (stato) +* Destroy (rimozione) +* Get/Set (lettura/modifica proprietà) + +Lista delle zpool + +```bash +# Crea una zpool raidz +$ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 + +# Lista delle zpool +$ zpool list +NAME    SIZE  ALLOC   FREE  EXPANDSZ   FRAG    CAP  DEDUP  HEALTH  ALTROOT +zroot   141G   106G  35.2G         -    43%    75%  1.00x  ONLINE  - + +# Informazioni dettagliate su una 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% +``` + +Stato delle zpool + +```bash +# Informazioni sullo stato delle zpool +$ zpool status +  pool: zroot + state: ONLINE +  scan: scrub repaired 0 in 2h51m with 0 errors on Thu Oct  1 07:08:31 2015 +config: + +        NAME                                          STATE     READ WRITE CKSUM +        zroot                                         ONLINE       0     0     0 +          gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655  ONLINE       0     0     0 + +errors: No known data errors + +# "Scrubbing" (correzione degli errori) +$ 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 +``` + +Proprietà delle zpool + +```bash + +# Proprietà di una zpool (gestite dal sistema o dall'utente) +$ zpool get all zroot +NAME   PROPERTY                       VALUE                          SOURCE +zroot  size                           141G                           - +zroot  capacity                       75%                            - +zroot  altroot                        -                              default +zroot  health                         ONLINE                         - +... + +# Modifica di una proprietà +$ zpool set comment="Dati" zroot +$ zpool get comment +NAME   PROPERTY  VALUE  SOURCE +tank   comment   -      default +zroot  comment   Dati   local +``` + +Rimozione di una zpool + +```bash +$ zpool destroy test +``` + + +### Dataset + +Azioni: + +* Create +* List +* Rename +* Delete  +* Get/Set (proprietà) + +Creazione dataset + +```bash +# Crea un dataset +$ zfs create tank/root/data +$ mount | grep data +tank/root/data on /data (zfs, local, nfsv4acls) + +# Crea un sottodataset +$ 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) + + +# Crea un 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  - +``` + +Lista dei dataset + +```bash +# Lista dei dataset +$ 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 +... + +# Informazioni su un dataset +$ zfs list zroot/home +NAME         USED  AVAIL  REFER  MOUNTPOINT +zroot/home   288K  30.8G   144K  none + +# Lista degli snapshot +$ 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  - +``` + +Rinominare un dataset + +```bash +$ zfs rename tank/root/home tank/root/old_home +$ zfs rename tank/root/new_home tank/root/home +``` + +Eliminare un dataset + +```bash +# I dataset non possono essere eliminati se hanno degli snapshot +$ zfs destroy tank/root/home +``` + +Lettura/modifica proprietà + +```bash +# Tutte le proprietà di un dataset +$ 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                    - +... + +# Proprietà specifica +$ zfs get compression zroot/usr/home +NAME            PROPERTY     VALUE     SOURCE +zroot/home      compression  off       default + +# Modifica di una proprietà +$ zfs set compression=gzip-9 mypool/lamb + +# Specifiche proprietà per tutti i dataset +$ 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 +... +``` + + +### Snapshot + +Gli snapshot sono una delle funzioni più importanti di ZFS: + +* Lo spazio occupato è la differenza tra il filesystem e l'ultimo snapshot +* Il tempo di creazione è di pochi secondi +* Possono essere ripristinati alla velocità di scrittura del disco +* Possono essere automatizzati molto semplicemente + +Azioni: + +* Create +* Delete +* Rename +* Access +* Send / Receive +* Clone + + +Creazione di uno snapshot + +```bash +# Crea uno snapshot di un singolo dataset +zfs snapshot tank/home/sarlalian@now + +# Crea uno snapshot di un dataset e dei suoi sottodataset +$ 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  - +... +``` + +Eliminazione di uno snapshot + +```bash +# Elimina uno snapshot +$ zfs destroy tank/home/sarlalian@now + +# Elimina uno snapshot ricorsivamente +$ zfs destroy -r tank/home/sarlalian@now + +``` + +Rinominare uno snapshot + +```bash +$ zfs rename tank/home/sarlalian@now tank/home/sarlalian@today +$ zfs rename tank/home/sarlalian@now today + +$ zfs rename -r tank/home@now @yesterday +``` + +Accedere ad uno snapshot + +```bash +# Utilizzare il comando cd come per una directory +$ cd /home/.zfs/snapshot/ +``` + +Invio e ricezione + +```bash +# Backup di uno snapshot su un file +$ zfs send tank/home/sarlalian@now | gzip > backup_file.gz + +# Invia uno snapshot ad un altro dataset +$ zfs send tank/home/sarlalian@now | zfs recv backups/home/sarlalian + +# Invia uno snapshot ad un host remoto +$ zfs send tank/home/sarlalian@now | ssh root@backup_server 'zfs recv tank/home/sarlalian' + +# Invia l'intero dataset e i suoi snapshot ad un host remoto +$ zfs send -v -R tank/home@now | ssh root@backup_server 'zfs recv tank/home' +``` + +Clonare gli snapshot + +```bash +# Clona uno snapshot +$ zfs clone tank/home/sarlalian@now tank/home/sarlalian_new + +# Rende il clone indipendente dallo snapshot originale +$ zfs promote tank/home/sarlalian_new +``` + +### Letture aggiuntive (in inglese) + +* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) +* [FreeBSD Handbook on ZFS](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/zfs.html) +* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) +* [Oracle's Tuning Guide](http://www.oracle.com/technetwork/articles/servers-storage-admin/sto-recommended-zfs-settings-1951715.html) +* [OpenZFS Tuning Guide](http://open-zfs.org/wiki/Performance_tuning) +* [FreeBSD ZFS Tuning Guide](https://wiki.freebsd.org/ZFSTuningGuide) diff --git a/jsonnet.html.markdown b/jsonnet.html.markdown new file mode 100644 index 00000000..175642d4 --- /dev/null +++ b/jsonnet.html.markdown @@ -0,0 +1,139 @@ +--- +language: jsonnet +filename: learnjsonnet.jsonnet +contributors: +  - ["Huan Wang", "https://github.com/fredwangwang"] +--- + +Jsonnet is a powerful templating language for JSON. Any valid JSON +document is a valid Jsonnet object. For an interactive demo/tutorial, +click [here](https://jsonnet.org/learning/tutorial.html) + +```python +// single line comment + +/* +    multiline comment +*/ + +// as well as python style comment + +# define a variable. +# Variables have no effect in the generated JSON without being used. +local num1 = 1; +local num2 = 1 + 1; +local num3 = 5 - 2; +local num4 = 9 % 5; +local num5 = 10 / 2.0; +# jsonnet is a lazy language, if a variable is not used, it is not evaluated. +local num_runtime_error = 1 / 0; + +# fields are valid identifiers without quotes +local obj1 = { a: 'letter a', B: 'letter B' }; + +local arr1 = ['a', 'b', 'c']; + +# string literals use " or '. +local str1 = 'a' + 'B'; +# multiline text literal in between ||| +# Each line must start with a white space. +local str_multiline = ||| +  this is a +  multiline string +|||; +# Python-compatible string formatting is available via % +# When combined with ||| this can be used for templating text files. +local str_templating = ||| +  %(f1)0.3f +||| % { f1: 1.2345678 }; +assert str_templating == '1.235\n'; + +# if b then e else e. The else branch is optional and defaults to null +local var1 = if 3 < 2 then "YES"; +assert var1 == null; + +local obj2 = { +  # variable defined inside the object ends with ',' +  local var_in_obj = 0, + +  local vowels = ['a', 'e', 'i', 'o', 'u'], +  local numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + +  # [num] to look up an array element +  first_vowel: vowels[0], +  # can also slice the array like in Python +  even_numbers: numbers[1::2], + +  # python-style list and object comprehensions are also supported +  double_numbers: [x * 2 for x in numbers], +  even_numbers_map: { +      # [ ] syntax in field name is to compute the field name dynamically +      [x + '_is_even']: true for x in numbers if x % 2 == 0 +  }, + +  nested: { +    nested_field1: 'some-value', +    # self refers to the current object +    # ["field-name"] or .field-name can be used to look up a field +    nested_field2: self.nested_field1, +    nested_field3: self.nested_field1, +    # $ refers to outer-most object +    nested_field4: $.first_vowel, + +    assert self.nested_field1 == self.nested_field2, +    assert self.nested_field1 == self.nested_field3, +  }, + +  special_field: 'EVERYTHING FEELS BAD', +}; + +local obj3 = { +  local var_in_obj = 1.234, +  local var_in_obj2 = { a: { b: 'c' } }, + +  concat_array: [1, 2, 3] + [4], +  # strings can be concat with +, +  # which implicitly converts one operand to string if needed. +  concat_string: '123' + 4, + +  # == tests deep equality +  equals: { a: { b: 'c', d: {} } } == var_in_obj2, + +  special_field: 'this feels good', +}; + +# objects can be merged with + where the right-hand side wins field conflicts +local obj4 = obj2 + obj3; +assert obj4.special_field == 'this feels good'; + +# define a function +# functions have positional parameters, named parameters, and default arguments +local my_function(x, y, z=1) = x + y - z; +local num6 = my_function(7, 8, 9); +local num7 = my_function(8, z=10, y=9); +local num8 = my_function(4, 5); +# inline anonymous function +local num9 = (function(x) x * x)(3); + +local obj5 = { +  # define a method +  # fields defined with :: are hidden, which does not apper in generated JSON +  # function cannot be serialized so need to be hidden +  # if the object is used in the generated JSON. +  is_odd(x):: x % 2 == 1, +}; +assert obj5 == {}; + +# a jsonnet doucment have to evaluate to something +# be it an object, list, number or just string literal +"FIN" + +``` + +## Further Reading +There are a few but important concepts that are not touched in this exmaple, including: + +- Passing variables from command line: [Parameterize Entire Config](https://jsonnet.org/learning/tutorial.html#parameterize-entire-config) +- Import other jsonnet libraries/files: [Imports](https://jsonnet.org/learning/tutorial.html#imports) +- In depth example of OOP aspect of Jsonnet: [Object-Orientation](https://jsonnet.org/learning/tutorial.html#Object-Orientation) +- Useful standard library: [Stdlib](https://jsonnet.org/ref/stdlib.html) diff --git a/ko-kr/vim-kr.html.markdown b/ko-kr/vim-kr.html.markdown index cd0fa236..76063143 100644 --- a/ko-kr/vim-kr.html.markdown +++ b/ko-kr/vim-kr.html.markdown @@ -5,12 +5,13 @@ contributors:      - ["RadhikaG", "https://github.com/RadhikaG"]  translators:      - ["Wooseop Kim", "https://github.com/linterpreteur"] +    - ["Yeongjae Jang", "https://github.com/Liberatedwinner"]  filename: LearnVim-kr.txt  lang: ko-kr  ---  [Vim](http://www.vim.org) -(Vi IMproved)은 유닉스의 인기 있는 vi 에디터의 클론입니다. Vim은 속도와 생산성을 위해 +(Vi IMproved)은 유닉스에서 인기 있는 vi 에디터의 클론입니다. Vim은 속도와 생산성을 위해  설계된 텍스트 에디터로, 대부분의 유닉스 기반 시스템에 내장되어 있습니다. 다양한 단축 키를 통해  파일 안에서 빠르게 이동하고 편집할 수 있습니다. @@ -18,19 +19,21 @@ lang: ko-kr  ```      vim <filename>   # vim으로 <filename> 열기 +    :help <topic>    # (존재하는 경우에) <topic>에 대한, 내장된 도움말 문서 열기      :q               # vim 종료      :w               # 현재 파일 저장      :wq              # 파일 저장 후 종료 +    ZZ               # 파일 저장 후 종료      :q!              # 저장하지 않고 종료                       # ! *강제로* :q를 실행하여, 저장 없이 종료 -    :x               # 파일 저장 후 종료 (짧은 :wq) +    :x               # 파일 저장 후 종료 (:wq의 축약)      u                # 동작 취소      CTRL+R           # 되돌리기      h                # 한 글자 왼쪽으로 이동 -    j                # 아래로 한 줄 이동 -    k                # 위로 한 줄 이동 +    j                # 한 줄 아래로 이동 +    k                # 한 줄 위로 이동      l                # 한 글자 오른쪽으로 이동      # 줄 안에서의 이동 @@ -38,6 +41,11 @@ lang: ko-kr      0                # 줄 시작으로 이동      $                # 줄 끝으로 이동      ^                # 줄의 공백이 아닌 첫 문자로 이동 +     +    Ctrl+B           # 한 화면 뒤로 이동 +    Ctrl+F           # 한 화면 앞으로 이동 +    Ctrl+D           # 반 화면 앞으로 이동 +    Ctrl+U           # 반 화면 뒤로 이동      # 텍스트 검색 @@ -48,6 +56,8 @@ lang: ko-kr      :%s/foo/bar/g    # 파일 모든 줄에 있는 'foo'를 'bar'로 치환      :s/foo/bar/g     # 현재 줄에 있는 'foo'를 'bar'로 치환 +    :%s/foo/bar/gc   # 사용자에게 확인을 요구하는, 모든 줄에 있는 'foo'를 'bar'로 치환 +    :%s/\n/\r/g      # 한 종류의 개행 문자에서 다른 종류의 것으로 치환 (\n에서 \r로)      # 문자로 이동 @@ -74,14 +84,22 @@ lang: ko-kr      L                # 화면 바닥으로 이동  ``` +## 도움말 문서 + +Vim은 `:help <topic>` 명령을 통해 접근할 수 있는 도움말 문서를 내장하고 있습니다. +예를 들어, `:help navigation` 은 당신의 작업 공간을 탐색하는 방법에 대한 문서를 표시합니다! + +`:help`는 옵션 없이도 사용할 수 있습니다. 이는 기본 도움말 대화 상자를 표시합니다. +이 대화 상자는 Vim을 시작하는 것이 보다 용이하도록 도와줍니다. +  ## 모드  Vim은 **모드**의 개념에 기초를 두고 있습니다. -명령어 모드   - vim을 시작하면 처음에 이 모드입니다. 이동과 명령어 입력에 사용합니다. -삽입 모드     - 파일을 수정합니다. -비주얼 모드   - 텍스트를 하이라이트하고 그 텍스트에 대한 작업을 합니다. -실행 모드     - ':' 이후 명령어를 입력합니다. +- 명령어 모드   - vim은 이 모드로 시작됩니다. 이동과 명령어 입력에 사용합니다. +- 삽입 모드     - 파일을 수정합니다. +- 비주얼 모드   - 텍스트를 하이라이트하고 그 텍스트에 대한 작업을 합니다. +- 실행 모드     - ':' 이후 명령어를 입력합니다.  ```      i                # 커서 위치 앞에서 삽입 모드로 변경 @@ -97,11 +115,11 @@ Vim은 **모드**의 개념에 기초를 두고 있습니다.      d                # 선택한 객체 삭제      dd               # 현재 줄 삭제      p                # 커서 위치 뒤에 복사한 텍스트 붙여넣기 -    P                # 커서 위치 뒤에 복사한 텍스트 붙여넣기 +    P                # 커서 위치 앞에 복사한 텍스트 붙여넣기      x                # 현재 커서 위치의 문자 삭제  ``` -## vim의 문법 +## vim의 '문법'  Vim의 명령어는 '서술어-수식어-목적어'로 생각할 수 있습니다. @@ -134,7 +152,7 @@ Vim의 명령어는 '서술어-수식어-목적어'로 생각할 수 있습니      w                # 단어를      s                # 문장을      p                # 문단을 -    b                # 블락을 +    b                # 블록을      # 예시 '문장' (명령어) @@ -157,6 +175,22 @@ Vim의 명령어는 '서술어-수식어-목적어'로 생각할 수 있습니      ddp              # 이어지는 줄과 위치 맞바꾸기 (dd 후 p)      .                # 이전 동작 반복      :w !sudo tee %   # 현재 파일을 루트 권한으로 저장 +    :set syntax=c    # 문법 강조를 'C'의 것으로 설정 +    :sort            # 모든 줄을 정렬 +    :sort!           # 모든 줄을 역순으로 정렬 +    :sort u          # 모든 줄을 정렬하고, 중복되는 것을 삭제 +    ~                # 선택된 텍스트의 대/소문자 토글 +    u                # 선택된 텍스트를 소문자로 바꾸기 +    U                # 선택된 텍스트를 대문자로 바꾸기 +     +    # 텍스트 폴딩 +    zf               # 선택된 텍스트 위치에서 폴딩 만들기 +    zo               # 현재 폴딩 펴기 +    zc               # 현재 폴딩 접기 +    zR               # 모든 폴딩 펴기 +    zM               # 모든 폴딩 접기 +    zi               # 폴딩 접기/펴기 토글 +    zd               # 접은 폴딩 삭제  ```  ## 매크로 diff --git a/ldpl.html.markdown b/ldpl.html.markdown index cc95f5fb..86603d94 100644 --- a/ldpl.html.markdown +++ b/ldpl.html.markdown @@ -165,19 +165,6 @@ display myNumber crlf  exit  ``` -## Topics Not Covered - - * [Command line arguments](https://docs.ldpl-lang.org/variables-in-ldpl/command-line-arguments) - * [Error variables](https://docs.ldpl-lang.org/variables-in-ldpl/errorcode-and-errortext) - * [Import other files](https://docs.ldpl-lang.org/structure-of-ldpl-source-code/importing-other-sources) - * [Identifier naming schemes](https://docs.ldpl-lang.org/naming-rules) - * [Text Statements](https://docs.ldpl-lang.org/text-statements/join-and-in) - * [List Statements](https://docs.ldpl-lang.org/list-statements/push-to) - * [Map Statements](https://docs.ldpl-lang.org/vector-statements/clear) - * [File loading / writing](https://docs.ldpl-lang.org/i-o-statements/load-file-in) - * [Executing commands](https://docs.ldpl-lang.org/i-o-statements/execute) - * [Extending LDPL with C++](https://docs.ldpl-lang.org/extensions/c++-extensions) -  ## Further Reading   * [LDPL Docs](https://docs.ldpl-lang.org) diff --git a/matlab.html.markdown b/matlab.html.markdown index 5790bcc6..4ca31857 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -234,7 +234,7 @@ A'  % Concise version of complex transpose  % On their own, the arithmetic operators act on whole matrices. When preceded  % by a period, they act on each element instead. For example:  A * B % Matrix multiplication -A .* B % Multiple each element in A by its corresponding element in B +A .* B % Multiply each element in A by its corresponding element in B  % There are several pairs of functions, where one acts on each element, and  % the other (whose name ends in m) acts on the whole matrix. diff --git a/mips.html.markdown b/mips.html.markdown index 7f759bec..33d4f87c 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -209,7 +209,7 @@ gateways and routers.  ## LOOPS ##    _loops:      # The basic structure of loops is having an exit condition and a jump  -    instruction to continue its execution +    # instruction to continue its execution      li $t0, 0      while:        bgt $t0, 10, end_while                # While $t0 is less than 10,  diff --git a/moonscript.html.markdown b/moonscript.html.markdown index 941578e7..193d7f97 100644 --- a/moonscript.html.markdown +++ b/moonscript.html.markdown @@ -192,7 +192,7 @@ items = {1, 2, 3, 4}  doubled = [item * 2 for item in *items]  -- Uses `when` to determine if a value should be included. -slice = [item for item in *items when i > 1 and i < 3] +slice = [item for item in *items when item > 1 and item < 3]  -- `for` clauses inside of list comprehensions can be chained. diff --git a/nl-nl/json-nl.html.markdown b/nl-nl/json-nl.html.markdown index 906112ff..d243802d 100644 --- a/nl-nl/json-nl.html.markdown +++ b/nl-nl/json-nl.html.markdown @@ -5,26 +5,27 @@ contributors:    - ["Anna Harren", "https://github.com/iirelu"]    - ["Marco Scannadinari", "https://github.com/marcoms"]    - ["himanshu", "https://github.com/himanshu81494"] +  - ["Maarten Jacobs", "https://github.com/maartenJacobs"]  translators:    - ["Niels van Velzen", "https://nielsvanvelzen.me"]  lang: nl-nl  --- -Gezien JSON een zeer eenvouding formaat heeft zal dit een van de simpelste +Gezien JSON een zeer eenvouding formaat heeft zal dit één van de simpelste  Learn X in Y Minutes ooit zijn. -JSON heeft volgens de specificaties geen commentaar, ondanks dat hebben de +JSON heeft volgens de specificaties geen commentaar. Ondanks dat hebben de  meeste parsers support voor C-stijl (`//`, `/* */`) commentaar.  Sommige parsers staan zelfs trailing komma's toe. -(Een komma na het laatste element in een array of ahter de laatste eigenshap van een object). -Het is wel beter om dit soort dingen te vermijden omdat het niet overal zal werken. +(Een komma na het laatste element in een array of achter de laatste eigenschap van een object). +Het is wel beter om dit soort dingen te vermijden omdat het niet in elke parser zal werken.  In het voorbeeld zal alleen 100% geldige JSON gebruikt worden.  Data types gesupport door JSON zijn: nummers, strings, booleans, arrays, objecten en null.  Gesupporte browsers zijn: Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4. -De extensie voor JSON bestanden is ".json". De MIME type is "application/json" -Enkele nadelen van JSON zijn het gebrek een type definities en een manier van DTD. +De extensie voor JSON bestanden is ".json". De MIME type is "application/json". +Enkele nadelen van JSON zijn het gebrek aan type definities en een manier van DTD.  ```json  { diff --git a/p5.html.markdown b/p5.html.markdown index be22d3e5..f6084b98 100644 --- a/p5.html.markdown +++ b/p5.html.markdown @@ -7,7 +7,7 @@ contributors:  filename: p5.js  --- -p5.js is a JavaScript library that starts with the original goal of [Processing](http://processing.org"), to make coding accessible for artists, designers, educators, and beginners, and reinterprets this for today's web. +p5.js is a JavaScript library that starts with the original goal of [Processing](https://processing.org), to make coding accessible for artists, designers, educators, and beginners, and reinterprets this for today's web.  Since p5 is a JavaScript library, you should learn [Javascript](https://learnxinyminutes.com/docs/javascript/) first.  ```js diff --git a/php.html.markdown b/php.html.markdown index d4103e97..e1411085 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -41,12 +41,15 @@ Hello World Again!   */  // Variables begin with the $ symbol. -// A valid variable name starts with a letter or underscore, +// A valid variable name starts with a letter or an underscore,  // followed by any number of letters, numbers, or underscores. +// You don't have to (and cannot) declare variables. +// Once you assign a value, PHP will create the variable with the right type. +  // Boolean values are case-insensitive  $boolean = true;  // or TRUE or True -$boolean = false; // or FALSE or False +$boolean = FALSE; // or false or False  // Integers  $int1 = 12;   // => 12 diff --git a/powershell.html.markdown b/powershell.html.markdown index 5d74024d..6efd984c 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -55,6 +55,11 @@ The tutorial starts here:  ```powershell  # As you already figured, comments start with # +<# +  Multi-line comments +  like so +#> +  # Simple hello world example:  echo Hello world!  # echo is an alias for Write-Output (=cmdlet) @@ -68,6 +73,8 @@ $aString="Some string"  # Or like this:  $aNumber = 5 -as [double]  $aList = 1,2,3,4,5 +# Reverse an array *Note this is a mutation on the existing array +[array]::Reverse($aList)  $anEmptyList = @()  $aString = $aList -join '--' # yes, -split exists also  $aHashtable = @{name1='val1'; name2='val2'} @@ -100,6 +107,10 @@ echo "Bound arguments in a function, script or code block: $PSBoundParameters"  echo "Unbound arguments: $($Args -join ', ')."  # More builtins: `help about_Automatic_Variables` +# Find the datatype of variables or properties you're working with +$true.GetType() +$aHashtable.name2.GetType() +  # Inline another file (dot operator)  . .\otherScriptName.ps1 @@ -184,7 +195,7 @@ Get-Process | Sort-Object ID -Descending | Select-Object -First 10 Name,ID,VM `  Get-EventLog Application -After (Get-Date).AddHours(-2) | Format-List  # Use % as a shorthand for ForEach-Object -(a,b,c) | ForEach-Object ` +('a','b','c') | ForEach-Object `  	-Begin { "Starting"; $counter = 0 } `  	-Process { "Processing $_"; $counter++ } `  	-End { "Finishing: $counter" } @@ -198,12 +209,13 @@ ps | Format-Table ID,Name,@{n='VM(MB)';e={'{0:n2}' -f ($_.VM / 1MB)}} -autoSize  ### Functions  # The [string] attribute is optional. -function foo([string]$name) { +# Function names should follow Verb-Noun convention +function Get-Foo([string]$name) {  	echo "Hey $name, have a function"  }  # Calling your function -foo "Say my name" +Get-Foo "Say my name"  # Functions with named parameters, parameter attributes, parsable documentation  <# @@ -283,7 +295,22 @@ Pop-Location # change back to previous working directory  # Unblock a directory after download  Get-ChildItem -Recurse | Unblock-File +# You can also pass arguments to a Function with a hash table +# This is called Splatting +# Normal Command +Export-Csv -InputObject $csv -Path 'c:\mypath' -Encoding UTF8 -NoTypeInformation +# With Splatting +$csvArguments = @{ +    InputObject = $csv +    Path = 'c:\mypath' +    Encoding = 'UTF8' +    NoTypeInformation = $true +} +Export-Csv @csvArguments +  # Open Windows Explorer in working directory +Invoke-Item . +# Or the alias  ii .  # Any key to exit @@ -318,6 +345,7 @@ Interesting Projects  * [PSGet](https://github.com/psget/psget) NuGet for PowerShell  * [PSReadLine](https://github.com/lzybkr/PSReadLine/) A bash inspired readline implementation for PowerShell (So good that it now ships with Windows10 by default!)  * [Posh-Git](https://github.com/dahlbyk/posh-git/) Fancy Git Prompt (Recommended!) +* [Oh-My-Posh](https://github.com/JanDeDobbeleer/oh-my-posh) Shell customization similar to the popular Oh-My-Zsh on Mac  * [PSake](https://github.com/psake/psake) Build automation tool  * [Pester](https://github.com/pester/Pester) BDD Testing Framework  * [Jump-Location](https://github.com/tkellogg/Jump-Location) Powershell `cd` that reads your mind diff --git a/python.html.markdown b/python.html.markdown index 56cb9aac..ec89b53b 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -132,7 +132,7 @@ b == a            # => True, a's and b's objects are equal  "Hello " "world!"    # => "Hello world!"  # A string can be treated like a list of characters -"This is a string"[0]  # => 'T' +"Hello world!"[0]  # => 'H'  # You can find the length of a string  len("This is a string")  # => 16 @@ -1040,3 +1040,5 @@ print(say(say_please=True))  # Can you buy me a beer? Please! I am poor :(  * [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/)  * [Dive Into Python 3](http://www.diveintopython3.net/index.html)  * [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) +* [Python Tutorial for Intermediates](https://pythonbasics.org/) +* [Build a Desktop App with Python](https://pythonpyqt.com/) diff --git a/raku.html.markdown b/raku.html.markdown index 2460ac7e..8a30427a 100644 --- a/raku.html.markdown +++ b/raku.html.markdown @@ -15,7 +15,7 @@ the JVM and the [MoarVM](http://moarvm.com).  Meta-note: -* Although the  pound sign (`#`) is used for sentences and notes, Pod-styled +* Although the pound sign (`#`) is used for sentences and notes, Pod-styled    comments (more below about them) are used whenever it's convenient.  * `# OUTPUT:` is used to represent the output of a command to any standard     stream. If the output has a newline, it's represented by the `` symbol. @@ -265,7 +265,7 @@ takes-a-bool('config', :bool);  # OUTPUT: «config takes True»  takes-a-bool('config', :!bool); # OUTPUT: «config takes False»  =begin comment -Since paranthesis can be omitted when calling a subroutine, you need to use +Since parenthesis can be omitted when calling a subroutine, you need to use  `&` in order to distinguish between a call to a sub with no arguments and   the code object.  @@ -614,8 +614,8 @@ say Int === Int;       # OUTPUT: «True»  # Here are some common comparison semantics:  # String or numeric equality -say 'Foo' ~~ 'Foo'; # OUTPU: «True», if strings are equal. -say 12.5 ~~ 12.50;  # OUTPU: «True», if numbers are equal. +say 'Foo' ~~ 'Foo'; # OUTPUT: «True», if strings are equal. +say 12.5 ~~ 12.50;  # OUTPUT: «True», if numbers are equal.  # Regex - For matching a regular expression against the left side.  # Returns a `Match` object, which evaluates as True if regexp matches. @@ -624,7 +624,7 @@ say $obj;       # OUTPUT: «「a」»  say $obj.WHAT;  # OUTPUT: «(Match)»  # Hashes -say 'key' ~~ %hash; # OUTPUT:«True», if key exists in hash. +say 'key' ~~ %hash; # OUTPUT: «True», if key exists in hash.  # Type - Checks if left side "is of type" (can check superclasses and roles).  say 1 ~~ Int;       # OUTPUT: «True» @@ -862,7 +862,7 @@ Both pointy blocks and blocks are pretty much the same thing, except that  the former can take arguments, and that the latter can be mistaken as  a hash by the parser. That being said, blocks can declare what's known   as placeholders parameters through the twigils `$^` (for positional -parameters) and `$:` (for named parameters). More on them latern on. +parameters) and `$:` (for named parameters). More on them later on.  =end comment  my &mult = { $^numbers * $:times } @@ -1558,9 +1558,9 @@ END  { say "Runs at run time, as late as possible, only once" }  #  # 14.3 Block phasers  # -ENTER { say "[*] Runs everytime you enter a block, repeats on loop blocks" } +ENTER { say "[*] Runs every time you enter a block, repeats on loop blocks" }  LEAVE { -    say "Runs everytime you leave a block, even when an exception +    say "Runs every time you leave a block, even when an exception      happened. Repeats on loop blocks."  } @@ -1619,9 +1619,9 @@ say "This code took " ~ (time - CHECK time) ~ "s to compile";  # ... or clever organization:  class DB { -    method start-transaction { say "Starting transation!" } -    method commit            { say "Commiting transaction..." } -    method rollback          { say "Something went wrong. Rollingback!" } +    method start-transaction { say "Starting transaction!" } +    method commit            { say "Committing transaction..." } +    method rollback          { say "Something went wrong. Rolling back!" }  }  sub do-db-stuff { @@ -2078,19 +2078,19 @@ say so 'abc' ~~ / a  b+  c /;    # OUTPUT: «True», one is enough  say so 'abbbbc' ~~ / a  b+  c /; # OUTPUT: «True», matched 4 "b"s  # `*` - zero or more matches -say so 'ac' ~~ / a  b*  c /;     # OUTPU: «True», they're all optional -say so 'abc' ~~ / a  b*  c /;    # OUTPU: «True» -say so 'abbbbc' ~~ / a  b*  c /; # OUTPU: «True» -say so 'aec' ~~ / a  b*  c /;    # OUTPU: «False», "b"(s) are optional, not replaceable. +say so 'ac' ~~ / a  b*  c /;     # OUTPUT: «True», they're all optional +say so 'abc' ~~ / a  b*  c /;    # OUTPUT: «True» +say so 'abbbbc' ~~ / a  b*  c /; # OUTPUT: «True» +say so 'aec' ~~ / a  b*  c /;    # OUTPUT: «False», "b"(s) are optional, not replaceable.  # `**` - (Unbound) Quantifier  # If you squint hard enough, you might understand why exponentation is used  # for quantity. -say so 'abc' ~~ / a  b**1  c /;         # OUTPU: «True», exactly one time -say so 'abc' ~~ / a  b**1..3  c /;      # OUTPU: «True», one to three times -say so 'abbbc' ~~ / a  b**1..3  c /;    # OUTPU: «True» -say so 'abbbbbbc' ~~ / a  b**1..3  c /; # OUTPU: «Fals», too much -say so 'abbbbbbc' ~~ / a  b**3..*  c /; # OUTPU: «True», infinite ranges are ok +say so 'abc' ~~ / a  b**1  c /;         # OUTPUT: «True», exactly one time +say so 'abc' ~~ / a  b**1..3  c /;      # OUTPUT: «True», one to three times +say so 'abbbc' ~~ / a  b**1..3  c /;    # OUTPUT: «True» +say so 'abbbbbbc' ~~ / a  b**1..3  c /; # OUTPUT: «Fals», too much +say so 'abbbbbbc' ~~ / a  b**3..*  c /; # OUTPUT: «True», infinite ranges are ok  #  # 18.2 `<[]>` - Character classes @@ -2202,8 +2202,8 @@ say $/[0].list.perl; # OUTPUT: «(Match.new(...),).list»  # Alternation - the `or` of regexes  # WARNING: They are DIFFERENT from PCRE regexps. -say so 'abc' ~~ / a [ b | y ] c /; # OUTPU: «True», Either "b" or "y". -say so 'ayc' ~~ / a [ b | y ] c /; # OUTPU: «True», Obviously enough... +say so 'abc' ~~ / a [ b | y ] c /; # OUTPUT: «True», Either "b" or "y". +say so 'ayc' ~~ / a [ b | y ] c /; # OUTPUT: «True», Obviously enough...  # The difference between this `|` and the one you're used to is  # LTM ("Longest Token Matching") strategy. This means that the engine will @@ -2218,7 +2218,7 @@ To decide which part is the "longest", it first splits the regex in two parts:      yet introduced), literals, characters classes and quantifiers.      * The "procedural part" includes everything else: back-references, -    code assertions, and other things that can't traditionnaly be represented +    code assertions, and other things that can't traditionally be represented      by normal regexps.  Then, all the alternatives are tried at once, and the longest wins. diff --git a/rst.html.markdown b/rst.html.markdown index 2423622e..bdc73c7a 100644 --- a/rst.html.markdown +++ b/rst.html.markdown @@ -49,9 +49,11 @@ Subtitles with dashes  You can put text in *italic* or in **bold**, you can "mark" text as code with double backquote ``print()``. +Special characters can be escaped using a backslash, e.g. \\ or \*. +  Lists are similar to Markdown, but a little more involved. -Remember to line up list symbols (like - or *) with the left edge of the previous text block, and remember to use blank lines to separate new lists from parent lists:     +Remember to line up list symbols (like - or \*) with the left edge of the previous text block, and remember to use blank lines to separate new lists from parent lists:      - First item  - Second item @@ -86,7 +88,7 @@ There are multiple ways to make links:  - By typing a full comprehensible URL : https://github.com/ (will be automatically converted to a link)  - By making a more Markdown-like link: `Github <https://github.com/>`_ . -.. _Github https://github.com/ +.. _Github: https://github.com/  ``` diff --git a/ru-ru/pascal-ru.html.markdown b/ru-ru/pascal-ru.html.markdown new file mode 100644 index 00000000..8a41918f --- /dev/null +++ b/ru-ru/pascal-ru.html.markdown @@ -0,0 +1,216 @@ +--- +language: Pascal +filename: learnpascal-ru.pas +contributors: +    - ["Ganesha Danu", "http://github.com/blinfoldking"] +    - ["Keith Miyake", "https://github.com/kaymmm"] +translators: +    - ["Anton 'Dart' Nikolaev", "https://github.com/dartfnm"] +--- + + +>Pascal - это процедурный язык программирования, который Никлаус Вирт разработал в 1968–69 годах и опубликовал в 1970 году как небольшой эффективный язык, предназначенный для поощрения хороших методов программирования с использованием структурированного программирования и структурирования данных. Он назван в честь французского математика, философа и физика Блеза Паскаля. +> +>source : [wikipedia](https://ru.wikipedia.org/wiki/Паскаль_(язык_программирования))) + + + +Для компиляции и запуска программы на языке Паскаль вы можете использовать бесплатный компилятор FreePascal. [Скачать здесь](https://www.freepascal.org/)  + +Либо современный бесплатный компилятор Паскаля нового поколения под платформу .Net [PascalABC.NET](http://pascalabc.net) + +```pascal +// это комментарий +{ +    а вот это:   +    - комментарий на несколько строк +} + +//объявляем имя программы +program learn_pascal; //<-- не забываем ставить точку с запятой (;) + +const +    { +        это секция в которой вы должны объявлять константы +    } +type +    { +    	здесь вы можете объявлять собственные типы данных +    } +var +    { +        секция для объявления переменных +    } + +begin //начало основной программы +    { +        тело вашей программы +    } +end. // В конце основной программы обязательно должна стоять точка "." +``` + +```pascal +//объявление переменных +//вы можете сделать так +var a:integer; +var b:integer; +//или так +var  +    a : integer; +    b : integer; +//или даже так +var a,b : integer; +``` + +```pascal +program Learn_More; + +// Познакомимся с типами данных и с их операциями +const +    PI = 3.141592654; +    GNU = 'GNU''s Not Unix'; +        // имена константам принято давать ЗАГЛАВНЫМИ_БУКВАМИ (в верхнем регистре) +        // их значения фиксированны т.е никогда не меняются во время выполнения программы +        // содержат любой стандартный тип данных (integer, real, boolean, char, string) + +type +    ch_array : array [0..255] of char; +        // массивы - это составной тип данных +        // мы указываем индекс первого и последнего элемента массива ([0..255]) +        // здесь мы объявили новый тип данных содержащий 255 символов 'char' +        // (по сути, это просто строка - string[256]) +         +    md_array : array of array of integer; +        // массив в массиве - по сути является двумерным массивом +        // можно задать массив нулевой (0) длины, а потом динамически расширить его +        // это двумерный массив целых чисел + +//Объявление переменных +var +    int, c, d  : integer; +           // три переменные, которые содержат целые числа +           // Тип "integer" это 16-битное число в диапазоне [-32,768..32,767] +    r    : real; +           // переменная типа "real" принимает вещественные (дробные) значения +           // в диапазоне [3.4E-38..3.4E38] +    bool : boolean; +           // переменная логического типа, принимающая булевы-значения: True/False (Правда/Ложь) +    ch   : char; +           // эта переменная содержит значение кода одного символа +           // тип 'char' это 8-битное число (1 байт), так что никакого Юникода +    str  : string; +           // это переменная составного типа, являющееся строкой +           // по сути, строка это массив в 255 символов длиною, по умолчанию +           +    s    : string[50]; +           // эта строка может содержать максимум 50 символов +           // вы можете сами указать длину строки, чтобы минимизировать использование памяти +    my_str: ch_array; +           // вы можете объявлять переменные собственных типов +    my_2d : md_array; +           // динамически расширяемые массивы требуют указания длины перед их использованием. + +    // дополнительные целочисленные типы данных +    b    : byte;     // диапазон [0..255] +    shi  : shortint; // диапазон [-128..127] +    smi  : smallint; // диапазон [-32,768..32,767] (стандартный Integer) +    w    : word;     // диапазон [0..65,535] +    li   : longint;  // диапазон [-2,147,483,648..2,147,483,647] +    lw   : longword; // диапазон [0..4,294,967,295] +    c    : cardinal; // тоже что и longword +    i64  : int64;    // диапазон [-9223372036854775808..9223372036854775807] +    qw   : qword;    // диапазон [0..18,446,744,073,709,551,615] + +    // дополнительные вещественные типы данных (дробные) +    rr   : real;     // диапазон зависит от платформы (т.е. 8-бит, 16-бит и т.д.) +    rs   : single;   // диапазон [1.5E-45..3.4E38] +    rd   : double;   // диапазон [5.0E-324 .. 1.7E308] +    re   : extended; // диапазон [1.9E-4932..1.1E4932] +    rc   : comp;     // диапазон [-2E64+1 .. 2E63-1] + +Begin +    int := 1; // так мы присваиваем значение переменной +    r   := 3.14; +    ch  := 'a'; +    str := 'apple'; +    bool := true; +    // Паскаль не чувствителен к регистру +     +    // арифметические операции +    int := 1 + 1; // int = 2; заменяет предыдущее значение +    int := int + 1; // int = 2 + 1 = 3; +    int := 4 div 2; //int = 2; 'div' операция деления, с отбрасыванием дробной части +    int := 3 div 2; //int = 1; +    int := 1 div 2; //int = 0; + +    bool := true or false; // bool = true +    bool := false and true; // bool = false +    bool := true xor true; // bool = false + +    r := 3 / 2; // деления вещественных чисел с дробной частью +    r := int; // вещественной переменной можно присвоить целочисленное значение, но не наоборот + +    my_str[0] := 'a'; // для доступа к элементу массива нужно указать его индекс в квадратных скобках ([0]) + +    c := str[1]; // первая буква во всех Строках находится по индексу [1] +    str := 'hello' + 'world'; //объединяем 2 строки в одну +	 +    SetLength(my_2d,10,10); // инициализируем динамически расширяемый массив +                            // задаём размер 2х-мерного массива 10×10  +     +    // первый элемент массива лежит в индексе [0], последний [длина_массива-1] +    for c := 0 to 9 do +        for d := 0 to 9 do // переменные для счетчиков циклов должны быть объявлены +        my_2d[c,d] := c * d; +          // обращаться к многомерным массивам нужно с помощью одного набора скобок + +End. +``` + +```pascal +program Functional_Programming; + +Var +    i, dummy : integer; + +function factorial_recursion(const a: integer) : integer; +{ Функция расчёта Факториала целочисленного параметра 'a', рекурсивно. Возвращает целое значение } + +// Мы можем объявлять локальные переменные внутри своей функции: +// Var +//    local_a : integer; + +Begin +    If a >= 1 Then +        factorial_recursion := a * factorial_recursion(a-1) +        // возвращаем результат, присваивая найденное значение переменной с тем же именем, как у функции +    Else +        factorial_recursion := 1; +End; // Для завершения функции, используется символ ";" после оператора "End;" + + + +procedure get_integer( var i : integer; dummy : integer ); +{   Эта процедура ждёт от пользователя ввода целого числа и возвращает его значение через параметр i. +    Если параметр функции начинается с 'var', это означает, что его значение было передано, по ссылке, то есть, оно может использоваться не только как входное значение, но и для возвращения дополнительных результатов работы функции. +    Параметры функции (без 'var'), (такие как "dummy" (пустышка)), передаются по значению, и по сути являются - локальными переменными, таким образом изменения, внесенные внутри функции/процедуры, не влияют на значение переменной за её пределами. +} +Begin // начало процедуры +    write('Введите целое число: '); +    readln(i); // число, введённое пользователем, сохранится в переменной i +               // и её значение будет доступно вызывающей подпрограмме +     +    dummy := 4; // значение 'dummy' не будет влиять на значения переменной вне процедуры +End; // конец процедуры + +Begin // главный блок программы +    dummy := 3; +    get_integer(i, dummy); // вызываем процедуру получения числа от пользователя     +    writeln(i, '! = ', factorial_recursion(i)); // ввыводим значение факториала от i +     +    writeln('dummy = ', dummy);  +    // всегда выводит "3", поскольку фиктивная переменная не изменяется. +End. // конец программы + +``` + diff --git a/ruby.html.markdown b/ruby.html.markdown index 376f4a47..d21c727f 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -430,6 +430,16 @@ def guests(*array)    array.each { |guest| puts guest }  end +# There is also the shorthand block syntax. It's most useful when you need +# to call a simple method on all array items. +upcased = ['Watch', 'these', 'words', 'get', 'upcased'].map(&:upcase) +puts upcased +#=> ["WATCH", "THESE", "WORDS", "GET", "UPCASED"] +  +sum = [1, 2, 3, 4, 5].reduce(&:+) +puts sum +#=> 15 +  # Destructuring  # Ruby will automatically destructure arrays on assignment to multiple variables. diff --git a/set-theory.html.markdown b/set-theory.html.markdown new file mode 100644 index 00000000..c6bc39c5 --- /dev/null +++ b/set-theory.html.markdown @@ -0,0 +1,162 @@ +--- +category: Algorithms & Data Structures +name: Set theory +contributors: +--- +The set theory is a study for sets, their operations, and their properties. It is the basis of the whole mathematical system. + +* A set is a collection of definite distinct items. + +## Basic operators +These operators don't require a lot of text to describe. + +* `∨` means or. +* `∧` means and. +* `,` separates the filters that determine the items in the set. + +## A brief history of the set theory +### Naive set theory +* Cantor invented the naive set theory. +* It has lots of paradoxes and initiated the third mathematical crisis. + +### Axiomatic set theory +* It uses axioms to define the set theory. +* It prevents paradoxes from happening. + +## Built-in sets +* `∅`, the set of no items. +* `N`, the set of all natural numbers. `{0,1,2,3,…}` +* `Z`, the set of all integers. `{…,-2,-1,0,1,2,…}` +* `Q`, the set of all rational numbers. +* `R`, the set of all real numbers. + +### The empty set +* The set containing no items is called the empty set. Representation: `∅` +* The empty set can be described as `∅ = {x|x ≠ x}` +* The empty set is always unique. +* The empty set is the subset of all sets. + +``` +A = {x|x∈N,x < 0} +A = ∅ +∅ = {}              (Sometimes) + +|∅|   = 0 +|{∅}| = 1 +``` + +## Representing sets +### Enumeration +* List all items of the set, e.g. `A = {a,b,c,d}` +* List some of the items of the set. Ignored items are represented with `…`. E.g. `B = {2,4,6,8,10,…}` + +### Description +* Describes the features of all items in the set. Syntax: `{body|condtion}` + +``` +A = {x|x is a vowel} +B = {x|x ∈ N, x < 10l} +C = {x|x = 2k, k ∈ N} +C = {2x|x ∈ N} +``` + +## Relations between sets +### Belongs to +* If the value `a` is one of the items of the set `A`, `a` belongs to `A`. Representation: `a∈A` +* If the value `a` is not one of the items of the set `A`, `a` does not belong to `A`. Representation: `a∉A` + +### Equals +* If all items in a set are exactly the same to another set, they are equal. Representation: `a=b` +* Items in a set are not order sensitive. `{1,2,3,4}={2,3,1,4}` +* Items in a set are unique. `{1,2,2,3,4,3,4,2}={1,2,3,4}` +* Two sets are equal if and only if all of their items are exactly equal to each other. Representation: `A=B`. Otherwise, they are not equal. Representation: `A≠B`. +* `A=B` if `A ⊆ B` and `B ⊆ A` + +### Belongs to +* If the set A contains an item `x`, `x` belongs to A (`x∈A`). +* Otherwise, `x` does not belong to A (`x∉A`). + +### Subsets +* If all items in a set `B` are items of set `A`, we say that `B` is a subset of `A` (`B⊆A`). +* If B is not a subset of A, the representation is `B⊈A`. + +### Proper subsets +* If `B ⊆ A` and `B ≠ A`, B is a proper subset of A (`B ⊂ A`). Otherwise, B is not a proper subset of A (`B ⊄ A`). + +## Set operations +### Base number +* The number of items in a set is called the base number of that set. Representation: `|A|` +* If the base number of the set is finite, this set is a finite set. +* If the base number of the set is infinite, this set is an infinite set. + +``` +A   = {A,B,C} +|A| = 3 +B   = {a,{b,c}} +|B| = 2 +|∅| = 0         (it has no items) +``` + +### Powerset +* Let `A` be any set. The set that contains all possible subsets of `A` is called a powerset (written as `P(A)`). + +``` +P(A) = {x|x ⊆ A} + +|A| = N, |P(A)| = 2^N +``` + +## Set operations among two sets +### Union +Given two sets `A` and `B`, the union of the two sets are the items that appear in either `A` or `B`, written as `A ∪ B`. + +``` +A ∪ B = {x|x∈A∨x∈B} +``` + +### Intersection +Given two sets `A` and `B`, the intersection of the two sets are the items that appear in both `A` and `B`, written as `A ∩ B`. + +``` +A ∩ B = {x|x∈A,x∈B} +``` + +### Difference +Given two sets `A` and `B`, the set difference of `A` with `B` is every item in `A` that does not belong to `B`. + +``` +A \ B = {x|x∈A,x∉B} +``` + +### Symmetrical difference +Given two sets `A` and `B`, the symmetrical difference is all items among `A` and `B` that doesn't appear in their intersections. + +``` +A △ B = {x|(x∈A∧x∉B)∨(x∈B∧x∉A)} + +A △ B = (A \ B) ∪ (B \ A) +``` + +### Cartesian product +Given two sets `A` and `B`, the cartesian product between `A` and `B` consists of a set containing all combinations of items of `A` and `B`. + +``` +A × B = { {x, y} | x ∈ A, y ∈ B } +``` + +## "Generalized" operations +### General union +Better known as "flattening" of a set of sets. + +``` +∪A = {x|X∈A,x∈X} +∪A={a,b,c,d,e,f} +∪B={a} +∪C=a∪{c,d} +``` + +### General intersection + +``` +∩ A = A1 ∩ A2 ∩ … ∩ An +``` diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index d6d369cc..58dccae4 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -388,7 +388,7 @@ y := $A max: $B.  ```smalltalk  | b x y |  x := #Hello.                                      "symbol assignment" -y := 'String', 'Concatenation'.                   "symbol concatenation (result is string)" +y := #Symbol, #Concatenation.                     "symbol concatenation (result is string)"  b := x isEmpty.                                   "test if symbol is empty"  y := x size.                                      "string size"  y := x at: 2.                                     "char at location" diff --git a/vim.html.markdown b/vim.html.markdown index 5b84a3ea..27d90f18 100644 --- a/vim.html.markdown +++ b/vim.html.markdown @@ -24,6 +24,7 @@ specific points in the file, and for fast editing.      ZZ               # Save file and quit vim      :q!              # Quit vim without saving file                       # ! *forces* :q to execute, hence quiting vim without saving +    ZQ               # Quit vim without saving file      :x               # Save file and quit vim, shorter version of :wq      u                # Undo @@ -181,6 +182,7 @@ A few important examples of 'Verbs', 'Modifiers', and 'Nouns':      ~                # Toggle letter case of selected text      u                # Selected text to lower case      U                # Selected text to upper case +    J                # Join the current line with the next line      # Fold text      zf               # Create fold from selected text  | 
