summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--.gitignore16
-rw-r--r--csharp.html.markdown9
-rw-r--r--css.html.markdown57
-rw-r--r--de-de/bash-de.html.markdown4
-rw-r--r--de-de/d-de.html.markdown250
-rw-r--r--de-de/haskell-de.html.markdown14
-rw-r--r--es-es/forth-es.html.markdown2
-rw-r--r--es-es/python-es.html.markdown14
-rw-r--r--forth.html.markdown2
-rw-r--r--fsharp.html.markdown8
-rw-r--r--id-id/json-id.html.markdown5
-rw-r--r--kotlin.html.markdown2
-rw-r--r--markdown.html.markdown18
-rw-r--r--nl-nl/coffeescript-nl.html.markdown11
-rw-r--r--nl-nl/typescript-nl.html.markdown174
-rw-r--r--paren.html.markdown15
-rw-r--r--pt-br/java-pt.html.markdown44
-rw-r--r--python.html.markdown31
-rw-r--r--pythonstatcomp.html.markdown4
-rw-r--r--ru-ru/markdown-ru.html.markdown300
-rw-r--r--vi-vn/objective-c-vi.html.markdown2
-rw-r--r--zh-cn/swift-cn.html.markdown43
-rw-r--r--zh-cn/typescript-cn.html.markdown173
23 files changed, 956 insertions, 242 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..dd41ec4a
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,16 @@
+**/*~
+**/*#
+**/#*#
+**/*.swp
+**/*.swo
+**/*.bak
+**/*.log*
+**/*.sublime-workspace
+**/.DS_Store
+**/.DS_Store?
+**/._*
+**/.Spotlight-V100
+**/.Trashes
+**/ehthumbs.db
+**/Thumbs.db
+**/desktop.ini \ No newline at end of file
diff --git a/csharp.html.markdown b/csharp.html.markdown
index 197f43e7..7be34fb9 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -694,7 +694,10 @@ on a new line! ""Wow!"", the masses cried";
public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type
// Decorate an enum with the FlagsAttribute to indicate that multiple values can be switched on
- [Flags] // Any class derived from Attribute can be used to decorate types, methods, parameters etc
+ // Any class derived from Attribute can be used to decorate types, methods, parameters etc
+ // Bitwise operators & and | can be used to perform and/or operations
+
+ [Flags]
public enum BikeAccessories
{
None = 0,
@@ -881,8 +884,8 @@ on a new line! ""Wow!"", the masses cried";
bool Broken { get; } // interfaces can contain properties as well as methods & events
}
- // Class can inherit only one other class, but can implement any amount of interfaces, however
- // the base class name must be the first in the list and all interfaces follow
+ // Classes can inherit only one other class, but can implement any amount of interfaces,
+ // however the base class name must be the first in the list and all interfaces follow
class MountainBike : Bicycle, IJumpable, IBreakable
{
int damage = 0;
diff --git a/css.html.markdown b/css.html.markdown
index 8ee4f4b9..5dae06ca 100644
--- a/css.html.markdown
+++ b/css.html.markdown
@@ -7,16 +7,23 @@ contributors:
- ["Connor Shea", "https://github.com/connorshea"]
- ["Deepanshu Utkarsh", "https://github.com/duci9y"]
- ["Tyler Mumford", "https://tylermumford.com"]
+
filename: learncss.css
---
-Web pages are built with HTML, which specifies the content of a page. CSS (Cascading Style Sheets) is a separate language which specifies a page's **appearance**.
+Web pages are built with HTML, which specifies the content of a page.
+CSS (Cascading Style Sheets) is a separate language which specifies
+a page's **appearance**.
-CSS code is made of static *rules*. Each rule takes one or more *selectors* and gives specific *values* to a number of visual *properties*. Those properties are then applied to the page elements indicated by the selectors.
+CSS code is made of static *rules*. Each rule takes one or more *selectors* and
+gives specific *values* to a number of visual *properties*. Those properties are
+then applied to the page elements indicated by the selectors.
-This guide has been written with CSS 2 in mind, which is extended by the new features of CSS 3.
+This guide has been written with CSS 2 in mind, which is extended by the new
+features of CSS 3.
-**NOTE:** Because CSS produces visual results, in order to learn it, you need to try everything in a CSS playground like [dabblet](http://dabblet.com/).
+**NOTE:** Because CSS produces visual results, in order to learn it, you need to
+try everything in a CSS playground like [dabblet](http://dabblet.com/).
The main focus of this article is on the syntax and some general tips.
## Syntax
@@ -66,7 +73,7 @@ div { }
[otherAttr~='foo'] { }
[otherAttr~='bar'] { }
-/* or contains a value in a dash-separated list, ie, "-" (U+002D) */
+/* or contains a value in a dash-separated list, e.g., "-" (U+002D) */
[otherAttr|='en'] { font-size:smaller; }
@@ -113,7 +120,8 @@ selector:first-child {}
/* any element that is the last child of its parent */
selector:last-child {}
-/* Just like pseudo classes, pseudo elements allow you to style certain parts of a document */
+/* Just like pseudo classes, pseudo elements allow you to style certain parts of
+ a document */
/* matches a virtual first child of the selected element */
selector::before {}
@@ -132,9 +140,9 @@ selector::after {}
#################### */
selector {
-
+
/* Units of length can be absolute or relative. */
-
+
/* Relative units */
width: 50%; /* percentage of parent element width */
font-size: 2em; /* multiples of element's original font-size */
@@ -143,14 +151,14 @@ selector {
font-size: 2vh; /* or its height */
font-size: 2vmin; /* whichever of a vh or a vw is smaller */
font-size: 2vmax; /* or greater */
-
+
/* Absolute units */
width: 200px; /* pixels */
font-size: 20pt; /* points */
width: 5cm; /* centimeters */
min-width: 50mm; /* millimeters */
max-width: 5in; /* inches */
-
+
/* Colors */
color: #F6E; /* short hex format */
color: #FF66EE; /* long hex format */
@@ -161,10 +169,10 @@ selector {
color: transparent; /* equivalent to setting the alpha to 0 */
color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */
color: hsla(0, 100%, 50%, 0.3); /* as hsl percentages with alpha */
-
+
/* Images as backgrounds of elements */
background-image: url(/img-path/img.jpg); /* quotes inside url() optional */
-
+
/* Fonts */
font-family: Arial;
/* if the font family name has a space, it must be quoted */
@@ -195,7 +203,13 @@ Save a CSS stylesheet with the extension `.css`.
## Precedence or Cascade
-An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Rules with a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one.
+An element may be targeted by multiple selectors and may have a property set on
+it in more than once. In these cases, one of the rules takes precedence over
+others. Rules with a more specific selector take precedence over a less specific
+one, and a rule occurring later in the stylesheet overwrites a previous one
+(which also means that if two different linked stylesheets contain rules for an
+element and if the rules are of the same specificity, then order of linking
+would take precedence and the sheet linked latest would govern styling) .
This process is called cascading, hence the name Cascading Style Sheets.
@@ -224,18 +238,25 @@ and the following markup:
<p style='/*F*/ property:value;' class='class1 class2' attr='value' />
```
-The precedence of style is as follows. Remember, the precedence is for each **property**, not for the entire block.
+The precedence of style is as follows. Remember, the precedence is for each
+**property**, not for the entire block.
-* `E` has the highest precedence because of the keyword `!important`. It is recommended that you avoid its usage.
+* `E` has the highest precedence because of the keyword `!important`. It is
+recommended that you avoid its usage.
* `F` is next, because it is an inline style.
-* `A` is next, because it is more "specific" than anything else. It has 3 specifiers: The name of the element `p`, its class `class1`, an attribute `attr='value'`.
-* `C` is next, even though it has the same specificity as `B`. This is because it appears after `B`.
+* `A` is next, because it is more "specific" than anything else. It has 3
+ specifiers: The name of the element `p`, its class `class1`, an attribute
+ `attr='value'`.
+* `C` is next, even though it has the same specificity as `B`.
+ This is because it appears after `B`.
* `B` is next.
* `D` is the last one.
## Compatibility
-Most of the features in CSS 2 (and many in CSS 3) are available across all browsers and devices. But it's always good practice to check before using a new feature.
+Most of the features in CSS 2 (and many in CSS 3) are available across all
+browsers and devices. But it's always good practice to check before using
+a new feature.
## Resources
diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown
index 541d28bb..654fcdd4 100644
--- a/de-de/bash-de.html.markdown
+++ b/de-de/bash-de.html.markdown
@@ -92,12 +92,12 @@ echo "immer ausgeführt" || echo "Nur ausgeführt wenn der erste Befehl fehlschl
echo "immer ausgeführt" && echo "Nur ausgeführt wenn der erste Befehl Erfolg hat"
# Um && und || mit if statements zu verwenden, braucht man mehrfache Paare eckiger Klammern:
-if [ $NAME == "Steve" ] && [ $Alter -eq 15 ]
+if [ "$NAME" == "Steve" ] && [ "$Alter" -eq 15 ]
then
echo "Wird ausgeführt wenn $NAME gleich 'Steve' UND $Alter gleich 15."
fi
-if [ $Name == "Daniya" ] || [ $Name == "Zach" ]
+if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ]
then
echo "Wird ausgeführt wenn $NAME gleich 'Daniya' ODER $NAME gleich 'Zach'."
fi
diff --git a/de-de/d-de.html.markdown b/de-de/d-de.html.markdown
new file mode 100644
index 00000000..ae036d70
--- /dev/null
+++ b/de-de/d-de.html.markdown
@@ -0,0 +1,250 @@
+---
+language: D
+filename: learnd-de.d
+contributors:
+ - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"]
+translators:
+ - ["Dominik Süß", "www.thesuess.me"]
+lang: de-de
+---
+
+```c
+// Es war klar dass das kommt...
+module hello;
+
+import std.stdio;
+
+// argumente sind optional
+void main(string[] args) {
+ writeln("Hello, World!");
+}
+```
+
+Wenn du so wie ich bist und viel zeit im Internet verbringst stehen die Chancen gut
+das du schonmal über [D](http://dlang.org/) gehört hast.
+Die D-Sprache ist eine moderne, überall einsetzbare programmiersprache die von Low bis
+High Level verwendet werden kann und dabei viele Stile anbietet.
+
+D wird aktiv von Walter Bright und Andrei Alexandrescu entwickelt, zwei super schlaue,
+richtig coole leute. Da das jetzt alles aus dem weg ist - auf zu den Beispielen!
+
+```c
+import std.stdio;
+
+void main() {
+
+ // Logische Ausdrücke und Schleifen funktionieren wie erwartet
+ for(int i = 0; i < 10000; i++) {
+ writeln(i);
+ }
+
+ auto n = 1; // auto um den typ vom Compiler bestimmen zu lassen
+
+ // Zahlenliterale können _ verwenden für lesbarkeit
+ while(n < 10_000) {
+ n += n;
+ }
+
+ do {
+ n -= (n / 2);
+ } while(n > 0);
+
+ // For und while sind ja schön und gut aber D bevorzugt foreach
+ // .. erstellt eine spanne von zahlen, exklusive dem Ende
+ foreach(i; 1..1_000_000) {
+ if(n % 2 == 0)
+ writeln(i);
+ }
+
+ foreach_reverse(i; 1..int.max) {
+ if(n % 2 == 1) {
+ writeln(i);
+ } else {
+ writeln("No!");
+ }
+ }
+}
+```
+
+Neue Typen können mit `struct`, `class`, `union`, und `enum` definiert werden. Structs und unions
+werden as-value (koppiert) an methoden übergeben wogegen Klassen als Referenz übergeben werden.
+Templates können verwendet werden um alle typen zu parameterisieren.
+
+```c
+// Hier, T ist ein Type-Parameter, Er funktioniert wie Generics in C#/Java/C++
+struct LinkedList(T) {
+ T data = null;
+ LinkedList!(T)* next; // Das ! wird verwendet um T zu übergeben. (<T> in C#/Java/C++)
+}
+
+class BinTree(T) {
+ T data = null;
+
+ // Wenn es nur einen T parameter gibt können die Klammern um ihn weggelassen werden
+ BinTree!T left;
+ BinTree!T right;
+}
+
+enum Day {
+ Sunday,
+ Monday,
+ Tuesday,
+ Wednesday,
+ Thursday,
+ Friday,
+ Saturday,
+}
+
+// Aliase können verwendet werden um die Entwicklung zu erleichtern
+
+alias IntList = LinkedList!int;
+alias NumTree = BinTree!double;
+
+// Funktionen können genau so Templates beinhalten
+
+T max(T)(T a, T b) {
+ if(a < b)
+ return b;
+
+ return a;
+}
+
+// Steht ref vor einem Parameter wird sichergestellt das er als Referenz übergeben wird.
+// Selbst bei werten wird es immer eine Referenz sein.
+void swap(T)(ref T a, ref T b) {
+ auto temp = a;
+
+ a = b;
+ b = temp;
+}
+
+// Templates können ebenso werte parameterisieren.
+class Matrix(uint m, uint n, T = int) {
+ T[m] rows;
+ T[n] columns;
+}
+
+auto mat = new Matrix!(3, 3); // Standardmäßig ist T vom typ Integer
+
+```
+
+Wo wir schon bei Klassen sind - Wie wäre es mit Properties! Eine Property
+ist eine Funktion die wie ein Wert agiert. Das gibt uns viel klarere Syntax
+im Stil von `structure.x = 7` was gleichgültig wäre zu `structure.setX(7)`
+
+```c
+// Diese Klasse ist parameterisiert mit T, U
+
+class MyClass(T, U) {
+ T _data;
+ U _other;
+
+}
+
+// Ihre Getter und Setter Methoden sehen so aus
+class MyClass(T, U) {
+ T _data;
+ U _other;
+
+ // Konstruktoren heißen immer `this`
+ this(T t, U u) {
+ data = t;
+ other = u;
+ }
+
+ // getters
+ @property T data() {
+ return _data;
+ }
+
+ @property U other() {
+ return _other;
+ }
+
+ // setters
+ // @property kann genauso gut am ende der Methodensignatur stehen
+ void data(T t) @property {
+ _data = t;
+ }
+
+ void other(U u) @property {
+ _other = u;
+ }
+}
+// Und so kann man sie dann verwenden
+
+void main() {
+ auto mc = MyClass!(int, string);
+
+ mc.data = 7;
+ mc.other = "seven";
+
+ writeln(mc.data);
+ writeln(mc.other);
+}
+```
+
+Mit properties können wir sehr viel logik hinter unseren gettern
+und settern hinter einer schönen syntax verstecken
+
+Other object-oriented goodies at our disposal
+Andere Objektorientierte features sind beispielsweise
+`interface`s, `abstract class` und `override`.
+Vererbung funktioniert in D wie in Java:
+Erben von einer Klasse, so viele interfaces wie man will.
+
+Jetzt haben wir Objektorientierung in D gesehen aber schauen
+wir uns noch was anderes an.
+D bietet funktionale programmierung mit _first-class functions_
+puren funktionen und unveränderbare daten.
+Zusätzlich können viele funktionale Algorithmen wie z.B
+map, filter, reduce und friends im `std.algorithm` Modul gefunden werden!
+
+```c
+import std.algorithm : map, filter, reduce;
+import std.range : iota; // builds an end-exclusive range
+
+void main() {
+ // Wir wollen die summe aller quadratzahlen zwischen
+ // 1 und 100 ausgeben. Nichts leichter als das!
+
+ // Einfach eine lambda funktion als template parameter übergeben
+ // Es ist genau so gut möglich eine normale funktion hier zu übergeben
+ // Lambdas bieten sich hier aber an.
+ auto num = iota(1, 101).filter!(x => x % 2 == 0)
+ .map!(y => y ^^ 2)
+ .reduce!((a, b) => a + b);
+
+ writeln(num);
+}
+```
+
+Ist dir aufgefallen wie wir eine Haskell-Style pipeline gebaut haben
+um num zu berechnen?
+Das war möglich durch die Uniform Function Call Syntax.
+Mit UFCS können wir auswählen ob wir eine Funktion als Methode oder
+als freie Funktion aufrufen. Walters artikel dazu findet ihr
+[hier.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
+Kurzgesagt kann man Funktionen deren erster parameter vom typ A ist, als
+Methode auf A anwenden.
+
+Parrallel Computing ist eine Tolle sache, findest du nicht auch?
+
+```c
+import std.stdio;
+import std.parallelism : parallel;
+import std.math : sqrt;
+
+void main() {
+ // Wir wollen die Wurzel von jeder Zahl in unserem Array berechnen
+ // und dabei alle Kerne verwenden die wir zur verfügung haben
+ auto arr = new double[1_000_000];
+
+ // Wir verwenden den index und das element als referenz
+ // und rufen einfach parallel auf!
+ foreach(i, ref elem; parallel(arr)) {
+ ref = sqrt(i + 1.0);
+ }
+}
+
+```
diff --git a/de-de/haskell-de.html.markdown b/de-de/haskell-de.html.markdown
index d1a0008e..5d17ccc7 100644
--- a/de-de/haskell-de.html.markdown
+++ b/de-de/haskell-de.html.markdown
@@ -100,7 +100,7 @@ not False -- True
[1..] !! 999 -- 1000
-- Haskell evaluiert nun die ersten 1 - 1000 Elemente, aber der Rest der Liste
--- bleibt unangetastet. Haskell wird sie solange nicht weiterevalieren
+-- bleibt unangetastet. Haskell wird sie solange nicht weiterevaluieren
-- bis es muss.
-- Zwei Listen konkatenieren
@@ -115,7 +115,7 @@ tail [1..5] -- [2, 3, 4, 5]
init [1..5] -- [1, 2, 3, 4]
last [1..5] -- 5
--- list comprehensions | Listen erschaffen
+-- Listen erschaffen ("list comprehensions")
[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10]
-- Mit Bedingungen
@@ -179,7 +179,7 @@ myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7]
-- Fold (`inject` in einigen Sprachen)
-- Foldl1 bedeutet: fold von links nach rechts und nehme den ersten
--- Wert der Liste als Basiswert f[r den Akkumulator.
+-- Wert der Liste als Basiswert für den Akkumulator.
foldl1 (\acc x -> acc + x) [1..5] -- 15
----------------------------------------------------
@@ -201,7 +201,7 @@ foo 5 -- 15
-- Funktionskomposition
-- Die (.) Funktion verkettet Funktionen.
--- Zum Beispiel, die Funktion Foo nimmt ein Argument addiert 10 dazu und
+-- Zum Beispiel, die Funktion Foo nimmt ein Argument, addiert 10 dazu und
-- multipliziert dieses Ergebnis mit 4.
foo = (*4) . (+10)
@@ -212,7 +212,7 @@ foo 5 -- 60
-- Haskell hat einen Operator `$`, welcher Funktionsapplikation durchführt.
-- Im Gegenzug zu der Standard-Funktionsapplikation, welche linksassoziativ ist
-- und die höchstmögliche Priorität von "10" hat, ist der `$`-Operator
--- rechtsassoziativ und hat die Priorität 0. Dieses hat (idr.) den Effekt,
+-- rechtsassoziativ und hat die Priorität 0. Dieses hat (i.d.R.) den Effekt,
-- dass der `komplette` Ausdruck auf der rechten Seite als Parameter für die
-- Funktion auf der linken Seite verwendet wird.
-- Mit `.` und `$` kann man sich so viele Klammern ersparen.
@@ -283,7 +283,7 @@ for [0..5] $ \i -> show i
for [0..5] show
-- foldl oder foldr reduziren Listen auf einen Wert.
--- foldl <fn> <initial value> <list>
+-- foldl <Funktion> <initialer Wert> <Liste>
foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43
-- die Abarbeitung sieht so aus:
@@ -435,7 +435,7 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater
```
Haskell ist sehr einfach zu installieren.
-Hohl es dir von [hier](http://www.haskell.org/platform/).
+Hol es dir von [hier](http://www.haskell.org/platform/).
Eine sehr viele langsamere Einführung findest du unter:
[Learn you a Haskell](http://learnyouahaskell.com/) oder
diff --git a/es-es/forth-es.html.markdown b/es-es/forth-es.html.markdown
index 05dc0cc5..edc5d38c 100644
--- a/es-es/forth-es.html.markdown
+++ b/es-es/forth-es.html.markdown
@@ -1,4 +1,4 @@
----
+---
language: forth
contributors:
- ["Horse M.D.", "http://github.com/HorseMD/"]
diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown
index 4930eebc..a27203d1 100644
--- a/es-es/python-es.html.markdown
+++ b/es-es/python-es.html.markdown
@@ -9,8 +9,8 @@ lang: es-es
filename: learnpython-es.py
---
-Python fue creado por Guido Van Rossum en el principio de los 90'. Ahora es uno
-de los lenguajes más populares en existencia. Me enamoré de Python por su claridad sintáctica.
+Python fue creado por Guido Van Rossum en el principio de los 90. Ahora es uno
+de los lenguajes más populares que existen. Me enamoré de Python por su claridad sintáctica.
Es básicamente pseudocódigo ejecutable.
¡Comentarios serán muy apreciados! Pueden contactarme en [@louiedinh](http://twitter.com/louiedinh) o louiedinh [at] [servicio de email de google]
@@ -19,8 +19,8 @@ Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser apl
```python
# Comentarios de una línea comienzan con una almohadilla (o signo gato)
-""" Strings multilinea pueden escribirse
- usando tres "'s, y comunmente son usados
+""" Strings multilínea pueden escribirse
+ usando tres "'s, y comúnmente son usados
como comentarios.
"""
@@ -48,7 +48,7 @@ Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser apl
# Resultado de la división de enteros truncada para positivos y negativos
5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # funciona con números en coma flotante
+5.0 // 3.0 # => 1.0 # funciona con números de coma flotante
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
@@ -436,7 +436,7 @@ class Humano(object):
def get_especie(cls):
return cls.especie
- # Un metodo estatico es llamado sin la clase o instancia como referencia
+ # Un metodo estático es llamado sin la clase o instancia como referencia
@staticmethod
def roncar():
return "*roncar*"
@@ -507,7 +507,7 @@ def duplicar_numeros(iterable):
# Nota: xrange es un generador que hace lo mismo que range.
# Crear una lista de 1 a 900000000 lleva mucho tiempo y ocupa mucho espacio.
# xrange crea un generador, mientras que range crea toda la lista.
-# Añadimos un guion bajo a los nombres de variable que coinciden con palabras
+# Añadimos un guión bajo a los nombres de variable que coinciden con palabras
# reservadas de python.
xrange_ = xrange(1, 900000000)
diff --git a/forth.html.markdown b/forth.html.markdown
index b4a5581b..55d755b2 100644
--- a/forth.html.markdown
+++ b/forth.html.markdown
@@ -54,7 +54,7 @@ Forth, but most of what is written here should work elsewhere.
3 dup - \ duplicate the top item (1st now equals 2nd): 3 - 3
2 5 swap / \ swap the top with the second element: 5 / 2
6 4 5 rot .s \ rotate the top 3 elements: 4 5 6
-4 0 drop 2 / \ remove the top item (dont print to screen): 4 / 2
+4 0 drop 2 / \ remove the top item (don't print to screen): 4 / 2
1 2 3 nip .s \ remove the second item (similar to drop): 1 3
\ ---------------------- More Advanced Stack Manipulation ----------------------
diff --git a/fsharp.html.markdown b/fsharp.html.markdown
index 809a1da2..e345201d 100644
--- a/fsharp.html.markdown
+++ b/fsharp.html.markdown
@@ -346,7 +346,7 @@ module DataTypeExamples =
let trySendEmail email =
match email with // use pattern matching
| ValidEmailAddress address -> () // send
- | InvalidEmailAddress address -> () // dont send
+ | InvalidEmailAddress address -> () // don't send
// The combination of union types and record types together
// provide a great foundation for domain driven design.
@@ -426,7 +426,7 @@ module ActivePatternExamples =
// -----------------------------------
// You can create partial matching patterns as well
- // Just use underscore in the defintion, and return Some if matched.
+ // Just use underscore in the definition, and return Some if matched.
let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None
let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None
@@ -627,7 +627,3 @@ module NetCompatibilityExamples =
For more demonstrations of F#, go to the [Try F#](http://www.tryfsharp.org/Learn) site, or my [why use F#](http://fsharpforfunandprofit.com/why-use-fsharp/) series.
Read more about F# at [fsharp.org](http://fsharp.org/).
-
-
-
-
diff --git a/id-id/json-id.html.markdown b/id-id/json-id.html.markdown
index 52e61449..ca346f6c 100644
--- a/id-id/json-id.html.markdown
+++ b/id-id/json-id.html.markdown
@@ -1,11 +1,12 @@
---
language: json
-filename: learnjson.json
+filename: learnjson-id.json
contributors:
- ["Anna Harren", "https://github.com/iirelu"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
-translators
+translators:
- ["Rizky Luthfianto", "https://github.com/rilut"]
+lang: id-id
---
JSON adalah format pertukaran data yang sangat simpel, kemungkinan besar,
diff --git a/kotlin.html.markdown b/kotlin.html.markdown
index 72018f51..7b1475a8 100644
--- a/kotlin.html.markdown
+++ b/kotlin.html.markdown
@@ -9,7 +9,7 @@ Kotlin is a Statically typed programming language for the JVM, Android and the
browser. It is 100% interoperable with Java.
[Read more here.](https://kotlinlang.org/)
-```kotlin
+```java
// Single-line comments start with //
/*
Multi-line comments look like this.
diff --git a/markdown.html.markdown b/markdown.html.markdown
index b4ad3202..bdf42368 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -7,7 +7,9 @@ filename: markdown.md
---
-Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well).
+Markdown was created by John Gruber in 2004. It's meant to be an easy to read
+and write syntax which converts easily to HTML (and now many other formats as
+well).
Markdown also varies in implementation from one parser to a next. This
guide will attempt to clarify when features are universal or when they are
@@ -28,9 +30,10 @@ specific to a certain parser.
Markdown is a superset of HTML, so any HTML file is valid Markdown.
```markdown
-<!--This means we can use HTML elements in Markdown, such as the comment element,
-and they won't be affected by a markdown parser. However, if you create an HTML element
-in your markdown file, you cannot use markdown syntax within that element's contents.-->
+<!--This means we can use HTML elements in Markdown, such as the comment
+element, and they won't be affected by a markdown parser. However, if you
+create an HTML element in your markdown file, you cannot use markdown syntax
+within that element's contents.-->
```
## Headings
@@ -214,8 +217,8 @@ highlighting of the language you specify after the \`\`\`
## Horizontal rule
-Horizontal rules (`<hr/>`) are easily added with three or more asterisks or hyphens,
-with or without spaces.
+Horizontal rules (`<hr/>`) are easily added with three or more asterisks or
+hyphens, with or without spaces.
```markdown
***
@@ -298,7 +301,8 @@ in italics, so I do this: \*this text surrounded by asterisks\*.
### Keyboard keys
-In GitHub Flavored Markdown, you can use a `<kbd>` tag to represent keyboard keys.
+In GitHub Flavored Markdown, you can use a `<kbd>` tag to represent keyboard
+keys.
```markdown
Your computer crashed? Try sending a
diff --git a/nl-nl/coffeescript-nl.html.markdown b/nl-nl/coffeescript-nl.html.markdown
index dc0b1e19..390e6572 100644
--- a/nl-nl/coffeescript-nl.html.markdown
+++ b/nl-nl/coffeescript-nl.html.markdown
@@ -6,6 +6,7 @@ contributors:
translators:
- ["Jelle Besseling", "https://github.com/Jell-E"]
- ["D.A.W. de Waal", "http://github.com/diodewaal"]
+ - ["Sam van Kampen", "http://tehsvk.net"]
filename: coffeescript-nl.coffee
lang: nl-nl
---
@@ -13,10 +14,10 @@ lang: nl-nl
CoffeeScript is een kleine programmeertaal die direct compileert naar
JavaScript en er is geen interpretatie tijdens het uitvoeren.
CoffeeScript probeert om leesbare, goed geformatteerde en goed draaiende
-JavaScript code te genereren, die in elke JavaScript runtime werkt, als een
+JavaScript code te genereren, die in elke JavaScript-runtime werkt, als een
opvolger van JavaScript.
-Op [de CoffeeScript website](http://coffeescript.org/), staat een
+Op [de CoffeeScript-website](http://coffeescript.org/), staat een
volledigere tutorial voor CoffeeScript.
``` coffeescript
@@ -26,7 +27,7 @@ volledigere tutorial voor CoffeeScript.
###
Blokken commentaar maak je zo, ze vertalen naar JavaScripts */ en /*
-in de uitvoer van de CoffeeScript compiler.
+in de uitvoer van de CoffeeScript-compiler.
Het is belangrijk dat je ongeveer snapt hoe JavaScript
werkt voordat je verder gaat.
@@ -43,7 +44,7 @@ getal = -42 if tegengestelde #=> if(tegengestelde) { getal = -42; }
kwadraat = (x) -> x * x #=> var kwadraat = function(x) { return x * x; }
vul = (houder, vloeistof = "koffie") ->
- "Nu de #{houder} met #{koffie} aan het vullen..."
+ "Nu de #{houder} met #{vloeistof} aan het vullen..."
#=>var vul;
#
#vul = function(houder, vloeistof) {
@@ -80,7 +81,7 @@ wedstrijd = (winnaar, lopers...) ->
alert "Ik wist het!" if elvis?
#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
-# Lijst abstractie:
+# Lijstabstracties:
derdemachten = (wiskunde.derdemacht num for num in lijst)
#=>derdemachten = (function() {
# var _i, _len, _results;
diff --git a/nl-nl/typescript-nl.html.markdown b/nl-nl/typescript-nl.html.markdown
new file mode 100644
index 00000000..dcea2a4d
--- /dev/null
+++ b/nl-nl/typescript-nl.html.markdown
@@ -0,0 +1,174 @@
+---
+language: TypeScript
+contributors:
+ - ["Philippe Vlérick", "https://github.com/pvlerick"]
+filename: learntypescript-nl.ts
+translators:
+ - ["Niels van Velzen", "https://nielsvanvelzen.me"]
+lang: nl-nl
+---
+
+TypeScript is een taal gericht op het versoepelen van de ontwikkeling van
+grote applicaties gemaakt in JavaScript.
+TypeScript voegt veelgebruikte technieken zoals klassen, modules, interfaces,
+generieken en statische typen toe aan JavaScript.
+TypeScript is een superset van JavaScript: alle JavaScript code is geldige
+TypeScript code waardoor de overgang van JavaScript naar TypeScript wordt versoepeld.
+
+Dit artikel focust zich alleen op de extra's van TypeScript tegenover [JavaScript] (../javascript-nl/).
+
+Om de compiler van TypeScript te kunnen proberen kun je naar de [Playground] (http://www.typescriptlang.org/Playground) gaan.
+Hier kun je automatisch aangevulde code typen in TypeScript en de JavaScript variant bekijken.
+
+```js
+// Er zijn 3 basis typen in TypeScript
+var isKlaar: boolean = false;
+var lijnen: number = 42;
+var naam: string = "Peter";
+
+// Wanneer het type onbekend is gebruik je "Any"
+var nietZeker: any = 4;
+nietZeker = "misschien een string";
+nietZeker = false; // Toch een boolean
+
+// Voor collecties zijn er "typed arrays"
+var lijst: number[] = [1, 2, 3];
+// of generieke arrays
+var lijst: Array<number> = [1, 2, 3];
+
+// Voor enumeraties:
+enum Kleur {Rood, Groen, Blauw};
+var c: Kleur = Kleur.Groen;
+
+// Als laatst, "void" wordt gebruikt voor als een functie geen resultaat geeft
+function groteVerschrikkelijkeMelding(): void {
+ alert("Ik ben een vervelende melding!");
+}
+
+// Functies zijn eersteklas ?, supporten de lambda "fat arrow" syntax en
+// gebruiken gebruiken "type inference"
+
+// Het volgende is allemaal hetzelfde
+var f1 = function(i: number): number { return i * i; }
+var f2 = function(i: number) { return i * i; }
+var f3 = (i: number): number => { return i * i; }
+var f4 = (i: number) => { return i * i; }
+// Omdat we maar 1 lijn gebruiken hoeft het return keyword niet gebruikt te worden
+var f5 = (i: number) => i * i;
+
+// Interfaces zijn structureel, elk object wat de eigenschappen heeft
+// is een gebruiker van de interface
+interface Persoon {
+ naam: string;
+ // Optionele eigenschappen worden gemarkeerd met "?"
+ leeftijd?: number;
+ // En natuurlijk functies
+ verplaats(): void;
+}
+
+// Object die gebruikt maakt van de "Persoon" interface
+// Kan gezien worden als persoon sinds het de naam en verplaats eigenschappen bevat
+var p: Persoon = { naam: "Bobby", verplaats: () => {} };
+// Object met de optionele leeftijd eigenschap
+var geldigPersoon: Persoon = { naam: "Bobby", leeftijd: 42, verplaats: () => {} };
+// Ongeldig persoon vanwege de leeftijds type
+var ongeldigPersoon: Persoon = { naam: "Bobby", leeftijd: true };
+
+// Interfaces kunnen ook een functie ype beschrijven
+interface ZoekFunc {
+ (bron: string, subString: string): boolean;
+}
+// Alleen de parameters types zijn belangrijk, namen maken niet uit.
+var mySearch: ZoekFunc;
+mySearch = function(src: string, sub: string) {
+ return src.search(sub) != -1;
+}
+
+// Classes - leden zijn standaard publiek
+class Punt {
+ // Eigenschappen
+ x: number;
+
+ // Constructor - de publieke / prive trefwoorden in deze context zullen
+ // eigenschappen in de klasse kunnen aanmaken zonder ze te defineren.
+ // In dit voorbeeld zal "y" net als "x" gedefineerd worden met minder code.
+ // Standaard waardes zijn ook gesupport
+
+ constructor(x: number, public y: number = 0) {
+ this.x = x;
+ }
+
+ // Functies
+ dist(): number { return Math.sqrt(this.x * this.x + this.y * this.y); }
+
+ // Statische leden
+ static origin = new Punt(0, 0);
+}
+
+var p1 = new Punt(10 ,20);
+var p2 = new Punt(25); // y zal de waarde 0 krijgen
+
+// Overnemen
+class Punt3D extends Punt {
+ constructor(x: number, y: number, public z: number = 0) {
+ super(x, y); // Constructor van ouder aanroepen (Punt)
+ }
+
+ // Overschrijven
+ dist(): number {
+ var d = super.dist();
+ return Math.sqrt(d * d + this.z * this.z);
+ }
+}
+
+// Modules werken ongeveer hetzelfde als namespaces
+// met "." kan je submodules defineren
+module Geometrie {
+ export class Vierkant {
+ constructor(public zijLengte: number = 0) {
+ }
+
+ oppervlakte() {
+ return Math.pow(this.zijLengte, 2);
+ }
+ }
+}
+
+var s1 = new Geometrie.Vierkant(5);
+
+// Local alias for referencing a module
+import G = Geometrie;
+
+var s2 = new G.Vierkant(10);
+
+// Generieken
+// Classes
+class Tupel<T1, T2> {
+ constructor(public item1: T1, public item2: T2) {
+ }
+}
+
+// Interfaces
+interface Paar<T> {
+ item1: T;
+ item2: T;
+}
+
+// En functies
+var paarNaarTupel = function<T>(p: Paar<T>) {
+ return new Tupel(p.item1, p.item2);
+};
+
+var tupel = paarNaarTupel({ item1: "hallo", item2: "wereld" });
+
+// Refferentie naar een definitie bestand:
+/// <reference path="jquery.d.ts" />
+
+```
+
+## Verder lezen (engels)
+ * [TypeScript Official website] (http://www.typescriptlang.org/)
+ * [TypeScript language specifications (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238)
+ * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript)
+ * [Source Code on GitHub] (https://github.com/Microsoft/TypeScript)
+ * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/)
diff --git a/paren.html.markdown b/paren.html.markdown
index cde14853..701cadfd 100644
--- a/paren.html.markdown
+++ b/paren.html.markdown
@@ -4,6 +4,7 @@ language: Paren
filename: learnparen.paren
contributors:
- ["KIM Taegyoon", "https://github.com/kimtg"]
+ - ["Claudson Martins", "https://github.com/claudsonm"]
---
[Paren](https://bitbucket.org/ktg/paren) is a dialect of Lisp. It is designed to be an embedded language.
@@ -77,7 +78,7 @@ some-var ; => 5
;; Accessing a previously unassigned variable is an exception
; x ; => Unknown variable: x : nil
-;; Local binding: Use lambda calculus! `a' and `b' are bound to `1' and `2' only within the (fn ...)
+;; Local binding: Use lambda calculus! 'a' and 'b' are bound to '1' and '2' only within the (fn ...)
((fn (a b) (+ a b)) 1 2) ; => 3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@@ -88,12 +89,12 @@ some-var ; => 5
;; Lists are vector-like data structures. (Random access is O(1).)
(cons 1 (cons 2 (cons 3 (list)))) ; => (1 2 3)
-;; `list' is a convenience variadic constructor for lists
+;; 'list' is a convenience variadic constructor for lists
(list 1 2 3) ; => (1 2 3)
;; and a quote can also be used for a literal list value
(quote (+ 1 2)) ; => (+ 1 2)
-;; Can still use `cons' to add an item to the beginning of a list
+;; Can still use 'cons' to add an item to the beginning of a list
(cons 0 (list 1 2 3)) ; => (0 1 2 3)
;; Lists are a very basic type, so there is a *lot* of functionality for
@@ -106,7 +107,7 @@ some-var ; => 5
;; 3. Functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;; Use `fn' to create functions.
+;; Use 'fn' to create functions.
;; A function always returns the value of its last expression
(fn () "Hello World") ; => (fn () Hello World) : fn
@@ -117,7 +118,7 @@ some-var ; => 5
(set hello-world (fn () "Hello World"))
(hello-world) ; => "Hello World"
-;; You can shorten this using the function definition syntatcic sugae:
+;; You can shorten this using the function definition syntactic sugar:
(defn hello-world2 () "Hello World")
;; The () in the above is the list of arguments for the function
@@ -134,7 +135,7 @@ some-var ; => 5
;; 4. Equality
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;; for numbers use `=='
+;; for numbers use '=='
(== 3 3.0) ; => true
(== 2 1) ; => false
@@ -166,7 +167,7 @@ some-var ; => 5
;; 6. Mutation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;; Use `set' to assign a new value to a variable or a place
+;; Use 'set' to assign a new value to a variable or a place
(set n 5) ; => 5
(set n (inc n)) ; => 6
n ; => 6
diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown
index 3c9512aa..db087a5f 100644
--- a/pt-br/java-pt.html.markdown
+++ b/pt-br/java-pt.html.markdown
@@ -214,42 +214,42 @@ public class LearnJava {
//Iteração feita 10 vezes, fooFor 0->9
}
System.out.println("Valor do fooFor: " + fooFor);
-
- // O Loop For Each
+
+ // O Loop For Each
// Itera automaticamente por um array ou lista de objetos.
int[] fooList = {1,2,3,4,5,6,7,8,9};
//estrutura do loop for each => for(<objeto> : <array_de_objeto>)
//lê-se: para cada objeto no array
//nota: o tipo do objeto deve ser o mesmo do array.
-
+
for( int bar : fooList ){
//System.out.println(bar);
//Itera 9 vezes e imprime 1-9 em novas linhas
}
-
+
// Switch
// Um switch funciona com os tipos de dados: byte, short, char e int
// Ele também funciona com tipos enumerados (vistos em tipos Enum)
// como também a classe String e algumas outras classes especiais
// tipos primitivos: Character, Byte, Short e Integer
- int mes = 3;
- String mesString;
- switch (mes){
+ int mes = 3;
+ String mesString;
+ switch (mes){
case 1:
- mesString = "Janeiro";
+ mesString = "Janeiro";
break;
case 2:
- mesString = "Fevereiro";
+ mesString = "Fevereiro";
break;
case 3:
- mesString = "Março";
+ mesString = "Março";
break;
default:
- mesString = "Algum outro mês";
+ mesString = "Algum outro mês";
break;
}
System.out.println("Resultado do Switch: " + mesString);
-
+
// Condição de forma abreviada.
// Você pode usar o operador '?' para atribuições rápidas ou decisões lógicas.
// Lê-se "Se (declaração) é verdadeira, use <primeiro valor>
@@ -287,9 +287,9 @@ public class LearnJava {
// Classes e Métodos
///////////////////////////////////////
- System.out.println("\n->Classes e Métodos");
+ System.out.println("\n->Classes e Métodos");
- // (segue a definição da classe Bicicleta)
+ // (segue a definição da classe Bicicleta)
// Use o new para instanciar uma classe
Bicicleta caloi = new Bicicleta(); // Objeto caloi criado.
@@ -318,9 +318,9 @@ class Bicicleta {
// Atributos/Variáveis da classe Bicicleta.
public int ritmo; // Public: Pode ser acessada em qualquer lugar.
- private int velocidade; // Private: Apenas acessível a classe.
+ private int velocidade; // Private: Apenas acessível a classe.
protected int catraca; // Protected: Acessível a classe e suas subclasses.
- String nome; // default: Apenas acessível ao pacote.
+ String nome; // default: Apenas acessível ao pacote.
// Construtores são uma forma de criação de classes
// Este é o construtor padrão.
@@ -388,7 +388,7 @@ class Bicicleta {
// Velocipede é uma subclasse de bicicleta.
class Velocipede extends Bicicleta {
// (Velocípedes são bicicletas com rodas dianteiras grandes
- // Elas não possuem catraca.)
+ // Elas não possuem catraca.)
public Velocipede(int ritmoInicial, int velocidadeInicial){
// Chame o construtor do pai (construtor de Bicicleta) com o comando super.
@@ -626,11 +626,11 @@ Os links fornecidos aqui abaixo são apenas para ter uma compreensão do tema, u
Outros tópicos para pesquisar:
-* [Tutorial Java para Sun Trail / Oracle](http://docs.oracle.com/javase/tutorial/index.html)
+* [Tutorial Java para Sun Trail / Oracle](http://docs.oracle.com/javase/tutorial/index.html)
* [Modificadores de acesso do Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
-* [Coceitos de Programação Orientada à Objetos](http://docs.oracle.com/javase/tutorial/java/concepts/index.html):
+* [Coceitos de Programação Orientada à Objetos](http://docs.oracle.com/javase/tutorial/java/concepts/index.html):
* [Herança](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)
* [Polimorfismo](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html)
* [Abstração](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
@@ -646,3 +646,9 @@ Outros tópicos para pesquisar:
Livros:
* [Use a cabeça, Java] (http://www.headfirstlabs.com/books/hfjava/)
+
+Apostila:
+
+* [Java e Orientação a Objetos] (http://www.caelum.com.br/apostila-java-orientacao-objetos/)
+
+* [Java para Desenvolvimento Web] (https://www.caelum.com.br/apostila-java-web/)
diff --git a/python.html.markdown b/python.html.markdown
index 12be4be1..28b0a7ae 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -8,20 +8,22 @@ contributors:
filename: learnpython.py
---
-Python was created by Guido Van Rossum in the early 90s. It is now one of the most popular
-languages in existence. I fell in love with Python for its syntactic clarity. It's basically
-executable pseudocode.
+Python was created by Guido Van Rossum in the early 90s. It is now one of the
+most popular languages in existence. I fell in love with Python for its
+syntactic clarity. It's basically executable pseudocode.
-Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service]
+Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh)
+or louiedinh [at] [google's email service]
-Note: This article applies to Python 2.7 specifically, but should be applicable
-to Python 2.x. Python 2.7 is reaching end of life and will stop being maintained in 2020,
-it is though recommended to start learning Python with Python 3.
-For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
+Note: This article applies to Python 2.7 specifically, but should be applicable
+to Python 2.x. Python 2.7 is reaching end of life and will stop being
+maintained in 2020, it is though recommended to start learning Python with
+Python 3. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
-It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same time,
-using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports
-allow you to write Python 3 code that will run on Python 2, so check out the Python 3 tutorial.
+It is also possible to write Python code which is compatible with Python 2.7
+and 3.x at the same time, using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports
+allow you to write Python 3 code that will run on Python 2, so check out the
+Python 3 tutorial.
```python
@@ -32,6 +34,7 @@ allow you to write Python 3 code that will run on Python 2, so check out the Pyt
as comments
"""
+
####################################################
## 1. Primitive Datatypes and Operators
####################################################
@@ -188,6 +191,7 @@ some_other_var # Raises a name error
# Equivalent of C's '?:' ternary operator
"yahoo!" if 3 > 2 else 2 # => "yahoo!"
+
# Lists store sequences
li = []
# You can start with a prefilled list
@@ -441,6 +445,7 @@ with open("myfile.txt") as f:
for line in f:
print line
+
####################################################
## 4. Functions
####################################################
@@ -464,7 +469,6 @@ def varargs(*args):
varargs(1, 2, 3) # => (1, 2, 3)
-
# You can define functions that take a variable number of
# keyword args, as well, which will be interpreted as a dict by using **
def keyword_args(**kwargs):
@@ -698,7 +702,6 @@ for i in double_numbers(xrange_):
# message
from functools import wraps
-
def beg(target_function):
@wraps(target_function)
def wrapper(*args, **kwargs):
@@ -709,13 +712,11 @@ def beg(target_function):
return wrapper
-
@beg
def say(say_please=False):
msg = "Can you buy me a beer?"
return msg, say_please
-
print say() # Can you buy me a beer?
print say(say_please=True) # Can you buy me a beer? Please! I am poor :(
```
diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown
index 0b02dca8..8ee3aa64 100644
--- a/pythonstatcomp.html.markdown
+++ b/pythonstatcomp.html.markdown
@@ -1,8 +1,8 @@
---
-language: Statistical computing with Python
+category: tool
+tool: Statistical Computing with Python
contributors:
- ["e99n09", "https://github.com/e99n09"]
-filename: pythonstatcomp.py
---
This is a tutorial on how to do some typical statistical programming tasks using Python. It's intended for people basically familiar with Python and experienced at statistical programming in a language like R, Stata, SAS, SPSS, or MATLAB.
diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown
index c41e9676..f71435ea 100644
--- a/ru-ru/markdown-ru.html.markdown
+++ b/ru-ru/markdown-ru.html.markdown
@@ -2,55 +2,77 @@
language: markdown
contributors:
- ["Dan Turkel", "http://danturkel.com/"]
+ - ["Jacob Ward", "http://github.com/JacobCWard/"]
+translators:
- ["Pirogov Alexey", "http://twitter.com/alex_pir"]
+ - ["Andre Polykanine", https://github.com/Oire"]
filename: markdown-ru.md
lang: ru-ru
---
Язык разметки Markdown создан Джоном Грубером (англ. John Gruber)
-и Аароном Шварцем (англ. Aaron H. Swartz) в 2004 году.
+в 2004 году.
Авторы задавались целью создать максимально удобочитаемый
и удобный в публикации облегчённый язык разметки,
пригодный для последующего преобразования в HTML
(а также и в другие форматы).
+Также реализации Markdown варьируют в зависимости от парсера.
+В этом руководстве будет указано, какие функции универсальны для языка,
+а какие зависят от конкретного парсера.
+
+- [HTML-элементы](#html-elements)
+- [Заголовки](#headings)
+- [Простейшая стилизация текста](#simple-text-styles)
+- [Абзацы](#paragraphs)
+- [Списки](#lists)
+- [Блоки кода](#code-blocks)
+- [Горизонтальный разделитель](#horizontal-rule)
+- [Ссылки](#links)
+- [Изображения](#images)
+- [Разное](#miscellany)
+
+## HTML-элементы
+Markdown является надмножеством HTML, поэтому любой HTML-файл является
+корректным документом Markdown.
+
```markdown
-<!-- Markdown является надмножеством HTML, поэтому любой HTML-файл является
-валидным документом Markdown, что позволяет использовать напрямую
+<!-- Это позволяет использовать напрямую
любые элементы HTML-разметки, такие, например, как этот комментарий.
Встроенные в документ HTML-элементы не затрагиваются парсером Markdown
-и попадают в итоговый HTML без изменений. Однако, следует понимать,
+и попадают в итоговый HTML без изменений. Однако следует понимать,
что эта же особенность не позволяет использовать разметку Markdown внутри
HTML-элементов -->
-<!-- Ещё одна особенность формата Markdown состоит в том, что поддерживаемые
-возможности разметки зависят от конкретной реализации парсера. В данном
-руководстве возможности, поддерживаемые лишь определёнными парсерами,
-сопровождаются соответствующими примечаниями. -->
-
-<!-- Заголовки -->
+## Заголовки
-<!-- HTML-элементы от <h1> до <h6> размечаются очень просто:
+HTML-элементы от <h1> до <h6> размечаются очень просто:
текст, который должен стать заголовком, предваряется
-соответствующим количеством символов "#": -->
+соответствующим количеством символов "#":
+
+```markdown
# Это заголовок h1
## Это заголовок h2
### Это заголовок h3
#### Это заголовок h4
##### Это заголовок h5
###### Это заголовок h6
+```
+Markdown позволяет размечать заголовки <h1> и <h2> ещё одним способом:
-<!-- Markdown позволяет размечать заголовки <h1> и <h2> ещё одним способом: -->
+```markdown
Это заголовок h1
================
А это заголовок h2
------------------
+```
-<!-- Простейшая стилизация текста -->
+## Простейшая стилизация текста
-<!-- Текст легко сделать полужирным и/или курсивным: -->
+Текст легко сделать полужирным и/или курсивным:
+```markdown
*Этот текст будет выведен курсивом.*
_Так же, как этот._
@@ -60,44 +82,58 @@ __И этот тоже.__
***Полужирный курсив.***
**_И тут!_**
*__И даже здесь!__*
+```
-<!-- В GitHub Flavored Markdown (версии Markdown, использующейся в GitHub,
-для рендеринга Markdown-документов) текст можно сделать зачёркнутым: -->
+В Github Flavored Markdown, стандарте, который используется в Github,
+текст также можно сделать зачёркнутым:
+```markdown
~~Зачёркнутый текст.~~
+```
+
+## Абзацы
+
+Абзацами являются любые строки, следующие друг за другом.
+Разделяются же абзацы одной или несколькими пустыми строками:
-<!-- Абзацами являются любые строки, следующие друг за другом.
-Разделяются же абзацы одной или несколькими пустыми строками: -->
+```markdown
+Это абзац. Я печатаю в абзаце, разве это не прикольно?
-Это абзац. Всё предельно просто.
+А тут уже абзац №2.
+Эта строка всё ещё относится к абзацу №2!
-А тут уже параграф №2.
-Эта строка всё ещё относится к параграфу №2!
+О, а вот это уже абзац №3!
+```
-О, а вот это уже параграф №3!
+Для вставки принудительных переносов можно завершить абзац двумя дополнительными пробелами:
-<!-- Для вставки принудительных переносов можно использовать HTML-тэг <br/>: -->
+```markdown
+Эта строка завершается двумя пробелами (выделите, чтобы увидеть!).
-Принудительный <br/> перенос!
+Над этой строкой есть <br />!
+```
-<!-- Цитаты размечаются с помощью символа ">": -->
+Цитаты размечаются с помощью символа «>»:
+```markdown
> Это цитата. В цитатах можно
-> принудительно переносить строки, вставляя ">" в начало каждой следующей строки. А можно просто оставлять достаточно длинными, и такие длинные строки будут перенесены автоматически.
+> принудительно переносить строки, вставляя «>» в начало каждой следующей строки. А можно просто оставлять их достаточно длинными, и такие длинные строки будут перенесены автоматически.
> Разницы между этими двумя подходами к переносу строк нет, коль скоро
-> каждая строка начинается с символа ">"
+> каждая строка начинается с символа «>»
> А ещё цитаты могут быть многоуровневыми:
>> как здесь
>>> и здесь :)
> Неплохо?
+```
-<!-- Списки -->
-<!-- Маркированные списки размечаются вставкой в начало каждого элемента
-одного из символов "*", "+" или "-":
-(символ должен быть одним и тем же для всех элементов) -->
+## Списки
+Маркированные списки размечаются вставкой в начало каждого элемента
+одного из символов «*», «+» или «-»:
+(символ должен быть одним и тем же для всех элементов)
+```markdown
* Список,
* Размеченный
* Звёздочками
@@ -113,167 +149,207 @@ __И этот тоже.__
- Список,
- Размеченный
- Дефисами
+```
-<!-- В нумерованных списках каждая строка начинается
-с числа и точки вслед за ним: -->
+В нумерованных списках каждая строка начинается
+с числа и точки вслед за ним:
+```markdown
1. Первый элемент
2. Второй элемент
3. Третий элемент
+```
-<!-- Заметьте, нумеровать элементы корректно необязательно. Достаточно указать
-любое число в начале каждого элемента и рендер пронумерует элементы сам!
-Правда, злоупотреблять этим не стоит :) -->
+Заметьте, нумеровать элементы корректно необязательно. Достаточно указать
+любое число в начале каждого элемента, и парсер пронумерует элементы сам!
+Правда, злоупотреблять этим не стоит :)
+```markdown
1. Первый элемент
1. Второй элемент
1. Третий элемент
-<!-- (Этот список будет отрендерен так же, как и предыдущий!) -->
+```
+(Этот список будет отображён так же, как и предыдущий!)
-<!-- Списки могут быть вложенными: -->
+Списки могут быть вложенными:
+```markdown
1. Введение
2. Начало работы
3. Примеры использования
* Простые
* Сложные
4. Заключение
+```
+
+Можно даже делать списки задач. Блок ниже создаёт HTML-флажки.
-<!-- Блоки с исходным кодом -->
-<!-- Фрагменты исходного кода выделяются очень просто - каждая строка блока должна иметь отступ в четыре пробела либо в один символ табуляции -->
+```markdown
+Для отметки флажка используйте «x»
+- [ ] Первая задача
+- [ ] Вторая задача
+Этот флажок ниже будет отмечен
+- [x] Задача была завершена
+```
+## Блоки кода
+
+Фрагменты исходного кода (обычно отмечаемые тегом `<code>`) выделяются просто:
+каждая строка блока должна иметь отступ в четыре пробела либо в один символ табуляции.
+
+```markdown
Это код,
- причём - многострочный
+ причём многострочный
+```
-<!-- Дополнительные отступы в коде следует делать с помощью четырёх пробелов: -->
+Вы также можете делать дополнительные отступы, добавляя символы табуляции
+или по четыре пробела:
+```markdown
my_array.each do |item|
puts item
end
+```
-<!-- Иногда бывает нужно вставить фрагмент кода прямо в строку текста,
+Иногда бывает нужно вставить фрагмент кода прямо в строку текста,
не выделяя код в блок. Для этого фрагменты кода нужно обрамлять
-символами "`": -->
+символами «`»:
-Например, можно выделить имя функции `go_to()` прямо посреди текста.
+```markdown
+Ваня даже не знал, что делает функция `go_to()`!
+```
-<!-- GitHub Flavored Markdown позволяет указать для блока кода синтаксис оного.
-В этом случае синтаксис внутри блока будет подсвечен. Пример: -->
+В Github Flavored Markdown для блоков кода можно использовать
+специальный синтаксис:
-\`\`\`ruby <!-- Только нужно будет убрать символы "\", оставив лишь "```ruby" -->
+<pre>
+<code class="highlight">&#x60;&#x60;&#x60;ruby
def foobar
- puts "Hello world!"
+ puts "Привет, мир!"
end
-\`\`\` <!-- И здесь тоже backslashes нужно убрать, т.е. оставить "```" -->
+&#x60;&#x60;&#x60;</code></pre>
-<-- Обратите внимание: фрагмент, указанный выше, не предваряется отступами,
-поскольку GitHub сам в состоянии определить границы блока - по строкам "```" -->
+Во фрагменте, приведённом выше, отступ не требуется.
+Кроме того, Github подсветит синтаксис языка, указанного после \`\`\`
-<!-- Горизонтальный разделитель (<hr />) -->
-<!-- Разделители добавляются вставкой строки из трёх и более
-(одинаковых) символов "*" или "-": -->
+## Горизонтальный разделитель
+Разделители (`<hr>`) добавляются вставкой строки из трёх и более
+(одинаковых) символов «*» или «-», с пробелами или без них:
+
+```markdown
***
---
-- - - <!-- между символами допустимы пробелы -->
+- - -
****************
+```
+
+## Ссылки
-<!-- Ссылки -->
-<!-- Одной из сильных сторон Markdown можно смело считать то,
+Одной из сильных сторон Markdown можно смело считать то,
как просто размечаются гиперссылки. Для создания ссылки укажите
текст ссылки, заключив его в квадратные скобки,
-и сразу после - url, заключенный в "круглые" -->
+и сразу после — URL-адрес, заключенный в круглые
+```markdown
[Ссылка!](http://test.com/)
+```
+Также для ссылки можно указать всплывающую подсказку (`title`), используя
+кавычки внутри круглых скобок:
-<!-- Также для ссылки можно указать всплывающую подсказку: -->
-
+```markdown
[Ссылка!](http://test.com/ "Ссылка на Test.com")
+```
+Относительные пути тоже возможны:
-<!-- В url можно использовать относительные пути: -->
-
+```markdown
[Перейти к музыке](/music/).
+```
-<!-- Markdown позволяет размечать ссылку в виде сноски: -->
+Markdown также позволяет размечать ссылку в виде сноски:
-[Здесь][link1] высможете узнать больше!
-А можно кликнуть [сюда][foobar], если очень хочется.
+<pre><code class="highlight">&#x5b;<span class="nv">Щёлкните эту ссылку</span>][<span class="ss">link1</span>] для подробной информации!
+&#x5b;<span class="nv">Также посмотрите эту ссылку,</span>][<span class="ss">foobar</span>] если хотите.
-<!-- где-нибудь внизу -->
-[link1]: http://test.com/ "Круто!"
-[foobar]: http://foobar.biz/ "Тоже хорошо!"
+&#x5b;<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Круто!"</span>
+&#x5b;<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Нормально!"</span></code></pre>
-<!-- Примечания:
-- Подсказка может быть заключена в одинарные кавычки вместо двойных,
- а также в круглые скобки.
-- Сноска может находиться в любом месте документа и может иметь
-идентификатор (далее ID) произвольной длины,
-лишь бы это ID был уникальным. -->
+`Title` также может быть в одинарных кавычках или круглых скобках, а также
+отсутствовать вовсе. Ссылки на сноски могут быть в любом месте документа,
+а идентификаторы могут быть какими угодно, лишь бы они были уникальными.
-<!-- Также при разметке ссылок-сносок можно опустить ID,
-если текст ссылки уникален в пределах документа: -->
+Существует также неявное именование, когда ссылка является идентификатором.
-Ссылка на [Google][].
+<pre><code class="highlight">&#x5b;<span class="nv">Это</span>][] ссылка.
-[google]: http://google.com/
+&#x5b;<span class="nv">это</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
-<!-- Правда, эта возможность не очень распространена. -->
+Правда, эта возможность не очень распространена.
-<!-- Изображения -->
-<!-- Разметка изображений очень похожа на разметку ссылок.
-Нужно всего лишь добавить "!" перед ссылкой! -->
+## Изображения
+Разметка изображений очень похожа на разметку ссылок.
+Нужно всего лишь добавить перед ссылкой восклицательный знак!
+```markdown
![Альтернативный текст для изображения](http://imgur.com/myimage.jpg "Подсказка")
+```
+Изображения тоже могут быть оформлены, как сноски.
-<!-- Изображения тоже могут быть оформлены, как сноски: -->
-
-![Альтернативный текст][myimage]
-
-![То же изображение ещё раз][myimage]
-
-[myimage]: relative/urls/cool/image.jpg "подсказка"
+<pre><code class="highlight">!&#x5b;<span class="nv">Это альтернативный текст.</span>][<span class="ss">myimage</span>]
-<!-- Ещё немного ссылок: -->
-<!-- Автоссылки -->
+&#x5b;<span class="nv">myimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"Если нужна подсказка, её можно добавить"</span></code></pre>
+## Разное
+### Автоссылки
+```markdown
Ссылка вида <http://testwebsite.com/> эквивалентна
[http://testwebsite.com/](http://testwebsite.com/)
+```
-<!-- Автоссылки для адресов электронной почты -->
+### Автоссылки для адресов электронной почты
+```markdown
<foo@bar.com>
+```
+
+### Экранирование символов
-<!-- Экранирование символов -->
+```markdown
+Я хочу напечатать *текст, заключённый в звёздочки*, но я не хочу,
+чтобы он был курсивным. Тогда я делаю так:
+\*Текст, заключённый в звёздочки\*
+```
-<!-- Может потребоваться вставить спецсимвол в текст "как есть",
-т.е. защитить его от обработки парсером.
-Такой символ должен быть "экранирован" с помощью обратной косой черты
-(символа "\"): -->
+### Клавиши на клавиатуре
+В Github Flavored Markdown для представления клавиш на клавиатуре
+вы можете использовать тег `<kbd>`.
-\*текст, заключённый в звёздочки!\*
+```markdown
+Ваш компьютер завис? Попробуйте нажать
+<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
+```
-<!-- Таблицы -->
-<!-- Таблицы официально поддерживаются только в GitHub Flavored Markdown,
+### Таблицы
+Таблицы официально поддерживаются только в GitHub Flavored Markdown,
да и синтаксис имеют не слишком удобный.
-Но если очень нужно, размечайте таблицы так: -->
+Но если очень нужно, размечайте таблицы так:
+```markdown
| Столбец 1 | Столбец 2 | Столбец 3 |
| :----------- | :----------: | -----------: |
| Выравнивание | Выравнивание | Выравнивание |
| влево | по центру | вправо |
+```
+Или более компактно
-<!-- Или более компактно -->
-
-Колонка 1|Колонка 2|Колонка 3
+```markdown
+Столбец 1|Столбец 2|Столбец 3
:--|:-:|--:
Выглядит|это|страшновато...
-
-<!-- Ну вот и всё! -->
-
```
-За более подробной информацией обращайтесь к [статье](http://daringfireball.net/projects/markdown/syntax) Джона Грубера о синтаксисе Markdown.
+Ну вот и всё!
-Также часто бывает полезной отличная ["шпаргалка"](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) по Markdown от Adam Pritchard.
+За более подробной информацией обращайтесь к [статье](http://daringfireball.net/projects/markdown/syntax) Джона Грубера о синтаксисе Markdown.
-Если вдруг встретите ошибки в переводе или же захотите его дополнить, делайте pull requests - авторы всегда рады обратной связи!
+Также часто бывает полезной отличная ["шпаргалка"](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) по Markdown от Адама Притчарда.
diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown
index 38e418e9..8bc334ab 100644
--- a/vi-vn/objective-c-vi.html.markdown
+++ b/vi-vn/objective-c-vi.html.markdown
@@ -1,12 +1,10 @@
---
-
language: Objective-C
contributors:
- ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
- ["Yannick Loriot", "https://github.com/YannickL"]
lang: vi-vn
filename: LearnObjectiveC-vi.m
-
---
Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch.
diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown
index 3efe4941..017a7812 100644
--- a/zh-cn/swift-cn.html.markdown
+++ b/zh-cn/swift-cn.html.markdown
@@ -31,7 +31,7 @@ import UIKit
// Swift2.0 println() 及 print() 已经整合成 print()。
print("Hello, world") // 这是原本的 println(),会自动进入下一行
-print("Hello, world", appendNewLine: false) // 如果不要自动进入下一行,需设定进入下一行为 false
+print("Hello, world", terminator: "") // 如果不要自动进入下一行,需设定结束符为空串
// 变量 (var) 的值设置后可以随意改变
// 常量 (let) 的值设置后不能改变
@@ -171,8 +171,8 @@ while i < 1000 {
i *= 2
}
-// do-while 循环
-do {
+// repeat-while 循环
+repeat {
print("hello")
} while 1 == 2
@@ -212,11 +212,11 @@ default: // 在 Swift 里,switch 语句的 case 必须处理所有可能的情
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
-greet("Bob", "Tuesday")
+greet("Bob", day: "Tuesday")
-// 函数参数前带 `#` 表示外部参数名和内部参数名使用同一个名称。
+// 第一个参数表示外部参数名和内部参数名使用同一个名称。
// 第二个参数表示外部参数名使用 `externalParamName` ,内部参数名使用 `localParamName`
-func greet2(#requiredName: String, externalParamName localParamName: String) -> String {
+func greet2(requiredName requiredName: String, externalParamName localParamName: String) -> String {
return "Hello \(requiredName), the day is \(localParamName)"
}
greet2(requiredName:"John", externalParamName: "Sunday") // 调用时,使用命名参数来指定参数的值
@@ -235,8 +235,8 @@ print("Gas price: \(price)")
// 可变参数
func setup(numbers: Int...) {
// 可变参数是个数组
- let number = numbers[0]
- let argCount = numbers.count
+ let _ = numbers[0]
+ let _ = numbers.count
}
// 函数变量以及函数作为返回值返回
@@ -257,7 +257,7 @@ func swapTwoInts(inout a: Int, inout b: Int) {
}
var someIntA = 7
var someIntB = 3
-swapTwoInts(&someIntA, &someIntB)
+swapTwoInts(&someIntA, b: &someIntB)
print(someIntB) // 7
@@ -286,17 +286,10 @@ numbers = numbers.map({ number in 3 * number })
print(numbers) // [3, 6, 18]
// 简洁的闭包
-numbers = sorted(numbers) { $0 > $1 }
-// 函数的最后一个参数可以放在括号之外,上面的语句是这个语句的简写形式
-// numbers = sorted(numbers, { $0 > $1 })
+numbers = numbers.sort { $0 > $1 }
print(numbers) // [18, 6, 3]
-// 超级简洁的闭包,因为 `<` 是个操作符函数
-numbers = sorted(numbers, < )
-
-print(numbers) // [3, 6, 18]
-
//
// MARK: 结构体
@@ -305,7 +298,7 @@ print(numbers) // [3, 6, 18]
// 结构体和类非常类似,可以有属性和方法
struct NamesTable {
- let names = [String]()
+ let names: [String]
// 自定义下标运算符
subscript(index: Int) -> String {
@@ -516,7 +509,7 @@ protocol ShapeGenerator {
// 一个类实现一个带 optional 方法的协议时,可以实现或不实现这个方法
// optional 方法可以使用 optional 规则来调用
@objc protocol TransformShape {
- optional func reshaped()
+ optional func reshape()
optional func canReshape() -> Bool
}
@@ -528,9 +521,9 @@ class MyShape: Rect {
// 在 optional 属性,方法或下标运算符后面加一个问号,可以优雅地忽略 nil 值,返回 nil。
// 这样就不会引起运行时错误 (runtime error)
- if let allow = self.delegate?.canReshape?() {
+ if let reshape = self.delegate?.canReshape?() where reshape {
// 注意语句中的问号
- self.delegate?.reshaped?()
+ self.delegate?.reshape?()
}
}
}
@@ -542,8 +535,8 @@ class MyShape: Rect {
// 扩展: 给一个已经存在的数据类型添加功能
-// 给 Square 类添加 `Printable` 协议的实现,现在其支持 `Printable` 协议
-extension Square: Printable {
+// 给 Square 类添加 `CustomStringConvertible` 协议的实现,现在其支持 `CustomStringConvertible` 协议
+extension Square: CustomStringConvertible {
var description: String {
return "Area: \(self.getArea()) - ID: \(self.identifier)"
}
@@ -567,8 +560,8 @@ print(14.multiplyBy(3)) // 42
// 泛型: 和 Java 及 C# 的泛型类似,使用 `where` 关键字来限制类型。
// 如果只有一个类型限制,可以省略 `where` 关键字
-func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
- for (index, value) in enumerate(array) {
+func findIndex<T: Equatable>(array: [T], _ valueToFind: T) -> Int? {
+ for (index, value) in array.enumerate() {
if value == valueToFind {
return index
}
diff --git a/zh-cn/typescript-cn.html.markdown b/zh-cn/typescript-cn.html.markdown
new file mode 100644
index 00000000..2651b1cb
--- /dev/null
+++ b/zh-cn/typescript-cn.html.markdown
@@ -0,0 +1,173 @@
+---
+language: TypeScript
+category: language
+contributors:
+ - ["Philippe Vlérick", "https://github.com/pvlerick"]
+translators:
+ - ["Shawn Zhang", "https://github.com/shawnzhang009"]
+filename: learntypescript-cn.ts
+lang: zh-cn
+---
+
+TypeScript是一门为开发大型JavaScript应用而设计的语言。TypeScript在JavaScript的基础上增加了类、模块、接口、泛型和静态类型(可选)等常见的概念。它是JavaScript的一个超集:所有JavaScript代码都是有效的TypeScript代码,所以任何JavaScript项目都可以无缝引入TypeScript. TypeScript编译器会把TypeScript代码编译成JavaScript代码。
+
+本文只关注TypeScript额外增加的区别于[JavaScript](../javascript-cn/)的语法,.
+
+如需测试TypeScript编译器,你可以在[Playground](http://www.typescriptlang.org/Playground)码代码,它会自动编译成JavaScript代码然后直接显示出来。
+
+```js
+// TypeScript有三种基本类型
+var isDone: boolean = false;
+var lines: number = 42;
+var name: string = "Anders";
+
+// 如果不知道是什么类型,可以使用"any"(任意)类型
+var notSure: any = 4;
+notSure = "maybe a string instead";
+notSure = false; // 亦可,定义为布尔型
+
+// 对于集合的声明, 有类型化数组和泛型数组
+var list: number[] = [1, 2, 3];
+// 另外一种,使用泛型数组
+var list: Array<number> = [1, 2, 3];
+
+// 枚举:
+enum Color {Red, Green, Blue};
+var c: Color = Color.Green;
+
+// 最后,"void"用于函数没有任何返回的特殊情况下
+function bigHorribleAlert(): void {
+ alert("I'm a little annoying box!");
+}
+
+// 函数是"第一等公民"(first class citizens), 支持使用箭头表达式和类型推断
+
+// 以下是相等的,TypeScript编译器会把它们编译成相同的JavaScript代码
+var f1 = function(i: number): number { return i * i; }
+// 返回推断类型的值
+var f2 = function(i: number) { return i * i; }
+var f3 = (i: number): number => { return i * i; }
+// 返回推断类型的值
+var f4 = (i: number) => { return i * i; }
+// 返回推断类型的值, 单行程式可以不需要return关键字和大括号
+var f5 = (i: number) => i * i;
+
+// 接口是结构化的,任何具有这些属性的对象都与该接口兼容
+interface Person {
+ name: string;
+ // 可选属性,使用"?"标识
+ age?: number;
+ // 函数
+ move(): void;
+}
+
+// 实现"Person"接口的对象,当它有了"name"和"move"方法之后可被视为一个"Person"
+var p: Person = { name: "Bobby", move: () => {} };
+// 带了可选参数的对象
+var validPerson: Person = { name: "Bobby", age: 42, move: () => {} };
+// 因为"age"不是"number"类型所以这不是一个"Person"
+var invalidPerson: Person = { name: "Bobby", age: true };
+
+// 接口同样可以描述一个函数的类型
+interface SearchFunc {
+ (source: string, subString: string): boolean;
+}
+// 参数名并不重要,参数类型才是重要的
+var mySearch: SearchFunc;
+mySearch = function(src: string, sub: string) {
+ return src.search(sub) != -1;
+}
+
+// 类 - 成员默认为公共的(public)
+class Point {
+ // 属性
+ x: number;
+
+ // 构造器 - 这里面的public/private关键字会为属性生成样板代码和初始化值
+ // 这个例子中,y会被同x一样定义,不需要额外代码
+ // 同样支持默认值
+
+ constructor(x: number, public y: number = 0) {
+ this.x = x;
+ }
+
+ // 函数
+ dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
+
+ // 静态成员
+ static origin = new Point(0, 0);
+}
+
+var p1 = new Point(10 ,20);
+var p2 = new Point(25); //y为0
+
+// 继承
+class Point3D extends Point {
+ constructor(x: number, y: number, public z: number = 0) {
+ super(x, y); // 必须显式调用父类的构造器
+ }
+
+ // 重写
+ dist() {
+ var d = super.dist();
+ return Math.sqrt(d * d + this.z * this.z);
+ }
+}
+
+// 模块, "."可以作为子模块的分隔符
+module Geometry {
+ export class Square {
+ constructor(public sideLength: number = 0) {
+ }
+ area() {
+ return Math.pow(this.sideLength, 2);
+ }
+ }
+}
+
+var s1 = new Geometry.Square(5);
+
+// 引入模块并定义本地别名
+import G = Geometry;
+
+var s2 = new G.Square(10);
+
+// 泛型
+// 类
+class Tuple<T1, T2> {
+ constructor(public item1: T1, public item2: T2) {
+ }
+}
+
+// 接口
+interface Pair<T> {
+ item1: T;
+ item2: T;
+}
+
+// 以及函数
+var pairToTuple = function<T>(p: Pair<T>) {
+ return new Tuple(p.item1, p.item2);
+};
+
+var tuple = pairToTuple({ item1:"hello", item2:"world"});
+
+// 引用定义文件
+// <reference path="jquery.d.ts" />
+
+// 模板字符串(使用反引号的字符串)
+// 嵌入变量的模板字符串
+var name = 'Tyrone';
+var greeting = `Hi ${name}, how are you?`
+// 有多行内容的模板字符串
+var multiline = `This is an example
+of a multiline string`;
+
+```
+
+## 参考资料
+ * [TypeScript官网](http://www.typescriptlang.org/)
+ * [TypeScript语言规范说明书(pdf)](http://go.microsoft.com/fwlink/?LinkId=267238)
+ * [Anders Hejlsberg - TypeScript介绍](http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript)
+ * [GitHub源码](https://github.com/Microsoft/TypeScript)
+ * [Definitely Typed - 类型定义仓库](http://definitelytyped.org/)