summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--.github/CODEOWNERS2
-rw-r--r--awk.html.markdown4
-rw-r--r--de-de/brainfuck-de.html.markdown4
-rw-r--r--de-de/git-de.html.markdown2
-rw-r--r--de-de/rust-de.html.markdown2
-rw-r--r--de-de/vim-de.html.markdown1
-rw-r--r--docker.html.markdown3
-rw-r--r--el-gr/ocaml-gr.html.markdown4
-rw-r--r--erlang.html.markdown2
-rw-r--r--es-es/awk-es.html.markdown2
-rw-r--r--es-es/git-es.html.markdown2
-rw-r--r--es-es/rust-es.html.markdown2
-rw-r--r--fortran90.html.markdown (renamed from fortran95.html.markdown)124
-rw-r--r--fr-fr/awk-fr.html.markdown146
-rw-r--r--fr-fr/git-fr.html.markdown2
-rw-r--r--fr-fr/rust-fr.html.markdown4
-rw-r--r--fr-fr/set-theory-fr.html.markdown28
-rw-r--r--git.html.markdown2
-rw-r--r--go.html.markdown2
-rw-r--r--it-it/rust-it.html.markdown2
-rw-r--r--latex.html.markdown2
-rw-r--r--mips.html.markdown2
-rw-r--r--mongodb.html.markdown6
-rw-r--r--pt-br/awk-pt.html.markdown2
-rw-r--r--pt-br/c-pt.html.markdown3
-rw-r--r--pt-br/git-pt.html.markdown2
-rw-r--r--pt-br/groovy-pt.html.markdown15
-rw-r--r--pt-br/latex-pt.html.markdown101
-rw-r--r--pt-br/lua-pt.html.markdown2
-rw-r--r--pt-br/make-pt.html.markdown4
-rw-r--r--pt-br/php-pt.html.markdown2
-rw-r--r--pt-br/pythonstatcomp-pt.html.markdown249
-rw-r--r--pt-br/r-pt.html.markdown786
-rw-r--r--pt-br/rust-pt.html.markdown2
-rw-r--r--pt-br/yaml-pt.html.markdown150
-rw-r--r--pt-pt/git-pt.html.markdown2
-rw-r--r--r.html.markdown289
-rw-r--r--ru-ru/javascript-ru.html.markdown2
-rw-r--r--ru-ru/kotlin-ru.html.markdown2
-rw-r--r--ru-ru/lua-ru.html.markdown4
-rw-r--r--ru-ru/objective-c-ru.html.markdown4
-rw-r--r--ru-ru/rust-ru.html.markdown2
-rw-r--r--ru-ru/swift-ru.html.markdown2
-rw-r--r--sk-sk/git-sk.html.markdown2
-rw-r--r--solidity.html.markdown10
-rw-r--r--tr-tr/bf-tr.html.markdown2
-rw-r--r--tr-tr/git-tr.html.markdown2
-rw-r--r--uk-ua/mips-ua.html.markdown2
-rw-r--r--uk-ua/rust-ua.html.markdown2
-rw-r--r--vi-vn/git-vi.html.markdown2
-rw-r--r--vi-vn/json-vi.html.markdown2
-rw-r--r--vim.html.markdown2
-rw-r--r--vimscript.html.markdown2
-rw-r--r--zh-cn/awk-cn.html.markdown2
-rw-r--r--zh-cn/docker-cn.html.markdown3
-rw-r--r--zh-cn/gdscript-cn.html.markdown314
-rw-r--r--zh-cn/git-cn.html.markdown2
-rw-r--r--zh-cn/mips-cn.html.markdown2
-rw-r--r--zh-cn/python-cn.html.markdown739
-rw-r--r--zh-cn/raylib-cn.html.markdown147
-rw-r--r--zh-cn/rust-cn.html.markdown2
-rw-r--r--zh-cn/sql-cn.html.markdown (renamed from zh-cn/sql.html.markdown)0
62 files changed, 2617 insertions, 597 deletions
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 6c1efe0d..7bc421a7 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -4,3 +4,5 @@
/zh-cn/ @geoffliu @imba-tjd
/zh-tw/ @geoffliu @imba-tjd
/ko-kr/ @justin-themedium
+/pt-pt/ @mribeirodantas
+/pt-br/ @mribeirodantas
diff --git a/awk.html.markdown b/awk.html.markdown
index 3ff3f937..b8b6271a 100644
--- a/awk.html.markdown
+++ b/awk.html.markdown
@@ -48,7 +48,7 @@ BEGIN {
# the preliminary set-up code, before you process any text files. If you
# have no text files, then think of BEGIN as the main entry point.
- # Variables are global. Just set them or use them, no need to declare..
+ # Variables are global. Just set them or use them, no need to declare.
count = 0;
# Operators just like in C and friends
@@ -209,7 +209,7 @@ function string_functions( localvar, arr) {
# Both return number of matches replaced
localvar = "fooooobar";
sub("fo+", "Meet me at the ", localvar); # localvar => "Meet me at the bar"
- gsub("e+", ".", localvar); # localvar => "m..t m. at th. bar"
+ gsub("e", ".", localvar); # localvar => "m..t m. at th. bar"
# Search for a string that matches a regular expression
# index() does the same thing, but doesn't allow a regular expression
diff --git a/de-de/brainfuck-de.html.markdown b/de-de/brainfuck-de.html.markdown
index dd62dd67..09f01cd2 100644
--- a/de-de/brainfuck-de.html.markdown
+++ b/de-de/brainfuck-de.html.markdown
@@ -1,11 +1,11 @@
---
-language: brainfuck
+language: bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]
translators:
- ["urfuchs", "https://github.com/urfuchs"]
-filename: brainfuck-de
+filename: brainfuck-de.bf
lang: de-de
---
diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown
index 0896f513..3065a033 100644
--- a/de-de/git-de.html.markdown
+++ b/de-de/git-de.html.markdown
@@ -385,6 +385,4 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-* [GitGuys](http://www.gitguys.com/)
-
* [gitflow - Ein Modell um mit Branches zu arbeiten](http://nvie.com/posts/a-successful-git-branching-model/)
diff --git a/de-de/rust-de.html.markdown b/de-de/rust-de.html.markdown
index 02bb460a..6208db68 100644
--- a/de-de/rust-de.html.markdown
+++ b/de-de/rust-de.html.markdown
@@ -1,5 +1,5 @@
---
-language: rust
+language: Rust
contributors:
- ["P1start", "http://p1start.github.io/"]
translators:
diff --git a/de-de/vim-de.html.markdown b/de-de/vim-de.html.markdown
index 8abf9a14..93fd9773 100644
--- a/de-de/vim-de.html.markdown
+++ b/de-de/vim-de.html.markdown
@@ -21,7 +21,6 @@ einer Datei.
```
vim <filename> # Öffne <filename> in Vim
- :help <topic> # Open up built-in help docs about <topic> if any exists
:help <topic> # Öffne die eingebaute Hilfe zum Thema <topic>, wenn
# es existiert
:q # Schließe vim
diff --git a/docker.html.markdown b/docker.html.markdown
index 1dad267a..1df49cc3 100644
--- a/docker.html.markdown
+++ b/docker.html.markdown
@@ -1,5 +1,6 @@
---
-language: docker
+category: tool
+tool: docker
filename: docker.bat
contributors:
- ["Ruslan López", "http://javapro.org/"]
diff --git a/el-gr/ocaml-gr.html.markdown b/el-gr/ocaml-gr.html.markdown
index 2a434821..9a15b2d3 100644
--- a/el-gr/ocaml-gr.html.markdown
+++ b/el-gr/ocaml-gr.html.markdown
@@ -5,6 +5,7 @@ contributors:
- ["Daniil Baturin", "http://baturin.org/"]
translators:
- ["Chariton Charitonidis", "https://github.com/haritonch"]
+lang: el-gr
---
Η OCaml είναι μία strictly evaluated συναρτησιακή γλώσσα με κάποια στοιχεία
@@ -270,7 +271,7 @@ let line = read_line () ;;
(*** User-defined τύποι δεδομένων ***)
(* Μπορούμε να ορίζουμε τύπους δεδομένων με τη δομή "type some_type".
- Όπως σε αυτό τον άχρηστο τύπο που αντιγράφει τους ακεραίους: )
+ Όπως σε αυτό τον άχρηστο τύπο που αντιγράφει τους ακεραίους: *)
type my_int = int ;;
(* Πιο ενδιαφέροντες τύποι περιλαμβάνουν τους λεγόμενους type constructors.
@@ -372,7 +373,6 @@ let rec sum_int_list l =
let t = Cons (1, Cons (2, Cons (3, Nil))) ;;
sum_int_list t ;;
-
```
## Περισσότερα για την OCaml
diff --git a/erlang.html.markdown b/erlang.html.markdown
index a9d280d7..62666c3a 100644
--- a/erlang.html.markdown
+++ b/erlang.html.markdown
@@ -1,7 +1,7 @@
---
language: erlang
contributors:
- - ["Giovanni Cappellotto", "http://www.focustheweb.com/"]
+ - ["Giovanni Cappellotto", "http://giovanni.curlybrackets.it/"]
filename: learnerlang.erl
---
diff --git a/es-es/awk-es.html.markdown b/es-es/awk-es.html.markdown
index 8da8f024..2f771320 100644
--- a/es-es/awk-es.html.markdown
+++ b/es-es/awk-es.html.markdown
@@ -196,7 +196,7 @@ function string_functions( localvar, arr) {
# Ambas regresan el número de matches remplazados.
localvar = "fooooobar"
sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar"
- gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar"
+ gsub("e", ".", localvar) # localvar => "m..t m. at th. bar"
# Buscar una cadena que haga match con una expresión regular
# index() hace lo mismo, pero no permite expresiones regulares
diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown
index 749365d1..dc0dda30 100644
--- a/es-es/git-es.html.markdown
+++ b/es-es/git-es.html.markdown
@@ -410,8 +410,6 @@ $ git rm /directorio/del/archivo/FooBar.c
* [SalesForce Chuleta](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-* [GitGuys](http://www.gitguys.com/)
-
* [Git - La guía simple](http://rogerdudler.github.io/git-guide/index.html)
* [Pro Git](http://www.git-scm.com/book/en/v2)
diff --git a/es-es/rust-es.html.markdown b/es-es/rust-es.html.markdown
index dc48abf5..b0a3873c 100644
--- a/es-es/rust-es.html.markdown
+++ b/es-es/rust-es.html.markdown
@@ -1,5 +1,5 @@
---
-language: rust
+language: Rust
contributors:
- ["P1start", "http://p1start.github.io/"]
translators:
diff --git a/fortran95.html.markdown b/fortran90.html.markdown
index 5fa8ca88..2f2cfdfd 100644
--- a/fortran95.html.markdown
+++ b/fortran90.html.markdown
@@ -2,16 +2,16 @@
language: Fortran
contributors:
- ["Robert Steed", "https://github.com/robochat"]
-filename: learnfortran.f95
+filename: learnfortran.f90
---
-Fortran is one of the oldest computer languages. It was developed in the 1950s
-by IBM for numeric calculations (Fortran is an abbreviation of "Formula
+Fortran is one of the oldest computer languages. It was developed in the 1950s
+by IBM for numeric calculations (Fortran is an abbreviation of "Formula
Translation"). Despite its age, it is still used for high-performance computing
such as weather prediction. However, the language has changed considerably over
the years, although mostly maintaining backwards compatibility; well known
-versions are FORTRAN 77, Fortran 90, Fortran 95, Fortran 2003, Fortran 2008 and
-Fortran 2015.
+versions are FORTRAN 77, Fortran 90, Fortran 95, Fortran 2003, Fortran 2008,
+Fortran 2015, and Fortran 2018.
This overview will discuss the features of Fortran 95 since it is the most
widely implemented of the more recent specifications and the later versions are
@@ -30,29 +30,29 @@ program example !declare a program called example.
! Declaring Variables
! ===================
-
+
! All declarations must come before statements and expressions.
-
+
implicit none !prevents dynamic declaration of variables (recommended!)
! Implicit none must be redeclared in every function/program/module...
-
+
! IMPORTANT - Fortran is case insensitive.
real z
REAL Z2
- real :: v,x ! WARNING: default initial values are compiler dependent!
+ real :: v,x ! WARNING: default initial values are compiler dependent!
real :: a = 3, b=2E12, c = 0.01
integer :: i, j, k=1, m
real, parameter :: PI = 3.1415926535897931 !declare a constant.
logical :: y = .TRUE. , n = .FALSE. !boolean type.
complex :: w = (0,1) !sqrt(-1)
character (len=3) :: month !string of 3 characters.
-
+
real :: array(6) !declare an array of 6 reals.
real, dimension(4) :: arrayb !another way to declare an array.
integer :: arrayc(-10:10) !an array with a custom index.
real :: array2d(3,2) !multidimensional array.
-
+
! The '::' separators are not always necessary but are recommended.
! many other variable attributes also exist:
@@ -65,8 +65,8 @@ program example !declare a program called example.
! in functions since this automatically implies the 'save' attribute
! whereby values are saved between function calls. In general, separate
! declaration and initialisation code except for constants!
-
-
+
+
! Strings
! =======
@@ -75,7 +75,7 @@ program example !declare a program called example.
character (len = 30) :: str_b
character (len = *), parameter :: a_long_str = "This is a long string."
!can have automatic counting of length using (len=*) but only for constants.
-
+
str_b = a_str // " keyboard" !concatenate strings using // operator.
@@ -98,7 +98,7 @@ program example !declare a program called example.
! Other symbolic comparisons are < > <= >= == /=
b = 4
else if (z .GT. a) then !z greater than a
- ! Text equivalents to symbol operators are .LT. .GT. .LE. .GE. .EQ. .NE.
+ ! Text equivalents to symbol operators are .LT. .GT. .LE. .GE. .EQ. .NE.
b = 6
else if (z < a) then !'then' must be on this line.
b = 5 !execution block must be on a new line.
@@ -145,32 +145,32 @@ program example !declare a program called example.
cycle !jump to next loop iteration.
enddo
-
+
! Goto statement exists but it is heavily discouraged though.
- goto 10
+ goto 10
stop 1 !stops code immediately (returning specified condition code).
10 j = 201 !this line is labeled as line 10
-
-
+
+
! Arrays
! ======
array = (/1,2,3,4,5,6/)
array = [1,2,3,4,5,6] !using Fortran 2003 notation.
arrayb = [10.2,3e3,0.41,4e-5]
array2d = reshape([1.0,2.0,3.0,4.0,5.0,6.0], [3,2])
-
+
! Fortran array indexing starts from 1.
! (by default but can be defined differently for specific arrays).
v = array(1) !take first element of array.
v = array2d(2,2)
-
+
print *, array(3:5) !print all elements from 3rd to 5th (inclusive).
print *, array2d(1,:) !print first column of 2d array.
-
+
array = array*3 + 2 !can apply mathematical expressions to arrays.
array = array*array !array operations occur element-wise.
!array = array*array2d !these arrays would not be compatible.
-
+
! There are many built-in functions that operate on arrays.
c = dot_product(array,array) !this is the dot product.
! Use matmul() for matrix maths.
@@ -180,13 +180,13 @@ program example !declare a program called example.
c = size(array)
print *, shape(array)
m = count(array > 0)
-
+
! Loop over an array (could have used Product() function normally).
v = 1
do i = 1, size(array)
v = v*array(i)
end do
-
+
! Conditionally execute element-wise assignments.
array = [1,2,3,4,5,6]
where (array > 3)
@@ -196,30 +196,30 @@ program example !declare a program called example.
elsewhere
array = 0
end where
-
+
! Implied-DO loops are a compact way to create arrays.
array = [ (i, i = 1,6) ] !creates an array of [1,2,3,4,5,6]
array = [ (i, i = 1,12,2) ] !creates an array of [1,3,5,7,9,11]
array = [ (i**2, i = 1,6) ] !creates an array of [1,4,9,16,25,36]
array = [ (4,5, i = 1,3) ] !creates an array of [4,5,4,5,4,5]
-
+
! Input/Output
! ============
-
+
print *, b !print the variable 'b' to the command line
! We can format our printed output.
print "(I6)", 320 !prints ' 320'
- print "(I6.4)", 3 !prints ' 0003'
+ print "(I6.4)", 3 !prints ' 0003'
print "(F6.3)", 4.32 !prints ' 4.320'
-
- ! The letter indicates the expected type and the number afterwards gives
+
+ ! The letter indicates the expected type and the number afterwards gives
! the number of characters to use for printing the value.
- ! Letters can be I (integer), F (real), E (engineering format),
+ ! Letters can be I (integer), F (real), E (engineering format),
! L (logical), A (characters) ...
print "(I3)", 3200 !print '***' since the number doesn't fit.
-
+
! we can have multiple format specifications.
print "(I5,F6.2,E6.2)", 120, 43.41, 43.41
print "(3I5)", 10, 20, 30 !3 repeats of integers (field width = 5).
@@ -230,7 +230,7 @@ program example !declare a program called example.
read "(2F6.2)", v, x !read two numbers
! To read a file.
- open(unit=11, file="records.txt", status="old")
+ open(unit=11, file="records.txt", status="old")
! The file is referred to by a 'unit number', an integer that you pick in
! the range 9:99. Status can be one of {'old','replace','new'}.
read(unit=11, fmt="(3F10.2)") a, b, c
@@ -241,39 +241,39 @@ program example !declare a program called example.
write(12, "(F10.2,F10.2,F10.2)") c, b, a
close(12)
- ! There are more features available than discussed here and alternative
+ ! There are more features available than discussed here and alternative
! variants due to backwards compatibility with older Fortran versions.
-
-
+
+
! Built-in Functions
! ==================
! Fortran has around 200 functions/subroutines intrinsic to the language.
- ! Examples -
+ ! Examples -
call cpu_time(v) !sets 'v' to a time in seconds.
k = ior(i,j) !bitwise OR of 2 integers.
v = log10(x) !log base 10.
i = floor(b) !returns the closest integer less than or equal to x.
v = aimag(w) !imaginary part of a complex number.
-
+
! Functions & Subroutines
! =======================
-
+
! A subroutine runs some code on some input values and can cause
! side-effects or modify the input values.
-
+
call routine(a,c,v) !subroutine call.
-
+
! A function takes a list of input parameters and returns a single value.
- ! However the input parameters may still be modified and side effects
+ ! However the input parameters may still be modified and side effects
! executed.
-
+
m = func(3,2,k) !function call.
-
+
! Function calls can also be evoked within expressions.
- Print *, func2(3,2,k)
-
+ Print *, func2(3,2,k)
+
! A pure function is a function that doesn't modify its input parameters
! or cause any side-effects.
m = func3(3,2,k)
@@ -297,7 +297,7 @@ contains ! Zone for defining sub-programs internal to the program.
function func2(a,b,c) result(f) !return variable declared to be 'f'.
implicit none
- integer, intent(in) :: a,b !can declare and enforce that variables
+ integer, intent(in) :: a,b !can declare and enforce that variables
!are not modified by the function.
integer, intent(inout) :: c
integer :: f !function return type declared inside the function.
@@ -328,14 +328,14 @@ contains ! Zone for defining sub-programs internal to the program.
end program example ! End of Program Definition -----------------------
-! Functions and Subroutines declared externally to the program listing need
+! Functions and Subroutines declared externally to the program listing need
! to be declared to the program using an Interface declaration (even if they
! are in the same source file!) (see below). It is easier to define them within
! the 'contains' section of a module or program.
elemental real function func4(a) result(res)
! An elemental function is a Pure function that takes a scalar input variable
-! but can also be used on an array where it will be separately applied to all
+! but can also be used on an array where it will be separately applied to all
! of the elements of an array and return a new array.
real, intent(in) :: a
res = a**2 + 1.0
@@ -345,7 +345,7 @@ end function func4
! Modules
! =======
-! A module is a useful way to collect related declarations, functions and
+! A module is a useful way to collect related declarations, functions and
! subroutines together for reusability.
module fruit
@@ -358,7 +358,7 @@ end module fruit
module fruity
! Declarations must be in the order: modules, interfaces, variables.
! (can declare modules and interfaces in programs too).
-
+
use fruit, only: apple, pear ! use apple and pear from fruit module.
implicit none !comes after module imports.
@@ -367,7 +367,7 @@ module fruity
public :: apple,mycar,create_mycar
! Declare some variables/functions private to the module (redundant here).
private :: func4
-
+
! Interfaces
! ==========
! Explicitly declare an external function/procedure within the module
@@ -377,14 +377,14 @@ module fruity
real, intent(in) :: a
end function func4
end interface
-
+
! Overloaded functions can be defined using named interfaces.
interface myabs
! Can use 'module procedure' keyword to include functions already
! defined within the module.
module procedure real_abs, complex_abs
- end interface
-
+ end interface
+
! Derived Data Types
! ==================
! Can create custom structured data collections.
@@ -394,19 +394,19 @@ module fruity
real :: dimensions(3) !i.e. length-width-height (metres).
character :: colour
end type car
-
+
type(car) :: mycar !declare a variable of your custom type.
! See create_mycar() routine for usage.
-
+
! Note: There are no executable statements in modules.
-
+
contains
subroutine create_mycar(mycar)
! Demonstrates usage of a derived data type.
implicit none
type(car),intent(out) :: mycar
-
+
! Access type elements using '%' operator.
mycar%model = "Ford Prefect"
mycar%colour = 'r'
@@ -414,7 +414,7 @@ contains
mycar%dimensions(1) = 5.0 !default indexing starts from 1!
mycar%dimensions(2) = 3.0
mycar%dimensions(3) = 1.5
-
+
end subroutine
real function real_abs(x)
@@ -425,7 +425,7 @@ contains
real_abs = x
end if
end function real_abs
-
+
real function complex_abs(z)
complex :: z
! long lines can be continued using the continuation character '&'
diff --git a/fr-fr/awk-fr.html.markdown b/fr-fr/awk-fr.html.markdown
index 75c48811..9e45a89b 100644
--- a/fr-fr/awk-fr.html.markdown
+++ b/fr-fr/awk-fr.html.markdown
@@ -10,13 +10,19 @@ lang: fr-fr
---
-AWK est un outil standard présent dans chaque système UNIX conforme aux normes POSIX.
-C’est un outil en ligne de commande qui ressemble au Perl et qui est excellent dans les tâches de traitement de fichiers texte.
-Vous pouvez l’appeler à partir d’un script shell, ou l’utiliser comme un langage de script autonome.
+AWK est un outil standard présent dans chaque système UNIX conforme aux normes
+POSIX. C’est un outil en ligne de commande qui ressemble au Perl et qui est
+excellent dans les tâches de traitement de fichiers texte.
+Vous pouvez l’appeler à partir d’un script shell, ou l’utiliser comme un langage
+de script autonome.
Pourquoi utiliser AWK au lieu du langage Perl ?
-Principalement, car AWK fait partie d'UNIX et est donc présent par défaut sur une très grande partie des systèmes d'exploitation UNIX et Linux.
-AWK est aussi plus facile à lire que le langage Perl ; et est l'outil idéal pour ce qui concerne le traitement de texte simple. Notamment le traitement de ceux qui necéssitent de lire des fichiers ligne par ligne ; chaque ligne comportant des champs séparés par des délimiteur.
+Principalement, car AWK fait partie d'UNIX et est donc présent par défaut sur
+une très grande partie des systèmes d'exploitation UNIX et Linux.
+AWK est aussi plus facile à lire que le langage Perl ; et est l'outil idéal pour
+ce qui concerne le traitement de texte simple. Notamment le traitement de ceux
+qui nécessitent de lire des fichiers ligne par ligne ; chaque ligne comportant
+des champs séparés par des délimiteur.
```awk
@@ -30,17 +36,25 @@ règle1 { action; }
règle2 { action; }
# AWK lit et analyse automatiquement chaque ligne de chaque fichier fourni.
-# Chaque ligne est divisée par un délimiteur FS qui est par défaut l'espace (plusieurs espaces ou une tabulation comptent pour un espace). Ce délimiteur peut être changer grâce à l'option -F ou être renseigné au début d'un bloc (exemple: FS = " ").
-
-# BEGIN est une règle spécifique exécutée au début du programme. C'est à cet endroit que vous mettrez tout le code à exécuter avant de traiter les fichiers texte. Si vous ne disposez pas de fichiers texte, considérez BEGIN comme le point d’entrée principal du script.
-# A l'opposé de BEGIN, il existe la règle END. Cette règle est présente après chaque fin de fichier (EOF : End Of File).
+# Chaque ligne est divisée par un délimiteur FS qui est par défaut l'espace
+# (plusieurs espaces ou une tabulation comptent pour un espace). Ce délimiteur
+# peut être changé grâce à l'option -F ou être renseigné au début d'un bloc
+# (exemple: FS = " ").
+
+# BEGIN est une règle spécifique exécutée au début du programme. C'est à cet
+# endroit que vous mettrez tout le code à exécuter avant de traiter les fichiers
+# texte. Si vous ne disposez pas de fichiers texte, considérez BEGIN comme le
+# point d’entrée principal du script.
+# À l'opposé de BEGIN, il existe la règle END. Cette règle est présente après
+#chaque fin de fichier (EOF : End Of File).
BEGIN {
# Les variables sont globales. Pas besoin de les déclarer.
count = 0;
- # les opérateurs sont identiques au langage C et aux langages similaires (exemple: C#, C++)
+ # les opérateurs sont identiques au langage C et aux langages similaires
+ # (tels que C#, C++, etc.)
a = count + 1; # addition
b = count - 1; # soustraction
c = count * 1; # multiplication
@@ -74,7 +88,8 @@ BEGIN {
# Les blocs sont composés d'une multitude de lignes entre accolades
while (a < 10) {
- print "La concaténation de chaînes de caractères" " se fait avec des séries de chaînes " " séparées par des espaces";
+ print "La concaténation de chaînes de caractères" " se fait avec"
+ "des séries de chaînes " "séparées par des espaces";
print a;
a++;
@@ -113,7 +128,9 @@ BEGIN {
assoc["foo"] = "bar";
assoc["bar"] = "baz";
- # et les tableaux multi-dimentions, avec certaines limitations que l'on ne mentionnera pas ici
+ # et les tableaux multi-dimensions, avec certaines limitations que l'on ne
+ # mentionnera pas ici
+
multidim[0,0] = "foo";
multidim[0,1] = "bar";
multidim[1,0] = "baz";
@@ -123,7 +140,8 @@ BEGIN {
if ("foo" in assoc)
print "Fooey!";
- # Vous pouvez aussi utilisez l'opérateur 'in' pour parcourir les clés d'un tableau
+ # Vous pouvez aussi utilisez l'opérateur 'in' pour parcourir les clés
+ # d'un tableau
for (key in assoc)
print assoc[key];
@@ -132,10 +150,12 @@ BEGIN {
print ARGV[argnum];
# Vous pouvez supprimer des éléments d'un tableau
- # C'est utile pour empêcher AWK de supposer que certains arguments soient des fichiers à traiter.
+ # C'est utile pour empêcher AWK de supposer que certains arguments soient
+ # des fichiers à traiter.
+
delete ARGV[1];
- # Le nombre d'arguments de la ligne de commande est dans une variable appellée ARGC
+ # Le nombre d'arguments de la ligne de commande est assigné à la variable ARGC
print ARGC;
# AWK inclue trois catégories de fonction.
@@ -149,22 +169,24 @@ BEGIN {
# Voici comment définir une fonction
function arithmetic_functions(a, b, c, d) {
- # La partie la plus ennuieuse de AWK est probablement l’absence de variables locales.
- # Tout est global. Pour les scripts courts, c'est très utile, mais pour les scripts plus longs,
- # cela peut poser problème.
+ # La partie la plus ennuyeuse de AWK est probablement l’absence de variables
+ # locales. Tout est global. Pour les scripts courts, c'est très utile, mais
+ # pour les scripts plus longs, cela peut poser un problème.
- # Il y a cepandant une solution de contournement (enfin ... une bidouille).
+ # Il y a cependant une solution de contournement (enfin ... une bidouille).
# Les arguments d'une fonction sont locaux à cette fonction.
# Et AWK vous permet de définir plus d'arguments à la fonction que nécessaire.
# Il suffit donc de mettre une variable locale dans la déclaration de fonction,
- # comme ci-dessus. La convention veut que vous mettiez quelques espaces supplémentaires
- # pour faire la distinction entre les paramètres réels et les variables locales.
+ # comme ci-dessus. La convention veut que vous mettiez quelques espaces
+ # supplémentaires pour faire la distinction entre les paramètres réels et
+ # les variables locales.
# Dans cet exemple, a, b et c sont des paramètres réels,
# alors que d est simplement une variable locale.
# Maintenant, les fonctions arithmétiques
- # La plupart des implémentations de AWK ont des fonctions trigonométriques standards
+ # La plupart des implémentations de AWK ont des fonctions trigonométriques
+ # standards
localvar = sin(a);
localvar = cos(a);
localvar = atan2(b, a); # arc tangente de b / a
@@ -180,10 +202,10 @@ function arithmetic_functions(a, b, c, d) {
localvar = int(5.34); # localvar => 5
# Les nombres aléatoires
- srand();
+ srand();
# L'argument de la fonction srand() est la valeur de départ pour générer
# les nombres aléatoires . Par défaut, il utilise l'heure du système
-
+
localvar = rand(); # Nombre aléatoire entre 0 et 1.
# Maintenant on retourne la valeur
@@ -195,11 +217,13 @@ function string_functions( localvar, arr) {
# AWK a plusieurs fonctions pour le traitement des chaînes de caractères,
# dont beaucoup reposent sur des expressions régulières.
- # Chercher et remplacer, la première occurence (sub) ou toutes les occurences (gsub)
+ # Chercher et remplacer, la première occurrence (sub) ou toutes les
+ # occurrences (gsub)
# Les deux renvoient le nombre de correspondances remplacées
+
localvar = "fooooobar";
sub("fo+", "Meet me at the ", localvar); # localvar => "Meet me at the bar"
- gsub("e+", ".", localvar); # localvar => "m..t m. at th. bar"
+ gsub("e", ".", localvar); # localvar => "m..t m. at th. bar"
# Rechercher une chaîne de caractères qui correspond à une expression régulière
# index() fait la même chose, mais n'autorise pas les expressions régulières
@@ -226,7 +250,8 @@ function io_functions( localvar) {
printf("%s %d %d %d\n", "Testing", 1, 2, 3);
# AWK n'a pas de descripteur de fichier en soi. Il ouvrira automatiquement
- # un descripteur de fichier lorsque vous utilisez quelque chose qui en a besoin.
+ # un descripteur de fichier lorsque vous utilisez quelque chose qui en a
+ # besoin.
# La chaîne de caractères que vous avez utilisée pour cela peut être traitée
# comme un descripteur de fichier à des fins d'entrée / sortie.
@@ -241,11 +266,12 @@ function io_functions( localvar) {
# Voici comment exécuter quelque chose dans le shell
system("echo foobar"); # => affiche foobar
- # Lire quelque chose depuis l'entrée standard et la stocker dans une variable locale
+ # Lire quelque chose depuis l'entrée standard et la stocker dans une variable
+ # locale
getline localvar;
- # Lire quelque chose à partir d'un pipe (encore une fois, utilisez une chaine de caractère
- # que vous fermerez proprement)
+ # Lire quelque chose à partir d'un pipe (encore une fois, utilisez une
+ # chaîne de caractère que vous fermerez proprement)
"echo foobar" | getline localvar # localvar => "foobar"
close("echo foobar")
@@ -256,18 +282,19 @@ function io_functions( localvar) {
}
# Comme dit au début, AWK consiste en une collection de règles et d'actions.
-# Vous connaissez déjà les règles BEGIN et END. Les autres règles ne sont utilisées que si vous traitez
-# des lignes à partir de fichiers ou l'entrée standard (stdin).
-# Quand vous passez des arguments à AWK, ils sont considérés comme des noms de fichiers à traiter.
-# AWK les traitera tous dans l'ordre. Voyez les comme dans à une boucle implicite,
-# parcourant les lignes de ces fichiers.
-# Ces règles et ces actions ressemblent à des instructions switch dans la boucle.
+# Vous connaissez déjà les règles BEGIN et END. Les autres règles ne sont
+# utilisées que si vous traitez des lignes à partir de fichiers ou l'entrée
+# standard (stdin).
+# Quand vous passez des arguments à AWK, ils sont considérés comme des noms de
+# fichiers à traiter. AWK les traitera tous dans l'ordre. Voyez les comme dans
+# une boucle implicite, parcourant les lignes de ces fichiers. Ces règles et ces
+# actions ressemblent à des instructions switch dans la boucle.
/^fo+bar$/ {
- # Cette action sera exécutée pour chaque ligne qui correspond à l'expression régulière,
- # /^fo+bar$/, et sera ignorée pour toute ligne qui n'y correspond pas.
- # Imprimons simplement la ligne:
+ # Cette action sera exécutée pour chaque ligne qui correspond à l'expression
+ # régulière, /^fo+bar$/, et sera ignorée pour toute ligne qui n'y correspond
+ # pas. Imprimons simplement la ligne:
print;
@@ -275,14 +302,15 @@ function io_functions( localvar) {
# $0 est le nom de la ligne en cours de traitement. Il est créé automatiquement.
# Vous devinez probablement qu'il existe d'autres variables $.
- # Chaque ligne est divisée implicitement avant que chaque action soit exécutée, comme
- # le fait le shell. Et, comme le shell, chaque champ est accessible avec un signe dollar
+ # Chaque ligne est divisée implicitement avant que chaque action soit exécutée,
+ # comme le fait le shell. Et, comme le shell, chaque champ est accessible
+ # avec un signe dollar
# Ceci affichera les deuxième et quatrième champs de la ligne.
print $2, $4;
- # AWK défini automatiquement beaucoup d'autres variables qui peuvent vous aider
- # à inspecter et traiter chaque ligne. La plus importante est NF
+ # AWK défini automatiquement beaucoup d'autres variables qui peuvent vous
+ # aider à inspecter et traiter chaque ligne. La plus importante est NF
# Affiche le nombre de champs de la ligne
print NF;
@@ -291,33 +319,37 @@ function io_functions( localvar) {
print $NF;
}
-# Chaque règle est en réalité un test conditionel.
+# Chaque règle est en réalité un test conditionnel.
a > 0 {
# Ceci s’exécutera une fois pour chaque ligne, tant que le test est positif
}
-# Les expressions régulières sont également des tests conditionels.
-#Si le test de l'expression régulières n'est pas vrais alors le bloc n'est pas executé
-$0 /^fobar/ {
- print "la ligne commance par fobar"
+# Les expressions régulières sont également des tests conditionnels.
+# Si le test de l'expression régulières n'est pas vrais alors le bloc
+# n'est pas exécuté.
+
+$0 /^fobar/ {
+ print "la ligne commence par foobar"
}
-# Dans le cas où vous voulez tester votre chaine de caractères sur la ligne en cours de traitement
-# $0 est optionnelle.
+# Dans le cas où vous voulez tester votre chaîne de caractères sur la ligne
+# en cours de traitement $0 est optionnelle.
/^[a-zA-Z0-9]$/ {
print "La ligne courante ne contient que des caractères alphanumériques.";
}
-# AWK peut parcourir un fichier texte ligne par ligne et exécuter des actions en fonction de règles établies
-# Cela est si courant sous UNIX qu'AWK est un langage de script.
+# AWK peut parcourir un fichier texte ligne par ligne et exécuter des actions en
+# fonction de règles établies. Cela est si courant sous UNIX qu'AWK est un
+# langage de script.
-# Ce qui suit est un exemple rapide d'un petit script, pour lequel AWK est parfait.
-# Le script lit un nom à partir de l'entrée standard, puis affiche l'âge moyen de toutes les
-# personnes portant ce prénom.
-# Supposons que vous fournissiez comme argument le nom d'un fichier comportant ces données:
+# Ce qui suit est un exemple rapide d'un petit script, pour lequel AWK est
+# parfait. Le script lit un nom à partir de l'entrée standard, puis affiche
+# l'âge moyen de toutes les personnes portant ce prénom.
+# Supposons que vous fournissiez comme argument le nom d'un fichier comportant
+# ces données:
#
# Bob Jones 32
# Jane Doe 22
@@ -330,7 +362,7 @@ $0 /^fobar/ {
BEGIN {
# Premièrement, on demande à l'utilisateur le prénom voulu
- print "Pour quel prénom vouldriez vous savoir l'age moyen ?";
+ print "Pour quel prénom voudriez vous savoir l'age moyen ?";
# On récupère la ligne à partir de l'entrée standard, pas de la ligne de commande
getline name < "/dev/stdin";
diff --git a/fr-fr/git-fr.html.markdown b/fr-fr/git-fr.html.markdown
index 510459fe..00b6b6e1 100644
--- a/fr-fr/git-fr.html.markdown
+++ b/fr-fr/git-fr.html.markdown
@@ -574,8 +574,6 @@ $ git rm /chemin/vers/le/fichier/HelloWorld.c
* [SalesForce Cheat Sheet (EN)](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-* [GitGuys (EN)](http://www.gitguys.com/)
-
* [Git - the simple guide (EN)](http://rogerdudler.github.io/git-guide/index.html)
* [Livre Pro Git](http://www.git-scm.com/book/fr/v1)
diff --git a/fr-fr/rust-fr.html.markdown b/fr-fr/rust-fr.html.markdown
index a61f78be..6fc0d07d 100644
--- a/fr-fr/rust-fr.html.markdown
+++ b/fr-fr/rust-fr.html.markdown
@@ -1,5 +1,5 @@
---
-language: rust
+language: Rust
contributors:
- ["P1start", "http://p1start.github.io/"]
translators:
@@ -309,7 +309,7 @@ fn main() {
Il y a beaucoup plus à Rust -- ce est juste l'essentiel de Rust afin que vous puissiez comprendre
les choses les plus importantes. Pour en savoir plus sur Rust, lire [La Programmation Rust
-Langue](http://doc.rust-lang.org/book/index.html) et etudier la
+Langue](http://doc.rust-lang.org/book/index.html) et étudier la
[/r/rust](http://reddit.com/r/rust) subreddit. Les gens sur le canal de #rust sur
irc.mozilla.org sont aussi toujours prêts à aider les nouveaux arrivants.
diff --git a/fr-fr/set-theory-fr.html.markdown b/fr-fr/set-theory-fr.html.markdown
index 50a4ea30..543bd98b 100644
--- a/fr-fr/set-theory-fr.html.markdown
+++ b/fr-fr/set-theory-fr.html.markdown
@@ -1,11 +1,11 @@
-```
---
-category: tool
-lang: fr-fr
+category: Algorithms & Data Structures
name: Set theory
+lang: fr-fr
contributors:
- - ["kieutrang", "https://github.com/kieutrang1729"]
+ - ["kieutrang", "https://github.com/kieutrang1729"]
---
+
La théorie des ensembles est une branche des mathématiques qui étudie les ensembles, leurs opérations et leurs propriétés.
* Un ensemble est une collection d'éléments disjoints.
@@ -32,9 +32,9 @@ La théorie des ensembles est une branche des mathématiques qui étudie les ens
* `ℚ`, l'ensemble des nombres rationnels ;
* `ℝ`, l'ensemble des nombres réels.
-Quelques mise en gardes sur les ensembles definis ci-dessus:
+Quelques mise en gardes sur les ensembles définis ci-dessus:
1. Même si l'ensemble vide ne contient aucun élément, il est lui-même un sous-ensemble de n'importe quel ensemble.
-2. Il n'y a pas d'accord général sur l'appartenance de zéro dans l'ensemble des nombres naturels, et les livres indiquent explicitment si l'auteur considère le zéro comme nombre naturel ou pas.
+2. Il n'y a pas d'accord général sur l'appartenance de zéro dans l'ensemble des nombres naturels, et les livres indiquent explicitement si l'auteur considère le zéro comme nombre naturel ou pas.
### Cardinalité
@@ -43,7 +43,7 @@ La cardinalité, ou taille, d'un ensemble est déterminée par le nombre d'élé
Par exemple, si `S = { 1, 2, 4 }`, alors `|S| = 3`.
### L'ensemble vide
-* L'ensemble vide peut se définir en comprehension à l'aide d'une propriété qui n'est satisfaite par nul élément, e.g. `∅ = { x : x ≠ x }`, ou `∅ = { x : x ∈ N, x < 0 }`.
+* L'ensemble vide peut se définir en compréhension à l'aide d'une propriété qui n'est satisfaite par nul élément, e.g. `∅ = { x : x ≠ x }`, ou `∅ = { x : x ∈ N, x < 0 }`.
* il n'y a qu'un seul ensemble vide.
* l'ensemble vide est sous-ensemble de tout ensemble.
* la cardinalité de l'ensemble vide est 0, ou `|∅| = 0`.
@@ -54,9 +54,9 @@ Par exemple, si `S = { 1, 2, 4 }`, alors `|S| = 3`.
Un ensemble peut être defini en extension par une liste de tous les éléments qui sont contenus dans l'ensemble. Par exemple, `S = { a, b, c, d }`.
-Quand le contexte est clair, on peut raccourcir la liste en utilisant des points de suspension. Par exemple, `E = { 2, 4, 6, 8, ... }` est clairement l'ensemble de tous les nombres pairs, contenant un nombre infini des éléments, même si on a explicitement écrit seulement les quatres premiers.
+Quand le contexte est clair, on peut raccourcir la liste en utilisant des points de suspension. Par exemple, `E = { 2, 4, 6, 8, ... }` est clairement l'ensemble de tous les nombres pairs, contenant un nombre infini des éléments, même si on a explicitement écrit seulement les quatre premiers.
-### Définition par comprehension
+### Définition par compréhension
C'est une notation plus descriptif qui permet de définir un ensemble à l'aide d'un sujet et d'une propriété, et il est noté `S = { sujet : propriété }`. Par exemple,
@@ -76,18 +76,18 @@ D = { 2x : x ∈ N } = { 0, 2, 4, 6, 8, ... }
### Appartenance
-* Si l'élement `a` est dans l'ensemble `A`, on dit que `a` appartient à `A` et on le note `a ∈ A`.
-* Si l'élement `a` n'est pas dans l'ensemble `A`, on dit que `a` n'appartient pas à `A` et on le note `a ∉ A`.
+* Si l'élément `a` est dans l'ensemble `A`, on dit que `a` appartient à `A` et on le note `a ∈ A`.
+* Si l'élément `a` n'est pas dans l'ensemble `A`, on dit que `a` n'appartient pas à `A` et on le note `a ∉ A`.
### Égalité
* On dit que deux ensembles `A` et `B` sont égaux s'ils contiennent les mêmes éléments, et on le note `A = B`.
* Les ensembles n'ont pas de notion d'ordre, par exemple `{ 1, 2, 3, 4 } = { 2, 3, 1, 4 }`.
* Un élément ne peut apparaître qu'au plus une seule fois - il n'y a jamais de répétition, e.g. `{ 1, 2, 2, 3, 4, 3, 4, 2 } = { 1, 2, 3, 4 }`.
-* Deux ensembles `A` and `B` sont égaux si et seulement si `A ⊆ B` and `B ⊆ A`.
+* Deux ensembles `A` et `B` sont égaux si et seulement si `A ⊆ B` et `B ⊆ A`.
## Ensemble puissance
-* L'ensemble puissance d'un ensemble `A` est l'ensemble contenant tous les sous-ensembles de `A`. Il est noté `P(A)`. Si la cardinalité d'`A` est `n`, la cardinalité de `P(A)` est `2^n`.
+* L'ensemble puissance d'un ensemble `A` est l'ensemble contenant tous les sous-ensembles de `A`. Il est noté `P(A)`. Si la cardinalité de `A` est `n`, la cardinalité de `P(A)` est `2^n`.
```
P(A) = { x : x ⊆ A }
@@ -130,5 +130,3 @@ Le produit cartésien de deux ensembles `A` et `B` est l'ensemble contenant tous
```
A × B = { (x, y) | x ∈ A, y ∈ B }
```
-
-```
diff --git a/git.html.markdown b/git.html.markdown
index a40ef01b..474ee25d 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -597,8 +597,6 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [SalesForce Cheat Sheet](http://res.cloudinary.com/hy4kyit2a/image/upload/SF_git_cheatsheet.pdf)
-* [GitGuys](http://www.gitguys.com/)
-
* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html)
* [Pro Git](http://www.git-scm.com/book/en/v2)
diff --git a/go.html.markdown b/go.html.markdown
index dfbfc374..39c8ac74 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -478,6 +478,6 @@ There are many excellent conference talks and video tutorials on Go available on
- [Golang University 101](https://www.youtube.com/playlist?list=PLEcwzBXTPUE9V1o8mZdC9tNnRZaTgI-1P) introduces fundamental Go concepts and shows you how to use the Go tools to create and manage Go code
- [Golang University 201](https://www.youtube.com/playlist?list=PLEcwzBXTPUE_5m_JaMXmGEFgduH8EsuTs) steps it up a notch, explaining important techniques like testing, web services, and APIs
-- [Golang University 301](https://www.youtube.com/watch?v=YHRO5WQGh0k&list=PLEcwzBXTPUE8KvXRFmmfPEUmKoy9LfmAf) dives into more advanced topics like the Go scheduler, implementation of maps and channels, and optimisation techniques
+- [Golang University 301](https://www.youtube.com/playlist?list=PLEcwzBXTPUE8KvXRFmmfPEUmKoy9LfmAf) dives into more advanced topics like the Go scheduler, implementation of maps and channels, and optimisation techniques
Go Mobile adds support for mobile platforms (Android and iOS). You can write all-Go native mobile apps or write a library that contains bindings from a Go package, which can be invoked via Java (Android) and Objective-C (iOS). Check out the [Go Mobile page](https://github.com/golang/go/wiki/Mobile) for more information.
diff --git a/it-it/rust-it.html.markdown b/it-it/rust-it.html.markdown
index df4d6279..acb8b8ba 100644
--- a/it-it/rust-it.html.markdown
+++ b/it-it/rust-it.html.markdown
@@ -1,5 +1,5 @@
---
-language: rust
+language: Rust
contributors:
- ["Carlo Milanesi", "http://github.com/carlomilanesi"]
lang: it-it
diff --git a/latex.html.markdown b/latex.html.markdown
index 34c4b78d..9edc057e 100644
--- a/latex.html.markdown
+++ b/latex.html.markdown
@@ -320,3 +320,5 @@ That's all for now!
* The amazing LaTeX Wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX)
* An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
* A quick guide for learning LaTeX: [Learn LaTeX in 30 minutes](https://www.overleaf.com/learn/latex/Learn_LaTeX_in_30_minutes)
+* An interactive platform to learn LaTeX (installationfree) [learnlatex.org/](https://www.learnlatex.org/)
+* Stack Exchange's question and answer site about TeX, LaTeX, ConTeXt, etc. [tex.stackexchange.com](https://tex.stackexchange.com/)
diff --git a/mips.html.markdown b/mips.html.markdown
index 7f679082..0e7a7d0c 100644
--- a/mips.html.markdown
+++ b/mips.html.markdown
@@ -193,7 +193,7 @@ gateways and routers.
# Let $s0 = a, $s1 = b, $s2 = c, $v0 = return register
ble $s0, $s1, a_LTE_b # if(a <= b) branch(a_LTE_b)
ble $s0, $s2, max_C # if(a > b && a <=c) branch(max_C)
- move $v0, $s1 # else [a > b && a > c] max = a
+ move $v0, $s0 # else [a > b && a > c] max = a
j done # Jump to the end of the program
a_LTE_b: # Label for when a <= b
diff --git a/mongodb.html.markdown b/mongodb.html.markdown
index 959b57d0..306f361c 100644
--- a/mongodb.html.markdown
+++ b/mongodb.html.markdown
@@ -256,7 +256,7 @@ db.engineers.find({ $gt: { age: 25 }})
db.engineers.find({ $gte: { age: 25 }})
// Find all less than or less than equal to some condition
-db.engineers.find({ $lte: { age: 25 }})
+db.engineers.find({ $lt: { age: 25 }})
db.engineers.find({ $lte: { age: 25 }})
// Find all equal or not equal to
@@ -293,7 +293,7 @@ db.engineers.find({ $not: {
// Must match none of the query conditions
db.engineers.find({ $nor [
- gender: 'Female,
+ gender: 'Female',
age: {
$gte: 18
}
@@ -400,6 +400,6 @@ features, I would look at
- Aggregation - useful for creating advanced queries to be executed by the
database
-- Idexing allows for caching, which allows for much faster execution of queries
+- Indexing allows for caching, which allows for much faster execution of queries
- Sharding allows for horizontal data scaling and distribution between multiple
machines.
diff --git a/pt-br/awk-pt.html.markdown b/pt-br/awk-pt.html.markdown
index 70d0a01c..366ae886 100644
--- a/pt-br/awk-pt.html.markdown
+++ b/pt-br/awk-pt.html.markdown
@@ -202,7 +202,7 @@ function string_functions( localvar, arr) {
# Ambas retornam o número de instâncias substituídas
localvar = "fooooobar"
sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar"
- gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar"
+ gsub("e", ".", localvar) # localvar => "m..t m. at th. bar"
# Localiza um texto que casa com uma expressão regular
# index() faz a mesma coisa, mas não permite uma expressão regular
diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown
index 4e55f068..6885c41a 100644
--- a/pt-br/c-pt.html.markdown
+++ b/pt-br/c-pt.html.markdown
@@ -1,6 +1,6 @@
---
language: c
-filename: learnc.c
+filename: learnc-pt.c
contributors:
- ["Adam Bard", "http://adambard.com/"]
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
@@ -10,7 +10,6 @@ translators:
- ["Cássio Böck", "https://github.com/cassiobsilva"]
- ["Heitor P. de Bittencourt", "https://github.com/heitorPB/"]
lang: pt-br
-filename: c-pt.el
---
Ah, C. Ainda é **a** linguagem de computação de alta performance.
diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown
index e59ba901..c2e85ab2 100644
--- a/pt-br/git-pt.html.markdown
+++ b/pt-br/git-pt.html.markdown
@@ -440,5 +440,3 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/)
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-
-* [GitGuys](http://www.gitguys.com/)
diff --git a/pt-br/groovy-pt.html.markdown b/pt-br/groovy-pt.html.markdown
index 3acfce21..dff3f2e1 100644
--- a/pt-br/groovy-pt.html.markdown
+++ b/pt-br/groovy-pt.html.markdown
@@ -5,7 +5,8 @@ filename: learngroovy-pt.groovy
contributors:
- ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"]
translators:
- - ["João Farias", "https://github.com/JoaoGFarias"]
+ - ["João Farias", "https://github.com/joaogfarias"]
+ - ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"]
lang: pt-br
---
@@ -201,8 +202,16 @@ if(x==1) {
//Groovy também suporta o operador ternário
def y = 10
-def x = (y > 1) ? "functionou" : "falhou"
-assert x == "functionou"
+def x = (y > 1) ? "funcionou" : "falhou"
+assert x == "funcionou"
+
+//E suporta o 'The Elvis Operator' também!
+//Em vez de usar o operador ternário:
+
+displayName = nome.name ? nome.name : 'Anonimo'
+
+//Podemos escrever:
+displayName = nome.name ?: 'Anonimo'
//Loop 'for'
//Itera sobre um intervalo (range)
diff --git a/pt-br/latex-pt.html.markdown b/pt-br/latex-pt.html.markdown
index 58586522..919c0f4f 100644
--- a/pt-br/latex-pt.html.markdown
+++ b/pt-br/latex-pt.html.markdown
@@ -8,6 +8,7 @@ contributors:
- ["Svetlana Golubeva", "https://attillax.github.io/"]
translators:
- ["Paulo Henrique Rodrigues Pinheiro", "https://github.com/paulohrpinheiro"]
+ - ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"]
lang: pt-br
filename: learn-latex-pt.tex
---
@@ -16,10 +17,10 @@ filename: learn-latex-pt.tex
% Todas as linhas de comentários começam com %
% Não existem comentários multilinhas
-$ LaTeX não é um programa processador de textos "Visual" como
+% LaTeX não é um programa processador de textos "Visual" como
% MS Word ou OpenOffice Writer
-$ Todo comando LaTeX começa com uma barra invertida (\)
+% Todo comando LaTeX começa com uma barra invertida (\)
% Documentos LaTeX começam com a definição do tipo que será % compilado
% Os tipos de documento podem ser livro, relatório, apresentação, etc.
@@ -37,14 +38,11 @@ $ Todo comando LaTeX começa com uma barra invertida (\)
\usepackage{float}
\usepackage{hyperref}
-% Para poder usar caracteres acentuados, use o seguinte pacote:
-\usepackage[utf8]{inputenc}
-
% Podemos definir algumas outras propriedades do documento também!
\author{Chaitanya Krishna Ande, Colton Kohnke, Sricharan Chiruvolu \& \\
Svetlana Golubeva}
\date{\today}
-\title{Aprenda \LaTeX \hspace{1pt} em Y Minutos!}
+\title{Aprenda \LaTeX{} em Y Minutos!}
% Agora estamos prontos para começar o documento
% Tudo antes dessa linha é chamado "preâmbulo".
@@ -52,6 +50,7 @@ Svetlana Golubeva}
% Se informarmos os campos author (autores), date (data), "title" (título),
% LaTeX poderá cria uma página inicial para nós.
\maketitle
+
% Se tivermos seções, poderemos criar uma tabela de conteúdo. Para isso,
% o documento deve ser compilado duas vezes, para que tudo apareça na ordem
% correta.
@@ -69,7 +68,7 @@ Svetlana Golubeva}
% Esse comando está disponível para os documentos do tipo artigo (article)
% e relatório (report).
\begin{abstract}
- Documentação do \LaTeX \hspace{1pt} escrita em \LaTeX! Nada original!
+ Documentação do \LaTeX{} escrita em \LaTeX! Nada original!
\end{abstract}
% Comandos para seções são intuitivos.
@@ -93,11 +92,17 @@ Muito melhor agora.
Afinal nem todas as seções precisam ser numeradas!
\section{Algumas notas sobre texto}
-%\section{Espaçamento % É necessário mais informação sobre intervalos de espaço.
-\LaTeX \hspace{1pt} geralmente é muito bom sobre colocar texto onde ele deve
+%\section{Espaçamento} % É necessário mais informação sobre intervalos de espaço.
+\LaTeX{} geralmente é muito bom sobre colocar texto onde ele deve
ser posto. Se
uma linha \\ deve \\ ser \\ quebrada \\ adicione \textbackslash\textbackslash
-\hspace{1pt} ao código de seu documento. \\
+\hspace{1pt} ao código de seu documento.
+
+Separe parágrafos por linhas vazias.
+
+Você precisa adicionar um til após abreviações (se não forem seguidas de vírgula)
+para um espaço sem quebra, senão o espaçamento após o ponto será muito largo:
+E.g., i.e., etc.~são exemplos de abreviações.
\section{Listas}
Listas são uma das coisas mais fáceis de criar no \LaTeX! Preciso fazer compras
@@ -112,21 +117,21 @@ amanhã, então façamos uma lista de compras.
Não é um item da lista, mas faz parte do bloco enumerate.
- \end{enumerate} % Todos os blocos devem ter um final (end{}).
+\end{enumerate} % Todos os blocos devem ter um final (end{}).
\section{Matemática}
-Um dos usos iniciais para \LaTeX \hspace{1pt} foi a produção de artigos
+Um dos usos iniciais para \LaTeX{} foi a produção de artigos
acadêmicos e técnicos. Usualmente nos campos da matemática e ciência. Assim, é
-necessários que consigamos incluir alguns símbolos especiais em nosso texto! \\
+necessários que consigamos incluir alguns símbolos especiais em nosso texto!
A matemática tem muitos símbolos, além dos quais se pode encontrar no teclado;
símbolos para relações e conjuntos, setas, operadores, e letras gregas, apenas
-para mencionar alguns.\\
+para mencionar alguns.
Conjuntos e relações são essenciais em muitos textos de pesquisa em matemática.
Aqui está como você pode indicar como todo x que pertence
-a X, $\forall$ x $\in$ X. \\
+a X, $\forall$ x $\in$ X.
% Perceba que é necessário adicionar os sinais $ antes e depois dos símbolos.
% Isso é porque quando escrevendo, estamos em modo texto.
% Mas os símbolos de matemática só existem no modo matemática.
@@ -138,15 +143,14 @@ a X, $\forall$ x $\in$ X. \\
\[a^2 + b^2 = c^2 \]
Minha letra grega favorita é $\xi$. Eu também gosto da $\beta$, $\gamma$ e $\sigma$.
-Eu ainda não encontrei uma letra grega que o \LaTeX \hspace{1pt} não tenha!\\
+Eu ainda não encontrei uma letra grega que o \LaTeX{} não tenha!\\
Operadores são parte essencial de um documento sobre matemática:
funções trigonométricas ($\sin$, $\cos$, $\tan$),
logaritmo e exponencial ($\log$, $\exp$),
-limites ($\lim$), etc.
-possuem comandos pré-definidos em LaTex.
+limites ($\lim$), etc.~possuem comandos pré-definidos em LaTex.
Vamos escrever uma equação para ver como se faz:
-$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ \\
+$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$
Frações (numerador/denominador) podem ser escritas dessa forma:
@@ -183,8 +187,10 @@ Somatórios e Integrais são escritas com os comandos sum e int:
\section{Figuras}
-Insiramos uma Figura. O local para colocar a figura pode ser difícil
-de determinar. Eu tenho sempre que verificar as opções toda vez.
+Insiramos uma Figura. O local para colocar a figura pode ser difícil de determinar.
+Operações básicas são [t] para o topo, [b] para base, [h] para aqui (aproximadamente).
+Eu tenho sempre que verificar as opções toda vez.
+% Veja https://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions para mais detalhes
\begin{figure}[H] % H aqui é uma opção para o local da figura.
\centering % centra a figura na página
@@ -201,36 +207,45 @@ Também podemos incluir tabelas da mesma forma que figuras.
\begin{table}[H]
\caption{Título para a Tabela.}
% os argumentos {} abaixo descrevem como cada linha da tabela é desenhada.
- % Aqui também, Preciso ver isso. Toda. E. Cada. Vez.
+ % O básico é simples: uma letra para cada coluna, para controlar o alinhamento:
+ % Operações básicas são: c, l, r e p para centro, esquerda, direita e parágrafo
+ % opcionalmente, você pode adicionar um | para linha vertical
+ % Veja https://en.wikibooks.org/wiki/LaTeX/Tables para mais detalhes
\begin{tabular}{c|cc}
- Número & Sobrenome & Primeiro Nome \\ % Colunas são separadas por &
+ Número & Primeiro Nome & Sobrenome \\ % Colunas são separadas por &
\hline % uma linha horizontal
1 & Biggus & Dickus \\
2 & Monty & Python
\end{tabular}
+ % Vai ficar mais ou menos assim:
+ % Número | Primeiro Nome Sobrenome
+ % -------|--------------------------- % por causa do \hline
+ % 1 | Biggus Dickus
+ % 2 | Monty Python
\end{table}
-\section{Fazendo o \LaTeX \hspace{1pt} não compilar algo (o código fonte)}
+\section{Fazendo o \LaTeX{} não compilar algo (o código fonte)}
Digamos que precisamos incluir algum código dentro do nosso
-documento \LaTeX \hspace{1pt}, para isso precisamos com o \LaTeX \hspace{1pt}
+documento \LaTeX{}, para isso precisamos com o \LaTeX{}
não tente interpretar esse texto e que apenas inclua ele no documento. Fazemos
isso com o bloco verbatim.
% Existem outros pacotes (por exemplo, minty, lstlisting, etc.)
% mas verbatim é o básico
\begin{verbatim}
- print("Hello World!")
+ print("Olá mundo!")
a%b; % olha só! Podemos usar os sinais % no bloco verbatim.
- random = 4; #decided by fair random dice roll
+ random = 4; #decidido por um lançamento honesto de dado
+ Veja https://www.explainxkcd.com/wiki/index.php/221:_Random_Number
\end{verbatim}
\section{Compilando}
Imagino que agora você esteja pensando como compilar esse fantástico documento
-e visualizar a gloriosa glória que é um pdf gerado por \LaTeX \hspace{1pt} pdf.
+e visualizar a gloriosa glória que é um pdf gerado por \LaTeX{} pdf.
(sim, esse documento é compilável). \\
-Finalizando o documento usando \LaTeX \hspace{1pt} consiste nos seguintes passos:
+Finalizando o documento usando \LaTeX{} consiste nos seguintes passos:
\begin{enumerate}
\item Escrever o documento em texto puro (o ``código fonte'').
\item Compilar o código fonte para gerar um pdf.
@@ -240,7 +255,7 @@ Finalizando o documento usando \LaTeX \hspace{1pt} consiste nos seguintes passos
\end{verbatim}
\end{enumerate}
-Existem editores de \LaTeX \hspace{1pt} que combinam os passos 1 e 2 no mesmo
+Existem editores de \LaTeX{} que combinam os passos 1 e 2 no mesmo
sistema de software. Assim, você pode ver o passo 1, mas não o passo 2 por
completo. Passo 2 estará acontecendo escondido\footnote{Por exemplo, quando usar
referências (como Equação~\ref{eq:pythagoras}), pode ser necessário executar o
@@ -267,6 +282,27 @@ Existem dois tipos principais de links: URL visíveis \\
Esse pacote também produz uma lista de thumbnails no documento pdf gerado e
ativa os links na tabela de conteúdo.
+\section{Escrevendo em ASCII ou outras codificações}
+
+Por padrão, historicamente LaTeX aceita entradas que são puro ASCII (128),
+mas não ASCII extendido, o que significa sem acentos (à, è etc.) e símbolos não latinos.
+
+É fácil inserir acentos e símbolos latinos básicos através de atalhos de barra invertida
+como \,c, \'e, \`A, \ae e \oe etc. % Para ç, é, À, etc
+% Veja https://en.wikibooks.org/wiki/LaTeX/Special_Characters#Escaped_codes para mais detalhes
+
+Para escrever diretamente em UTF-8 quando compilando com pdflatex, use
+\begin{verbatim}
+ \usepackage[utf8]{inputenc}
+\end{verbatim}
+A fonte selecionada precisa suportar os glifos usados em seu documento. Você precisa adicionar
+\begin{verbatim}
+ \usepackage[T1]{fontenc}
+\end{verbatim}
+
+Desde LuaTeX e XeLaTeX, suporte para UTF-8 vem embutido por padrão, tornando a vida muito
+mais fácil para escrever em alfabetos não latinos.
+
\section{End}
Por enquanto é isso!
@@ -276,7 +312,7 @@ Por enquanto é isso!
\begin{thebibliography}{1}
% como em outras listas, o comando \bibitem pode ser usado para itens da lista
% cada entrada pode ser citada diretamente no corpo do texto
- \bibitem{latexwiki} The amazing \LaTeX \hspace{1pt} wikibook: {\em
+ \bibitem{latexwiki} The amazing \LaTeX{} wikibook: {\em
https://en.wikibooks.org/wiki/LaTeX}
\bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com}
\end{thebibliography}
@@ -289,3 +325,6 @@ https://en.wikibooks.org/wiki/LaTeX}
* The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX)
* An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
+* A quick guide for learning LaTeX: [Learn LaTeX in 30 minutes](https://www.overleaf.com/learn/latex/Learn_LaTeX_in_30_minutes)
+* An interactive platform to learn LaTeX (installationfree) [learnlatex.org/](https://www.learnlatex.org/)
+* Stack Exchange's question and answer site about TeX, LaTeX, ConTeXt, etc. [tex.stackexchange.com](https://tex.stackexchange.com/)
diff --git a/pt-br/lua-pt.html.markdown b/pt-br/lua-pt.html.markdown
index 0c75da26..4aaf3a1e 100644
--- a/pt-br/lua-pt.html.markdown
+++ b/pt-br/lua-pt.html.markdown
@@ -2,7 +2,7 @@
language: Lua
contributors:
- ["Tyler Neylon", "http://tylerneylon.com/"]
-filename: learnlua.lua
+filename: learnlua-pt.lua
translators:
- ["Iaan Mesquita", "https://github.com/ianitow"]
lang: pt-br
diff --git a/pt-br/make-pt.html.markdown b/pt-br/make-pt.html.markdown
index cbdebde7..40ac733a 100644
--- a/pt-br/make-pt.html.markdown
+++ b/pt-br/make-pt.html.markdown
@@ -4,7 +4,9 @@ tool: make
contributors:
- ["Robert Steed", "https://github.com/robochat"]
- ["Stephan Fuhrmann", "https://github.com/sfuhrm"]
-filename: Makefile
+translators:
+ - ["Rogério Gomes Rio", "https://github.com/rogerlista"]
+filename: Makefile-pt
lang: pt-br
---
diff --git a/pt-br/php-pt.html.markdown b/pt-br/php-pt.html.markdown
index e55f1100..7db6a671 100644
--- a/pt-br/php-pt.html.markdown
+++ b/pt-br/php-pt.html.markdown
@@ -7,7 +7,7 @@ translators:
- ["Abdala Cerqueira", "http://abda.la"]
- ["Raquel Diniz", "http://twitter.com/raquelrdiniz"]
lang: pt-br
-filename: php-pt.html.markdown
+filename: learnphp-pt.php
---
Este documento descreve PHP 5+.
diff --git a/pt-br/pythonstatcomp-pt.html.markdown b/pt-br/pythonstatcomp-pt.html.markdown
new file mode 100644
index 00000000..aa532eb4
--- /dev/null
+++ b/pt-br/pythonstatcomp-pt.html.markdown
@@ -0,0 +1,249 @@
+---
+category: tool
+tool: Statistical Computing with Python
+contributors:
+ - ["e99n09", "https://github.com/e99n09"]
+translators:
+ - ["waltercjunior", "https://github.com/waltercjunior"]
+filename: pythonstatcomp-pt.py
+lang: pt-br
+---
+
+Este é um tutorial sobre como fazer algumas tarefas típicas de programação estatística usando Python.
+É destinado basicamente à pessoas familizarizadas com Python e experientes com programação estatística em linguagens como R,
+Stata, SAS, SPSS ou MATLAB.
+
+```python
+
+
+
+# 0. Preparando-se ====
+
+""" Para começar, instale o seguinte : jupyther, numpy, scipy, pandas,
+ matplotlib, seaborn, requests.
+ Certifique-se de executar este tutorial utilizando o Jupyther notebook para
+ que você utilize os gráficos embarcados e ter uma fácil consulta à
+ documentação.
+ O comando para abrir é simplesmente '`jupyter notebook`, quando abrir então
+ clique em 'New -> Python'.
+"""
+
+# 1. Aquisição de dados ====
+
+""" A única razão das pessoas optarem por Python no lugar de R é que pretendem
+ interagir com o ambiente web, copiando páginas diretamente ou solicitando
+ dados utilizando uma API. Você pode fazer estas coisas em R, mas no
+ contexto de um projeto já usando Python, há uma vantagem em se ater uma
+ linguágem única.
+"""
+
+import requests # para requisições HTTP (web scraping, APIs)
+import os
+
+# web scraping
+r = requests.get("https://github.com/adambard/learnxinyminutes-docs")
+r.status_code # se retornou código 200, a requisição foi bem sucedida
+r.text # código fonte bruto da página
+print(r.text) # formatado bonitinho
+# salve a o código fonte d apágina em um arquivo:
+os.getcwd() # verifique qual é o diretório de trabalho
+with open("learnxinyminutes.html", "wb") as f:
+ f.write(r.text.encode("UTF-8"))
+
+# Baixar um arquivo csv
+fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/"
+fn = "pets.csv"
+r = requests.get(fp + fn)
+print(r.text)
+with open(fn, "wb") as f:
+ f.write(r.text.encode("UTF-8"))
+
+""" para mais informações sobre o módulo de solicitações, incluindo API's, veja em
+ http://docs.python-requests.org/en/latest/user/quickstart/
+"""
+
+# 2. Lendo um arquivo formato CSV ====
+
+""" Um pacote de pandas da Wes McKinney lhe dá um objeto 'DataFrame' em Python.
+ Se você já usou R, já deve estar familiarizado com a ideia de "data.frame".
+"""
+
+import pandas as pd
+import numpy as np
+import scipy as sp
+pets = pd.read_csv(fn)
+pets
+# name age weight species
+# 0 fluffy 3 14 cat
+# 1 vesuvius 6 23 fish
+# 2 rex 5 34 dog
+
+""" Usuários R: observe que o Python, como a maioria das linguagens de programação
+ influenciada pelo C, a indexação começa de 0. Em R, começa a indexar em 1
+ devido à influência do Fortran.
+"""
+
+# duas maneiras diferentes de imprimir uma coluna
+pets.age
+pets["age"]
+
+pets.head(2) # imprima as 2 primeiras linhas
+pets.tail(1) # imprima a última linha
+
+pets.name[1] # 'vesuvius'
+pets.species[0] # 'cat'
+pets["weight"][2] # 34
+
+# Em R, você esperaria obter 3 linhas fazendo isso, mas aqui você obtem 2:
+pets.age[0:2]
+# 0 3
+# 1 6
+
+sum(pets.age) * 2 # 28
+max(pets.weight) - min(pets.weight) # 20
+
+""" Se você está fazendo alguma álgebra linear séria e processamento de
+ números você pode desejar apenas arrays, não DataFrames. DataFrames são
+ ideais para combinar colunas de diferentes tipos de dados.
+"""
+
+# 3. Gráficos ====
+
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+%matplotlib inline
+
+# Para fazer a visualiação de dados em Python, use matplotlib
+
+plt.hist(pets.age);
+
+plt.boxplot(pets.weight);
+
+plt.scatter(pets.age, pets.weight)
+plt.xlabel("age")
+plt.ylabel("weight");
+
+# seaborn utiliza a biblioteca do matplotlib e torna os enredos mais bonitos
+
+import seaborn as sns
+
+plt.scatter(pets.age, pets.weight)
+plt.xlabel("age")
+plt.ylabel("weight");
+
+# também existem algumas funções de plotagem específicas do seaborn
+# observe como o seaborn automaticamenteo o eixto x neste gráfico de barras
+sns.barplot(pets["age"])
+
+# Veteranos em R ainda podem usar o ggplot
+from ggplot import *
+ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets")
+# fonte: https://pypi.python.org/pypi/ggplot
+
+# há até um d3.js veja em: https://github.com/mikedewar/d3py
+
+# 4. Limpeza de dados simples e análise exploratória ====
+
+""" Aqui está um exemplo mais complicado que demonstra dados básicos
+ fluxo de trabalho de limpeza levando à criação de algumas parcelas
+ e a execução de uma regressão linear.
+ O conjunto de dados foi transcrito da Wikipedia à mão. Contém
+ todos os sagrados imperadores romanos e os marcos importantes em suas vidas
+ (birth, death, coronation, etc.).
+ O objetivo da análise será explorar se um relacionamento existe
+ entre o ano de nascimento (birth year) e a expectativa de vida (lifespam)
+ do imperador.
+ Fonte de dados: https://en.wikipedia.org/wiki/Holy_Roman_Emperor
+"""
+
+# carregue alguns dados dos sagrados imperadores romanos
+url = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/hre.csv"
+r = requests.get(url)
+fp = "hre.csv"
+with open(fp, "wb") as f:
+ f.write(r.text.encode("UTF-8"))
+
+hre = pd.read_csv(fp)
+
+hre.head()
+"""
+ Ix Dynasty Name Birth Death
+0 NaN Carolingian Charles I 2 April 742 28 January 814
+1 NaN Carolingian Louis I 778 20 June 840
+2 NaN Carolingian Lothair I 795 29 September 855
+3 NaN Carolingian Louis II 825 12 August 875
+4 NaN Carolingian Charles II 13 June 823 6 October 877
+
+ Coronation 1 Coronation 2 Ceased to be Emperor
+0 25 December 800 NaN 28 January 814
+1 11 September 813 5 October 816 20 June 840
+2 5 April 823 NaN 29 September 855
+3 Easter 850 18 May 872 12 August 875
+4 29 December 875 NaN 6 October 877
+"""
+
+# limpar as colunas Birth e Death
+
+import re # módulo para expressões regulares
+
+rx = re.compile(r'\d+$') # conincidir com os códigos finais
+
+""" Esta função aplia a expressão reguar a uma coluna de entrada (here Birth,
+ Death), nivela a lista resultante, converte-a em uma lista de objetos, e
+ finalmente converte o tipo do objeto da lista de String para inteiro. para
+ mais informações sobre o que as diferentes partes do código fazer, veja em:
+ - https://docs.python.org/2/howto/regex.html
+ - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list
+ - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html
+"""
+
+from functools import reduce
+
+def extractYear(v):
+ return(pd.Series(reduce(lambda x, y: x + y, map(rx.findall, v), [])).astype(int))
+
+hre["BirthY"] = extractYear(hre.Birth)
+hre["DeathY"] = extractYear(hre.Death)
+
+# faça uma coluna infomrnado a idade estimada ("EstAge")
+hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int)
+
+# gráfico de dispersão simples, sem linha de tendência, cor representa dinastia
+sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False)
+
+# use o scipy para executar uma regrassão linear
+from scipy import stats
+(slope, intercept, rval, pval, stderr) = stats.linregress(hre.BirthY, hre.EstAge)
+# código fonte: http://wiki.scipy.org/Cookbook/LinearRegression
+
+# varifique o declive (slope)
+slope # 0.0057672618839073328
+
+# varifique o valor R^2:
+rval**2 # 0.020363950027333586
+
+# varifique o valor p-value
+pval # 0.34971812581498452
+
+# use o seaborn para fazer um gráfico de dispersão e traçar a linha de tendência de regrassão linear
+sns.lmplot("BirthY", "EstAge", data=hre)
+
+""" Para mais informações sobre o seaborn, veja
+ - http://web.stanford.edu/~mwaskom/software/seaborn/
+ - https://github.com/mwaskom/seaborn
+ Para mais informações sobre o SciPy, veja
+ - http://wiki.scipy.org/SciPy
+ - http://wiki.scipy.org/Cookbook/
+ Para ver uma versão da análise dos sagrados imperadores romanos usando R, consulte
+ - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R
+"""
+
+```
+
+Se você quiser saber mais, obtenha o Python para análise de dados de Wes McKinney. É um excelente recurso e usei-o como referência ao escrever este tutorial.
+
+Você também pode encontrar muitos tutoriais interativos de IPython sobre assuntos específicos de seus interesses, como Cam Davidson-Pilon's <a href="http://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/" Title="Programação Probabilística e Métodos Bayesianos para Hackers">Programação Probabilística e Métodos Bayesianos para Hackers</a>.
+
+Mais alguns módulos para pesquisar:
+ - análise de texto e processamento de linguagem natural: nltk, http://www.nltk.org
+ - análise de rede social: igraph, http://igraph.org/python/
diff --git a/pt-br/r-pt.html.markdown b/pt-br/r-pt.html.markdown
new file mode 100644
index 00000000..5c9304ec
--- /dev/null
+++ b/pt-br/r-pt.html.markdown
@@ -0,0 +1,786 @@
+---
+language: R
+contributors:
+ - ["e99n09", "http://github.com/e99n09"]
+ - ["isomorphismes", "http://twitter.com/isomorphisms"]
+ - ["kalinn", "http://github.com/kalinn"]
+translators:
+ - ["Marcel Ribeiro-Dantas", "http://github.com/mribeirodantas"]
+lang: pt-br
+filename: learnr-pt.r
+---
+
+R é uma linguagem de programação estatística. Ela tem muitas bibliotecas para carregar e limpar conjuntos de dados, executar análises estatísticas e produzir gráficos. Você também pode executar comandos do `R` dentro de um documento LaTeX.
+
+```r
+
+# Comentários começam com o símbolo de Cerquilha, também conhecido como
+# jogo da velha
+
+# Não existe um símbolo especial para comentários em várias linhas
+# mas você pode escrever várias linhas de comentários adicionando a
+# cerquilha (#) ao início de cada uma delas.
+
+# No Windows e Linux, você pode usar CTRL-ENTER para executar uma linha.
+# No MacOS, o equivalente é COMMAND-ENTER
+
+
+
+#############################################################################
+# Coisas que você pode fazer sem entender nada sobre programação
+#############################################################################
+
+# Nesta seção, mostramos algumas das coisas legais que você pode fazer em
+# R sem entender nada de programação. Não se preocupe em entender tudo o
+# que o código faz. Apenas aproveite!
+
+data() # navegue pelos conjuntos de dados pré-carregados
+data(rivers) # carregue este: "Comprimentos dos principais rios norte-americanos"
+ls() # observe que "rivers" apareceu na área de trabalho (workspace)
+head(rivers) # dê uma espiada no conjunto de dados
+# 735 320 325 392 524 450
+
+length(rivers) # quantos rios foram medidos?
+# 141
+summary(rivers) # consulte um sumário de estatísticas básicas
+# Min. 1st Qu. Median Mean 3rd Qu. Max.
+# 135.0 310.0 425.0 591.2 680.0 3710.0
+
+# faça um diagrama de ramos e folhas (uma visualização de dados semelhante a um histograma)
+stem(rivers)
+
+# A vírgula está 2 dígito(s) à direita do símbolo |
+#
+# 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)) # Observe que os dados não são normais nem log-normais!
+# Tome isso, fundamentalistas da curva normal!
+
+# O ponto decimal está 1 dígito(s) à esquerda do símbolo |
+#
+# 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
+
+# faça um histograma:
+hist(rivers, col="#333333", border="white", breaks=25) # brinque com estes parâmetros
+hist(log(rivers), col="#333333", border="white", breaks=25) # você fará mais gráficos mais tarde
+
+# Aqui está outro conjunto de dados que vem pré-carregado. O R tem toneladas deles.
+data(discoveries)
+plot(discoveries, col="#333333", lwd=3, xlab="Ano",
+ main="Número de descobertas importantes por ano")
+plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Ano",
+ main="Número de descobertas importantes por ano")
+
+# Em vez de deixar a ordenação padrão (por ano),
+# também podemos ordenar para ver o que é mais comum:
+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)
+#
+# O ponto decimal está no símbolo |
+#
+# 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
+
+# Role um dado algumas vezes
+round(runif(7, min=.5, max=6.5))
+# 1 4 6 1 4 6 4
+# Seus números serão diferentes dos meus, a menos que definamos a mesma semente aleatória com o set.seed
+
+# Obtenha 9 números de forma aleatória a partir de uma distribuição normal
+rnorm(9)
+# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271
+# [7] -0.59975593 0.57629164 1.08455362
+
+
+
+##################################################
+# Tipos de dados e aritmética básica
+##################################################
+
+# Agora para a parte orientada a programação do tutorial.
+# Nesta seção você conhecerá os tipos de dados importantes do R:
+# integers, numerics, characters, logicals, e factors.
+# Existem outros, mas estes são o mínimo que você precisa para
+# iniciar.
+
+# INTEGERS
+# Os inteiros de armazenamento longo são escritos com L
+5L # 5
+class(5L) # "integer"
+# (Experimente ?class para obter mais informações sobre a função class().)
+# Em R, todo e qualquer valor, como 5L, é considerado um vetor de comprimento 1
+length(5L) # 1
+# Você pode ter um vetor inteiro com comprimento > 1 também:
+c(4L, 5L, 8L, 3L) # 4 5 8 3
+length(c(4L, 5L, 8L, 3L)) # 4
+class(c(4L, 5L, 8L, 3L)) # "integer"
+
+# NUMERICS
+# Um "numeric" é um número de ponto flutuante de precisão dupla
+5 # 5
+class(5) # "numeric"
+# De novo, tudo em R é um vetor;
+# você pode fazer um vetor numérico com mais de um elemento
+c(3,3,3,2,2,1) # 3 3 3 2 2 1
+# Você também pode usar a notação científica
+5e4 # 50000
+6.02e23 # Número de Avogadro
+1.6e-35 # Comprimento de Planck
+# Você também pode ter números infinitamente grandes ou pequenos
+class(Inf) # "numeric"
+class(-Inf) # "numeric"
+# Você pode usar "Inf", por exemplo, em integrate(dnorm, 3, Inf)
+# isso evita as tabelas de escores-Z.
+
+# ARITMÉTICA BÁSICA
+# Você pode fazer aritmética com números
+# Fazer aritmética com uma mistura de números inteiros (integers) e com
+# ponto flutuante (numeric) resulta em um numeric
+10L + 66L # 76 # integer mais integer resulta em integer
+53.2 - 4 # 49.2 # numeric menos numeric resulta em numeric
+2.0 * 2L # 4 # numeric vezes integer resulta em numeric
+3L / 4 # 0.75 # integer dividido por numeric resulta em numeric
+3 %% 2 # 1 # o resto de dois numeric é um outro numeric
+# Aritmética ilegal produz um "não-é-um-número" (do inglês Not-a-Number):
+0 / 0 # NaN
+class(NaN) # "numeric"
+# Você pode fazer aritmética em dois vetores com comprimento maior que 1,
+# desde que o comprimento do vetor maior seja um múltiplo inteiro do menor
+c(1,2,3) + c(1,2,3) # 2 4 6
+# Como um único número é um vetor de comprimento um, escalares são aplicados
+# elemento a elemento com relação a vetores
+(4 * c(1,2,3) - 2) / 2 # 1 3 5
+# Exceto para escalares, tenha cuidado ao realizar aritmética em vetores com
+# comprimentos diferentes. Embora possa ser feito,
+c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6
+# ter comprimentos iguais é uma prática melhor e mais fácil de ler
+c(1,2,3,1,2,3) * c(1,2,1,2,1,2)
+
+# CHARACTERS
+# Não há diferença entre strings e caracteres em R
+"Horatio" # "Horatio"
+class("Horatio") # "character"
+class('H') # "character"
+# São ambos vetores de caracteres de comprimento 1
+# Aqui está um mais longo:
+c('alef', 'bet', 'gimmel', 'dalet', 'he')
+# "alef" "bet" "gimmel" "dalet" "he"
+length(c("Call","me","Ishmael")) # 3
+# Você pode utilizar expressões regulares (regex) em vetores de caracteres:
+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 tem vários vetores de caracteres embutidos:
+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"
+
+# LOGICALS
+# Em R, um "logical" é um booleano
+class(TRUE) # "logical"
+class(FALSE) # "logical"
+# O comportamento deles é normal
+TRUE == TRUE # TRUE
+TRUE == FALSE # FALSE
+FALSE != FALSE # FALSE
+FALSE != TRUE # TRUE
+# Dados ausentes (NA) são logical, também
+class(NA) # "logical"
+# Use | e & para operações lógicas.
+# OR
+TRUE | FALSE # TRUE
+# AND
+TRUE & FALSE # FALSE
+# Aplicar | e & a vetores retorna operações lógicas elemento a elemento
+c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE
+c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE
+# Você pode testar se x é TRUE
+isTRUE(TRUE) # TRUE
+# Aqui obtemos um vetor logical com muitos elementos:
+c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE
+c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE
+
+# FACTORS
+# A classe factor é para dados categóricos
+# Os fatores podem ser ordenados (como as avaliações de crianças) ou
+# não ordenados (como as cores)
+factor(c("azul", "azul", "verde", NA, "azul"))
+# azul azul verde <NA> azul
+# Levels: azul verde
+# Os "levels" são os valores que os dados categóricos podem assumir
+# Observe que os dados ausentes não entram nos levels
+levels(factor(c("verde", "verde", "azul", NA, "azul"))) # "azul" "verde"
+# Se um vetor de factor tem comprimento 1, seus levels também terão comprimento 1
+length(factor("green")) # 1
+length(levels(factor("green"))) # 1
+# Os fatores são comumente vistos em data frames, uma estrutura de dados que abordaremos
+# mais tarde
+data(infert) # "Infertilidade após aborto espontâneo e induzido"
+levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs"
+
+# NULL
+# "NULL" é um valor estranho; use-o para "apagar" um vetor
+class(NULL) # NULL
+parakeet = c("bico", "penas", "asas", "olhos")
+parakeet
+# [1] "bico" "penas" "asas" "olhos"
+parakeet <- NULL
+parakeet
+# NULL
+
+# COERÇÃO DE TIPO
+# Coerção de tipo é quando você força um valor a assumir um tipo diferente
+as.character(c(6, 8)) # "6" "8"
+as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE
+# Se você colocar elementos de diferentes tipos em um vetor, coerções estranhas acontecem:
+c(TRUE, 4) # 1 4
+c("cachorro", TRUE, 4) # "cachorro" "TRUE" "4"
+as.numeric("Bilbo")
+# [1] NA
+# Warning message:
+# NAs introduced by coercion
+
+# Observe também: esses são apenas os tipos de dados básicos
+# Existem muitos outros tipos de dados, como datas, séries temporais, etc.
+
+
+
+##################################################
+# Variáveis, laços, expressões condicionais
+##################################################
+
+# Uma variável é como uma caixa na qual você armazena um valor para uso posterior.
+# Chamamos isso de "atribuir" o valor à variável.
+# Ter variáveis nos permite escrever laços, funções e instruções com condição
+
+# VARIÁVEIS
+# Existem muitas maneiras de atribuir valores:
+x = 5 # é possível fazer assim
+y <- "1" # mas é preferível fazer assim
+TRUE -> z # isso funciona, mas é estranho
+
+# LAÇOS
+# Nós temos laços com for
+for (i in 1:4) {
+ print(i)
+}
+# [1] 1
+# [1] 2
+# [1] 3
+# [1] 4
+# Nós temos laços com while
+a <- 10
+while (a > 4) {
+ cat(a, "...", sep = "")
+ a <- a - 1
+}
+# 10...9...8...7...6...5...
+# Tenha em mente que os laços for e while são executados lentamente em R
+# Operações em vetores inteiros (por exemplo, uma linha inteira, uma coluna inteira)
+# ou funções do tipo apply() (discutiremos mais tarde) são mais indicadas
+
+# IF/ELSE
+# Novamente, bastante padrão
+if (4 > 3) {
+ print("4 é maior que 3")
+} else {
+ print("4 não é maior que 3")
+}
+# [1] "4 é maior que 3"
+
+# FUNÇÕES
+# Definidas assim:
+jiggle <- function(x) {
+ x = x + rnorm(1, sd=.1) # adicione um pouco de ruído (controlado)
+ return(x)
+}
+# Chamada como qualquer outra função R:
+jiggle(5) # 5±ε. Após set.seed(2716057), jiggle(5)==5.005043
+
+
+
+###########################################################################
+# Estruturas de dados: Vetores, matrizes, data frames e arranjos (arrays)
+###########################################################################
+
+# UNIDIMENSIONAL
+
+# Vamos começar do início, e com algo que você já sabe: vetores.
+vec <- c(8, 9, 10, 11)
+vec # 8 9 10 11
+# Consultamos elementos específicos utilizando colchetes
+# (Observe que R começa a contar a 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
+# Também podemos pesquisar os índices de componentes específicos,
+which(vec %% 2 == 0) # 1 3
+# pegue apenas as primeiras ou últimas entradas no vetor,
+head(vec, 1) # 8
+tail(vec, 2) # 10 11
+# ou descubra se um determinado valor está no vetor
+any(vec == 10) # TRUE
+# Se um índice for além do comprimento de um vetor, você obterá NA:
+vec[6] # NA
+# Você pode encontrar o comprimento do seu vetor com length()
+length(vec) # 4
+# Você pode realizar operações em vetores inteiros ou subconjuntos de vetores
+vec * 4 # 32 36 40 44
+vec[2:3] * 5 # 45 50
+any(vec[2:3] == 8) # FALSE
+# e R tem muitas funções internas para sumarizar vetores
+mean(vec) # 9.5
+var(vec) # 1.666667
+sd(vec) # 1.290994
+max(vec) # 11
+min(vec) # 8
+sum(vec) # 38
+# Mais alguns recursos embutidos:
+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
+
+# BIDIMENSIONAL (ELEMENTOS DA MESMA CLASSE)
+
+# Você pode fazer uma matriz com entradas do mesmo tipo assim:
+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
+# Ao contrário de um vetor, a classe de uma matriz é "matrix" independente do que ela contém
+class(mat) # "matrix"
+# Consulte a primeira linha
+mat[1,] # 1 4
+# Execute uma operação na primeira coluna
+3 * mat[,1] # 3 6 9
+# Consulte uma célula específica
+mat[3,2] # 6
+
+# Transponha toda a matriz
+t(mat)
+# [,1] [,2] [,3]
+# [1,] 1 2 3
+# [2,] 4 5 6
+
+# Multiplicação de matrizes
+mat %*% t(mat)
+# [,1] [,2] [,3]
+# [1,] 17 22 27
+# [2,] 22 29 36
+# [3,] 27 36 45
+
+# cbind() une vetores em colunas para formar uma matriz
+mat2 <- cbind(1:4, c("cachorro", "gato", "passaro", "cachorro"))
+mat2
+# [,1] [,2]
+# [1,] "1" "cachorro"
+# [2,] "2" "gato"
+# [3,] "3" "passaro"
+# [4,] "4" "cachorro"
+class(mat2) # matrix
+# Mais uma vez, observe o que aconteceu!
+# Como as matrizes devem conter todas as entradas da mesma classe,
+# tudo foi convertido para a classe character
+c(class(mat2[,1]), class(mat2[,2]))
+
+# rbind() une vetores linha a linha para fazer uma matriz
+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, tudo da mesma classe. Sem coerções. Muito melhor.
+
+# BIDIMENSIONAL (CLASSES DIFERENTES)
+
+# Para colunas de tipos diferentes, use um data frame
+# Esta estrutura de dados é tão útil para programação estatística,
+# que uma versão dela foi adicionada ao Python através do pacote "pandas".
+
+estudantes <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"),
+ c(3,2,2,1,0,-1),
+ c("H", "G", "G", "R", "S", "G"))
+names(estudantes) <- c("nome", "ano", "casa") # nomeie as colunas
+class(estudantes) # "data.frame"
+estudantes
+# nome ano casa
+# 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(estudantes$ano) # "numeric"
+class(estudantes[,3]) # "factor"
+# encontre as dimensões
+nrow(estudantes) # 6
+ncol(estudantes) # 3
+dim(estudantes) # 6 3
+# A função data.frame() converte vetores de caracteres em vetores de fator
+# por padrão; desligue isso definindo stringsAsFactors = FALSE quando
+# você criar um data frame
+?data.frame
+
+# Existem muitas maneiras particulares de consultar partes de um data frame,
+# todas sutilmente diferentes
+estudantes$ano # 3 2 2 1 0 -1
+estudantes[,2] # 3 2 2 1 0 -1
+estudantes[,"ano"] # 3 2 2 1 0 -1
+
+# Uma versão extendida da estrutura data.frame é a data.table
+# Se você estiver trabalhando com dados enormes ou em painel, ou precisar mesclar
+# alguns conjuntos de dados, data.table pode ser uma boa escolha. Aqui está um tour
+# relâmpago:
+install.packages("data.table") # baixe o pacote a partir do CRAN
+require(data.table) # carregue ele
+estudantes <- as.data.table(estudantes)
+estudantes # observe a saída ligeiramente diferente
+# nome ano casa
+# 1: Cedric 3 H
+# 2: Fred 2 G
+# 3: George 2 G
+# 4: Cho 1 R
+# 5: Draco 0 S
+# 6: Ginny -1 G
+estudantes[nome=="Ginny"] # Consulte estudantes com o nome == "Ginny"
+# nome ano casa
+# 1: Ginny -1 G
+estudantes[ano==2] # Consulte estudantes com o ano == 2
+# nome ano casa
+# 1: Fred 2 G
+# 2: George 2 G
+# data.table facilita a fusão de dois conjuntos de dados
+# vamos fazer outro data.table para mesclar com os alunos
+fundadores <- data.table(casa=c("G","H","R","S"),
+ fundador=c("Godric","Helga","Rowena","Salazar"))
+fundadores
+# casa fundador
+# 1: G Godric
+# 2: H Helga
+# 3: R Rowena
+# 4: S Salazar
+setkey(estudantes, casa)
+setkey(fundadores, casa)
+estudantes <- fundadores[estudantes] # mescle os dois conjuntos de dados com base na "casa"
+setnames(estudantes, c("casa","nomeFundadorCasa","nomeEstudante","ano"))
+estudantes[,order(c("nome","ano","casa","nomeFundadorCasa")), with=F]
+# nomeEstudante ano casa nomeFundadorCasa
+# 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
+
+# O data.table torna as tabelas de sumário fáceis
+estudantes[,sum(ano),by=casa]
+# casa V1
+# 1: G 3
+# 2: H 3
+# 3: R 1
+# 4: S 0
+
+# Para remover uma coluna de um data.frame ou data.table,
+# atribua a ela o valor NULL
+estudantes$nomeFundadorCasa <- NULL
+estudantes
+# nomeEstudante ano casa
+# 1: Fred 2 G
+# 2: George 2 G
+# 3: Ginny -1 G
+# 4: Cedric 3 H
+# 5: Cho 1 R
+# 6: Draco 0 S
+
+# Remova uma linha consultando parte dos dados
+# Usando data.table:
+estudantes[nomeEstudante != "Draco"]
+# casa estudanteNome ano
+# 1: G Fred 2
+# 2: G George 2
+# 3: G Ginny -1
+# 4: H Cedric 3
+# 5: R Cho 1
+# Usando data.frame:
+estudantes <- as.data.frame(estudantes)
+estudantes[estudantes$casa != "G",]
+# casa nomeFundadorCasa nomeEstudante ano
+# 4 H Helga Cedric 3
+# 5 R Rowena Cho 1
+# 6 S Salazar Draco 0
+
+# MULTIDIMENSIONAL (TODOS OS ELEMENTOS DE UM TIPO)
+
+# Arranjos (arrays) criam tabelas n-dimensionais
+# Todos os elementos devem ser do mesmo tipo
+# Você pode fazer uma tabela bidimensional (como uma matriz)
+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
+# Você pode usar array para fazer matrizes tridimensionais também
+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
+
+# LISTAS (MULTIDIMENSIONAIS, POSSIVELMENTE IMPERFEITAS, DE DIFERENTES TIPOS)
+
+# Finalmente, R tem listas (de vetores)
+lista1 <- list(tempo = 1:40)
+lista1$preco = c(rnorm(40,.5*lista1$tempo,4)) # aleatória
+lista1
+# Você pode obter itens na lista assim
+lista1$tempo # um modo
+lista1[["tempo"]] # um outro modo
+lista1[[1]] # e ainda um outro modo
+# [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
+# Você pode obter itens de uma lista como qualquer outro vetor
+lista1$preco[4]
+
+# Listas não são a estrutura de dados mais eficiente para se trabalhar em R;
+# a menos que você tenha um bom motivo, você deve se ater a data.frames
+# As listas geralmente são retornadas por funções que realizam regressões lineares
+
+##################################################
+# A família de funções apply()
+##################################################
+
+# Lembra de mat?
+mat
+# [,1] [,2]
+# [1,] 1 4
+# [2,] 2 5
+# [3,] 3 6
+# Use apply(X, MARGIN, FUN) para aplicar a função FUN a uma matriz X
+# sobre linhas (MARGIN = 1) ou colunas (MARGIN = 2)
+# Ou seja, R faz FUN para cada linha (ou coluna) de X, muito mais rápido que um
+# laço for ou while faria
+apply(mat, MAR = 2, jiggle)
+# [,1] [,2]
+# [1,] 3 15
+# [2,] 7 19
+# [3,] 11 23
+# Outras funções: ?lappy, ?sapply
+
+# Não as deixe te intimidar; todos concordam que essas funções são bem confusas
+
+# O pacote plyr visa substituir (e melhorar!) a família *apply().
+install.packages("plyr")
+require(plyr)
+?plyr
+
+
+
+#########################
+# Carregando dados
+#########################
+
+# "pets.csv" é um arquivo hospedado na internet
+# (mas também poderia tranquilamente ser um arquivo no seu computador)
+require(RCurl)
+pets <- read.csv(textConnection(getURL("https://learnxinyminutes.com/docs/pets.csv")))
+pets
+head(pets, 2) # primeiras duas linhas
+tail(pets, 1) # última linha
+
+# Para salvar um data frame ou matriz como um arquivo .csv:
+write.csv(pets, "pets2.csv") # para criar um novo arquivo .csv
+# Define o diretório de trabalho com setwd(), confirme em qual você está com getwd()
+
+# Experimente ?read.csv e ?write.csv para obter mais informações
+
+
+
+#########################
+# Análise estatística
+#########################
+
+# Regressão linear!
+modeloLinear <- lm(preco ~ tempo, data = lista1)
+modeloLinear # imprime na tela o resultado da regressão
+# Call:
+# lm(formula = preco ~ tempo, data = lista1)
+#
+# Coefficients:
+# (Intercept) tempo
+# 0.1453 0.4943
+summary(modeloLinear) # saída mais detalhada da regressão
+# Call:
+# lm(formula = preco ~ tempo, data = lista1)
+#
+# Residuals:
+# Min 1Q Median 3Q Max
+# -8.3134 -3.0131 -0.3606 2.8016 10.3992
+#
+# Coefficients:
+# Estimate Std. Error t value Pr(>|t|)
+# (Intercept) 0.14527 1.50084 0.097 0.923
+# tempo 0.49435 0.06379 7.749 2.44e-09 ***
+# ---
+# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
+#
+# Residual standard error: 4.657 on 38 degrees of freedom
+# Multiple R-squared: 0.6124, Adjusted R-squared: 0.6022
+# F-statistic: 60.05 on 1 and 38 DF, p-value: 2.44e-09
+coef(modeloLinear) # extrai os parâmetros estimados
+# (Intercept) tempo
+# 0.1452662 0.4943490
+summary(modeloLinear)$coefficients # um outro meio de extrair os resultados
+# Estimate Std. Error t value Pr(>|t|)
+# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01
+# tempo 0.4943490 0.06379348 7.74920901 2.440008e-09
+summary(modeloLinear)$coefficients[,4] # the p-values
+# (Intercept) tempo
+# 9.234021e-01 2.440008e-09
+
+# MODELOS LINEARES GERAIS
+# Regressão logística
+set.seed(1)
+lista1$sucesso = rbinom(length(lista1$tempo), 1, .5) # binário aleatório
+modeloLg <- glm(sucesso ~ tempo, data = lista1,
+ family=binomial(link="logit"))
+modeloLg # imprime na tela o resultado da regressão logística
+# Call: glm(formula = sucesso ~ tempo,
+# family = binomial(link = "logit"), data = lista1)
+#
+# Coefficients:
+# (Intercept) tempo
+# 0.17018 -0.01321
+#
+# Degrees of Freedom: 39 Total (i.e. Null); 38 Residual
+# Null Deviance: 55.35
+# Residual Deviance: 55.12 AIC: 59.12
+summary(modeloLg) # saída mais detalhada da regressão
+# Call:
+# glm(formula = sucesso ~ tempo,
+# family = binomial(link = "logit"), data = lista1)
+
+# Deviance Residuals:
+# Min 1Q Median 3Q Max
+# -1.245 -1.118 -1.035 1.202 1.327
+#
+# Coefficients:
+# Estimate Std. Error z value Pr(>|z|)
+# (Intercept) 0.17018 0.64621 0.263 0.792
+# tempo -0.01321 0.02757 -0.479 0.632
+#
+# (Dispersion parameter for binomial family taken to be 1)
+#
+# Null deviance: 55.352 on 39 degrees of freedom
+# Residual deviance: 55.121 on 38 degrees of freedom
+# AIC: 59.121
+#
+# Number of Fisher Scoring iterations: 3
+
+
+#########################
+# Gráficos
+#########################
+
+# FUNÇÕES DE PLOTAGEM INTEGRADAS
+# Gráficos de dispersão!
+plot(lista1$tempo, lista1$preco, main = "dados falsos")
+# Trace a linha de regressão em um gráfico existente!
+abline(modeloLinear, col = "red")
+# Obtenha uma variedade de diagnósticos legais
+plot(modeloLinear)
+# Histogramas!
+hist(rpois(n = 10000, lambda = 5), col = "thistle")
+# Gráficos de barras!
+barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow"))
+
+# GGPLOT2
+# Mas estes não são nem os mais bonitos dos gráficos no R
+# Experimente o pacote ggplot2 para gráficos diferentes e mais bonitos
+install.packages("ggplot2")
+require(ggplot2)
+?ggplot2
+pp <- ggplot(estudantes, aes(x=casa))
+pp + geom_bar()
+ll <- as.data.table(lista1)
+pp <- ggplot(ll, aes(x=tempo,preco))
+pp + geom_point()
+# ggplot2 tem uma excelente documentação (disponível em http://docs.ggplot2.org/current/)
+
+
+
+```
+
+## Como faço para obter R?
+
+* Obtenha o R e uma interface gráfica para o R em [http://www.r-project.org/](http://www.r-project.org/)
+* [RStudio](http://www.rstudio.com/ide/) é uma outra interface gráfica
diff --git a/pt-br/rust-pt.html.markdown b/pt-br/rust-pt.html.markdown
index 3dd4a8d5..1080baa4 100644
--- a/pt-br/rust-pt.html.markdown
+++ b/pt-br/rust-pt.html.markdown
@@ -1,5 +1,5 @@
---
-language: rust
+language: Rust
filename: rust-pt.rs
contributors:
- ["Paulo Henrique Rodrigues Pinheiro", "https://about.me/paulohrpinheiro"]
diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown
index 21e9b4bb..732a36ad 100644
--- a/pt-br/yaml-pt.html.markdown
+++ b/pt-br/yaml-pt.html.markdown
@@ -2,6 +2,7 @@
language: yaml
contributors:
- ["Leigh Brenecki", "https://github.com/adambrenecki"]
+ - [Suhas SG, 'https://github.com/jargnar']
translators:
- ["Rodrigo Russo", "https://github.com/rodrigozrusso"]
filename: learnyaml-pt.yaml
@@ -14,6 +15,8 @@ legível por seres humanos.
É um superconjunto de JSON, com a adição de identação e quebras de linhas sintaticamente significativas, como Python. Ao contrário de Python, entretanto, YAML não permite o caracter literal tab para identação.
```yaml
+--- # início do documento
+
# Comentários em YAML são como este.
###################
@@ -30,28 +33,32 @@ boleano: true
valor_nulo: null
chave com espaco: valor
# Observe que strings não precisam de aspas. Porém, elas podem ter.
-porem: "Uma string, entre aspas."
-"Chaves podem estar entre aspas tambem.": "É útil se você quiser colocar um ':' na sua chave."
+porem: 'Uma string, entre aspas.'
+'Chaves podem estar entre aspas tambem.': "É útil se você quiser colocar um ':' na sua chave."
+aspas simples: 'possuem ''um'' padrão de escape'
+aspas duplas: "possuem vários: \", \0, \t, \u263A, \x0d\x0a == \r\n, e mais."
+# Caracteres UTF-8/16/32 precisam ser codificados
+Superscript dois: \u00B2
# Seqüências de várias linhas podem ser escritas como um 'bloco literal' (utilizando |),
# ou em um 'bloco compacto' (utilizando '>').
bloco_literal: |
- Todo esse bloco de texto será o valor da chave 'bloco_literal',
- preservando a quebra de com linhas.
+ Todo esse bloco de texto será o valor da chave 'bloco_literal',
+ preservando a quebra de com linhas.
- O literal continua até de-dented, e a primeira identação é
- removida.
+ O literal continua até 'des-indentar', e a primeira identação é
+ removida.
- Quaisquer linhas que são 'mais identadas' mantém o resto de suas identações -
- estas linhas serão identadas com 4 espaços.
+ Quaisquer linhas que são 'mais identadas' mantém o resto de suas identações -
+ estas linhas serão identadas com 4 espaços.
estilo_compacto: >
- Todo esse bloco de texto será o valor de 'estilo_compacto', mas esta
- vez, todas as novas linhas serão substituídas com espaço simples.
+ Todo esse bloco de texto será o valor de 'estilo_compacto', mas esta
+ vez, todas as novas linhas serão substituídas com espaço simples.
- Linhas em branco, como acima, são convertidas em um carater de nova linha.
+ Linhas em branco, como acima, são convertidas em um carater de nova linha.
- Linhas 'mais-indentadas' mantém suas novas linhas também -
- este texto irá aparecer em duas linhas.
+ Linhas 'mais-indentadas' mantém suas novas linhas também -
+ este texto irá aparecer em duas linhas.
####################
# TIPOS DE COLEÇÃO #
@@ -59,54 +66,84 @@ estilo_compacto: >
# Texto aninhado é conseguido através de identação.
um_mapa_aninhado:
- chave: valor
- outra_chave: Outro valor
- outro_mapa_aninhado:
- ola: ola
+ chave: valor
+ outra_chave: Outro valor
+ outro_mapa_aninhado:
+ ola: ola
# Mapas não tem que ter chaves com string.
0.25: uma chave com valor flutuante
# As chaves podem ser também objetos multi linhas, utilizando ? para indicar o começo de uma chave.
? |
- Esta é uma chave
- que tem várias linhas
+ Esta é uma chave
+ que tem várias linhas
: e este é o seu valor
-# também permite tipos de coleção de chaves, mas muitas linguagens de programação
-# vão reclamar.
+# YAML também permite o mapeamento entre sequências com a sintaxe chave complexa
+# Alguns analisadores de linguagem de programação podem reclamar
+# Um exemplo
+? - Manchester United
+ - Real Madrid
+: [2001-01-01, 2002-02-02]
# Sequências (equivalente a listas ou arrays) semelhante a isso:
uma_sequencia:
- - Item 1
- - Item 2
- - 0.5 # sequencias podem conter tipos diferentes.
- - Item 4
- - chave: valor
- outra_chave: outro_valor
- -
- - Esta é uma sequencia
- - dentro de outra sequencia
+ - Item 1
+ - Item 2
+ - 0.5 # sequencias podem conter tipos diferentes.
+ - Item 4
+ - chave: valor
+ outra_chave: outro_valor
+ -
+ - Esta é uma sequencia
+ - dentro de outra sequencia
+ - - - Indicadores de sequência aninhadas
+ - podem ser recolhidas
# Como YAML é um super conjunto de JSON, você também pode escrever mapas JSON de estilo e
-# sequencias:
+# sequências:
mapa_json: {"chave": "valor"}
json_seq: [3, 2, 1, "decolar"]
+e aspas são opcionais: {chave: [3, 2, 1, decolar]}
-##########################
-# RECURSOS EXTRA DO YAML #
-##########################
+###########################
+# RECURSOS EXTRAS DO YAML #
+###########################
# YAML também tem um recurso útil chamado "âncoras", que permitem que você facilmente duplique
# conteúdo em seu documento. Ambas estas chaves terão o mesmo valor:
-conteudo_ancora: & nome_ancora Essa string irá aparecer como o valor de duas chaves.
-outra_ancora: * nome_ancora
+conteudo_ancora: &nome_ancora Essa string irá aparecer como o valor de duas chaves.
+outra_ancora: *nome_ancora
+
+# Âncoras podem ser usadas para dubplicar/herdar propriedades
+base: &base
+ name: Todos possuem o mesmo nome
+
+# O regexp << é chamado Mesclar o Tipo Chave Independente-de-Idioma. É usado para
+# indicar que todas as chaves de um ou mais mapas específicos devam ser inseridos
+# no mapa atual.
+
+foo:
+ <<: *base
+ idade: 10
+
+bar:
+ <<: *base
+ idade: 20
+
+# foo e bar terão o mesmo nome: Todos possuem o mesmo nome
# YAML também tem tags, que você pode usar para declarar explicitamente os tipos.
-string_explicita: !! str 0,5
+string_explicita: !!str 0.5
# Alguns analisadores implementam tags específicas de linguagem, como este para Python de
# Tipo de número complexo.
-numero_complexo_em_python: !! python / complex 1 + 2j
+numero_complexo_em_python: !!python/complex 1+2j
+
+# Podemos utilizar chaves YAML complexas com tags específicas de linguagem
+? !!python/tuple [5, 7]
+: Fifty Seven
+# Seria {(5, 7): 'Fifty Seven'} em Python
####################
# YAML TIPOS EXTRA #
@@ -114,27 +151,34 @@ numero_complexo_em_python: !! python / complex 1 + 2j
# Strings e números não são os únicos que escalares YAML pode entender.
# Data e 'data e hora' literais no formato ISO também são analisados.
-datetime: 2001-12-15T02: 59: 43.1Z
-datetime_com_espacos 2001/12/14: 21: 59: 43.10 -5
-Data: 2002/12/14
+datetime: 2001-12-15T02:59:43.1Z
+datetime_com_espaços: 2001-12-14 21:59:43.10 -5
+date: 2002-12-14
# A tag !!binary indica que a string é na verdade um base64-encoded (codificado)
# representação de um blob binário.
gif_file: !!binary |
- R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
- OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
- +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
- AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
+ R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
+ OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+ +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
+ AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
# YAML também tem um tipo de conjunto, o que se parece com isso:
-set:
- ? item1
- ? item2
- ? item3
+conjunto:
+ ? item1
+ ? item2
+ ? item3
+ou: {item1, item2, item3}
# Como Python, são apenas conjuntos de mapas com valors nulos; o acima é equivalente a:
-set2:
- item1: nulo
- item2: nulo
- item3: nulo
+conjunto2:
+ item1: null
+ item2: null
+ item3: null
+
+... # fim do documento
```
+### Mais Recursos
+
++ [Site Oficial do YAML](https://yaml.org/)
++ [Validador YAML Online](http://www.yamllint.com/)
diff --git a/pt-pt/git-pt.html.markdown b/pt-pt/git-pt.html.markdown
index bd0f0fc5..86710a13 100644
--- a/pt-pt/git-pt.html.markdown
+++ b/pt-pt/git-pt.html.markdown
@@ -411,5 +411,3 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/)
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-
-* [GitGuys](http://www.gitguys.com/)
diff --git a/r.html.markdown b/r.html.markdown
index e90d5a97..2746d1eb 100644
--- a/r.html.markdown
+++ b/r.html.markdown
@@ -4,6 +4,7 @@ contributors:
- ["e99n09", "http://github.com/e99n09"]
- ["isomorphismes", "http://twitter.com/isomorphisms"]
- ["kalinn", "http://github.com/kalinn"]
+ - ["mribeirodantas", "http://github.com/mribeirodantas"]
filename: learnr.r
---
@@ -29,13 +30,13 @@ R is a statistical computing language. It has lots of libraries for uploading an
# R without understanding anything about programming. Do not worry
# about understanding everything the code does. Just enjoy!
-data() # browse pre-loaded data sets
-data(rivers) # get this one: "Lengths of Major North American Rivers"
-ls() # notice that "rivers" now appears in the workspace
-head(rivers) # peek at the data set
+data() # browse pre-loaded data sets
+data(rivers) # get this one: "Lengths of Major North American Rivers"
+ls() # notice that "rivers" now appears in the workspace
+head(rivers) # peek at the data set
# 735 320 325 392 524 450
-length(rivers) # how many rivers were measured?
+length(rivers) # how many rivers were measured?
# 141
summary(rivers) # what are some summary statistics?
# Min. 1st Qu. Median Mean 3rd Qu. Max.
@@ -91,14 +92,15 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
# 82 | 2
# make a histogram:
-hist(rivers, col="#333333", border="white", breaks=25) # play around with these parameters
-hist(log(rivers), col="#333333", border="white", breaks=25) # you'll do more plotting later
+hist(rivers, col = "#333333", border = "white", breaks = 25)
+hist(log(rivers), col = "#333333", border = "white", breaks = 25)
+# play around with these parameters, you'll do more plotting later
# Here's another neat data set that comes pre-loaded. R has tons of these.
data(discoveries)
-plot(discoveries, col="#333333", lwd=3, xlab="Year",
+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",
+plot(discoveries, col = "#333333", lwd = 3, type = "h", xlab = "Year",
main="Number of important discoveries per year")
# Rather than leaving the default ordering (by year),
@@ -109,7 +111,7 @@ sort(discoveries)
# [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)
+stem(discoveries, scale = 2)
#
# The decimal point is at the |
#
@@ -134,7 +136,7 @@ summary(discoveries)
# 0.0 2.0 3.0 3.1 4.0 12.0
# Roll a die a few times
-round(runif(7, min=.5, max=6.5))
+round(runif(7, min = .5, max = 6.5))
# 1 4 6 1 4 6 4
# Your numbers will differ from mine unless we set the same random.seed(31337)
@@ -157,69 +159,68 @@ rnorm(9)
# INTEGERS
# Long-storage integers are written with L
-5L # 5
-class(5L) # "integer"
+5L # 5
+class(5L) # "integer"
# (Try ?class for more information on the class() function.)
# In R, every single value, like 5L, is considered a vector of length 1
-length(5L) # 1
+length(5L) # 1
# You can have an integer vector with length > 1 too:
-c(4L, 5L, 8L, 3L) # 4 5 8 3
-length(c(4L, 5L, 8L, 3L)) # 4
-class(c(4L, 5L, 8L, 3L)) # "integer"
+c(4L, 5L, 8L, 3L) # 4 5 8 3
+length(c(4L, 5L, 8L, 3L)) # 4
+class(c(4L, 5L, 8L, 3L)) # "integer"
# NUMERICS
# A "numeric" is a double-precision floating-point number
-5 # 5
-class(5) # "numeric"
+5 # 5
+class(5) # "numeric"
# Again, everything in R is a vector;
# you can make a numeric vector with more than one element
-c(3,3,3,2,2,1) # 3 3 3 2 2 1
+c(3, 3, 3, 2, 2, 1) # 3 3 3 2 2 1
# You can use scientific notation too
-5e4 # 50000
-6.02e23 # Avogadro's number
-1.6e-35 # Planck length
+5e4 # 50000
+6.02e23 # Avogadro's number
+1.6e-35 # Planck length
# You can also have infinitely large or small numbers
-class(Inf) # "numeric"
-class(-Inf) # "numeric"
+class(Inf) # "numeric"
+class(-Inf) # "numeric"
# You might use "Inf", for example, in integrate(dnorm, 3, Inf);
# this obviates Z-score tables.
# BASIC ARITHMETIC
# You can do arithmetic with numbers
# Doing arithmetic on a mix of integers and numerics gives you another numeric
-10L + 66L # 76 # integer plus integer gives integer
-53.2 - 4 # 49.2 # numeric minus numeric gives numeric
-2.0 * 2L # 4 # numeric times integer gives numeric
-3L / 4 # 0.75 # integer over numeric gives numeric
-3 %% 2 # 1 # the remainder of two numerics is another numeric
+10L + 66L # 76 # integer plus integer gives integer
+53.2 - 4 # 49.2 # numeric minus numeric gives numeric
+2.0 * 2L # 4 # numeric times integer gives numeric
+3L / 4 # 0.75 # integer over numeric gives numeric
+3 %% 2 # 1 # the remainder of two numerics is another numeric
# Illegal arithmetic yields you a "not-a-number":
-0 / 0 # NaN
-class(NaN) # "numeric"
+0 / 0 # NaN
+class(NaN) # "numeric"
# You can do arithmetic on two vectors with length greater than 1,
# so long as the larger vector's length is an integer multiple of the smaller
-c(1,2,3) + c(1,2,3) # 2 4 6
+c(1, 2, 3) + c(1, 2, 3) # 2 4 6
# Since a single number is a vector of length one, scalars are applied
# elementwise to vectors
-(4 * c(1,2,3) - 2) / 2 # 1 3 5
+(4 * c(1, 2, 3) - 2) / 2 # 1 3 5
# Except for scalars, use caution when performing arithmetic on vectors with
# different lengths. Although it can be done,
-c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6
-# Matching lengths is better practice and easier to read
-c(1,2,3,1,2,3) * c(1,2,1,2,1,2)
+c(1, 2, 3, 1, 2, 3) * c(1, 2) # 1 4 3 2 2 6
+# Matching lengths is better practice and easier to read most times
+c(1, 2, 3, 1, 2, 3) * c(1, 2, 1, 2, 1, 2) # 1 4 3 2 2 6
# CHARACTERS
# There's no difference between strings and characters in R
-"Horatio" # "Horatio"
-class("Horatio") # "character"
-class('H') # "character"
+"Horatio" # "Horatio"
+class("Horatio") # "character"
+class("H") # "character"
# Those were both character vectors of length 1
# Here is a longer one:
-c('alef', 'bet', 'gimmel', 'dalet', 'he')
-# =>
-# "alef" "bet" "gimmel" "dalet" "he"
+c("alef", "bet", "gimmel", "dalet", "he")
+# => "alef" "bet" "gimmel" "dalet" "he"
length(c("Call","me","Ishmael")) # 3
# You can do regex operations on character vectors:
-substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis "
+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 has several built-in character vectors:
letters
@@ -230,32 +231,33 @@ month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "D
# LOGICALS
# In R, a "logical" is a boolean
-class(TRUE) # "logical"
-class(FALSE) # "logical"
+
+class(TRUE) # "logical"
+class(FALSE) # "logical"
# Their behavior is normal
-TRUE == TRUE # TRUE
-TRUE == FALSE # FALSE
-FALSE != FALSE # FALSE
-FALSE != TRUE # TRUE
+TRUE == TRUE # TRUE
+TRUE == FALSE # FALSE
+FALSE != FALSE # FALSE
+FALSE != TRUE # TRUE
# Missing data (NA) is logical, too
-class(NA) # "logical"
+class(NA) # "logical"
# Use | and & for logic operations.
# OR
-TRUE | FALSE # TRUE
+TRUE | FALSE # TRUE
# AND
-TRUE & FALSE # FALSE
+TRUE & FALSE # FALSE
# Applying | and & to vectors returns elementwise logic operations
-c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE
-c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE
+c(TRUE, FALSE, FALSE) | c(FALSE, TRUE, FALSE) # TRUE TRUE FALSE
+c(TRUE, FALSE, TRUE) & c(FALSE, TRUE, TRUE) # FALSE FALSE TRUE
# You can test if x is TRUE
-isTRUE(TRUE) # TRUE
+isTRUE(TRUE) # TRUE
# Here we get a logical vector with many elements:
-c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE
-c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE
+c("Z", "o", "r", "r", "o") == "Zorro" # FALSE FALSE FALSE FALSE FALSE
+c("Z", "o", "r", "r", "o") == "Z" # TRUE FALSE FALSE FALSE FALSE
# FACTORS
# The factor class is for categorical data
-# Factors can be ordered (like childrens' grade levels) or unordered (like colors)
+# Factors can be ordered (like grade levels) or unordered (like colors)
factor(c("blue", "blue", "green", NA, "blue"))
# blue blue green <NA> blue
# Levels: blue green
@@ -263,31 +265,27 @@ factor(c("blue", "blue", "green", NA, "blue"))
# Note that missing data does not enter the levels
levels(factor(c("green", "green", "blue", NA, "blue"))) # "blue" "green"
# If a factor vector has length 1, its levels will have length 1, too
-length(factor("green")) # 1
+length(factor("green")) # 1
length(levels(factor("green"))) # 1
# Factors are commonly seen in data frames, a data structure we will cover later
-data(infert) # "Infertility after Spontaneous and Induced Abortion"
+data(infert) # "Infertility after Spontaneous and Induced Abortion"
levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs"
# NULL
# "NULL" is a weird one; use it to "blank out" a vector
-class(NULL) # NULL
+class(NULL) # NULL
parakeet = c("beak", "feathers", "wings", "eyes")
-parakeet
-# =>
-# [1] "beak" "feathers" "wings" "eyes"
+parakeet # "beak" "feathers" "wings" "eyes"
parakeet <- NULL
-parakeet
-# =>
-# NULL
+parakeet # NULL
# TYPE COERCION
# Type-coercion is when you force a value to take on a different type
-as.character(c(6, 8)) # "6" "8"
-as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE
+as.character(c(6, 8)) # "6" "8"
+as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE
# If you put elements of different types into a vector, weird coercions happen:
-c(TRUE, 4) # 1 4
-c("dog", TRUE, 4) # "dog" "TRUE" "4"
+c(TRUE, 4) # 1 4
+c("dog", TRUE, 4) # "dog" "TRUE" "4"
as.numeric("Bilbo")
# =>
# [1] NA
@@ -309,14 +307,15 @@ as.numeric("Bilbo")
# VARIABLES
# Lots of way to assign stuff:
-x = 5 # this is possible
-y <- "1" # this is preferred
-TRUE -> z # this works but is weird
+x = 5 # this is possible
+y <- "1" # this is preferred traditionally
+TRUE -> z # this works but is weird
+# Refer to the Internet for the behaviors and preferences about them.
# LOOPS
# We've got for loops
for (i in 1:4) {
- print(i)
+ print(i)
}
# We've got while loops
a <- 10
@@ -341,11 +340,11 @@ if (4 > 3) {
# FUNCTIONS
# Defined like so:
jiggle <- function(x) {
- x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise
+ x = x + rnorm(1, sd=.1) # add in a bit of (controlled) noise
return(x)
}
# Called like any other R function:
-jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043
+jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043
@@ -357,39 +356,39 @@ jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043
# Let's start from the very beginning, and with something you already know: vectors.
vec <- c(8, 9, 10, 11)
-vec # 8 9 10 11
+vec # 8 9 10 11
# We ask for specific elements by subsetting with square brackets
# (Note that R starts counting from 1)
-vec[1] # 8
-letters[18] # "r"
-LETTERS[13] # "M"
-month.name[9] # "September"
-c(6, 8, 7, 5, 3, 0, 9)[3] # 7
+vec[1] # 8
+letters[18] # "r"
+LETTERS[13] # "M"
+month.name[9] # "September"
+c(6, 8, 7, 5, 3, 0, 9)[3] # 7
# We can also search for the indices of specific components,
-which(vec %% 2 == 0) # 1 3
+which(vec %% 2 == 0) # 1 3
# grab just the first or last few entries in the vector,
-head(vec, 1) # 8
-tail(vec, 2) # 10 11
+head(vec, 1) # 8
+tail(vec, 2) # 10 11
# or figure out if a certain value is in the vector
-any(vec == 10) # TRUE
+any(vec == 10) # TRUE
# If an index "goes over" you'll get NA:
-vec[6] # NA
+vec[6] # NA
# You can find the length of your vector with length()
-length(vec) # 4
+length(vec) # 4
# You can perform operations on entire vectors or subsets of vectors
-vec * 4 # 32 36 40 44
-vec[2:3] * 5 # 45 50
-any(vec[2:3] == 8) # FALSE
+vec * 4 # 32 36 40 44
+vec[2:3] * 5 # 45 50
+any(vec[2:3] == 8) # FALSE
# and R has many built-in functions to summarize vectors
-mean(vec) # 9.5
-var(vec) # 1.666667
-sd(vec) # 1.290994
-max(vec) # 11
-min(vec) # 8
-sum(vec) # 38
+mean(vec) # 9.5
+var(vec) # 1.666667
+sd(vec) # 1.290994
+max(vec) # 11
+min(vec) # 8
+sum(vec) # 38
# Some more nice built-ins:
-5:15 # 5 6 7 8 9 10 11 12 13 14 15
-seq(from=0, to=31337, by=1337)
+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
@@ -397,7 +396,7 @@ seq(from=0, to=31337, by=1337)
# TWO-DIMENSIONAL (ALL ONE CLASS)
# You can make a matrix out of entries all of the same type like so:
-mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6))
+mat <- matrix(nrow = 3, ncol = 2, c(1, 2, 3, 4, 5, 6))
mat
# =>
# [,1] [,2]
@@ -405,13 +404,13 @@ mat
# [2,] 2 5
# [3,] 3 6
# Unlike a vector, the class of a matrix is "matrix", no matter what's in it
-class(mat) # => "matrix"
+class(mat) # "matrix" "array"
# Ask for the first row
-mat[1,] # 1 4
+mat[1, ] # 1 4
# Perform operation on the first column
-3 * mat[,1] # 3 6 9
+3 * mat[, 1] # 3 6 9
# Ask for a specific cell
-mat[3,2] # 6
+mat[3, 2] # 6
# Transpose the whole matrix
t(mat)
@@ -437,14 +436,14 @@ mat2
# [2,] "2" "cat"
# [3,] "3" "bird"
# [4,] "4" "dog"
-class(mat2) # matrix
+class(mat2) # matrix
# Again, note what happened!
# Because matrices must contain entries all of the same class,
# everything got converted to the character class
-c(class(mat2[,1]), class(mat2[,2]))
+c(class(mat2[, 1]), class(mat2[, 2]))
# rbind() sticks vectors together row-wise to make a matrix
-mat3 <- rbind(c(1,2,4,5), c(6,7,0,4))
+mat3 <- rbind(c(1, 2, 4, 5), c(6, 7, 0, 4))
mat3
# =>
# [,1] [,2] [,3] [,4]
@@ -458,11 +457,11 @@ mat3
# This data structure is so useful for statistical programming,
# a version of it was added to Python in the package "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"))
+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"
+class(students) # "data.frame"
students
# =>
# name year house
@@ -472,21 +471,22 @@ students
# 4 Cho 1 R
# 5 Draco 0 S
# 6 Ginny -1 G
-class(students$year) # "numeric"
-class(students[,3]) # "factor"
+class(students$year) # "numeric"
+class(students[,3]) # "factor"
# find the dimensions
-nrow(students) # 6
-ncol(students) # 3
-dim(students) # 6 3
-# The data.frame() function converts character vectors to factor vectors
-# by default; turn this off by setting stringsAsFactors = FALSE when
-# you create the data.frame
+nrow(students) # 6
+ncol(students) # 3
+dim(students) # 6 3
+# The data.frame() function used to convert character vectors to factor
+# vectors by default; This has changed in R 4.0.0. If your R version is
+# older, turn this off by setting stringsAsFactors = FALSE when you
+# create the data.frame
?data.frame
# There are many twisty ways to subset data frames, all subtly unalike
-students$year # 3 2 2 1 0 -1
-students[,2] # 3 2 2 1 0 -1
-students[,"year"] # 3 2 2 1 0 -1
+students$year # 3 2 2 1 0 -1
+students[, 2] # 3 2 2 1 0 -1
+students[, "year"] # 3 2 2 1 0 -1
# An augmented version of the data.frame structure is the data.table
# If you're working with huge or panel data, or need to merge a few data
@@ -503,19 +503,19 @@ students # note the slightly different print-out
# 4: Cho 1 R
# 5: Draco 0 S
# 6: Ginny -1 G
-students[name=="Ginny"] # get rows with name == "Ginny"
+students[name == "Ginny"] # get rows with name == "Ginny"
# =>
# name year house
# 1: Ginny -1 G
-students[year==2] # get rows with year == 2
+students[year == 2] # get rows with year == 2
# =>
# name year house
# 1: Fred 2 G
# 2: George 2 G
# data.table makes merging two data sets easy
# let's make another data.table to merge with students
-founders <- data.table(house=c("G","H","R","S"),
- founder=c("Godric","Helga","Rowena","Salazar"))
+founders <- data.table(house = c("G" , "H" , "R" , "S"),
+ founder = c("Godric", "Helga", "Rowena", "Salazar"))
founders
# =>
# house founder
@@ -526,8 +526,8 @@ founders
setkey(students, house)
setkey(founders, house)
students <- founders[students] # merge the two data sets by matching "house"
-setnames(students, c("house","houseFounderName","studentName","year"))
-students[,order(c("name","year","house","houseFounderName")), with=F]
+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
@@ -538,7 +538,7 @@ students[,order(c("name","year","house","houseFounderName")), with=F]
# 6: Draco 0 S Salazar
# data.table makes summary tables easy
-students[,sum(year),by=house]
+students[, sum(year), by = house]
# =>
# house V1
# 1: G 3
@@ -571,7 +571,7 @@ students[studentName != "Draco"]
# 5: R Cho 1
# Using data.frame:
students <- as.data.frame(students)
-students[students$house != "G",]
+students[students$house != "G", ]
# =>
# house houseFounderName studentName year
# 4 H Helga Cedric 3
@@ -583,13 +583,13 @@ students[students$house != "G",]
# Arrays creates n-dimensional tables
# All elements must be of the same type
# You can make a two-dimensional table (sort of like a matrix)
-array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4))
+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
# You can use array to make three-dimensional matrices too
-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))
+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
#
@@ -609,7 +609,7 @@ 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))
# Finally, R has lists (of vectors)
list1 <- list(time = 1:40)
-list1$price = c(rnorm(40,.5*list1$time,4)) # random
+list1$price = c(rnorm(40, .5*list1$time, 4)) # random
list1
# You can get items in the list like so
list1$time # one way
@@ -682,7 +682,7 @@ write.csv(pets, "pets2.csv") # to make a new .csv file
#########################
# Linear regression!
-linearModel <- lm(price ~ time, data = list1)
+linearModel <- lm(price ~ time, data = list1)
linearModel # outputs result of regression
# =>
# Call:
@@ -719,7 +719,7 @@ summary(linearModel)$coefficients # another way to extract results
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01
# time 0.4943490 0.06379348 7.74920901 2.440008e-09
-summary(linearModel)$coefficients[,4] # the p-values
+summary(linearModel)$coefficients[, 4] # the p-values
# =>
# (Intercept) time
# 9.234021e-01 2.440008e-09
@@ -728,8 +728,7 @@ summary(linearModel)$coefficients[,4] # the p-values
# Logistic regression
set.seed(1)
list1$success = rbinom(length(list1$time), 1, .5) # random binary
-glModel <- glm(success ~ time, data = list1,
- family=binomial(link="logit"))
+glModel <- glm(success ~ time, data = list1, family=binomial(link="logit"))
glModel # outputs result of logistic regression
# =>
# Call: glm(formula = success ~ time,
@@ -745,8 +744,10 @@ glModel # outputs result of logistic regression
summary(glModel) # more verbose output from the regression
# =>
# Call:
-# glm(formula = success ~ time,
-# family = binomial(link = "logit"), data = list1)
+# glm(
+# formula = success ~ time,
+# family = binomial(link = "logit"),
+# data = list1)
# Deviance Residuals:
# Min 1Q Median 3Q Max
@@ -780,7 +781,7 @@ plot(linearModel)
# Histograms!
hist(rpois(n = 10000, lambda = 5), col = "thistle")
# Barplots!
-barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow"))
+barplot(c(1, 4, 5, 1, 2), names.arg = c("red", "blue", "purple", "green", "yellow"))
# GGPLOT2
# But these are not even the prettiest of R's plots
@@ -788,10 +789,10 @@ barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow"))
install.packages("ggplot2")
require(ggplot2)
?ggplot2
-pp <- ggplot(students, aes(x=house))
+pp <- ggplot(students, aes(x = house))
pp + geom_bar()
ll <- as.data.table(list1)
-pp <- ggplot(ll, aes(x=time,price))
+pp <- ggplot(ll, aes(x = time, price))
pp + geom_point()
# ggplot2 has excellent documentation (available http://docs.ggplot2.org/current/)
diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown
index c31c6994..4556b425 100644
--- a/ru-ru/javascript-ru.html.markdown
+++ b/ru-ru/javascript-ru.html.markdown
@@ -473,7 +473,7 @@ if (0) {
}
// Впрочем, объекты-обёртки и встроенные типы имеют общие прототипы,
-// поэтому вы можете расширить функционал строк, например:
+// поэтому вы можете расширить функциональность строк, например:
String.prototype.firstCharacter = function() {
return this.charAt(0);
}
diff --git a/ru-ru/kotlin-ru.html.markdown b/ru-ru/kotlin-ru.html.markdown
index 85f44c96..6ec52927 100644
--- a/ru-ru/kotlin-ru.html.markdown
+++ b/ru-ru/kotlin-ru.html.markdown
@@ -333,7 +333,7 @@ fun helloWorld(val name : String) {
}
/*
- Расширения - это способ добавить новый функционал к классу.
+ Расширения - это способ добавить новую функциональность к классу.
Это то же самое, что методы расширений в C#.
*/
fun String.remove(c: Char): String {
diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown
index da9ced6a..6bfea4bb 100644
--- a/ru-ru/lua-ru.html.markdown
+++ b/ru-ru/lua-ru.html.markdown
@@ -98,7 +98,7 @@ end
-- Вложенные и анонимные функции являются нормой:
function adder(x)
- -- Возращаемая функция создаётся, когда вызывается функция adder,
+ -- Возвращаемая функция создаётся, когда вызывается функция adder,
-- и запоминает значение переменной x:
return function (y) return x + y end
end
@@ -363,7 +363,7 @@ end
return M
--- Другой файл может использовать функционал mod.lua:
+-- Другой файл может использовать функциональность mod.lua:
local mod = require('mod') -- Запустим файл mod.lua.
-- require - стандартный способ подключения модулей.
diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown
index 092c3e2f..6c7d9f6c 100644
--- a/ru-ru/objective-c-ru.html.markdown
+++ b/ru-ru/objective-c-ru.html.markdown
@@ -507,8 +507,8 @@ distance = 18; // Ссылается на "long distance" из реализац
@end
// Теперь, если мы хотим создать объект Truck - грузовик, мы должны создать подкласс класса Car, что
-// изменит функционал Car и позволит вести себя подобно грузовику. Но что, если мы хотим только добавить
-// определенный функционал в уже существующий класс Car? Например - чистка автомобиля. Мы просто создадим
+// изменит функциональность Car и позволит вести себя подобно грузовику. Но что, если мы хотим только добавить
+// определенную функциональность в уже существующий класс Car? Например - чистка автомобиля. Мы просто создадим
// категорию, которая добавит несколько методов для чистки автомобиля в класс Car:
// @interface ИмяФайла: Car+Clean.h (ИмяБазовогоКласса+ИмяКатегории.h)
#import "Car.h" // Убедитесь в том, что базовый класс импортирован для расширения.
diff --git a/ru-ru/rust-ru.html.markdown b/ru-ru/rust-ru.html.markdown
index d46d301c..a568ac37 100644
--- a/ru-ru/rust-ru.html.markdown
+++ b/ru-ru/rust-ru.html.markdown
@@ -1,5 +1,5 @@
---
-language: rust
+language: Rust
filename: learnrust-ru.rs
contributors:
diff --git a/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown
index b1931f9a..bd2d23a0 100644
--- a/ru-ru/swift-ru.html.markdown
+++ b/ru-ru/swift-ru.html.markdown
@@ -622,7 +622,7 @@ class MyShape: Rect {
// MARK: Прочее
//
-// `extension`s: Добавляет расширенный функционал к существующему типу
+// `extension`s: Добавляет расширенную функциональность к существующему типу
// Класс Square теперь "соответствует" протоколу `CustomStringConvertible`
extension Square: CustomStringConvertible {
diff --git a/sk-sk/git-sk.html.markdown b/sk-sk/git-sk.html.markdown
index 21741406..ddcd9658 100644
--- a/sk-sk/git-sk.html.markdown
+++ b/sk-sk/git-sk.html.markdown
@@ -514,8 +514,6 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-* [GitGuys](http://www.gitguys.com/)
-
* [Git - jednoducho](http://rogerdudler.github.io/git-guide/index.html)
* [Pro Git](http://www.git-scm.com/book/en/v2)
diff --git a/solidity.html.markdown b/solidity.html.markdown
index 5f8ef407..c52d2002 100644
--- a/solidity.html.markdown
+++ b/solidity.html.markdown
@@ -214,7 +214,7 @@ assert(c >= a); // assert tests for internal invariants; require is used for use
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
-// No random functions built in, you can get a pseduo-random number by hashing the current blockhash, or get a truely random number using something like Chainlink VRF.
+// No random functions built in, you can get a pseduo-random number by hashing the current blockhash, or get a truly random number using something like Chainlink VRF.
// https://docs.chain.link/docs/get-a-random-number
// Type casting
@@ -396,13 +396,13 @@ function increment(uint x) returns (uint) {
return x;
}
-// Functions can return many arguments, and by specifying returned arguments
-// name don't need to explicitly return
+// Functions can return many arguments,
+// and by specifying returned arguments name explicit return is not needed
function increment(uint x, uint y) returns (uint x, uint y) {
x += 1;
y += 1;
}
-// Call previous functon
+// Call previous function
uint (a,b) = increment(1,1);
// 'view' (alias for 'constant')
@@ -654,7 +654,7 @@ reveal(100, "mySecret");
// Time-based implementations of contracts are also done through oracles, as
// contracts need to be directly called and can not "subscribe" to a time.
// Due to smart contracts being decentralized, you also want to get your data
-// in a decentralized manner, other your run into the centralized risk that
+// in a decentralized manner, otherwise you run into the centralized risk that
// smart contract design matter prevents.
// To easiest way get and use pre-boxed decentralized data is with Chainlink Data Feeds
diff --git a/tr-tr/bf-tr.html.markdown b/tr-tr/bf-tr.html.markdown
index e7015cd0..ef46f362 100644
--- a/tr-tr/bf-tr.html.markdown
+++ b/tr-tr/bf-tr.html.markdown
@@ -1,6 +1,6 @@
---
language: bf
-filename: brainfuck-tr
+filename: brainfuck-tr.bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io"]
translators:
diff --git a/tr-tr/git-tr.html.markdown b/tr-tr/git-tr.html.markdown
index 87c1820c..c6979468 100644
--- a/tr-tr/git-tr.html.markdown
+++ b/tr-tr/git-tr.html.markdown
@@ -587,8 +587,6 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [SalesForce Kopya Kağıdı](http://res.cloudinary.com/hy4kyit2a/image/upload/SF_git_cheatsheet.pdf)
-* [GitGuys](http://www.gitguys.com/)
-
* [Git - Basit bir kılavuz](http://rogerdudler.github.io/git-guide/index.html)
* [Pro Git](http://www.git-scm.com/book/en/v2)
diff --git a/uk-ua/mips-ua.html.markdown b/uk-ua/mips-ua.html.markdown
index 8d4517fe..2d42e85d 100644
--- a/uk-ua/mips-ua.html.markdown
+++ b/uk-ua/mips-ua.html.markdown
@@ -188,7 +188,7 @@ lang: uk-ua
# Нехай $s0 = a, $s1 = b, $s2 = c, $v0 = повернути регістр
ble $s0, $s1, a_LTE_b # якщо (a <= b) розгалуження(a_LTE_b)
ble $s0, $s2, max_C # якщо (a > b && a <=c) розгалуження(max_C)
- move $v0, $s1 # інакше [a > b && a > c] max = a
+ move $v0, $s0 # інакше [a > b && a > c] max = a
j done # Перейти в кінець програми
a_LTE_b: # Мітка розгалуження, коли a <= b
diff --git a/uk-ua/rust-ua.html.markdown b/uk-ua/rust-ua.html.markdown
index 422de371..4aad0cbb 100644
--- a/uk-ua/rust-ua.html.markdown
+++ b/uk-ua/rust-ua.html.markdown
@@ -1,5 +1,5 @@
---
-language: rust
+language: Rust
contributors:
- ["P1start", "http://p1start.github.io/"]
translators:
diff --git a/vi-vn/git-vi.html.markdown b/vi-vn/git-vi.html.markdown
index 1bcc94a0..f5454ebf 100644
--- a/vi-vn/git-vi.html.markdown
+++ b/vi-vn/git-vi.html.markdown
@@ -396,8 +396,6 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-* [GitGuys](http://www.gitguys.com/)
-
* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html)
diff --git a/vi-vn/json-vi.html.markdown b/vi-vn/json-vi.html.markdown
index 257216ff..f709b838 100644
--- a/vi-vn/json-vi.html.markdown
+++ b/vi-vn/json-vi.html.markdown
@@ -37,7 +37,7 @@ kiểu dữ liệu cũng như quy chuẩn cú pháp chặt chẽ sử dụng DTD
"các khóa": "phải luôn được đặt trong dấu ngoặc kép",
"số": 0,
- "chuỗi kí tự": "Xin chàø. Tất cả kí tự unicode đều được chấp nhận, sử dụng với dạng \"kí tự\"."
+ "chuỗi kí tự": "Xin chàø. Tất cả kí tự unicode đều được chấp nhận, sử dụng với dạng \"kí tự\".",
"có đúng không?": true,
"không có gì": null,
diff --git a/vim.html.markdown b/vim.html.markdown
index 00a44807..a72db158 100644
--- a/vim.html.markdown
+++ b/vim.html.markdown
@@ -54,7 +54,7 @@ specific points in the file, and for fast editing.
/word # Highlights all occurrences of word after cursor
?word # Highlights all occurrences of word before cursor
n # Moves cursor to next occurrence of word after search
- N # Moves cursor to previous occerence of word
+ N # Moves cursor to previous occurrence of word
:%s/foo/bar/g # Change 'foo' to 'bar' on every line in the file
:s/foo/bar/g # Change 'foo' to 'bar' on the current line
diff --git a/vimscript.html.markdown b/vimscript.html.markdown
index c2934af8..c32faee9 100644
--- a/vimscript.html.markdown
+++ b/vimscript.html.markdown
@@ -42,7 +42,7 @@ pwd " Displays the current working directory
" comment (echo assumes that the quotation mark begins a string)
echo 'Hello world!' | " Displays a message
-" Line breaks can be escaped by pacing a backslash as the first non-whitespace
+" Line breaks can be escaped by placing a backslash as the first non-whitespace
" character on the *following* line. Only works in script files, not on the
" command line
echo " Hello
diff --git a/zh-cn/awk-cn.html.markdown b/zh-cn/awk-cn.html.markdown
index 8ee2db2c..bac833a6 100644
--- a/zh-cn/awk-cn.html.markdown
+++ b/zh-cn/awk-cn.html.markdown
@@ -179,7 +179,7 @@ function string_functions( localvar, arr) {
# 都是返回替换的个数
localvar = "fooooobar"
sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar"
- gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar"
+ gsub("e", ".", localvar) # localvar => "m..t m. at th. bar"
# 搜索匹配正则的字符串
# index() 也是搜索, 不支持正则
diff --git a/zh-cn/docker-cn.html.markdown b/zh-cn/docker-cn.html.markdown
index f55e805a..ff793ae0 100644
--- a/zh-cn/docker-cn.html.markdown
+++ b/zh-cn/docker-cn.html.markdown
@@ -1,5 +1,6 @@
---
-language: docker
+category: tool
+tool: docker
lang: zh-cn
filename: docker-cn.bat
contributors:
diff --git a/zh-cn/gdscript-cn.html.markdown b/zh-cn/gdscript-cn.html.markdown
new file mode 100644
index 00000000..3405bb8d
--- /dev/null
+++ b/zh-cn/gdscript-cn.html.markdown
@@ -0,0 +1,314 @@
+---
+language: GDScript
+contributors:
+ - ["Wichamir", "https://github.com/Wichamir/"]
+translators:
+ - ["ShiftWatchOut", "https://github.com/ShiftWatchOut"]
+filename: learngdscript-cn.gd
+lang: zh-cn
+---
+
+GDScript 是一种动态类型的脚本语言,专门为免费开源游戏引擎 Godot 制作。 GDScript 的语法类似 Python。
+它的主要优点是易于使用和与引擎深度集成。 它非常适合游戏开发。
+
+## 基础
+
+```nim
+# 单行注释使用 # 号书写。
+"""
+ 多行
+ 注释
+ 是
+ 使用
+ 文档字符串(docstring)
+ 书写。
+"""
+
+# 脚本文件本身默认是一个类,文件名为类名,您也可以为其定义其他名称。
+class_name MyClass
+
+# 继承
+extends Node2D
+
+# 成员变量
+var x = 8 # 整型
+var y = 1.2 # 浮点型
+var b = true # 布尔型
+var s = "Hello World!" # 字符串
+var a = [1, false, "brown fox"] # 数组(Array) - 类似于 Python 的列表(list),
+ # 它可以同时保存不同类型的变量。
+var d = {
+ "key" : "value",
+ 42 : true
+} # 字典包含键值对。
+var p_arr = PoolStringArray(["Hi", "there", "!"]) # 池数组只能包含单一类型。
+ # 放入其他类型会被转换为目标类型
+
+# 内置向量类型:
+var v2 = Vector2(1, 2)
+var v3 = Vector3(1, 2, 3)
+
+# 常量
+const ANSWER_TO_EVERYTHING = 42
+const BREAKFAST = "Spam and eggs!"
+
+# 枚举
+enum { ZERO, ONE , TWO, THREE }
+enum NamedEnum { ONE = 1, TWO, THREE }
+
+# 导出的变量将在检查器中可见。
+export(int) var age
+export(float) var height
+export var person_name = "Bob" # 如果设置了默认值,则不需要类型注解。
+
+# 函数
+func foo():
+ pass # pass 关键字是未书写的代码的占位符
+
+func add(first, second):
+ return first + second
+
+# 打印值
+func printing():
+ print("GDScript ", "简直", "棒呆了")
+ prints("这", "些", "字", "被", "空", "格", "分", "割")
+ printt("这", "些", "字", "被", "制", "表", "符", "分", "割")
+ printraw("这句话将被打印到系统控制台。")
+
+# 数学
+func doing_math():
+ var first = 8
+ var second = 4
+ print(first + second) # 12
+ print(first - second) # 4
+ print(first * second) # 32
+ print(first / second) # 2
+ print(first % second) # 0
+ # 还有 +=, -=, *=, /=, %= 等操作符,但并没有 ++ 和 -- .
+ print(pow(first, 2)) # 64
+ print(sqrt(second)) # 2
+ printt(PI, TAU, INF, NAN) # 内置常量
+
+# 控制流
+func control_flow():
+ x = 8
+ y = 2 # y 最初被设为一个浮点数,
+ # 但我们可以利用语言提供的动态类型能力将它的类型变为整型!
+
+ if x < y:
+ print("x 小于 y")
+ elif x > y:
+ print("x 大于 y")
+ else:
+ print("x 等于 y")
+
+ var a = true
+ var b = false
+ var c = false
+ if a and b or not c: # 你也可以用 &&, || 和 !
+ print("看到这句说明上面的条件判断为真!")
+
+ for i in range(20): # GDScript 有类似 Python 的 range 函数
+ print(i) # 所以这句将打印从 0 到 19 的数字
+
+ for i in ["two", 3, 1.0]: # 遍历数组
+ print(i)
+
+ while x > y:
+ printt(x, y)
+ y += 1
+
+ x = 2
+ y = 10
+ while x < y:
+ x += 1
+ if x == 6:
+ continue # continue 语句使 x 等于 6 时,程序跳过这次循环后面的代码,不会打印 6。
+ prints("x 等于:", x)
+ if x == 7:
+ break # 循环将在 x 等于 7 处跳出,后续所有循环不再执行,因此不会打印 8、9 和 10
+
+ match x:
+ 1:
+ print("match 很像其他语言中的 switch.")
+ 2:
+ print("但是,您不需要在每个值之前写一个 case 关键字。")
+ 3:
+ print("此外,每种情况都会默认跳出。")
+ break # 错误!不要在 match 里用 break 语句!
+ 4:
+ print("如果您需要跳过后续代码,这里也使用 continue 关键字。")
+ continue
+ _:
+ print("下划线分支,在其他分支都不满足时,在这里书写默认的逻辑。")
+
+ # 三元运算符 (写在一行的 if-else 语句)
+ prints("x 是", "正值" if x >= 0 else "负值")
+
+# 类型转换
+func casting_examples():
+ var i = 42
+ var f = float(42) # 使用变量构造函数强制转换
+ var b = i as bool # 或使用 as 关键字
+
+# 重载函数
+# 通常,我们只会重载以下划线开头的内置函数,
+# 但实际上您可以重载几乎任何函数。
+
+# _init 在对象初始化时被调用。
+# 这是对象的构造函数。
+func _init():
+ # 在此处初始化对象的内部属性。
+ pass
+
+# _ready 在脚本节点及其子节点进入场景树时被调用。
+func _ready():
+ pass
+
+# _process 在每一帧上都被调用。
+func _process(delta):
+ # 传递给此函数的 delta 参数是时间,即从上一帧到当前帧经过的秒数。
+ print("Delta 时间为:", delta)
+
+# _physics_process 在每个物理帧上都被调用。
+# 这意味着 delta 应该是恒定的。
+func _physics_process(delta):
+ # 使用向量加法和乘法进行简单移动。
+ var direction = Vector2(1, 0) # 或使用 Vector2.RIGHT
+ var speed = 100.0
+ self.global_position += direction * speed * delta
+ # self 指向当前类的实例
+
+# 重载函数时,您可以使用 . 运算符调用父函数
+# like here:
+func get_children():
+ # 在这里做一些额外的事情。
+ var r = .get_children() # 调用父函数的实现
+ return r
+
+# 内部类
+class InnerClass:
+ extends Object
+
+ func hello():
+ print("来自内部类的 Hello!")
+
+func use_inner_class():
+ var ic = InnerClass.new()
+ ic.hello()
+ ic.free() # 可以自行释放内存
+```
+
+## 访问场景树中其他节点
+
+```nim
+extends Node2D
+
+var sprite # 该变量将用来保存引用。
+
+# 您可以在 _ready 中获取对其他节点的引用。
+func _ready() -> void:
+ # NodePath 对于访问节点很有用。
+ # 将 String 传递给其构造函数来创建 NodePath:
+ var path1 = NodePath("path/to/something")
+ # 或者使用 NodePath 字面量:
+ var path2 = @"path/to/something"
+ # NodePath 示例:
+ var path3 = @"Sprite" # 相对路径,当前节点的直接子节点
+ var path4 = @"Timers/Firerate" # 相对路径,子节点的子节点
+ var path5 = @".." # 当前节点的父节点
+ var path6 = @"../Enemy" # 当前节点的兄弟节点
+ var path7 = @"/root" # 绝对路径,等价于 get_tree().get_root()
+ var path8 = @"/root/Main/Player/Sprite" # Player 的 Sprite 的绝对路径
+ var path9 = @"Timers/Firerate:wait_time" # 访问属性
+ var path10 = @"Player:position:x" # 访问子属性
+
+ # 最后,获取节点引用可以使用以下方法:
+ sprite = get_node(@"Sprite") as Sprite # 始终转换为您期望的类型
+ sprite = get_node("Sprite") as Sprite # 这里 String 被隐式转换为 NodePath
+ sprite = get_node(path3) as Sprite
+ sprite = get_node_or_null("Sprite") as Sprite
+ sprite = $Sprite as Sprite
+
+func _process(delta):
+ # 现在我们就可以在别处使用 sprite 里保存的引用了。
+ prints("Sprite 有一个全局位置 ", sprite.global_position)
+
+# 在 _ready 执行之前,使用 onready 关键字为变量赋值。
+# 这是一种常用的语法糖。
+onready var tween = $Tween as Tween
+
+# 您可以导出这个 NodePath,以便在检查器中给它赋值。
+export var nodepath = @""
+onready var reference = get_node(nodepath) as Node
+```
+
+## 信号(Signals)
+
+信号系统是 Godot 对观察者编程模式的实现。例子如下:
+
+```nim
+class_name Player extends Node2D
+
+var hp = 10
+
+signal died() # 定义一个信号
+signal hurt(hp_old, hp_new) # 信号可以带参数
+
+func apply_damage(dmg):
+ var hp_old = hp
+ hp -= dmg
+ emit_signal("hurt", hp_old, hp) # 发出信号并传递参数
+ if hp <= 0:
+ emit_signal("died")
+
+func _ready():
+ # 将信号 "died" 连接到 self 中定义的 _on_death 函数
+ self.connect("died", self, "_on_death")
+
+func _on_death():
+ self.queue_free() # 死亡时销毁 Player
+```
+
+## 类型注解
+
+GDScript 可以选择性地使用静态类型。
+
+```nim
+extends Node
+
+var x: int # 定义带有类型的变量
+var y: float = 4.2
+var z := 1.0 # 使用 := 运算符根据默认值推断类型
+
+onready var node_ref_typed := $Child as Node
+
+export var speed := 50.0
+
+const CONSTANT := "Typed constant."
+
+func _ready() -> void:
+ # 此函数不返回任何东西
+ x = "string" # 错误!不要更改类型!
+ return
+
+func join(arg1: String, arg2: String) -> String:
+ # 此函数接受两个 String 并返回一个 String。
+ return arg1 + arg2
+
+func get_child_at(index: int) -> Node:
+ # 此函数接受一个 int 并返回一个 Node
+ return get_children()[index]
+
+signal example(arg: int) # 错误!信号不能接受类型参数!
+```
+
+## 延展阅读
+
+* [Godot's Website](https://godotengine.org/)
+* [Godot Docs](https://docs.godotengine.org/en/stable/)
+* [Getting started with GDScript](https://docs.godotengine.org/en/stable/getting_started/scripting/gdscript/index.html)
+* [NodePath](https://docs.godotengine.org/en/stable/classes/class_nodepath.html)
+* [Signals](https://docs.godotengine.org/en/stable/getting_started/step_by_step/signals.html)
+* [GDQuest](https://www.gdquest.com/)
+* [GDScript.com](https://gdscript.com/) \ No newline at end of file
diff --git a/zh-cn/git-cn.html.markdown b/zh-cn/git-cn.html.markdown
index 63d740a1..9dfbbb93 100644
--- a/zh-cn/git-cn.html.markdown
+++ b/zh-cn/git-cn.html.markdown
@@ -370,5 +370,3 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [Atlassian Git - 教程与工作流程](https://www.atlassian.com/git/)
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-
-* [GitGuys](http://www.gitguys.com/)
diff --git a/zh-cn/mips-cn.html.markdown b/zh-cn/mips-cn.html.markdown
index 83888338..4f9ea7da 100644
--- a/zh-cn/mips-cn.html.markdown
+++ b/zh-cn/mips-cn.html.markdown
@@ -160,7 +160,7 @@ MIPS(Microprocessor without Interlocked Pipeline Stages)汇编语言是为
# 让 $s0 = a, $s1 = b, $s2 = c, $v0 = 返回寄存器
ble $s0, $s1, a_LTE_b # 如果 (a <= b) 跳转到 (a_LTE_b)
ble $s0, $s2, max_C # 如果 (a > b && a <= c) 跳转到 (max_C)
- move $v0, $s1 # 否则 [a > b && a > c] max = a
+ move $v0, $s0 # 否则 [a > b && a > c] max = a
j done # 跳转到程序结束
a_LTE_b: # 当 a <= b 时的标签
diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown
index 4469443f..a4e53c1b 100644
--- a/zh-cn/python-cn.html.markdown
+++ b/zh-cn/python-cn.html.markdown
@@ -6,8 +6,10 @@ contributors:
- ["Andre Polykanine", "https://github.com/Oire"]
translators:
- ["Geoff Liu", "http://geoffliu.me"]
+ - ["Maple", "https://github.com/mapleincode"]
filename: learnpython-cn.py
lang: zh-cn
+
---
Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。
@@ -19,7 +21,6 @@ Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。
注意:这篇教程是基于 Python 3 写的。如果你想学旧版 Python 2,我们特别有[另一篇教程](http://learnxinyminutes.com/docs/pythonlegacy/)。
```python
-
# 用井字符开头的是单行注释
""" 多行字符串用三个引号
@@ -35,50 +36,66 @@ Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。
3 # => 3
# 算术没有什么出乎意料的
-1 + 1 # => 2
-8 - 1 # => 7
+1 + 1 # => 2
+8 - 1 # => 7
10 * 2 # => 20
# 但是除法例外,会自动转换成浮点数
35 / 5 # => 7.0
-5 / 3 # => 1.6666666666666667
+10.0 / 3 # => 3.3333333333333335
# 整数除法的结果都是向下取整
-5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # 浮点数也可以
--5 // 3 # => -2
--5.0 // 3.0 # => -2.0
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # 浮点数也可以
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
# 浮点数的运算结果也是浮点数
3 * 2.0 # => 6.0
# 模除
7 % 3 # => 1
+# i % j 结果的正负符号会和 j 相同,而不是和 i 相同
+-7 % 3 # => 2
-# x的y次方
+# x 的 y 次方
2**4 # => 16
# 用括号决定优先级
+1 + 3 * 2 # => 7
(1 + 3) * 2 # => 8
-# 布尔值
-True
-False
+# 布尔值 (注意: 首字母大写)
+True # => True
+False # => False
-# 用not取非
-not True # => False
+# 用 not 取非
+not True # => False
not False # => True
-# 逻辑运算符,注意and和or都是小写
+# 逻辑运算符,注意 and 和 or 都是小写
True and False # => False
False or True # => True
-# 整数也可以当作布尔值
-0 and 2 # => 0
--5 or 0 # => -5
+# True 和 False 实质上就是数字 1 和0
+True + True # => 2
+True * 8 # => 8
+False - 5 # => -5
+
+# 数值与 True 和 False 之间的比较运算
0 == False # => True
2 == True # => False
1 == True # => True
+-5 != False # => True
+
+# 使用布尔逻辑运算符对数字类型的值进行运算时,会把数值强制转换为布尔值进行运算
+# 但计算结果会返回它们的强制转换前的值
+# 注意不要把 bool(ints) 与位运算的 "按位与"、"按位或" (&, |) 混淆
+bool(0) # => False
+bool(4) # => True
+bool(-6) # => True
+0 and 2 # => 0
+-5 or 0 # => -5
# 用==判断相等
1 == 1 # => True
@@ -94,43 +111,66 @@ False or True # => True
2 <= 2 # => True
2 >= 2 # => True
+# 判断一个值是否在范围里
+1 < 2 and 2 < 3 # => True
+2 < 3 and 3 < 2 # => False
# 大小比较可以连起来!
1 < 2 < 3 # => True
2 < 3 < 2 # => False
-# 字符串用单引双引都可以
+# (is 对比 ==) is 判断两个变量是否引用同一个对象,
+# 而 == 判断两个对象是否含有相同的值
+a = [1, 2, 3, 4] # 变量 a 是一个新的列表, [1, 2, 3, 4]
+b = a # 变量 b 赋值了变量 a 的值
+b is a # => True, a 和 b 引用的是同一个对象
+b == a # => True, a 和 b 的对象的值相同
+b = [1, 2, 3, 4] # 变量 b 赋值了一个新的列表, [1, 2, 3, 4]
+b is a # => False, a 和 b 引用的不是同一个对象
+b == a # => True, a 和 b 的对象的值相同
+
+
+# 创建字符串可以使用单引号(')或者双引号(")
"这是个字符串"
'这也是个字符串'
-# 用加号连接字符串
+# 字符串可以使用加号连接成新的字符串
"Hello " + "world!" # => "Hello world!"
+# 非变量形式的字符串甚至可以在没有加号的情况下连接
+"Hello " "world!" # => "Hello world!"
# 字符串可以被当作字符列表
-"This is a string"[0] # => 'T'
+"Hello world!"[0] # => 'H'
-# 用.format来格式化字符串
-"{} can be {}".format("strings", "interpolated")
+# 你可以获得字符串的长度
+len("This is a string") # => 16
+# 你可以使用 f-strings 格式化字符串(python3.6+)
+name = "Reiko"
+f"She said her name is {name}." # => "She said her name is Reiko"
+# 你可以在大括号内几乎加入任何 python 表达式,表达式的结果会以字符串的形式返回
+f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long."
+
+# 用 .format 来格式化字符串
+"{} can be {}".format("strings", "interpolated")
# 可以重复参数以节省时间
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
# => "Jack be nimble, Jack be quick, Jack jump over the candle stick"
-
# 如果不想数参数,可以用关键字
"{name} wants to eat {food}".format(name="Bob", food="lasagna")
# => "Bob wants to eat lasagna"
-# 如果你的Python3程序也要在Python2.5以下环境运行,也可以用老式的格式化语法
+# 如果你的 Python3 程序也要在 Python2.5 以下环境运行,也可以用老式的格式化语法
"%s can be %s the %s way" % ("strings", "interpolated", "old")
# None是一个对象
None # => None
-# 当与None进行比较时不要用 ==,要用is。is是用来比较两个变量是否指向同一个对象。
+# 当与 None 进行比较时不要用 ==,要用 is。is 是用来比较两个变量是否指向同一个对象。
"etc" is None # => False
None is None # => True
-# None,0,空字符串,空列表,空字典,空元组都算是False
-# 所有其他值都是True
+# None,0,空字符串,空列表,空字典,空元组都算是 False
+# 所有其他值都是 True
bool(0) # => False
bool("") # => False
bool([]) # => False
@@ -145,16 +185,26 @@ bool(()) # => False
# print是内置的打印函数
print("I'm Python. Nice to meet you!")
+# 默认情况下,print 函数会在输出结果后加入一个空行作为结尾
+# 可以使用附加参数改变输出结尾
+print("Hello, World", end="!") # => Hello, World!
+
+# 可以很简单的从终端获得输入数据
+input_string_var = input("Enter some data: ") # 返回字符串数值
+
# 在给变量赋值前不用提前声明
-# 传统的变量命名是小写,用下划线分隔单词
+# 习惯上变量命名是小写,用下划线分隔单词
some_var = 5
some_var # => 5
# 访问未赋值的变量会抛出异常
# 参考流程控制一段来学习异常处理
-some_unknown_var # 抛出NameError
+some_unknown_var # 抛出 NameError
+
+# "if" 可以用作表达式,它的作用等同于 C 语言的三元运算符 "?:"
+"yay!" if 0 > 1 else "nay!" # => "nay!"
-# 用列表(list)储存序列
+# 用列表 (list) 储存序列
li = []
# 创建列表时也可以同时赋给元素
other_li = [4, 5, 6]
@@ -174,128 +224,177 @@ li[0] # => 1
# 取出最后一个元素
li[-1] # => 3
-# 越界存取会造成IndexError
-li[4] # 抛出IndexError
+# 越界存取会造成 IndexError
+li[4] # 抛出 IndexError
# 列表有切割语法
-li[1:3] # => [2, 4]
+li[1:3] # => [2, 4]
# 取尾
-li[2:] # => [4, 3]
+li[2:] # => [4, 3]
# 取头
-li[:3] # => [1, 2, 4]
+li[:3] # => [1, 2, 4]
# 隔一个取一个
-li[::2] # =>[1, 4]
+li[::2] # =>[1, 4]
# 倒排列表
li[::-1] # => [3, 4, 2, 1]
# 可以用三个参数的任何组合来构建切割
# li[始:终:步伐]
-# 用del删除任何一个元素
-del li[2] # li is now [1, 2, 3]
+# 简单的实现了单层数组的深度复制
+li2 = li[:] # => li2 = [1, 2, 4, 3] ,但 (li2 is li) 会返回 False
+
+# 用 del 删除任何一个元素
+del li[2] # li 现在为 [1, 2, 3]
+
+# 删除第一个匹配的元素
+li.remove(2) # li 现在为 [1, 3]
+li.remove(2) # 抛出错误 ValueError: 2 is not in the list
+
+# 在指定索引处插入一个新的元素
+li.insert(1, 2) # li is now [1, 2, 3] again
+
+# 获得列表第一个匹配的值的索引
+li.index(2) # => 1
+li.index(4) # 抛出一个 ValueError: 4 is not in the list
# 列表可以相加
-# 注意:li和other_li的值都不变
+# 注意:li 和 other_li 的值都不变
li + other_li # => [1, 2, 3, 4, 5, 6]
-# 用extend拼接列表
-li.extend(other_li) # li现在是[1, 2, 3, 4, 5, 6]
+# 用 "extend()" 拼接列表
+li.extend(other_li) # li 现在是[1, 2, 3, 4, 5, 6]
-# 用in测试列表是否包含值
+# 用 "in" 测试列表是否包含值
1 in li # => True
-# 用len取列表长度
+# 用 "len()" 取列表长度
len(li) # => 6
-# 元组是不可改变的序列
+# 元组类似列表,但是不允许修改
tup = (1, 2, 3)
tup[0] # => 1
-tup[0] = 3 # 抛出TypeError
+tup[0] = 3 # 抛出 TypeError
+
+# 如果元素数量为 1 的元组必须在元素之后加一个逗号
+# 其他元素数量的元组,包括空元组,都不需要
+type((1)) # => <class 'int'>
+type((1,)) # => <class 'tuple'>
+type(()) # => <class 'tuple'>
-# 列表允许的操作元组大都可以
+# 列表允许的操作元组大多都可以
len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
tup[:2] # => (1, 2)
2 in tup # => True
# 可以把元组合列表解包,赋值给变量
-a, b, c = (1, 2, 3) # 现在a是1,b是2,c是3
+a, b, c = (1, 2, 3) # 现在 a 是 1,b 是 2,c 是 3
+# 也可以做扩展解包
+a, *b, c = (1, 2, 3, 4) # 现在 a 是 1, b 是 [2, 3], c 是 4
# 元组周围的括号是可以省略的
-d, e, f = 4, 5, 6
+d, e, f = 4, 5, 6 # 元组 4, 5, 6 通过解包被赋值给变量 d, e, f
# 交换两个变量的值就这么简单
-e, d = d, e # 现在d是5,e是4
+e, d = d, e # 现在 d 是 5,e 是 4
-# 用字典表达映射关系
+# 字典用来存储 key 到 value 的映射关系
empty_dict = {}
# 初始化的字典
filled_dict = {"one": 1, "two": 2, "three": 3}
+# 字典的 key 必须为不可变类型。 这是为了确保 key 被转换为唯一的哈希值以用于快速查询
+# 不可变类型包括整数、浮点、字符串、元组
+invalid_dict = {[1,2,3]: "123"} # => 抛出 TypeError: unhashable type: 'list'
+valid_dict = {(1,2,3):[1,2,3]} # 然而 value 可以是任何类型
+
# 用[]取值
filled_dict["one"] # => 1
-
# 用 keys 获得所有的键。
-# 因为 keys 返回一个可迭代对象,所以在这里把结果包在 list 里。我们下面会详细介绍可迭代。
-# 注意:字典键的顺序是不定的,你得到的结果可能和以下不同。
-list(filled_dict.keys()) # => ["three", "two", "one"]
+# 因为 keys 返回一个可迭代对象,所以我们需要把它包在 "list()" 里才能转换为列表。
+# 我们下面会详细介绍可迭代。
+# 注意: 对于版本 < 3.7 的 python, 字典的 key 的排序是无序的。你的运行结果
+# 可能与下面的例子不符,但是在 3.7 版本,字典中的项会按照他们被插入到字典的顺序进行排序
+list(filled_dict.keys()) # => ["three", "two", "one"] Python 版本 <3.7
+list(filled_dict.keys()) # => ["one", "two", "three"] Python 版本 3.7+
+# 用 "values()" 获得所有的值。跟 keys 一样也是可迭代对象,要使用 "list()" 才能转换为列表。
+# 注意: 排序顺序和 keys 的情况相同。
-# 用values获得所有的值。跟keys一样,要用list包起来,顺序也可能不同。
-list(filled_dict.values()) # => [3, 2, 1]
+list(filled_dict.values()) # => [3, 2, 1] Python 版本 < 3.7
+list(filled_dict.values()) # => [1, 2, 3] Python 版本 3.7+
# 用in测试一个字典是否包含一个键
"one" in filled_dict # => True
1 in filled_dict # => False
-# 访问不存在的键会导致KeyError
+# 访问不存在的键会导致 KeyError
filled_dict["four"] # KeyError
-# 用get来避免KeyError
-filled_dict.get("one") # => 1
-filled_dict.get("four") # => None
-# 当键不存在的时候get方法可以返回默认值
+# 用 "get()" 来避免KeyError
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
+# 当键不存在的时候 "get()" 方法可以返回默认值
filled_dict.get("one", 4) # => 1
-filled_dict.get("four", 4) # => 4
+filled_dict.get("four", 4) # => 4
-# setdefault方法只有当键不存在的时候插入新值
-filled_dict.setdefault("five", 5) # filled_dict["five"]设为5
-filled_dict.setdefault("five", 6) # filled_dict["five"]还是5
+# "setdefault()" 方法只有当键不存在的时候插入新值
+filled_dict.setdefault("five", 5) # filled_dict["five"] 设为5
+filled_dict.setdefault("five", 6) # filled_dict["five"] 还是5
# 字典赋值
filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
-filled_dict["four"] = 4 # 另一种赋值方法
+filled_dict["four"] = 4 # 另一种赋值方法
-# 用del删除
-del filled_dict["one"] # 从filled_dict中把one删除
+# 用 del 删除项
+del filled_dict["one"] # 从 filled_dict 中把 one 删除
-# 用set表达集合
+# 用 set 表达集合
empty_set = set()
# 初始化一个集合,语法跟字典相似。
-some_set = {1, 1, 2, 2, 3, 4} # some_set现在是{1, 2, 3, 4}
+some_set = {1, 1, 2, 2, 3, 4} # some_set现在是 {1, 2, 3, 4}
+
+# 类似字典的 keys,set 的元素也必须是不可变类型
+invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list'
+valid_set = {(1,), 1}
# 可以把集合赋值于变量
filled_set = some_set
# 为集合添加元素
-filled_set.add(5) # filled_set现在是{1, 2, 3, 4, 5}
+filled_set.add(5) # filled_set 现在是 {1, 2, 3, 4, 5}
+# set 没有重复的元素
+filled_set.add(5) # filled_set 依然是 {1, 2, 3, 4, 5}
-# & 取交集
+# "&" 取交集
other_set = {3, 4, 5, 6}
filled_set & other_set # => {3, 4, 5}
-# | 取并集
+# "|" 取并集
filled_set | other_set # => {1, 2, 3, 4, 5, 6}
-# - 取补集
+# "-" 取补集
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+# "^" 取异或集(对称差)
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# 判断左边的集合是否是右边集合的超集
+{1, 2} >= {1, 2, 3} # => False
+
+# 判断左边的集合是否是右边集合的子集
+{1, 2} <= {1, 2, 3} # => True
+
# in 测试集合是否包含元素
2 in filled_set # => True
10 in filled_set # => False
+# 单层集合的深度复制
+filled_set = some_set.copy() # filled_set 是 {1, 2, 3, 4, 5}
+filled_set is some_set # => False
####################################################
## 3. 流程控制和迭代器
@@ -304,28 +403,30 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# 先随便定义一个变量
some_var = 5
-# 这是个if语句。注意缩进在Python里是有意义的
-# 印出"some_var比10小"
+# 这是个if语句。注意缩进在Python里是有意义的!
+# 缩进要使用 4 个空格而不是 tabs。
+# 这段代码会打印 "some_var is smaller than 10"
if some_var > 10:
- print("some_var比10大")
-elif some_var < 10: # elif句是可选的
- print("some_var比10小")
-else: # else也是可选的
- print("some_var就是10")
+ print("some_var is totally bigger than 10.")
+elif some_var < 10: # elif 语句是可选的
+ print("some_var is smaller than 10.")
+else: # else 也是可选的
+ print("some_var is indeed 10.")
"""
-用for循环语句遍历列表
+用 for 循环语句遍历列表
打印:
dog is a mammal
cat is a mammal
mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
+ # 你可以使用 format() 格式化字符串并插入值
print("{} is a mammal".format(animal))
"""
-"range(number)"返回数字列表从0到给的数字
+"range(number)" 返回数字列表从 0 到 number 的数字
打印:
0
1
@@ -334,9 +435,41 @@ for animal in ["dog", "cat", "mouse"]:
"""
for i in range(4):
print(i)
+
+"""
+"range(lower, upper)" 会返回一个包含从 lower 到 upper 的数字迭代器
+prints:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print(i)
"""
-while循环直到条件不满足
+"range(lower, upper, step)" 会返回一个,从 lower 到 upper、并且间隔值为 step 的迭代器。
+如果 step 未传入则会使用默认值 1
+prints:
+ 4
+ 6
+"""
+for i in range(4, 8, 2):
+ print(i)
+
+"""
+遍历列表,并且同时返回列表里的每一个元素的索引和数值。
+prints:
+ 0 dog
+ 1 cat
+ 2 mouse
+"""
+animals = ["dog", "cat", "mouse"]
+for i, value in enumerate(animals):
+ print(i, value)
+
+"""
+while 循环直到条件不满足
打印:
0
1
@@ -348,20 +481,51 @@ while x < 4:
print(x)
x += 1 # x = x + 1 的简写
-# 用try/except块处理异常状况
+
+# 用 try/except 块处理异常状况
try:
- # 用raise抛出异常
+ # 用 raise 抛出异常
raise IndexError("This is an index error")
except IndexError as e:
- pass # pass是无操作,但是应该在这里处理错误
+ pass # pass 是无操作,但是应该在这里处理错误
except (TypeError, NameError):
- pass # 可以同时处理不同类的错误
-else: # else语句是可选的,必须在所有的except之后
+ pass # 可以同时处理不同类的错误
+else: # else语句是可选的,必须在所有的except之后
print("All good!") # 只有当try运行完没有错误的时候这句才会运行
+finally: # 在任何情况下都会执行
+ print("We can clean up resources here")
+
+# 你可以使用 with 语句来代替 try/finally 对操作进行结束的操作
+with open("myfile.txt") as f:
+ for line in f:
+ print(line)
+
+# 写入文件
+contents = {"aa": 12, "bb": 21}
+with open("myfile1.txt", "w+") as file:
+ file.write(str(contents)) # 写入字符串到文件
+
+with open("myfile2.txt", "w+") as file:
+ file.write(json.dumps(contents)) # 写入对象到文件
+
+# Reading from a file
+with open("myfile1.txt", "r+") as file:
+ contents = file.read() # 从文件读取字符串
+print(contents)
+# print: {"aa": 12, "bb": 21}
+
+with open("myfile2.txt", "r+") as file:
+ contents = json.load(file) # 从文件读取 json 对象
+print(contents)
+# print: {"aa": 12, "bb": 21}
+
+# Windows 环境调用 open() 读取文件的默认编码为 ANSI,如果需要读取 utf-8 编码的文件,
+# 需要指定 encoding 参数:
+# open("myfile3.txt", "r+", encoding = "utf-8")
-# Python提供一个叫做可迭代(iterable)的基本抽象。一个可迭代对象是可以被当作序列
-# 的对象。比如说上面range返回的对象就是可迭代的。
+# Python 提供一个叫做可迭代 (iterable) 的基本抽象。一个可迭代对象是可以被当作序列
+# 的对象。比如说上面 range 返回的对象就是可迭代的。
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
@@ -378,19 +542,24 @@ our_iterable[1] # 抛出TypeError
our_iterator = iter(our_iterable)
# 迭代器是一个可以记住遍历的位置的对象
-# 用__next__可以取得下一个元素
-our_iterator.__next__() # => "one"
+# 用 "next()" 获得下一个对象
+next(our_iterator) # => "one"
-# 再一次调取__next__时会记得位置
-our_iterator.__next__() # => "two"
-our_iterator.__next__() # => "three"
+# 再一次调取 "next()" 时会记得位置
+next(our_iterator) # => "two"
+next(our_iterator) # => "three"
-# 当迭代器所有元素都取出后,会抛出StopIteration
-our_iterator.__next__() # 抛出StopIteration
+# 当迭代器所有元素都取出后,会抛出 StopIteration
+next(our_iterator) # 抛出 StopIteration
-# 可以用list一次取出迭代器所有的元素
-list(filled_dict.keys()) # => Returns ["one", "two", "three"]
+# 我们可以通过遍历还访问所有的值,实际上,for 内部实现了迭代
+our_iterator = iter(our_iterable)
+for i in our_iterator:
+ print(i) # 依次打印 one, two, three
+# 可以用 list 一次取出迭代器或者可迭代对象所有的元素
+list(filled_dict.keys()) # => 返回 ["one", "two", "three"]
+list(our_iterator) # => 返回 [] 因为迭代的位置被保存了
####################################################
@@ -400,10 +569,10 @@ list(filled_dict.keys()) # => Returns ["one", "two", "three"]
# 用def定义新函数
def add(x, y):
print("x is {} and y is {}".format(x, y))
- return x + y # 用return语句返回
+ return x + y # 用 return 语句返回
# 调用函数
-add(5, 6) # => 印出"x is 5 and y is 6"并且返回11
+add(5, 6) # => 打印 "x is 5 and y is 6" 并且返回 11
# 也可以用关键字参数来调用函数
add(y=6, x=5) # 关键字参数可以用任何顺序
@@ -434,33 +603,43 @@ all_the_args(1, 2, a=3, b=4) prints:
{"a": 3, "b": 4}
"""
-# 调用可变参数函数时可以做跟上面相反的,用*展开序列,用**展开字典。
+# 调用可变参数函数时可以做跟上面相反的,用 * 展开元组,用 ** 展开字典。
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args) # 相当于 all_the_args(1, 2, 3, 4)
all_the_args(**kwargs) # 相当于 all_the_args(a=3, b=4)
all_the_args(*args, **kwargs) # 相当于 all_the_args(1, 2, 3, 4, a=3, b=4)
+# 使用返回多个数值(返回值为元组类型)
+def swap(x, y):
+ return y, x # 用不带括号的元组的格式来返回多个数值
+ # (注意: 括号不需要加,但是也可以加)
+
+x = 1
+y = 2
+x, y = swap(x, y) # => x = 2, y = 1
+# (x, y) = swap(x,y) # 同上,括号不需要加,但是也可以加
+
# 函数作用域
x = 5
def setX(num):
- # 局部作用域的x和全局域的x是不同的
+ # 局部作用域的 x 和全局域的 x 是不同的
x = num # => 43
print (x) # => 43
def setGlobalX(num):
global x
print (x) # => 5
- x = num # 现在全局域的x被赋值
+ x = num # 现在全局域的 x 被赋值
print (x) # => 6
setX(43)
setGlobalX(6)
-# 函数在Python是一等公民
+# 函数在 Python 是一等公民
def create_adder(x):
def adder(y):
return x + y
@@ -470,39 +649,90 @@ add_10 = create_adder(10)
add_10(3) # => 13
# 也有匿名函数
-(lambda x: x > 2)(3) # => True
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
# 内置的高阶函数
-map(add_10, [1, 2, 3]) # => [11, 12, 13]
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+list(map(add_10, [1, 2, 3])) # => [11, 12, 13]
+list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3]
+
+list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7]
# 用列表推导式可以简化映射和过滤。列表推导式的返回值是另一个列表。
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
+# 你也可以用这种方式实现对集合和字典的构建
+{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'}
+{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
+
+
####################################################
-## 5. 类
+## 5. 模块
####################################################
+# 导入模块
+import math
+print(math.sqrt(16)) # => 4.0
+
+# 你可以导入模块中具体的函数
+from math import ceil, floor
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
+
+# 你可以导入模块中的所有的函数
+# 警告: 此操作不推荐
+from math import *
+
+# 你可以对模块名进行简化
+import math as m
+math.sqrt(16) == m.sqrt(16) # => True
+
+# Python 模块实质上是 Python 文件
+# 你可以自己编写自己的模块,然后导入
+# 模块的名称和文件名相同
+
+# 你可以用 "dir()" 查看模块中定义的函数和字段
+import math
+dir(math)
+
+# 当你的脚本文件所在的文件夹也包含了一个名为 math.py 的 Python 文件
+# 这个 math.p 文件会被代替引入,而不是引入 Python 內建模块中的 math
+# 出现这个情况的原因是本地文件夹的引入优先级要比 Python 內建库引入优先级要高
+
+
+####################################################
+## 6. 类
+####################################################
-# 定义一个继承object的类
-class Human(object):
+# 我们使用 "class" 语句来创建类
+class Human:
- # 类属性,被所有此类的实例共用。
+ # 一个类的字段。 这个字段共享给这个类的所有实例。
species = "H. sapiens"
- # 构造方法,当实例被初始化时被调用。注意名字前后的双下划线,这是表明这个属
- # 性或方法对Python有特殊意义,但是允许用户自行定义。你自己取名时不应该用这
- # 种格式。
+ # 构造方法,当实例被初始化时被调用。注意名字前后的双下划线,这是表明这个属性
+ # 或方法对 Python 有特殊意义,但是允许用户自行定义。
+ # 方法(可能是对象或者属性) 类似: __init__, __str__,__repr__ etc
+ # 都是特殊的方法
+ # 你自己取名时不应该用这种格式
def __init__(self, name):
- # Assign the argument to the instance's name attribute
+ # 将参数赋值给实例的 name 字段
self.name = name
- # 实例方法,第一个参数总是self,就是这个实例对象
+ # 初始化属性
+ self._age = 0
+
+ # 实例方法,第一个参数总是self,也就是这个实例对象
def say(self, msg):
- return "{name}: {message}".format(name=self.name, message=msg)
+ print("{name}: {message}".format(name=self.name, message=msg))
+
+ # 另一个实例方法
+ def sing(self):
+ return 'yo... yo... microphone check... one two... one two...'
- # 类方法,被所有此类的实例共用。第一个参数是这个类对象。
+ # 类方法,被所有此类的实例共用。
+ # 第一个参数是这个类对象。
@classmethod
def get_species(cls):
return cls.species
@@ -512,53 +742,225 @@ class Human(object):
def grunt():
return "*grunt*"
+ # property 有点类似 getter
+ # 它把方法 age() 转换为同名并且只读的属性
+ # 通常情况下,可以不需要编写复杂的 getter 和 setter。
+ @property
+ def age(self):
+ return self._age
+
+ # 允许属性被修改
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # 允许属性被删除
+ @age.deleter
+ def age(self):
+ del self._age
+
+# 当 Python 解释器在读取源文件的时候,就会执行文件中所有的代码
+# 对 __name__ 的检查可以保证这块代码只会在执行这个模块是住程序情况下被运行(而不是在引用时运行)
+if __name__ == '__main__':
+ #
+ i = Human(name="Ian")
+ i.say("hi") # "Ian: hi"
+ j = Human("Joel")
+ j.say("hello") # "Joel: hello"
+ # i 和 j 都是 Human 实例化后的对象,换一句话说,它们都是 Human 实例
+
+ # 运行类方法 (classmethod)
+ i.say(i.get_species()) # "Ian: H. sapiens"
+ # 修改共享的类属性
+ Human.species = "H. neanderthalensis"
+ i.say(i.get_species()) # => "Ian: H. neanderthalensis"
+ j.say(j.get_species()) # => "Joel: H. neanderthalensis"
+
+ # 运行静态方法 (staticmethod)
+ print(Human.grunt()) # => "*grunt*"
+
+ # 实例上也可以执行静态方法
+ print(i.grunt()) # => "*grunt*"
+
+ # 更新实例的属性
+ i.age = 42
+ # 访问实例的属性
+ i.say(i.age) # => "Ian: 42"
+ j.say(j.age) # => "Joel: 0"
+ # 删除实例的属性
+ del i.age
+ # i.age # => 这会抛出一个错误: AttributeError
+
+
+####################################################
+## 6.1 类的继承
+####################################################
+
+# 继承机制允许子类可以继承父类上的方法和变量。
+# 我们可以把 Human 类作为一个基础类或者说叫做父类,
+# 然后定义一个名为 Superhero 的子类来继承父类上的比如 "species"、 "name"、 "age" 的属性
+# 和比如 "sing" 、"grunt" 这样的方法,同时,也可以定义它自己独有的属性
+
+# 基于 Python 文件模块化的特点,你可以把这个类放在独立的文件中,比如说,human.py。
+
+# 要从别的文件导入函数,需要使用以下的语句
+# from "filename-without-extension" import "function-or-class"
+
+from human import Human
+
+# 指定父类作为类初始化的参数
+class Superhero(Human):
+
+ # 如果子类需要继承所有父类的定义,并且不需要做任何的修改,
+ # 你可以直接使用 "pass" 关键字(并且不需要其他任何语句)
+ # 但是在这个例子中会被注释掉,以用来生成不一样的子类。
+ # pass
+
+ # 子类可以重写父类定义的字段
+ species = 'Superhuman'
+
+ # 子类会自动的继承父类的构造函数包括它的参数,但同时,子类也可以新增额外的参数或者定义,
+ # 甚至去覆盖父类的方法比如说构造函数。
+ # 这个构造函数从父类 "Human" 上继承了 "name" 参数,同时又新增了 "superpower" 和
+ # "movie" 参数:
+ def __init__(self, name, movie=False,
+ superpowers=["super strength", "bulletproofing"]):
+
+ # 新增额外类的参数
+ self.fictional = True
+ self.movie = movie
+ # 注意可变的默认值,因为默认值是共享的
+ self.superpowers = superpowers
+
+ # "super" 函数让你可以访问父类中被子类重写的方法
+ # 在这个例子中,被重写的是 __init__ 方法
+ # 这个语句是用来运行父类的构造函数:
+ super().__init__(name)
+
+ # 重写父类中的 sing 方法
+ def sing(self):
+ return 'Dun, dun, DUN!'
+
+ # 新增一个额外的方法
+ def boast(self):
+ for power in self.superpowers:
+ print("I wield the power of {pow}!".format(pow=power))
+
+
+if __name__ == '__main__':
+ sup = Superhero(name="Tick")
+
+ # 检查实例类型
+ if isinstance(sup, Human):
+ print('I am human')
+ if type(sup) is Superhero:
+ print('I am a superhero')
-# 构造一个实例
-i = Human(name="Ian")
-print(i.say("hi")) # 印出 "Ian: hi"
+ # 获取方法解析顺序 MRO,MRO 被用于 getattr() 和 super()
+ # 这个字段是动态的,并且可以被修改
+ print(Superhero.__mro__) # => (<class '__main__.Superhero'>,
+ # => <class 'human.Human'>, <class 'object'>)
-j = Human("Joel")
-print(j.say("hello")) # 印出 "Joel: hello"
+ # 调用父类的方法并且使用子类的属性
+ print(sup.get_species()) # => Superhuman
-# 调用一个类方法
-i.get_species() # => "H. sapiens"
+ # 调用被重写的方法
+ print(sup.sing()) # => Dun, dun, DUN!
-# 改一个共用的类属性
-Human.species = "H. neanderthalensis"
-i.get_species() # => "H. neanderthalensis"
-j.get_species() # => "H. neanderthalensis"
+ # 调用 Human 的方法
+ sup.say('Spoon') # => Tick: Spoon
-# 调用静态方法
-Human.grunt() # => "*grunt*"
+ # 调用 Superhero 独有的方法
+ sup.boast() # => I wield the power of super strength!
+ # => I wield the power of bulletproofing!
+
+ # 继承类的字段
+ sup.age = 31
+ print(sup.age) # => 31
+
+ # Superhero 独有的字段
+ print('Am I Oscar eligible? ' + str(sup.movie))
####################################################
-## 6. 模块
+## 6.2 多重继承
####################################################
-# 用import导入模块
-import math
-print(math.sqrt(16)) # => 4.0
+# 定义另一个类
+# bat.py
+class Bat:
-# 也可以从模块中导入个别值
-from math import ceil, floor
-print(ceil(3.7)) # => 4.0
-print(floor(3.7)) # => 3.0
+ species = 'Baty'
-# 可以导入一个模块中所有值
-# 警告:不建议这么做
-from math import *
+ def __init__(self, can_fly=True):
+ self.fly = can_fly
-# 如此缩写模块名字
-import math as m
-math.sqrt(16) == m.sqrt(16) # => True
+ # 这个类同样有 say 的方法
+ def say(self, msg):
+ msg = '... ... ...'
+ return msg
-# Python模块其实就是普通的Python文件。你可以自己写,然后导入,
-# 模块的名字就是文件的名字。
+ # 新增一个独有的方法
+ def sonar(self):
+ return '))) ... ((('
-# 你可以这样列出一个模块里所有的值
-import math
-dir(math)
+if __name__ == '__main__':
+ b = Bat()
+ print(b.say('hello'))
+ print(b.fly)
+
+# 现在我们来定义一个类来同时继承 Superhero 和 Bat
+# superhero.py
+from superhero import Superhero
+from bat import Bat
+
+# 定义 Batman 作为子类,来同时继承 SuperHero 和 Bat
+class Batman(Superhero, Bat):
+
+ def __init__(self, *args, **kwargs):
+ # 通常要继承属性,你必须调用 super:
+ # super(Batman, self).__init__(*args, **kwargs)
+ # 然而在这里我们处理的是多重继承,而 super() 只会返回 MRO 列表的下一个基础类。
+ # 因此,我们需要显式调用初始类的 __init__
+ # *args 和 **kwargs 传递参数时更加清晰整洁,而对于父类而言像是 “剥了一层洋葱”
+ Superhero.__init__(self, 'anonymous', movie=True,
+ superpowers=['Wealthy'], *args, **kwargs)
+ Bat.__init__(self, *args, can_fly=False, **kwargs)
+ # 重写了 name 字段
+ self.name = 'Sad Affleck'
+
+ def sing(self):
+ return 'nan nan nan nan nan batman!'
+
+
+if __name__ == '__main__':
+ sup = Batman()
+
+ # 获取方法解析顺序 MRO,MRO 被用于 getattr() 和 super()
+ # 这个字段是动态的,并且可以被修改
+ print(Batman.__mro__) # => (<class '__main__.Batman'>,
+ # => <class 'superhero.Superhero'>,
+ # => <class 'human.Human'>,
+ # => <class 'bat.Bat'>, <class 'object'>)
+
+ # 调用父类的方法并且使用子类的属性
+ print(sup.get_species()) # => Superhuman
+
+ # 调用被重写的类
+ print(sup.sing()) # => nan nan nan nan nan batman!
+
+ # 调用 Human 上的方法,(之所以是 Human 而不是 Bat),是因为继承顺序起了作用
+ sup.say('I agree') # => Sad Affleck: I agree
+
+ # 调用仅存在于第二个继承的父类的方法
+ print(sup.sonar()) # => ))) ... (((
+
+ # 继承类的属性
+ sup.age = 100
+ print(sup.age) # => 100
+
+ # 从第二个类上继承字段,并且其默认值被重写
+ print('Can I fly? ' + str(sup.fly)) # => Can I fly? False
####################################################
@@ -583,6 +985,10 @@ for i in double_numbers(range_):
print(i)
if i >= 30:
break
+# 你也可以把一个生成器推导直接转换为列表
+values = (-x for x in [1,2,3,4,5])
+gen_to_list = list(values)
+print(gen_to_list) # => [-1, -2, -3, -4, -5]
# 装饰器(decorators)
@@ -612,18 +1018,27 @@ print(say()) # Can you buy me a beer?
print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
```
-## 想继续学吗?
-### 线上免费材料(英文)
-* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
-* [Dive Into Python](http://www.diveintopython.net/)
-* [Ideas for Python Projects](http://pythonpracticeprojects.com)
+## 想继续学吗?
-* [The Official Docs](http://docs.python.org/3/)
-* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Module of the Week](http://pymotw.com/3/)
-* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+### 在线免费材料(英文)
+
+* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com/)
+* [Ideas for Python Projects](http://pythonpracticeprojects.com/)
+* [The Official Docs](https://docs.python.org/3/)
+* [Hitchhiker’s Guide to Python](https://docs.python-guide.org/en/latest/)
+* [Python Course](https://www.python-course.eu/)
+* [Free Interactive Python Course](http://www.kikodo.io/)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
+* [30 Python Language Features and Tricks You May Not Know About](https://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
+* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/)
+* [Python 3 Computer Science Circles](https://cscircles.cemc.uwaterloo.ca/)
+* [Dive Into Python 3](https://www.diveintopython3.net/index.html)
+* [A Crash Course in Python for Scientists](https://nbviewer.jupyter.org/gist/anonymous/5924718)
+* [Python Tutorial for Intermediates](https://pythonbasics.org/)
+* [Build a Desktop App with Python](https://pythonpyqt.com/)
### 书籍(也是英文)
diff --git a/zh-cn/raylib-cn.html.markdown b/zh-cn/raylib-cn.html.markdown
new file mode 100644
index 00000000..c88aa91e
--- /dev/null
+++ b/zh-cn/raylib-cn.html.markdown
@@ -0,0 +1,147 @@
+---
+category: tool
+tool: raylib
+lang: zh-cn
+filename: learnraylib-cn.c
+contributors:
+ - ["Nikolas Wipper", "https://notnik.cc"]
+translators:
+ - ["lzw-723", "https://github.com/lzw-723"]
+---
+
+**raylib** 是一个跨平台、易用的图形库,围绕OpenGL 1.1、2.1、3.3和OpenGL ES 2.0构建。
+虽然它是用C语言编写的,却有超过50种不同语言的绑定。本教程将使用C语言。
+更确切地说,是C99。
+
+```c
+#include <raylib.h>
+
+int main(void)
+{
+ const int screenWidth = 800;
+ const int screenHeight = 450;
+
+ // 在初始化raylib之前,可以设置标志位
+ SetConfigFlags(FLAG_MSAA_4X_HINT | FLAG_VSYNC_HINT);
+
+ // raylib并不要求我们存储任何实例结构
+ // 目前raylib一次只能处理一个窗口
+ InitWindow(screenWidth, screenHeight, "MyWindow");
+
+ // 设置我们的游戏以每秒60帧的速度运行
+ SetTargetFPS(60);
+
+ // 设置一个关闭窗口的键。
+ //可以是0,表示没有键
+ SetExitKey(KEY_DELETE);
+
+ // raylib定义了两种类型的相机。Camera3D和Camera2D
+ // Camera是Camera3D的一个类型化定义
+ Camera camera = {
+ .position = {0.0f, 0.0f, 0.0f},
+ .target = {0.0f, 0.0f, 1.0f},
+ .up = {0.0f, 1.0f, 0.0f},
+ .fovy = 70.0f,
+ .type = CAMERA_PERSPECTIVE
+ };
+
+
+ // raylib支持加载各种不同的文件格式的模型、动画、图像和声音。
+ Model myModel = LoadModel("my_model.obj");
+ Font someFont = LoadFont("some_font.ttf");
+
+ // 创建一个100x100的渲染纹理
+ RenderTexture renderTexture = LoadRenderTexture(100, 100);
+
+ // WindowShouldClose方法检查用户是否正在关闭窗口。
+ // 可能用的是快捷方式、窗口控制或之前设置的关闭窗口键
+ while (!WindowShouldClose())
+ {
+
+ // BeginDrawing方法要在任何绘图操作之前被调用。
+ BeginDrawing();
+ {
+
+ // 为背景设定某种颜色
+ ClearBackground(BLACK);
+
+ if (IsKeyDown(KEY_SPACE))
+ DrawCircle(400, 400, 30, GREEN);
+
+ // 简单地绘制文本
+ DrawText("Congrats! You created your first window!",
+ 190, // x
+ 200, // y
+ 20, // 字体大小
+ LIGHTGRAY
+ );
+
+ // 大多数函数都有几个版本
+ // 通常后缀为Ex, Pro, V
+ // 或者是Rec、Wires(仅适用于3D)、Lines(仅适用于2D)。
+ DrawTextEx(someFont,
+ "Text in another font",
+ (Vector2) {10, 10},
+ 20, // 字体大小
+ 2, // 间距
+ LIGHTGRAY);
+
+ // 绘制3D时需要,有2D的等价方法
+ BeginMode3D(camera);
+ {
+
+ DrawCube((Vector3) {0.0f, 0.0f, 3.0f},
+ 1.0f, 1.0f, 1.0f, RED);
+
+ // 绘图时的白色色调将保持原来的颜色
+ DrawModel(myModel, (Vector3) {0.0f, 0.0f, 3.0f},
+ 1.0f, // 缩放
+ WHITE);
+
+ }
+ // 结束3D模式,这样就可以再次普通绘图
+ EndMode3D();
+
+ // 开始在渲染纹理上绘图
+ BeginTextureMode(renderTexture);
+ {
+
+ // 它的行为与刚才调用的`BeginDrawing()`方法相同
+
+ ClearBackground(RAYWHITE);
+
+ BeginMode3D(camera);
+ {
+
+ DrawGrid(10, // Slices
+ 1.0f // 间距
+ );
+
+ }
+ EndMode3D();
+
+ }
+ EndTextureMode();
+
+ // 渲染有Texture2D字段的纹理
+ DrawTexture(renderTexture.texture, 40, 378, BLUE);
+
+ }
+ EndDrawing();
+ }
+
+ // 卸载已载入的对象
+ UnloadFont(someFont);
+ UnloadModel(myModel);
+
+ // 关闭窗口和OpenGL上下文
+ CloseWindow();
+
+ return 0;
+}
+
+```
+
+## 延伸阅读
+raylib有一些[不错的例子](https://www.raylib.com/examples.html)
+如果你不喜欢C语言你也可以看看[raylib的其他语言绑定](https://github.com/raysan5/raylib/blob/master/BINDINGS.md)
diff --git a/zh-cn/rust-cn.html.markdown b/zh-cn/rust-cn.html.markdown
index b77c9c38..6bed1650 100644
--- a/zh-cn/rust-cn.html.markdown
+++ b/zh-cn/rust-cn.html.markdown
@@ -1,5 +1,5 @@
---
-language: rust
+language: Rust
contributors:
- ["P1start", "http://p1start.github.io/"]
translators:
diff --git a/zh-cn/sql.html.markdown b/zh-cn/sql-cn.html.markdown
index 9d430bd1..9d430bd1 100644
--- a/zh-cn/sql.html.markdown
+++ b/zh-cn/sql-cn.html.markdown