summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--bash.html.markdown4
-rw-r--r--c++.html.markdown16
-rw-r--r--compojure.html.markdown8
-rw-r--r--elisp.html.markdown12
-rw-r--r--erlang.html.markdown96
-rw-r--r--fr-fr/r-fr.html.markdown746
-rw-r--r--haxe.html.markdown23
-rw-r--r--java.html.markdown202
-rw-r--r--nim.html.markdown20
-rw-r--r--zh-cn/javascript-cn.html.markdown2
10 files changed, 940 insertions, 189 deletions
diff --git a/bash.html.markdown b/bash.html.markdown
index ee783c14..08182c2c 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -56,7 +56,7 @@ echo '$Variable'
# String substitution in variables
echo ${Variable/Some/A}
-# This will substitute the first occurance of "Some" with "A"
+# This will substitute the first occurrence of "Some" with "A"
# Substring from a variable
Length=7
@@ -74,7 +74,7 @@ echo "Last program return value: $?"
echo "Script's PID: $$"
echo "Number of arguments: $#"
echo "Scripts arguments: $@"
-echo "Scripts arguments seperated in different variables: $1 $2..."
+echo "Scripts arguments separated in different variables: $1 $2..."
# Reading a value from input:
echo "What's your name?"
diff --git a/c++.html.markdown b/c++.html.markdown
index 66d4aeb1..5cd491b9 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -288,7 +288,7 @@ public:
// Functions can also be defined inside the class body.
// Functions defined as such are automatically inlined.
- void bark() const { std::cout << name << " barks!\n" }
+ void bark() const { std::cout << name << " barks!\n"; }
// Along with constructors, C++ provides destructors.
// These are called when an object is deleted or falls out of scope.
@@ -300,7 +300,7 @@ public:
}; // A semicolon must follow the class definition.
// Class member functions are usually implemented in .cpp files.
-void Dog::Dog()
+Dog::Dog()
{
std::cout << "A dog has been constructed\n";
}
@@ -323,7 +323,7 @@ void Dog::print() const
std::cout << "Dog is " << name << " and weighs " << weight << "kg\n";
}
-void Dog::~Dog()
+Dog::~Dog()
{
cout << "Goodbye " << name << "\n";
}
@@ -332,7 +332,7 @@ int main() {
Dog myDog; // prints "A dog has been constructed"
myDog.setName("Barkley");
myDog.setWeight(10);
- myDog.printDog(); // prints "Dog is Barkley and weighs 10 kg"
+ myDog.print(); // prints "Dog is Barkley and weighs 10 kg"
return 0;
} // prints "Goodbye Barkley"
@@ -341,7 +341,7 @@ int main() {
// This class inherits everything public and protected from the Dog class
class OwnedDog : public Dog {
- void setOwner(const std::string& dogsOwner)
+ void setOwner(const std::string& dogsOwner);
// Override the behavior of the print function for all OwnedDogs. See
// http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
@@ -425,7 +425,7 @@ int main () {
Point up (0,1);
Point right (1,0);
// This calls the Point + operator
- // Point up calls the + (function) with right as its paramater
+ // Point up calls the + (function) with right as its parameter
Point result = up + right;
// Prints "Result is upright (1,1)"
cout << "Result is upright (" << result.x << ',' << result.y << ")\n";
@@ -464,7 +464,7 @@ intBox.insert(123);
Box<Box<int> > boxOfBox;
boxOfBox.insert(intBox);
-// Up until C++11, you muse place a space between the two '>'s, otherwise '>>'
+// Up until C++11, you must place a space between the two '>'s, otherwise '>>'
// will be parsed as the right shift operator.
// You will sometimes see
@@ -712,7 +712,7 @@ Foo f1;
f1 = f2;
```
-Futher Reading:
+Further Reading:
An up-to-date language reference can be found at
<http://cppreference.com/w/cpp>
diff --git a/compojure.html.markdown b/compojure.html.markdown
index 36a8d123..32181e26 100644
--- a/compojure.html.markdown
+++ b/compojure.html.markdown
@@ -155,8 +155,8 @@ Now, your handlers may utilize query parameters:
```clojure
(defroutes myapp
(GET "/posts" req
- (let [title (get (:params req) "title")
- author (get (:params req) "author")]
+ (let [title (get (:params req) :title)
+ author (get (:params req) :author)]
(str "Title: " title ", Author: " author))))
```
@@ -165,8 +165,8 @@ Or, for POST and PUT requests, form parameters as well
```clojure
(defroutes myapp
(POST "/posts" req
- (let [title (get (:params req) "title")
- author (get (:params req) "author")]
+ (let [title (get (:params req) :title)
+ author (get (:params req) :author)]
(str "Title: " title ", Author: " author))))
```
diff --git a/elisp.html.markdown b/elisp.html.markdown
index 3208ffb8..3bed5d1c 100644
--- a/elisp.html.markdown
+++ b/elisp.html.markdown
@@ -29,7 +29,7 @@ filename: learn-emacs-lisp.el
;; I hereby decline any responsability. Have fun!
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;
+;;
;; Fire up Emacs.
;;
;; Hit the `q' key to dismiss the welcome message.
@@ -42,9 +42,9 @@ filename: learn-emacs-lisp.el
;; The scratch buffer is the default buffer when opening Emacs.
;; You are never editing files: you are editing buffers that you
;; can save to a file.
-;;
+;;
;; "Lisp interaction" refers to a set of commands available here.
-;;
+;;
;; Emacs has a built-in set of commands available in every buffer,
;; and several subsets of commands available when you activate a
;; specific mode. Here we use the `lisp-interaction-mode', which
@@ -109,7 +109,7 @@ filename: learn-emacs-lisp.el
;; The empty parentheses in the function's definition means that
;; it does not accept arguments. But always using `my-name' is
;; boring, let's tell the function to accept one argument (here
-;; the argument is called "name"):
+;; the argument is called "name"):
(defun hello (name) (insert "Hello " name))
;; `C-xC-e' => hello
@@ -305,7 +305,7 @@ filename: learn-emacs-lisp.el
(defun boldify-names ()
(switch-to-buffer-other-window "*test*")
(goto-char (point-min))
- (while (re-search-forward "Bonjour \\([^!]+\\)!" nil 't)
+ (while (re-search-forward "Bonjour \\(.+\\)!" nil 't)
(add-text-properties (match-beginning 1)
(match-end 1)
(list 'face 'bold)))
@@ -318,7 +318,7 @@ filename: learn-emacs-lisp.el
;; The regular expression is "Bonjour \\(.+\\)!" and it reads:
;; the string "Bonjour ", and
;; a group of | this is the \\( ... \\) construct
-;; any character not ! | this is the [^!]
+;; any character | this is the .
;; possibly repeated | this is the +
;; and the "!" string.
diff --git a/erlang.html.markdown b/erlang.html.markdown
index a7390c3e..a3b571d1 100644
--- a/erlang.html.markdown
+++ b/erlang.html.markdown
@@ -18,7 +18,7 @@ filename: learnerlang.erl
% Periods (`.`) (followed by whitespace) separate entire functions and
% expressions in the shell.
% Semicolons (`;`) separate clauses. We find clauses in several contexts:
-% function definitions and in `case`, `if`, `try..catch` and `receive`
+% function definitions and in `case`, `if`, `try..catch`, and `receive`
% expressions.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -27,20 +27,20 @@ filename: learnerlang.erl
Num = 42. % All variable names must start with an uppercase letter.
-% Erlang has single assignment variables, if you try to assign a different value
-% to the variable `Num`, you’ll get an error.
+% Erlang has single-assignment variables; if you try to assign a different
+% value to the variable `Num`, you’ll get an error.
Num = 43. % ** exception error: no match of right hand side value 43
% In most languages, `=` denotes an assignment statement. In Erlang, however,
-% `=` denotes a pattern matching operation. `Lhs = Rhs` really means this:
-% evaluate the right side (Rhs), and then match the result against the pattern
-% on the left side (Lhs).
+% `=` denotes a pattern-matching operation. `Lhs = Rhs` really means this:
+% evaluate the right side (`Rhs`), and then match the result against the
+% pattern on the left side (`Lhs`).
Num = 7 * 6.
-% Floating point number.
+% Floating-point number.
Pi = 3.14159.
-% Atoms, are used to represent different non-numerical constant values. Atoms
+% Atoms are used to represent different non-numerical constant values. Atoms
% start with lowercase letters, followed by a sequence of alphanumeric
% characters or the underscore (`_`) or at (`@`) sign.
Hello = hello.
@@ -53,34 +53,34 @@ AtomWithSpace = 'some atom with space'.
% Tuples are similar to structs in C.
Point = {point, 10, 45}.
-% If we want to extract some values from a tuple, we use the pattern matching
+% If we want to extract some values from a tuple, we use the pattern-matching
% operator `=`.
{point, X, Y} = Point. % X = 10, Y = 45
% We can use `_` as a placeholder for variables that we’re not interested in.
% The symbol `_` is called an anonymous variable. Unlike regular variables,
-% several occurrences of _ in the same pattern don’t have to bind to the same
-% value.
+% several occurrences of `_` in the same pattern don’t have to bind to the
+% same value.
Person = {person, {name, {first, joe}, {last, armstrong}}, {footsize, 42}}.
{_, {_, {_, Who}, _}, _} = Person. % Who = joe
% We create a list by enclosing the list elements in square brackets and
% separating them with commas.
% The individual elements of a list can be of any type.
-% The first element of a list is the head of the list. If you imagine removing the
-% head from the list, what’s left is called the tail of the list.
+% The first element of a list is the head of the list. If you imagine removing
+% the head from the list, what’s left is called the tail of the list.
ThingsToBuy = [{apples, 10}, {pears, 6}, {milk, 3}].
% If `T` is a list, then `[H|T]` is also a list, with head `H` and tail `T`.
% The vertical bar (`|`) separates the head of a list from its tail.
% `[]` is the empty list.
-% We can extract elements from a list with a pattern matching operation. If we
+% We can extract elements from a list with a pattern-matching operation. If we
% have a nonempty list `L`, then the expression `[X|Y] = L`, where `X` and `Y`
% are unbound variables, will extract the head of the list into `X` and the tail
% of the list into `Y`.
[FirstThing|OtherThingsToBuy] = ThingsToBuy.
% FirstThing = {apples, 10}
-% OtherThingsToBuy = {pears, 6}, {milk, 3}
+% OtherThingsToBuy = [{pears, 6}, {milk, 3}]
% There are no strings in Erlang. Strings are really just lists of integers.
% Strings are enclosed in double quotation marks (`"`).
@@ -117,17 +117,19 @@ c(geometry). % {ok,geometry}
geometry:area({rectangle, 10, 5}). % 50
geometry:area({circle, 1.4}). % 6.15752
-% In Erlang, two functions with the same name and different arity (number of arguments)
-% in the same module represent entirely different functions.
+% In Erlang, two functions with the same name and different arity (number of
+% arguments) in the same module represent entirely different functions.
-module(lib_misc).
--export([sum/1]). % export function `sum` of arity 1 accepting one argument: list of integers.
+-export([sum/1]). % export function `sum` of arity 1
+ % accepting one argument: list of integers.
sum(L) -> sum(L, 0).
sum([], N) -> N;
sum([H|T], N) -> sum(T, H+N).
-% Funs are "anonymous" functions. They are called this way because they have no
-% name. However they can be assigned to variables.
-Double = fun(X) -> 2*X end. % `Double` points to an anonymous function with handle: #Fun<erl_eval.6.17052888>
+% Funs are "anonymous" functions. They are called this way because they have
+% no name. However, they can be assigned to variables.
+Double = fun(X) -> 2 * X end. % `Double` points to an anonymous function
+ % with handle: #Fun<erl_eval.6.17052888>
Double(2). % 4
% Functions accept funs as their arguments and can return funs.
@@ -140,8 +142,9 @@ Triple(5). % 15
% The notation `[F(X) || X <- L]` means "the list of `F(X)` where `X` is taken
% from the list `L`."
L = [1,2,3,4,5].
-[2*X || X <- L]. % [2,4,6,8,10]
-% A list comprehension can have generators and filters which select subset of the generated values.
+[2 * X || X <- L]. % [2,4,6,8,10]
+% A list comprehension can have generators and filters, which select subset of
+% the generated values.
EvenNumbers = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4]
% Guards are constructs that we can use to increase the power of pattern
@@ -155,17 +158,24 @@ max(X, Y) -> Y.
% A guard is a series of guard expressions, separated by commas (`,`).
% The guard `GuardExpr1, GuardExpr2, ..., GuardExprN` is true if all the guard
-% expressions `GuardExpr1, GuardExpr2, ...` evaluate to true.
+% expressions `GuardExpr1`, `GuardExpr2`, ..., `GuardExprN` evaluate to `true`.
is_cat(A) when is_atom(A), A =:= cat -> true;
is_cat(A) -> false.
is_dog(A) when is_atom(A), A =:= dog -> true;
is_dog(A) -> false.
-% A `guard sequence` is either a single guard or a series of guards, separated
-%by semicolons (`;`). The guard sequence `G1; G2; ...; Gn` is true if at least
-% one of the guards `G1, G2, ...` evaluates to true.
-is_pet(A) when is_dog(A); is_cat(A) -> true;
-is_pet(A) -> false.
+% A guard sequence is either a single guard or a series of guards, separated
+% by semicolons (`;`). The guard sequence `G1; G2; ...; Gn` is true if at
+% least one of the guards `G1`, `G2`, ..., `Gn` evaluates to `true`.
+is_pet(A) when is_atom(A), (A =:= dog) or (A =:= cat) -> true;
+is_pet(A) -> false.
+
+% Warning: not all valid Erlang expressions can be used as guard expressions;
+% in particular, our `is_cat` and `is_dog` functions cannot be used within the
+% guard sequence in `is_pet`'s definition. For a description of the
+% expressions allowed in guard sequences, refer to this
+% [section](http://erlang.org/doc/reference_manual/expressions.html#id81912)
+% of the Erlang reference manual.
% Records provide a method for associating a name with a particular element in a
% tuple.
@@ -188,7 +198,7 @@ X = #todo{}.
X1 = #todo{status = urgent, text = "Fix errata in book"}.
% #todo{status = urgent, who = joe, text = "Fix errata in book"}
X2 = X1#todo{status = done}.
-% #todo{status = done,who = joe,text = "Fix errata in book"}
+% #todo{status = done, who = joe, text = "Fix errata in book"}
% `case` expressions.
% `filter` returns a list of all elements `X` in a list `L` for which `P(X)` is
@@ -209,8 +219,8 @@ max(X, Y) ->
true -> nil
end.
-% Warning: at least one of the guards in the `if` expression must evaluate to true;
-% otherwise, an exception will be raised.
+% Warning: at least one of the guards in the `if` expression must evaluate to
+% `true`; otherwise, an exception will be raised.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -218,7 +228,7 @@ max(X, Y) ->
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Exceptions are raised by the system when internal errors are encountered or
-% explicitly in code by calling `throw(Exception)`, `exit(Exception)` or
+% explicitly in code by calling `throw(Exception)`, `exit(Exception)`, or
% `erlang:error(Exception)`.
generate_exception(1) -> a;
generate_exception(2) -> throw(a);
@@ -227,7 +237,7 @@ generate_exception(4) -> {'EXIT', a};
generate_exception(5) -> erlang:error(a).
% Erlang has two methods of catching an exception. One is to enclose the call to
-% the function, which raised the exception within a `try...catch` expression.
+% the function that raises the exception within a `try...catch` expression.
catcher(N) ->
try generate_exception(N) of
Val -> {N, normal, Val}
@@ -241,23 +251,24 @@ catcher(N) ->
% exception, it is converted into a tuple that describes the error.
catcher(N) -> catch generate_exception(N).
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 4. Concurrency
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Erlang relies on the actor model for concurrency. All we need to write
-% concurrent programs in erlang are three primitives: spawning processes,
+% concurrent programs in Erlang are three primitives: spawning processes,
% sending messages and receiving messages.
-% To start a new process we use the `spawn` function, which takes a function
+% To start a new process, we use the `spawn` function, which takes a function
% as argument.
F = fun() -> 2 + 2 end. % #Fun<erl_eval.20.67289768>
spawn(F). % <0.44.0>
-% `spawn` returns a pid (process identifier), you can use this pid to send
-% messages to the process. To do message passing we use the `!` operator.
-% For all of this to be useful we need to be able to receive messages. This is
+% `spawn` returns a pid (process identifier); you can use this pid to send
+% messages to the process. To do message passing, we use the `!` operator.
+% For all of this to be useful, we need to be able to receive messages. This is
% achieved with the `receive` mechanism:
-module(calculateGeometry).
@@ -272,12 +283,13 @@ calculateArea() ->
io:format("We can only calculate area of rectangles or circles.")
end.
-% Compile the module and create a process that evaluates `calculateArea` in the shell
+% Compile the module and create a process that evaluates `calculateArea` in the
+% shell.
c(calculateGeometry).
CalculateArea = spawn(calculateGeometry, calculateArea, []).
CalculateArea ! {circle, 2}. % 12.56000000000000049738
-% The shell is also a process, you can use `self` to get the current pid
+% The shell is also a process; you can use `self` to get the current pid.
self(). % <0.41.0>
```
diff --git a/fr-fr/r-fr.html.markdown b/fr-fr/r-fr.html.markdown
new file mode 100644
index 00000000..3f225a0f
--- /dev/null
+++ b/fr-fr/r-fr.html.markdown
@@ -0,0 +1,746 @@
+---
+language: R
+contributors:
+ - ["e99n09", "http://github.com/e99n09"]
+ - ["isomorphismes", "http://twitter.com/isomorphisms"]
+translators:
+ - ["Anne-Catherine Dehier", "https://github.com/spellart"]
+filename: learnr-fr.r
+---
+
+R est un langage de programmation statistique. Il dispose de nombreuses
+bibliothèques pour le téléchargement et le nettoyage d'ensembles de données,
+l'exécution de procédures statistiques, et la réalisation de graphiques.
+On peut également exécuter des commmandes `R` au sein d'un document LaTeX.
+
+
+```r
+
+# Les commentaires commencent avec des symboles numériques.
+
+# Il n'est pas possible de faire des commentaires multilignes,
+# mais on peut placer plusieurs commentaires les uns en dessous
+# des autres comme ceci.
+
+# Sur Mac, taper COMMAND-ENTER pour exécuter une ligne
+# et sur Windows taper CTRL-ENTER
+
+
+
+########################################################################
+# Les choses que vous pouvez faire sans rien comprendre
+# à la programmation
+########################################################################
+
+# Dans cette section, nous vous montrons quelques trucs cools que vous
+# pouvez faire avec R sans rien comprendre à la programmation.
+# Ne vous inquiétez pas si vous ne comprenez pas tout ce que le code fait.
+# Profitez simplement !
+
+data() # parcours les ensembles de données préchargées
+data(rivers) # récupère ceci : "Lengths of Major North American Rivers"
+ls() # notez que "rivers" apparaît maintenant dans votre espace de travail
+head(rivers) # donne un aperçu des données
+# 735 320 325 392 524 450
+
+length(rivers) # Combien de rivers ont été mesurées ?
+# 141
+summary(rivers) # Quelles sont les principales données statistiques ?
+# Min. 1st Qu. Median Mean 3rd Qu. Max.
+# 135.0 310.0 425.0 591.2 680.0 3710.0
+
+# Fait un diagramme à tiges et à feuilles (visualisation de données de
+# types histogramme)
+stem(rivers)
+
+
+# Le point décimal est de 2 chiffres à droite du |
+#
+# 0 | 4
+# 2 | 011223334555566667778888899900001111223333344455555666688888999
+# 4 | 111222333445566779001233344567
+# 6 | 000112233578012234468
+# 8 | 045790018
+# 10 | 04507
+# 12 | 1471
+# 14 | 56
+# 16 | 7
+# 18 | 9
+# 20 |
+# 22 | 25
+# 24 | 3
+# 26 |
+# 28 |
+# 30 |
+# 32 |
+# 34 |
+# 36 | 1
+
+stem(log(rivers)) # Notez que les données ne sont ni normales
+# ni lognormales !
+# Prenez-ça, la courbe en cloche
+
+# Le point décimal est à 1 chiffre à gauche du |
+#
+# 48 | 1
+# 50 |
+# 52 | 15578
+# 54 | 44571222466689
+# 56 | 023334677000124455789
+# 58 | 00122366666999933445777
+# 60 | 122445567800133459
+# 62 | 112666799035
+# 64 | 00011334581257889
+# 66 | 003683579
+# 68 | 0019156
+# 70 | 079357
+# 72 | 89
+# 74 | 84
+# 76 | 56
+# 78 | 4
+# 80 |
+# 82 | 2
+
+# Fait un histogramme :
+hist(rivers, col="#333333", border="white", breaks=25) # amusez-vous avec ces paramètres
+hist(log(rivers), col="#333333", border="white", breaks=25) # vous ferez plus de tracés plus tard
+
+# Ici d'autres données qui viennent préchargées. R en a des tonnes.
+data(discoveries)
+plot(discoveries, col="#333333", lwd=3, xlab="Year",
+ main="Number of important discoveries per year")
+plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year",
+ main="Number of important discoveries per year")
+
+# Plutôt que de laisser l'ordre par défaut (par année)
+# Nous pourrions aussi trier pour voir ce qu'il y a de typique
+sort(discoveries)
+# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2
+# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3
+# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4
+# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12
+
+stem(discoveries, scale=2)
+#
+# Le point décimale est à la |
+#
+# 0 | 000000000
+# 1 | 000000000000
+# 2 | 00000000000000000000000000
+# 3 | 00000000000000000000
+# 4 | 000000000000
+# 5 | 0000000
+# 6 | 000000
+# 7 | 0000
+# 8 | 0
+# 9 | 0
+# 10 | 0
+# 11 |
+# 12 | 0
+
+max(discoveries)
+# 12
+summary(discoveries)
+# Min. 1st Qu. Median Mean 3rd Qu. Max.
+# 0.0 2.0 3.0 3.1 4.0 12.0
+
+# Lance un dé plusieurs fois
+round(runif(7, min=.5, max=6.5))
+# 1 4 6 1 4 6 4
+# Vos numéros diffèreront des miens à moins que nous mettions
+# le même random.seed(31337)
+
+# Dessine à partir d'une normale Gaussienne 9 fois
+rnorm(9)
+# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271
+# [7] -0.59975593 0.57629164 1.08455362
+
+
+
+##############################################################
+# les types de données et l'arithmétique de base
+##############################################################
+
+# Maintenant pour la partie orientée programmation du tutoriel.
+# Dans cette section vous rencontrerez les types de données importants de R :
+# les entiers, les numériques, les caractères, les logiques, et les facteurs.
+
+# LES ENTIERS
+# Les entiers de type long sont écrits avec L
+5L # 5
+class(5L) # "integer"
+# (Essayez ?class pour plus d'informations sur la fonction class().)
+# Avec R, chaque valeur seule, comme 5L, est considérée comme
+# un vecteur de longueur 1
+length(5L) # 1
+# On peut avoir un vecteur d'entiers avec une longueur > 1 :
+c(4L, 5L, 8L, 3L) # 4 5 8 3
+length(c(4L, 5L, 8L, 3L)) # 4
+class(c(4L, 5L, 8L, 3L)) # "integer"
+
+# LES NUMÉRIQUES
+# Un "numeric" est un nombre à virgule flottante d'une précision double
+5 # 5
+class(5) # "numeric"
+# Encore une fois, tout dans R est un vecteur ;
+# Vous pouvez faire un vecteur numérique avec plus d'un élément
+c(3,3,3,2,2,1) # 3 3 3 2 2 1
+# Vous pouvez aussi utiliser la notation scientifique
+5e4 # 50000
+6.02e23 # nombre d'Avogadro
+1.6e-35 # longueur de Planck
+# Vous pouvez également avoir des nombres infiniments grands ou petits
+class(Inf) # "numeric"
+class(-Inf) # "numeric"
+# Vous pouvez utiliser "Inf", par exemple, dans integrate(dnorm, 3, Inf);
+# Ça permet d'éviter de réaliser une table de la loi normale.
+
+# ARITHMÉTIQUES DE BASE
+# Vous pouvez faire de l'arithmétique avec des nombres
+# Faire des opérations arithmétiques en mixant des entiers
+# et des numériques
+# donne un autre numérique
+10L + 66L # 76 # un entier plus un entier donne un entier
+53.2 - 4 # 49.2 # un numérique moins un numérique donne un numérique
+2.0 * 2L # 4 # un numérique multiplié par un entier donne un numérique
+3L / 4 # 0.75 # un entier sur un numérique donne un numérique
+3 %% 2 # 1 # le reste de deux numériques est un autre numérique
+# Les opérations arithmétiques illégales donnent un "Not A Number" :
+0 / 0 # NaN
+class(NaN) # "numeric"
+# Vous pouvez faire des opérations arithmétiques avec deux vecteurs d'une
+# longueur plus grande que 1, à condition que la longueur du plus grand
+# vecteur soit un multiple entier du plus petit
+c(1,2,3) + c(1,2,3) # 2 4 6
+
+# LES CARACTÈRES
+# Il n'y a pas de différences entre les chaînes de caractères et
+# les caractères en R
+"Horatio" # "Horatio"
+class("Horatio") # "character"
+class('H') # "character"
+# Ceux-ci sont tous les deux des vecteurs de longueur 1
+# Ici un plus long :
+c('alef', 'bet', 'gimmel', 'dalet', 'he')
+# =>
+# "alef" "bet" "gimmel" "dalet" "he"
+length(c("Call","me","Ishmael")) # 3
+# Vous pouvez utiliser des expressions rationnelles sur les vecteurs de caractères :
+substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis "
+gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis."
+# R possède plusieurs vecteurs de caractères préconstruits :
+letters
+# =>
+# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
+# [20] "t" "u" "v" "w" "x" "y" "z"
+month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
+
+# LES TYPES BOOLÉENS
+# En R, un "logical" est un booléen
+class(TRUE) # "logical"
+class(FALSE) # "logical"
+# Leur comportement est normal
+TRUE == TRUE # TRUE
+TRUE == FALSE # FALSE
+FALSE != FALSE # FALSE
+FALSE != TRUE # TRUE
+# Les données manquantes (NA) sont logiques également
+class(NA) # "logical"
+# On utilise | et & pour les operations logiques.
+# OR
+TRUE | FALSE # TRUE
+# AND
+TRUE & FALSE # FALSE
+# Vous pouvez tester si x est TRUE
+isTRUE(TRUE) # TRUE
+# Ici nous avons un vecteur de type logique avec plusieurs éléments :
+c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE
+c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE
+
+# LES FACTEURS
+# Les facteurs sont généralement utilisés pour y stocker des
+# variables qualitatives (catégorielles).
+# Les facteurs peuvent être ordonnés (comme le niveau scolaire
+# des enfants) ou non ordonnés (comme le sexe)
+factor(c("female", "female", "male", NA, "female"))
+# female female male <NA> female
+# Les niveaux : female male
+# Les facteurs possèdent un attribut appelé niveau ("level").
+# Les niveaux sont des vecteurs contenant toutes les valeurs
+# que peuvent prendre les données catégorielles.
+# Notez que les données manquantes n'entrent pas dans le niveau
+levels(factor(c("male", "male", "female", NA, "female"))) # "female" "male"
+# Si le vecteur de facteurs a une longueur 1, ses niveaux seront
+# de longueur 1 également
+length(factor("male")) # 1
+length(levels(factor("male"))) # 1
+# On rencontre communément des facteurs dans des "data frame",
+# un type de données que nous couvrirons plus tard
+data(infert) # "Infertility after Spontaneous and Induced Abortion"
+levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs"
+
+# NULL
+# "NULL" est bizarre ; on l'utilise pour effacer un vecteur
+class(NULL) # NULL
+parakeet = c("beak", "feathers", "wings", "eyes")
+parakeet
+# =>
+# [1] "beak" "feathers" "wings" "eyes"
+parakeet <- NULL
+parakeet
+# =>
+# NULL
+
+# LES CONVERSIONS DE TYPES
+# Les conversions de types servent à forcer une valeur à prendre
+# un type différent
+as.character(c(6, 8)) # "6" "8"
+as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE
+# Si vous mettez des éléments de différents types dans un vecteur,
+# des coercitions bizarres se produisent :
+c(TRUE, 4) # 1 4
+c("dog", TRUE, 4) # "dog" "TRUE" "4"
+as.numeric("Bilbo")
+# =>
+# [1] NA
+# Message d'avertissement :
+# NAs est introduit par coercition
+
+# Notez également : ce n'étaient que des types de données basiques
+# Il y a beaucoup d'autres types de données, comme les dates,
+# les séries temporelles, etc ...
+
+
+
+#######################################
+# Variables, boucles , if/else
+#######################################
+
+# Une variable est comme une boîte dans laquelle on garde une valeur
+# pour l'utiliser plus tard.
+# Nous appellons ça "assigner" une valeur à une variable.
+# Avoir des variables nous permet d'écrire des boucles, des fonctions, et
+# des instructions conditionnelles (if/else)
+
+# LES VARIABLES
+# Beaucoup de façons d'assigner des choses :
+x = 5 # c'est correct
+y <- "1" # c'est préféré
+TRUE -> z # ça marche mais c'est bizarre
+
+# LES BOUCLES
+# Il y a les boucles for :
+for (i in 1:4) {
+ print(i)
+}
+# Il y a les boucles while :
+a <- 10
+while (a > 4) {
+ cat(a, "...", sep = "")
+ a <- a - 1
+}
+# Gardez à l'esprit que les boucles for et while s'exécutent lentement
+# en R.
+# Des opérations sur la totalité d'un vecteur (ex une ligne entière,
+# une colonne entière),
+# ou les fonctions de type apply() (nous en parlerons plus tard),
+# sont préférées.
+
+# IF/ELSE
+# Encore une fois assez standard
+if (4 > 3) {
+ print("4 is greater than 3")
+} else {
+ print("4 is not greater than 3")
+}
+# =>
+# [1] "4 is greater than 3"
+
+# LES FONCTIONS
+# se définissent comme ceci :
+jiggle <- function(x) {
+ x = x + rnorm(1, sd=.1) # ajoute un peu de bruit (contrôlé)
+ return(x)
+}
+# Appelées comme n'importe quelles autres fonction R :
+jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043
+
+
+
+##########################################################################
+# Les structures de données : les vecteurs, les matrices,
+# les data frames et les tableaux
+##########################################################################
+
+# À UNE DIMENSION
+
+# Commençons par le tout début, et avec quelque chose que
+# vous connaissez déjà : les vecteurs.
+vec <- c(8, 9, 10, 11)
+vec # 8 9 10 11
+# Nous demandons des éléments spécifiques en les mettant entre crochets
+# (Notez que R commence à compter à partir de 1)
+vec[1] # 8
+letters[18] # "r"
+LETTERS[13] # "M"
+month.name[9] # "September"
+c(6, 8, 7, 5, 3, 0, 9)[3] # 7
+# Nous pouvons également rechercher des indices de composants spécifiques,
+which(vec %% 2 == 0) # 1 3
+# Récupèrer seulement les premières ou dernières entrées du vecteur,
+head(vec, 1) # 8
+tail(vec, 2) # 10 11
+# ou vérifier si un certaine valeur est dans le vecteur
+any(vec == 10) # TRUE
+# Si un index "dépasse" vous obtiendrez NA :
+vec[6] # NA
+# Vous pouvez trouver la longueur de votre vecteur avec length()
+length(vec) # 4
+# Vous pouvez réaliser des opérations sur des vecteurs entiers ou des
+# sous-ensembles de vecteurs
+vec * 4 # 16 20 24 28
+vec[2:3] * 5 # 25 30
+any(vec[2:3] == 8) # FALSE
+# Et R a beaucoup de méthodes statistiques pré-construites pour les vecteurs :
+mean(vec) # 9.5
+var(vec) # 1.666667
+sd(vec) # 1.290994
+max(vec) # 11
+min(vec) # 8
+sum(vec) # 38
+# Quelques fonctions préconstruites sympas supplémentaires :
+5:15 # 5 6 7 8 9 10 11 12 13 14 15
+seq(from=0, to=31337, by=1337)
+# =>
+# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707
+# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751
+
+# À DEUX DIMENSIONS (TOUT DANS UNE CLASSE)
+
+# Vous pouvez créer une matrice à partir d'entrées du même type comme ceci :
+mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6))
+mat
+# =>
+# [,1] [,2]
+# [1,] 1 4
+# [2,] 2 5
+# [3,] 3 6
+# Différemment du vecteur, la classe d'une matrice est "matrix",
+# peut importe ce qu'elle contient
+class(mat) # => "matrix"
+# Récupérer la première ligne
+mat[1,] # 1 4
+# Réaliser une opération sur la première colonne
+3 * mat[,1] # 3 6 9
+# Demander une cellule spécifique
+mat[3,2] # 6
+
+# Transposer la matrice entière
+t(mat)
+# =>
+# [,1] [,2] [,3]
+# [1,] 1 2 3
+# [2,] 4 5 6
+
+# La multiplication de matrices
+mat %*% t(mat)
+# =>
+# [,1] [,2] [,3]
+# [1,] 17 22 27
+# [2,] 22 29 36
+# [3,] 27 36 45
+
+# cbind() colle des vecteurs ensemble en colonne pour faire une matrice
+mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog"))
+mat2
+# =>
+# [,1] [,2]
+# [1,] "1" "dog"
+# [2,] "2" "cat"
+# [3,] "3" "bird"
+# [4,] "4" "dog"
+class(mat2) # matrix
+# Encore une fois regardez ce qui se passe !
+# Parce que les matrices peuvent contenir des entrées de toutes sortes de
+# classes, tout sera converti en classe caractère
+c(class(mat2[,1]), class(mat2[,2]))
+
+# rbind() colle des vecteurs ensemble par lignes pour faire une matrice
+mat3 <- rbind(c(1,2,4,5), c(6,7,0,4))
+mat3
+# =>
+# [,1] [,2] [,3] [,4]
+# [1,] 1 2 4 5
+# [2,] 6 7 0 4
+# Ah, tout de la même classe. Pas de coercitions. Beaucoup mieux.
+
+# À DEUX DIMENSIONS (DE CLASSES DIFFÉRENTES)
+
+# Pour des colonnes de différents types, utiliser une data frame
+# Cette structure de données est si utile pour la programmation statistique,
+# qu'une version a été ajoutée à Python dans le paquet "pandas".
+
+students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"),
+ c(3,2,2,1,0,-1),
+ c("H", "G", "G", "R", "S", "G"))
+names(students) <- c("name", "year", "house") # name the columns
+class(students) # "data.frame"
+students
+# =>
+# name year house
+# 1 Cedric 3 H
+# 2 Fred 2 G
+# 3 George 2 G
+# 4 Cho 1 R
+# 5 Draco 0 S
+# 6 Ginny -1 G
+class(students$year) # "numeric"
+class(students[,3]) # "factor"
+# Trouver les dimensions
+nrow(students) # 6
+ncol(students) # 3
+dim(students) # 6 3
+# La fonction data.frame() convertit les vecteurs caractères en vecteurs de
+# facteurs par défaut; désactiver cette fonction en règlant
+# stringsAsFactors = FALSE quand vous créer la data.frame
+?data.frame
+
+# Il y a plusieurs façons de subdiviser les data frames,
+# toutes subtilement différentes
+students$year # 3 2 2 1 0 -1
+students[,2] # 3 2 2 1 0 -1
+students[,"year"] # 3 2 2 1 0 -1
+
+# Une version améliorée de la structure data.frame est data.table.
+# Si vous travaillez avec des données volumineuses ou des panels, ou avez
+# besoin de fusionner quelques ensembles de données, data.table peut être
+# un bon choix. Ici un tour éclair :
+install.packages("data.table") # télécharge le paquet depuis CRAN
+require(data.table) # le charge
+students <- as.data.table(students)
+students # regardez la différence à l'impression
+# =>
+# name year house
+# 1: Cedric 3 H
+# 2: Fred 2 G
+# 3: George 2 G
+# 4: Cho 1 R
+# 5: Draco 0 S
+# 6: Ginny -1 G
+students[name=="Ginny"] # obtiens les lignes avec name == "Ginny"
+# =>
+# name year house
+# 1: Ginny -1 G
+students[year==2] # obtiens les lignes avec year == 2
+# =>
+# name year house
+# 1: Fred 2 G
+# 2: George 2 G
+# data.table facilite la fusion entre deux ensembles de données
+# Faisons une autre data.table pour fusionner students
+founders <- data.table(house=c("G","H","R","S"),
+ founder=c("Godric","Helga","Rowena","Salazar"))
+founders
+# =>
+# house founder
+# 1: G Godric
+# 2: H Helga
+# 3: R Rowena
+# 4: S Salazar
+setkey(students, house)
+setkey(founders, house)
+students <- founders[students] # merge les deux ensembles de données qui matchent "house"
+setnames(students, c("house","houseFounderName","studentName","year"))
+students[,order(c("name","year","house","houseFounderName")), with=F]
+# =>
+# studentName year house houseFounderName
+# 1: Fred 2 G Godric
+# 2: George 2 G Godric
+# 3: Ginny -1 G Godric
+# 4: Cedric 3 H Helga
+# 5: Cho 1 R Rowena
+# 6: Draco 0 S Salazar
+
+# data.table facilite le résumé des tableaux
+students[,sum(year),by=house]
+# =>
+# house V1
+# 1: G 3
+# 2: H 3
+# 3: R 1
+# 4: S 0
+
+# Pour supprimer une colonne d'une data.frame ou data.table,
+# assignez-lui la valeur NULL
+students$houseFounderName <- NULL
+students
+# =>
+# studentName year house
+# 1: Fred 2 G
+# 2: George 2 G
+# 3: Ginny -1 G
+# 4: Cedric 3 H
+# 5: Cho 1 R
+# 6: Draco 0 S
+
+# Supprimer une ligne en subdivisant
+# En utilisant data.table :
+students[studentName != "Draco"]
+# =>
+# house studentName year
+# 1: G Fred 2
+# 2: G George 2
+# 3: G Ginny -1
+# 4: H Cedric 3
+# 5: R Cho 1
+# En utilisant data.frame :
+students <- as.data.frame(students)
+students[students$house != "G",]
+# =>
+# house houseFounderName studentName year
+# 4 H Helga Cedric 3
+# 5 R Rowena Cho 1
+# 6 S Salazar Draco 0
+
+# MULTI-DIMENSIONNELLE (TOUS ÉLÉMENTS D'UN TYPE)
+
+# Les arrays créent des tableaux de n dimensions.
+# Tous les éléments doivent être du même type.
+# Vous pouvez faire un tableau à 2 dimensions (une sorte de matrice)
+array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4))
+# =>
+# [,1] [,2] [,3] [,4]
+# [1,] 1 4 8 3
+# [2,] 2 5 9 6
+# Vous pouvez aussi utiliser array pour faire des matrices à 3 dimensions :
+array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2))
+# =>
+# , , 1
+#
+# [,1] [,2]
+# [1,] 2 8
+# [2,] 300 9
+# [3,] 4 0
+#
+# , , 2
+#
+# [,1] [,2]
+# [1,] 5 66
+# [2,] 60 7
+# [3,] 0 847
+
+# LES LISTES (MULTI-DIMENSIONNELLES, ÉVENTUELLEMMENT DÉCHIRÉES,
+# DE DIFFÉRENTS TYPES)
+
+# Enfin, R a des listes (de vecteurs)
+list1 <- list(time = 1:40)
+list1$price = c(rnorm(40,.5*list1$time,4)) # random
+list1
+# Vous pouvez obtenir des éléments de la liste comme ceci
+list1$time # une façon
+list1[["time"]] # une autre façon
+list1[[1]] # encore une façon différente
+# =>
+# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
+# [34] 34 35 36 37 38 39 40
+# Vous pouvez subdiviser les éléments d'une liste comme n'importe quel vecteur
+list1$price[4]
+
+# Les listes ne sont pas les structures de données les plus efficaces
+# à utiliser avec R ;
+# À moins d'avoir une très bonne raison, vous devriez utiliser data.frames
+# Les listes sont souvent retournées par des fonctions qui effectuent
+# des régressions linéaires.
+
+##########################################
+# La famille de fonction apply()
+##########################################
+
+# Vous vous rappelez mat ?
+mat
+# =>
+# [,1] [,2]
+# [1,] 1 4
+# [2,] 2 5
+# [3,] 3 6
+# Utilisez apply(X, MARGIN, FUN) pour appliquer la fonction FUN à la matrice X
+# sur les lignes (MAR = 1) ou les colonnes (MAR = 2)
+# R exécute FUN à chaque lignes (ou colonnes) de X, beaucoup plus rapidement
+# que le ferait une boucle for ou while
+apply(mat, MAR = 2, jiggle)
+# =>
+# [,1] [,2]
+# [1,] 3 15
+# [2,] 7 19
+# [3,] 11 23
+# D'autres fonctions : ?lapply, ?sapply
+
+# Ne soyez pas trop intimidé ; tout le monde reconnaît que c'est un peu déroutant
+
+# Le paquet plyr vise à remplacer (et améliorer !) la famille *apply().
+install.packages("plyr")
+require(plyr)
+?plyr
+
+
+
+############################
+# Charger des données
+############################
+
+# "pets.csv" est un fichier sur internet
+# (mais il pourrait être tout aussi facilement sur votre ordinateur)
+pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv")
+pets
+head(pets, 2) # first two rows
+tail(pets, 1) # last row
+
+# Pour sauvegarder une data frame ou une matrice en fichier .csv
+write.csv(pets, "pets2.csv") # to make a new .csv file
+# définir le répertoire de travail avec setwd(), le récupérer avec getwd()
+
+# Essayez ?read.csv et ?write.csv pour plus d'informations
+
+
+
+################
+# Les tracés
+################
+
+# LES FONCTIONS DE TRACÉ PRÉCONSTRUITES
+# Les diagrammes de dispersion !
+plot(list1$time, list1$price, main = "fake data")
+# Les régressions !
+linearModel <- lm(price ~ time, data = list1)
+linearModel # sort le résultat de la régression
+# Tracer une ligne de regression sur une tracé existant
+abline(linearModel, col = "red")
+# Obtenir une variété de diagnostiques sympas
+plot(linearModel)
+# Les histogrammes !
+hist(rpois(n = 10000, lambda = 5), col = "thistle")
+# Les diagrammes en bâtons !
+barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow"))
+
+# GGPLOT2
+# Mais ceux-ci ne sont même pas les plus jolis tracés de R
+# Essayez le paquet ggplot2 pour d'avantages de graphiques
+install.packages("ggplot2")
+require(ggplot2)
+?ggplot2
+pp <- ggplot(students, aes(x=house))
+pp + geom_histogram()
+ll <- as.data.table(list1)
+pp <- ggplot(ll, aes(x=time,price))
+pp + geom_point()
+# ggplot2 a une documentation excellente
+#(disponible sur http://docs.ggplot2.org/current/)
+
+
+
+```
+
+## Comment obtenir R ?
+
+* Obtiens R et R GUI depuis [http://www.r-project.org/](http://www.r-project.org/)
+* [RStudio](http://www.rstudio.com/ide/) est un autre GUI
diff --git a/haxe.html.markdown b/haxe.html.markdown
index c807d2d7..ee214540 100644
--- a/haxe.html.markdown
+++ b/haxe.html.markdown
@@ -323,7 +323,7 @@ class LearnHaxe3{
var l = 0;
do{
trace("do statement always runs at least once");
- } while (i > 0);
+ } while (l > 0);
// for loop
/*
@@ -340,7 +340,7 @@ class LearnHaxe3{
// (more on ranges later as well)
var n = ['foo', 'bar', 'baz'];
for (val in 0...n.length){
- trace(val + " is the value for val (an index for m)");
+ trace(val + " is the value for val (an index for n)");
}
@@ -375,7 +375,7 @@ class LearnHaxe3{
case "rex" : favorite_thing = "shoe";
case "spot" : favorite_thing = "tennis ball";
default : favorite_thing = "some unknown treat";
- // case _ : "some unknown treat"; // same as default
+ // case _ : favorite_thing = "some unknown treat"; // same as default
}
// The "_" case above is a "wildcard" value
// that will match anything.
@@ -397,7 +397,7 @@ class LearnHaxe3{
// if statements
var k = if (true) 10 else 20;
- trace("K equals ", k); // outputs 10
+ trace("k equals ", k); // outputs 10
var other_favorite_thing = switch(my_dog_name) {
case "fido" : "teddy";
@@ -495,8 +495,10 @@ class LearnHaxe3{
// foo_instance.public_read = 4; // this will throw an error if uncommented:
// trace(foo_instance.public_write); // as will this.
- trace(foo_instance + " is the value for foo_instance"); // calls the toString method
- trace(foo_instance.toString() + " is the value for foo_instance.toString()"); // same thing
+ // calls the toString method:
+ trace(foo_instance + " is the value for foo_instance");
+ // same thing:
+ trace(foo_instance.toString() + " is the value for foo_instance.toString()");
/*
@@ -524,8 +526,8 @@ class LearnHaxe3{
*/
class FooClass extends BarClass implements BarInterface{
public var public_any:Int; // public variables are accessible anywhere
- public var public_read (default,null): Int; // use this style to only enable public read
- public var public_write (null, default): Int; // or public write
+ public var public_read (default, null): Int; // enable only public read
+ public var public_write (null, default): Int; // or only public write
public var property (get, set): Int; // use this style to enable getters/setters
// private variables are not available outside the class.
@@ -534,9 +536,10 @@ class FooClass extends BarClass implements BarInterface{
// a public constructor
public function new(arg:Int){
- super(); // call the constructor of the parent object, since we extended BarClass
+ // call the constructor of the parent object, since we extended BarClass:
+ super();
- this.public_any= 0;
+ this.public_any = 0;
this._private = arg;
}
diff --git a/java.html.markdown b/java.html.markdown
index 10dd498c..928eb39f 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -1,16 +1,16 @@
---
-
language: java
contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
- - ["Madison Dickson", "http://github.com/mix3d"]
- ["Jakukyo Friel", "http://weakish.github.io"]
+ - ["Madison Dickson", "http://github.com/mix3d"]
+ - ["Simon Morgan", "http://sjm.io/"]
filename: LearnJava.java
-
---
-Java is a general-purpose, concurrent, class-based, object-oriented computer programming language.
-[Read more here.](http://docs.oracle.com/javase/tutorial/java/index.html)
+Java is a general-purpose, concurrent, class-based, object-oriented computer
+programming language.
+[Read more here.](http://docs.oracle.com/javase/tutorial/java/)
```java
// Single-line comments start with //
@@ -31,17 +31,17 @@ import java.security.*;
// the file.
public class LearnJava {
- // A program must have a main method as an entry point
+ // A program must have a main method as an entry point.
public static void main (String[] args) {
- // Use System.out.println to print lines
+ // Use System.out.println() to print lines.
System.out.println("Hello World!");
System.out.println(
"Integer: " + 10 +
" Double: " + 3.14 +
" Boolean: " + true);
- // To print without a newline, use System.out.print
+ // To print without a newline, use System.out.print().
System.out.print("Hello ");
System.out.print("World");
@@ -69,7 +69,7 @@ public class LearnJava {
// L is used to denote that this variable value is of type Long;
// anything without is treated as integer by default.
- // Note: Java has no unsigned types
+ // Note: Java has no unsigned types.
// Float - Single-precision 32-bit IEEE 754 Floating Point
float fooFloat = 234.5f;
@@ -86,7 +86,7 @@ public class LearnJava {
// Char - A single 16-bit Unicode character
char fooChar = 'A';
- // final variables can't be reassigned to another object
+ // final variables can't be reassigned to another object.
final int HOURS_I_WORK_PER_WEEK = 9001;
// Strings
@@ -101,10 +101,10 @@ public class LearnJava {
System.out.println(bazString);
// Arrays
- //The array size must be decided upon instantiation
- //The following formats work for declaring an array
- //<datatype>[] <var name> = new <datatype>[<array size>];
- //<datatype> <var name>[] = new <datatype>[<array size>];
+ // The array size must be decided upon instantiation
+ // The following formats work for declaring an array
+ // <datatype>[] <var name> = new <datatype>[<array size>];
+ // <datatype> <var name>[] = new <datatype>[<array size>];
int[] intArray = new int[10];
String[] stringArray = new String[1];
boolean boolArray[] = new boolean[100];
@@ -122,17 +122,17 @@ public class LearnJava {
System.out.println("intArray @ 1: " + intArray[1]); // => 1
// Others to check out
- // ArrayLists - Like arrays except more functionality is offered,
- // and the size is mutable
+ // ArrayLists - Like arrays except more functionality is offered, and
+ // the size is mutable.
// LinkedLists - Implementation of doubly-linked list. All of the
- // operations perform as could be expected for
- // a doubly-linked list.
- // Maps - A set of objects that maps keys to values. A map cannot contain
- // duplicate keys; each key can map to at most one value.
- // HashMaps - This class uses a hashtable to implement the Map interface.
- // This allows the execution time of basic operations,
- // such as get and insert element, to remain constant even
- // for large sets.
+ // operations perform as could be expected for a
+ // doubly-linked list.
+ // Maps - A set of objects that maps keys to values. A map cannot
+ // contain duplicate keys; each key can map to at most one value.
+ // HashMaps - This class uses a hashtable to implement the Map
+ // interface. This allows the execution time of basic
+ // operations, such as get and insert element, to remain
+ // constant even for large sets.
///////////////////////////////////////
// Operators
@@ -160,13 +160,13 @@ public class LearnJava {
// Bitwise operators!
/*
- ~ Unary bitwise complement
- << Signed left shift
- >> Signed right shift
- >>> Unsigned right shift
- & Bitwise AND
- ^ Bitwise exclusive OR
- | Bitwise inclusive OR
+ ~ Unary bitwise complement
+ << Signed left shift
+ >> Signed right shift
+ >>> Unsigned right shift
+ & Bitwise AND
+ ^ Bitwise exclusive OR
+ | Bitwise inclusive OR
*/
// Incrementations
@@ -175,10 +175,10 @@ public class LearnJava {
// The ++ and -- operators increment and decrement by 1 respectively.
// If they are placed before the variable, they increment then return;
// after the variable they return then increment.
- System.out.println(i++); //i = 1, prints 0 (post-increment)
- System.out.println(++i); //i = 2, prints 2 (pre-increment)
- System.out.println(i--); //i = 1, prints 2 (post-decrement)
- System.out.println(--i); //i = 0, prints 0 (pre-decrement)
+ System.out.println(i++); // i = 1, prints 0 (post-increment)
+ System.out.println(++i); // i = 2, prints 2 (pre-increment)
+ System.out.println(i--); // i = 1, prints 2 (post-decrement)
+ System.out.println(--i); // i = 0, prints 0 (pre-decrement)
///////////////////////////////////////
// Control Structures
@@ -197,73 +197,69 @@ public class LearnJava {
// While loop
int fooWhile = 0;
- while(fooWhile < 100)
- {
- //System.out.println(fooWhile);
- //Increment the counter
- //Iterated 100 times, fooWhile 0,1,2...99
+ while(fooWhile < 100) {
+ System.out.println(fooWhile);
+ // Increment the counter
+ // Iterated 100 times, fooWhile 0,1,2...99
fooWhile++;
}
System.out.println("fooWhile Value: " + fooWhile);
// Do While Loop
int fooDoWhile = 0;
- do
- {
- //System.out.println(fooDoWhile);
- //Increment the counter
- //Iterated 99 times, fooDoWhile 0->99
+ do {
+ System.out.println(fooDoWhile);
+ // Increment the counter
+ // Iterated 99 times, fooDoWhile 0->99
fooDoWhile++;
- }while(fooDoWhile < 100);
+ } while(fooDoWhile < 100);
System.out.println("fooDoWhile Value: " + fooDoWhile);
// For Loop
int fooFor;
- //for loop structure => for(<start_statement>; <conditional>; <step>)
- for(fooFor=0; fooFor<10; fooFor++){
- //System.out.println(fooFor);
- //Iterated 10 times, fooFor 0->9
+ // for loop structure => for(<start_statement>; <conditional>; <step>)
+ for (fooFor = 0; fooFor < 10; fooFor++) {
+ System.out.println(fooFor);
+ // Iterated 10 times, fooFor 0->9
}
System.out.println("fooFor Value: " + fooFor);
// For Each Loop
- // An automatic iteration through an array or list of objects.
- int[] fooList = {1,2,3,4,5,6,7,8,9};
- //for each loop structure => for(<object> : <array_object>)
- //reads as: for each object in the array
- //note: the object type must match the array.
-
- for( int bar : fooList ){
- //System.out.println(bar);
+ // The for loop is also able to iterate over arrays as well as objects
+ // that implement the Iterable interface.
+ int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9};
+ // for each loop structure => for (<object> : <iterable>)
+ // reads as: for each element in the iterable
+ // note: the object type must match the element type of the iterable.
+
+ for (int bar : fooList) {
+ System.out.println(bar);
//Iterates 9 times and prints 1-9 on new lines
}
// Switch Case
// A switch works with the byte, short, char, and int data types.
- // It also works with enumerated types (discussed in Enum Types),
- // the String class, and a few special classes that wrap
- // primitive types: Character, Byte, Short, and Integer.
+ // It also works with enumerated types (discussed in Enum Types), the
+ // String class, and a few special classes that wrap primitive types:
+ // Character, Byte, Short, and Integer.
int month = 3;
String monthString;
- switch (month){
- case 1:
- monthString = "January";
- break;
- case 2:
- monthString = "February";
+ switch (month) {
+ case 1: monthString = "January";
break;
- case 3:
- monthString = "March";
+ case 2: monthString = "February";
break;
- default:
- monthString = "Some other month";
+ case 3: monthString = "March";
break;
+ default: monthString = "Some other month";
+ break;
}
System.out.println("Switch Case Result: " + monthString);
// Conditional Shorthand
// You can use the '?' operator for quick assignments or logic forks.
- // Reads as "If (statement) is true, use <first value>, otherwise, use <second value>"
+ // Reads as "If (statement) is true, use <first value>, otherwise, use
+ // <second value>"
int foo = 5;
String bar = (foo < 10) ? "A" : "B";
System.out.println(bar); // Prints A, because the statement is true
@@ -287,9 +283,8 @@ public class LearnJava {
// String
// Typecasting
- // You can also cast java objects, there's a lot of details and
- // deals with some more intermediate concepts.
- // Feel free to check it out here:
+ // You can also cast Java objects, there's a lot of details and deals
+ // with some more intermediate concepts. Feel free to check it out here:
// http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
@@ -319,9 +314,9 @@ public class LearnJava {
// Class Declaration Syntax:
-// <public/private/protected> class <class name>{
-// //data fields, constructors, functions all inside.
-// //functions are called as methods in Java.
+// <public/private/protected> class <class name> {
+// // data fields, constructors, functions all inside.
+// // functions are called as methods in Java.
// }
class Bicycle {
@@ -342,7 +337,8 @@ class Bicycle {
}
// This is a constructor that takes arguments
- public Bicycle(int startCadence, int startSpeed, int startGear, String name) {
+ public Bicycle(int startCadence, int startSpeed, int startGear,
+ String name) {
this.gear = startGear;
this.cadence = startCadence;
this.speed = startSpeed;
@@ -388,10 +384,8 @@ class Bicycle {
//Method to display the attribute values of this Object.
@Override
public String toString() {
- return "gear: " + gear +
- " cadence: " + cadence +
- " speed: " + speed +
- " name: " + name;
+ return "gear: " + gear + " cadence: " + cadence + " speed: " + speed +
+ " name: " + name;
}
} // end class Bicycle
@@ -405,26 +399,26 @@ class PennyFarthing extends Bicycle {
super(startCadence, startSpeed, 0, "PennyFarthing");
}
- // You should mark a method you're overriding with an @annotation
- // To learn more about what annotations are and their purpose
- // check this out: http://docs.oracle.com/javase/tutorial/java/annotations/
+ // You should mark a method you're overriding with an @annotation.
+ // To learn more about what annotations are and their purpose check this
+ // out: http://docs.oracle.com/javase/tutorial/java/annotations/
@Override
public void setGear(int gear) {
gear = 0;
}
-
}
-//Interfaces
-//Interface declaration syntax
-//<access-level> interface <interface-name> extends <super-interfaces> {
-// //Constants
-// //Method declarations
-//}
+// Interfaces
+// Interface declaration syntax
+// <access-level> interface <interface-name> extends <super-interfaces> {
+// // Constants
+// // Method declarations
+// }
-//Example - Food:
+// Example - Food:
public interface Edible {
- public void eat(); //Any class that implements this interface, must implement this method
+ public void eat(); // Any class that implements this interface, must
+ // implement this method.
}
public interface Digestible {
@@ -432,33 +426,31 @@ public interface Digestible {
}
-//We can now create a class that implements both of these interfaces
+// We can now create a class that implements both of these interfaces.
public class Fruit implements Edible, Digestible {
@Override
public void eat() {
- //...
+ // ...
}
@Override
public void digest() {
- //...
+ // ...
}
}
-//In java, you can extend only one class, but you can implement many interfaces.
-//For example:
-public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo {
+// In Java, you can extend only one class, but you can implement many
+// interfaces. For example:
+public class ExampleClass extends ExampleClassParent implements InterfaceOne,
+ InterfaceTwo {
@Override
public void InterfaceOneMethod() {
-
}
@Override
public void InterfaceTwoMethod() {
-
}
}
-
```
## Further Reading
@@ -500,5 +492,3 @@ The links provided here below are just to get an understanding of the topic, fee
* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660)
* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300)
-
-
diff --git a/nim.html.markdown b/nim.html.markdown
index aa15e591..c9548a1c 100644
--- a/nim.html.markdown
+++ b/nim.html.markdown
@@ -155,7 +155,7 @@ var anotherArray = ["Default index", "starts at", "0"]
# More data structures are available, including tables, sets, lists, queues,
# and crit bit trees.
-# http://nimrod-lang.org/lib.html#collections-and-algorithms
+# http://nim-lang.org/docs/lib.html#collections-and-algorithms
#
# IO and Control Flow
@@ -174,7 +174,7 @@ else:
# `while`, `if`, `continue`, `break`
-import strutils as str # http://nimrod-lang.org/strutils.html
+import strutils as str # http://nim-lang.org/docs/strutils.html
echo "I'm thinking of a number between 41 and 43. Guess which!"
let number: int = 42
var
@@ -263,11 +263,11 @@ performance, and compile-time features.
## Further Reading
-* [Home Page](http://nimrod-lang.org)
-* [Download](http://nimrod-lang.org/download.html)
-* [Community](http://nimrod-lang.org/community.html)
-* [FAQ](http://nimrod-lang.org/question.html)
-* [Documentation](http://nimrod-lang.org/documentation.html)
-* [Manual](http://nimrod-lang.org/manual.html)
-* [Standard Library](http://nimrod-lang.org/lib.html)
-* [Rosetta Code](http://rosettacode.org/wiki/Category:Nimrod)
+* [Home Page](http://nim-lang.org)
+* [Download](http://nim-lang.org/download.html)
+* [Community](http://nim-lang.org/community.html)
+* [FAQ](http://nim-lang.org/question.html)
+* [Documentation](http://nim-lang.org/documentation.html)
+* [Manual](http://nim-lang.org/docs/manual.html)
+* [Standard Library](http://nim-lang.org/docs/lib.html)
+* [Rosetta Code](http://rosettacode.org/wiki/Category:Nim)
diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown
index 64b0aadc..b450ab84 100644
--- a/zh-cn/javascript-cn.html.markdown
+++ b/zh-cn/javascript-cn.html.markdown
@@ -341,7 +341,7 @@ var myFunc = myObj.myFunc;
myFunc(); // = undefined
// 相应的,一个函数也可以被指定为一个对象的方法,并且可以通过`this`访问
-// 这个对象的成员,即使在行数被定义时并没有依附在对象上。
+// 这个对象的成员,即使在函数被定义时并没有依附在对象上。
var myOtherFunc = function(){
return this.myString.toUpperCase();
}