summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--coldfusion.html.markdown11
-rw-r--r--css.html.markdown35
-rw-r--r--d.html.markdown6
-rw-r--r--de-de/scala-de.html.markdown518
-rw-r--r--edn.html.markdown2
-rw-r--r--fsharp.html.markdown74
-rw-r--r--git.html.markdown14
-rw-r--r--java.html.markdown25
-rw-r--r--make.html.markdown2
-rw-r--r--markdown.html.markdown36
-rw-r--r--matlab.html.markdown18
-rw-r--r--ms-my/javascript-my.html.markdown588
-rw-r--r--objective-c.html.markdown50
-rw-r--r--php.html.markdown8
-rw-r--r--pt-br/c-pt.html.markdown71
-rw-r--r--pt-br/css-pt.html.markdown8
-rw-r--r--pt-br/java-pt.html.markdown213
-rw-r--r--pt-br/json-pt.html.markdown15
-rw-r--r--pt-br/sass-pt.html.markdown27
-rw-r--r--python.html.markdown20
-rw-r--r--ru-ru/java-ru.html.markdown2
-rw-r--r--ru-ru/javascript-ru.html.markdown2
-rw-r--r--ru-ru/php-ru.html.markdown2
-rw-r--r--ru-ru/python-ru.html.markdown2
-rw-r--r--ruby.html.markdown11
-rw-r--r--swift.html.markdown3
-rw-r--r--tr-tr/brainfuck-tr.html.markdown2
-rw-r--r--tr-tr/c-tr.html.markdown34
-rw-r--r--ua-ua/javascript-ua.html.markdown501
-rw-r--r--visualbasic.html.markdown3
30 files changed, 1866 insertions, 437 deletions
diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown
index 70804a1e..d49ad254 100644
--- a/coldfusion.html.markdown
+++ b/coldfusion.html.markdown
@@ -3,13 +3,17 @@ language: coldfusion
filename: learncoldfusion.cfm
contributors:
- ["Wayne Boka", "http://wboka.github.io"]
+ - ["Kevin Morris", "https://twitter.com/kevinmorris"]
---
ColdFusion is a scripting language for web development.
[Read more here.](http://www.adobe.com/products/coldfusion-family.html)
-```html
+### CFML
+_**C**old**F**usion **M**arkup **L**anguage_
+ColdFusion started as a tag-based language. Almost all functionality is available using tags.
+```html
<em>HTML tags have been provided for output readability</em>
<!--- Comments start with "<!---" and end with "--->" --->
@@ -314,8 +318,13 @@ ColdFusion is a scripting language for web development.
<cfoutput><p>#getWorld()#</p></cfoutput>
```
+### CFScript
+_**C**old**F**usion **S**cript_
+In recent years, the ColdFusion language has added script syntax to mirror tag functionality. When using an up-to-date CF server, almost all functionality is available using scrypt syntax.
+
## Further Reading
The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples.
1. [Coldfusion Reference From Adobe](https://helpx.adobe.com/coldfusion/cfml-reference/topics.html)
+2. [Open Source Documentation](http://cfdocs.org/)
diff --git a/css.html.markdown b/css.html.markdown
index d8f30ca3..8ee4f4b9 100644
--- a/css.html.markdown
+++ b/css.html.markdown
@@ -6,20 +6,21 @@ contributors:
- ["Geoffrey Liu", "https://github.com/g-liu"]
- ["Connor Shea", "https://github.com/connorshea"]
- ["Deepanshu Utkarsh", "https://github.com/duci9y"]
+ - ["Tyler Mumford", "https://tylermumford.com"]
filename: learncss.css
---
-In the early days of the web there were no visual elements, just pure text. But with further development of web browsers, fully visual web pages also became common.
+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 helps maintain separation between the content (HTML) and the look-and-feel of a web page.
+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 lets you target different elements on an HTML page and assign different visual properties to them.
+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 for CSS 2, though CSS 3 is fast becoming popular.
-
-**NOTE:** Because CSS produces visual results, in order to learn it, you need 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
+
```css
/* comments appear inside slash-asterisk, just like this line!
there are no "one-line comments"; this is the only comment style */
@@ -28,7 +29,7 @@ The main focus of this article is on the syntax and some general tips.
## SELECTORS
#################### */
-/* the selector is used to target an element on a page.
+/* the selector is used to target an element on a page. */
selector { property: value; /* more properties...*/ }
/*
@@ -69,7 +70,7 @@ div { }
[otherAttr|='en'] { font-size:smaller; }
-/* You can concatenate different selectors to create a narrower selector. Don't
+/* You can combine different selectors to create a more focused selector. Don't
put spaces between them. */
div.some-class[attr$='ue'] { }
@@ -92,7 +93,7 @@ div.some-parent.class-name { }
.i-am-any-element-before ~ .this-element { }
/* There are some selectors called pseudo classes that can be used to select an
- element when it is in a particular state */
+ element only when it is in a particular state */
/* for example, when the cursor hovers over an element */
selector:hover { }
@@ -103,7 +104,7 @@ selector:visited { }
/* or hasn't been visited */
selected:link { }
-/* or an element in focus */
+/* or an element is in focus */
selected:focus { }
/* any element that is the first child of its parent */
@@ -156,10 +157,10 @@ selector {
color: tomato; /* a named color */
color: rgb(255, 255, 255); /* as rgb values */
color: rgb(10%, 20%, 50%); /* as rgb percentages */
- color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 < a < 1 */
+ color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 <= a <= 1 */
color: transparent; /* equivalent to setting the alpha to 0 */
color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */
- color: hsla(0, 100%, 50%, 0.3); /* as hsla percentages with alpha */
+ 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 */
@@ -194,7 +195,7 @@ 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. Generally, a rule in 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 occuring later in the stylesheet overwrites a previous one.
This process is called cascading, hence the name Cascading Style Sheets.
@@ -238,10 +239,10 @@ Most of the features in CSS 2 (and many in CSS 3) are available across all brows
## Resources
-* To run a quick compatibility check, [CanIUse](http://caniuse.com).
-* CSS Playground [Dabblet](http://dabblet.com/).
-* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS)
-* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/)
+* [CanIUse](http://caniuse.com) (Detailed compatibility info)
+* [Dabblet](http://dabblet.com/) (CSS playground)
+* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) (Tutorials and reference)
+* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) (Reference)
## Further Reading
diff --git a/d.html.markdown b/d.html.markdown
index 80c1dc65..6f3710ab 100644
--- a/d.html.markdown
+++ b/d.html.markdown
@@ -199,8 +199,8 @@ our getter and setter methods, and keep the clean syntax of
accessing members directly!
Other object-oriented goodies at our disposal
-include `interface`s, `abstract class`es,
-and `override`ing methods. D does inheritance just like Java:
+include interfaces, abstract classes,
+and overriding methods. D does inheritance just like Java:
Extend one class, implement as many interfaces as you please.
We've seen D's OOP facilities, but let's switch gears. D offers
@@ -247,7 +247,7 @@ void main() {
// and take advantage of as many cores as we have available.
auto arr = new double[1_000_000];
- // Use an index, and an array element by referece,
+ // Use an index, and an array element by reference,
// and just call parallel on the array!
foreach(i, ref elem; parallel(arr)) {
ref = sqrt(i + 1.0);
diff --git a/de-de/scala-de.html.markdown b/de-de/scala-de.html.markdown
index 7fd299b4..456403a2 100644
--- a/de-de/scala-de.html.markdown
+++ b/de-de/scala-de.html.markdown
@@ -5,6 +5,7 @@ contributors:
- ["Dominic Bou-Samra", "http://dbousamra.github.com"]
- ["Geoff Liu", "http://geoffliu.me"]
- ["Ha-Duong Nguyen", "http://reference-error.org"]
+ - ["Dennis Keller", "github.com/denniskeller"]
translators:
- ["Christian Albrecht", "https://github.com/coastalchief"]
filename: learnscala-de.scala
@@ -16,167 +17,172 @@ für die Java Virtual Machine (JVM), um allgemeine Programmieraufgaben
zu erledigen. Scala hat einen akademischen Hintergrund und wurde an
der EPFL (Lausanne / Schweiz) unter der Leitung von Martin Odersky entwickelt.
-
-# 0. Umgebung einrichten
+```scala
+/*
Scala Umgebung einrichten:
1. Scala binaries herunterladen- http://www.scala-lang.org/downloads
2. Unzip/untar in ein Verzeichnis
3. das bin Unterverzeichnis der `PATH` Umgebungsvariable hinzufügen
4. Mit dem Kommando `scala` wird die REPL gestartet und zeigt als Prompt:
-```
+
scala>
-```
Die REPL (Read-Eval-Print Loop) ist der interaktive Scala Interpreter.
Hier kann man jeden Scala Ausdruck verwenden und das Ergebnis wird direkt
ausgegeben.
Als nächstes beschäftigen wir uns mit ein paar Scala Basics.
+*/
-# 1. Basics
-Einzeilige Kommentare beginnen mit zwei vorwärts Slash
+/////////////////////////////////////////////////
+// 1. Basics
+/////////////////////////////////////////////////
+
+// Einzeilige Kommentare beginnen mit zwei Slashes
/*
- Mehrzeilige Kommentare, werden starten
- mit Slash-Stern und enden mit Stern-Slash
+ Mehrzeilige Kommentare, starten
+ mit einem Slash-Stern und enden mit einem Stern-Slash
*/
// Einen Wert, und eine zusätzliche neue Zeile ausgeben
-```
+
println("Hello world!")
println(10)
-```
+
// Einen Wert, ohne eine zusätzliche neue Zeile ausgeben
-```
+
print("Hello world")
-```
-// Variablen werden entweder mit var oder val deklariert.
-// Deklarationen mit val sind immutable, also unveränderlich
-// Deklarationen mit var sind mutable, also veränderlich
-// Immutability ist gut.
-```
+/*
+ Variablen werden entweder mit var oder val deklariert.
+ Deklarationen mit val sind immutable, also unveränderlich
+ Deklarationen mit var sind mutable, also veränderlich
+ Immutability ist gut.
+*/
val x = 10 // x ist 10
x = 20 // error: reassignment to val
var y = 10
y = 20 // y ist jetzt 20
-```
-Scala ist eine statisch getypte Sprache, auch wenn in dem o.g. Beispiel
+/*
+Scala ist eine statisch getypte Sprache, auch wenn wir in dem o.g. Beispiel
keine Typen an x und y geschrieben haben.
-In Scala ist etwas eingebaut, was sich Type Inference nennt. D.h. das der
-Scala Compiler in den meisten Fällen erraten kann, von welchen Typ eine ist,
-so dass der Typ nicht jedes mal angegeben werden soll.
+In Scala ist etwas eingebaut, was sich Type Inference nennt. Das heißt das der
+Scala Compiler in den meisten Fällen erraten kann, von welchen Typ eine Variable ist,
+so dass der Typ nicht jedes mal angegeben werden muss.
Einen Typ gibt man bei einer Variablendeklaration wie folgt an:
-```
+*/
val z: Int = 10
val a: Double = 1.0
-```
+
// Bei automatischer Umwandlung von Int auf Double wird aus 10 eine 10.0
-```
+
val b: Double = 10
-```
+
// Boolean Werte
-```
+
true
false
-```
+
// Boolean Operationen
-```
+
!true // false
!false // true
true == false // false
10 > 5 // true
-```
+
// Mathematische Operationen sind wie gewohnt
-```
+
1 + 1 // 2
2 - 1 // 1
5 * 3 // 15
6 / 2 // 3
6 / 4 // 1
6.0 / 4 // 1.5
-```
+
// Die Auswertung eines Ausdrucks in der REPL gibt den Typ
// und das Ergebnis zurück.
-```
+
scala> 1 + 7
res29: Int = 8
-```
+/*
Das bedeutet, dass das Resultat der Auswertung von 1 + 7 ein Objekt
von Typ Int ist und einen Wert 0 hat.
"res29" ist ein sequentiell generierter name, um das Ergebnis des
Ausdrucks zu speichern. Dieser Wert kann bei Dir anders sein...
-
+*/
"Scala strings werden in doppelten Anführungszeichen eingeschlossen"
'a' // A Scala Char
// 'Einzeln ge-quotete strings gibt es nicht!' <= This causes an error
// Für Strings gibt es die üblichen Java Methoden
-```
+
"hello world".length
"hello world".substring(2, 6)
"hello world".replace("C", "3")
-```
+
// Zusätzlich gibt es noch extra Scala Methoden
// siehe: scala.collection.immutable.StringOps
-```
+
"hello world".take(5)
"hello world".drop(5)
-```
+
// String interpolation: prefix "s"
-```
+
val n = 45
s"We have $n apples" // => "We have 45 apples"
-```
-// Ausdrücke im innern von interpolierten Strings gibt es auch
-```
+
+// Ausdrücke im Innern von interpolierten Strings gibt es auch
+
val a = Array(11, 9, 6)
val n = 100
s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old."
s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples."
s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4"
-```
+
// Formatierung der interpolierten Strings mit dem prefix "f"
-```
+
f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25"
f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454"
-```
+
// Raw Strings, ignorieren Sonderzeichen.
-```
+
raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r."
-```
+
// Manche Zeichen müssen "escaped" werden, z.B.
// ein doppeltes Anführungszeichen in innern eines Strings.
-```
+
"They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown""
-```
+
// Dreifache Anführungszeichen erlauben es, dass ein String über mehrere Zeilen geht
// und Anführungszeichen enthalten kann.
-```
+
val html = """<form id="daform">
<p>Press belo', Joe</p>
<input type="submit">
</form>"""
-```
-# 2. Funktionen
+
+/////////////////////////////////////////////////
+// 2. Funktionen
+/////////////////////////////////////////////////
// Funktionen werden so definiert
//
@@ -184,74 +190,74 @@ val html = """<form id="daform">
//
// Beachte: Es gibt kein return Schlüsselwort. In Scala ist der letzte Ausdruck
// in einer Funktion der Rückgabewert.
-```
+
def sumOfSquares(x: Int, y: Int): Int = {
val x2 = x * x
val y2 = y * y
x2 + y2
}
-```
+
// Die geschweiften Klammern können weggelassen werden, wenn
// die Funktion nur aus einem einzigen Ausdruck besteht:
-```
+
def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y
-```
+
// Syntax für Funktionsaufrufe:
-```
+
sumOfSquares(3, 4) // => 25
-```
+
// In den meisten Fällen (mit Ausnahme von rekursiven Funktionen), können
// Rückgabetypen auch weggelassen werden, da dieselbe Typ Inference, wie bei
// Variablen, auch bei Funktionen greift:
-```
+
def sq(x: Int) = x * x // Compiler errät, dass der return type Int ist
-```
+
// Funktionen können default parameter haben:
-```
+
def addWithDefault(x: Int, y: Int = 5) = x + y
addWithDefault(1, 2) // => 3
addWithDefault(1) // => 6
-```
+
// Anonyme Funktionen sehen so aus:
-```
+
(x: Int) => x * x
-```
+
// Im Gegensatz zu def bei normalen Funktionen, kann bei anonymen Funktionen
// sogar der Eingabetyp weggelassen werden, wenn der Kontext klar ist.
// Beachte den Typ "Int => Int", dies beschreibt eine Funktion,
// welche Int als Parameter erwartet und Int zurückgibt.
-```
+
val sq: Int => Int = x => x * x
-```
+
// Anonyme Funktionen benutzt man ganz normal:
-```
+
sq(10) // => 100
-```
+
// Wenn ein Parameter einer anonymen Funktion nur einmal verwendet wird,
// bietet Scala einen sehr kurzen Weg diesen Parameter zu benutzen,
// indem die Parameter als Unterstrich "_" in der Parameterreihenfolge
// verwendet werden. Diese anonymen Funktionen werden sehr häufig
// verwendet.
-```
+
val addOne: Int => Int = _ + 1
val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3)
addOne(5) // => 6
weirdSum(2, 4) // => 16
-```
+
// Es gibt einen keyword return in Scala. Allerdings ist seine Verwendung
// nicht immer ratsam und kann fehlerbehaftet sein. "return" gibt nur aus
// dem innersten def, welches den return Ausdruck umgibt, zurück.
// "return" hat keinen Effekt in anonymen Funktionen:
-```
+
def foo(x: Int): Int = {
val anonFunc: Int => Int = { z =>
if (z > 5)
@@ -261,28 +267,30 @@ def foo(x: Int): Int = {
}
anonFunc(x) // Zeile ist der return Wert von foo
}
-```
-# 3. Flow Control
-## Wertebereiche und Schleifen
-```
+/////////////////////////////////////////////////
+// 3. Flow Control
+/////////////////////////////////////////////////
+
+// Wertebereiche und Schleifen
+
1 to 5
val r = 1 to 5
r.foreach(println)
r foreach println
(5 to 1 by -1) foreach (println)
-```
-// Scala ist syntaktisch sehr grosszügig, Semikolons am Zeilenende
+
+// Scala ist syntaktisch sehr großzügig, Semikolons am Zeilenende
// sind optional, beim Aufruf von Methoden können die Punkte
// und Klammern entfallen und Operatoren sind im Grunde austauschbare Methoden
// while Schleife
-```
+
var i = 0
while (i < 10) { println("i " + i); i += 1 }
i // i ausgeben, res3: Int = 10
-```
+
// Beachte: while ist eine Schleife im klassischen Sinne -
// Sie läuft sequentiell ab und verändert die loop-Variable.
@@ -291,28 +299,28 @@ i // i ausgeben, res3: Int = 10
// und zu parellelisieren.
// Ein do while Schleife
-```
+
do {
println("x ist immer noch weniger wie 10")
x += 1
} while (x < 10)
-```
+
// Endrekursionen sind ideomatisch um sich wiederholende
// Dinge in Scala zu lösen. Rekursive Funtionen benötigen explizit einen
// return Typ, der Compiler kann ihn nicht erraten.
// Unit, in diesem Beispiel.
-```
+
def showNumbersInRange(a: Int, b: Int): Unit = {
print(a)
if (a < b)
showNumbersInRange(a + 1, b)
}
showNumbersInRange(1, 14)
-```
-## Conditionals
-```
+
+// Conditionals
+
val x = 10
if (x == 1) println("yeah")
if (x == 10) println("yeah")
@@ -320,186 +328,193 @@ if (x == 11) println("yeah")
if (x == 11) println ("yeah") else println("nay")
println(if (x == 10) "yeah" else "nope")
val text = if (x == 10) "yeah" else "nope"
-```
-# 4. Daten Strukturen (Array, Map, Set, Tuples)
-## Array
-```
+/////////////////////////////////////////////////
+// 4. Daten Strukturen (Array, Map, Set, Tuples)
+/////////////////////////////////////////////////
+
+// Array
+
val a = Array(1, 2, 3, 5, 8, 13)
a(0)
a(3)
a(21) // Exception
-```
-## Map - Speichert Key-Value-Paare
-```
+
+// Map - Speichert Key-Value-Paare
+
val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo")
m("fork")
m("spoon")
m("bottle") // Exception
val safeM = m.withDefaultValue("no lo se")
safeM("bottle")
-```
-## Set - Speichert Unikate, unsortiert (sortiert -> SortedSet)
-```
+
+// Set - Speichert Unikate, unsortiert (sortiert -> SortedSet)
+
val s = Set(1, 3, 7)
s(0) //false
s(1) //true
val s = Set(1,1,3,3,7)
s: scala.collection.immutable.Set[Int] = Set(1, 3, 7)
-```
-## Tuple - Speichert beliebige Daten und "verbindet" sie miteinander
+
+// Tuple - Speichert beliebige Daten und "verbindet" sie miteinander
// Ein Tuple ist keine Collection.
-```
+
(1, 2)
(4, 3, 2)
(1, 2, "three")
(a, 2, "three")
-```
+
// Hier ist der Rückgabewert der Funktion ein Tuple
// Die Funktion gibt das Ergebnis, so wie den Rest zurück.
-```
+
val divideInts = (x: Int, y: Int) => (x / y, x % y)
divideInts(10, 3)
-```
+
// Um die Elemente eines Tuples anzusprechen, benutzt man diese
// Notation: _._n wobei n der index des Elements ist (Index startet bei 1)
-```
+
val d = divideInts(10, 3)
d._1
d._2
-```
-# 5. Objekt Orientierte Programmierung
-Bislang waren alle gezeigten Sprachelemente einfache Ausdrücke, welche zwar
-zum Ausprobieren und Lernen in der REPL gut geeignet sind, jedoch in
-einem Scala file selten alleine zu finden sind.
-Die einzigen Top-Level Konstrukte in Scala sind nämlich:
-- Klassen (classes)
-- Objekte (objects)
-- case classes
-- traits
+/////////////////////////////////////////////////
+// 5. Objektorientierte Programmierung
+/////////////////////////////////////////////////
+
+/*
+ Bislang waren alle gezeigten Sprachelemente einfache Ausdrücke, welche zwar
+ zum Ausprobieren und Lernen in der REPL gut geeignet sind, jedoch in
+ einem Scala file selten alleine zu finden sind.
+ Die einzigen Top-Level Konstrukte in Scala sind nämlich:
+
+ - Klassen (classes)
+ - Objekte (objects)
+ - case classes
+ - traits
-Diesen Sprachelemente wenden wir uns jetzt zu.
+ Diesen Sprachelemente wenden wir uns jetzt zu.
+*/
-## Klassen
+// Klassen
// Zum Erstellen von Objekten benötigt man eine Klasse, wie in vielen
// anderen Sprachen auch.
// erzeugt Klasse mit default Konstruktor
-```
+
class Hund
scala> val t = new Hund
t: Hund = Hund@7103745
-```
+
// Der Konstruktor wird direkt hinter dem Klassennamen deklariert.
-```
+
class Hund(sorte: String)
scala> val t = new Hund("Dackel")
t: Hund = Hund@14be750c
scala> t.sorte //error: value sorte is not a member of Hund
-```
+
// Per val wird aus dem Attribut ein unveränderliches Feld der Klasse
// Per var wird aus dem Attribut ein veränderliches Feld der Klasse
-```
+
class Hund(val sorte: String)
scala> val t = new Hund("Dackel")
t: Hund = Hund@74a85515
scala> t.sorte
res18: String = Dackel
-```
+
// Methoden werden mit def geschrieben
-```
+
def bark = "Woof, woof!"
-```
+
// Felder und Methoden können public, protected und private sein
// default ist public
// private ist nur innerhalb des deklarierten Bereichs sichtbar
-```
+
class Hund {
private def x = ...
def y = ...
}
-```
+
// protected ist nur innerhalb des deklarierten und aller
// erbenden Bereiche sichtbar
-```
+
class Hund {
protected def x = ...
}
class Dackel extends Hund {
// x ist sichtbar
}
-```
-## Object
-Wird ein Objekt ohne das Schlüsselwort "new" instanziert, wird das sog.
-"companion object" aufgerufen. Mit dem "object" Schlüsselwort wird so
-ein Objekt (Typ UND Singleton) erstellt. Damit kann man dann eine Klasse
-benutzen ohne ein Objekt instanziieren zu müssen.
-Ein gültiges companion Objekt einer Klasse ist es aber erst dann, wenn
-es genauso heisst und in derselben Datei wie die Klasse definiert wurde.
-```
+
+// Object
+// Wird ein Objekt ohne das Schlüsselwort "new" instanziert, wird das sog.
+// "companion object" aufgerufen. Mit dem "object" Schlüsselwort wird so
+// ein Objekt (Typ UND Singleton) erstellt. Damit kann man dann eine Klasse
+// benutzen ohne ein Objekt instanziieren zu müssen.
+// Ein gültiges companion Objekt einer Klasse ist es aber erst dann, wenn
+// es genauso heisst und in derselben Datei wie die Klasse definiert wurde.
+
object Hund {
def alleSorten = List("Pitbull", "Dackel", "Retriever")
def createHund(sorte: String) = new Hund(sorte)
}
-```
-## Case classes
-Fallklassen bzw. Case classes sind Klassen die normale Klassen um extra
-Funktionalität erweitern. Mit Case Klassen bekommt man ein paar
-Dinge einfach dazu, ohne sich darum kümmern zu müssen. Z.B.
-ein companion object mit den entsprechenden Methoden,
-Hilfsmethoden wie toString(), equals() und hashCode() und auch noch
-Getter für unsere Attribute (das Angeben von val entfällt dadurch)
-```
+
+// Case classes
+// Fallklassen bzw. Case classes sind Klassen die normale Klassen um extra
+// Funktionalität erweitern. Mit Case Klassen bekommt man ein paar
+// Dinge einfach dazu, ohne sich darum kümmern zu müssen. Z.B.
+// ein companion object mit den entsprechenden Methoden,
+// Hilfsmethoden wie toString(), equals() und hashCode() und auch noch
+// Getter für unsere Attribute (das Angeben von val entfällt dadurch)
+
class Person(val name: String)
class Hund(val sorte: String, val farbe: String, val halter: Person)
-```
+
// Es genügt das Schlüsselwort case vor die Klasse zu schreiben.
-```
+
case class Person(name: String)
case class Hund(sorte: String, farbe: String, halter: Person)
-```
+
// Für neue Instanzen brauch man kein "new"
-```
+
val dackel = Hund("dackel", "grau", Person("peter"))
val dogge = Hund("dogge", "grau", Person("peter"))
-```
+
// getter
-```
+
dackel.halter // => Person = Person(peter)
-```
+
// equals
-```
+
dogge == dackel // => false
-```
+
// copy
// otherGeorge == Person("george", "9876")
-```
+
val otherGeorge = george.copy(phoneNumber = "9876")
-```
-## Traits
-Ähnlich wie Java interfaces, definiert man mit traits einen Objekttyp
-und Methodensignaturen. Scala erlaubt allerdings das teilweise
-implementieren dieser Methoden. Konstruktorparameter sind nicht erlaubt.
-Traits können von anderen Traits oder Klassen erben, aber nur von
-parameterlosen.
-```
+
+// Traits
+// Ähnlich wie Java interfaces, definiert man mit traits einen Objekttyp
+// und Methodensignaturen. Scala erlaubt allerdings das teilweise
+// implementieren dieser Methoden. Konstruktorparameter sind nicht erlaubt.
+// Traits können von anderen Traits oder Klassen erben, aber nur von
+// parameterlosen.
+
trait Hund {
def sorte: String
def farbe: String
@@ -511,9 +526,9 @@ class Bernhardiner extends Hund{
val farbe = "braun"
def beissen = false
}
-```
+
-```
+
scala> b
res0: Bernhardiner = Bernhardiner@3e57cd70
scala> b.sorte
@@ -522,10 +537,10 @@ scala> b.bellen
res2: Boolean = true
scala> b.beissen
res3: Boolean = false
-```
+
// Traits können auch via Mixins (Schlüsselwort "with") eingebunden werden
-```
+
trait Bellen {
def bellen: String = "Woof"
}
@@ -541,25 +556,27 @@ scala> val b = new Bernhardiner
b: Bernhardiner = Bernhardiner@7b69c6ba
scala> b.bellen
res0: String = Woof
-```
-# 6. Pattern Matching
-Pattern matching in Scala ist ein sehr nützliches und wesentlich
-mächtigeres Feature als Vergleichsfunktionen in Java. In Scala
-benötigt ein case Statement kein "break", ein fall-through gibt es nicht.
-Mehrere Überprüfungen können mit einem Statement gemacht werden.
-Pattern matching wird mit dem Schlüsselwort "match" gemacht.
-```
+/////////////////////////////////////////////////
+// 6. Pattern Matching
+/////////////////////////////////////////////////
+
+// Pattern matching in Scala ist ein sehr nützliches und wesentlich
+// mächtigeres Feature als Vergleichsfunktionen in Java. In Scala
+// benötigt ein case Statement kein "break", ein fall-through gibt es nicht.
+// Mehrere Überprüfungen können mit einem Statement gemacht werden.
+// Pattern matching wird mit dem Schlüsselwort "match" gemacht.
+
val x = ...
x match {
case 2 =>
case 3 =>
case _ =>
}
-```
+
// Pattern Matching kann auf beliebige Typen prüfen
-```
+
val any: Any = ...
val gleicht = any match {
case 2 | 3 | 5 => "Zahl"
@@ -568,19 +585,19 @@ val gleicht = any match {
case 45.35 => "Double"
case _ => "Unbekannt"
}
-```
+
// und auf Objektgleichheit
-```
+
def matchPerson(person: Person): String = person match {
case Person("George", nummer) => "George! Die Nummer ist " + number
case Person("Kate", nummer) => "Kate! Die Nummer ist " + nummer
case Person(name, nummer) => "Irgendjemand: " + name + ", Telefon: " + nummer
}
-```
+
// Und viele mehr...
-```
+
val email = "(.*)@(.*)".r // regex
def matchEverything(obj: Any): String = obj match {
// Werte:
@@ -600,18 +617,21 @@ def matchEverything(obj: Any): String = obj match {
// Patterns kann man ineinander schachteln:
case List(List((1, 2, "YAY"))) => "Got a list of list of tuple"
}
-```
+
// Jedes Objekt mit einer "unapply" Methode kann per Pattern geprüft werden
// Ganze Funktionen können Patterns sein
-```
+
val patternFunc: Person => String = {
case Person("George", number) => s"George's number: $number"
case Person(name, number) => s"Random person's number: $number"
}
-```
-# 7. Higher-order functions
+
+/////////////////////////////////////////////////
+// 37. Higher-order functions
+/////////////////////////////////////////////////
+
Scala erlaubt, das Methoden und Funktion wiederum Funtionen und Methoden
als Aufrufparameter oder Return Wert verwenden. Diese Methoden heissen
higher-order functions
@@ -621,116 +641,117 @@ Nennenswerte sind:
"filter", "map", "reduce", "foldLeft"/"foldRight", "exists", "forall"
## List
-```
+
def isGleichVier(a:Int) = a == 4
val list = List(1, 2, 3, 4)
val resultExists4 = list.exists(isEqualToFour)
-```
+
## map
// map nimmt eine Funktion und führt sie auf jedem Element aus und erzeugt
// eine neue Liste
// Funktion erwartet ein Int und returned ein Int
-```
+
val add10: Int => Int = _ + 10
-```
+
// add10 wird auf jedes Element angewendet
-```
+
List(1, 2, 3) map add10 // => List(11, 12, 13)
-```
+
// Anonyme Funktionen können anstatt definierter Funktionen verwendet werden
-```
+
List(1, 2, 3) map (x => x + 10)
-```
+
// Der Unterstrich wird anstelle eines Parameters einer anonymen Funktion
// verwendet. Er wird an die Variable gebunden.
-```
+
List(1, 2, 3) map (_ + 10)
-```
+
// Wenn der anonyme Block und die Funtion beide EIN Argument erwarten,
// kann sogar der Unterstrich weggelassen werden.
-```
+
List("Dom", "Bob", "Natalia") foreach println
-```
-## filter
+
+// filter
// filter nimmt ein Prädikat (eine Funktion von A -> Boolean) und findet
// alle Elemente die auf das Prädikat passen
-```
+
List(1, 2, 3) filter (_ > 2) // => List(3)
case class Person(name: String, age: Int)
List(
Person(name = "Dom", age = 23),
Person(name = "Bob", age = 30)
).filter(_.age > 25) // List(Person("Bob", 30))
-```
-## reduce
+
+// reduce
// reduce nimmt zwei Elemente und kombiniert sie zu einem Element,
// und zwar solange bis nur noch ein Element da ist.
-## foreach
+// foreach
// foreach gibt es für einige Collections
-```
+
val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100)
aListOfNumbers foreach (x => println(x))
aListOfNumbers foreach println
-```
-## For comprehensions
+
+// For comprehensions
// Eine for-comprehension definiert eine Beziehung zwischen zwei Datensets.
// Dies ist keine for-Schleife.
-```
+
for { n <- s } yield sq(n)
val nSquared2 = for { n <- s } yield sq(n)
for { n <- nSquared2 if n < 10 } yield n
for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared
-```
+
/////////////////////////////////////////////////
-# 8. Implicits
+// 8. Implicits
/////////////////////////////////////////////////
-**ACHTUNG:**
-Implicits sind ein sehr mächtiges Sprachfeature von Scala. Es sehr einfach
-sie falsch zu benutzen und Anfänger sollten sie mit Vorsicht oder am
-besten erst dann benutzen, wenn man versteht wie sie funktionieren.
-Dieses Tutorial enthält Implicits, da sie in Scala an jeder Stelle
-vorkommen und man auch mit einer Lib die Implicits benutzt nichts sinnvolles
-machen kann.
-Hier soll ein Grundverständnis geschaffen werden, wie sie funktionieren.
+// **ACHTUNG:**
+// Implicits sind ein sehr mächtiges Sprachfeature von Scala.
+// Es sehr einfach
+// sie falsch zu benutzen und Anfänger sollten sie mit Vorsicht oder am
+// besten erst dann benutzen, wenn man versteht wie sie funktionieren.
+// Dieses Tutorial enthält Implicits, da sie in Scala an jeder Stelle
+// vorkommen und man auch mit einer Lib die Implicits benutzt nichts sinnvolles
+// machen kann.
+// Hier soll ein Grundverständnis geschaffen werden, wie sie funktionieren.
// Mit dem Schlüsselwort implicit können Methoden, Werte, Funktion, Objekte
// zu "implicit Methods" werden.
-```
+
implicit val myImplicitInt = 100
implicit def myImplicitFunction(sorte: String) = new Hund("Golden " + sorte)
-```
+
// implicit ändert nicht das Verhalten eines Wertes oder einer Funktion
-```
+
myImplicitInt + 2 // => 102
myImplicitFunction("Pitbull").sorte // => "Golden Pitbull"
-```
+
// Der Unterschied ist, dass diese Werte ausgewählt werden können, wenn ein
// anderer Codeteil einen implicit Wert benötigt, zum Beispiel innerhalb von
// implicit Funktionsparametern
// Diese Funktion hat zwei Parameter: einen normalen und einen implicit
-```
+
def sendGreetings(toWhom: String)(implicit howMany: Int) =
s"Hello $toWhom, $howMany blessings to you and yours!"
-```
+
// Werden beide Parameter gefüllt, verhält sich die Funktion wie erwartet
-```
+
sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!"
-```
+
// Wird der implicit Parameter jedoch weggelassen, wird ein anderer
// implicit Wert vom gleichen Typ genommen. Der Compiler sucht im
@@ -739,66 +760,69 @@ sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!
// geforderten Typ konvertieren kann.
// Hier also: "myImplicitInt", da ein Int gesucht wird
-```
+
sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!"
-```
+
// bzw. "myImplicitFunction"
// Der String wird erst mit Hilfe der Funktion in Hund konvertiert, und
// dann wird die Methode aufgerufen
-```
+
"Retriever".sorte // => "Golden Retriever"
-```
-# 9. Misc
-## Importe
-```
+
+/////////////////////////////////////////////////
+// 19. Misc
+/////////////////////////////////////////////////
+// Importe
+
import scala.collection.immutable.List
-```
+
// Importiere alle Unterpackages
-```
+
import scala.collection.immutable._
-```
+
// Importiere verschiedene Klassen mit einem Statement
-```
+
import scala.collection.immutable.{List, Map}
-```
+
// Einen Import kann man mit '=>' umbenennen
-```
+
import scala.collection.immutable.{List => ImmutableList}
-```
+
// Importiere alle Klasses, mit Ausnahem von....
// Hier ohne: Map and Set:
-```
+
import scala.collection.immutable.{Map => _, Set => _, _}
-```
-## Main
-```
+
+// Main
+
object Application {
def main(args: Array[String]): Unit = {
- // stuff goes here.
+ // Sachen kommen hierhin
}
}
-```
-## I/O
+
+// I/O
// Eine Datei Zeile für Zeile lesen
-```
+
import scala.io.Source
for(line <- Source.fromFile("myfile.txt").getLines())
println(line)
-```
+
// Eine Datei schreiben
-```
+
val writer = new PrintWriter("myfile.txt")
writer.write("Schreibe Zeile" + util.Properties.lineSeparator)
writer.write("Und noch eine Zeile" + util.Properties.lineSeparator)
writer.close()
+
```
## Weiterführende Hinweise
diff --git a/edn.html.markdown b/edn.html.markdown
index 655c20f1..0a0dc9b5 100644
--- a/edn.html.markdown
+++ b/edn.html.markdown
@@ -16,7 +16,7 @@ will see how it is extended later on.
```Clojure
; Comments start with a semicolon.
-; Anythng after the semicolon is ignored.
+; Anything after the semicolon is ignored.
;;;;;;;;;;;;;;;;;;;
;;; Basic Types ;;;
diff --git a/fsharp.html.markdown b/fsharp.html.markdown
index b5c47ed7..d63b9f1d 100644
--- a/fsharp.html.markdown
+++ b/fsharp.html.markdown
@@ -31,14 +31,14 @@ If you want to try out the code below, you can go to [tryfsharp.org](http://www.
// The "let" keyword defines an (immutable) value
let myInt = 5
let myFloat = 3.14
-let myString = "hello" //note that no types needed
+let myString = "hello" // note that no types needed
// ------ Lists ------
-let twoToFive = [2;3;4;5] // Square brackets create a list with
+let twoToFive = [2; 3; 4; 5] // Square brackets create a list with
// semicolon delimiters.
let oneToFive = 1 :: twoToFive // :: creates list with new 1st element
-// The result is [1;2;3;4;5]
-let zeroToFive = [0;1] @ twoToFive // @ concats two lists
+// The result is [1; 2; 3; 4; 5]
+let zeroToFive = [0; 1] @ twoToFive // @ concats two lists
// IMPORTANT: commas are never used as delimiters, only semicolons!
@@ -53,7 +53,7 @@ add 2 3 // Now run the function.
// to define a multiline function, just use indents. No semicolons needed.
let evens list =
- let isEven x = x%2 = 0 // Define "isEven" as a sub function
+ let isEven x = x % 2 = 0 // Define "isEven" as a sub function
List.filter isEven list // List.filter is a library function
// with two parameters: a boolean function
// and a list to work on
@@ -75,7 +75,7 @@ let sumOfSquaresTo100piped =
// you can define lambdas (anonymous functions) using the "fun" keyword
let sumOfSquaresTo100withFun =
- [1..100] |> List.map (fun x -> x*x) |> List.sum
+ [1..100] |> List.map (fun x -> x * x) |> List.sum
// In F# there is no "return" keyword. A function always
// returns the value of the last expression used.
@@ -109,7 +109,7 @@ optionPatternMatch invalidValue
// The printf/printfn functions are similar to the
// Console.Write/WriteLine functions in C#.
printfn "Printing an int %i, a float %f, a bool %b" 1 2.0 true
-printfn "A string %s, and something generic %A" "hello" [1;2;3;4]
+printfn "A string %s, and something generic %A" "hello" [1; 2; 3; 4]
// There are also sprintf/sprintfn functions for formatting data
// into a string, similar to String.Format in C#.
@@ -131,19 +131,19 @@ module FunctionExamples =
// basic usage of a function
let a = add 1 2
- printfn "1+2 = %i" a
+ printfn "1 + 2 = %i" a
// partial application to "bake in" parameters
let add42 = add 42
let b = add42 1
- printfn "42+1 = %i" b
+ printfn "42 + 1 = %i" b
// composition to combine functions
let add1 = add 1
let add2 = add 2
let add3 = add1 >> add2
let c = add3 7
- printfn "3+7 = %i" c
+ printfn "3 + 7 = %i" c
// higher order functions
[1..10] |> List.map add3 |> printfn "new list is %A"
@@ -151,7 +151,7 @@ module FunctionExamples =
// lists of functions, and more
let add6 = [add1; add2; add3] |> List.reduce (>>)
let d = add6 7
- printfn "1+2+3+7 = %i" d
+ printfn "1 + 2 + 3 + 7 = %i" d
// ================================================
// Lists and collection
@@ -168,12 +168,12 @@ module FunctionExamples =
module ListExamples =
// lists use square brackets
- let list1 = ["a";"b"]
+ let list1 = ["a"; "b"]
let list2 = "c" :: list1 // :: is prepending
let list3 = list1 @ list2 // @ is concat
// list comprehensions (aka generators)
- let squares = [for i in 1..10 do yield i*i]
+ let squares = [for i in 1..10 do yield i * i]
// prime number generator
let rec sieve = function
@@ -190,8 +190,8 @@ module ListExamples =
| [first; second] -> printfn "list is %A and %A" first second
| _ -> printfn "the list has more than two elements"
- listMatcher [1;2;3;4]
- listMatcher [1;2]
+ listMatcher [1; 2; 3; 4]
+ listMatcher [1; 2]
listMatcher [1]
listMatcher []
@@ -219,7 +219,7 @@ module ListExamples =
module ArrayExamples =
// arrays use square brackets with bar
- let array1 = [| "a";"b" |]
+ let array1 = [| "a"; "b" |]
let first = array1.[0] // indexed access using dot
// pattern matching for arrays is same as for lists
@@ -230,13 +230,13 @@ module ArrayExamples =
| [| first; second |] -> printfn "array is %A and %A" first second
| _ -> printfn "the array has more than two elements"
- arrayMatcher [| 1;2;3;4 |]
+ arrayMatcher [| 1; 2; 3; 4 |]
// Standard library functions just as for List
[| 1..10 |]
- |> Array.map (fun i -> i+3)
- |> Array.filter (fun i -> i%2 = 0)
+ |> Array.map (fun i -> i + 3)
+ |> Array.filter (fun i -> i % 2 = 0)
|> Array.iter (printfn "value is %i. ")
@@ -255,7 +255,7 @@ module SequenceExamples =
yield! [5..10]
yield! seq {
for i in 1..10 do
- if i%2 = 0 then yield i }}
+ if i % 2 = 0 then yield i }}
// test
strange |> Seq.toList
@@ -280,11 +280,11 @@ module DataTypeExamples =
// Tuples are quick 'n easy anonymous types
// -- Use a comma to create a tuple
- let twoTuple = 1,2
- let threeTuple = "a",2,true
+ let twoTuple = 1, 2
+ let threeTuple = "a", 2, true
// Pattern match to unpack
- let x,y = twoTuple //sets x=1 y=2
+ let x, y = twoTuple // sets x = 1, y = 2
// ------------------------------------
// Record types have named fields
@@ -297,7 +297,7 @@ module DataTypeExamples =
let person1 = {First="John"; Last="Doe"}
// Pattern match to unpack
- let {First=first} = person1 //sets first="John"
+ let {First = first} = person1 // sets first="John"
// ------------------------------------
// Union types (aka variants) have a set of choices
@@ -331,7 +331,7 @@ module DataTypeExamples =
| Worker of Person
| Manager of Employee list
- let jdoe = {First="John";Last="Doe"}
+ let jdoe = {First="John"; Last="Doe"}
let worker = Worker jdoe
// ------------------------------------
@@ -383,8 +383,8 @@ module DataTypeExamples =
type Rank = Two | Three | Four | Five | Six | Seven | Eight
| Nine | Ten | Jack | Queen | King | Ace
- let hand = [ Club,Ace; Heart,Three; Heart,Ace;
- Spade,Jack; Diamond,Two; Diamond,Ace ]
+ let hand = [ Club, Ace; Heart, Three; Heart, Ace;
+ Spade, Jack; Diamond, Two; Diamond, Ace ]
// sorting
List.sort hand |> printfn "sorted hand is (low to high) %A"
@@ -419,7 +419,7 @@ module ActivePatternExamples =
| _ -> printfn "%c is something else" ch
// print a list
- ['a';'b';'1';' ';'-';'c'] |> List.iter printChar
+ ['a'; 'b'; '1'; ' '; '-'; 'c'] |> List.iter printChar
// -----------------------------------
// FizzBuzz using active patterns
@@ -479,7 +479,7 @@ module AlgorithmExamples =
List.concat [smallerElements; [firstElem]; largerElements]
// test
- sort [1;5;23;18;9;1;3] |> printfn "Sorted = %A"
+ sort [1; 5; 23; 18; 9; 1; 3] |> printfn "Sorted = %A"
// ================================================
// Asynchronous Code
@@ -536,7 +536,7 @@ module NetCompatibilityExamples =
// ------- work with existing library functions -------
- let (i1success,i1) = System.Int32.TryParse("123");
+ let (i1success, i1) = System.Int32.TryParse("123");
if i1success then printfn "parsed as %i" i1 else printfn "parse failed"
// ------- Implement interfaces on the fly! -------
@@ -570,12 +570,12 @@ module NetCompatibilityExamples =
// abstract base class with virtual methods
[<AbstractClass>]
type Shape() =
- //readonly properties
+ // readonly properties
abstract member Width : int with get
abstract member Height : int with get
- //non-virtual method
+ // non-virtual method
member this.BoundingArea = this.Height * this.Width
- //virtual method with base implementation
+ // virtual method with base implementation
abstract member Print : unit -> unit
default this.Print () = printfn "I'm a shape"
@@ -586,19 +586,19 @@ module NetCompatibilityExamples =
override this.Height = y
override this.Print () = printfn "I'm a Rectangle"
- //test
- let r = Rectangle(2,3)
+ // test
+ let r = Rectangle(2, 3)
printfn "The width is %i" r.Width
printfn "The area is %i" r.BoundingArea
r.Print()
// ------- extension methods -------
- //Just as in C#, F# can extend existing classes with extension methods.
+ // Just as in C#, F# can extend existing classes with extension methods.
type System.String with
member this.StartsWithA = this.StartsWith "A"
- //test
+ // test
let s = "Alice"
printfn "'%s' starts with an 'A' = %A" s s.StartsWithA
diff --git a/git.html.markdown b/git.html.markdown
index bedc9853..e7ca07d6 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Leo Rudberg" , "http://github.com/LOZORD"]
- ["Betsy Lorton" , "http://github.com/schbetsy"]
- ["Bruno Volcov", "http://github.com/volcov"]
+ - ["Andrew Taylor", "http://github.com/andrewjt71"]
filename: LearnGit.txt
---
@@ -333,6 +334,9 @@ $ git log --oneline
# Show merge commits only
$ git log --merges
+
+# Show all commits represented by an ASCII graph
+$ git log --graph
```
### merge
@@ -499,6 +503,16 @@ $ git reset 31f2bb1
# after the specified commit).
$ git reset --hard 31f2bb1
```
+### revert
+
+Revert can be used to undo a commit. It should not be confused with reset which restores
+the state of a project to a previous point. Revert will add a new commit which is the
+inverse of the specified commit, thus reverting it.
+
+```bash
+# Revert a specified commit
+$ git revert <commit>
+```
### rm
diff --git a/java.html.markdown b/java.html.markdown
index 1813f81c..84978ecc 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -128,7 +128,7 @@ public class LearnJava {
//
// BigInteger can be initialized using an array of bytes or a string.
- BigInteger fooBigInteger = new BigDecimal(fooByteArray);
+ BigInteger fooBigInteger = new BigInteger(fooByteArray);
// BigDecimal - Immutable, arbitrary-precision signed decimal number
@@ -144,7 +144,12 @@ public class LearnJava {
// or by initializing the unscaled value (BigInteger) and scale (int).
BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt);
-
+
+ // Be wary of the constructor that takes a float or double as
+ // the inaccuracy of the float/double will be copied in BigDecimal.
+ // Prefer the String constructor when you need an exact value.
+
+ BigDecimal tenCents = new BigDecimal("0.1");
// Strings
@@ -207,8 +212,8 @@ public class LearnJava {
System.out.println("1+2 = " + (i1 + i2)); // => 3
System.out.println("2-1 = " + (i2 - i1)); // => 1
System.out.println("2*1 = " + (i2 * i1)); // => 2
- System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down)
- System.out.println("1/2 = " + (i1 / (i2*1.0))); // => 0.5
+ System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns an int)
+ System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5
// Modulo
System.out.println("11%3 = "+(11 % 3)); // => 2
@@ -416,7 +421,7 @@ public class LearnJava {
// easier way, by using something that is called Double Brace
// Initialization.
- private static final Set<String> COUNTRIES = HashSet<String>() {{
+ private static final Set<String> COUNTRIES = new HashSet<String>() {{
add("DENMARK");
add("SWEDEN");
add("FINLAND");
@@ -701,10 +706,12 @@ public abstract class Mammal()
// Enum Type
//
-// An enum type is a special data type that enables for a variable to be a set of predefined constants. The // variable must be equal to one of the values that have been predefined for it.
-// Because they are constants, the names of an enum type's fields are in uppercase letters.
-// In the Java programming language, you define an enum type by using the enum keyword. For example, you would
-// specify a days-of-the-week enum type as:
+// An enum type is a special data type that enables for a variable to be a set
+// of predefined constants. The variable must be equal to one of the values that
+// have been predefined for it. Because they are constants, the names of an enum
+// type's fields are in uppercase letters. In the Java programming language, you
+// define an enum type by using the enum keyword. For example, you would specify
+// a days-of-the-week enum type as:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
diff --git a/make.html.markdown b/make.html.markdown
index 563139d1..e8cfd2b5 100644
--- a/make.html.markdown
+++ b/make.html.markdown
@@ -234,10 +234,8 @@ bar = 'hello'
endif
```
-
### More Resources
+ [gnu make documentation](https://www.gnu.org/software/make/manual/)
+ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/)
+ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)
-
diff --git a/markdown.html.markdown b/markdown.html.markdown
index 2333110f..b956a5f2 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -11,7 +11,7 @@ Give me as much feedback as you want! / Feel free to fork and pull request!
```markdown
-<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown, that
+<!-- Markdown is a superset of HTML, so any HTML file is valid 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
@@ -21,9 +21,9 @@ element's contents. -->
guide will attempt to clarify when features are universal or when they are
specific to a certain parser. -->
-<!-- Headers -->
+<!-- Headings -->
<!-- You can create HTML elements <h1> through <h6> easily by prepending the
-text you want to be in that element by a number of hashes (#) -->
+text you want to be in that element by a number of hashes (#). -->
# This is an <h1>
## This is an <h2>
### This is an <h3>
@@ -31,7 +31,7 @@ text you want to be in that element by a number of hashes (#) -->
##### This is an <h5>
###### This is an <h6>
-<!-- Markdown also provides us with two alternative ways of indicating h1 and h2 -->
+<!-- Markdown also provides us with two alternative ways of indicating h1 and h2. -->
This is an h1
=============
@@ -39,7 +39,7 @@ This is an h2
-------------
<!-- Simple text styles -->
-<!-- Text can be easily styled as italic or bold using markdown -->
+<!-- Text can be easily styled as italic or bold using markdown. -->
*This text is in italics.*
_And so is this text._
@@ -85,7 +85,7 @@ There's a <br /> above me!
> How neat is that?
<!-- Lists -->
-<!-- Unordered lists can be made using asterisks, pluses, or hyphens -->
+<!-- Unordered lists can be made using asterisks, pluses, or hyphens. -->
* Item
* Item
@@ -103,21 +103,21 @@ or
- Item
- One last item
-<!-- Ordered lists are done with a number followed by a period -->
+<!-- Ordered lists are done with a number followed by a period. -->
1. Item one
2. Item two
3. Item three
<!-- You don't even have to label the items correctly and markdown will still
-render the numbers in order, but this may not be a good idea -->
+render the numbers in order, but this may not be a good idea. -->
1. Item one
1. Item two
1. Item three
<!-- (This renders the same as the above example) -->
-<!-- You can also use sublists -->
+<!-- You can also use sublists. -->
1. Item one
2. Item two
@@ -136,13 +136,13 @@ This checkbox below will be a checked HTML checkbox.
<!-- Code blocks -->
<!-- You can indicate a code block (which uses the <code> element) by indenting
-a line with four spaces or a tab -->
+a line with four spaces or a tab. -->
This is code
So is this
<!-- You can also re-tab (or add an additional four spaces) for indentation
-inside your code -->
+inside your code. -->
my_array.each do |item|
puts item
@@ -152,7 +152,7 @@ inside your code -->
John didn't even know what the `go_to()` function did!
-<!-- In Github Flavored Markdown, you can use a special syntax for code -->
+<!-- In Github Flavored Markdown, you can use a special syntax for code. -->
\`\`\`ruby <!-- except remove those backslashes when you do this, just ```ruby ! -->
def foobar
@@ -174,11 +174,11 @@ with or without spaces. -->
<!-- Links -->
<!-- One of the best things about markdown is how easy it is to make links. Put
-the text to display in hard brackets [] followed by the url in parentheses () -->
+the text to display in hard brackets [] followed by the url in parentheses (). -->
[Click me!](http://test.com/)
-<!-- You can also add a link title using quotes inside the parentheses -->
+<!-- You can also add a link title using quotes inside the parentheses. -->
[Click me!](http://test.com/ "Link to Test.com")
@@ -186,7 +186,7 @@ the text to display in hard brackets [] followed by the url in parentheses () --
[Go to music](/music/).
-<!-- Markdown also supports reference style links -->
+<!-- Markdown also supports reference style links. -->
[Click this link][link1] for more info about it!
[Also check out this link][foobar] if you want to.
@@ -198,7 +198,7 @@ the text to display in hard brackets [] followed by the url in parentheses () --
entirely. The references can be anywhere in your document and the reference IDs
can be anything so long as they are unique. -->
-<!-- There is also "implicit naming" which lets you use the link text as the id -->
+<!-- There is also "implicit naming" which lets you use the link text as the id. -->
[This][] is a link.
@@ -211,7 +211,7 @@ can be anything so long as they are unique. -->
![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title")
-<!-- And reference style works as expected -->
+<!-- And reference style works as expected. -->
![This is the alt-attribute.][myimage]
@@ -233,7 +233,7 @@ I want to type *this text surrounded by asterisks* but I don't want it to be
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. -->
Your computer crashed? Try sending a
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
diff --git a/matlab.html.markdown b/matlab.html.markdown
index ad42d9a9..9d78978e 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -123,6 +123,7 @@ x(2:end) % ans = 32 53 7 1
x = [4; 32; 53; 7; 1] % Column vector
x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
+x = [1:2:10] % Increment by 2, i.e. x = 1 3 5 7 9
% Matrices
A = [1 2 3; 4 5 6; 7 8 9]
@@ -205,6 +206,8 @@ transpose(A) % Transpose the matrix, which is the same as:
A one
ctranspose(A) % Hermitian transpose the matrix
% (the transpose, followed by taking complex conjugate of each element)
+A' % Concise version of complex transpose
+A.' % Concise version of transpose (without taking complex conjugate)
@@ -254,6 +257,8 @@ axis equal % Set aspect ratio so data units are the same in every direction
scatter(x, y); % Scatter-plot
hist(x); % Histogram
+stem(x); % Plot values as stems, useful for displaying discrete data
+bar(x); % Plot bar graph
z = sin(x);
plot3(x,y,z); % 3D line plot
@@ -400,7 +405,7 @@ exp(x)
sqrt(x)
log(x)
log10(x)
-abs(x)
+abs(x) %If x is complex, returns magnitude
min(x)
max(x)
ceil(x)
@@ -411,6 +416,14 @@ rand % Uniformly distributed pseudorandom numbers
randi % Uniformly distributed pseudorandom integers
randn % Normally distributed pseudorandom numbers
+%Complex math operations
+abs(x) % Magnitude of complex variable x
+phase(x) % Phase (or angle) of complex variable x
+real(x) % Returns the real part of x (i.e returns a if x = a +jb)
+imag(x) % Returns the imaginary part of x (i.e returns b if x = a+jb)
+conj(x) % Returns the complex conjugate
+
+
% Common constants
pi
NaN
@@ -465,6 +478,9 @@ median % median value
mean % mean value
std % standard deviation
perms(x) % list all permutations of elements of x
+find(x) % Finds all non-zero elements of x and returns their indexes, can use comparison operators,
+ % i.e. find( x == 3 ) returns indexes of elements that are equal to 3
+ % i.e. find( x >= 3 ) returns indexes of elements greater than or equal to 3
% Classes
diff --git a/ms-my/javascript-my.html.markdown b/ms-my/javascript-my.html.markdown
new file mode 100644
index 00000000..90e37133
--- /dev/null
+++ b/ms-my/javascript-my.html.markdown
@@ -0,0 +1,588 @@
+---
+language: javascript
+contributors:
+ - ["Adam Brenecki", "http://adam.brenecki.id.au"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
+filename: javascript-ms.js
+translators:
+ - ["abdalim", "https://github.com/abdalim"]
+lang: ms-my
+---
+
+Javascript dicipta oleh Brendan Eich dari Netscape pada 1995. Pada awalnya, ia
+dicipta sebagai bahasa skrip yang ringkas untuk laman web, melengkapi penggunaan
+Java untuk aplikasi web yang lebih rumit, namun begitu, integrasi rapat pada
+halaman web dan sokongan tersedia dalam pelayar web telah menyebabkan ia menjadi
+lebih kerap digunakan berbanding Java pada bahagian hadapan laman web.
+
+Namun begitu, Javascript tidak terhad pada pelayar web; Node.js, sebuah projek
+yang menyediakan 'runtime' berdiri sendiri untuk enjin V8 Google Chrome sedang
+kian mendapat sambutan yang hangat.
+
+```js
+// Komentar adalah seperti dalam C. Komentar sebaris bermula dengan dua sengkang
+/* dan komentar banyak baris bermula dengan sengkang-bintang
+ dan berakhir dengan bintang-sengkang */
+
+// Pernyataan boleh ditamatkan dengan ';'
+doStuff();
+
+// ... tetapi ia tidak wajib, kerana koma bertitik secara automatik akan
+// dimasukkan dimana tempat yang ada baris baru, kecuali dalam kes - kes
+// tertentu.
+doStuff()
+
+// Disebabkan kes - kes itu boleh menyebabkan hasil yang tidak diduga, kami
+// akan sentiasa menggunakan koma bertitik dalam panduan ini.
+
+///////////////////////////////////
+// 1. Nombor, String dan Operator
+
+// Javascript mempunyai satu jenis nombor (iaitu 64-bit IEEE 754 double).
+// Double mempunyai 52-bit mantissa, iaitu ia cukup untuk menyimpan integer
+// sehingga 9✕10¹⁵ secara tepatnya.
+3; // = 3
+1.5; // = 1.5
+
+// Sebahagian aritmetic asas berfungsi seperti yang anda jangkakan.
+1 + 1; // = 2
+0.1 + 0.2; // = 0.30000000000000004
+8 - 1; // = 7
+10 * 2; // = 20
+35 / 5; // = 7
+
+// Termasuk pembahagian tidak rata.
+5 / 2; // = 2.5
+
+// Dan pembahagian modulo.
+10 % 2; // = 0
+30 % 4; // = 2
+18.5 % 7; // = 4.5
+
+// Operasi bitwise juga boleh digunakan; bila anda melakukan operasi bitwise,
+// float anda akan ditukarkan kepada int bertanda *sehingga* 32 bit.
+1 << 2; // = 4
+
+// Keutamaan ditekankan menggunakan kurungan.
+(1 + 3) * 2; // = 8
+
+// Terdapat tiga nilai nombor-tidak-nyata istimewa
+Infinity; // hasil operasi seperti 1/0
+-Infinity; // hasil operasi seperti -1/0
+NaN; // hasil operasi seperti 0/0, bermaksud 'Bukan Sebuah Nombor'
+
+// Terdapat juga jenis boolean
+true;
+false;
+
+// Talian dicipta dengan ' atau ''.
+'abc';
+"Hello, world";
+
+// Penafian menggunakan simbol !
+!true; // = tidak benar
+!false; // = benar
+
+// Sama ialah ===
+1 === 1; // = benar
+2 === 1; // = tidak benar
+
+// Tidak sama ialah !==
+1 !== 1; // = tidak benar
+2 !== 1; // = benar
+
+// Lagi perbandingan
+1 < 10; // = benar
+1 > 10; // = tidak benar
+2 <= 2; // = benar
+2 >= 2; // = benar
+
+// Talian disambungkan dengan +
+"Hello " + "world!"; // = "Hello world!"
+
+// dan dibandingkan dengan < dan >
+"a" < "b"; // = benar
+
+// Paksaan jenis dilakukan untuk perbandingan menggunakan dua sama dengan...
+"5" == 5; // = benar
+null == undefined; // = benar
+
+// ...melainkan anda menggunakan ===
+"5" === 5; // = tidak benar
+null === undefined; // = tidak benar
+
+// ...yang boleh menghasilkan keputusan yang pelik...
+13 + !0; // 14
+"13" + !0; // '13true'
+
+// Anda boleh akses huruf dalam perkataan dengan `charAt`
+"This is a string".charAt(0); // = 'T'
+
+// ...atau menggunakan `substring` untuk mendapatkan bahagian yang lebih besar.
+"Hello world".substring(0, 5); // = "Hello"
+
+// `length` adalah ciri, maka jangan gunakan ().
+"Hello".length; // = 5
+
+// Selain itu, terdapat juga `null` dan `undefined`.
+null; // digunakan untuk menandakan bukan-nilai yang disengajakan
+undefined; // digunakan untuk menandakan nilai yang tidak wujud pada waktu ini (walaupun `undefined` adalah nilai juga)
+
+// false, null, undefined, NaN, 0 dan "" adalah tidak benar; semua selain itu adalah benar.
+// Peringatan, 0 adalah tidak benar dan "0" adalah benar, walaupun 0 == "0".
+
+///////////////////////////////////
+// 2. Pembolehubah, Array dan Objek
+
+// Pembolehubah digunakan dengan kata kunci 'var'. Javascript ialah sebuah
+// bahasa aturcara yang jenisnya dinamik, maka anda tidak perlu spesifikasikan
+// jenis pembolehubah. Penetapan menggunakan satu '=' karakter.
+var someVar = 5;
+
+// jika anda tinggalkan kata kunci var, anda tidak akan dapat ralat...
+someOtherVar = 10;
+
+// ...tetapi pembolehubah anda akan dicipta di dalam skop global, bukan di
+// dalam skop anda menciptanya.
+
+// Pembolehubah yang dideklarasikan tanpa ditetapkan sebarang nilai akan
+// ditetapkan kepada undefined.
+var someThirdVar; // = undefined
+
+// jika anda ingin mendeklarasikan beberapa pembolehubah, maka anda boleh
+// menggunakan koma sebagai pembahagi
+var someFourthVar = 2, someFifthVar = 4;
+
+// Terdapat cara mudah untuk melakukan operasi - operasi matematik pada
+// pembolehubah:
+someVar += 5; // bersamaan dengan someVar = someVar +5; someVar sama dengan 10 sekarang
+someVar *= 10; // sekarang someVar bernilai 100
+
+// dan cara lebih mudah untuk penambahan atau penolakan 1
+someVar++; // sekarang someVar ialah 101
+someVar--; // kembali kepada 100
+
+// Array adalah senarai nilai yang tersusun, yang boleh terdiri daripada
+// pembolehubah pelbagai jenis.
+var myArray = ["Hello", 45, true];
+
+// Setiap ahli array boleh diakses menggunakan syntax kurungan-petak.
+// Indeks array bermula pada sifar.
+myArray[1]; // = 45
+
+// Array boleh diubah dan mempunyai panjang yang tidak tetap dan boleh ubah.
+myArray.push("World");
+myArray.length; // = 4
+
+// Tambah/Ubah di index yang spesifik
+myArray[3] = "Hello";
+
+// Objek javascript adalah sama dengan "dictionaries" atau "maps" dalam bahasa
+// aturcara yang lain: koleksi pasangan kunci-nilai yang tidak mempunyai
+// sebarang susunan.
+var myObj = {key1: "Hello", key2: "World"};
+
+// Kunci adalah string, tetapi 'quote' tidak diperlukan jika ia adalah pengecam
+// javascript yang sah. Nilai boleh mempunyai sebarang jenis.
+var myObj = {myKey: "myValue", "my other key": 4};
+
+// Ciri - ciri objek boleh juga diakses menggunakan syntax subskrip (kurungan-
+// petak),
+myObj["my other key"]; // = 4
+
+// ... atau menggunakan syntax titik, selagi kuncinya adalah pengecam yang sah.
+myObj.myKey; // = "myValue"
+
+// Objek adalah boleh diubah; nilai boleh diubah dan kunci baru boleh ditambah.
+myObj.myThirdKey = true;
+
+// Jika anda cuba untuk akses nilai yang belum ditetapkan, anda akan mendapat
+// undefined.
+myObj.myFourthKey; // = undefined
+
+///////////////////////////////////
+// 3. Logik dan Struktur Kawalan
+
+// Syntax untuk bahagian ini adalah hampir sama dengan Java.
+
+// Struktur `if` berfungsi seperti yang anda jangkakan.
+var count = 1;
+if (count == 3){
+ // dinilai jika count ialah 3
+} else if (count == 4){
+ // dinilai jika count ialah 4
+} else {
+ // dinilai jika count bukan 3 atau 4
+}
+
+// Sama juga dengan `while`.
+while (true){
+ // Sebuah ulangan yang tidak terhingga!
+ // An infinite loop!
+}
+
+// Ulangan do-while adalah sama dengan ulangan while, kecuali ia akan diulang
+// sekurang-kurangnya sekali.
+var input;
+do {
+ input = getInput();
+} while (!isValid(input))
+
+// Ulangan `for` adalah sama dengan C dan Java:
+// Persiapan; kondisi untuk bersambung; pengulangan.
+for (var i = 0; i < 5; i++){
+ // akan berulang selama 5 kali
+}
+
+// Pernyataan ulangan For/In akan mengulang setiap ciri seluruh jaringan
+// 'prototype'
+var description = "";
+var person = {fname:"Paul", lname:"Ken", age:18};
+for (var x in person){
+ description += person[x] + " ";
+}
+
+// Jika anda cuma mahu mengambil kira ciri - ciri yang ditambah pada objek it
+// sendiri dan bukan 'prototype'nya, sila gunakan semakan hasOwnProperty()
+var description = "";
+var person = {fname:"Paul", lname:"Ken", age:18};
+for (var x in person){
+ if (person.hasOwnProperty(x)){
+ description += person[x] + " ";
+ }
+}
+
+// for/in tidak sepatutnya digunakan untuk mengulang sebuah Array di mana
+// indeks susunan adalah penting.
+// Tiada sebarang jaminan bahawa for/in akan mengembalikan indeks dalam
+// mana - mana susunan
+
+// && adalah logikal dan, || adalah logikal atau
+if (house.size == "big" && house.colour == "blue"){
+ house.contains = "bear";
+}
+if (colour == "red" || colour == "blue"){
+ // warna adalah sama ada 'red' atau 'blue'
+}
+
+// && dan || adalah "lintar pintas", di mana ia berguna untuk menetapkan
+// nilai asal.
+var name = otherName || "default";
+
+
+// Pernyataan `switch` menyemak persamaan menggunakan `===`.
+// gunakan pernyataan `break` selepas setiap kes
+// atau tidak, kes - kes selepas kes yang betul akan dijalankan juga.
+grade = 'B';
+switch (grade) {
+ case 'A':
+ console.log("Great job");
+ break;
+ case 'B':
+ console.log("OK job");
+ break;
+ case 'C':
+ console.log("You can do better");
+ break;
+ default:
+ console.log("Oy vey");
+ break;
+}
+
+
+///////////////////////////////////
+// 4. Functions, Skop dan Closures
+
+// Function javascript dideklarasikan dengan kata kunci `function`.
+function myFunction(thing){
+ return thing.toUpperCase();
+}
+myFunction("foo"); // = "FOO"
+
+// Perhatikan yang nilai yang dikembalikan mesti bermula pada baris yang sama
+// dengan kata kunci `return`, jika tidak, anda akan sentiasa mengembalikan
+// `undefined` disebabkan kemasukan 'semicolon' secara automatik. Sila berjaga -
+// jaga dengan hal ini apabila menggunakan Allman style.
+function myFunction(){
+ return // <- semicolon dimasukkan secara automatik di sini
+ {thisIsAn: 'object literal'}
+}
+myFunction(); // = undefined
+
+// Function javascript adalah objek kelas pertama, maka ia boleh diberikan
+// nama pembolehubah yang lain dan diberikan kepada function yang lain sebagai
+// input - sebagai contoh, apabila membekalkan pengendali event:
+function myFunction(){
+ // kod ini akan dijalankan selepas 5 saat
+}
+setTimeout(myFunction, 5000);
+// Nota: setTimeout bukan sebahagian daripada bahasa JS, tetapi ia disediakan
+// oleh pelayar web dan Node.js.
+
+// Satu lagi function yang disediakan oleh pelayar web adalah setInterval
+function myFunction(){
+ // kod ini akan dijalankan setiap 5 saat
+}
+setInterval(myFunction, 5000);
+
+// Objek function tidak perlu dideklarasikan dengan nama - anda boleh menulis
+// function yang tidak bernama didalam input sebuah function lain.
+setTimeout(function(){
+ // kod ini akan dijalankan dalam 5 saat
+}, 5000);
+
+// Javascript mempunyai skop function; function mempunyai skop mereka
+// tersendiri tetapi blok tidak.
+if (true){
+ var i = 5;
+}
+i; // = 5 - bukan undefined seperti yang anda jangkakan di dalam bahasa blok-skop
+
+// Ini telah menyebabkan corak biasa iaitu "immediately-executing anonymous
+// functions", yang mengelakkan pembolehubah sementara daripada bocor ke
+// skop global.
+(function(){
+ var temporary = 5;
+ // Kita boleh akses skop global dengan menetapkan nilai ke "objek global",
+ // iaitu dalam pelayar web selalunya adalah `window`. Objek global mungkin
+ // mempunyai nama yang berlainan dalam alam bukan pelayar web seperti Node.js.
+ window.permanent = 10;
+})();
+temporary; // akan menghasilkan ralat ReferenceError
+permanent; // = 10
+
+// Salah satu ciri terhebat Javascript ialah closure. Jika sebuah function
+// didefinisikan di dalam sebuah function lain, function yang di dalam akan
+// mempunyai akses kepada semua pembolehubah function yang di luar, mahupun
+// selepas function yang di luar tersebut selesai.
+function sayHelloInFiveSeconds(name){
+ var prompt = "Hello, " + name + "!";
+ // Function dalam diletakkan di dalam skop lokal secara asal, seperti
+ // ia dideklarasikan dengan `var`.
+ function inner(){
+ alert(prompt);
+ }
+ setTimeout(inner, 5000);
+ // setTimeout adalah tak segerak atau asinkroni, maka function sayHelloInFiveSeconds akan selesai serta merta, dan setTimeout akan memanggil
+ // inner selepas itu. Walaubagaimanapun, disebabkan inner terletak didalam
+ // sayHelloInFiveSeconds, inner tetap mempunyai akses kepada pembolehubah
+ // `prompt` apabila ia dipanggil.
+}
+sayHelloInFiveSeconds("Adam"); // akan membuka sebuah popup dengan "Hello, Adam!" selepas 5s
+
+///////////////////////////////////
+// 5. Lagi tentang Objek, Constructor dan Prototype
+
+// Objek boleh mengandungi function.
+var myObj = {
+ myFunc: function(){
+ return "Hello world!";
+ }
+};
+myObj.myFunc(); // = "Hello world!"
+
+// Apabila function sesebuah object dipanggil, ia boleh mengakses objek asalnya
+// dengan menggunakan kata kunci `this`.
+myObj = {
+ myString: "Hello world!",
+ myFunc: function(){
+ return this.myString;
+ }
+};
+myObj.myFunc(); // = "Hello world!"
+
+// Nilai sebenar yang ditetapkan kepada this akan ditentukan oleh bagaimana
+// sesebuah function itu dipanggil, bukan dimana ia didefinisikan. Oleh it,
+// sesebuah function tidak akan berfungsi jika ia dipanggil bukan pada konteks
+// objeknya.
+var myFunc = myObj.myFunc;
+myFunc(); // = undefined
+
+// Sebaliknya, sebuah function boleh ditetapkan kepada objek dan mendapat akses
+// kepada objek itu melalui `this`, walaupun ia tidak ditetapkan semasa ia
+// didefinisikan.
+var myOtherFunc = function(){
+ return this.myString.toUpperCase();
+}
+myObj.myOtherFunc = myOtherFunc;
+myObj.myOtherFunc(); // = "HELLO WORLD!"
+
+// Kita juga boleh menentukan konteks untuk sebuah function dijalankan apabila
+// ia dipanggil menggunakan `call` atau `apply`.
+
+var anotherFunc = function(s){
+ return this.myString + s;
+}
+anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"
+
+// Function `apply` adalah hampir sama, tetapi ia mengambil sebuah array
+// sebagai senarai input.
+
+anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!"
+
+// Ini sangat berguna apabila menggunakan sebuah function yang menerima senarai
+// input dan anda mahu menggunakan sebuah array sebagai input.
+
+Math.min(42, 6, 27); // = 6
+Math.min([42, 6, 27]); // = NaN (uh-oh!)
+Math.min.apply(Math, [42, 6, 27]); // = 6
+
+// Tetapi, `call` dan `apply` adalah hanya sementara, sebagaimana hidup ini.
+// Apabila kita mahu ia kekal, kita boleh menggunakan `bind`.
+
+var boundFunc = anotherFunc.bind(myObj);
+boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!"
+
+// `bind` boleh juga digunakan untuk menggunakan sebuah function tidak
+// sepenuhnya (curry).
+
+var product = function(a, b){ return a * b; }
+var doubler = product.bind(this, 2);
+doubler(8); // = 16
+
+// Apabila anda memanggil sebuah function dengan kata kunci `new`, sebuah
+// objek baru akan dicipta dan dijadikan tersedia kepada function itu melalui
+// kata kunci `this`. Function yang direka bentuk untuk dipanggil sebegitu rupa
+// dikenali sebagai constructors.
+
+var MyConstructor = function(){
+ this.myNumber = 5;
+}
+myNewObj = new MyConstructor(); // = {myNumber: 5}
+myNewObj.myNumber; // = 5
+
+// Setiap objek JavaScript mempunyai `prototype`. Apabila anda akses sesuatu
+// ciri sebuah objek yang tidak wujud dalam objek sebenar itu, interpreter akan
+// mencari ciri itu didalam `prototype`nya.
+
+// Sebahagian implementasi JS membenarkan anda untuk akses prototype sebuah
+// objek pada ciri istimewa `__proto__`. Walaupun ini membantu dalam menerangkan
+// mengenai prototypes, ia bukan sebahagian dari piawai; kita akan melihat
+// cara - cara piawai untuk menggunakan prototypes nanti.
+var myObj = {
+ myString: "Hello world!"
+};
+var myPrototype = {
+ meaningOfLife: 42,
+ myFunc: function(){
+ return this.myString.toLowerCase()
+ }
+};
+
+myObj.__proto__ = myPrototype;
+myObj.meaningOfLife; // = 42
+
+// Ini berfungsi untuk function juga.
+myObj.myFunc(); // = "hello world!"
+
+// Sudah pasti, jika ciri anda bukan pada prototype anda, prototype kepada
+// prototype anda akan disemak, dan seterusnya.
+myPrototype.__proto__ = {
+ myBoolean: true
+};
+myObj.myBoolean; // = true
+
+// Tiada penyalinan terlibat disini; setiap objek menyimpan rujukan kepada
+// prototypenya sendiri. Ini bermaksud, kita boleh mengubah prototypenya dan
+// pengubahsuaian itu akan dilihat dan berkesan dimana sahaja.
+myPrototype.meaningOfLife = 43;
+myObj.meaningOfLife; // = 43
+
+// Kami menyatakan yang `__proto__` adalah bukan piawai, dan tiada cara rasmi
+// untuk mengubah prototype sesebuah objek. Walaubagaimanapun, terdapat dua
+// cara untuk mencipta objek baru dengan sesebuah prototype.
+
+// Yang pertama ialah Object.create, yang merupakan tambahan terbaru pada JS,
+// dan oleh itu tiada dalam semua implementasi buat masa ini.
+var myObj = Object.create(myPrototype);
+myObj.meaningOfLife; // = 43
+
+// Cara kedua, yang boleh digunakan dimana sahaja, adalah berkaitan dengan
+// constructor. Constructors mempunyai sebuah ciri yang dipanggil prototype.
+// Ini *bukan* prototype constructor terbabit; tetapi, ia adalah prototype yang
+// diberikan kepada objek baru apabila ia dicipta menggunakan constructor dan
+// kata kunci new.
+MyConstructor.prototype = {
+ myNumber: 5,
+ getMyNumber: function(){
+ return this.myNumber;
+ }
+};
+var myNewObj2 = new MyConstructor();
+myNewObj2.getMyNumber(); // = 5
+myNewObj2.myNumber = 6
+myNewObj2.getMyNumber(); // = 6
+
+// Jenis yang terbina sedia seperti string dan nombor juga mempunyai constructor
+// yang mencipta objek pembalut yang serupa.
+var myNumber = 12;
+var myNumberObj = new Number(12);
+myNumber == myNumberObj; // = true
+
+// Kecuali, mereka sebenarnya tak sama sepenuhnya.
+typeof myNumber; // = 'number'
+typeof myNumberObj; // = 'object'
+myNumber === myNumberObj; // = false
+if (0){
+ // Kod ini tidak akan dilaksanakan, kerana 0 adalah tidak benar.
+}
+
+// Walaubagaimanapun, pembalut objek dan jenis terbina yang biasa berkongsi
+// prototype, maka sebagai contoh, anda sebenarnya boleh menambah fungsi
+// kepada string.
+String.prototype.firstCharacter = function(){
+ return this.charAt(0);
+}
+"abc".firstCharacter(); // = "a"
+
+// Fakta ini selalu digunakan dalam "polyfilling", iaitu melaksanakan fungsi
+// baru JavaScript didalam subset JavaScript yang lama, supaya ia boleh
+// digunakan di dalam persekitaran yang lama seperti pelayar web yang lama.
+
+// Sebagai contoh, kami menyatakan yang Object.create belum lagi tersedia
+// di semua implementasi, tetapi kita masih boleh menggunakannya dengan polyfill:
+if (Object.create === undefined){ // jangan ganti jika ia sudah wujud
+ Object.create = function(proto){
+ // buat satu constructor sementara dengan prototype yang betul
+ var Constructor = function(){};
+ Constructor.prototype = proto;
+ // kemudian gunakannya untuk mencipta objek baru yang diberikan
+ // prototype yang betul
+ return new Constructor();
+ }
+}
+```
+## Bacaan Lanjut
+
+[Mozilla Developer Network][1] menyediakan dokumentasi yang sangat baik untuk
+JavaScript kerana ia digunakan di dalam pelayar - pelayar web. Tambahan pula,
+ia adalah sebuah wiki, maka, sambil anda belajar lebih banyak lagi, anda boleh
+membantu orang lain dengan berkongsi pengetahuan anda.
+
+[A re-introduction to JavaScript][2] oleh MDN meliputi semua konsep yang
+diterangkan di sini dengan lebih terperinci. Panduan ini menerangkan bahasa
+aturcara JavaScript dengan agak mudah; jika anda mahu belajar lebih lanjut
+tentang menggunakan JavaScript didalam laman web, mulakan dengan mempelajari
+tentang [Document Object Model][3].
+
+[Learn Javascript by Example and with Challenges][4] adalah variasi panduan ini
+dengan cabaran yang tersedia pakai.
+
+[JavaScript Garden][5] pula adalah panduan yang lebih terperinci mengenai
+semua bahagian bahasa aturcara ini yang bertentangan dengan naluri atau
+kebiasaan.
+
+[JavaScript: The Definitive Guide][6] adalah panduan klasik dan buku rujukan.
+
+Selain daripada penyumbang terus kepada artikel ini, sebahagian kandungannya
+adalah adaptasi daripada tutorial Python Louie Dinh di dalam laman web ini,
+dan [JS Tutorial][7] di Mozilla Developer Network.
+
+
+[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript
+[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
+[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core
+[4]: http://www.learneroo.com/modules/64/nodes/350
+[5]: http://bonsaiden.github.io/JavaScript-Garden/
+[6]: http://www.amazon.com/gp/product/0596805527/
+[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
diff --git a/objective-c.html.markdown b/objective-c.html.markdown
index f130ea0c..1fa731e3 100644
--- a/objective-c.html.markdown
+++ b/objective-c.html.markdown
@@ -20,6 +20,10 @@ It is a general-purpose, object-oriented programming language that adds Smalltal
Multi-line comments look like this
*/
+// XCode supports pragma mark directive that improve jump bar readability
+#pragma mark Navigation Functions // New tag on jump bar named 'Navigation Functions'
+#pragma mark - Navigation Functions // Same tag, now with a separator
+
// Imports the Foundation headers with #import
// Use <> to import global files (in general frameworks)
// Use "" to import local files (from project)
@@ -599,6 +603,52 @@ int main (int argc, const char * argv[]) {
@end
+// Starting in Xcode 7.0, you can create Generic classes,
+// allowing you to provide greater type safety and clarity
+// without writing excessive boilerplate.
+@interface Result<__covariant A> : NSObject
+
+- (void)handleSuccess:(void(^)(A))success
+ failure:(void(^)(NSError *))failure;
+
+@property (nonatomic) A object;
+
+@end
+
+// we can now declare instances of this class like
+Result<NSNumber *> *result;
+Result<NSArray *> *result;
+
+// Each of these cases would be equivalent to rewriting Result's interface
+// and substituting the appropriate type for A
+@interface Result : NSObject
+- (void)handleSuccess:(void(^)(NSArray *))success
+ failure:(void(^)(NSError *))failure;
+@property (nonatomic) NSArray * object;
+@end
+
+@interface Result : NSObject
+- (void)handleSuccess:(void(^)(NSNumber *))success
+ failure:(void(^)(NSError *))failure;
+@property (nonatomic) NSNumber * object;
+@end
+
+// It should be obvious, however, that writing one
+// Class to solve a problem is always preferable to writing two
+
+// Note that Clang will not accept generic types in @implementations,
+// so your @implemnation of Result would have to look like this:
+
+@implementation Result
+
+- (void)handleSuccess:(void (^)(id))success
+ failure:(void (^)(NSError *))failure {
+ // Do something
+}
+
+@end
+
+
///////////////////////////////////////
// Protocols
///////////////////////////////////////
diff --git a/php.html.markdown b/php.html.markdown
index 0504ced2..7b0cf61c 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -3,6 +3,7 @@ language: PHP
contributors:
- ["Malcolm Fell", "http://emarref.net/"]
- ["Trismegiste", "https://github.com/Trismegiste"]
+ - [ Liam Demafelix , https://liamdemafelix.com/]
filename: learnphp.php
---
@@ -156,14 +157,13 @@ unset($array[3]);
* Output
*/
-echo('Hello World!');
+echo 'Hello World!';
// Prints Hello World! to stdout.
// Stdout is the web page if running in a browser.
print('Hello World!'); // The same as echo
-// echo and print are language constructs too, so you can drop the parentheses
-echo 'Hello World!';
+// print is a language construct too, so you can drop the parentheses
print 'Hello World!';
$paragraph = 'paragraph';
@@ -335,7 +335,7 @@ switch ($x) {
$i = 0;
while ($i < 5) {
echo $i++;
-}; // Prints "01234"
+} // Prints "01234"
echo "\n";
diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown
index 43688724..2c274f12 100644
--- a/pt-br/c-pt.html.markdown
+++ b/pt-br/c-pt.html.markdown
@@ -7,29 +7,30 @@ contributors:
translators:
- ["João Farias", "https://github.com/JoaoGFarias"]
- ["Elton Viana", "https://github.com/eltonvs"]
+ - ["Cássio Böck", "https://github.com/cassiobsilva"]
lang: pt-br
filename: c-pt.el
---
Ah, C. Ainda é **a** linguagem de computação de alta performance.
-C é a liguangem de mais baixo nível que a maioria dos programadores
-irão usar, e isso dá a ela uma grande velocidade bruta. Apenas fique
-antento que este manual de gerenciamento de memória e C vai levanter-te
-tão longe quanto você precisa.
+C é a linguagem de mais baixo nível que a maioria dos programadores
+utilizarão, e isso dá a ela uma grande velocidade bruta. Apenas fique
+atento se este manual de gerenciamento de memória e C vai te levar
+tão longe quanto precisa.
```c
// Comentários de uma linha iniciam-se com // - apenas disponível a partir do C99
/*
-Comentários de multiplas linhas se parecem com este.
+Comentários de múltiplas linhas se parecem com este.
Funcionam no C89 também.
*/
// Constantes: #define <palavra-chave>
#definie DAY_IN_YEAR 365
-//enumarações também são modos de definir constantes.
+//enumerações também são modos de definir constantes.
enum day {DOM = 1, SEG, TER, QUA, QUI, SEX, SAB};
// SEG recebe 2 automaticamente, TER recebe 3, etc.
@@ -54,13 +55,13 @@ int soma_dois_ints(int x1, int x2); // protótipo de função
// O ponto de entrada do teu programa é uma função
// chamada main, com tipo de retorno inteiro
int main() {
- // Usa-se printf para escrever na tela,
+ // Usa-se printf para escrever na tela,
// para "saída formatada"
// %d é um inteiro, \n é uma nova linha
printf("%d\n", 0); // => Imprime 0
// Todos as declarações devem acabar com
// ponto e vírgula
-
+
///////////////////////////////////////
// Tipos
///////////////////////////////////////
@@ -78,7 +79,7 @@ int main() {
// longs tem entre 4 e 8 bytes; longs long tem garantia
// de ter pelo menos 64 bits
long x_long = 0;
- long long x_long_long = 0;
+ long long x_long_long = 0;
// floats são normalmente números de ponto flutuante
// com 32 bits
@@ -93,7 +94,7 @@ int main() {
unsigned int ux_int;
unsigned long long ux_long_long;
- // caracteres dentro de aspas simples são inteiros
+ // caracteres dentro de aspas simples são inteiros
// no conjunto de caracteres da máquina.
'0' // => 48 na tabela ASCII.
'A' // => 65 na tabela ASCII.
@@ -104,7 +105,7 @@ int main() {
// Se o argumento do operador `sizeof` é uma expressão, então seus argumentos
// não são avaliados (exceto em VLAs (veja abaixo)).
- // O valor devolve, neste caso, é uma constante de tempo de compilação.
+ // O valor devolve, neste caso, é uma constante de tempo de compilação.
int a = 1;
// size_t é um inteiro sem sinal com pelo menos 2 bytes que representa
// o tamanho de um objeto.
@@ -120,7 +121,7 @@ int main() {
// Você pode inicializar um array com 0 desta forma:
char meu_array[20] = {0};
- // Indexar um array é semelhante a outras linguages
+ // Indexar um array é semelhante a outras linguagens
// Melhor dizendo, outras linguagens são semelhantes a C
meu_array[0]; // => 0
@@ -129,7 +130,7 @@ int main() {
printf("%d\n", meu_array[1]); // => 2
// No C99 (e como uma features opcional em C11), arrays de tamanho variável
- // VLA (do inglês), podem ser declarados também. O tamanho destes arrays
+ // VLA (do inglês), podem ser declarados também. O tamanho destes arrays
// não precisam ser uma constante de tempo de compilação:
printf("Entre o tamanho do array: "); // Pergunta ao usuário pelo tamanho
char buf[0x100];
@@ -144,14 +145,14 @@ int main() {
// > Entre o tamanho do array: 10
// > sizeof array = 40
- // String são apenas arrays de caracteres terminados por um
+ // String são apenas arrays de caracteres terminados por um
// byte nulo (0x00), representado em string pelo caracter especial '\0'.
// (Não precisamos incluir o byte nulo em literais de string; o compilador
// o insere ao final do array para nós.)
- char uma_string[20] = "Isto é uma string";
+ char uma_string[20] = "Isto é uma string";
// Observe que 'é' não está na tabela ASCII
// A string vai ser salva, mas a saída vai ser estranha
- // Porém, comentários podem conter acentos
+ // Porém, comentários podem conter acentos
printf("%s\n", uma_string); // %s formata a string
printf("%d\n", uma_string[17]); // => 0
@@ -175,7 +176,7 @@ int main() {
///////////////////////////////////////
// Atalho para multiplas declarações:
- int i1 = 1, i2 = 2;
+ int i1 = 1, i2 = 2;
float f1 = 1.0, f2 = 2.0;
int a, b, c;
@@ -206,7 +207,7 @@ int main() {
2 <= 2; // => 1
2 >= 2; // => 1
- // C não é Python - comparações não se encadeam.
+ // C não é Python - comparações não se encadeiam.
int a = 1;
// Errado:
int entre_0_e_2 = 0 < a < 2;
@@ -231,7 +232,7 @@ int main() {
char *s = "iLoveC";
int j = 0;
s[j++]; // => "i". Retorna o j-ésimo item de s E DEPOIS incrementa o valor de j.
- j = 0;
+ j = 0;
s[++j]; // => "L". Incrementa o valor de j. E DEPOIS retorna o j-ésimo item de s.
// o mesmo com j-- e --j
@@ -308,7 +309,7 @@ int main() {
exit(-1);
break;
}
-
+
///////////////////////////////////////
// Cast de tipos
@@ -327,8 +328,8 @@ int main() {
// Tipos irão ter overflow sem aviso
printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 se char tem 8 bits)
- // Para determinar o valor máximo de um `char`, de um `signed char` e de
- // um `unisigned char`, respectivamente, use as macros CHAR_MAX, SCHAR_MAX
+ // Para determinar o valor máximo de um `char`, de um `signed char` e de
+ // um `unisigned char`, respectivamente, use as macros CHAR_MAX, SCHAR_MAX
// e UCHAR_MAX de <limits.h>
// Tipos inteiros podem sofrer cast para pontos-flutuantes e vice-versa.
@@ -341,7 +342,7 @@ int main() {
///////////////////////////////////////
// Um ponteiro é uma variável declarada para armazenar um endereço de memória.
- // Seu declaração irá também dizer o tipo de dados para o qual ela aponta. Você
+ // Sua declaração irá também dizer o tipo de dados para o qual ela aponta. Você
// Pode usar o endereço de memória de suas variáveis, então, brincar com eles.
int x = 0;
@@ -363,13 +364,13 @@ int main() {
printf("%d\n", *px); // => Imprime 0, o valor de x
// Você também pode mudar o valor que o ponteiro está apontando.
- // Teremo que cercar a de-referência entre parenteses, pois
+ // Temos que cercar a de-referência entre parênteses, pois
// ++ tem uma precedência maior que *.
(*px)++; // Incrementa o valor que px está apontando por 1
printf("%d\n", *px); // => Imprime 1
printf("%d\n", x); // => Imprime 1
- // Arrays são um boa maneira de alocar um bloco contínuo de memória
+ // Arrays são uma boa maneira de alocar um bloco contínuo de memória
int x_array[20]; // Declara um array de tamanho 20 (não pode-se mudar o tamanho
int xx;
for (xx = 0; xx < 20; xx++) {
@@ -379,7 +380,7 @@ int main() {
// Declara um ponteiro do tipo int e inicialize ele para apontar para x_array
int* x_ptr = x_array;
// x_ptr agora aponta para o primeiro elemento do array (o inteiro 20).
- // Isto funciona porque arrays são apenas ponteiros para seu primeiros elementos.
+ // Isto funciona porque arrays são apenas ponteiros para seus primeiros elementos.
// Por exemplo, quando um array é passado para uma função ou é atribuído a um
// ponteiro, ele transforma-se (convertido implicitamente) em um ponteiro.
// Exceções: quando o array é o argumento de um operador `&` (endereço-de):
@@ -395,7 +396,7 @@ int main() {
printf("%zu, %zu\n", sizeof arr, sizeof ptr); // provavelmente imprime "40, 4" ou "40, 8"
// Ponteiros podem ser incrementados ou decrementados baseado no seu tipo
- // (isto é chamado aritimética de ponteiros
+ // (isto é chamado aritmética de ponteiros
printf("%d\n", *(x_ptr + 1)); // => Imprime 19
printf("%d\n", x_array[1]); // => Imprime 19
@@ -413,9 +414,9 @@ int main() {
// "resultados imprevisíveis" - o programa é dito ter um "comportamento indefinido"
printf("%d\n", *(my_ptr + 21)); // => Imprime quem-sabe-o-que? Talvez até quebre o programa.
- // Quando termina-se de usar um bloco de memória alocado, você pode liberá-lo,
+ // Quando se termina de usar um bloco de memória alocado, você pode liberá-lo,
// ou ninguém mais será capaz de usá-lo até o fim da execução
- // (Isto cham-se "memory leak"):
+ // (Isto chama-se "memory leak"):
free(my_ptr);
// Strings são arrays de char, mas elas geralmente são representadas
@@ -537,7 +538,7 @@ int area(retan r)
return r.largura * r.altura;
}
-// Se você tiver structus grande, você pode passá-las "por ponteiro"
+// Se você tiver structus grande, você pode passá-las "por ponteiro"
// para evitar cópia de toda a struct:
int area(const retan *r)
{
@@ -554,8 +555,8 @@ conhecidos. Ponteiros para funções são como qualquer outro ponteiro
diretamente e passá-las para por toda parte.
Entretanto, a sintaxe de definição por ser um pouco confusa.
-Exemplo: use str_reverso através de um ponteiro
-*/
+Exemplo: use str_reverso através de um ponteiro
+*/
void str_reverso_através_ponteiro(char *str_entrada) {
// Define uma variável de ponteiro para função, nomeada f.
void (*f)(char *); //Assinatura deve ser exatamente igual à função alvo.
@@ -575,7 +576,7 @@ typedef void (*minha_função_type)(char *);
// Declarando o ponteiro:
// ...
-// minha_função_type f;
+// minha_função_type f;
//Caracteres especiais:
'\a' // Alerta (sino)
@@ -586,7 +587,7 @@ typedef void (*minha_função_type)(char *);
'\r' // Retorno de carroça
'\b' // Backspace
'\0' // Caracter nulo. Geralmente colocado ao final de string em C.
- // oi\n\0. \0 é usado por convenção para marcar o fim da string.
+ // oi\n\0. \0 é usado por convenção para marcar o fim da string.
'\\' // Barra invertida
'\?' // Interrogação
'\'' // Aspas simples
@@ -606,7 +607,7 @@ typedef void (*minha_função_type)(char *);
"%p" // ponteiro
"%x" // hexadecimal
"%o" // octal
-"%%" // imprime %
+"%%" // imprime %
///////////////////////////////////////
// Ordem de avaliação
diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown
index ed6f6c4c..b1fbd961 100644
--- a/pt-br/css-pt.html.markdown
+++ b/pt-br/css-pt.html.markdown
@@ -159,11 +159,11 @@ seletor {
    color: # FF66EE; /* Formato hexadecimal longo */
    color: tomato; /* Uma cor nomeada */
    color: rgb (255, 255, 255); /* Como valores rgb */
-    cor: RGB (10%, 20%, 50%); /* Como porcentagens rgb */
-    cor: rgba (255, 0, 0, 0,3); /* Como valores RGBA (CSS 3) NOTA: 0 <a <1 */
+    color: RGB (10%, 20%, 50%); /* Como porcentagens rgb */
+    color: rgba (255, 0, 0, 0,3); /* Como valores RGBA (CSS 3) NOTA: 0 <a <1 */
    color: transparent; /* Equivale a definir o alfa a 0 */
-    cor: HSL (0, 100%, 50%); /* Como porcentagens HSL (CSS 3) */
-    cor: HSLA (0, 100%, 50%, 0,3); /* Como porcentagens HSLA com alfa */
+    color: HSL (0, 100%, 50%); /* Como porcentagens HSL (CSS 3) */
+    color: HSLA (0, 100%, 50%, 0,3); /* Como porcentagens HSLA com alfa */
    /* Imagens como fundos de elementos */
    background-image: url (/img-path/img.jpg); /* Citações dentro url () opcional */
diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown
index a884f273..3c9512aa 100644
--- a/pt-br/java-pt.html.markdown
+++ b/pt-br/java-pt.html.markdown
@@ -405,6 +405,219 @@ class Velocipede extends Bicicleta {
}
+// Interfaces
+// Sintaxe de declaração de Interface
+// <nível de acesso> Interface <nome-da-interface> extends <super-interfaces> {
+// // Constantes
+// // Declarações de método
+//}
+
+// Exemplo - Comida:
+public interface Comestivel {
+ public void comer(); // Qualquer classe que implementa essa interface, deve
+                        // Implementar este método.
+}
+
+public interface Digestivel {
+ public void digerir();
+}
+
+
+// Agora podemos criar uma classe que implementa ambas as interfaces.
+public class Fruta implements Comestivel, Digestivel {
+
+ @Override
+ public void comer() {
+ // ...
+ }
+
+ @Override
+ public void digerir() {
+ // ...
+ }
+}
+
+// Em Java, você pode estender somente uma classe, mas você pode implementar muitas
+// Interfaces. Por exemplo:
+public class ClasseExemplo extends ExemploClassePai implements InterfaceUm,
+ InterfaceDois {
+
+ @Override
+ public void InterfaceUmMetodo() {
+ }
+
+ @Override
+ public void InterfaceDoisMetodo() {
+ }
+
+}
+
+// Classes abstratas
+
+// Sintaxe de declaração de classe abstrata
+// <Nível de acesso> abstract <nome-da-classe-abstrata> extends <estende super-abstratas-classes> {
+// // Constantes e variáveis
+// // Declarações de método
+//}
+
+// Marcar uma classe como abstrata significa que ela contém métodos abstratos que devem
+// ser definido em uma classe filha. Semelhante às interfaces, classes abstratas não podem
+// ser instanciadas, ao invés disso devem ser extendidas e os métodos abstratos
+// definidos. Diferente de interfaces, classes abstratas podem conter uma mistura de
+// métodos concretos e abstratos. Métodos em uma interface não podem ter um corpo,
+// a menos que o método seja estático, e as variáveis sejam finais, por padrão, ao contrário de um
+// classe abstrata. Classes abstratas também PODEM ter o método "main".
+
+public abstract class Animal
+{
+ public abstract void fazerSom();
+
+ // Método pode ter um corpo
+ public void comer()
+ {
+ System.out.println("Eu sou um animal e estou comendo.");
+ //Nota: Nós podemos acessar variáveis privadas aqui.
+ idade = 30;
+ }
+
+ // Não há necessidade de inicializar, no entanto, em uma interface
+    // a variável é implicitamente final e, portanto, tem
+    // de ser inicializado.
+ protected int idade;
+
+ public void mostrarIdade()
+ {
+ System.out.println(idade);
+ }
+
+ //Classes abstratas podem ter o método main.
+ public static void main(String[] args)
+ {
+ System.out.println("Eu sou abstrata");
+ }
+}
+
+class Cachorro extends Animal
+{
+
+ // Nota: ainda precisamos substituir os métodos abstratos na
+    // classe abstrata
+ @Override
+ public void fazerSom()
+ {
+ System.out.println("Bark");
+ // idade = 30; ==> ERRO! idade é privada de Animal
+ }
+
+ // NOTA: Você receberá um erro se usou a
+    // anotação Override aqui, uma vez que java não permite
+    // sobrescrita de métodos estáticos.
+    // O que está acontecendo aqui é chamado de "esconder o método".
+    // Vejá também este impressionante SO post: http://stackoverflow.com/questions/16313649/
+ public static void main(String[] args)
+ {
+ Cachorro pluto = new Cachorro();
+ pluto.fazerSom();
+ pluto.comer();
+ pluto.mostrarIdade();
+ }
+}
+
+// Classes Finais
+
+// Sintaxe de declaração de classe final
+// <nível de acesso> final <nome-da-classe-final> {
+// // Constantes e variáveis
+// // Declarações de método
+//}
+
+// Classes finais são classes que não podem ser herdadas e são, portanto, um
+// filha final. De certa forma, as classes finais são o oposto de classes abstratas
+// Porque classes abstratas devem ser estendidas, mas as classes finais não pode ser
+// estendidas.
+public final class TigreDenteDeSabre extends Animal
+{
+ // Nota: Ainda precisamos substituir os métodos abstratos na
+     // classe abstrata.
+ @Override
+ public void fazerSom();
+ {
+ System.out.println("Roar");
+ }
+}
+
+// Métodos Finais
+public abstract class Mamifero()
+{
+ // Sintaxe de Métodos Finais:
+ // <modificador-de-acesso> final <tipo-de-retorno> <nome-do-método>(<argumentos>)
+
+ // Métodos finais, como, classes finais não podem ser substituídas por uma classe filha,
+    // e são, portanto, a implementação final do método.
+ public final boolean EImpulsivo()
+ {
+ return true;
+ }
+}
+
+
+// Tipo Enum
+//
+// Um tipo enum é um tipo de dado especial que permite a uma variável ser um conjunto de constantes predefinidas. A
+// variável deve ser igual a um dos valores que foram previamente definidos para ela.
+// Por serem constantes, os nomes dos campos de um tipo de enumeração estão em letras maiúsculas.
+// Na linguagem de programação Java, você define um tipo de enumeração usando a palavra-chave enum. Por exemplo, você poderia
+// especificar um tipo de enum dias-da-semana como:
+
+public enum Dia {
+ DOMINGO, SEGUNDA, TERÇA, QUARTA,
+ QUINTA, SEXTA, SABADO
+}
+
+// Nós podemos usar nosso enum Dia assim:
+
+public class EnumTeste {
+
+ // Variável Enum
+ Dia dia;
+
+ public EnumTeste(Dia dia) {
+ this.dia = dia;
+ }
+
+ public void digaComoE() {
+ switch (dia) {
+ case SEGUNDA:
+ System.out.println("Segundas são ruins.");
+ break;
+
+ case SEXTA:
+ System.out.println("Sextas são melhores.");
+ break;
+
+ case SABADO:
+ case DOMINGO:
+ System.out.println("Finais de semana são os melhores.");
+ break;
+
+ default:
+ System.out.println("Dias no meio da semana são mais ou menos.");
+ break;
+ }
+ }
+
+ public static void main(String[] args) {
+ EnumTeste primeiroDia = new EnumTeste(Dia.SEGUNDA);
+ primeiroDia.digaComoE(); // => Segundas-feiras são ruins.
+ EnumTeste terceiroDia = new EnumTeste(Dia.QUARTA);
+ terceiroDia.digaComoE(); // => Dias no meio da semana são mais ou menos.
+ }
+}
+
+// Tipos Enum são muito mais poderosos do que nós mostramos acima.
+// O corpo de um enum pode incluir métodos e outros campos.
+// Você pode ver mais em https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
+
```
## Leitura Recomendada
diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown
index e4f10a61..fd822c03 100644
--- a/pt-br/json-pt.html.markdown
+++ b/pt-br/json-pt.html.markdown
@@ -3,6 +3,7 @@ language: json
contributors:
- ["Anna Harren", "https://github.com/iirelu"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["Francisco Marques", "https://github.com/ToFran"]
translators:
- ["Miguel Araújo", "https://github.com/miguelarauj1o"]
lang: pt-br
@@ -12,10 +13,16 @@ filename: learnjson-pt.json
Como JSON é um formato de intercâmbio de dados, este será, muito provavelmente, o
"Learn X in Y minutes" mais simples existente.
-JSON na sua forma mais pura não tem comentários em reais, mas a maioria dos analisadores
-aceitarão comentários no estilo C (//, /\* \*/). Para os fins do presente, no entanto,
-tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si.
+JSON na sua forma mais pura não tem comentários, mas a maioria dos analisadores
+aceitarão comentários no estilo C (//, /\* \*/). No entanto estes devem ser evitados para otimizar a compatibilidade.
+Um valor JSON pode ser um numero, uma string, um array, um objeto, um booleano (true, false) ou null.
+
+Os browsers suportados são: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, e Safari 4.0+.
+
+A extensão dos ficheiros JSON é “.json” e o tipo de mídia de Internet (MIME) é “application/json”.
+
+Mais informação em: http://www.json.org/
```json
{
@@ -57,6 +64,6 @@ tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si.
, "outro comentário": "que bom"
},
- "que foi curto": "E, você está feito. Você já sabe tudo que JSON tem para oferecer.".
+ "que foi curto": "E, você está feito. Você já sabe tudo que JSON tem para oferecer."
}
```
diff --git a/pt-br/sass-pt.html.markdown b/pt-br/sass-pt.html.markdown
index 105896b2..3d91f1ca 100644
--- a/pt-br/sass-pt.html.markdown
+++ b/pt-br/sass-pt.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Sean Corrales", "https://github.com/droidenator"]
translators:
- ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"]
+ - ["Cássio Böck", "https://github.com/cassiobsilva"]
lang: pt-br
---
@@ -155,16 +156,6 @@ body {
background-color: rgba(0, 0, 0, 0.75);
}
-/* You may also define your own functions. Functions are very similar to
- mixins. When trying to choose between a function or a mixin, remember
- that mixins are best for generating CSS while functions are better for
- logic that might be used throughout your Sass code. The examples in
- the Math Operators' section are ideal candidates for becoming a reusable
- function. */
-
-/* This function will take a target size and the parent size and calculate
- and return the percentage */
-
/* Você também pode definir suas próprias funções. As funções são muito semelhantes aos
   mixins. Ao tentar escolher entre uma função ou um mixin, lembre-
   que mixins são os melhores para gerar CSS enquanto as funções são melhores para
@@ -319,11 +310,6 @@ ol {
padding: 0;
}
-/* Sass offers @import which can be used to import partials into a file.
- This differs from the traditional CSS @import statement which makes
- another HTTP request to fetch the imported file. Sass takes the
- imported file and combines it with the compiled code. */
-
/* Sass oferece @import que pode ser usado para importar parciais em um arquivo.
   Isso difere da declaração CSS @import tradicional, que faz
   outra solicitação HTTP para buscar o arquivo importado. Sass converte os
@@ -354,12 +340,6 @@ body {
==============================*/
-
-/* Placeholders are useful when creating a CSS statement to extend. If you
- wanted to create a CSS statement that was exclusively used with @extend,
- you can do so using a placeholder. Placeholders begin with a '%' instead
- of '.' or '#'. Placeholders will not appear in the compiled CSS. */
-
/* Os espaços reservados são úteis na criação de uma declaração CSS para ampliar. Se você
   queria criar uma instrução CSS que foi usado exclusivamente com @extend,
   Você pode fazer isso usando um espaço reservado. Espaços reservados começar com um '%' em vez
@@ -396,11 +376,6 @@ body {
============================== * /
-/* Sass provides the following operators: +, -, *, /, and %. These can
- be useful for calculating values directly in your Sass files instead
- of using values that you've already calculated by hand. Below is an example
- of a setting up a simple two column design. */
-
/* Sass fornece os seguintes operadores: +, -, *, /, e %. estes podem
   ser úteis para calcular os valores diretamente no seu Sass arquivos em vez
   de usar valores que você já calculados pela mão. Abaixo está um exemplo
diff --git a/python.html.markdown b/python.html.markdown
index 541bd36d..2b43c5fc 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -63,7 +63,7 @@ allow you to write Python 3 code that will run on Python 2, so check out the Pyt
# to carry out normal division with just one '/'.
from __future__ import division
11/4 # => 2.75 ...normal division
-11//4 # => 2 ...floored division
+11//4 # => 2 ...floored division
# Modulo operation
7 % 3 # => 1
@@ -132,6 +132,7 @@ z = "The items in the basket are %s and %s" % (x,y)
# A newer way to format strings is the format method.
# This method is the preferred way
+"{} is a {}".format("This", "placeholder")
"{0} can be {1}".format("strings", "formatted")
# You can use keywords if you don't want to count.
"{name} wants to eat {food}".format(name="Bob", food="lasagna")
@@ -148,8 +149,16 @@ None is None # => True
# very useful when dealing with primitive values, but is
# very useful when dealing with objects.
-# None, 0, and empty strings/lists all evaluate to False.
-# All other values are True
+# Any object can be used in a Boolean context.
+# The following values are considered falsey:
+# - None
+# - zero of any numeric type (e.g., 0, 0L, 0.0, 0j)
+# - empty sequences (e.g., '', (), [])
+# - empty containers (e.g., {}, set())
+# - instances of user-defined classes meeting certain conditions
+# see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
+#
+# All other values are truthy (using the bool() function on them returns True).
bool(0) # => False
bool("") # => False
@@ -238,7 +247,7 @@ li.remove(2) # Raises a ValueError as 2 is not in the list
li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again
# Get the index of the first item found
-li.index(2) # => 3
+li.index(2) # => 1
li.index(7) # Raises a ValueError as 7 is not in the list
# Check for existence in a list with "in"
@@ -261,8 +270,9 @@ tup[:2] # => (1, 2)
# You can unpack tuples (or lists) into variables
a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3
+d, e, f = 4, 5, 6 # you can leave out the parentheses
# Tuples are created by default if you leave out the parentheses
-d, e, f = 4, 5, 6
+g = 4, 5, 6 # => (4, 5, 6)
# Now look how easy it is to swap two values
e, d = d, e # d is now 5 and e is now 4
diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown
index 005495cc..b24ad555 100644
--- a/ru-ru/java-ru.html.markdown
+++ b/ru-ru/java-ru.html.markdown
@@ -451,7 +451,7 @@ public class Fruit implements Edible, Digestible {
}
}
-// В Java Вы можете наследоватьтолько один класс, однако можете реализовывать
+// В Java Вы можете наследовать только один класс, однако можете реализовывать
// несколько интерфейсов. Например:
public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo {
public void InterfaceOneMethod() {
diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown
index 8655ae4a..54499f46 100644
--- a/ru-ru/javascript-ru.html.markdown
+++ b/ru-ru/javascript-ru.html.markdown
@@ -330,7 +330,7 @@ function sayHelloInFiveSeconds(name) {
sayHelloInFiveSeconds("Адам"); // Через 5 с откроется окно «Привет, Адам!»
///////////////////////////////////
-// 5. Подробнее об объектах; конструкторы и прототипы
+// 5. Подробнее об объектах; Конструкторы и Прототипы
// Объекты могут содержать в себе функции.
var myObj = {
diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown
index dc254bf8..37b6a86e 100644
--- a/ru-ru/php-ru.html.markdown
+++ b/ru-ru/php-ru.html.markdown
@@ -483,7 +483,7 @@ echo MyClass::MY_CONST; // Выведет 'value';
echo MyClass::$staticVar; // Выведет 'static';
MyClass::myStaticMethod(); // Выведет 'I am static';
-// Новый экземпляр класса используя new
+// Создание нового экземпляра класса используя new
$my_class = new MyClass('An instance property');
// Если аргументы отсутствуют, можно не ставить круглые скобки
diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown
index 3852a550..43142eff 100644
--- a/ru-ru/python-ru.html.markdown
+++ b/ru-ru/python-ru.html.markdown
@@ -280,7 +280,7 @@ filled_dict.get("four", 4) #=> 4
# Присваивайте значение ключам так же, как и в списках
filled_dict["four"] = 4 # теперь filled_dict["four"] => 4
-# Метод setdefault вставляет() пару ключ-значение, только если такого ключа нет
+# Метод setdefault() вставляет пару ключ-значение, только если такого ключа нет
filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5
filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 998b4bf7..8720fec6 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -41,7 +41,11 @@ You shouldn't either
35 / 5 #=> 7
2**5 #=> 32
5 % 3 #=> 2
-5 ^ 6 #=> 3
+
+# Bitwise operators
+3 & 5 #=> 1
+3 | 5 #=> 7
+3 ^ 5 #=> 6
# Arithmetic is just syntactic sugar
# for calling a method on an object
@@ -77,6 +81,11 @@ false.class #=> FalseClass
2 <= 2 #=> true
2 >= 2 #=> true
+# Combined comparison operator
+1 <=> 10 #=> -1
+10 <=> 1 #=> 1
+1 <=> 1 #=> 0
+
# Logical operators
true && false #=> false
true || false #=> true
diff --git a/swift.html.markdown b/swift.html.markdown
index f451288d..1ca81bc2 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -25,6 +25,7 @@ import UIKit
// Xcode supports landmarks to annotate your code and lists them in the jump bar
// MARK: Section mark
+// MARK: - Section mark with a separator line
// TODO: Do something soon
// FIXME: Fix this code
@@ -128,6 +129,7 @@ shoppingList[1] = "bottle of water"
let emptyArray = [String]() // let == immutable
let emptyArray2 = Array<String>() // same as above
var emptyMutableArray = [String]() // var == mutable
+var explicitEmptyMutableStringArray: [String] = [] // same as above
// Dictionary
@@ -139,6 +141,7 @@ occupations["Jayne"] = "Public Relations"
let emptyDictionary = [String: Float]() // let == immutable
let emptyDictionary2 = Dictionary<String, Float>() // same as above
var emptyMutableDictionary = [String: Float]() // var == mutable
+var explicitEmptyMutableDictionary: [String: Float] = [:] // same as above
//
diff --git a/tr-tr/brainfuck-tr.html.markdown b/tr-tr/brainfuck-tr.html.markdown
index baca4217..bd842b17 100644
--- a/tr-tr/brainfuck-tr.html.markdown
+++ b/tr-tr/brainfuck-tr.html.markdown
@@ -19,7 +19,7 @@ gözardı edilir.
Brainfuck 30,000 hücresi olan ve ilk değerleri sıfır olarak atanmış bir
dizidir. İşaretçi ilk hücreyi işaret eder.
-Sekik komut vardır:
+Sekiz komut vardır:
+ : Geçerli hücrenin değerini bir artırır.
- : Geçerli hücrenin değerini bir azaltır.
> : Veri işaretçisini bir sonraki hücreye hareket ettirir(sağdaki hücreye).
diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown
index 128901de..2d4240ed 100644
--- a/tr-tr/c-tr.html.markdown
+++ b/tr-tr/c-tr.html.markdown
@@ -91,9 +91,9 @@ int main() {
// Örneğin,
printf("%lu\n", sizeof(int)); // => 4 (bir çok makinede 4-byte words)
- // If the argument of the `sizeof` operator an expression, then its argument
- // is not evaluated (except VLAs (see below)).
- // The value it yields in this case is a compile-time constant.
+ // Eger arguman düzenli ifae olan sizeof operatoru ise degerlendirilmez.
+ // VLAs hariç asagiya bakiniz).
+ // Bu durumda verimliligin degeri derleme-zamani sabitidir.
int a = 1;
// size_t bir objeyi temsil etmek için kullanılan 2 byte uzunluğundaki bir
@@ -101,7 +101,7 @@ int main() {
size_t size = sizeof(a++); // a++ is not evaluated
printf("sizeof(a++) = %zu where a = %d\n", size, a);
- // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture)
+ // yazdirilan "sizeof(a++) = 4 where a = 1" (32-bit mimaride)
// Diziler somut bir boyut ile oluşturulmalıdır.
char my_char_array[20]; // Bu dizi 1 * 20 = 20 byte alan kaplar
@@ -119,19 +119,19 @@ int main() {
my_array[1] = 2;
printf("%d\n", my_array[1]); // => 2
- // In C99 (and as an optional feature in C11), variable-length arrays (VLAs)
- // can be declared as well. The size of such an array need not be a compile
- // time constant:
- printf("Enter the array size: "); // ask the user for an array size
+ // C99'da (ve C11 istege bagli bir ozellik olarak), değidken-uzunluklu diziler (VLAs) bildirilebilirler.
+ // Böyle bir dizinin boyuunu derlenmesi gerekmez
+ // zaman sabiti:
+ printf("Enter the array size: "); // dizi boyutu kullaniciya soruluyor
char buf[0x100];
fgets(buf, sizeof buf, stdin);
- // strtoul parses a string to an unsigned integer
+ // strtoul isaretsiz integerlar icin string ayiricisidir.
size_t size = strtoul(buf, NULL, 10);
int var_length_array[size]; // declare the VLA
printf("sizeof array = %zu\n", sizeof var_length_array);
- // A possible outcome of this program may be:
+ // Bu programın olası bir sonucu olabilir:
// > Enter the array size: 10
// > sizeof array = 40
@@ -151,8 +151,8 @@ int main() {
printf("%d\n", a_string[16]); // => 0
// i.e., byte #17 is 0 (as are 18, 19, and 20)
- // If we have characters between single quotes, that's a character literal.
- // It's of type `int`, and *not* `char` (for historical reasons).
+ // Tek tirnak arasinda karakterlere sahipsek, bu karakterler degismezdir.
+ // Tip `int` ise, `char` *degildir* (tarihsel sebeplerle).
int cha = 'a'; // fine
char chb = 'a'; // fine too (implicit conversion from int to char)
@@ -201,10 +201,10 @@ int main() {
0x01 << 1; // => 0x02 (bitwise left shift (by 1))
0x02 >> 1; // => 0x01 (bitwise right shift (by 1))
- // Be careful when shifting signed integers - the following are undefined:
- // - shifting into the sign bit of a signed integer (int a = 1 << 32)
- // - left-shifting a negative number (int a = -1 << 2)
- // - shifting by an offset which is >= the width of the type of the LHS:
+ // Isaretli sayilari kaydirirken dikkatli olun - tanimsizlar sunlardir:
+ // - isaretli sayinin isaret bitinde yapilan kaydirma (int a = 1 << 32)
+ // - negatif sayilarda sol kaydirma (int a = -1 << 2)
+ // - LHS tipinde >= ile olan ofset genisletmelerde yapilan kaydirma:
// int a = 1 << 32; // UB if int is 32 bits wide
///////////////////////////////////////
@@ -485,4 +485,4 @@ Readable code is better than clever code and fast code. For a good, sane coding
Diğer taraftan google sizin için bir arkadaş olabilir.
-[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file
+[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member
diff --git a/ua-ua/javascript-ua.html.markdown b/ua-ua/javascript-ua.html.markdown
new file mode 100644
index 00000000..fedbf5ac
--- /dev/null
+++ b/ua-ua/javascript-ua.html.markdown
@@ -0,0 +1,501 @@
+---
+language: javascript
+contributors:
+ - ["Adam Brenecki", "http://adam.brenecki.id.au"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
+filename: javascript-ru.js
+translators:
+ - ["Alexey Gonchar", "http://github.com/finico"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+lang: ru-ru
+---
+
+JavaScript було створено в 1995 році Бренданом Айком, який працював у копаніх Netscape.
+Він був задуманий як проста мова сценаріїв для веб-сайтів, який би доповнював Java
+для більш складних веб-застосунків. Але тісна інтеграція з веб-сторінками і
+вбудована підтримка браузерами призвела до того, що JavaScript став популярніший
+за власне Java.
+
+Зараз JavaScript не обмежується тільки веб-браузеорм. Наприклад, Node.js,
+програмна платформа, що дозволяє виконувати JavaScript код з використанням
+рушія V8 від браузера Google Chrome, стає все більш і більш популярною.
+
+```js
+// С-подібні коментарі. Однорядкові коментарі починаються з двох символів /(слеш)
+/* а багаторядкові коментарі починаються з послідовності слеша та зірочки і
+ закінчуються символами зірочка-слеш */
+
+Інструкції можуть закінчуватися крапкою з комою ;
+doStuff();
+
+// ... але не обов’язково, тому що крапка з комою автоматично вставляється на
+// місці символу нового рядка, крім деяких випадків.
+doStuff()
+
+// Ми завжди будемо використовувати крапку з комою в цьому посібнику, тому що ці
+// винятки можуть призвести до неочікуваних результатів
+
+///////////////////////////////////
+// 1. Числа, Рядки і Оператори
+
+// В JavaScript числа зберігаються тільки в одному форматі (64-bit IEEE 754 double)
+// Цей тип має 52-бітну мантису, якої достатньо для збереження чисел з
+// точністю до 9✕10¹⁵.
+3; // = 3
+1.5; // = 1.5
+
+// Деякі прості арифметичні операції працють так, як ми очікуємо.
+1 + 1; // = 2
+0.1 + 0.2; // = 0.30000000000000004 (а деякі - ні)
+8 - 1; // = 7
+10 * 2; // = 20
+35 / 5; // = 7
+
+// В тому числі ділення з остачою
+5 / 2; // = 2.5
+
+// В JavaScript є побітові операції; коли ви виконуєте таку операцію,
+// число з плаваючою точкою переводиться в ціле зі знаком
+// довжиною *до* 32 розрядів.
+1 << 2; // = 4
+
+// Пріоритет у виразах можна задати явно круглими дужками
+(1 + 3) * 2; // = 8
+
+// Є три спеціальні значення, які не є реальними числами:
+Infinity; // "нескінченність", наприклад, як результат ділення на 0
+-Infinity; // "мінус нескінченність", як результат ділення від’ємного числа на 0
+NaN; // "не число", наприклад, ділення 0/0
+
+// Логічні типи
+true;
+false;
+
+// Рядки створюються за допомогою подвійних та одинарних лапок
+'абв';
+"Hello, world!";
+
+// Для логічного заперечення використовується знак оклику.
+!true; // = false
+!false; // = true
+
+// Строга рівність ===
+1 === 1; // = true
+2 === 1; // = false
+
+// Строга нерівність !==
+1 !== 1; // = false
+2 !== 1; // = true
+
+// Інші оператори порівняння
+1 < 10; // = true
+1 > 10; // = false
+2 <= 2; // = true
+2 >= 2; // = true
+
+// Рядки об’єднуються за допомогою оператор +
+"hello, " + "world!"; // = "hello, world!"
+
+// І порівнюються за допомогою > і <
+"a" < "b"; // = true
+
+// Перевірка на рівність з приведнням типів здійснюється оператором ==
+"5" == 5; // = true
+null == undefined; // = true
+
+// ... але приведення не виконується при ===
+"5" === 5; // = false
+null === undefined; // = false
+
+// ... приведення типів може призвести до дивних результатів
+13 + !0; // 14
+"13" + !0; // '13true'
+
+// Можна отримати доступ до будь-якого символа рядка за допомгою charAt
+"Это строка".charAt(0); // = 'Э'
+
+// ... або використати метод substring, щоб отримати більший кусок
+"Hello, world".substring(0, 5); // = "Hello"
+
+// length - це не метод, а поле
+"Hello".length; // = 5
+
+// Типи null и undefined
+null; // навмисна відсутність результату
+undefined; // використовується для позначення відсутності присвоєного значення
+
+// false, null, undefined, NaN, 0 и "" — хиба; все інше - істина.
+// Потрібно відмітити, що 0 — це зиба, а "0" — істина, не зважаючи на те що:
+// 0 == "0".
+
+///////////////////////////////////
+// 2. Змінні, Масиви, Об’єкти
+
+// Змінні оголошуються за допомогою ключового слова var. JavaScript — мова з
+// динамічною типізацією, тому не потрібно явно вказувати тип. Для присвоєння
+// значення змінної використовується символ =
+var someVar = 5;
+
+// якщо пропустити слово var, ви не отримаєте повідомлення про помилку, ...
+someOtherVar = 10;
+
+// ... але ваша змінна буде створення в глобальному контексті, а не там, де
+// ви її оголосили
+
+// Змінні, які оголошені без присвоєння, автоматично приймають значення undefined
+var someThirdVar; // = undefined
+
+// У математичних операцій є скорочені форми:
+someVar += 5; // як someVar = someVar + 5;
+someVar *= 10; // тепер someVar = 100
+
+// Інкремент і декремент
+someVar++; // тепер someVar дорівнює 101
+someVar--; // а зараз 100
+
+// Масиви — це нумеровані списку, які зберігають значення будь-якого типу.
+var myArray = ["Hello", 45, true];
+
+// Доступ до елементів можна отримати за допомогою синтаксиса з квадратними дужками
+// Індексація починається з нуля
+myArray[1]; // = 45
+
+// Массивы можно изменять, как и их длину,
+myArray.push("Мир");
+myArray.length; // = 4
+
+// додавання і редагування елементів
+myArray[3] = "Hello";
+
+// Об’єкти в JavaScript сході на словники або асоціативні масиви в інших мовах
+var myObj = {key1: "Hello", key2: "World"};
+
+// Ключі - це рядки, але лапки не обов’язкі, якщо ключ задовольняє
+// правилам формування назв змінних. Значення можуть бути будь-яких типів.
+var myObj = {myKey: "myValue", "my other key": 4};
+
+// Атрибути можна отримати використовуючи квадратні дужки
+myObj["my other key"]; // = 4
+
+// Або через точку, якщо ключ є правильним ідентифікатором
+myObj.myKey; // = "myValue"
+
+// Об’єкти можна динамічно змінювати й додавати нові поля
+myObj.myThirdKey = true;
+
+// Коли ви звертаєтесб до поля, яке не існує, ви отримуєте значення undefined
+myObj.myFourthKey; // = undefined
+
+///////////////////////////////////
+// 3. Управляючі конструкції
+
+// Синтаксис для цього розділу майже такий самий, як у Java
+
+// Умовна конструкція
+var count = 1;
+if (count == 3) {
+ // виконується, якщо count дорівнює 3
+} else if (count == 4) {
+ // ..
+} else {
+ // ...
+}
+
+// ... цикл while.
+while (true){
+ // Нескінченний цикл!
+}
+
+// Цикл do-while такий самий, як while, але завжди виконується принаймні один раз.
+var input
+do {
+ input = getInput();
+} while (!isValid(input))
+
+// цикл for такий самий, кяк в C і Java:
+// ініціалізація; умова; крок.
+for (var i = 0; i < 5; i++) {
+ // виконається 5 разів
+}
+
+// && — логічне І, || — логічне АБО
+if (house.size == "big" && house.color == "blue") {
+ house.contains = "bear";
+}
+if (color == "red" || color == "blue") {
+ // колір червоний або синій
+}
+
+// && і || використовують скорочене обчислення
+// тому їх можна використовувати для задання значень за замовчуванням.
+var name = otherName || "default";
+
+// Оператор switch виконує перевірку на рівність за допомогою ===
+// використовуйте break, щоб призупити виконання наступного case,
+grade = 4;
+switch (grade) {
+ case 5:
+ console.log("Відмінно");
+ break;
+ case 4:
+ console.log("Добре");
+ break;
+ case 3:
+ console.log("Можна краще");
+ break;
+ default:
+ console.log("Погано!");
+ break;
+}
+
+
+///////////////////////////////////
+// 4. Функції, область видимості і замикання
+
+// Функції в JavaScript оголошуються за допомогою ключового слова function.
+function myFunction(thing) {
+ return thing.toUpperCase();
+}
+myFunction("foo"); // = "FOO"
+
+// Зверність увагу, що значення яке буде повернено, повинно починатися на тому ж
+// рядку, що і ключове слово return, інакше завжди буде повертатися значення undefined
+// із-за автоматичної вставки крапки з комою
+function myFunction()
+{
+ return // <- крапка з комою вставляється автоматично
+ {
+ thisIsAn: 'object literal'
+ }
+}
+myFunction(); // = undefined
+
+// В JavaScript функції - це об`єкти першого класу, тому вони можуть присвоюватися
+// іншим змінним і передаватися іншим функціям, наприклад, щоб визначити обробник
+// події.
+function myFunction() {
+ // код буде виконано через 5 сек.
+}
+setTimeout(myFunction, 5000);
+// setTimeout не є частиною мови, але реалізований в браузерах і Node.js
+
+// Функции не обязательно должны иметь имя при объявлении — вы можете написать
+// анонимное определение функции непосредственно в аргументе другой функции.
+// Функції не обов’язково мають мати ім’я при оголошенні — ви можете написати
+// анонімну функцію прямо в якості аргумента іншої функції
+setTimeout(function() {
+ // Цей код буде виконано через п’ять секунд
+}, 5000);
+
+// В JavaScript реалізована концепція області видимості; функції мають свою
+// область видимости, а інші блоки не мають
+if (true) {
+ var i = 5;
+}
+i; // = 5, а не undefined, як це звичайно буває в інших мова
+
+// Така особливість призвела до шаблону "анонімних функцій, які викликають самих себе"
+// що дозволяє уникнути проникнення змінних в глобальну область видимості
+(function() {
+ var temporary = 5;
+ // об’єкт window зберігає глобальний контекст; таким чином ми можемо також додавати
+ // змінні до глобальної області
+ window.permanent = 10;
+})();
+temporary; // повідомлення про помилку ReferenceError
+permanent; // = 10
+
+// Одной из самых мощных возможностей JavaScript являются замыкания. Если функция
+// определена внутри другой функции, то внутренняя функция имеет доступ к
+// переменным внешней функции даже после того, как контекст выполнения выйдет из
+// внешней функции.
+// Замикання - одна з найпотужніших інтрументів JavaScript. Якщо функція визначена
+// всередині іншої функції, то внутрішня функція має доступ до змінних зовнішньої
+// функції навіть після того, як код буде виконуватися поза контекстом зовнішньої функції
+function sayHelloInFiveSeconds(name) {
+ var prompt = "Hello, " + name + "!";
+ // Внутрішня функція зберігається в локальній області так,
+ // ніби функція була оголошена за допомогою ключового слова var
+ function inner() {
+ alert(prompt);
+ }
+ setTimeout(inner, 5000);
+ // setTimeout асинхронна, тому функція sayHelloInFiveSeconds зразу завершиться,
+ // після чого setTimeout викличе функцію inner. Але функція inner
+ // «замкнута» кругом sayHelloInFiveSeconds, вона все рівно має доступ до змінної prompt
+}
+sayHelloInFiveSeconds("Адам"); // Через 5 с відкриється вікно «Hello, Адам!»
+
+///////////////////////////////////
+// 5. Об’єкти: конструктори і прототипи
+
+// Об’єкти можуть містити функції
+var myObj = {
+ myFunc: function() {
+ return "Hello, world!";
+ }
+};
+myObj.myFunc(); // = "Hello, world!"
+
+// Функції, що прикріплені до об’єктів мають доступ до поточного об’єкта за
+// допомогою ключового слова this.
+myObj = {
+ myString: "Hello, world!",
+ myFunc: function() {
+ return this.myString;
+ }
+};
+myObj.myFunc(); // = "Hello, world!"
+
+// Значення this залежить від того, як функція викликається
+// а не від того, де вона визначена. Таким чином наша функція не працює, якщо
+// вона викликана не в контексті об’єкта
+var myFunc = myObj.myFunc;
+myFunc(); // = undefined
+
+// Функція може бути присвоєна іншому об’єкту. Тоді вона матиме доступ до
+// цього об’єкта через this
+var myOtherFunc = function() {
+}
+myObj.myOtherFunc = myOtherFunc;
+myObj.myOtherFunc(); // = "HELLO, WORLD!"
+
+// Контекст виконання функції можна задати за допомогою сall або apply
+var anotherFunc = function(s) {
+ return this.myString + s;
+}
+anotherFunc.call(myObj, " Hello!"); // = "Hello, world! Hello!"
+
+// Функцiя apply приймає в якості аргументу масив
+anotherFunc.apply(myObj, [" Hello!"]); // = "Hello, world! Hello!"
+
+// apply можна використати, коли функція працює послідовністю аргументів, а
+// ви хочете передати масив
+Math.min(42, 6, 27); // = 6
+Math.min([42, 6, 27]); // = NaN (Ой-ой!)
+Math.min.apply(Math, [42, 6, 27]); // = 6
+
+// Але call і apply — тимчасові. Коли ми хочемо зв’язати функцію і об’єкт
+// використовують bind
+var boundFunc = anotherFunc.bind(myObj);
+boundFunc(" Hello!"); // = "Hello world, Hello!"
+
+// Bind можна використати для задання аргументів
+var product = function(a, b) { return a * b; }
+var doubler = product.bind(this, 2);
+doubler(8); // = 16
+
+// Коли ви викликаєте функцію за допомогою ключового слова new, створюється новий об’єкт,
+// доступний функції за допомогою this. Такі функції називають конструкторами.
+var MyConstructor = function() {
+ this.myNumber = 5;
+}
+myNewObj = new MyConstructor(); // = {myNumber: 5}
+myNewObj.myNumber; // = 5
+
+// У кожного об’єкта є прототип. Коли ви звертаєтесь до поля, яке не існує в цьому
+// об’єктів, інтерпретатор буде шукати поле в прототипі
+
+// Деякі реалізації мови дозволяють отримати доступ до прототипа об’єкта через
+// "магічну" властивість __proto__. Це поле не є частиною стандарта, але існують
+// стандартні способи використання прототипів, які ми побачимо пізніше
+var myObj = {
+ myString: "Hello, world!"
+};
+var myPrototype = {
+ meaningOfLife: 42,
+ myFunc: function() {
+ return this.myString.toLowerCase()
+ }
+};
+
+myObj.__proto__ = myPrototype;
+myObj.meaningOfLife; // = 42
+
+// Аналогічно для функцій
+myObj.myFunc(); // = "Hello, world!"
+
+// Якщо інтерпретатор не знайде властивість в прототипі, то він продвжить пошук
+// в прототипі прототипа і так далі
+myPrototype.__proto__ = {
+ myBoolean: true
+};
+myObj.myBoolean; // = true
+
+// Кожег об’єкт зберігає посилання на свій прототип. Це значить, що ми можемо змінити
+// наш прототип, і наші зміни будуть всюди відображені.
+myPrototype.meaningOfLife = 43;
+myObj.meaningOfLife; // = 43
+
+// Ми сказали, що властивість __proto__ нестандартне, і нема ніякого стандартного способу
+// змінити прототип об’єкта, що вже існує. Але є два способи створити новий об’єкт зі заданим
+// прототипом
+
+// Перший спосіб — це Object.create, який з’явився JavaScript недавно,
+// а тому в деяких реалізаціях може бути не доступним.
+var myObj = Object.create(myPrototype);
+myObj.meaningOfLife; // = 43
+
+// Другий спосіб: у конструкторів є властивість з іменем prototype. Це *не*
+// прототип функції-конструктора, це прототип для нових об’єктів, які будуть створені
+// цим конструктором і ключового слова new.
+MyConstructor.prototype = {
+ myNumber: 5,
+ getMyNumber: function() {
+ return this.myNumber;
+ }
+};
+var myNewObj2 = new MyConstructor();
+myNewObj2.getMyNumber(); // = 5
+myNewObj2.myNumber = 6
+myNewObj2.getMyNumber(); // = 6
+
+// У вбудованих типів(рядок, число) теж є конструктори, які створють еквівалентні
+// об’єкти-обгортки
+var myNumber = 12;
+var myNumberObj = new Number(12);
+myNumber == myNumberObj; // = true
+
+// Але вони не ідентичні
+typeof myNumber; // = 'number'
+typeof myNumberObj; // = 'object'
+myNumber === myNumberObj; // = false
+if (0) {
+ // Этот код не выполнится, потому что 0 - это ложь.
+}
+
+// Об’єкти-обгортки і вбудовані типи мають спільні прототипи, тому
+// ви можете розширити функціонал рядків:
+String.prototype.firstCharacter = function() {
+ return this.charAt(0);
+}
+"abc".firstCharacter(); // = "a"
+
+// Такий прийом часто використовуються в поліфілах, які реалізують нові можливості
+// JavaScript в старій реалізації мови, так що вони можуть бути використані в старих
+// середовищах
+
+// Наприклад, Object.create доступний не у всіх реалізація, но ми можемо
+// використати функції за допомогою наступного поліфіла:
+if (Object.create === undefined) { // не перезаписываем метод, если он существует
+ Object.create = function(proto) {
+ // Створюємо правильний конструктор з правильним прототипом
+ var Constructor = function(){};
+ Constructor.prototype = proto;
+
+ return new Constructor();
+ }
+}
+```
+
+## Що почитати
+
+[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript
+[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
+[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core
+[4]: http://www.learneroo.com/modules/64/nodes/350
+[5]: http://bonsaiden.github.io/JavaScript-Garden/
+[6]: http://www.amazon.com/gp/product/0596805527/
+[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
+[8]: http://eloquentjavascript.net/
+[9]: http://jstherightway.org/
diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown
index bdfdcc10..accdbf56 100644
--- a/visualbasic.html.markdown
+++ b/visualbasic.html.markdown
@@ -32,6 +32,9 @@ Module Module1
Console.WriteLine("50. About")
Console.WriteLine("Please Choose A Number From The Above List")
Dim selection As String = Console.ReadLine
+ ' The "Case" in the Select statement is optional.
+ ' For example, "Select selection" instead of "Select Case selection"
+ ' will also work.
Select Case selection
Case "1" 'HelloWorld Output
Console.Clear() 'Clears the application and opens the private sub