summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--CHICKEN.html.markdown519
-rw-r--r--HTML-fr.html.markdown115
-rw-r--r--bash.html.markdown10
-rw-r--r--binary-search.html.markdown2
-rw-r--r--c.html.markdown7
-rw-r--r--clojure.html.markdown13
-rw-r--r--cs-cz/go.html.markdown431
-rw-r--r--csharp.html.markdown86
-rw-r--r--css.html.markdown52
-rw-r--r--de-de/asciidoc-de.html.markdown125
-rw-r--r--de-de/d-de.html.markdown4
-rw-r--r--de-de/go-de.html.markdown4
-rw-r--r--de-de/html-de.html.markdown120
-rw-r--r--de-de/ruby-de.html.markdown33
-rw-r--r--de-de/rust-de.html.markdown2
-rw-r--r--de-de/swift-de.html.markdown591
-rw-r--r--dynamic-programming.html.markdown37
-rw-r--r--elixir.html.markdown8
-rw-r--r--elm.html.markdown1
-rw-r--r--es-es/asymptotic-notation-es.html.markdown1
-rw-r--r--es-es/binary-search-es.html.markdown68
-rw-r--r--es-es/dynamic-programming-es.html.markdown54
-rw-r--r--es-es/edn-es.html.markdown111
-rw-r--r--es-es/html-es.html.markdown122
-rw-r--r--es-es/jquery-es.html.markdown141
-rw-r--r--es-es/kotlin-es.html.markdown361
-rw-r--r--es-es/php-composer-es.html.markdown176
-rw-r--r--es-es/racket-es.html.markdown683
-rw-r--r--es-es/ruby-ecosystem-es.html.markdown157
-rw-r--r--es-es/sass-es.html.markdown585
-rw-r--r--es-es/swift-es.html.markdown88
-rw-r--r--es-es/tmux.html.markdown242
-rw-r--r--es-es/vim-es.html.markdown242
-rw-r--r--fr-fr/HTML-fr.html.markdown2
-rw-r--r--fr-fr/clojure-fr.html.markdown18
-rw-r--r--fr-fr/rust-fr.html.markdown26
-rw-r--r--git.html.markdown2
-rw-r--r--html.html.markdown120
-rw-r--r--id-id/asciidoc-id.html.markdown125
-rw-r--r--id-id/coffeescript-id.html.markdown106
-rw-r--r--id-id/json-id.html.markdown2
-rw-r--r--id-id/markdown.html.markdown1
-rw-r--r--id-id/pyqt-id.html.markdown83
-rw-r--r--id-id/smallbasic-id.html.markdown133
-rw-r--r--it-it/bash-it.html.markdown89
-rw-r--r--it-it/rust-it.html.markdown3
-rw-r--r--java.html.markdown70
-rw-r--r--jquery.html.markdown138
-rw-r--r--kotlin.html.markdown68
-rw-r--r--latex.html.markdown105
-rw-r--r--less.html.markdown59
-rw-r--r--logtalk.html.markdown543
-rw-r--r--markdown.html.markdown4
-rw-r--r--meteor.html.markdown567
-rw-r--r--perl6.html.markdown367
-rw-r--r--pl-pl/ruby-pl.html.markdown2
-rw-r--r--pt-br/amd.html.markdown2
-rw-r--r--pt-br/binary-search-pt.html.markdown77
-rw-r--r--pt-br/c-pt.html.markdown2
-rw-r--r--pt-br/clojure-macros-pt.html.markdown2
-rw-r--r--pt-br/dynamic-programming-pt.html.markdown76
-rw-r--r--pt-br/elixir.html.markdown1
-rw-r--r--pt-br/elm-pt.html.markdown384
-rw-r--r--pt-br/git-pt.html.markdown2
-rw-r--r--pt-br/julia-pt.html.markdown748
-rw-r--r--pt-br/python3-pt.html.markdown2
-rw-r--r--pt-br/self-pt.html.markdown165
-rw-r--r--pt-br/swift-pt.html.markdown2
-rw-r--r--pt-br/vim-pt.html.markdown239
-rw-r--r--pt-pt/git-pt.html.markdown2
-rw-r--r--pt-pt/swift.html.markdown2
-rw-r--r--pyqt.html.markdown82
-rw-r--r--python3.html.markdown28
-rw-r--r--qt.html.markdown16
-rw-r--r--ru-ru/binary-search-ru.html.markdown64
-rw-r--r--ru-ru/c-ru.html.markdown9
-rw-r--r--ru-ru/javascript-ru.html.markdown1
-rw-r--r--ru-ru/php-ru.html.markdown35
-rw-r--r--ru-ru/qt-ru.html.markdown158
-rw-r--r--ru-ru/swift-ru.html.markdown264
-rw-r--r--rust-pt.html.markdown332
-rw-r--r--rust.html.markdown2
-rw-r--r--sass.html.markdown10
-rw-r--r--sk-sk/LearnGit-sk.txt208
-rw-r--r--sk-sk/ruby.html.markdown553
-rw-r--r--solidity.html.markdown4
-rw-r--r--swift.html.markdown72
-rw-r--r--tmux.html.markdown10
-rwxr-xr-xtoml.html.markdown274
-rw-r--r--uk-ua/json-ua.html.markdown24
-rw-r--r--zh-cn/c++-cn.html.markdown4
-rw-r--r--zh-cn/ruby-cn.html.markdown401
-rw-r--r--zh-cn/rust-cn.html.markdown2
-rw-r--r--zh-cn/swift-cn.html.markdown2
-rw-r--r--zh-cn/visualbasic-cn.html.markdown2
95 files changed, 11145 insertions, 942 deletions
diff --git a/CHICKEN.html.markdown b/CHICKEN.html.markdown
new file mode 100644
index 00000000..c6a3a914
--- /dev/null
+++ b/CHICKEN.html.markdown
@@ -0,0 +1,519 @@
+---
+language: "CHICKEN"
+filename: CHICKEN.scm
+contributors:
+ - ["Diwakar Wagle", "https://github.com/deewakar"]
+---
+
+
+CHICKEN is an implementation of Scheme programming language that can
+compile Scheme programs to C code as well as interpret them. CHICKEN
+supports RSR5 and RSR7 (work in progress) standards and many extensions.
+
+
+```scheme
+;; #!/usr/bin/env csi -s
+
+;; Run the CHICKEN REPL in the commandline as follows :
+;; $ csi
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; 0. Syntax
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Single line comments start with a semicolon
+
+#| Block comments
+ can span multiple lines and...
+ #| can be nested
+ |#
+|#
+
+;; S-expression comments are used to comment out expressions
+#; (display "nothing") ; discard this expression
+
+;; CHICKEN has two fundamental pieces of syntax: Atoms and S-expressions
+;; an atom is something that evaluates to itself
+;; all builtin data types viz. numbers, chars, booleans, strings etc. are atoms
+;; Furthermore an atom can be a symbol, an identifier, a keyword, a procedure
+;; or the empty list (also called null)
+'athing ;; => athing
+'+ ;; => +
++ ;; => <procedure C_plus>
+
+;; S-expressions (short for symbolic expressions) consists of one or more atoms
+(quote +) ;; => + ; another way of writing '+
+(+ 1 2 3) ;; => 6 ; this S-expression evaluates to a function call
+'(+ 1 2 3) ;; => (+ 1 2 3) ; evaluates to a list
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; 1. Primitive Datatypes and Operators
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Numbers
+99999999999999999999 ;; integers
+#b1010 ;; binary ; => 10
+#o10 ;; octal ; => 8
+#x8ded ;; hexadecimal ; => 36333
+3.14 ;; real
+6.02e+23
+3/4 ;; rational
+
+;;Characters and Strings
+#\A ;; A char
+"Hello, World!" ;; strings are fixed-length arrays of characters
+
+;; Booleans
+#t ;; true
+#f ;; false
+
+;; Function call is written as (f x y z ...)
+;; where f is a function and x,y,z, ... are arguments
+(print "Hello, World!") ;; => Hello, World!
+;; formatted output
+(printf "Hello, ~a.\n" "World") ;; => Hello, World.
+
+;; print commandline arguments
+(map print (command-line-arguments))
+
+(list 'foo 'bar 'baz) ;; => (foo bar baz)
+(string-append "pine" "apple") ;; => "pineapple"
+(string-ref "tapioca" 3) ;; => #\i;; character 'i' is at index 3
+(string->list "CHICKEN") ;; => (#\C #\H #\I #\C #\K #\E #\N)
+(string->intersperse '("1" "2") ":") ;; => "1:2"
+(string-split "1:2:3" ":") ;; => ("1" "2" "3")
+
+
+;; Predicates are special functions that return boolean values
+(atom? #t) ;; => #t
+
+(symbol? #t) ;; => #f
+
+(symbol? '+) ;; => #t
+
+(procedure? +) ;; => #t
+
+(pair? '(1 2)) ;; => #t
+
+(pair? '(1 2 . 3)) ;; => #t
+
+(pair? '()) ;; => #f
+
+(list? '()) ;; => #t
+
+
+;; Some arithmetic operations
+
+(+ 1 1) ;; => 2
+(- 8 1) ;; => 7
+(* 10 2) ;; => 20
+(expt 2 3) ;; => 8
+(remainder 5 2) ;; => 1
+(/ 35 5) ;; => 7
+(/ 1 3) ;; => 0.333333333333333
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; 2. Variables
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; You can create variables with define
+;; A variable name can use any character except: ()[]{}",'`;#\
+(define myvar 5)
+myvar ;; => 5
+
+;; Alias to a procedure
+(define ** expt)
+(** 2 3) ;; => 8
+
+;; Accessing an undefined variable raises an exception
+s ;; => Error: unbound variable: s
+
+;; Local binding
+(let ((me "Bob"))
+ (print me)) ;; => Bob
+
+(print me) ;; => Error: unbound variable: me
+
+;; Assign a new value to previously defined variable
+(set! myvar 10)
+myvar ;; => 10
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; 3. Collections
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Pairs
+;; 'cons' constructs pairs,
+;; 'car' extracts the first element, 'cdr' extracts the rest of the elements
+(cons 'subject 'verb) ;; => '(subject . verb)
+(car (cons 'subject 'verb)) ;; => subject
+(cdr (cons 'subject 'verb)) ;; => verb
+
+;; Lists
+;; cons creates a new list if the second item is a list
+(cons 0 '()) ;; => (0)
+(cons 1 (cons 2 (cons 3 '()))) ;; => (1 2 3)
+;; 'list' is a convenience variadic constructor for lists
+(list 1 2 3) ;; => (1 2 3)
+
+
+;; Use 'append' to append lists together
+(append '(1 2) '(3 4)) ;; => (1 2 3 4)
+
+;; Some basic operations on lists
+(map add1 '(1 2 3)) ;; => (2 3 4)
+(reverse '(1 3 4 7)) ;; => (7 4 3 1)
+(sort '(11 22 33 44) >) ;; => (44 33 22 11)
+
+(define days '(SUN MON FRI))
+(list-ref days 1) ;; => MON
+(set! (list-ref days 1) 'TUE)
+days ;; => (SUN TUE FRI)
+
+;; Vectors
+;; Vectors are heterogeneous structures whose elements are indexed by integers
+;; A Vector typically occupies less space than a list of the same length
+;; Random access of an element in a vector is faster than in a list
+#(1 2 3) ;; => #(1 2 3) ;; literal syntax
+(vector 'a 'b 'c) ;; => #(a b c)
+(vector? #(1 2 3)) ;; => #t
+(vector-length #(1 (2) "a")) ;; => 3
+(vector-ref #(1 (2) (3 3)) 2);; => (3 3)
+
+(define vec #(1 2 3))
+(vector-set! vec 2 4)
+vec ;; => #(1 2 4)
+
+;; Vectors can be created from lists and vice-verca
+(vector->list #(1 2 4)) ;; => '(1 2 4)
+(list->vector '(a b c)) ;; => #(a b c)
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; 4. Functions
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Use 'lambda' to create functions.
+;; A function always returns the value of its last expression
+(lambda () "Hello World") ;; => #<procedure (?)>
+
+;; Use extra parens around function definition to execute
+((lambda () "Hello World")) ;; => Hello World ;; argument list is empty
+
+;; A function with an argument
+((lambda (x) (* x x)) 3) ;; => 9
+;; A function with two arguments
+((lambda (x y) (* x y)) 2 3) ;; => 6
+
+;; assign a function to a variable
+(define sqr (lambda (x) (* x x)))
+sqr ;; => #<procedure (sqr x)>
+(sqr 3) ;; => 9
+
+;; We can shorten this using the function definition syntactic sugar
+(define (sqr x) (* x x))
+(sqr 3) ;; => 9
+
+;; We can redefine existing procedures
+(foldl cons '() '(1 2 3 4 5)) ;; => (((((() . 1) . 2) . 3) . 4) . 5)
+(define (foldl func accu alist)
+ (if (null? alist)
+ accu
+ (foldl func (func (car alist) accu) (cdr alist))))
+
+(foldl cons '() '(1 2 3 4 5)) ;; => (5 4 3 2 1)
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; 5. Equality
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; For numbers use '='
+(= 3 3.0) ;; => #t
+(= 2 1) ;; => #f
+
+;; 'eq?' returns #t if two arguments refer to the same object in memory
+;; In other words, it's a simple pointer comparision.
+(eq? '() '()) ;; => #t ;; there's only one empty list in memory
+(eq? (list 3) (list 3)) ;; => #f ;; not the same object
+(eq? 'yes 'yes) ;; => #t
+(eq? 3 3) ;; => #t ;; don't do this even if it works in this case
+(eq? 3 3.0) ;; => #f ;; it's better to use '=' for number comparisions
+(eq? "Hello" "Hello") ;; => #f
+
+;; 'eqv?' is same as 'eq?' all datatypes except numbers and characters
+(eqv? 3 3.0) ;; => #f
+(eqv? (expt 2 3) (expt 2 3)) ;; => #t
+(eqv? 'yes 'yes) ;; => #t
+
+;; 'equal?' recursively compares the contents of pairs, vectors, and strings,
+;; applying eqv? on other objects such as numbers and symbols.
+;; A rule of thumb is that objects are generally equal? if they print the same.
+
+(equal? '(1 2 3) '(1 2 3)) ;; => #t
+(equal? #(a b c) #(a b c)) ;; => #t
+(equal? 'a 'a) ;; => #t
+(equal? "abc" "abc") ;; => #f
+
+;; In Summary:
+;; eq? tests if objects are identical
+;; eqv? tests if objects are operationally equivalent
+;; equal? tests if objects have same structure and contents
+
+;; Comparing strings for equality
+(string=? "Hello" "Hello") ;; => #t
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; 6. Control Flow
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Conditionals
+(if #t ;; test expression
+ "True" ;; then expression
+ "False") ;; else expression
+ ;; => "True"
+
+(if (> 3 2)
+ "yes"
+ "no") ;; => "yes"
+
+;; In conditionals, all values that are not '#f' are treated as true.
+;; 0, '(), #() "" , are all true values
+(if 0
+ "0 is not false"
+ "0 is false") ;; => "0 is not false"
+
+;; 'cond' chains a series of tests and returns as soon as it encounters a true condition
+;; 'cond' can be used to simulate 'if/elseif/else' statements
+(cond ((> 2 2) "not true so don't return this")
+ ((< 2 5) "true, so return this")
+ (else "returning default")) ;; => "true, so return this"
+
+
+;; A case expression is evaluated as follows:
+;; The key is evaluated and compared with each datum in sense of 'eqv?',
+;; The corresponding clause in the matching datum is evaluated and returned as result
+(case (* 2 3) ;; the key is 6
+ ((2 3 5 7) 'prime) ;; datum 1
+ ((1 4 6 8) 'composite)) ;; datum 2; matched!
+ ;; => composite
+
+;; case with else clause
+(case (car '(c d))
+ ((a e i o u) 'vowel)
+ ((w y) 'semivowel)
+ (else 'consonant)) ;; => consonant
+
+;; Boolean expressions
+;; 'and' returns the first expression that evaluates to #f
+;; otherwise, it returns the result of the last expression
+(and #t #f (= 2 2.0)) ;; => #f
+(and (< 2 5) (> 2 0) "0 < 2 < 5") ;; => "0 < 2 < 5"
+
+;; 'or' returns the first expression that evaluates to #t
+;; otherwise the result of the last expression is returned
+(or #f #t #f) ;; => #t
+(or #f #f #f) ;; => #f
+
+;; 'when' is like 'if' without the else expression
+(when (positive? 5) "I'm positive") ;; => "I'm positive"
+
+;; 'unless' is equivalent to (when (not <test>) <expr>)
+(unless (null? '(1 2 3)) "not null") ;; => "not null"
+
+
+;; Loops
+;; loops can be created with the help of tail-recursions
+(define (loop count)
+ (unless (= count 0)
+ (print "hello")
+ (loop (sub1 count))))
+(loop 4) ;; => hello, hello ...
+
+;; Or with a named let
+(let loop ((i 0) (limit 5))
+ (when (< i limit)
+ (printf "i = ~a\n" i)
+ (loop (add1 i) limit))) ;; => i = 0, i = 1....
+
+;; 'do' is another iteration construct
+;; It initializes a set of variables and updates them in each iteration
+;; A final expression is evaluated after the exit condition is met
+(do ((x 0 (add1 x ))) ;; initialize x = 0 and add 1 in each iteration
+ ((= x 10) (print "done")) ;; exit condition and final expression
+ (print x)) ;; command to execute in each step
+ ;; => 0,1,2,3....9,done
+
+;; Iteration over lists
+(for-each (lambda (a) (print (* a a)))
+ '(3 5 7)) ;; => 9, 25, 49
+
+;; 'map' is like for-each but returns a list
+(map add1 '(11 22 33)) ;; => (12 23 34)
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; 7. Extensions
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; The CHICKEN core is very minimal, but additional features are provided by library extensions known as Eggs.
+;; You can install Eggs with 'chicken-install <eggname>' command.
+
+;; 'numbers' egg provides support for full numeric tower.
+(require-extension numbers)
+;; complex numbers
+3+4i ;; => 3+2i
+;; Supports fractions without falling back to inexact flonums
+1/3 ;; => 1/3
+;; provides support for large integers through bignums
+(expt 9 20) ;; => 12157665459056928801
+;; And other 'extended' functions
+(log 10 (exp 1)) ;; => 2.30258509299405
+(numerator 2/3) ;; => 2
+
+;; 'utf8' provides unicode support
+(require-extension utf8)
+"\u03BBx:(\u03BC\u0251.\u0251\u2192\u0251).xx" ;; => "λx:(μɑ.ɑ→ɑ).xx"
+
+;; 'posix' provides file I/O and lots of other services for unix-like operating systems
+;; Some of the functions are not available in Windows system,
+;; See http://wiki.call-cc.org/man/4/Unit%20posix for more details
+
+;; Open a file to append, open "write only" and create file if it does not exist
+(define outfn (file-open "chicken-hen.txt" (+ open/append open/wronly open/creat)))
+;; write some text to the file
+(file-write outfn "Did chicken came before hen?")
+;; close the file
+(file-close outfn)
+;; Open the file "read only"
+(define infn (file-open "chicken-hen.txt" open/rdonly))
+;; read some text from the file
+(file-read infn 30) ;; => ("Did chicken came before hen? ", 28)
+(file-close infn)
+
+;; CHICKEN also supports SRFI (Scheme Requests For Implementation) extensions
+;; See 'http://srfi.schemers.org/srfi-implementers.html" to see srfi's supported by CHICKEN
+(require-extension srfi-1) ;; list library
+(filter odd? '(1 2 3 4 5 6 7)) ;; => (1 3 5 7)
+(count even? '(1 2 3 4 5)) ;; => 2
+(take '(12 24 36 48 60) 3) ;; => (12 24 36)
+(drop '(12 24 36 48 60) 2) ;; => (36 48 60)
+(circular-list 'z 'q) ;; => z q z q ...
+
+(require-extension srfi-13) ;; string library
+(string-reverse "pan") ;; => "nap"
+(string-index "Turkey" #\k) ;; => 3
+(string-every char-upper-case? "CHICKEN") ;; => #t
+(string-join '("foo" "bar" "baz") ":") ;; => "foo:bar:baz"
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; 8. Macros
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; A 'for .. in ..' iteration like python, for lists
+(define-syntax for
+ (syntax-rules (in)
+ ((for elem in alist body ...)
+ (for-each (lambda (elem) body ...) alist))))
+
+(for x in '(2 4 8 16)
+ (print x)) ;; => 2, 4, 8, 16
+
+(for chr in (string->list "PENCHANT")
+ (print chr)) ;; => P, E, N, C, H, A, N, T
+
+;; While loop
+(define-syntax while
+ (syntax-rules ()
+ ((while cond body ...)
+ (let loop ()
+ (when cond
+ body ...
+ (loop))))))
+
+(let ((str "PENCHANT") (i 0))
+ (while (< i (string-length str)) ;; while (condition)
+ (print (string-ref str i)) ;; body
+ (set! i (add1 i))))
+ ;; => P, E, N, C, H, A, N, T
+
+;; Advanced Syntax-Rules Primer -> http://petrofsky.org/src/primer.txt
+;; Macro system in chicken -> http://lists.gnu.org/archive/html/chicken-users/2008-04/msg00013.html
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; 9. Modules
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Also See http://wiki.call-cc.org/man/4/Modules
+
+;; The 'test' module exports a value named 'hello' and a macro named 'greet'
+(module test (hello greet)
+ (import scheme)
+
+ (define-syntax greet
+ (syntax-rules ()
+ ((_ whom)
+ (begin
+ (display "Hello, ")
+ (display whom)
+ (display " !\n") ) ) ) )
+
+ (define (hello)
+ (greet "world") ) )
+
+;; we can define our modules in a separate file (say test.scm) and load them to the interpreter with
+;; (load "test.scm")
+
+;; import the module
+(import test)
+(hello) ;; => Hello, world !
+(greet "schemers") ;; => Hello, schemers !
+
+;; We can compile the module files in to shared libraries by using following command,
+;; csc -s test.scm
+;; (load "test.so")
+
+;; Functors
+;; Functors are high level modules that can be parameterized by other modules
+;; Following functor requires another module named 'M' that provides a funtion called 'multiply'
+;; The functor itself exports a generic function 'square'
+(functor (squaring-functor (M (multiply))) (square)
+ (import scheme M)
+ (define (square x) (multiply x x)))
+
+;; Module 'nums' can be passed as a parameter to 'squaring-functor'
+(module nums (multiply)
+ (import scheme) ;; predefined modules
+ (define (multiply x y) (* x y)))
+;; the final module can be imported and used in our program
+(module number-squarer = (squaring-functor nums))
+
+(import number-squarer)
+(square 3) ;; => 9
+
+;; We can instantiate the functor for other inputs
+;; Here's another example module that can be passed to squaring-functor
+(module stars (multiply)
+ (import chicken scheme) ;; chicken module for the 'use' keyword
+ (use srfi-1) ;; we can use external libraries in our module
+ (define (multiply x y)
+ (list-tabulate x (lambda _ (list-tabulate y (lambda _ '*))))))
+(module star-squarer = (squaring-functor stars))
+
+(import star-squarer)
+(square 3) ;; => ((* * *)(* * *)(* * *))
+
+```
+## Further Reading
+* [CHICKEN User's Manual](http://wiki.call-cc.org/man/4/The%20User%27s%20Manual).
+* [RSR5 standards](http://www.schemers.org/Documents/Standards/R5RS)
+
+
+## Extra Info
+
+* [For programmers of other languages](http://wiki.call-cc.org/chicken-for-programmers-of-other-languages)
+* [Compare CHICKEN syntax with other languages](http://plr.sourceforge.net/cgi-bin/plr/launch.py)
diff --git a/HTML-fr.html.markdown b/HTML-fr.html.markdown
deleted file mode 100644
index fdde9107..00000000
--- a/HTML-fr.html.markdown
+++ /dev/null
@@ -1,115 +0,0 @@
----
-language: html
-filename: learnhtml-fr.html
-contributors:
- - ["Christophe THOMAS", "https://github.com/WinChris"]
-lang: fr-fr
----
-HTML signifie HyperText Markup Language.
-C'est un langage (format de fichiers) qui permet d'écrire des pages internet.
-C’est un langage de balisage, il nous permet d'écrire des pages HTML au moyen de balises (Markup, en anglais).
-Les fichiers HTML sont en réalité de simple fichier texte.
-Qu'est-ce que le balisage ? C'est une façon de hiérarchiser ses données en les entourant par une balise ouvrante et une balise fermante.
-Ce balisage sert à donner une signification au texte ainsi entouré.
-Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parlons de HTML5.
-
-**NOTE :** Vous pouvez tester les différentes balises que nous allons voir au fur et à mesure du tutoriel sur des sites comme [codepen](http://codepen.io/pen/) afin de voir les résultats, comprendre, et vous familiariser avec le langage.
-Cet article porte principalement sur la syntaxe et quelques astuces.
-
-
-```HTML
-<!-- Les commentaires sont entouré comme cette ligne! -->
-
-<!-- #################### Les balises #################### -->
-
-<!-- Voici un exemple de fichier HTML que nous allons analyser -->
-<!-- Venez voir ce que ça donne -->
-
-<!doctype html>
- <html>
- <head>
- <title>Mon Site</title>
- </head>
- <body>
- <h1>Hello, world!</h1>
- <a href = "http://codepen.io/anon/pen/xwjLbZ">Venez voir ce que ça donne</a>
- <p>Ceci est un paragraphe</p>
- <p>Ceci est un autre paragraphe</p>
- <ul>
- <li>Ceci est un item d'une liste non ordonnée (liste à puces)</li>
- <li>Ceci est un autre item</li>
- <li>Et ceci est le dernier item de la liste</li>
- </ul>
- </body>
- </html>
-
-<!-- Un fichier HTML débute toujours par indiquer au navigateur que notre page est faite en HTML -->
-
-<!doctype html>
-
-<!-- Après ça on commence par ouvrir une balise <html> -->
-<html>
-</html>
-<!-- Et puis on la referme à la fin du fichier avec </html> -->
-<!-- après cette balise de fin, plus rien ne doit apparaître. -->
-
-<!-- À l'intérieur (entre la balise ouvrant et fermante <html></html>), on trouve : -->
-
-<!-- Un entête (<head> en anglais ; il faut le refermer avec </head>) -->
-<!-- L'entête contient des descriptions et informations annexes qui ne sont pas affichées : se sont les métadonnées -->
-
-<head>
- <title>Mon Site</title><!-- La balise <title> permet d'indiquer au navigateur le titre à afficher dans la barre de l'onglet de la fenêtre -->
-</head>
-
-<!-- Après la balise <head>, on trouve la balise <body> -->
-<!-- Pour le moment, rien n'est encore affiché dans la fenêtre du navigateur. -->
-<!-- Il faut ensuite remplir le corps (balise <body>) avec du contenu -->
-
-<body>
- <h1>Hello, world!</h1> <!-- La balise h1 permet de structurer le texte, c'est un titre -->
- <!-- Il exite différents sous-titres à <h1> qui sont hiérarchisés du plus important (h2) au plus précis (h6) -->
- <a href = "http://codepen.io/anon/pen/xwjLbZ">Venez voir ce que ça donne</a> <!-- Lien vers la source cible indiqué dans href="" -->
- <p>Ceci est un paragraphe </p> <!-- La balise <p> permet d'inclure du texte à la page html -->
- <p>Ceci est un autre paragraphe</p>
- <ul> <!-- La balise <ul> permet d'introduire une liste à puces -->
- <!-- Si on souhaite une liste ordonnée : <ol> liste numérotée, 1. pour le premier élément, 2. pour le second, etc -->
- <li>Ceci est un item d'une liste non ordonnée (liste à puces)</li>
- <li>Ceci est un autre item</li>
- <li>Et ceci est le dernier item de la liste</li>
- </ul>
-</body>
-
-<!-- Voilà comment créer un fichier HTML simple -->
-
-<!-- Mais il est possible d'ajouter encore des balises plus spécifiques -->
-
-<!-- Pour insérer une image -->
-<img src="http://i.imgur.com/XWG0O.gif"/> <!-- On indique la source de l'image dans src="" -->
-<!-- La source peut-être un URL ou encore la destination d'un fichier de votre ordinateur -->
-
-<!-- Il est possible de réaliser des tableaux également -->
-
-<table> <!-- On ouvre la balise <table> -->
- <tr> <!-- <tr> permet de créer une ligne -->
- <th>First Header</th> <!-- <th> permet de créer un titre au tableau -->
- <th>Second Header</th>
- </tr>
- <tr>
- <td>Première ligne, première cellule</td> <!-- <td> permet de créer une cellule -->
- <td>Première ligne, deuxième cellule</td>
- </tr>
- <tr>
- <td>Deuxième ligne, première cellule</td>
- <td>Deuxième ligne, deuxième cellule</td>
- </tr>
-</table>
-
-## Utilisation
-
-Le HTML s'écrit dans des fichiers `.html`.
-
-## En savoir plus
-
-* [Tutoriel HTML](http://slaout.linux62.org/html_css/html.html)
-* [W3School](http://www.w3schools.com/html/html_intro.asp)
diff --git a/bash.html.markdown b/bash.html.markdown
index b1a14bdb..271ef62c 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -23,8 +23,6 @@ Nearly all examples below can be a part of a shell script or executed directly i
[Read more here.](http://www.gnu.org/software/bash/manual/bashref.html)
-Another recommened link: [The Command Line Crash Course](http://cli.learncodethehardway.org/book/)
-
```bash
#!/bin/bash
# First line of the script is shebang which tells the system how to execute
@@ -98,10 +96,10 @@ echo "Script's arguments separated into different variables: $1 $2..."
# Now that we know how to echo and use variables,
# let's learn some of the other basics of bash!
-# Getting our current directory is available through the command `pwd`.
+# Our current directory is available through the command `pwd`.
# `pwd` stands for "print working directory".
# We can also use the builtin variable `$PWD`.
-# Observer that the following are equivalent:
+# Observe that the following are equivalent:
echo "I'm in $(pwd)" # execs `pwd` and interpolates output
echo "I'm in $PWD" # interpolates the variable
@@ -353,8 +351,8 @@ fgrep "foobar" file.txt
trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM
# `sudo` is used to perform commands as the superuser
-$NAME1=$(whoami)
-$NAME2=$(sudo whoami)
+NAME1=$(whoami)
+NAME2=$(sudo whoami)
echo "Was $NAME1, then became more powerful $NAME2"
# Read Bash shell builtins documentation with the bash 'help' builtin:
diff --git a/binary-search.html.markdown b/binary-search.html.markdown
index 92df4875..ce436b44 100644
--- a/binary-search.html.markdown
+++ b/binary-search.html.markdown
@@ -9,7 +9,7 @@ contributors:
## Why Binary Search?
-Searching is one of the prime problems in the domain of Computer Science.Today there are more than 1 trillion searches per year, and we need algorithms that can do that very fastly. Binary search is one of the fundamental algorithms in computer science. In order to explore it, we’ll first build up a theoretical backbone, then use that to implement the algorithm properly.
+Searching is one of the prime problems in the domain of Computer Science. Today there are more than 1 trillion searches per year, and we need algorithms that can do that very fastly. Binary search is one of the fundamental algorithms in computer science. In order to explore it, we’ll first build up a theoretical backbone, then use that to implement the algorithm properly.
## Introduction
diff --git a/c.html.markdown b/c.html.markdown
index 92f07fe2..ae87ca08 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -236,11 +236,9 @@ int main (int argc, char** argv)
z = (e > f) ? e : f; // => 10 "if e > f return e, else return f."
// Increment and decrement operators:
- char *s = "ILoveC";
int j = 0;
- s[j++]; // => "I". Returns the j-th item of s THEN increments value of j.
- j = 0;
- s[++j]; // => "L". Increments value of j THEN returns j-th value of s.
+ int s = j++; // Return j THEN increase j. (s = 0, j = 1)
+ s = ++j; // Increase j THEN return j. (s = 2, j = 2)
// same with j-- and --j
// Bitwise operators!
@@ -513,6 +511,7 @@ void str_reverse(char *str_in)
str_in[len - ii - 1] = tmp;
}
}
+//NOTE: string.h header file needs to be included to use strlen()
/*
char c[] = "This is a test.";
diff --git a/clojure.html.markdown b/clojure.html.markdown
index 58e835c9..bf9258f7 100644
--- a/clojure.html.markdown
+++ b/clojure.html.markdown
@@ -289,6 +289,19 @@ keymap ; => {:a 1, :b 2, :c 3}
(into [])) ;=> (into [] (filter odd? (map inc (range 10)))
; Result: [1 3 5 7 9]
+; When you are in a situation where you want more freedom as where to
+; put the result of previous data transformations in an
+; expression, you can use the as-> macro. With it, you can assign a
+; specific name to transformations' output ans use it as a
+; placeholder in your chained expressions:
+
+(as-> [1 2 3] input
+ (map inc input);=> You can use last transform's output at the last position
+ (nth input 4) ;=> and at the second position, in the same expression
+ (conj [4 5 6] input [8 9 10])) ;=> or in the middle !
+
+
+
; Modules
;;;;;;;;;;;;;;;
diff --git a/cs-cz/go.html.markdown b/cs-cz/go.html.markdown
new file mode 100644
index 00000000..36217414
--- /dev/null
+++ b/cs-cz/go.html.markdown
@@ -0,0 +1,431 @@
+---
+name: Go
+category: language
+language: Go
+filename: learngo-cs.go
+lang: cs-cz
+contributors:
+ - ["Sonia Keys", "https://github.com/soniakeys"]
+ - ["Christopher Bess", "https://github.com/cbess"]
+ - ["Jesse Johnson", "https://github.com/holocronweaver"]
+ - ["Quint Guvernator", "https://github.com/qguv"]
+ - ["Jose Donizetti", "https://github.com/josedonizetti"]
+ - ["Alexej Friesen", "https://github.com/heyalexej"]
+ - ["Clayton Walker", "https://github.com/cwalk"]
+translators:
+ - ["Ondra Linek", "https://github.com/defectus/"]
+---
+
+Jazyk Go byl vytvořen, jelikož bylo potřeba dokončit práci. Není to poslední
+trend ve světě počítačové vědy, ale je to nejrychlejší a nejnovější způsob,
+jak řešit realné problémy.
+
+Go používá známé koncepty imperativních jazyků se statickým typováním.
+Rychle se kompiluje a také rychle běží. Přidává snadno pochopitelnou
+podporu konkurenčnosti, což umožňuje využít výhody multi-core procesorů a
+jazyk také obsahuje utility, které pomáhají se škálovatelným programováním.
+
+Go má již v základu vynikající knihovnu a je s ním spojená nadšená komunita.
+
+```go
+// Jednořádkový komentář
+/* Několika
+ řádkový komentář */
+
+// Každý zdroják začíná deklarací balíčku (package)
+// Main je vyhrazené jméno, které označuje spustitelný soubor,
+// narozdíl od knihovny
+package main
+
+// Importní deklarace říkají, které knihovny budou použity v tomto souboru.
+import (
+ "fmt" // Obsahuje formátovací funkce a tisk na konzolu
+ "io/ioutil" // Vstupně/výstupní funkce
+ m "math" // Odkaz na knihovnu math (matematické funkce) pod zkratkou m
+ "net/http" // Podpora http protokolu, klient i server.
+ "strconv" // Konverze řetězců, např. na čísla a zpět.
+)
+
+// Definice funkce. Funkce main je zvláštní, je to vstupní bod do programu.
+// Ať se vám to líbí, nebo ne, Go používá složené závorky
+func main() {
+ // Println vypisuje na stdout.
+ // Musí být kvalifikováno jménem svého balíčko, ftm.
+ fmt.Println("Hello world!")
+
+ // Zavoláme další funkci
+ svetPoHello()
+}
+
+// Funkce mají své parametry v závorkách
+// Pokud funkce nemá parametry, tak musíme stejně závorky uvést.
+func svetPoHello() {
+ var x int // Deklarace proměnné. Proměnné musí být před použitím deklarované
+ x = 3 // Přiřazení hodnoty do proměnné
+ // Existuje "krátká" deklarace := kde se typ proměnné odvodí,
+ // proměnná vytvoří a přiřadí se jí hodnota
+ y := 4
+ sum, prod := naucSeNasobit(x, y) // Funkce mohou vracet více hodnot
+ fmt.Println("sum:", sum, "prod:", prod) // Jednoduchý výstup
+ naucSeTypy() // < y minut je za námi, je čas učit se víc!
+}
+
+/* <- začátek mnohořádkového komentáře
+Funkce mohou mít parametry a (několik) návratových hodnot.
+V tomto případě jsou `x`, `y` parametry a `sum`, `prod` jsou návratové hodnoty.
+Všiměte si, že `x` a `sum` jsou typu `int`.
+*/
+func naucSeNasobit(x, y int) (sum, prod int) {
+ return x + y, x * y // Vracíme dvě hodnoty
+}
+
+// zabudované typy a literáty.
+func naucSeTypy() {
+ // Krátká deklarace většinou funguje
+ str := "Learn Go!" // typ řetězec.
+
+ s2 := `"surový" literát řetězce
+může obsahovat nové řádky` // Opět typ řetězec.
+
+ // Můžeme použít ne ASCII znaky, Go používá UTF-8.
+ g := 'Σ' // type runa, což je alias na int32 a ukládá se do něj znak UTF-8
+
+ f := 3.14195 // float64, je IEEE-754 64-bit číslem s plovoucí čárkou.
+ c := 3 + 4i // complex128, interně uložené jako dva float64.
+
+ // takhle vypadá var s inicializací
+ var u uint = 7 // Číslo bez znaménka, jehož velikost záleží na implementaci,
+ // stejně jako int
+ var pi float32 = 22. / 7
+
+ // takto se převádí typy za pomoci krátké syntaxe
+ n := byte('\n') // byte je jiné jméno pro uint8.
+
+ // Pole mají fixní délku, které se určuje v době kompilace.
+ var a4 [4]int // Pole 4 intů, všechny nastaveny na 0.
+ a3 := [...]int{3, 1, 5} // Pole nastaveno na tři hodnoty
+ // elementy mají hodntu 3, 1 a 5
+
+ // Slicy mají dynamickou velikost. Pole i slacy mají své výhody,
+ // ale většinou se používají slicy.
+ s3 := []int{4, 5, 9} // Podobně jako a3, ale není tu výpustka.
+ s4 := make([]int, 4) // Alokuj slice 4 intů, všechny nastaveny na 0.
+ var d2 [][]float64 // Deklarace slicu, nic se nealokuje.
+ bs := []byte("a slice") // Přetypování na slice
+
+ // Protože jsou dynamické, můžeme ke slicům přidávat za běhu
+ // Přidat ke slicu můžeme pomocí zabudované funkce append().
+ // Prvním parametrem je slice, návratová hodnota je aktualizovaný slice.
+ s := []int{1, 2, 3} // Výsledkem je slice se 3 elementy.
+ s = append(s, 4, 5, 6) // Přidány další 3 elementy. Slice má teď velikost 6.
+ fmt.Println(s) // Slice má hodnoty [1 2 3 4 5 6]
+
+ // Pokud chceme k poli přičíst jiné pole, můžeme předat referenci na slice,
+ // nebo jeho literát a přidat výpustku, čímž se slicu "rozbalí" a přidá se k
+ // původnímu slicu.
+ s = append(s, []int{7, 8, 9}...) // druhým parametrem je literát slicu.
+ fmt.Println(s) // slice má teď hodnoty [1 2 3 4 5 6 7 8 9]
+
+ p, q := naucSePraciSPameti() // Deklarujeme p a q jako typ pointer na int.
+ fmt.Println(*p, *q) // * dereferencuje pointer. Tím se vypíší dva inty.
+
+ // Mapy jsou dynamické rostoucí asociativní pole, jako hashmapa, nebo slovník
+ // (dictionary) v jiných jazycích
+ m := map[string]int{"tri": 3, "ctyri": 4}
+ m["jedna"] = 1
+
+ // Napoužité proměnné jsou v Go chybou.
+ // Použijte podtržítko, abychom proměnno "použili".
+ _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs
+ // Výpis promenné se počítá jako použití.
+ fmt.Println(s, c, a4, s3, d2, m)
+
+ naucSeVetveníProgramu() // Zpátky do běhu.
+}
+
+// narozdíl od jiných jazyků, v Go je možné mít pojmenované návratové hodnoty.
+// Tak můžeme vracet hodnoty z mnoha míst funkce, aniž bychom uváděli hodnoty v
+// return.
+func naucSePojmenovaneNavraty(x, y int) (z int) {
+ z = x * y
+ return // z je zde implicitní, jelikož bylo pojmenováno.
+}
+
+// Go má garbage collector. Používá pointery, ale neumožňuje jejich aritmetiku.
+// Můžete tedy udělat chybu použitím nil odkazu, ale ne jeho posunutím.
+func naucSePraciSPameti() (p, q *int) {
+ // Pojmenované parametry p a q mají typ odkaz na int.
+ p = new(int) // Zabudované funkce new alokuje paměť.
+ // Alokované místo pro int má hodnotu 0 a p už není nil.
+ s := make([]int, 20) // Alokujeme paměť pro 20 intů.
+ s[3] = 7 // Jednu z nich nastavíme.
+ r := -2 // Deklarujeme další lokální proměnnou.
+ return &s[3], &r // a vezmeme si jejich odkaz pomocí &.
+}
+
+func narocnyVypocet() float64 {
+ return m.Exp(10)
+}
+
+func naucSeVetveníProgramu() {
+ // Výraz if vyžaduje složené závorky, ale podmínka nemusí být v závorkách.
+ if true {
+ fmt.Println("říkal jsme ti to")
+ }
+ // Formátování je standardizované pomocí utility "go fmt".
+ if false {
+ // posměšek.
+ } else {
+ // úšklebek.
+ }
+ // Použij switch, když chceš zřetězit if.
+ x := 42.0
+ switch x {
+ case 0:
+ case 1:
+ case 42:
+ // jednotlivé case nepropadávají. není potřeba "break"
+ case 43:
+ // nedosažitelné, jelikož už bylo ošetřeno.
+ default:
+ // implicitní větev je nepovinná.
+ }
+ // Stejně jako if, for (smyčka) nepoužívá závorky.
+ // Proměnné definované ve for jsou lokální vůči smyčce.
+ for x := 0; x < 3; x++ { // ++ je výrazem.
+ fmt.Println("iterace", x)
+ }
+ // zde je x == 42.
+
+ // For je jediná smyčka v Go, ale má několik tvarů.
+ for { // Nekonečná smyčka
+ break // Dělám si legraci
+ continue // Sem se nedostaneme
+ }
+
+ // Můžete použít klíčové slovo range pro iteraci nad mapami, poli, slicy,
+ // řetězci a kanály.
+ // range vrací jednu (kanál) nebo dvě hodnoty (pole, slice, řetězec a mapa).
+ for key, value := range map[string]int{"jedna": 1, "dva": 2, "tri": 3} {
+ // pro každý pár (klíč a hodnota) je vypiš
+ fmt.Printf("klíč=%s, hodnota=%d\n", key, value)
+ }
+
+ // stejně jako for, := v podmínce if přiřazuje hodnotu
+ // nejříve nastavíme y a pak otestujeme, jestli je y větší než x.
+ if y := narocnyVypocet(); y > x {
+ x = y
+ }
+ // Funkční literáty jsou tzv. uzávěry (closure)
+ xBig := func() bool {
+ return x > 10000 // odkazuje na x deklarované ve příkladu použití switch
+ }
+ x = 99999
+ fmt.Println("xBig:", xBig()) // true
+ x = 1.3e3 // To udělá z x == 1300
+ fmt.Println("xBig:", xBig()) // teď už false.
+
+ // Dále je možné funkční literáty definovat a volat na místě jako parametr
+ // funkce, dokavaď:
+ // a) funkční literát je okamžitě volán pomocí (),
+ // b) výsledek se shoduje s očekávaným typem.
+ fmt.Println("Sečte + vynásobí dvě čísla: ",
+ func(a, b int) int {
+ return (a + b) * 2
+ }(10, 2)) // Voláno s parametry 10 a 2
+ // => Sečti a vynásob dvě čísla. 24
+
+ // Když to potřebujete, tak to milujete
+ goto miluji
+miluji:
+
+ naučteSeFunkčníFactory() // funkce vracející funkce je zábava(3)(3)
+ naučteSeDefer() // malá zajížďka k důležitému klíčovému slovu.
+ naučteSeInterfacy() // Přichází dobré věci!
+}
+
+func naučteSeFunkčníFactory() {
+ // Následující dvě varianty jsou stejné, ale ta druhá je praktičtější
+ fmt.Println(větaFactory("létní")("Hezký", "den!"))
+
+ d := větaFactory("letní")
+ fmt.Println(d("Hezký", "den!"))
+ fmt.Println(d("Líný", "odpoledne!"))
+}
+
+// Dekorátory jsou běžné v jiných jazycích. To samé můžete udělat v Go
+// pomocí parameterizovatelných funkčních literátů.
+func větaFactory(můjŘetězec string) func(před, po string) string {
+ return func(před, po string) string {
+ return fmt.Sprintf("%s %s %s", před, můjŘetězec, po) // nový řetězec
+ }
+}
+
+func naučteSeDefer() (ok bool) {
+ // Odloží (defer) příkazy na okamžik těsně před opuštěním funkce.
+ // tedy poslední se provede první
+ defer fmt.Println("odložené příkazy jsou zpravovaná v LIFO pořadí.")
+ defer fmt.Println("\nProto je tato řádka vytištěna první")
+ // Defer se běžně používá k zavírání souborů a tím se zajistí, že soubor
+ // bude po ukončení funkce zavřen.
+ return true
+}
+
+// definuje typ interfacu s jednou metodou String()
+type Stringer interface {
+ String() string
+}
+
+// Definuje pár jako strukturu se dvěma poli typu int x a y.
+type pár struct {
+ x, y int
+}
+
+// Definuje method pár. Pár tedy implementuje interface Stringer.
+func (p pár) String() string { // p je tu nazýváno "Receiver" - přijímač
+ // Sprintf je další veřejná funkce z balíčku fmt.
+ // Pomocí tečky přistupujeme k polím proměnné p
+ return fmt.Sprintf("(%d, %d)", p.x, p.y)
+}
+
+func naučteSeInterfacy() {
+ // Složené závorky jsou "strukturální literáty. Vyhodnotí a inicializuje
+ // strukturu. Syntaxe := deklaruje a inicializuje strukturu.
+ p := pár{3, 4}
+ fmt.Println(p.String()) // Volá metodu String na p typu pár.
+ var i Stringer // Deklaruje i jako proměnné typu Stringer.
+ i = p // Toto je možné, jelikož oba implementují Stringer
+ // zavolá metodu String(( typu Stringer a vytiskne to samé jako předchozí.
+ fmt.Println(i.String())
+
+ // Funkce ve balíčku fmt volají metodu String, když zjišťují, jak se má typ
+ // vytisknout.
+ fmt.Println(p) // Vytiskne to samé, jelikož Println volá String().
+ fmt.Println(i) // Ten samý výstup.
+
+ naučSeVariabilníParametry("super", "učit se", "tady!")
+}
+
+// Funcke mohou mít proměnlivé množství parametrů.
+func naučSeVariabilníParametry(mojeŘetězce ...interface{}) {
+ // Iterujeme přes všechny parametry
+ // Potržítku tu slouží k ignorování indexu v poli.
+ for _, param := range mojeŘetězce {
+ fmt.Println("parameter:", param)
+ }
+
+ // Použít variadický parametr jako variadický parametr, nikoliv pole.
+ fmt.Println("parametery:", fmt.Sprintln(mojeŘetězce...))
+
+ naučSeOšetřovatChyby()
+}
+
+func naučSeOšetřovatChyby() {
+ // ", ok" je metodou na zjištění, jestli něco fungovalo, nebo ne.
+ m := map[int]string{3: "tri", 4: "ctyri"}
+ if x, ok := m[1]; !ok { // ok bude false, jelikož 1 není v mapě.
+ fmt.Println("není tu jedna")
+ } else {
+ fmt.Print(x) // x by bylo tou hodnotou, pokud by bylo v mapě.
+ }
+ // hodnota error není jen znamením OK, ale může říct více o chybě.
+ if _, err := strconv.Atoi("ne-int"); err != nil { // _ hodnotu zahodíme
+ // vytiskne 'strconv.ParseInt: parsing "non-int": invalid syntax'
+ fmt.Println(err)
+ }
+ // Znovu si povíme o interfacech, zatím se podíváme na
+ naučSeKonkurenčnost()
+}
+
+// c je kanál, způsob, jak bezpečně komunikovat v konkurenčním prostředí.
+func zvyš(i int, c chan int) {
+ c <- i + 1 // <- znamená "pošli" a posílá data do kanálu na levé straně.
+}
+
+// Použijeme funkci zvyš a konkurečně budeme zvyšovat čísla.
+func naučSeKonkurenčnost() {
+ // funkci make jsme již použili na slicy. make alokuje a inicializuje slidy,
+ // mapy a kanály.
+ c := make(chan int)
+ // nastartuj tři konkurenční go-rutiny. Čísla se budou zvyšovat
+ // pravděpodobně paralelně pokud je počítač takto nakonfigurován.
+ // Všechny tři zapisují do toho samého kanálu.
+ go zvyš(0, c) // go je výraz pro start nové go-rutiny.
+ go zvyš(10, c)
+ go zvyš(-805, c)
+ // Přečteme si tři výsledky a vytiskeneme je..
+ // Nemůžeme říct, v jakém pořadí výsledky přijdou!
+ fmt.Println(<-c, <-c, <-c) // pokud je kanál na pravo, jedná se o "přijmi".
+
+ cs := make(chan string) // Další kanál, tentokrát pro řetězce.
+ ccs := make(chan chan string) // Kanál kanálu řetězců.
+ go func() { c <- 84 }() // Start nové go-rutiny na posílání hodnot.
+ go func() { cs <- "wordy" }() // To samé s cs.
+ // Select má syntaxi jako switch, ale vztahuje se k operacím nad kanály.
+ // Náhodně vybere jeden case, který je připraven na komunikaci.
+ select {
+ case i := <-c: // Přijatá hodnota může být přiřazena proměnné.
+ fmt.Printf("je to typ %T", i)
+ case <-cs: // nebo může být zahozena
+ fmt.Println("je to řetězec")
+ case <-ccs: // prázdný kanál, nepřipraven ke komunikaci.
+ fmt.Println("to se nestane.")
+ }
+ // V tomto okamžiku máme hodnotu buď z kanálu c nabo cs. Jedna nebo druhá
+ // nastartovaná go-rutina skončila a další zůstane blokovaná.
+
+ naučSeProgramovatWeb() // Go to umí. A vy to chcete taky.
+}
+
+// jen jedna funkce z balíčku http spustí web server.
+func naučSeProgramovatWeb() {
+
+ // První parametr ListenAndServe je TCP adresa, kde poslouchat.
+ // Druhý parametr je handler, implementující interace http.Handler.
+ go func() {
+ err := http.ListenAndServe(":8080", pár{})
+ fmt.Println(err) // neignoruj chyby
+ }()
+
+ requestServer()
+}
+
+// Umožní typ pár stát se http tím, že implementuje její jedinou metodu
+// ServeHTTP.
+func (p pár) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ // Servíruj data metodou http.ResponseWriter
+ w.Write([]byte("Naučil ses Go za y minut!"))
+}
+
+func requestServer() {
+ resp, err := http.Get("http://localhost:8080")
+ fmt.Println(err)
+ defer resp.Body.Close()
+ body, err := ioutil.ReadAll(resp.Body)
+ fmt.Printf("\nWebserver řekl: `%s`", string(body))
+}
+```
+
+## Kam dále
+
+Vše hlavní o Go se nachází na [oficiálních stránkách go](http://golang.org/).
+Tam najdete tutoriály, interaktivní konzolu a mnoho materiálu ke čtení.
+Kromě úvodu, [dokumenty](https://golang.org/doc/) tam obsahují jak psát čistý kód v Go
+popis balíčků (package), dokumentaci příkazové řádky a historii releasů.
+
+Také doporučujeme přečíst si definici jazyka. Je čtivá a překvapivě krátká. Tedy alespoň proti
+jiným současným jazyků.
+
+Pokud si chcete pohrát s Go, tak navštivte [hřiště Go](https://play.golang.org/p/r46YvCu-XX).
+Můžete tam spouštět programy s prohlížeče. Také můžete [https://play.golang.org](https://play.golang.org) použít jako
+[REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop), kde si v rychlosti vyzkoušíte věci, bez instalace Go.
+
+Na vašem knižním seznamu, by neměly chybět [zdrojáky stadardní knihovny](http://golang.org/src/pkg/).
+Důkladně popisuje a dokumentuje Go, styl zápisu Go a Go idiomy. Pokud kliknete na [dokumentaci](http://golang.org/pkg/)
+tak se podíváte na dokumentaci.
+
+Dalším dobrým zdrojem informací je [Go v ukázkách](https://gobyexample.com/).
+
+Go mobile přidává podporu pro Android a iOS. Můžete s ním psát nativní mobilní aplikace nebo knihovny, které půjdou
+spustit přes Javu (pro Android), nebo Objective-C (pro iOS). Navštivte [web Go Mobile](https://github.com/golang/go/wiki/Mobile)
+pro více informací.
diff --git a/csharp.html.markdown b/csharp.html.markdown
index 4c9e8411..442700a6 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -459,7 +459,7 @@ on a new line! ""Wow!"", the masses cried";
if (i > limit/2) yield break;
yield return i;
}
- }
+ }
public static void OtherInterestingFeatures()
{
@@ -547,28 +547,22 @@ on a new line! ""Wow!"", the masses cried";
// PARALLEL FRAMEWORK
// http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
- var websites = new string[] {
- "http://www.google.com", "http://www.reddit.com",
- "http://www.shaunmccarthy.com"
- };
- var responses = new Dictionary<string, string>();
- // Will spin up separate threads for each request, and join on them
- // before going to the next step!
- Parallel.ForEach(websites,
- new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads
- website =>
- {
- // Do something that takes a long time on the file
- using (var r = WebRequest.Create(new Uri(website)).GetResponse())
+ var words = new List<string> {"dog", "cat", "horse", "pony"};
+
+ Parallel.ForEach(words,
+ new ParallelOptions() { MaxDegreeOfParallelism = 4 },
+ word =>
{
- responses[website] = r.ContentType;
+ Console.WriteLine(word);
}
- });
+ );
- // This won't happen till after all requests have been completed
- foreach (var key in responses.Keys)
- Console.WriteLine("{0}:{1}", key, responses[key]);
+ //Running this will produce different outputs
+ //since each thread finishes at different times.
+ //Some example outputs are:
+ //cat dog horse pony
+ //dog horse pony cat
// DYNAMIC OBJECTS (great for working with other languages)
dynamic student = new ExpandoObject();
@@ -677,6 +671,10 @@ on a new line! ""Wow!"", the masses cried";
int _speed; // Everything is private by default: Only accessible from within this class.
// can also use keyword private
public string Name { get; set; }
+
+ // Properties also have a special syntax for when you want a readonly property
+ // that simply returns the result of an expression
+ public string LongName => Name + " " + _speed + " speed";
// Enum is a value type that consists of a set of named constants
// It is really just mapping a name to a value (an int, unless specified otherwise).
@@ -948,7 +946,7 @@ on a new line! ""Wow!"", the masses cried";
A.A2();
}
}
-
+
// String interpolation by prefixing the string with $
// and wrapping the expression you want to interpolate with { braces }
public class Rectangle
@@ -956,7 +954,7 @@ on a new line! ""Wow!"", the masses cried";
public int Length { get; set; }
public int Width { get; set; }
}
-
+
class Program
{
static void Main(string[] args)
@@ -965,7 +963,49 @@ on a new line! ""Wow!"", the masses cried";
Console.WriteLine($"The length is {rect.Length} and the width is {rect.Width}");
}
}
-
+
+ // New C# 6 features
+ class GlassBall : IJumpable, IBreakable
+ {
+ // Autoproperty initializers
+ public int Damage { get; private set; } = 0;
+
+ // Autoproperty initializers on getter-only properties
+ public string Name { get; } = "Glass ball";
+
+ // Getter-only autoproperty that is initialized in constructor
+ public string GenieName { get; }
+
+ public GlassBall(string genieName = null)
+ {
+ GenieName = genieName;
+ }
+
+ public void Jump(int meters)
+ {
+ if (meters < 0)
+ // New nameof() expression; compiler will check that the identifier exists
+ // nameof(x) == "x"
+ // Prevents e.g. parameter names changing but not updated in error messages
+ throw new ArgumentException("Cannot jump negative amount!", nameof(meters));
+
+ Damage += meters;
+ }
+
+ // Expression-bodied properties ...
+ public bool Broken
+ => Damage > 100;
+
+ // ... and methods
+ public override string ToString()
+ // Interpolated string
+ => $"{Name}. Damage taken: {Damage}";
+
+ public string SummonGenie()
+ // Null-conditional operators
+ // x?.y will return null immediately if x is null; y is not evaluated
+ => GenieName?.ToUpper();
+ }
} // End Namespace
```
@@ -973,6 +1013,8 @@ on a new line! ""Wow!"", the masses cried";
* Attributes
* async/await, pragma directives
+ * Exception filters
+ * `using static`
* Web Development
* ASP.NET MVC & WebApi (new)
* ASP.NET Web Forms (old)
diff --git a/css.html.markdown b/css.html.markdown
index fc07fce4..1c569d04 100644
--- a/css.html.markdown
+++ b/css.html.markdown
@@ -6,8 +6,8 @@ contributors:
- ["Geoffrey Liu", "https://github.com/g-liu"]
- ["Connor Shea", "https://github.com/connorshea"]
- ["Deepanshu Utkarsh", "https://github.com/duci9y"]
+ - ["Brett Taylor", "https://github.com/glutnix"]
- ["Tyler Mumford", "https://tylermumford.com"]
-
filename: learncss.css
---
@@ -193,10 +193,10 @@ selector {
Save a CSS stylesheet with the extension `.css`.
-```xml
+```html
<!-- You need to include the css file in your page's <head>. This is the
recommended method. Refer to http://stackoverflow.com/questions/8284365 -->
-<link rel='stylesheet' type='text/css' href='path/to/style.css' />
+<link rel='stylesheet' type='text/css' href='path/to/style.css'>
<!-- You can also include some CSS inline in your markup. -->
<style>
@@ -241,8 +241,8 @@ p { property: value !important; }
and the following markup:
-```xml
-<p style='/*F*/ property:value;' class='class1 class2' attr='value' />
+```html
+<p style='/*F*/ property:value;' class='class1 class2' attr='value'>
```
The precedence of style is as follows. Remember, the precedence is for each
@@ -259,6 +259,48 @@ recommended that you avoid its usage.
* `B` is next.
* `D` is the last one.
+## Media Queries
+
+CSS Media Queries are a feature in CSS 3 which allows you to specify when certain CSS rules should be applied, such as when printed, or when on a screen with certain dimensions or pixel density. They do not add to the selector's specifity.
+
+```css
+/* A rule that will be used on all devices */
+h1 {
+ font-size: 2em;
+ color: white;
+ background-color: black;
+}
+
+/* change the h1 to use less ink on a printer */
+@media print {
+ h1 {
+ color: black;
+ background-color: white;
+ }
+}
+
+/* make the font bigger when shown on a screen at least 480px wide */
+@media screen and (min-width: 480px) {
+ h1 {
+ font-size: 3em;
+ font-weight: normal;
+ }
+}
+```
+
+Media queries can include these features:
+`width`, `height`, `device-width`, `device-height`, `orientation`, `aspect-ratio`, `device-aspect-ratio`, `color`, `color-index`, `monochrome`, `resolution`, `scan`, `grid`. Most of these features can be prefixed with `min-` or `max-`.
+
+The `resolution` feature is not supported by older devices, instead use `device-pixel-ratio`.
+
+Many smartphones and tablets will attempt to render the page as if it were on a desktop unless you provide a `viewport` meta-tag.
+
+```html
+<head>
+ <meta name="viewport" content="width=device-width; initial-scale=1.0">
+</head>
+```
+
## Compatibility
Most of the features in CSS 2 (and many in CSS 3) are available across all
diff --git a/de-de/asciidoc-de.html.markdown b/de-de/asciidoc-de.html.markdown
new file mode 100644
index 00000000..1a8cdd5a
--- /dev/null
+++ b/de-de/asciidoc-de.html.markdown
@@ -0,0 +1,125 @@
+---
+language: asciidoc
+contributors:
+ - ["Ryan Mavilia", "http://unoriginality.rocks/"]
+translators:
+ - ["Dennis Keller", "https://github.com/denniskeller"]
+filename: asciidoc-de.md
+lang: de-de
+---
+
+AsciiDoc ist eine Auszeichnungssprache ähnlich zu Markdown. Sie kann für alles verwendet werden von Büchern zu Blogs. Erfunden wurde sie 2002 von Stuart Rackham. Die Sprache ist simpel aber sie ermöglicht eine große Anzahl an Anpassungen.
+
+Kopfzeile des Dokuments
+
+Kopfzeilen sind optional und dürfen keine Leerzeilen besitzen. Sie müssen mindestens eine Leerzeile vom Inhalt versetzt sein.
+
+Nur Titel
+
+```
+= Dokumententitel
+
+Erster Satz des Dokuments.
+```
+
+Titel und Autor
+
+```
+= Dokumententitel
+Vorname Nachname <Vorname.Nachname@learnxinyminutes.com>
+
+Start des Dokuments.
+```
+
+Mehrere Autoren
+
+```
+= Dokumententitel
+John Doe <john@go.com>; Jane Doe<jane@yo.com>; Black Beard <beardy@pirate.com>
+
+Starte ein Dokument mit mehreren Autoren.
+```
+
+Revisionszeile (benötigt eine Autorzeile)
+
+```
+= Dokumententitel V1
+Potato Man <chip@crunchy.com>
+v1.0, 2016-01-13
+
+Dieser Artikel über Chips wird Spaß machen.
+```
+
+Absätze
+
+```
+Du musst nichts besonderes machen für Absätze.
+
+Füge eine Leerzeile zwischen zwei Absätze, um sie zu trennen.
+
+Um eine Leerzeile zu erhalten musst du ein +
+ergänzen und du erhälst einen Umbruch!
+```
+
+Textformatierung
+
+```
+_Unterstriche erstellt Kursivschrift_
+*Sternchen für Fett gedruckt*
+*_Kombinieren für extra Spaß_*
+`Benutze Ticks um Monospace zu signalisieren`
+`*Fett gedruckter Monospace*`
+```
+
+Abteilungstitel
+
+```
+= Level 0 (sollte nur in der Kopfzeile verwendet werden)
+
+== Level 1 <h2>
+
+=== Level 2 <h3>
+
+==== Level 3 <h4>
+
+===== Level 4 <h5>
+
+====== Level 5 <h6>
+
+======= Level 6 <h7>
+
+```
+
+Listen
+
+Um eine Aufzählung zu erstellen verwendest du Sternchen.
+
+```
+* foo
+* bar
+* baz
+```
+
+Um eine nummerierte Liste zu erstellen verwendest du Punkte.
+
+```
+. item 1
+. item 2
+. item 3
+```
+
+Um Listen zu verschachteln musst du zusätzliche Sternchen und Punkte hinzufügen. Dies ist bis zu fünf Mal möglich.
+
+```
+* foo 1
+** foo 2
+*** foo 3
+**** foo 4
+***** foo 5
+
+. foo 1
+.. foo 2
+... foo 3
+.... foo 4
+..... foo 5
+```
diff --git a/de-de/d-de.html.markdown b/de-de/d-de.html.markdown
index ae036d70..2b0b38dd 100644
--- a/de-de/d-de.html.markdown
+++ b/de-de/d-de.html.markdown
@@ -50,12 +50,14 @@ void main() {
} while(n > 0);
// For und while sind ja schön und gut aber D bevorzugt foreach
- // .. erstellt eine spanne von zahlen, exklusive dem Ende
+ // Die '..' erstellen eine Spanne von Zahlen, inklusive dem ersten Wert
+ // jedoch ohne dem letzten
foreach(i; 1..1_000_000) {
if(n % 2 == 0)
writeln(i);
}
+ // Es gibt auch ein 'foreach_reverse' wenn du rückwerts gehen willst.
foreach_reverse(i; 1..int.max) {
if(n % 2 == 1) {
writeln(i);
diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown
index dca88f01..817cb4ae 100644
--- a/de-de/go-de.html.markdown
+++ b/de-de/go-de.html.markdown
@@ -10,8 +10,8 @@ lang: de-de
---
Die Sprache Go (auch golang) wurde von Google entwickelt und wird seit 2007
benutzt. Go ähnelt in der Syntax der Sprache C, bietet darüber hinaus aber viele
-Vorteile. Einerseits verzichtet Gp auf Speicherarithmetik und
-benutzt einen Garbabe Collector. Andererseits enthält Go native Sprachelemente
+Vorteile. Einerseits verzichtet Go auf Speicherarithmetik und
+benutzt einen Garbage Collector. Andererseits enthält Go native Sprachelemente
für die Unterstützung von Nebenläufigkeit. Durch den Fokus auf einen schnellen
Kompilierprozess wird außerdem die Softwareentwicklung in Großprojekten
erleichtert.
diff --git a/de-de/html-de.html.markdown b/de-de/html-de.html.markdown
new file mode 100644
index 00000000..2ee18129
--- /dev/null
+++ b/de-de/html-de.html.markdown
@@ -0,0 +1,120 @@
+---
+language: html
+contributors:
+ - ["Christophe THOMAS", "https://github.com/WinChris"]
+translators:
+ - ["Dennis Keller", "https://github.com/denniskeller"]
+filename: learnhtml-de.html
+lang: de-de
+---
+
+HTML steht für HyperText Markup Language (Hypertext-Auszeichnungssprache).
+Sie ist eine Sprache, um Seiten für das World Wide Web zu schreiben..
+Es ist eine Auszeichnugssprache, die es uns ermöglicht Webseiten mithilfe des Codes zu schreiben, der kennzeichnet wie Text und Daten angezeigt werden sollen. Eigentlich sind HTML Dateien nur einfache Textdateien.
+Was sind das für Auszeichnungen? Es ist eine Methode, um die Daten der Website zu organisieren mithilfe von Start- und Endtags.
+Diese Auszeichnung dient dazu dem Text Bedeutung zu geben, welchen sie umschließt.
+Wie viele andere Computersprachen auch, besitzt HTML viele Versionen. Wir werden hier über HTML5 reden.
+
+**NOTE :** Du kannst die unterschiedlichen Tags und Elemente, während des Tutorials auf Seiten, wie [codepen](http://codepen.io/pen/) testen, um deren Effekte zu sehen und wie diese funktionieren. Auch kannst du dich damit besser mit der Sprache vertraut machen.
+Dieser Artikel ist bedacht darauf, nur HTML Syntax und nützliche Tipps zu geben.
+
+
+```html
+<!-- Kommentare werden wie in dieser Zeile geschrieben -->
+
+<!-- #################### Die Tags #################### -->
+
+<!-- Hier ist eine Beispiel HTML Datei, die wir analysieren werden -->
+
+<!doctype html>
+ <html>
+ <head>
+ <title>Meine Website</title>
+ </head>
+ <body>
+ <h1>Hallo Welt!</h1>
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Komm schau was das hier anzeigt</a>
+ <p>Das ist ein Paragraf.</p>
+ <p>Das ist ein weiterer Paragraf.</p>
+ <ul>
+ <li>Das ist eine Item mit einer nicht-nummerierten Liste (Aufzählungsliste)</li>
+ <li>Das ist ein weiteres Item</li>
+ <li>Und das ist das letzte Item in der Liste</li>
+ </ul>
+ </body>
+ </html>
+
+<!-- Jede HTML Datei startet damit dem Browser zu sagen, dass die Seite aus HTML besteht. -->
+<!doctype html>
+
+<!-- Danach startet sie mit einem Öffnungtag <html>. -->
+<html>
+
+<!-- Dieser wird am Ende der Datei mit</html> geschlossen. -->
+</html>
+
+<!-- Nichts sollte nach diesen finalen Tag erscheinen. -->
+
+<!-- Dazwischen (Zwischen dem Öffnungs- und Schließungstag <html></html>) finden wir: -->
+
+<!-- Ein Kopf wird definiert mit <head> (er muss mit </head> geschlossen werden). -->
+<!-- Der Header beinhaltet Beschreibungen und zusätzliche Informationen, welche nicht dargestellt werden. Das sind Metadaten. -->
+
+<head>
+ <title>Meine Seite</title><!-- Der <title> kennzeichnet dem Browser den Titel im Browserfenster und im Tabnamen anzuzeigen. -->
+</head>
+
+<!-- Nach dem <head> Bereich findet sich der <body> Tag -->
+<!-- Bis zu diesen Punkt wird nichts im Browerfenster angezeigt. -->
+<!-- Wir müssen den Body mit dem Inhalt füllen der angezeigt werden soll. -->
+
+<body>
+ <h1>Hallo, Welt!</h1> <!-- Der h1 Tag erstellt einen Titel. -->
+ <!-- Es gibt auch Untertitel für <h1> von den wichtigsten <h2> zu den Unwichtigsten (h6). -->
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Komm, schaue was das zeigt</a> <!-- Eine URL wird zum Hyperlink, wenn es das Attribut href="" -->
+ <p>Das ist ein Absatz.</p> <!-- Der Tag <p> lässt uns Text auf die HTML Seite hinzufügen. -->
+ <p>Das ist ein anderer Absatz.</p>
+ <ul> <!-- Der <ul> Tag erstellt eine Aufzählungsliste. -->
+ <!-- Für eine nummerierte Liste sollten wir stattdessen <ol> verwenden. Das erste Element bekommt 1., das zweite 2. usw. -->
+ <li>Das ist ein Element in einer nicht Aufzählungsliste</li>
+ <li>Das ist ein anderes Item</li>
+ <li>Und das ist das letzte Element in der List</li>
+ </ul>
+</body>
+
+<!-- Und das war es. Eine HTML Datei kann so simpel sein. -->
+
+<!-- Aber es ist möglich viele weitere zusätzliche HTML tags hinzuzufügen. -->
+
+<!-- Um ein Bild hinzuzufügen. -->
+<img src="http://i.imgur.com/XWG0O.gif"/> <!-- Die Quelle des Bildes wird gezeigt durch das Attribut src="" -->
+<!-- Die Quelle kann eine URL sein oder ein Pfad zu deinem Computer. -->
+
+<!-- Es ist ebenso möglich eine Tabelle zu erstellen. -->
+
+<table> <!-- Wir öffnen ein <table> Element. -->
+ <tr> <!-- <tr> erlaubt es uns Reihe zu erstellen. -->
+ <th>Erster Tabellenkopf</th> <!-- <th> erlaubt es uns der Tabelle einen Titel zu geben. -->
+ <th>Zweiter Tabllenkopf</th>
+ </tr>
+ <tr>
+ <td>Erste Zeile, erste Spalte</td> <!-- <td> erlaubt es eine Tabellenzelle zu erstellen. -->
+ <td>Erste Zeile, zweite Spalte</td>
+ </tr>
+ <tr>
+ <td>Zweite Zeile, erste Spalte</td>
+ <td>Zweite Zeile, zweite Spalte</td>
+ </tr>
+</table>
+
+```
+
+## Verwendung
+
+HTML Dateien enden mit `.html`.
+
+## Um mehr zu lernen
+
+* [wikipedia (EN)](https://en.wikipedia.org/wiki/HTML)
+* [HTML tutorial (EN)](https://developer.mozilla.org/en-US/docs/Web/HTML)
+* [W3School (EN)](http://www.w3schools.com/html/html_intro.asp)
diff --git a/de-de/ruby-de.html.markdown b/de-de/ruby-de.html.markdown
index bdeaa30b..e14603cd 100644
--- a/de-de/ruby-de.html.markdown
+++ b/de-de/ruby-de.html.markdown
@@ -13,6 +13,7 @@ contributors:
- ["Rahil Momin", "https://github.com/iamrahil"]
translators:
- ["Christian Albrecht", "https://github.com/coastalchief"]
+ - ["Dennis Keller", "https://github.com/denniskeller"]
filename: ruby-de.rb
lang: de-de
---
@@ -143,7 +144,7 @@ x #=> 10
y #=> 10
```
## Benennung
-### Konvention ist snake_case
+### Konvention ist snake_case
```
snake_case = true
```
@@ -153,9 +154,9 @@ path_to_project_root = '/good/name/'
path = '/bad/name/'
```
# Symbols (sind auch Objekte)
-Symbols sind unveränderliche, wiederverwendbare Konstanten, welche intern
-als integer repräsentiert werden. Sie werden häufig anstelle von Strings
-verwendet, um sinnvoll Werte zu übermitteln.
+Symbols sind unveränderliche, wiederverwendbare Konstanten, welche intern
+als integer repräsentiert werden. Sie werden häufig anstelle von Strings
+verwendet, um sinnvoll Werte zu übermitteln.
Symbols werden mit dem Doppelpunkt gekennzeichnet.
```
@@ -195,7 +196,7 @@ array[12] #=> nil
array[-1] #=> 5
```
-## Arrays können mit Stard Index und Länge indiziert werden
+## Arrays können mit Start Index und Länge indiziert werden
```
array[2, 3] #=> [3, 4, 5]
```
@@ -216,11 +217,9 @@ array.push(6) #=> [1, 2, 3, 4, 5, 6]
array.include?(1) #=> true
```
-# Hashes
+# Hashes
Hashes sind das Hauptfeature um Key/Values zu speichern
-```
-
## Ein Hash anlegen
```
hash = { 'color' => 'green', 'number' => 5 }
@@ -231,8 +230,8 @@ hash.keys #=> ['color', 'number']
```
hash['color'] #=> 'green'
hash['number'] #=> 5
-hash['nothing here'] #=> nil
-// Asking a hash for a key that doesn't exist returns nil:
+hash['nothing here'] #=> nil
+// Fragen an einen Hash nach einem Schlüssel, der nicht existiert, ruft nil hervor:
```
## Symbols können auch keys sein
@@ -247,7 +246,7 @@ new_hash.has_key?(:defcon) #=> true
new_hash.has_value?(3) #=> true
```
-### Tip: Arrays und Hashes sind Enumerable
+### Tipp: Arrays und Hashes sind Enumerable
### Und haben gemeinsame, hilfreiche Methoden wie:
### each, map, count, and more
@@ -269,8 +268,8 @@ for counter in 1..5
end
```
## Stattdessen: "each" Methode und einen Bloch übergeben
-Ein Block ist ein Codeteil, den man einer Methode übergeben kann
-Ähnelt stark lambdas, anonymen Funktionen oder Closures in anderen
+Ein Block ist ein Codeteil, den man einer Methode übergeben kann
+Ähnelt stark lambdas, anonymen Funktionen oder Closures in anderen
Programmiersprachen.
```
@@ -339,7 +338,7 @@ end
=> "OK job"
```
-# exception handling:
+# Exception handling:
```
begin
# code here that might raise an exception
@@ -360,13 +359,13 @@ def double(x)
x * 2
end
```
-## Funktionen (und Blocks)
+## Funktionen (und Blocks)
## geben implizit den Wert des letzten Statements zurück
```
double(2) #=> 4
```
-### Klammern sind optional wenn das Ergebnis nicht mehdeutig ist
+### Klammern sind optional wenn das Ergebnis nicht mehrdeutig ist
```
double 3 #=> 6
double double 3 #=> 12
@@ -604,7 +603,7 @@ Something.new.qux # => 'qux'
## Weiterführende Hinweise
-//EN
+//EN
- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.
- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/)
diff --git a/de-de/rust-de.html.markdown b/de-de/rust-de.html.markdown
index 2b1471a8..faa4ec2b 100644
--- a/de-de/rust-de.html.markdown
+++ b/de-de/rust-de.html.markdown
@@ -319,7 +319,7 @@ fn main() {
var = 3;
let ref_var: &i32 = &var;
- println!("{}", var); // Anders als `box`, `var` kann hier weiter verwendet werden
+ println!("{}", var); // Anders als `mine`, `var` kann hier weiter verwendet werden
println!("{}", *ref_var);
// var = 5; // das kompiliert nicht, da `var` ausgeliehen ist
// *ref_var = 6; // das kompiliert auch nicht, da `ref_var` eine unveränderliche Referenz ist
diff --git a/de-de/swift-de.html.markdown b/de-de/swift-de.html.markdown
new file mode 100644
index 00000000..b58a72d3
--- /dev/null
+++ b/de-de/swift-de.html.markdown
@@ -0,0 +1,591 @@
+---
+language: swift
+contributors:
+ - ["Grant Timmerman", "http://github.com/grant"]
+ - ["Christopher Bess", "http://github.com/cbess"]
+ - ["Joey Huang", "http://github.com/kamidox"]
+ - ["Anthony Nguyen", "http://github.com/anthonyn60"]
+translators:
+ - ["Jonas Wippermann", "http://vfuc.co"]
+filename: learnswift-de.swift
+lang: de-de
+---
+
+Swift ist eine Programmiersprache von Apple für die Entwicklung von iOS und OS X Applikationen. Swift wurde 2014 zu Apples WWDC Entwicklerkonferenz vorgestellt und wurde mit dem Ziel entwickelt, fehlerträchtigen Code zu vermeiden sowie mit Objective-C zu koexistieren. Es wird mit dem LLVM Compiler gebaut und ist ab Xcode 6+ verfügbar.
+
+Das offizielle [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) Buch von Apple ist kostenlos via iBooks verfügbar.
+
+Außerdem hilfreich ist Apples [Getting Started Guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), ein guter Einstiegspunkt mit komplettem Swift-Tutorial.
+
+```swift
+// importiere ein Modul
+import UIKit
+
+//
+// MARK: Grundlagen
+//
+
+// Xcode unterstützt "Landmarks" um Code zu gliedern, sie werden in der Jump Bar aufgelistet
+// MARK: Abschnitts-Markierung
+// TODO: Zu erledigen
+// FIXME: Zu beheben
+
+// In Swift 2 wurden println und print zusammengefasst in eine print-Methode. Es wird automatisch ein Zeilenumbruch angehängt.
+print("Hello, world!") // println ist jetzt print
+print("Hello, world!", appendNewLine: false) // printen ohne Zeilenumbruch am Ende
+
+// Variablen (var) können nach der Initialisierung verändert werden
+// Konstanten (let) können nach der Initialisierung NICHT verändert werden
+
+var myVariable = 42
+let øπΩ = "value" // Unicode-Variablennamen
+let π = 3.1415926
+let convenience = "keyword" // Kontext-abhängiger Variablenname
+let weak = "keyword"; let override = "another keyword" // Instruktionen können durch ein Semikolon aufgeteilt werden
+let `class` = "keyword" // Nutze "Backticks" um Schlüsselwörter als Variablennamen zu verwenden
+let explicitDouble: Double = 70 // Typ explizit festgelegt
+let intValue = 0007 // 7
+let largeIntValue = 77_000 // 77000
+let label = "some text " + String(myVariable) // Casting
+let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String Interpolation
+
+// Build-spezifische Werte
+// benutzt -D build configuration
+#if false
+ print("not printed")
+ let buildValue = 3
+#else
+ let buildValue = 7
+#endif
+print("Build value: \(buildValue)") // Build value: 7
+
+/*
+ Optionals ist ein Swift-Feature, welches ermöglicht, dass eine Variable entweder einen (`Some`) oder keinen (`None`) Wert hat
+
+ Da Swift von jeder property einen Wert erwartet, muss sogar nil explizit als Optional festgelegt werden.
+
+ Optional<T> ist ein Enum.
+*/
+var someOptionalString: String? = "optional" // Kann nil sein
+// Genau wie oben, aber ? ist ein postfix operator (Syntax Candy)
+var someOptionalString2: Optional<String> = "optional"
+
+if someOptionalString != nil {
+ // Ich bin nicht nil
+ if someOptionalString!.hasPrefix("opt") {
+ print("has the prefix")
+ }
+
+ let empty = someOptionalString?.isEmpty
+}
+someOptionalString = nil
+
+// Implizit entpackter Optionalwert
+var unwrappedString: String! = "Value is expected."
+// Genau wie oben, aber ! ist ein postfix operator (noch mehr Syntax Candy)
+var unwrappedString2: ImplicitlyUnwrappedOptional<String> = "Value is expected."
+
+if let someOptionalStringConstant = someOptionalString {
+ // hat einen (`Some`) Wert, nicht nil
+ if !someOptionalStringConstant.hasPrefix("ok") {
+ // hat keinen "ok"-Prefix
+ }
+}
+
+// Swift unterstützt das festlegen von Werten eines beliebigen Typens
+// AnyObject == id
+// Im Gegensatz zum Objective-C `id`, funktioniert AnyObject mit jeglichen Werten (Class, Int, struct, etc)
+var anyObjectVar: AnyObject = 7
+anyObjectVar = "Changed value to a string, not good practice, but possible."
+
+/*
+ Ein Kommentar
+
+ /*
+ Verschachtelte Kommentare sind ebenfalls unterstützt
+ */
+*/
+
+//
+// MARK: Collections
+//
+
+/*
+ Array und Dictionary-Typen sind structs.
+ Deswegen implizieren `let` und `var` bei der Initialisierung auch ob sie änderbar (var) oder unveränderlich (let) sind.
+*/
+
+// Array
+var shoppingList = ["catfish", "water", "lemons"]
+shoppingList[1] = "bottle of water"
+let emptyArray = [String]() // let == unveränderlich
+let emptyArray2 = Array<String>() // genau wie oben
+var emptyMutableArray = [String]() // var == änderbar
+
+
+// Dictionary
+var occupations = [
+ "Malcolm": "Captain",
+ "kaylee": "Mechanic"
+]
+occupations["Jayne"] = "Public Relations"
+let emptyDictionary = [String: Float]() // let == unveränderlich
+let emptyDictionary2 = Dictionary<String, Float>() // genau wie oben
+var emptyMutableDictionary = [String: Float]() // var == änderbar
+
+
+//
+// MARK: Kontrollstruktur
+//
+
+// for-Schleife (array)
+let myArray = [1, 1, 2, 3, 5]
+for value in myArray {
+ if value == 1 {
+ print("One!")
+ } else {
+ print("Not one!")
+ }
+}
+
+// for-Schleife mit Indizes (array)
+for index in myArray.indices {
+ print("Value with index \(index) is \(myArray[index])")
+}
+
+// for-Schleife (dictionary)
+var dict = ["one": 1, "two": 2]
+for (key, value) in dict {
+ print("\(key): \(value)")
+}
+
+// for-Schleife (range)
+for i in -1...shoppingList.count {
+ print(i)
+}
+shoppingList[1...2] = ["steak", "peacons"]
+// ..< schließt letzte Nummer aus
+
+// while-Schleife
+var i = 1
+while i < 1000 {
+ i *= 2
+}
+
+// do-while-Schleife
+do {
+ print("hello")
+} while 1 == 2
+
+// Switch
+// Sehr mächtig, wie `if` statement mit Syntax Candy
+// Unterstützt Strings, Objekt-Instanzen und primitive Typen (Int, Double, etc)
+let vegetable = "red pepper"
+switch vegetable {
+case "celery":
+ let vegetableComment = "Add some raisins and make ants on a log."
+case "cucumber", "watercress":
+ let vegetableComment = "That would make a good tea sandwich."
+case let localScopeValue where localScopeValue.hasSuffix("pepper"):
+ let vegetableComment = "Is it a spicy \(localScopeValue)?"
+default: // notwendig (um alle möglichen Eingaben zu verarbeiten)
+ let vegetableComment = "Everything tastes good in soup."
+}
+
+
+//
+// MARK: Funktionen
+//
+
+// Funktionen sind ein sogenannter "first-class" Typ, was bedeutet, dass sie
+// in Funktionen geschachtelt werden und "herumgereicht" werden können
+
+// Funktion mit Swift header Dokumentation
+
+/**
+ Eine Grüß-Funktion
+
+ - Ein Aufzählungspunkt
+ - Ein weiterer Aufzählungspunkt in der Dokumentation
+
+ :param: name Ein Name
+ :param: day Ein Tag
+ :returns: Ein String, der Name und Tag beinhält.
+*/
+func greet(name: String, day: String) -> String {
+ return "Hello \(name), today is \(day)."
+}
+greet("Bob", "Tuesday")
+
+// Ähnlich wie oben, bloß anderes Funktions-Parameter-Verhalten
+func greet2(#requiredName: String, externalParamName localParamName: String) -> String {
+ return "Hello \(requiredName), the day is \(localParamName)"
+}
+greet2(requiredName:"John", externalParamName: "Sunday")
+
+
+// Funktion, welche mehrere Werte in einem Tupel zurückgibt
+func getGasPrices() -> (Double, Double, Double) {
+ return (3.59, 3.69, 3.79)
+}
+let pricesTuple = getGasPrices()
+let price = pricesTuple.2 // 3.79
+// Ignoriere Tupel-(oder andere)Werte mit _ (Unterstrich)
+let (_, price1, _) = pricesTuple // price1 == 3.69
+print(price1 == pricesTuple.1) // true
+print("Gas price: \(price)")
+
+// Variierende Argumente..
+func setup(numbers: Int...) {
+ // .. liegen als Array vor
+ let number = numbers[0]
+ let argCount = numbers.count
+}
+
+// Funktionen übergeben und zurückgeben
+func makeIncrementer() -> (Int -> Int) {
+ func addOne(number: Int) -> Int {
+ return 1 + number
+ }
+ return addOne
+}
+var increment = makeIncrementer()
+increment(7)
+
+// Übergabe via Referenz ("Pass by reference")
+func swapTwoInts(inout a: Int, inout b: Int) {
+ let tempA = a
+ a = b
+ b = tempA
+}
+var someIntA = 7
+var someIntB = 3
+swapTwoInts(&someIntA, &someIntB)
+print(someIntB) // 7
+
+
+//
+// MARK: Closures
+//
+var numbers = [1, 2, 6]
+
+// Funktionen sind besondere Closures ({})
+
+// Closure Beispiel
+// `->` teilt Parameter und Rückgabe-Typ
+// `in` teilt den Closure Header vom Body
+numbers.map({
+ (number: Int) -> Int in
+ let result = 3 * number
+ return result
+})
+
+
+// Wenn der Typ bekannt ist, wie oben, kann folgendes getan werden
+numbers = numbers.map({ number in 3 * number })
+// oder sogar dies
+//numbers = numbers.map({ $0 * 3 })
+
+print(numbers) // [3, 6, 18]
+
+// "Schleppende Closure" (Trailing Closure)
+numbers = sorted(numbers) { $0 > $1 }
+
+print(numbers) // [18, 6, 3]
+
+// Sehr verkürzt, da sich der Typ durch den < Operator ableiten lässt
+
+numbers = sorted(numbers, < )
+
+print(numbers) // [3, 6, 18]
+
+//
+// MARK: Strukturen
+// (häufig einfach structs)
+//
+
+// Structures und Klassen haben sehr ähnliche Fähigkeiten
+struct NamesTable {
+ let names = [String]()
+
+ // Eigendefiniertes subscript
+ subscript(index: Int) -> String {
+ return names[index]
+ }
+}
+
+
+// Strukturen haben eine automatisch generierte, designierte Initialisierungsfunktion
+let namesTable = NamesTable(names: ["Me", "Them"])
+let name = namesTable[1]
+print("Name is \(name)") // Name is Them
+
+//
+// MARK: Klassen
+//
+
+// Klassen, Strukturen und deren Member haben drei Ebenen der Zugriffskontrolle
+// Es gibt: internal (default), public, private
+
+public class Shape {
+ public func getArea() -> Int {
+ return 0;
+ }
+}
+
+// Alle Methoden und Properties einer Klasse sind public
+// Wenn das einfache Ziel ist, Daten in einem strukturierten Objekt zu halten,
+// sollte ein `struct` verwendet werden
+
+internal class Rect: Shape {
+ var sideLength: Int = 1
+
+ // Eigendefinierte Getter und Setter für die Property
+ private var perimeter: Int {
+ get {
+ return 4 * sideLength
+ }
+ set {
+ // `newValue` ist eine implizite Variable, welche in Settern verfügbar ist
+ sideLength = newValue / 4
+ }
+ }
+
+ // "Lazy" (faules) Laden einer Property, sie bleibt uninitialisiert (nil),
+ // bis sie aufgerufen wird
+ lazy var subShape = Rect(sideLength: 4)
+
+ // Wenn kein eigendefinierter Getter/Setter notwendig ist,
+ // aber trotzdem Code vor und nach dem Setzen eines Variablenwertes laufen soll,
+ // kann "willSet" und "didSet" benutzt werden
+ var identifier: String = "defaultID" {
+ // der `willSet` Parameter wird der Variablenname für den neuen Wert sein
+ willSet(someIdentifier) {
+ print(someIdentifier)
+ }
+ }
+
+ init(sideLength: Int) {
+ self.sideLength = sideLength
+ // super.init muss immer aufgerufen werden, wenn eigene Properties initialisiert werden
+ super.init()
+ }
+
+ func shrink() {
+ if sideLength > 0 {
+ sideLength -= 1
+ }
+ }
+
+ override func getArea() -> Int {
+ return sideLength * sideLength
+ }
+}
+
+// Eine simple `Square`-Klasse erbt von/erweitert `Rect`
+class Square: Rect {
+ convenience init() {
+ self.init(sideLength: 5)
+ }
+}
+
+var mySquare = Square()
+print(mySquare.getArea()) // 25
+mySquare.shrink()
+print(mySquare.sideLength) // 4
+
+// Casten der Instanz
+let aShape = mySquare as Shape
+
+// Vergleiche Instanzen, nicht äquivalent zum == , welches Objekte vergleicht ("equal to")
+if mySquare === mySquare {
+ print("Yep, it's mySquare")
+}
+
+// Optionale Initialisierung
+class Circle: Shape {
+ var radius: Int
+ override func getArea() -> Int {
+ return 3 * radius * radius
+ }
+
+ // Ein Fragezeichen nach `init` ist eine optionale Initialisierung,
+ // welche nil zurückgeben kann
+ init?(radius: Int) {
+ self.radius = radius
+ super.init()
+
+ if radius <= 0 {
+ return nil
+ }
+ }
+}
+
+var myCircle = Circle(radius: 1)
+print(myCircle?.getArea()) // Optional(3)
+print(myCircle!.getArea()) // 3
+var myEmptyCircle = Circle(radius: -1)
+print(myEmptyCircle?.getArea()) // "nil"
+if let circle = myEmptyCircle {
+ // wird nicht ausgeführt, da myEmptyCircle nil ist
+ print("circle is not nil")
+}
+
+
+//
+// MARK: Enums
+//
+
+// Enums können optional einen eigenen Typen haben
+// Wie Klassen auch können sie Methoden haben
+
+enum Suit {
+ case Spades, Hearts, Diamonds, Clubs
+ func getIcon() -> String {
+ switch self {
+ case .Spades: return "♤"
+ case .Hearts: return "♡"
+ case .Diamonds: return "♢"
+ case .Clubs: return "♧"
+ }
+ }
+}
+
+
+// Enum-Werte können vereinfacht geschrieben werden, es muss nicht der Enum-Typ
+// genannt werden, wenn die Variable explizit deklariert wurde
+
+var suitValue: Suit = .Hearts
+
+// Nicht-Integer-Enums brauchen direkt zugewiesene "Rohwerte"
+enum BookName: String {
+ case John = "John"
+ case Luke = "Luke"
+}
+print("Name: \(BookName.John.rawValue)")
+
+// Enum mit assoziierten Werten
+enum Furniture {
+ // mit Int assoziiert
+ case Desk(height: Int)
+ // mit String und Int assoziiert
+ case Chair(String, Int)
+
+ func description() -> String {
+ switch self {
+ case .Desk(let height):
+ return "Desk with \(height) cm"
+ case .Chair(let brand, let height):
+ return "Chair of \(brand) with \(height) cm"
+ }
+ }
+}
+
+var desk: Furniture = .Desk(height: 80)
+print(desk.description()) // "Desk with 80 cm"
+var chair = Furniture.Chair("Foo", 40)
+print(chair.description()) // "Chair of Foo with 40 cm"
+
+
+//
+// MARK: Protokolle
+//
+
+// Protokolle (`protocol`s) können verlangen, dass entsprechende
+// Typen spezifische Instanz-Properties, Instanz/Klassen-Methoden,
+// Operatoren oder Subscripts implementieren/haben
+
+protocol ShapeGenerator {
+ var enabled: Bool { get set }
+ func buildShape() -> Shape
+}
+
+// Protocols mit @objc deklariert ermöglichen optionale Funktionen,
+// welche es ermöglichen, abzufragen ob ein Typ einem Protokoll entspricht
+@objc protocol TransformShape {
+ optional func reshaped()
+ optional func canReshape() -> Bool
+}
+
+class MyShape: Rect {
+ var delegate: TransformShape?
+
+ func grow() {
+ sideLength += 2
+
+ // Ein Fragezeichen nach einer optionalen Property, Methode oder Subscript
+ // ignoriert elegant Nil-Werte und geben nil zurück, anstatt einen Laufzeitfehler zu werfen
+ // Dies wird "optional Chaining" (optionale Verkettung) genannt
+ if let allow = self.delegate?.canReshape?() {
+ // frage erst nach delegate, dann nach Methode
+ self.delegate?.reshaped?()
+ }
+ }
+}
+
+
+//
+// MARK: Sonstiges
+//
+
+// `extension`s: (Erweiterungen), erweitere Typen um zusätzliche Funktionalität
+
+// Square entspricht jetzt dem `Printable` Protokoll
+extension Square: Printable {
+ var description: String {
+ return "Area: \(self.getArea()) - ID: \(self.identifier)"
+ }
+}
+
+print("Square: \(mySquare)")
+
+// Standardtypen können ebenfalls erweitert werden
+extension Int {
+ var customProperty: String {
+ return "This is \(self)"
+ }
+
+ func multiplyBy(num: Int) -> Int {
+ return num * self
+ }
+}
+
+print(7.customProperty) // "This is 7"
+print(14.multiplyBy(3)) // 42
+
+
+//Generics: Ähnlich zu Java und C#. Nutze das `where` keyword um die Bedingung
+// des Generics festzulegen
+
+func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
+ for (index, value) in enumerate(array) {
+ if value == valueToFind {
+ return index
+ }
+ }
+ return nil
+}
+let foundAtIndex = findIndex([1, 2, 3, 4], 3)
+print(foundAtIndex == 2) // true
+
+// Operatoren:
+// Eigendefinierte Operatoren können mit diesen Zeichen beginnen:
+// / = - + * % < > ! & | ^ . ~
+// oder
+// Unicode Mathematik, Symbole, Pfeile, Dingbat, und Linien/Box - Zeichen
+prefix operator !!! {}
+
+
+// Ein Prefix-Operator, welcher die Seitenlänge verdreifacht
+prefix func !!! (inout shape: Square) -> Square {
+ shape.sideLength *= 3
+ return shape
+}
+
+// Aktueller Wert
+print(mySquare.sideLength) // 4
+
+// Wert nach verwendung des eigenen Operators
+!!!mySquare
+print(mySquare.sideLength) // 12
+```
diff --git a/dynamic-programming.html.markdown b/dynamic-programming.html.markdown
index 95f774bf..94be22e9 100644
--- a/dynamic-programming.html.markdown
+++ b/dynamic-programming.html.markdown
@@ -11,39 +11,40 @@ contributors:
Dynamic Programming is a powerful technique used for solving a particular class of problems as we will see.The idea is very simple, If you have solved a problem with the given input, then save the result for future reference, so as to avoid solving the same problem again.
-Always remember!!
+Always remember!
"Those who can't remember the past are condemned to repeat it"
## Ways of solving such Problems
-1.) Top-Down : Start solving the given problem by breaking it down. If you see that the problem has been solved already, then just return the saved answer. If it has not been solved, solve it and save the answer. This is usually easy to think of and very intuitive. This is referred to as Memoization.
+1. *Top-Down* : Start solving the given problem by breaking it down. If you see that the problem has been solved already, then just return the saved answer. If it has not been solved, solve it and save the answer. This is usually easy to think of and very intuitive. This is referred to as Memoization.
-2.) Bottom-Up : Analyze the problem and see the order in which the sub-problems are solved and start solving from the trivial subproblem, up towards the given problem. In this process, it is guaranteed that the subproblems are solved before solving the problem. This is referred to as Dynamic Programming.
+2. *Bottom-Up* : Analyze the problem and see the order in which the sub-problems are solved and start solving from the trivial subproblem, up towards the given problem. In this process, it is guaranteed that the subproblems are solved before solving the problem. This is referred to as Dynamic Programming.
## Example of Dynamic Programming
-The Longest Increasing Subsequence problem is to find the longest increasing subsequence of a given sequence. Given a sequence S= {a1 , a2 , a3, a4, ............., an-1, an } we have to find a longest subset such that for all j and i, j<i in the subset aj<ai.
-First of all we have to find the value of the longest subsequences(LSi) at every index i with last element of sequence being ai. Then largest LSi would be the longest subsequence in the given sequence. To begin LSi is assigned to be one since ai is element of the sequence(Last element). Then for all j such that j<i and aj<ai ,we find Largest LSj and add it to LSi. Then algorithm take O(n2) time.
+The Longest Increasing Subsequence problem is to find the longest increasing subsequence of a given sequence. Given a sequence `S= {a1 , a2 , a3, a4, ............., an-1, an }` we have to find a longest subset such that for all `j` and `i`, `j<i` in the subset `aj<ai`.
+First of all we have to find the value of the longest subsequences(LSi) at every index i with last element of sequence being ai. Then largest LSi would be the longest subsequence in the given sequence. To begin LSi is assigned to be one since ai is element of the sequence(Last element). Then for all `j` such that `j<i` and `aj<ai`, we find Largest LSj and add it to LSi. Then algorithm take *O(n2)* time.
+
Pseudo-code for finding the length of the longest increasing subsequence:
This algorithms complexity could be reduced by using better data structure rather than array. Storing predecessor array and variable like largest_sequences_so_far and its index would save a lot time.
+
Similar concept could be applied in finding longest path in Directed acyclic graph.
----------------------------------------------------------------------------
- for i=0 to n-1
- LS[i]=1
- for j=0 to i-1
- if (a[i] > a[j] and LS[i]<LS[j])
- LS[i] = LS[j]+1
- for i=0 to n-1
- if (largest < LS[i])
-### Some Famous DP Problems
+```python
+for i=0 to n-1
+ LS[i]=1
+ for j=0 to i-1
+ if (a[i] > a[j] and LS[i]<LS[j])
+ LS[i] = LS[j]+1
+for i=0 to n-1
+ if (largest < LS[i])
```
-Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code
-
-Integer Knapsack Problem - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem
+### Some Famous DP Problems
-Longest Common Subsequence - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence
+- Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code
+- Integer Knapsack Problem - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem
+- Longest Common Subsequence - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence
## Online Resources
diff --git a/elixir.html.markdown b/elixir.html.markdown
index 26a547c3..63b7aef2 100644
--- a/elixir.html.markdown
+++ b/elixir.html.markdown
@@ -325,6 +325,14 @@ defmodule MyMod do
IO.inspect(@my_data) #=> 100
end
+# The pipe operator |> allows you to pass the output of an expression
+# as the first parameter into a function.
+
+Range.new(1,10)
+|> Enum.map(fn x -> x * x end)
+|> Enum.filter(fn x -> rem(x, 2) == 0 end)
+#=> [4, 16, 36, 64, 100]
+
## ---------------------------
## -- Structs and Exceptions
## ---------------------------
diff --git a/elm.html.markdown b/elm.html.markdown
index dab2ab34..96554e84 100644
--- a/elm.html.markdown
+++ b/elm.html.markdown
@@ -2,6 +2,7 @@
language: Elm
contributors:
- ["Max Goldstein", "http://maxgoldste.in/"]
+filename: learnelm.elm
---
Elm is a functional reactive programming language that compiles to (client-side)
diff --git a/es-es/asymptotic-notation-es.html.markdown b/es-es/asymptotic-notation-es.html.markdown
index f3fe1614..3507429c 100644
--- a/es-es/asymptotic-notation-es.html.markdown
+++ b/es-es/asymptotic-notation-es.html.markdown
@@ -168,3 +168,4 @@ definiciones y ejemplos.
* [MIT](http://web.mit.edu/16.070/www/lecture/big_o.pdf)
* [KhanAcademy](https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation)
+* [Apuntes Facultad de Ingeniería](https://www.scribd.com/document/317979564/Apuntes-Sobre-Analisis-de-Algoritmos)
diff --git a/es-es/binary-search-es.html.markdown b/es-es/binary-search-es.html.markdown
new file mode 100644
index 00000000..a1b42d21
--- /dev/null
+++ b/es-es/binary-search-es.html.markdown
@@ -0,0 +1,68 @@
+---
+category: Algorithms & Data Structures
+name: Binary Search
+contributors:
+ - ["Abhishek Jaisingh", "http://github.com/abhishekjiitr"]
+translators:
+ - ["Gino Amaury", "https://github.com/ginoamaury"]
+lang: es-es
+---
+
+# Búsqueda Binaria
+
+## Por qué Búsqueda Binaria?
+
+La búsqueda es uno de los problemas principales en el dominio de la ciencia de la computación. Hoy en dia hay mas de 1 billon de búsquedas por año, y necesitamos tener algoritmos que puedan hacer esto muy rápido. La búsqueda binaria es uno de los algoritmos fundamentales en la ciencia de la computación. Con el fin de explorarlo, vamos a construir por primera vez un esqueleto teórico y lo utilizaremos para implementar el algoritmo apropiadamente.
+
+## Introducción
+
+Un método sencillo para poner en práctica la búsqueda es hacer una búsqueda lineal, pero este método requiere mucho tiempo y este crece linealmente con la cantidad o el número de datos. es decir, empezar desde el elemento a la izquierda de la matriz [] y uno por uno compara x con cada elemento de la matriz [], si x coincide con un elemento, devuelve el índice. Si x no coincide con ninguno de los elementos, devuelve -1.
+
+```
+Búsqueda Lineal: O (n) Tiempo lineal
+
+Búsqueda Binaria: O ( log(n) ) Tiempo logarítmico
+
+```
+```
+def search(arr, x):
+
+ for i in range(len(arr)):
+
+ if arr[i] == x:
+ return i
+
+ return -1
+
+```
+## Algoritmo de Búsqueda Binaria
+
+El requisito básico para que la búsqueda binaria funcione es que los datos a buscar deben estar ordenados (en cualquier orden).
+
+
+### Algo
+
+```
+La idea de la búsqueda binaria es usar la información de que la matriz está ordenada y así reducir la complejidad del tiempo a O(Logn). Básicamente ignoramos la mitad de los elementos después de la primera comparación.
+1) Compare x con el elemento del medio.
+2) si x coincide con el elemento del medio , retornamos el índice del elemento del medio.
+3) Si no coincide, si x es mayor que el elemento del medio, entonces x solo puede estar en la mitad derecha justo después del elemento del medio. Así que recurrimos a la mitad derecha.
+4) Si no (x es más pequeño) recurrimos a la mitad izquierda.
+Siguiendo la implementación recursiva de búsqueda binaria.
+
+```
+
+### Notas finales
+
+Hay otra forma de búsqueda binaria que es muy útil.
+
+## Libros
+
+* [CLRS EN](https://mitpress.mit.edu/books/introduction-algorithms)
+* [Algoritmos EN](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X)
+* [Diseño de Algoritmos EN](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651)
+
+## Recursos en línea
+
+* [GeeksforGeeks EN](http://www.geeksforgeeks.org/the-ubiquitous-binary-search-set-1/)
+* [Topcoder Tutorial EN](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/)
diff --git a/es-es/dynamic-programming-es.html.markdown b/es-es/dynamic-programming-es.html.markdown
new file mode 100644
index 00000000..11930653
--- /dev/null
+++ b/es-es/dynamic-programming-es.html.markdown
@@ -0,0 +1,54 @@
+---
+category: Algorithms & Data Structures
+name: Dynamic Programming
+contributors:
+ - ["Akashdeep Goel", "http://github.com/akashdeepgoel"]
+translators:
+ - ["Gino Amaury", "https://github.com/ginoamaury"]
+lang: es-es
+---
+
+# programación dinámica
+
+## Introducción
+
+La programación dinámica es una técnica poderosa usada para resolver una clase particular de problemas como veremos más adelante. La idea es muy simple, si usted ha solucionado un problema con la entrada dada, entonces , guardaremos el resultado para una futura referencia, con el fin de evitar la solución del mismo problema de nuevo.
+
+
+Recuerde siempre!!
+"Aquellos que no pueden recordar el pasado están condenados a repetirlo"
+
+## Formas de resolver este tipo de problemas
+
+1.) De arriba hacia abajo : Empezamos resolviendo el problema dado descomponiendolo. Si ves que el problema fue resuelto, entonces retorna la respuesta guardada. si no se ha resuelto, resuélvelo y guarda la respuesta. Esto suele ser fácil pensar y muy intuitivo. Esto se conoce como memorización.
+
+2.) De abajo hacia arriba : Analiza el problema y mira el orden en que los subproblemas deben ser resueltos y empieza resolviendo el subproblema más trivial, hacia el problema dado.En este proceso, se garantiza que los subproblemas se resuelven antes de resolver el problema. Esto se conoce como programación dinámica.
+
+## Ejemplo de Programación Dinámica
+
+El problema de la subsecuencia creciente máxima consiste en encontrar la subsecuencia creciente máxima en una secuencia dada . Dada la secuencia S= {a1 , a2 , a3, a4, ............., an-1, an } tenemos que encontrar un subconjunto más largo tal que para todo j y i, j <i en el subconjunto aj <ai.
+En primer lugar tenemos que encontrar el valor de las subsecuencias más largas (LSI) en cada índice con el último elemento de la secuencia que es ai. El mayor LSi sería la subsecuencia más larga de la secuencia dada. Para empezar LSI es asignado a uno ya que ai es un elemento de la secuencia(El último elemento).Entonces, para todo j tal que j <i aj <ai, nos encontramos con Lsj más grande y lo agregamos a la LSI. A continuación, el algoritmo toma un tiempo de O (n2).
+Pseudocódigo para encontrar la longitud de la más larga subsecuencia creciente:
+La complejidad de este algoritmos podría reducirse mediante el uso de una mejor estructura de datos en lugar de una array. Almacenamiento de una matriz predecesora y una variable como Secuencia_mas_Grande_hasta_ahora y su índice podría ahorrar mucho tiempo.
+concepto similar se podría aplicar en encontrar el camino más largo de grafo acíclico dirigido.
+---------------------------------------------------------------------------
+ for i=0 to n-1
+ LS[i]=1
+ for j=0 to i-1
+ if (a[i] > a[j] and LS[i]<LS[j])
+ LS[i] = LS[j]+1
+ for i=0 to n-1
+ if (largest < LS[i])
+
+### Algunos problemas famosos de Programación Dinámica (DP).
+```
+Algoritmo Floyd Warshall(EN) - Tutorial y código fuente del programa en C:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code
+
+Problema de la Mochila(EN) - Tutorial y código fuente del programa en C: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem
+
+
+Problema de Subsecuencia Común mas Larga(EN) - Tutorial y código fuente del programa en C : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence
+
+## Recursos en línea
+
+* [codechef EN](https://www.codechef.com/wiki/tutorial-dynamic-programming) \ No newline at end of file
diff --git a/es-es/edn-es.html.markdown b/es-es/edn-es.html.markdown
new file mode 100644
index 00000000..32bba37d
--- /dev/null
+++ b/es-es/edn-es.html.markdown
@@ -0,0 +1,111 @@
+---
+language: edn
+filename: learnedn-es.edn
+contributors:
+ - ["Jason Yeo", "https://github.com/jsyeo"]
+translators:
+ - ["Gino Amaury", "https://github.com/ginoamaury"]
+lang: es-es
+---
+
+La notación de datos extensible (Extensible Data Notation (EDN)) es un formato para serializar los datos.
+
+La notación se utiliza internamente por Clojure para representar programas. También es
+utilizado como un formato de transferencia de datos como JSON. A pesar de que se utiliza más comúnmente en
+Clojure, existen implementaciones de EDN para muchos otros lenguajes.
+
+El principal beneficio de EDN sobre JSON y YAML es que es extensible.
+Vamos a ver cómo se extiende más adelante.
+
+```clojure
+; Los comentarios comienzan con un punto y coma.
+; Cualquier cosa después del punto y coma es ignorado.
+
+;;;;;;;;;;;;;;;;;;;
+;;;Tipos Básicos;;;
+;;;;;;;;;;;;;;;;;;;
+
+nil ; También conocido en otros lenguajes como nulo (null).
+
+; Booleanos
+true
+false
+
+; Las cadenas se encierran entre comillas dobles
+"desayuno húngaro"
+"tortilla de queso del granjero"
+
+; Los caracteres están precedidos por barras invertidas
+\g \r \a \c \e
+
+; Las palabras claves comienzan con dos puntos.Se comportan como las enumeraciones. Más o menos
+; Como símbolos en Ruby
+:huevos
+:queso
+:aceitunas
+
+; Los símbolos se utilizan para representar los identificadores.Estos empiezan con #.
+; puedes tener espacios usando el símbolo /. cualquier cosa precedida / es
+; un espacio en el nombre.
+#cuchara
+#cocina/cuchara ; no es lo mismo que #spoon
+#cocina/tenedor
+#github/tenedor ; no se puede comer con este.
+
+; Números enteros y flotantes
+42
+3.14159
+
+; Las listas son secuencias de valores.
+(:bollo :empanada-de-res 9 "yum!")
+
+; Vectores permiten acceso aleatorio
+[:helado 1 2 -2]
+
+; Los mapas son estructuras de datos asociativos que se asocian con la clave de su valor.
+{:huevos 2
+ :jugo-de-limon 3.5
+ :mantequilla 1}
+
+; Usted no está restringido a usar palabras clave como claves.
+{[1 2 3 4] "decirle a la gente lo que llevaba",
+ [5 6 7 8] "Entre mas tu ves, mas lo odias"}
+
+; Puede usar comas para facilitar la lectura. Se tratan como espacios en blanco.
+
+; Los conjuntos son colecciones que contienen elementos únicos.
+#{:a :b 88 "huat"}
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;;Elementos de etiqueta ;;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+; EDN puede ser extendido por elementos de etiqueta con el símbolo #.
+
+#MyYelpClone/MenuItem {:nombre "huevos-Benedict" :clasificacion 10}
+
+; Permíteme explicar esto con un ejemplo en colujre. Supongamos que quiero
+; transformar ese pedazo de EDN en un registro del Menú.
+
+(defrecord MenuItem [nombre clasificacion])
+
+; Para transformar EDN en valores clojure, necesitaremos usar el constructor en EDN
+; lectura, edn/read-string
+
+(edn/read-string "{:huevos 2 :mantequilla 1 :harina 5}")
+; -> {:huevos 2 :mantequilla 1 :harina 5}
+
+; Para transformar los elementos de etiqueta, definir la función de lectura y pasar un mapa
+; que asigna etiquetas a funciones del lector de edn/read-string al igual que.
+
+(edn/read-string {:lectores {'MyYelpClone/MenuItem map->menu-item}}
+ "#MyYelpClone/MenuItem {:nombre \"huevos-benedict\" :clasificacion 10}")
+; -> #user.MenuItem{:nombre "huevos-benedict", :clasificacion 10}
+
+```
+
+# Referencias
+
+- [EDN spec (EN)](https://github.com/edn-format/edn)
+- [Implementations (EN)](https://github.com/edn-format/edn/wiki/Implementations)
+- [Tagged Elements (EN)](http://www.compoundtheory.com/clojure-edn-walkthrough/)
diff --git a/es-es/html-es.html.markdown b/es-es/html-es.html.markdown
new file mode 100644
index 00000000..e4623131
--- /dev/null
+++ b/es-es/html-es.html.markdown
@@ -0,0 +1,122 @@
+---
+language: html
+filename: learnhtml-es.html
+contributors:
+ - ["Christophe THOMAS", "https://github.com/WinChris"]
+translators:
+ - ["Gino Amaury", "https://github.com/ginoamaury"]
+lang: es-es
+---
+
+HTML significa Lenguaje de marcado de hipertexto (HyperText Markup Language).
+Este es un lenguaje usado para escribir páginas en la web (WWW).
+Este es un lenguaje de marcado, es usado para escribir páginas web usando código para indicar cómo se debe mostrar el texto y los datos.
+En efecto, los archivos html son simples archivos de texto.
+Qué es esto de marcado? es un método para organizar los datos de la página encerrandolos con etiquetas de apertura y cierre.
+Este marcado sirve para darle significancia al texto que éste encierra.
+Como en otros lenguajes computacionales, HTML tiene varias versiones. Aquí hablaremos acerca de HTML5.
+
+**Nota :** Puedes probrar las diferentes etiquetas y elementos a medida que progresas en un tutorial en un sitio como [codepen](http://codepen.io/pen/) con el fin de ver sus efectos, entender como funcionan y familiarizarse con el lenguaje.
+Este artículo está centrado principalmente en la sintaxis HTML y algunos tips de importancia.
+
+
+```html
+<!-- los comentarios están encerrados como en esta línea! -->
+
+<!-- #################### Las Etiquetas #################### -->
+
+<!-- Este es un ejemplo de un archivo HTML que analizaremos! -->
+
+<!doctype html>
+ <html>
+ <head>
+ <title>Mi Sitio</title>
+ </head>
+ <body>
+ <h1>Hola, Mundo!</h1>
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">ven mira lo que esto muestra. </a>
+ <p>Esto es un párrafo</p>
+ <p>Este es otro párrafo</p>
+ <ul>
+ <li>Este es un elemento de una lista no numerada (lista de viñetas)</li>
+ <li>Este es otro ítem</li>
+ <li>Y este es el último ítem de la lista</li>
+ </ul>
+ </body>
+ </html>
+
+<!-- En un archivo HTML siempre inicia indicando le al buscador que esta es una página HTML. -->
+<!doctype html>
+
+<!-- Después de esto, iniciamos abriendo una etiqueta html <html> -->
+<html>
+
+<!-- Cuando termine el archivo cerraremos la etiqueta así </html>. -->
+</html>
+
+<!-- Después de la etiqueta final nada aparecerá o podrá aparecer -->
+
+<!-- Dentro (Entre las etiquetas de apertura y cierre <html></html>), encontraremos: -->
+
+<!-- Un encabezado definido por <head> (Este debe ser cerrado por </head>). -->
+
+<!-- El encabezado contiene alguna descripción y información adicional que no se muestra; estos son los metadatos. -->
+
+<head>
+ <title>Mi Sitio</title><!-- La etiqueta <title> Indica al buscador el título a mostrar en la ventana del buscador en la barra de título y en el nombre de la pestaña. -->
+</head>
+
+<!-- Después de la sección del encabezado <head> , Encontraremos la etiqueta de cuerpo - <body> -->
+<!-- Hasta este punto. no hay nada descrito para que se muestre en la ventana del navegador -->
+<!-- Debemos llenar el cuerpo con el contenido que se mostrará -->
+
+<body>
+ <h1>Hola, Mundo!</h1> <!-- La etiqueta <h1> crea un título. -->
+ <!-- También tenemos subtítulos para <h1> desde la más importante <h2> a la más precisa <h6> -->
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">ven mira lo que esto muestra.</a> <!-- Un hipervínculo a la URL dada por el atributo href="" -->
+ <p>Esto es un párrafo.</p> <!-- La etiqueta <p> nos permite incluir texto en nuestra página HTML -->
+ <p>Este es otro párrafo.</p>
+ <ul> <!-- La etiqueta <ul> crea una lista de viñetas -->
+ <!-- Para tener una lista numerada usamos la etiqueta <ol> dando 1. para el primer elemento, 2. para el segundo, etc. -->
+ <li>Este es un elemento de una lista no numerada (lista de viñetas)</li>
+ <li>Este es otro ítem</li>
+ <li>Y este es el último ítem de la lista</li>
+ </ul>
+</body>
+
+<!-- Y esto es todo, la creación de un archivo HTML puede ser muy simple. -->
+
+<!-- Sin embargo, es posible añadir muchos otros tipos de etiquetas HTML -->
+
+<!-- Para insertar una imagen -->
+<img src="http://i.imgur.com/XWG0O.gif"/> <!-- La fuente donde se localiza la imagen se indica utilizando el atributo src=""-->
+<!-- La fuente puede ser una URL o incluso una ruta a una archivo en tu computador. -->
+
+<!-- También es posible crear una tabla -->
+
+<table> <!-- Abrimos una etiqueta o elemento tabla <table> -->
+ <tr> <!-- <tr> Nos permite crear una fila. -->
+ <th>Primer encabezado</th> <!-- <th> Nos permite dar un título a una columna de una tabla -->
+ <th>Segundo encabezado</th>
+ </tr>
+ <tr>
+ <td>Primera fila, primera columna</td> <!-- <td> nos permite crear una celda -->
+ <td>Primera fila, segunda columna</td>
+ </tr>
+ <tr>
+ <td>Segunda fila, primera columna</td>
+ <td>Segunda fila, segunda columna</td>
+ </tr>
+</table>
+
+```
+
+## Uso
+
+HTML es escrito en archivos que terminan con (extensión) `.html`.
+
+## Para aprender más!
+
+* [wikipedia](https://es.wikipedia.org/wiki/HTML)
+* [HTML tutorial](https://developer.mozilla.org/es/docs/Web/HTML)
+* [W3School (EN)](http://www.w3schools.com/html/html_intro.asp)
diff --git a/es-es/jquery-es.html.markdown b/es-es/jquery-es.html.markdown
new file mode 100644
index 00000000..d35e6f17
--- /dev/null
+++ b/es-es/jquery-es.html.markdown
@@ -0,0 +1,141 @@
+---
+category: tool
+tool: jquery
+contributors:
+ - ["Sawyer Charles", "https://github.com/xssc"]
+translators:
+ - ["Ivan Alburquerque", "https://github.com/AlburIvan"]
+lang: es-es
+filename: jquery-es.js
+---
+
+jQuery es una librería de JavaScript que le ayuda a "hacer más y escribir menos". Esto hace que muchas de las tareas comunes de JavaScript sean más fáciles de escribir. jQuery es utilizado por muchas de las grandes empresas y desarrolladores de todo el mundo. Hace que AJAX, la gestión de eventos, la manipulación de documentos, y mucho más, sea más fácil y rápido.
+
+Debido a que jQuery es una librería de JavaScript debes [aprender JavaScript primero](https://learnxinyminutes.com/docs/es-es/javascript-es/)
+
+```js
+
+
+///////////////////////////////////
+// 1. Selectores
+
+// Los selectores en jQuery son usados para seleccionar un elemento
+var page = $(window); // Selecciona toda la ventana gráfica
+
+// Los selectores también pueden ser selectores CSS
+var paragraph = $('p'); // Selecciona todos los elementos de párrafo
+var table1 = $('#table1'); // Selecciona el elemento con id 'tabla1'
+var squares = $('.square'); // Selecciona todos los elementos con la clase "square"
+var square_p = $('p.square') // Selecciona los párrafos con la clase "square"
+
+
+///////////////////////////////////
+// 2. Eventos y efectos
+
+// Un evento muy común que se utiliza es el evento 'ready' en el documento
+// Se puede utilizar el método de 'ready' para esperar hasta que el elemento haya terminado de cargar
+$(document).ready(function(){
+ // El código no se ejecutará hasta que el documento haya terminado de cargar
+});
+
+// jQuery es muy bueno activando eventos
+// Y también en el manejo de lo que ocurre cuando se activa un evento
+$('#button').click(); // Dispara un evento click en $ ('# botón')
+$('#button').click(function(){
+ // El código es ejecutado cuando se hace clic en el elemento de botón #
+});
+
+function onAction() {
+ // Esto se ejecuta cuando se activa el evento
+}
+
+// Algunos otros eventos comunes son:
+$('#btn').dblclick(onAction); //Doble clic
+$('#btn').hover(onAction); // Pasar el cursor por encima
+$('#btn').focus(onAction); // Enfocado
+$('#btn').blur(onAction); // Pierde enfoque
+$('#btn').submit(onAction); // Enviado
+$('#btn').select(onAction); // Cuando se selecciona un elemento
+$('#btn').keydown(onAction); // Cuando una tecla es empujada hacia abajo
+$('#btn').keyup(onAction); // Cuando se suelta una tecla
+$('#btn').keypress(onAction); // Cuando se pulsa una tecla
+$('#btn').mousemove(onAction); // Cuando se mueve el mouse
+$('#btn').mouseenter(onAction); // El mouse entra en el elemento
+$('#btn').mouseleave(onAction); // El mouse sale en el elemento
+
+// También se puede utilizar una función anónima
+$('#btn').hover(function(){
+ // Se ejecuta al pasar por encima
+});
+
+// Todos estos pueden también desencadenar el evento en lugar de manejarlo
+// Simplemente no pasando ningún parámetro
+$('#btn').dblclick(); // Dispara el evento de doble clic sobre el elemento
+
+// Se puede manejar múltiples eventos, usando el selector una vez
+$('#btn').on(
+ {dblclick: myFunction1} // Activado con doble clic
+ {blur: myFunction1} // Activo en la perdida de enfoque
+);
+
+// Puede mover y ocultar elementos con algunos métodos de efecto
+$('.table').hide(); # Oculta el(los) elemento(s)
+
+// Nota: llamar a una función en estos métodos aún oculta el elemento
+$('.table').hide(function(){
+ // El elemento se oculta entonces función ejecutada
+});
+
+// Puedes almacenar los selectores en las variables
+var tables = $('.table');
+
+// Algunos métodos básicos de manipulación de documento son:
+tables.hide(); // Oculta elemento(s)
+tables.show(); // Muestra elemento(s)
+tables.toggle(); // Cambia el estado de ocultar / mostrar
+tables.fadeOut(); // Desvanece
+tables.fadeIn(); // Fundirse
+tables.fadeToggle(); // Desvanece dentro o fuera
+tables.fadeTo(0.5); // Desvanece a una opacidad (entre 0 y 1)
+tables.slideUp(); // Desliza hacia arriba
+tables.slideDown(); // Desliza hacia abajo
+tables.slideToggle(); // Desliza hacia arriba o hacia abajo
+
+// Todo lo anterior toma una velocidad (milisegundos) y la función de devolución de llamada
+tables.hide(1000, myFunction); // Animación de ocultar elemento a 1 segundo y luego la funcion de devolución
+
+// 'fadeTo' requiere de una opacidad como su segundo parámetro
+tables.fadeTo(2000, 0.1, myFunction); // 2 segundos. decolorar a opacidad de 0.1 luego la función
+
+// Puede conseguir un efecto un poco más avanzado con el método 'animate'
+tables.animate({margin-top:"+=50", height: "100px"}, 500, myFunction);
+// El método 'animate' toma un objeto de CSS y los valores finales,
+// Parámetro opcional de opciones para afinar la animación,
+// Y por supuesto la función de devolución de llamada
+
+///////////////////////////////////
+// 3. Manipulación
+
+// Estos son similares a los efectos, pero pueden hacer más
+$('div').addClass('div') // Añade la clase div a todos los divs
+
+// Métodos comunes de manipulación
+$('p').append('Hola mundo'); // Añade al final del elemento
+$('p').attr('class'); // Obtiene atributo
+$('p').attr('class', 'content'); // Configura atributos
+$('p').hasClass('div'); //Devuelve verdadero si tiene la clase
+$('p').height(); // Obtiene la altura del elemento o define la altura
+
+
+// Para muchos métodos de manipulación, obtener información sobre un elemento
+// consigue solamente el primer elemento coincidente
+$('p').height(); // Obtiene sólo la altura de la primera etiqueta 'p'
+
+// Puedes utilizar 'each' para recorrer todos los elementos
+var heights = [];
+$('p').each(function() {
+ heights.push($(this.height)); // Añade todas las alturas "p" de la etiqueta a la matriz
+});
+
+
+``` \ No newline at end of file
diff --git a/es-es/kotlin-es.html.markdown b/es-es/kotlin-es.html.markdown
new file mode 100644
index 00000000..5d2f165a
--- /dev/null
+++ b/es-es/kotlin-es.html.markdown
@@ -0,0 +1,361 @@
+---
+language: kotlin
+contributors:
+- ["S Webber", "https://github.com/s-webber"]
+translators:
+- ["Ivan Alburquerque", "https://github.com/AlburIvan"]
+lang: es-es
+filename: LearnKotlin-es.kt
+---
+
+Kotlin es un lenguaje estático tipado para la JVM, Android y el navegador. Es
+100% interoperable con Java.
+[Leer mas aqui.](https://kotlinlang.org/)
+
+```java
+// Los comentarios de una sóla línea comienzan con //
+
+/*
+ Los comentarios multilínea lucen así
+*/
+
+// La palabra clave "package" funciona de la misma manera que Java.
+
+/*
+El punto de entrada para un programa de Kotlin es una función llamada "main".
+A dicha función se le pasa un arreglo que contiene los argumentos de la linea de comando.
+*/
+fun main(args: Array<String>) {
+ /*
+ La declaración de valores se realiza utilizando tanto "var" como "val".
+ Las declaraciones "val" no pueden ser reasignadas, mientras que "var" sí.
+ */
+ val fooVal = 10 // más adelante no podremos reasignar fooVal con un valor distinto.
+ var fooVar = 10
+ fooVar = 20 // fooVar puede ser reasignado
+
+ /*
+ En la mayoría de los casos, Kotlin puede determinar cuál es el tipo de una variable,
+ de tal manera que no tenemos que especificarlo explícitamente cada vez.
+    Podemos declarar explícitamente el tipo de una variable así:
+ */
+ val foo : Int = 7
+
+ /*
+ Las cadenas pueden ser representadas de la misma manera que Java.
+ El escape de caracteres se realiza con una barra invertida.
+ */
+ val fooString = "Mi Cadena está aquí!";
+ val barString = "¿Imprimiendo en una nueva línea?\nNo hay problema!";
+ val bazString = "¿Quíeres agregar una tabulación?\tNo hay problema!";
+ println(fooString);
+ println(barString);
+ println(bazString);
+
+ /*
+ Una cadena está delimitada por comillas triple (""").
+    Estas cadenas pueden contener saltos de línea y otros caracteres.
+ */
+ val fooRawString = """
+ fun helloWorld(val name : String) {
+ println("Hola, mundo!")
+ }
+ """
+ println(fooRawString)
+
+ /*
+ Las cadenas pueden contener interpolación de cadenas.
+    La interpolación de cadenas comienza con un signo de dólar ($).
+ */
+ val fooTemplateString = "$fooString tiene ${fooString.length} caracteres"
+ println(fooTemplateString)
+
+ /*
+ Para que una variable pueda aceptar valor nulo se debe especificar
+ explícitamente como anulable añadiendole ? a su tipo.
+    Podemos acceder a una variable anulable mediante el uso del operador ?.
+    Podemos utilizar el operador ?: para especificar un valor alternativo
+ a usar si una variable es nula.
+ */
+ var fooNullable: String? = "abc"
+ println(fooNullable?.length) // => 3
+ println(fooNullable?.length ?: -1) // => 3
+ fooNullable = null
+ println(fooNullable?.length) // => null
+ println(fooNullable?.length ?: -1) // => -1
+
+
+ /*
+ Las funciones pueden ser declaras usando la palabra clave "fun".
+ Los argumentos de las funciones son especificados entre corchetes despues del nombre de la función.
+ Los argumentos de las funciones pueden tener opcionalmente un valor por defecto.
+ El tipo de retorno de las funciones, de ser requerido, es especificado despues del argumento.
+ */
+ fun hello(name: String = "mundo") : String {
+ return "Hola, $name!"
+ }
+ println(hello("foo")) // => Hola, foo!
+ println(hello(name = "bar")) // => Hola, bar!
+ println(hello()) // => Hola, mundo!
+
+ /*
+ Un parametro de la función puede ser marcado con la palabra clave "vararg"
+ que permite que una función acepte un numero variable de argumentos.
+ */
+ fun varargExample(vararg names: Int) {
+ println("Argument tiene ${names.size} elementos")
+ }
+ varargExample() // => Argument tiene 0 elementos
+ varargExample(1) // => Argument tiene 1 elementos
+ varargExample(1, 2, 3) // => Argument tiene 3 elementos
+
+ /*
+ Cuando una función consiste de una sola expresión entonces las llaves
+ pueden ser omitidas. El cuerpo es especificado despues del símbolo =
+ */
+ fun odd(x: Int): Boolean = x % 2 == 1
+ println(odd(6)) // => false
+ println(odd(7)) // => true
+
+ // Si el tipo de retorno puede ser inferido entonces no se necesita
+ // especificarlo.
+ fun even(x: Int) = x % 2 == 0
+ println(even(6)) // => true
+ println(even(7)) // => false
+
+ // Las funciones pueden tomar funciones como argumentos y
+ // retornar funciones.
+ fun not(f: (Int) -> Boolean) : (Int) -> Boolean {
+ return {n -> !f.invoke(n)}
+ }
+
+ // Las funciones con nombre pueden ser especificadas como argumentos
+ // utilizando el operador ::.
+ val notOdd = not(::odd)
+ val notEven = not(::even)
+ // Las funciones anónimas pueden ser especificadas como argumentos.
+ val notZero = not {n -> n == 0}
+ /*
+ Si una función anónima tiene un solo parametro entonces la declaración
+ puede ser omitida (junto con ->). El nombre del único parametro será "it".
+ */
+ val notPositive = not {it > 0}
+ for (i in 0..4) {
+ println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}")
+ }
+
+ // La palabra clave "class" es usada para declarar clases.
+ class ExampleClass(val x: Int) {
+ fun memberFunction(y: Int) : Int {
+ return x + y
+ }
+
+ infix fun infixMemberFunction(y: Int) : Int {
+ return x * y
+ }
+ }
+ /*
+ Para crear una nueva instancia llamamos al constructor.
+ Nótese que Kotlin no usa la palabra clave "new".
+ */
+ val fooExampleClass = ExampleClass(7)
+ // Las funciones miembros pueden ser llamadas usando la notación de punto (.)
+ println(fooExampleClass.memberFunction(4)) // => 11
+ /*
+ Si una función ha sido marcada con la palabra clave "infix" entonces
+ esta puede ser invocada usando la notación infija.
+ */
+ println(fooExampleClass infixMemberFunction 4) // => 28
+
+ /*
+ Las clases "data" son una manera concisa de crear clases que solo contengan datos.
+ Los metodos "hashCode"/"equals" y "toString" son generados automáticamente.
+ */
+ data class DataClassExample (val x: Int, val y: Int, val z: Int)
+ val fooData = DataClassExample(1, 2, 4)
+ println(fooData) // => DataClassExample(x=1, y=2, z=4)
+
+ // las clases de datos tienen una función "copy".
+ val fooCopy = fooData.copy(y = 100)
+ println(fooCopy) // => DataClassExample(x=1, y=100, z=4)
+
+ // Los objetos pueden ser estructurados en múltiples variables.
+ val (a, b, c) = fooCopy
+ println("$a $b $c") // => 1 100 4
+
+ // La función "with" es similar a la expresión de JavaScript "with".
+ data class MutableDataClassExample (var x: Int, var y: Int, var z: Int)
+ val fooMutableDate = MutableDataClassExample(7, 4, 9)
+ with (fooMutableDate) {
+ x -= 2
+ y += 2
+ z--
+ }
+ println(fooMutableDate) // => MutableDataClassExample(x=5, y=6, z=8)
+
+ /*
+ Podemos crear una lista utilizando la función "listOf".
+ La lista será inmutable - los elementos no pueden ser añadidos o eliminados.
+ */
+ val fooList = listOf("a", "b", "c")
+ println(fooList.size) // => 3
+ println(fooList.first()) // => a
+ println(fooList.last()) // => c
+ // Los elementos de una lista se pueden acceder a través de su índice.
+ println(fooList[1]) // => b
+
+ // Una lista mutable puede ser creada usando la función "mutableListOf".
+ val fooMutableList = mutableListOf("a", "b", "c")
+ fooMutableList.add("d")
+ println(fooMutableList.last()) // => d
+ println(fooMutableList.size) // => 4
+
+ // Podemos crear un set usando la función "setOf".
+ val fooSet = setOf("a", "b", "c")
+ println(fooSet.contains("a")) // => true
+ println(fooSet.contains("z")) // => false
+
+ // Podemos crear un mapa usando la función "mapOf".
+ val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9)
+ // Se puede acceder a los valores del mapa por su llave.
+ println(fooMap["a"]) // => 8
+
+ /*
+ Las secuencias representan colecciones evaluadas diferidamente.
+ Podemos crear una secuencia con la función "generateSequence".
+ */
+ val fooSequence = generateSequence(1, {it + 1})
+ val x = fooSequence.take(10).toList()
+ println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+
+ // Un ejemplo usando las secuencias para generar los números de Fibonacci:
+ fun fibonacciSequence() : Sequence<Long> {
+ var a = 0L
+ var b = 1L
+
+ fun next() : Long {
+ val result = a + b
+ a = b
+ b = result
+ return a
+ }
+
+ return generateSequence(::next)
+ }
+ val y = fibonacciSequence().take(10).toList()
+ println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
+
+ // Kotlin provee funciones de Orden-Mayor para trabajar con colecciones.
+ val z = (1..9).map {it * 3}
+ .filter {it < 20}
+ .groupBy {it % 2 == 0}
+ .mapKeys {if (it.key) "even" else "odd"}
+ println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]}
+
+ // Un bucle "for" puede ser usado con cualquier cosa que provea un iterador.
+ for (c in "hello") {
+ println(c)
+ }
+
+ // El bucle "while" funciona de la misma manera que en los demás lenguajes.
+ var ctr = 0
+ while (ctr < 5) {
+ println(ctr)
+ ctr++
+ }
+ do {
+ println(ctr)
+ ctr++
+ } while (ctr < 10)
+
+ /*
+ "if" puede ser usado como una expresión que retorna un valor.
+ Por esta razón el operador ternario ?: no es necesario en Kotlin.
+ */
+ val num = 5
+ val message = if (num % 2 == 0) "even" else "odd"
+ println("$num is $message") // => 5 is odd
+
+ // "when" puede ser usado como alternativa a cadenas de "if-else if".
+ val i = 10
+ when {
+ i < 7 -> println("primer bloque")
+ fooString.startsWith("hello") -> println("segundo bloque")
+ else -> println("else bloque")
+ }
+
+ // "when" puede ser usado con argumentos.
+ when (i) {
+ 0, 21 -> println("0 or 21")
+ in 1..20 -> println("in the range 1 to 20")
+ else -> println("none of the above")
+ }
+
+ // "when" puede ser usado como una función que retorna un valor.
+ var result = when (i) {
+ 0, 21 -> "0 or 21"
+ in 1..20 -> "in the range 1 to 20"
+ else -> "none of the above"
+ }
+ println(result)
+
+ /*
+ Podemos analizar si un objeto es de un tipo particular usando el operador "is".
+ Si un objeto pasa un chequeo de tipo entonces éste se puede utilizar como
+ ese tipo sin convertido de forma explícita.
+ */
+ fun smartCastExample(x: Any) : Boolean {
+ if (x is Boolean) {
+ // x es automaticamente convertido a Boolean
+ return x
+ } else if (x is Int) {
+ // x es automaticamente convertido a Int
+ return x > 0
+ } else if (x is String) {
+ // x es automaticamente convertido a String
+ return x.isNotEmpty()
+ } else {
+ return false
+ }
+ }
+ println(smartCastExample("Hola, mundo!")) // => true
+ println(smartCastExample("")) // => false
+ println(smartCastExample(5)) // => true
+ println(smartCastExample(0)) // => false
+ println(smartCastExample(true)) // => true
+
+ /*
+ Las extensiones son una manera de añadir nuevas funcionalidades a una clase.
+ Estas son similares a la extensión de métodos en C#.
+ */
+ fun String.remove(c: Char): String {
+ return this.filter {it != c}
+ }
+ println("Hola, mundo!".remove('l')) // => Hoa, mundo!
+
+ println(EnumExample.A) // => A
+ println(ObjectExample.hello()) // => hola
+}
+
+// Las clases "enum" son similares a los tipos "enum" de Java.
+enum class EnumExample {
+ A, B, C
+}
+
+/*
+La palabra clave "object" se puede utilizar para crear objetos únicos.
+No podemos asignarlo a una variable, pero podemos hacer referencia a ella por su nombre.
+Esto es similar a los objetos únicos de Scala
+*/
+object ObjectExample {
+ fun hello() : String {
+ return "hola"
+ }
+}
+```
+
+### Lectura Adicional
+
+* [Kotlin tutorials (EN)](https://kotlinlang.org/docs/tutorials/)
+* [Try Kotlin in your browser (EN)](http://try.kotlinlang.org/)
+* [A list of Kotlin resources (EN)](http://kotlin.link/)
diff --git a/es-es/php-composer-es.html.markdown b/es-es/php-composer-es.html.markdown
new file mode 100644
index 00000000..3add3e31
--- /dev/null
+++ b/es-es/php-composer-es.html.markdown
@@ -0,0 +1,176 @@
+---
+category: tool
+tool: composer
+contributors:
+ - ["Brett Taylor", "https://github.com/glutnix"]
+translators:
+ - ["Ivan Alburquerque", "https://github.com/AlburIvan"]
+lang: es-es
+filename: LearnComposer-es.sh
+---
+
+[Composer](https://getcomposer.org/) es una herramienta para manejar las dependencias en PHP. Nos permite declarar las librerías de las cuales el proyecto depende y las maneja automáticamente (instala/actualiza) por ti.
+
+# Instalando
+
+```sh
+# Instala el binario 'composer.phar' en el directorio actual
+curl -sS https://getcomposer.org/installer | php
+# Si utiliza este método, tendrá que invocar a 'composer' de esta manera:
+php composer.phar about
+
+# Instala el binario en ~/bin/composer
+# Nota: asegúrese de que ~/bin está en la variable de entorno PATH del shell
+curl -sS https://getcomposer.org/installer | php -- --install-dir=~/bin --filename=composer
+```
+
+Los usuarios de Windows deben seguir las [instrucciones de instalación de Windows (EN)](https://getcomposer.org/doc/00-intro.md#installation-windows)
+
+## Confirmación de la instalación
+
+```sh
+# Comprobar la versión y lista las opciones
+composer
+
+# Obtener más ayuda para las opciones
+composer help require
+
+# Comprueba si composer es capaz hacer las cosas que necesita y si está actualizado
+composer diagnose
+composer diag # versión corta
+
+# Actualiza el binario composer a la última versión
+composer self-update
+composer self # versión corta
+```
+
+# Uso
+
+Composer almacena sus dependencias del proyecto en `composer.json`. Usted puede editar este archivo, pero lo mejor es dejar que composer lo gestione por usted.
+
+```sh
+# Crear un nuevo proyecto en la carpeta actual
+composer init
+# Este corre un cuestionario interactivo que le pide detalles sobre su proyecto.
+# Dejándolos en blanco está bien a menos que usted está haciendo otros proyectos que dependen de éste.
+
+# Si un archivo 'composer.json' ya existe, descargar las dependencias
+composer install
+
+# Para descargar solo las dependencias de producción, es decir, excluyendo las
+# dependencias de desarrollo
+composer install --no-dev
+
+# Añadir una dependencia de producción a este proyecto
+composer require guzzlehttp/guzzle
+# Composer buscará cuál es la última versión de guzzlehttp/Guzzle, lo descarga,
+# y finalmente añade la nueva dependencia al campo requerido en 'composer.json'.
+
+composer require guzzlehttp/guzzle:6.0.*
+# Composer descargará la versión más reciente que coincida con el patrón
+# (ej 6.0.2) y añade la dependencia al campo requerido en 'composer.json'.
+
+composer require --dev phpunit/phpunit:~4.5.0
+# Se requerirá como una dependencia de desarrollo. Se usará la última
+# versión >= 4.5.0 y < 4.6.0
+
+composer require-dev phpunit/phpunit:^4.5.0
+# Se requerirá como una dependencia de desarrollo. Se usará la última versión >= 4.5.0 y < 5.0
+
+# Para obtener más información sobre las coincidencias de versiones de Composer,
+ver [La Documentación de Composer\'s Sobre Versiones (EN)](https://getcomposer.org/doc/articles/versions.md)
+
+# Para ver qué opciones están disponibles para instalar y los paquetes instalados actualmente
+composer show
+
+# Para ver qué paquetes están instalados actualmente
+composer show --installed
+
+# Para encontrar un paquete con 'mailgun' en su nombre o descripción
+composer search mailgun
+```
+
+[Packagist.org (EN)](https://packagist.org/) es el repositorio principal de paquetes de Composer. Busca allí para paquetes existentes de terceros.
+
+## `composer.json` vs `composer.lock`
+
+El archivo `composer.json` almacena las preferencias de versión flotantes de su proyecto para cada dependencia, junto con otra información.
+
+El archivo `composer.lock` almacena exactamente cuál es la versión que ha descargado para cada dependencia. Nunca editar este archivo.
+
+Si se incluye el archivo `composer.lock` en su repositorio git, todos los desarrolladores instalarán la versión utilizada actualmente de la dependencia. Incluso cuando se libera una nueva versión de una dependencia, Composer continuará para descargar la versión grabada en el archivo '.lock'.
+
+```sh
+# Si desea actualizar todas las dependencias a su versión más reciente aún que coincidan con sus preferencias versión
+composer update
+
+# Si desea la nueva versión de una dependencia particular:
+composer update phpunit/phpunit
+
+# Si desea migrar la preferencia de un paquete a una versión más reciente, puede que tenga que quitar primero el paquete de más antiguo y sus dependencias.
+composer remove --dev phpunit/phpunit
+composer require --dev phpunit/phpunit:^5.0
+
+```
+
+## Autocargador
+
+Composer crea una clase de cargador automático que puede requerir su aplicación. Se puede hacer instancias de clases a través de su espacio de nombres.
+
+```php
+require __DIR__ . '/vendor/autoload.php';
+
+$mailgun = new Mailgun\Mailgun("key");
+```
+
+### PSR-4 Autocargador
+
+Usted puede añadir sus propios espacios de nombres para el cargador automático.
+
+En `composer.json`, añadir el campo 'autoload':
+
+```json
+{
+ "autoload": {
+ "psr-4": {"Acme\\": "src/"}
+ }
+}
+```
+Esto le indicará al cargador automático que busque cualquier cosa en el espacio de nombres `\Acme\` dentro de la carpeta src`.
+
+También puedes usar [usar PSR-0, un mapa de clase o simplemente una lista de archivos para incluir (EN)](https://getcomposer.org/doc/04-schema.md#autoload). También está el campo `autoload-dev` para espacios de nombres de sólo desarrollo.
+
+Al añadir o modificar la clave de carga automática, tendrá que reconstruir el cargador automático:
+
+```sh
+composer dump-autoload
+composer dump # shorthand
+
+# Optimiza los paquetes PSR0 y PSR4 a ser cargados con classmaps también. Es lento para correr, pero mejora el rendimiento en producción.
+composer dump-autoload --optimize --no-dev
+```
+
+# El Cache de Composer
+
+```sh
+# Composer retendrá los paquetes descargados para su uso en el futuro. Puede removerlos con:
+composer clear-cache
+```
+
+# Solución de problemas
+
+```sh
+composer diagnose
+composer self-update
+composer clear-cache
+```
+
+## Temas (todavía) no cubiertos en este tutorial
+
+* Crear y distribuir tus propios paquetes en Packagist.org o en otra parte
+* Pre- y post- script: ejecutar tareas cuando ciertos eventos tienen lugar composer
+
+### Referencias
+
+* [Composer - Dependency Manager for PHP (EN)](https://getcomposer.org/)
+* [Packagist.org (EN)](https://packagist.org/) \ No newline at end of file
diff --git a/es-es/racket-es.html.markdown b/es-es/racket-es.html.markdown
new file mode 100644
index 00000000..a49509c7
--- /dev/null
+++ b/es-es/racket-es.html.markdown
@@ -0,0 +1,683 @@
+---
+language: racket
+filename: learnracket-es.rkt
+contributors:
+ - ["th3rac25", "https://github.com/voila"]
+ - ["Eli Barzilay", "https://github.com/elibarzilay"]
+ - ["Gustavo Schmidt", "https://github.com/gustavoschmidt"]
+ - ["Duong H. Nguyen", "https://github.com/cmpitg"]
+ - ["Keyan Zhang", "https://github.com/keyanzhang"]
+translators:
+ - ["Carlos Roman", "https://github.com/carlochess"]
+lang: es-es
+---
+Racket es un lenguaje de propósito general, multiparadigma que hace parte de la familia Lisp/Scheme.
+
+```racket
+#lang racket ; Define el lenguaje que usas
+
+;;; Comentarios
+
+;; Los comentarios de una sola línea inician con un punto y coma
+
+#| Un bloque de comentarios
+ puede distribuirse en varias líneas...
+ #|
+ ¡Incluso puede estar anidado!
+ |#
+|#
+
+;; Los comentarios descartan la siguiente expresión,
+;; pero son útiles para comentar expresiones al momento de depurar el código
+#; (Esta expresión es descartada)
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 1. Tipos de datos primitivos y operadores
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;;; Numeros
+9999999999999999999999 ; Enteros
+#b111 ; binario => 7
+#o111 ; octal => 73
+#x111 ; hexadecimal => 273
+3.14 ; reales
+6.02e+23
+1/2 ; racionaless
+1+2i ; numeros complejos
+
+;; La aplicación de funciones es escrita de la siguiente forma: (f x y z ...)
+;; donde f es una función y “x, y, z” son sus operandos
+;; Si quieres crear una lista de literales debes agregar ' al inicio
+;; para que no sean evaluados
+'(+ 1 2) ; => (+ 1 2)
+;; Ahora algunas operaciones aritméticas
+(+ 1 1) ; => 2
+(- 8 1) ; => 7
+(* 10 2) ; => 20
+(expt 2 3) ; => 8
+(quotient 5 2) ; => 2
+(remainder 5 2) ; => 1
+(/ 35 5) ; => 7
+(/ 1 3) ; => 1/3
+(exact->inexact 1/3) ; => 0.3333333333333333
+(+ 1+2i 2-3i) ; => 3-1i
+
+;;; Booleanos
+#t ; Para verdadero (true)
+#f ; Para falso (false) -- cualquier valor distinto de #f es verdadero
+(not #t) ; => #f
+(and 0 #f (error "No entra aquí")) ; => #f
+(or #f 0 (error "No entra aquí")) ; => 0
+
+;;; Caracteres
+#\A ; => #\A
+#\λ ; => #\λ
+#\u03BB ; => #\λ
+
+;;; Los Strings tienen una longitud fija
+"Hello, world!"
+"Benjamin \"Bugsy\" Siegel" ; backslash es un caracter de escape
+"Foo\tbar\41\x21\u0021\a\r\n" ; incluye escape para C, Unicode
+"λx:(μα.α→α).xx" ; Puedes incluir caracteres Unicode
+
+;; ¡Los tipos de dato Strings pueden unirse tambien!
+(string-append "Hello " "world!") ; => "Hello world!"
+
+;; Un string puede ser tratado como una lista de caracteres
+(string-ref "Apple" 0) ; => #\A
+
+;; la función format puede usarse para darle formato a un string:
+(format "~a can be ~a" "strings" "formatted")
+
+;; Imprimir en consola es muy simple
+(printf "I'm Racket. Nice to meet you!\n")
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 2. Variables
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; Puedes crear una variable usando define
+;; el nombre de una variable puede contener cualquier nombre excepto: ()[]{}",'`;#|\
+(define some-var 5)
+some-var ; => 5
+
+;; También puedes usar caracteres unicode
+(define ⊆ subset?)
+(⊆ (set 3 2) (set 1 2 3)) ; => #t
+
+;; Acceder a una variable no definida con anterioridad resulta en una excepción
+; x ; => x: undefined ...
+
+;; Local binding: La variable 'me' esta limitada a tomar el valor "Bob" dentro del ambiente (let ...)
+(let ([me "Bob"])
+ "Alice"
+ me) ; => "Bob"
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 3. Estructuras y colecciones
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Estructuras
+(struct dog (name breed age))
+(define my-pet
+ (dog "lassie" "collie" 5))
+my-pet ; => #<dog>
+(dog? my-pet) ; => #t
+(dog-name my-pet) ; => "lassie"
+
+;;; Parejas (Inmutables)
+;; 'cons' construye parejas, 'car' y 'cdr' extraen el primer
+;; y segundo elemento respectivamente de una pareja
+(cons 1 2) ; => '(1 . 2)
+(car (cons 1 2)) ; => 1
+(cdr (cons 1 2)) ; => 2
+
+;;; Listas
+
+;; Las Listas son estructuras secuenciales no indexadas, hechas con ‘cons’ y
+;; con un 'null' (o '()) para denotar el final de la lista
+(cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3)
+;; 'list' es otro constructor apropiado para las listas
+(list 1 2 3) ; => '(1 2 3)
+;; y el simbolo comilla (') puede ser usado en una lista de valores literales
+'(1 2 3) ; => '(1 2 3)
+
+;; Aquí aun se puede usar 'cons' para agregar un elemento al comienzo de la lista
+(cons 4 '(1 2 3)) ; => '(4 1 2 3)
+
+;; El uso de 'append' para unir un par de listas
+(append '(1 2) '(3 4)) ; => '(1 2 3 4)
+
+;; Las listas son un tipo de dato básico, por lo cual proveen numerosas funcionalidades;
+;; algunos ejemplos son:
+(map add1 '(1 2 3)) ; => '(2 3 4)
+(map + '(1 2 3) '(10 20 30)) ; => '(11 22 33)
+(filter even? '(1 2 3 4)) ; => '(2 4)
+(count even? '(1 2 3 4)) ; => 2
+(take '(1 2 3 4) 2) ; => '(1 2)
+(drop '(1 2 3 4) 2) ; => '(3 4)
+
+;;; Vectores
+
+;; Los Vectores son arreglos de longitud fija
+#(1 2 3) ; => '#(1 2 3)
+
+;; Se usa 'vector-append' para unir dos vectores
+(vector-append #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6)
+
+;;; Conjuntos
+
+;; Crear un conjunto a partir de una lista
+(list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3)
+
+;; Agregar/Asignar un nuevo elemento 'set-add'
+;; (Funcional: retorna un conjunto extendido en vez de una mutar la entrada)
+(set-add (set 1 2 3) 4) ; => (set 1 2 3 4)
+
+;; Remueve el elemento agregado anteriormente 'set-remove'
+(set-remove (set 1 2 3) 1) ; => (set 2 3)
+
+;; Prueba la existencia de un elemento con la funcion 'set-member?'
+(set-member? (set 1 2 3) 1) ; => #t
+(set-member? (set 1 2 3) 4) ; => #f
+
+;;; Tablas Hashs
+
+;; Crea una tabla hash inmutable (Abajo presentamos un ejemplo)
+(define m (hash 'a 1 'b 2 'c 3))
+
+;; Conseguir un valor
+(hash-ref m 'a) ; => 1
+
+;; Conseguir un valor que no está presente es una excepción
+; (hash-ref m 'd) => no value found
+
+;; Puedes proveer un valor por defecto si el valor para la llave no se encuentra
+(hash-ref m 'd 0) ; => 0
+
+;; Usa 'hash-set' para ampliar un tabla hash “inmutable”
+;; (Retorna la tabla hash extendida en vez de una mutarla)
+(define m2 (hash-set m 'd 4))
+m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3))
+
+;; ¡Recuerde que estas tablas hash son inmutables!
+m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no 'd'
+
+;; Usa 'hash-remove' para quitar las llaves de la tabla hash (functional tambien)
+(hash-remove m 'a) ; => '#hash((b . 2) (c . 3))
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 3. Funciones
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Usa 'lambda' para crear funciones.
+;; Una función siempre retorna el valor de su última expresión
+(lambda () "Hello World") ; => #<procedure>
+;; También se puede usar el caracter Unicode 'λ'
+(λ () "Hello World") ; => same function
+
+;; Usa los paréntesis exteriores para llamar la función
+((lambda () "Hello World")) ; => "Hello World"
+((λ () "Hello World")) ; => "Hello World"
+
+;; Asigna una función a una variable
+(define hello-world (lambda () "Hello World"))
+(hello-world) ; => "Hello World"
+
+;; Puede acortar esto usando el azúcar sintáctico para la definición de una función:
+(define (hello-world2) "Hello World")
+
+;; El paréntesis () del ejemplo anterior denota la lista de argumentos para la función
+(define hello
+ (lambda (name)
+ (string-append "Hello " name)))
+(hello "Steve") ; => "Hello Steve"
+;; ... O de forma similar, usando el azúcar sintáctico para una definición:
+(define (hello2 name)
+ (string-append "Hello " name))
+
+;; Puedes tener una función con parametros variables, using 'case-lambda'
+(define hello3
+ (case-lambda
+ [() "Hello World"]
+ [(name) (string-append "Hello " name)]))
+(hello3 "Jake") ; => "Hello Jake"
+(hello3) ; => "Hello World"
+;; ... o especificar los argumentos opcionales junto con su valor por defecto
+(define (hello4 [name "World"])
+ (string-append "Hello " name))
+
+;; Las funciones pueden tener argumentos extra empaquetados como una lista
+(define (count-args . args)
+ (format "You passed ~a args: ~a" (length args) args))
+(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)"
+;; ... o sin usar el azúcar sintáctico:
+(define count-args2
+ (lambda args
+ (format "You passed ~a args: ~a" (length args) args)))
+
+;; Puedes combinar argumentos regulares y empaquetados
+(define (hello-count name . args)
+ (format "Hello ~a, you passed ~a extra args" name (length args)))
+(hello-count "Finn" 1 2 3)
+; => "Hello Finn, you passed 3 extra args"
+;; ... Sin usar azúcar sintáctica:
+(define hello-count2
+ (lambda (name . args)
+ (format "Hello ~a, you passed ~a extra args" name (length args))))
+
+;; Y con keywords
+(define (hello-k #:name [name "World"] #:greeting [g "Hello"] . args)
+ (format "~a ~a, ~a extra args" g name (length args)))
+(hello-k) ; => "Hello World, 0 extra args"
+(hello-k 1 2 3) ; => "Hello World, 3 extra args"
+(hello-k #:greeting "Hi") ; => "Hi World, 0 extra args"
+(hello-k #:name "Finn" #:greeting "Hey") ; => "Hey Finn, 0 extra args"
+(hello-k 1 2 3 #:greeting "Hi" #:name "Finn" 4 5 6)
+ ; => "Hi Finn, 6 extra args"
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 4. Comparando
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Para números usa '='
+(= 3 3.0) ; => #t
+(= 2 1) ; => #f
+
+;; 'eq?' retorna #t si 2 argumentos refieren al mismo objeto en memoria
+;; #f de lo contrario.
+;; En otras palabras, es una simple comparación de punteros.
+(eq? '() '()) ; => #t, Debido a que existe solo una lista vacia en memoria
+(let ([x '()] [y '()])
+ (eq? x y)) ; => #t, igual que arriba
+
+(eq? (list 3) (list 3)) ; => #f
+(let ([x (list 3)] [y (list 3)])
+ (eq? x y)) ; => #f — ¡No es la misma lista en memoria!
+
+(let* ([x (list 3)] [y x])
+ (eq? x y)) ; => #t, debido a que ‘x’ y ‘y’ ahora apuntan a la misma posición en memoria
+
+(eq? 'yes 'yes) ; => #t
+(eq? 'yes 'no) ; => #f
+
+(eq? 3 3) ; => #t — Te cuidado aqui
+ ; es mejor usar '=' para comparacion de numeros.
+(eq? 3 3.0) ; => #f
+
+(eq? (expt 2 100) (expt 2 100)) ; => #f
+(eq? (integer->char 955) (integer->char 955)) ; => #f
+
+(eq? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f
+
+;; 'eqv?' permite comparar números y caracteres..
+;; for other datatypes, 'eqv?' and 'eq?' return the same result.
+(eqv? 3 3.0) ; => #f
+(eqv? (expt 2 100) (expt 2 100)) ; => #t
+(eqv? (integer->char 955) (integer->char 955)) ; => #t
+
+(eqv? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f
+
+;; 'equal?' permite comparar los siguientes tipos de datos:
+;; strings, byte strings, pairs, mutable pairs, vectors, boxes,
+;; hash tables, and inspectable estructuras.
+;; para otros tipos de datos, 'equal?' y 'eqv?' devuelven el mismo resultado.
+(equal? 3 3.0) ; => #f
+(equal? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #t
+(equal? (list 3) (list 3)) ; => #t
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 5. Control de flujo
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;;; Condicionales
+
+(if #t ; expresión de prueba
+ "this is true" ; expresión si la expresión de prueba es verdadera
+ "this is false") ; de lo contrario expression
+; => "this is true"
+
+;; En condicionales, todos los valores que no son #f son tratados como verdadero
+(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(Groucho Zeppo)
+(if (member 'Groucho '(Harpo Groucho Zeppo))
+ 'yep
+ 'nope)
+; => 'yep
+
+;; Las expresiones 'cond' son una serie de pruebas para seleccionar el resultado
+(cond [(> 2 2) (error "wrong!")]
+ [(< 2 2) (error "wrong again!")]
+ [else 'ok]) ; => 'ok
+
+;;; Coincidencia de patrones (Pattern Matching)
+
+(define (fizzbuzz? n)
+ (match (list (remainder n 3) (remainder n 5))
+ [(list 0 0) 'fizzbuzz]
+ [(list 0 _) 'fizz]
+ [(list _ 0) 'buzz]
+ [_ #f]))
+
+(fizzbuzz? 15) ; => 'fizzbuzz
+(fizzbuzz? 37) ; => #f
+
+;;; Ciclos
+
+;; Los ciclos pueden expresarse a través de recursión (de cola)
+(define (loop i)
+ (when (< i 10)
+ (printf "i=~a\n" i)
+ (loop (add1 i))))
+(loop 5) ; => i=5, i=6, ...
+
+;; De igual forma, con un let
+(let loop ((i 0))
+ (when (< i 10)
+ (printf "i=~a\n" i)
+ (loop (add1 i)))) ; => i=0, i=1, ...
+
+;; El siguiente ejemplo muestra cómo expresar un ciclo for, pero Racket tiene
+;; otra forma aún más flexible de expresarlos:
+(for ([i 10])
+ (printf "i=~a\n" i)) ; => i=0, i=1, ...
+(for ([i (in-range 5 10)])
+ (printf "i=~a\n" i)) ; => i=5, i=6, ...
+
+;;; Iterando sobre otras secuencias
+;; 'for' permite iterar sobre varios tipos de secuencias:
+;; lists, vectors, strings, sets, hash tables, etc...
+
+(for ([i (in-list '(l i s t))])
+ (displayln i))
+
+(for ([i (in-vector #(v e c t o r))])
+ (displayln i))
+
+(for ([i (in-string "string")])
+ (displayln i))
+
+(for ([i (in-set (set 'x 'y 'z))])
+ (displayln i))
+
+(for ([(k v) (in-hash (hash 'a 1 'b 2 'c 3 ))])
+ (printf "key:~a value:~a\n" k v))
+
+;;; Iteradores mas sofisticados
+
+;; Escaneo paralelo de múltiples secuencias (se detiene en la más pequeña)
+(for ([i 10] [j '(x y z)]) (printf "~a:~a\n" i j))
+; => 0:x 1:y 2:z
+
+;; Loops anidados
+(for* ([i 2] [j '(x y z)]) (printf "~a:~a\n" i j))
+; => 0:x, 0:y, 0:z, 1:x, 1:y, 1:z
+
+;; Condicionales
+(for ([i 1000]
+ #:when (> i 5)
+ #:unless (odd? i)
+ #:break (> i 10))
+ (printf "i=~a\n" i))
+; => i=6, i=8, i=10
+
+;;; Secuncias por compresión
+;; Muy similar a los ciclos 'for' -- solo recolectando los resultados
+
+(for/list ([i '(1 2 3)])
+ (add1 i)) ; => '(2 3 4)
+
+(for/list ([i '(1 2 3)] #:when (even? i))
+ i) ; => '(2)
+
+(for/list ([i 10] [j '(x y z)])
+ (list i j)) ; => '((0 x) (1 y) (2 z))
+
+(for/list ([i 1000] #:when (> i 5) #:unless (odd? i) #:break (> i 10))
+ i) ; => '(6 8 10)
+
+(for/hash ([i '(1 2 3)])
+ (values i (number->string i)))
+; => '#hash((1 . "1") (2 . "2") (3 . "3"))
+
+;; Existen otras formas de recolectar los valores usando otras expresiones:
+(for/sum ([i 10]) (* i i)) ; => 285
+(for/product ([i (in-range 1 11)]) (* i i)) ; => 13168189440000
+(for/and ([i 10] [j (in-range 10 20)]) (< i j)) ; => #t
+(for/or ([i 10] [j (in-range 0 20 2)]) (= i j)) ; => #t
+;; Y para usar cualquier combinación arbitraria, use 'for/fold'
+(for/fold ([sum 0]) ([i '(1 2 3 4)]) (+ sum i)) ; => 10
+;; (Esto frecuentemente reemplaza los ciclos en los lenguajes imperativos)
+
+;;; Excepciones
+
+;; Para atrapar excepciones, usa las funciones 'with-handlers'
+(with-handlers ([exn:fail? (lambda (exn) 999)])
+ (+ 1 "2")) ; => 999
+(with-handlers ([exn:break? (lambda (exn) "no time")])
+ (sleep 3)
+ "phew") ; => "phew", pero si usa un break => "no time"
+
+;; Usa 'raise' para lanzar una excepción o cualquier otro valor
+(with-handlers ([number? ; atrapa valores numericos lanzados
+ identity]) ; los retorna como valores
+ (+ 1 (raise 2))) ; => 2
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 6. Mutación
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Usa 'set!' para asignar un nuevo valor a una variable existente
+(define n 5)
+(set! n (add1 n))
+n ; => 6
+
+;; Usa boxes para valores explícitamente mutables (similar a punteros o
+;; referencias en otros lenguajes)
+(define n* (box 5))
+(set-box! n* (add1 (unbox n*)))
+(unbox n*) ; => 6
+
+;; Muchos tipos de datos en Racket son inmutables (pairs, lists, etc), algunos poseen
+;; ambos sabores mutable e immutable (strings, vectors, hash tables,
+;; etc...)
+
+;; Usa 'vector' o 'make-vector' para crear vectores mutables
+(define vec (vector 2 2 3 4))
+(define wall (make-vector 100 'bottle-of-beer))
+;; Usa vector-set! para actualizar una posición
+(vector-set! vec 0 1)
+(vector-set! wall 99 'down)
+vec ; => #(1 2 3 4)
+
+;; Crea una tabla hash vacía y manipulata
+(define m3 (make-hash))
+(hash-set! m3 'a 1)
+(hash-set! m3 'b 2)
+(hash-set! m3 'c 3)
+(hash-ref m3 'a) ; => 1
+(hash-ref m3 'd 0) ; => 0
+(hash-remove! m3 'a)
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 7. Modulos
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Los Modulos permiten organizar el código en multiples archivos para reusarlos
+;; en bibliotecas; Aquí usamos sub-modules, anidados en todo el modulo que
+;; este texto hace (empezando desde la línea "#lang")
+
+(module cake racket/base ; definimos un modulo llamado 'cake' basado en racket/base
+
+ (provide print-cake) ; function exportada por el modulo
+
+ (define (print-cake n)
+ (show " ~a " n #\.)
+ (show " .-~a-. " n #\|)
+ (show " | ~a | " n #\space)
+ (show "---~a---" n #\-))
+
+ (define (show fmt n ch) ; función interna
+ (printf fmt (make-string n ch))
+ (newline)))
+
+;; Usa 'require' para obtener todos los nombre que provee un modulo
+(require 'cake) ; el apostrofe ' indica que es un submódulo local
+(print-cake 3)
+; (show "~a" 1 #\A) ; => error, la función 'show' no fue exportada
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 8. Clases y objectos
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Crea una clase llamada fish% (-% Es un una forma de indicar los límites de la clase)
+(define fish%
+ (class object%
+ (init size) ; inicialización del argumento
+ (super-new) ; inicialización de la superclase
+ ;; Campo
+ (define current-size size)
+ ;; Metodos públicos
+ (define/public (get-size)
+ current-size)
+ (define/public (grow amt)
+ (set! current-size (+ amt current-size)))
+ (define/public (eat other-fish)
+ (grow (send other-fish get-size)))))
+
+;; Crea una instancia de la clase fish%
+(define charlie
+ (new fish% [size 10]))
+
+;; Usa 'send' para llamar un método de un objeto
+(send charlie get-size) ; => 10
+(send charlie grow 6)
+(send charlie get-size) ; => 16
+
+;; 'fish%' is a plain "first class" value, which can get us mixins
+(define (add-color c%)
+ (class c%
+ (init color)
+ (super-new)
+ (define my-color color)
+ (define/public (get-color) my-color)))
+(define colored-fish% (add-color fish%))
+(define charlie2 (new colored-fish% [size 10] [color 'red]))
+(send charlie2 get-color)
+;; o, sin nombres:
+(send (new (add-color fish%) [size 10] [color 'red]) get-color)
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 9. Macros
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Las Macros te permite extender la sintaxis del lenguaje
+
+;; Agreguemos un ciclo while
+(define-syntax-rule (while condition body ...)
+ (let loop ()
+ (when condition
+ body ...
+ (loop))))
+
+(let ([i 0])
+ (while (< i 10)
+ (displayln i)
+ (set! i (add1 i))))
+
+;; Las Macros son higienicas, ¡no puedes aplastar las variables existentes!
+(define-syntax-rule (swap! x y) ; -! es un caracter que indica mutación
+ (let ([tmp x])
+ (set! x y)
+ (set! y tmp)))
+
+(define tmp 2)
+(define other 3)
+(swap! tmp other)
+(printf "tmp = ~a; other = ~a\n" tmp other)
+;; La variable 'tmp' es renombrada a 'tmp_1'
+;; Para evitar el conflicto de nombres
+;; (let ([tmp_1 tmp])
+;; (set! tmp other)
+;; (set! other tmp_1))
+
+;; Pero aun hay algunas transfromaciones de código, por ejemplo:
+(define-syntax-rule (bad-while condition body ...)
+ (when condition
+ body ...
+ (bad-while condition body ...)))
+;; Esta macro es incorrecta: genera código infinitamente, si tratas de usarla
+;; el compilador entrará en un ciclo infinito
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 10. Contratos
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Los Contratos imponen restricciones a los valores exportados desde los módulos
+
+(module bank-account racket
+ (provide (contract-out
+ [deposit (-> positive? any)] ; Los montos siempre son positivos
+ [balance (-> positive?)]))
+
+ (define amount 0)
+ (define (deposit a) (set! amount (+ amount a)))
+ (define (balance) amount)
+ )
+
+(require 'bank-account)
+(deposit 5)
+
+(balance) ; => 5
+
+;; El cliente intenta depositar un monto negativo por lo cual es rechazado
+;; (deposit -5) ; => depósito: violación del contrato
+;; expected: positive?
+;; given: -5
+;; more details....
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 11. Entrada y salida
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Racket tiene el concepto de "port", el cual es muy similar al de descriptores
+;; de ficheros en otros lenguajes
+
+;; Abre "/tmp/tmp.txt" y escribe "Hello World"
+;; Esto lanzará un error si el archivo existe
+(define out-port (open-output-file "/tmp/tmp.txt"))
+(displayln "Hello World" out-port)
+(close-output-port out-port)
+
+;; Agregar información a "/tmp/tmp.txt" (incluso si el archivo existe)
+(define out-port (open-output-file "/tmp/tmp.txt"
+ #:exists 'append))
+(displayln "Hola mundo" out-port)
+(close-output-port out-port)
+
+;; Lee del archivo de nuevo
+(define in-port (open-input-file "/tmp/tmp.txt"))
+(displayln (read-line in-port))
+; => "Hello World"
+(displayln (read-line in-port))
+; => "Hola mundo"
+(close-input-port in-port)
+
+;; Alternativamente, haciendo uso de call-with-output-file no necesitas expresamente
+;; cerrar el archivo
+(call-with-output-file "/tmp/tmp.txt"
+ #:exists 'update ; Rewrite the content
+ (λ (out-port)
+ (displayln "World Hello!" out-port)))
+
+;; Y usar la función call-with-input-file hace lo mismo para la entrada
+(call-with-input-file "/tmp/tmp.txt"
+ (λ (in-port)
+ (displayln (read-line in-port))))
+```
+
+## Mas información
+
+¿Quieres saber mas? Prueba en [Empezando con Racket](http://docs.racket-lang.org/getting-started/)
+
+
+
+
diff --git a/es-es/ruby-ecosystem-es.html.markdown b/es-es/ruby-ecosystem-es.html.markdown
new file mode 100644
index 00000000..9ce62ef5
--- /dev/null
+++ b/es-es/ruby-ecosystem-es.html.markdown
@@ -0,0 +1,157 @@
+---
+category: tool
+tool: ruby ecosystem
+contributors:
+ - ["Jon Smock", "http://github.com/jonsmock"]
+ - ["Rafal Chmiel", "http://github.com/rafalchmiel"]
+translators:
+ - ["Ale Mohamad", "http://twitter.com/alemohamad"]
+lang: es-es
+---
+
+Las personas que usan Ruby en general tienen una tendencia a instalar diferentes
+versiones de Ruby, administrar sus paquetes (o gemas), y gestionar las
+dependencias de sus gemas.
+
+## Gestores de Ruby
+
+Algunas plataformas ya tienen Ruby pre-instalado o disponible como un paquete
+propio. Muchos rubystas no utilizan estas versiones, o si lo hacen, solo lo
+utilizan para preparar otra instalación o implementación de Ruby. En lugar de
+eso, los rubystas tienden a instalar un gestor de Ruby para poder instalar
+diferentes versiones y poder cambiar dependiendo del entorno de cada proyecto.
+
+Los siguientes son gestores populares de entorno de Ruby:
+
+* [RVM](https://rvm.io/) - Instala y cambia versiones de Ruby. Además RVM tiene
+ el concepto de gemsets para aislar complemtante entornos de proyectos.
+* [ruby-build](https://github.com/sstephenson/ruby-build) - Solo instala
+ versiones de Ruby. Se utiliza para tener un control más fino sobre las
+ versiones instaladas de Ruby.
+* [rbenv](https://github.com/sstephenson/rbenv) - Solo se utiliza para cambiar
+ la versión de Ruby. Se utiliza junto con ruby-build. Se utiliza para tener un
+ control más fino sobre cómo se carga Ruby en el sistema.
+* [chruby](https://github.com/postmodern/chruby) - Solo se utiliza para cambiar
+ la versión de Ruby. En espíritu es similar a rbenv. No le es tan importante
+ como son instaladas las versiones de Ruby.
+
+## Versiones de Ruby
+
+Ruby fue creado por Yukihiro "Matz" Matsumoto, quien se mantiene como una
+especie de [BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life),
+aunque recientemente está cambiando. Como resultado, la implementación de
+referencia de Ruby es llamada MRI (Matz' Reference Implementation), y cuando se
+habla de una versión de Ruby, se está haciendo referencia a la versión inicial
+de MRI.
+
+Las tres versiones mayores en uso de Ruby son:
+
+* 2.0.0 - Lanzada en Febrero de 2013. La mayoría de las librerías importantes y
+ frameworks soportan 2.0.0.
+* 1.9.3 - Lanzada en Octubre de 2011. Es la versión que actualmente usan más
+ rubystas. Además fue
+ [retirada](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/)
+* 1.8.7 - Ruby 1.8.7 fue
+ [retirada](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/).
+
+El cambio de 1.8.7 a 1.9.x es un cambio mucho mayor que de 1.9.3 a 2.0.0. Por
+ejemplo, la serie 1.9 presentó codificaciones (encodings) y un bytecode VM.
+Todavía hay proyectos que utilizan 1.8.7, pero se están convirtiendo en una
+pequeña minoría, debido a que la mayor parte de la comunidad está utilizando
+como mínimo 1.9.2 o 1.9.3.
+
+## Implementaciones de Ruby
+
+El ecosistema de Ruby disfruta de muchas diferentes implementaciones de Ruby,
+cada una con fortalezas únicas y estados de compatibilidad. Para ser claros, las
+diferentes implementaciones están escritas en diferentes lenguajes, pero *todas
+son Ruby*. Cada implementación tiene hooks especiales y características extra,
+pero todas interpretan archivos Ruby de forma normal. Por ejemplo, JRuby está
+escrito en Java, pero no necesitás saber de Java para poder utilizarla.
+
+Muy maduras/compatibles:
+
+* [MRI](https://github.com/ruby/ruby) - Escrita en C, es la implementación de
+ referencia de Ruby. Por definición es 100% compatible (consigo misma). Las
+ otras implementaciones de Ruby mantienen compatibilidad con MRI (ver
+ [RubySpec](#rubyspec) más abajo).
+* [JRuby](http://jruby.org/) - Escrita en Java y Ruby, esta implementación es
+ robusta y bastante veloz. Más importante, la fortaleza de JRuby reside en la
+ interoperabilidad con JVM/Java, pudiendo utilizar herramientas, proyectos y
+ lenguajes ya existentes en JVM.
+* [Rubinius](http://rubini.us/) - Escrita principalmente en Ruby junto con un
+ bytecode VM de C++. Además es bastante madura y veloz. Debido a que está
+ implementada de forma directa en Ruby, expone varias funcionalidades de VM en
+ rubyland.
+
+Medianamente maduras/compatibles:
+
+* [Maglev](http://maglev.github.io/) - Construida sobre Gemstone, una VM de
+ Smalltalk. Smalltalk tiene herramientas que son impresionantes, y este
+ proyecto intenta llevar eso dentro del desarrollo con Ruby.
+* [RubyMotion](http://www.rubymotion.com/) - Lleva Ruby al desarrollo en iOS.
+
+No tan maduras/compatibles:
+
+* [Topaz](http://topazruby.com/) - Escrito en RPython (usando el intérprete
+ PyPy), Topaz es bastante joven y no tan compatible. Se muestra prometedor para
+ ser una implementación de Ruby de alta performance.
+* [IronRuby](http://ironruby.net/) - Escrita en C#, apuntando a la plataforma
+ .NET. El trabajo en IronRuby parece haberse detenido desde que Microsoft
+ retiró su soporte.
+
+Las implementaciones de Ruby pueden tener su propio número de versión de
+release, pero siempre apuntan a una versión específica de MRI para poder tener
+compatibilidad. Muchas implementaciones tienen la habilidad de trabajar en
+diferentes modos (por ejemplo, modo 1.8 o 1.9) para especificar a qué versión de
+MRI están apuntando.
+
+## RubySpec
+
+Muchas implementaciones de Ruby dependen en gran medida de
+[RubySpec](http://rubyspec.org/). Ruby no tiene una especificación oficial, por
+lo que la comunidad ha escrito especificaciones ejecutables en Ruby para poder
+testear la compatibilidad de sus implementaciones con MRI.
+
+## RubyGems
+
+[RubyGems](http://rubygems.org/) es un manejador de paquetes/comunidad de Ruby.
+RubyGems viene incluido con Ruby, por lo que no hay necesidad de instalarlo por
+separado.
+
+Los paquetes de Ruby son llamados "gemas" ("gems"), y pueden ser alojados por la
+comunidad en RubyGems.org. Cada gema contiene su código fuente y algo de
+metadata, incluyendo cosas como la versión, dependencias, autor(es), y
+licencia(s).
+
+## Bundler
+
+[Bundler](http://bundler.io/) es una herramienta para resolución de dependencias
+de gemas. Utiliza un archivo llamado Gemfile en cada proyecto para poder
+organizar sus dependencias, y luego poder agregar dichas dependencias y sus
+dependencias de forma recursiva. Hace esta acción hasta que resuelve y descarga
+todas las dependencias, o se detiene si es que un conflicto aparece.
+
+Bundler eleva un error si encuentra dependencias conflictivas. Por ejemplo, si
+la gema A requiere la versión 3 o mayor de la gema Z, pero la gema B requiere la
+versión 2, Bundler va a notificarte sobre dicho conflicto. Esto es
+extremadamente útil ya que varias gemas hacen referencia a otras gemas (de las
+cuales puede referenciar a otras gemas), lo cual puede formar un gran grafo de
+dependencias para resolver.
+
+# Testing
+
+Testing es una parte grande dentro de la cultura de Ruby. Ruby incluye su propio
+framework de testing llamado minitest (o TestUnit para la versión 1.8.x de
+Ruby). Hay varias librerías de testing con diferentes objetivos.
+
+* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - Framework de testing de Ruby 1.8
+* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - Framework de testing de Ruby 1.9/2.0
+* [RSpec](http://rspec.info/) - Un framework de testing que se focaliza en expresividad
+* [Cucumber](http://cukes.info/) - Un framework de testing que utiliza BDD, que parsea tests con formato Gherkin
+
+## Se Amable
+
+La comunidad de Ruby se enorgullece de ser una comunidad abierta, diversa y
+acogedora. Matz mismo es extremadamente amigable, y en general la generosidad de
+los rubystas es increíble.
diff --git a/es-es/sass-es.html.markdown b/es-es/sass-es.html.markdown
new file mode 100644
index 00000000..89e56ba5
--- /dev/null
+++ b/es-es/sass-es.html.markdown
@@ -0,0 +1,585 @@
+---
+language: sass
+filename: learnsass.scss
+contributors:
+ - ["Laura Kyle", "https://github.com/LauraNK"]
+ - ["Sean Corrales", "https://github.com/droidenator"]
+ - ["Kyle Mendes", "https://github.com/pink401k"]
+ - ["Keith Miyake", "https://github.com/kaymmm"]
+translators:
+ - ["César Suárez", "https://github.com/csuarez"]
+lang: es-es
+---
+
+Sass es un lenguaje que extiende CSS y que añade características tales como variables, anidación, mixins y más. Sass (y otros preprocesadores tales como [Less](http://lesscess.org/)) ayudan a los desarrolladores a escribir código mantenible y DRY (Don't Repeat Yourself).
+
+Sass tiene dos sintaxis para elegir: SCSS, que usa la misma que CSS pero con las características añadidas de Sass, y Sass (la sintaxis original) que usa identación en vez de llaves y puntos y comas. Este tutorial está escrito en SCSS.
+
+Si ya estás familiarizado con CSS3, vas a entender Sass relativamente rápido. Sass no ofrece nuevas propiedades de estilo, si no que añade herramientas para escribir tus CSS de manera más eficiente, haciendo su mantenimiento mucho más sencillo.
+
+```scss
+
+
+//Los comentarios en una sola línea son eliminados cuando Sass es compilado a CSS.
+
+/* Los comentarios multi-línea se mantienen. */
+
+
+
+/* Variables
+============================== */
+
+
+/* Puedes almacenar valores CSS (como un color) en una variable.
+Usa el símbolo '$' para crear una variable */
+
+$primary-color: #A3A4FF;
+$secondary-color: #51527F;
+$body-font: 'Roboto', sans-serif;
+
+/* Puedes usar las variables a lo largo de tu hoja de estilos.
+Ahora, si quieres cambiar el color, sólo lo tienes que hacer una vez. */
+
+body {
+ background-color: $primary-color;
+ color: $secondary-color;
+ font-family: $body-font;
+}
+
+/* Este código compilará en: */
+body {
+ background-color: #A3A4FF;
+ color: #51527F;
+ font-family: 'Roboto', sans-serif;
+}
+
+/* El resultado es mucho más mantenible que tener que cambiar el color
+cada vez que aparece en la hoja de estilos. */
+
+
+
+/* Directivas de control
+============================== */
+
+
+/* Sass permite usar @if, @else, @for, @while, y @each para controlar la
+ compilación de tu código en CSS. */
+
+/* Los bloques @if/@else se comportan tal como es de esperar */
+
+$debug: true !default;
+
+@mixin debugmode {
+ @if $debug {
+ @debug "Modo debug activado";
+
+ display: inline-block;
+ }
+ @else {
+ display: none;
+ }
+}
+
+.info {
+ @include debugmode;
+}
+
+/* Si $debug es true, .info es mostrado; si es false entonces
+no se muestra.
+
+Nota: @debug mostrará información de depuración en la consola.
+Es muy útil para ver el contenido de tus variables cuando estás depurando. */
+
+.info {
+ display: inline-block;
+}
+
+/* @for es un bucle que itera un conjunto de valores.
+Es particularmente útil para dar estilos a una colección de objetos.
+Hay dos formas "through" y "to". El primero incluye el último valor
+mientras que el segundo para antes del último valor. */
+
+@for $c from 1 to 4 {
+ div:nth-of-type(#{$c}) {
+ left: ($c - 1) * 900 / 3;
+ }
+}
+
+@for $c from 1 through 3 {
+ .myclass-#{$c} {
+ color: rgb($c * 255 / 3, $c * 255 / 3, $c * 255 / 3);
+ }
+}
+
+/* Esto compila en: */
+
+div:nth-of-type(1) {
+ left: 0;
+}
+
+div:nth-of-type(2) {
+ left: 300;
+}
+
+div:nth-of-type(3) {
+ left: 600;
+}
+
+.myclass-1 {
+ color: #555555;
+}
+
+.myclass-2 {
+ color: #aaaaaa;
+}
+
+.myclass-3 {
+ color: white;
+// SASS convierte automáticamente #FFFFFF a white
+}
+
+/* @while es bastante sencillo: */
+
+$columns: 4;
+$column-width: 80px;
+
+@while $columns > 0 {
+ .col-#{$columns} {
+ width: $column-width;
+ left: $column-width * ($columns - 1);
+ }
+
+ $columns: $columns - 1;
+}
+
+/* Esto se convierte en el siguiente CSS: */
+
+.col-4 {
+ width: 80px;
+ left: 240px;
+}
+
+.col-3 {
+ width: 80px;
+ left: 160px;
+}
+
+.col-2 {
+ width: 80px;
+ left: 80px;
+}
+
+.col-1 {
+ width: 80px;
+ left: 0px;
+}
+
+/* @each funciona parecido a @for, pero usa una lista en ver del valor ordinal
+Nota: puedes especificar listas como cualquier otra variable usando espacios
+como delimitadores. */
+
+$social-links: facebook twitter linkedin reddit;
+
+.social-links {
+ @each $sm in $social-links {
+ .icon-#{$sm} {
+ background-image: url("images/#{$sm}.png");
+ }
+ }
+}
+
+/* Esto resultará en: */
+
+.social-links .icon-facebook {
+ background-image: url("images/facebook.png");
+}
+
+.social-links .icon-twitter {
+ background-image: url("images/twitter.png");
+}
+
+.social-links .icon-linkedin {
+ background-image: url("images/linkedin.png");
+}
+
+.social-links .icon-reddit {
+ background-image: url("images/reddit.png");
+}
+
+
+
+/* Mixins
+==============================*/
+
+
+/* Si te encuentras con que estás escribiendo el mismo código en más de un
+elemento, puede que quieras almacenarlo en un mixin.
+
+Usa la directiva '@mixin', más un nombre para tu mixin. */
+
+@mixin center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+/* Puedes usarlo con '@include' y el nombre del mixin. */
+
+div {
+ @include center;
+ background-color: $primary-color;
+}
+
+/* Esto compilará en: */
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #A3A4FF;
+}
+
+/* Puedes usar mixins para crear una propiedad shorthand. */
+
+@mixin size($width, $height) {
+ width: $width;
+ height: $height;
+}
+
+/* La que puedes invocar pasándole los argumentos width y height. */
+
+.rectangle {
+ @include size(100px, 60px);
+}
+
+.square {
+ @include size(40px, 40px);
+}
+
+/* Compila en: */
+.rectangle {
+ width: 100px;
+ height: 60px;
+}
+
+.square {
+ width: 40px;
+ height: 40px;
+}
+
+
+
+/* Funciones
+============================== */
+
+
+/* Sass ofrece funciones que pueden ser usadas para realizar una gran variedad
+ de tareas. Por ejemplo: */
+
+/* Se pueden invocar funciones usando su nombre y pasándole los
+ argumentos requeridos. */
+body {
+ width: round(10.25px);
+}
+
+.footer {
+ background-color: fade_out(#000000, 0.25);
+}
+
+/* Compila en: */
+
+body {
+ width: 10px;
+}
+
+.footer {
+ background-color: rgba(0, 0, 0, 0.75);
+}
+
+/* Puedes definir tus propias funciones. Las funciones son muy similares a
+ los mixins. Cuando tengas que elegir entre una función y un mixin, recuerda
+ que los mixins son mejores para generar CSS, mientras que las funciones son
+ mejores para la lógica que puedas necesitar en tu código Sass. Los ejemplos
+ de la sección 'Operadores matemáticos' son candidatos ideales para ser
+ usados como una función reusable. */
+
+/* Esta función toma un tamaño objetivo y el tamaño de un padre y
+ devuelve el porcentaje. */
+
+@function calculate-percentage($target-size, $parent-size) {
+ @return $target-size / $parent-size * 100%;
+}
+
+$main-content: calculate-percentage(600px, 960px);
+
+.main-content {
+ width: $main-content;
+}
+
+.sidebar {
+ width: calculate-percentage(300px, 960px);
+}
+
+/* Compila en: */
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+
+
+/* Extender (Herencia)
+============================== */
+
+
+/* Extend es una manera de compartir propiedades de un selector con otro. */
+
+.display {
+ @include size(5em, 5em);
+ border: 5px solid $secondary-color;
+}
+
+.display-success {
+ @extend .display;
+ border-color: #22df56;
+}
+
+/* Compila en: */
+.display, .display-success {
+ width: 5em;
+ height: 5em;
+ border: 5px solid #51527F;
+}
+
+.display-success {
+ border-color: #22df56;
+}
+
+/* Extender una declaración CSS es preferible a crear un mixin
+ debido a la manera en la que Sass agrupa las clases que comparten
+ los mismos estilos base. Si esto fuese hecho con un mixin, el ancho,
+ alto y el borden aparecerían duplicados para cada una de las declaraciones
+ que usasen el mixin. Esto no afectará a tu workflow, pero infla
+ innecesariamente los ficheros generados por el compilador Sass. */
+
+
+
+/* Anidación
+============================== */
+
+
+/* Sass permite anidar selectores dentro de otros selectores. */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: #FF0000;
+ }
+}
+
+/* '&' será reemplazado por el selector del padre. */
+
+/* También puedes anidar seudo clases. */
+
+/* Ten en cuenta que anidar demasiado hará tu código menos mantenible.
+Como buena práctica, se recomienda no tener más de 3 niveles de anidación.
+Por ejemplo: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: red;
+
+ &:hover {
+ background-color: blue;
+ }
+
+ a {
+ color: white;
+ }
+ }
+}
+
+/* Compila en: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+}
+
+ul li {
+ background-color: red;
+}
+
+ul li:hover {
+ background-color: blue;
+}
+
+ul li a {
+ color: white;
+}
+
+
+
+/* Parciales e importaciones
+============================== */
+
+
+/* Sass permite que crees ficheros parciales. Esto te puede ayudar a mantener
+ tu código Sass modularizado. Los ficheros parciales deben comenzar por '_',
+ p.e. _reset.css.
+ Los parciales no son convertidos en CSS. */
+
+/* Mira este al que vamos a añadir un fichero llamado _reset.css */
+
+html,
+body,
+ul,
+ol {
+ margin: 0;
+ padding: 0;
+}
+
+/* Con @import puedes importar parciales a un fichero. Este se diferencia del
+ @import de CSS en que no hace otra petición HTTP para importar el fichero.
+ Sass, sino que combina el código importado en el código compilado. */
+
+@import 'reset';
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+/* Compila en: */
+
+html, body, ul, ol {
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+
+
+/* Placeholders
+============================== */
+
+
+/* Los placeholders son útiles cuando estás creando una declaración CSS a
+ extender. Si quieres crear una declaración que sólo va a ser usada con @extend,
+ puedes hacerlo mediante un placeholder. Los placeholders comienzan con '%'
+ en vez de '.' o '#'. Esto no aparecen en el código CSS compilado. */
+
+%content-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ @extend %content-window;
+ background-color: #0000ff;
+}
+
+/* Compila en: */
+
+.message-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ background-color: #0000ff;
+}
+
+
+
+/* Operaciones matemáticas
+============================== */
+
+
+/* Sass provee los siguientes operadores: +, -, *, / y %. Estos son útiles
+ para calcular valores directamente en tu código Sass en vez de usar valores
+ calculados a mano. Mira el siguiente ejemplo que prepara un sencillo diseño
+ de dos columnas. */
+
+$content-area: 960px;
+$main-content: 600px;
+$sidebar-content: 300px;
+
+$main-size: $main-content / $content-area * 100%;
+$sidebar-size: $sidebar-content / $content-area * 100%;
+$gutter: 100% - ($main-size + $sidebar-size);
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: $main-size;
+}
+
+.sidebar {
+ width: $sidebar-size;
+}
+
+.gutter {
+ width: $gutter;
+}
+
+/* Compila en: */
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+.gutter {
+ width: 6.25%;
+}
+
+```
+
+## ¿SASS o Sass?
+¿Alguna vez has pensado si Sass es un acrónimo o no? Seguramente no, pero te lo vamos a explicar de todas maneras. "Sass" es una palabra, no un acrónimo.
+Como todo el mundo lo escribe como "SASS", el creador del lenguaje lo ha llamado de broma "Syntactically Awesome StyleSheets" (Hojas de estilo sintácticamente increíbles).
+
+
+## Practica Sass
+Si quieres probar Sass en tu navegador, prueba [SassMeister](http://sassmeister.com/).
+Puedes usar cualquier sintaxis, o elegir en la configuración entre Sass y SCSS.
+
+## Compatibilidad
+Sass puede ser usado en cualquier proyecto mientras tengas un programa que lo compile en CSS. Quizás quieras comprobar si el CSS que estás usando es compatible con tus navegadores objetivo.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) y [CanIUse](http://caniuse.com) son buenos recursos para comprobar la compatibilidad de navegadores.
+
+
+## Más información
+* [Documentación oficial (EN)](http://sass-lang.com/documentation/file.SASS_REFERENCE.html)
+* [The Sass Way (EN)](http://thesassway.com/) tiene tutoriales (para principiantes y avanzandos) and artículos.
diff --git a/es-es/swift-es.html.markdown b/es-es/swift-es.html.markdown
index c04ab02b..8f63517a 100644
--- a/es-es/swift-es.html.markdown
+++ b/es-es/swift-es.html.markdown
@@ -12,7 +12,7 @@ filename: learnswift-es.swift
---
Swift es un lenguaje de programación para el desarrollo en iOS y OS X creado
-por Apple. Diseñado para coexistir con Objective-C y ser más resistente contra
+por Apple. Diseñado para coexistir con Objective-C y ser más resistente contra
el código erroneo, Swift fue introducido en el 2014 en el WWDC, la conferencia
de desarrolladores de Apple.
@@ -27,13 +27,13 @@ import UIKit
// MARK: Básicos
//
-// XCode soporta referencias para anotar tu código y agregarlos a lista de la
+// XCode soporta referencias para anotar tu código y agregarlos a lista de la
// barra de saltos.
// MARK: Marca de sección
// TODO: Hacer algo pronto
// FIXME: Arreglar este código
-// En Swift 2, println y print fueron combinados en un solo método print.
+// En Swift 2, println y print fueron combinados en un solo método print.
// Print añade una nueva línea automáticamente.
print("Hola, mundo") // println ahora es print
print("Hola, mundo", appendNewLine: false) // print sin agregar nueva línea
@@ -46,18 +46,18 @@ let øπΩ = "value" // nombres de variable unicode
let π = 3.1415926
let convenience = "keyword" // nombre de variable contextual
// Las declaraciones pueden ser separadas por punto y coma (;)
-let weak = "keyword"; let override = "another keyword"
-// Los acentos abiertos (``) permiten utilizar palabras clave como nombres de
+let weak = "keyword"; let override = "another keyword"
+// Los acentos abiertos (``) permiten utilizar palabras clave como nombres de
// variable
-let `class` = "keyword"
+let `class` = "keyword"
let explicitDouble: Double = 70
let intValue = 0007 // 7
let largeIntValue = 77_000 // 77000
let label = "some text " + String(myVariable) // Conversión (casting)
-let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Interpolación de string
+let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Interpolación de string
// Valores específicos de la compilación (build)
-// utiliza la configuración -D
+// utiliza la configuración -D
#if false
print("No impreso")
let buildValue = 3
@@ -67,13 +67,13 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Interpolación de string
print("Build value: \(buildValue)") // Build value: 7
/*
- Las opcionales son un aspecto del lenguaje Swift que permite el
+ Las opcionales son un aspecto del lenguaje Swift que permite el
almacenamiento de un valor `Some` (algo) o `None` (nada).
-
- Debido a que Swift requiere que cada propiedad tenga un valor,
- hasta un valor 'nil' debe de ser explicitamente almacenado como un
+
+ Debido a que Swift requiere que cada propiedad tenga un valor,
+ hasta un valor 'nil' debe de ser explicitamente almacenado como un
valor opcional.
-
+
Optional<T> es un enum.
*/
var someOptionalString: String? = "opcional" // Puede ser nil
@@ -85,7 +85,7 @@ if someOptionalString != nil {
if someOptionalString!.hasPrefix("opt") {
print("Tiene el prefijo")
}
-
+
let empty = someOptionalString?.isEmpty
}
someOptionalString = nil
@@ -104,14 +104,14 @@ if let someOptionalStringConstant = someOptionalString {
// Swift tiene soporte de almacenamiento para cualquier tipo de valor.
// AnyObject == id
-// A diferencia de Objective-C `id`, AnyObject funciona con cualquier
+// A diferencia de Objective-C `id`, AnyObject funciona con cualquier
// valor (Class, Int, struct, etc)
var anyObjectVar: AnyObject = 7
anyObjectVar = "Cambiado a un valor string, no es buena práctica, pero posible."
/*
Comentar aquí
-
+
/*
Comentarios anidados también son soportados
*/
@@ -122,8 +122,8 @@ anyObjectVar = "Cambiado a un valor string, no es buena práctica, pero posible.
//
/*
- Tipos Array (arreglo) y Dictionary (diccionario) son structs (estructuras).
- Así que `let` y `var` también indican si son mudables (var) o
+ Tipos Array (arreglo) y Dictionary (diccionario) son structs (estructuras).
+ Así que `let` y `var` también indican si son mudables (var) o
inmutables (let) durante la declaración de sus tipos.
*/
@@ -173,7 +173,7 @@ for i in -1...shoppingList.count {
shoppingList[1...2] = ["steak", "peacons"]
// Utilizar ..< para excluir el último valor
-// Ciclo while
+// Ciclo while
var i = 1
while i < 1000 {
i *= 2
@@ -224,7 +224,7 @@ func greet(name: String, day: String) -> String {
}
greet("Bob", "Martes")
-// Similar a lo anterior, a excepción del compartamiento de los parámetros
+// Similar a lo anterior, a excepción del compartamiento de los parámetros
// de la función
func greet2(requiredName: String, externalParamName localParamName: String) -> String {
return "Hola \(requiredName), hoy es el día \(localParamName)"
@@ -312,7 +312,7 @@ print(numbers) // [3, 6, 18]
// Las estructuras y las clases tienen capacidades similares
struct NamesTable {
let names = [String]()
-
+
// Subscript personalizado
subscript(index: Int) -> String {
return names[index]
@@ -343,7 +343,7 @@ public class Shape {
internal class Rect: Shape {
var sideLength: Int = 1
-
+
// Getter y setter personalizado
private var perimeter: Int {
get {
@@ -354,13 +354,13 @@ internal class Rect: Shape {
sideLength = newValue / 4
}
}
-
- // Lazily loading (inicialización bajo demanda) a una propiedad
+
+ // Lazily loading (inicialización bajo demanda) a una propiedad
// subShape queda como nil (sin inicializar) hasta que getter es llamado
lazy var subShape = Rect(sideLength: 4)
-
+
// Si no necesitas un getter y setter personalizado
- // pero aún quieres ejecutar código antes y después de hacer get o set
+ // pero aún quieres ejecutar código antes y después de hacer get o set
// a una propiedad, puedes utilizar `willSet` y `didSet`
var identifier: String = "defaultID" {
// El argumento `willSet` será el nombre de variable para el nuevo valor
@@ -368,20 +368,20 @@ internal class Rect: Shape {
print(someIdentifier)
}
}
-
+
init(sideLength: Int) {
self.sideLength = sideLength
- // Siempre poner super.init de último al momento de inicializar propiedades
+ // Siempre poner super.init de último al momento de inicializar propiedades
// personalizadas
super.init()
}
-
+
func shrink() {
if sideLength > 0 {
- --sideLength
+ sideLength -= 1
}
}
-
+
override func getArea() -> Int {
return sideLength * sideLength
}
@@ -413,13 +413,13 @@ class Circle: Shape {
override func getArea() -> Int {
return 3 * radius * radius
}
-
+
// Un signo de interrogación como sufijo después de `init` es un init opcional
// que puede devolver nil
init?(radius: Int) {
self.radius = radius
super.init()
-
+
if radius <= 0 {
return nil
}
@@ -457,11 +457,11 @@ enum Suit {
}
}
-// Los valores de enum permite la sintaxis corta, sin necesidad de poner
+// Los valores de enum permite la sintaxis corta, sin necesidad de poner
// el tipo del enum cuando la variable es declarada de manera explícita
var suitValue: Suit = .Hearts
-// Enums de tipo no-entero requiere asignaciones de valores crudas directas
+// Enums de tipo no-entero requiere asignaciones de valores crudas directas
enum BookName: String {
case John = "John"
case Luke = "Luke"
@@ -474,7 +474,7 @@ enum Furniture {
case Desk(height: Int)
// Asociación con String e Int
case Chair(String, Int)
-
+
func description() -> String {
switch self {
case .Desk(let height):
@@ -496,7 +496,7 @@ print(chair.description()) // "Chair of Foo with 40 cm"
//
// `protocol` puede requerir que los tipos tengan propiedades
-// de instancia específicas, métodos de instancia, métodos de tipo,
+// de instancia específicas, métodos de instancia, métodos de tipo,
// operadores, y subscripts
@@ -514,13 +514,13 @@ protocol ShapeGenerator {
class MyShape: Rect {
var delegate: TransformShape?
-
+
func grow() {
sideLength += 2
- // Pon un signo de interrogación después de la propiedad opcional,
- // método, o subscript para ignorar un valor nil y devolver nil
- // en lugar de tirar un error de tiempo de ejecución
+ // Pon un signo de interrogación después de la propiedad opcional,
+ // método, o subscript para ignorar un valor nil y devolver nil
+ // en lugar de tirar un error de tiempo de ejecución
// ("optional chaining")
if let allow = self.delegate?.canReshape?() {
// test for delegate then for method
@@ -536,7 +536,7 @@ class MyShape: Rect {
// `extension`: Agrega funcionalidades a tipos existentes
-// Square ahora se "conforma" al protocolo `Printable`
+// Square ahora se "conforma" al protocolo `Printable`
extension Square: Printable {
var description: String {
return "Area: \(self.getArea()) - ID: \(self.identifier)"
@@ -550,7 +550,7 @@ extension Int {
var customProperty: String {
return "This is \(self)"
}
-
+
func multiplyBy(num: Int) -> Int {
return num * self
}
@@ -589,7 +589,7 @@ prefix func !!! (inout shape: Square) -> Square {
// Valor actual
print(mySquare.sideLength) // 4
-// Cambiar la longitud del lado utilizando el operador !!!,
+// Cambiar la longitud del lado utilizando el operador !!!,
// incrementa el tamaño por 3
!!!mySquare
print(mySquare.sideLength) // 12
diff --git a/es-es/tmux.html.markdown b/es-es/tmux.html.markdown
new file mode 100644
index 00000000..aaa4cb59
--- /dev/null
+++ b/es-es/tmux.html.markdown
@@ -0,0 +1,242 @@
+---
+category: tool
+tool: tmux
+contributors:
+ - ["mdln", "https://github.com/mdln"]
+translators:
+ - ["Ferran Pelayo", "https://github.com/ferranpm"]
+filename: LearnTmux-es.txt
+lang: es-es
+---
+
+[tmux](http://tmux.sourceforge.net) permite crear, controlar y acceder a
+multiples terminales desde una sola ventana. Puede desconectarse una sesión de
+la ventana, seguir corriendo en segundo plano y volver a conectar otra ventana
+más tarde.
+
+
+```
+
+ tmux [command] # Correr un comando de tmux
+ # 'tmux' sin comando crea una nueva sesión.
+
+ new # Crear una nueva sesión
+ -s "Session" # Crear una sesión con nombre
+ -n "Window" # Crear una ventana con nombre
+ -c "/dir" # Empezar en el directorio "/dir"
+
+ attach # Atar la ventana a la ultima sesión iniciada
+ -t "#" # Atar la ventana a la sesión "#"
+ -d # Desatar la ventana de la sesión
+
+ ls # Listar las sesiones abiertas
+ -a # Listar todas las sesiones abiertas
+
+ lsw # Listar ventanas
+ -a # Listar todas las ventanas
+ -s # Listar todas las ventanas de la sesión
+
+ lsp # Listar paneles
+ -a # Listar todos los paneles
+ -s # Listar todos los paneles de la sesión
+ -t # Listar paneles de la aplicación en el target
+
+ kill-window # Eliminar la ventana actual
+ -t "#" # Eliminar la ventana "#"
+ -a # Eliminar todas las ventanas
+ -a -t "#" # Eliminar todas las ventanas menos la "#"
+
+ kill-session # Eliminar la sesión actual
+ -t "#" # Eliminar la sesión "#"
+ -a # Eliminar todas las sessiones
+ -a -t "#" # Eliminar todas las sessiones menos la "#"
+
+```
+
+
+### Atajos de teclado
+
+Para controlar una sesión atada se usa la combinación llamada 'Prefijo' + atajo.
+
+```
+----------------------------------------------------------------------
+ (C-b) = Ctrl + b # 'Prefijo' por defecto requerido para usar los atajos
+
+ (M-1) = Meta + 1 -o- Alt + 1
+----------------------------------------------------------------------
+
+ ? # Listar todos los atajos de teclado
+ : # Insertar un comando de tmux
+ r # Forzar refresco gráfico del cliente
+ c # Crear una nueva ventana
+
+ ! # Quitar el panel actual de la ventana
+ % # Dividir el panel actual en dos (derecha e izquierda)
+ " # Dividir el panel actual en dos (arriba y abajo)
+
+ n # Cambiar a la siguiente ventana
+ p # Cambiar a la ventana anterior
+ { # Cambiar el panel por el panel anterior
+ } # Cambiar el panel por el siguiente panel
+
+ s # Seleccionar y atar el cliente a una sesión distinta
+ de forma interactiva
+ w # Seleccionar una ventana de forma interactiva
+ 0 to 9 # Seleccionar una ventana (del 0 al 9)
+
+ d # Desatar el cliente actual de la sesión
+ D # Escojer un cliente a desatar
+
+ & # Eliminar la ventana actual
+ x # Eliminar el panel actual
+
+ Up, Down # Cambiar al panel de arriba, debajo, izquierda o derecha
+ Left, Right
+
+ M-1 to M-5 # Ordenar los paneles
+
+ C-Up, C-Down # Dimensionar el panel actual en pasos de una celda
+ C-Left, C-Right
+
+ M-Up, M-Down # Dimensionar el panel actual en pasos de cinco celdas
+ M-Left, M-Right
+
+```
+
+
+### Configurar ~/.tmux.conf
+
+El fichero tmux.conf se puede configurar para establecer unas opciones por
+defecto, igual que .vimrc o init.el para vim o emacs.
+
+```
+# Ejemplo tmux.conf
+# 2014.10
+
+
+### General
+###########################################################################
+
+# Activar UTF-8
+setw -g utf8 on
+set-option -g status-utf8 on
+
+# Limite del historico de comandos
+set -g history-limit 2048
+
+# Index Start
+set -g base-index 1
+
+# Ratón
+set-option -g mouse-select-pane on
+
+# Forzar volver a cargar el fichero de configuración
+unbind r
+bind r source-file ~/.tmux.conf
+
+
+### Atajos de teclado
+###########################################################################
+
+# Quitar C-b como prefijo por defecto
+unbind C-b
+
+# Establecer ` como nuevo prefijo
+set-option -g prefix `
+
+# Volver a la ventana anterior cuando el prefijo se pulsa dos veces
+bind C-a last-window
+bind ` last-window
+
+# Intercambiar entre C-a y ` como prefijo pulsando F11/F12
+bind F11 set-option -g prefix C-a
+bind F12 set-option -g prefix `
+
+# Preferencias de los atajos
+setw -g mode-keys vi
+set-option -g status-keys vi
+
+# Mover entre paneles con atajos de vim
+bind h select-pane -L
+bind j select-pane -D
+bind k select-pane -U
+bind l select-pane -R
+
+# Cambiar/Saltar de ventana
+bind e previous-window
+bind f next-window
+bind E swap-window -t -1
+bind F swap-window -t +1
+
+# Divisiones de paneles
+bind = split-window -h
+bind - split-window -v
+unbind '"'
+unbind %
+
+### Tema de colores
+###########################################################################
+
+# Barra de estado
+set-option -g status-justify left
+set-option -g status-bg black
+set-option -g status-fg white
+set-option -g status-left-length 40
+set-option -g status-right-length 80
+
+# Bordes de paneles
+set-option -g pane-active-border-fg green
+set-option -g pane-active-border-bg black
+set-option -g pane-border-fg white
+set-option -g pane-border-bg black
+
+# Color de los mensajes
+set-option -g message-fg black
+set-option -g message-bg green
+
+# Colores del estado de las ventanas
+setw -g window-status-bg black
+setw -g window-status-current-fg green
+setw -g window-status-bell-attr default
+setw -g window-status-bell-fg red
+setw -g window-status-content-attr default
+setw -g window-status-content-fg yellow
+setw -g window-status-activity-attr default
+setw -g window-status-activity-fg yellow
+
+
+### UI
+###########################################################################
+
+# Notificaciones
+setw -g monitor-activity on
+set -g visual-activity on
+set-option -g bell-action any
+set-option -g visual-bell off
+
+# Titulos de las ventanas
+set-option -g set-titles on
+set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not)
+
+# Formato de la barra de estado
+set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]"
+
+# Mostrar estadisticas de rendimiento en la barra de estado
+# Requiere https://github.com/thewtex/tmux-mem-cpu-load/
+set -g status-interval 4
+set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]"
+
+```
+
+
+### Referencias
+
+[Tmux | Home](http://tmux.sourceforge.net)
+
+[Tmux Manual page](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux)
+
+[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux)
+
+[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux)
+
+[Display CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux)
diff --git a/es-es/vim-es.html.markdown b/es-es/vim-es.html.markdown
new file mode 100644
index 00000000..df97aa3d
--- /dev/null
+++ b/es-es/vim-es.html.markdown
@@ -0,0 +1,242 @@
+---
+category: tool
+tool: vim
+contributors:
+ - ["RadhikaG", "https://github.com/RadhikaG"]
+translators:
+ - ["Ivan Alburquerque", "https://github.com/AlburIvan"]
+lang: es-es
+filename: LearnVim-es.txt
+---
+
+
+[Vim](http://www.vim.org)
+(Vi IMproved) es un clón del popular editor vi para UNIX. Es un editor de texto
+diseñado para ser veloz e incrementar la productividad, es ubicuo en la mayoría
+de los sistemas basados en UNIX. Cuenta con numerosas combinaciones de teclas
+para la navegación rápida a puntos especificos en un archivo y para rápida edición.
+
+
+
+## Fundamentos de la navegación en Vim
+
+```
+ vim <archivo> # Abre <archivo> en vim
+ :q # Salir de vim
+ :w # Guardar archivo actual
+ :wq # Guardar archivo y salir de vim
+ :q! # Salir de vim sin guardar el archivo
+ # ! *forza* :q a ejecutarse, por lo tanto sale de vim sin guardar
+ :x # Guardar el archivo y salir de vim, versión corta de :wq
+
+ u # Deshacer
+ CTRL+R # Rehacer
+
+ h # Desplazarse un carácter hacía la izquierda
+ j # Desplazarse una línea hacía abajo
+ k # Desplazarse una línea hacía arriba
+ l # Desplazarse un carácter hacía la derecha
+
+ # Desplazarse dentro de la línea
+
+ 0 # Desplazarse hacia el inicio de la línea
+ $ # Desplazarse al final de la línea
+ ^ # Desplazarse al primer carácter no blanco en la línea
+
+ # Buscando en el texto
+
+ /word # Resalta todas las ocurrencias de la palabra después del cursor
+ ?word # Resalta todas las ocurrencias de la palabra antes del cursor
+ n # Desplaza el cursor a la siguiente ocurrencia de la palabra después de una búsqueda
+ N # Desplaza el cursor a la anterior ocurrencia de la palabra
+
+ :%s/foo/bar/g # Cambia 'foo' a 'bar' en cada línea en el archivo
+ :s/foo/bar/g # Cambia 'foo' a 'bar' en la línea actual
+
+ # Saltando caracteres
+
+ f<carácter> # Salta adelante y aterriza en <carácter>
+ t<carácter> # Salta adelante y aterriza antes de <carácter>
+
+ # Por ejemplo,
+ f< # Salta adelante y aterriza en <
+ t< # Salta adelante y aterriza justo antes de <
+
+ # Desplazarse por palabras
+
+ w # Desplazarse hacia adelante por una palabra
+ b # Desplazarse hacia atrás por una palabra
+ e # Desplazarse al final de la palabra actual
+
+ # Otros caracteres para desplazarse
+
+ gg # Ir al principio del archivo
+ G # Ir al final del archivo
+ :NUM # Ir a la línea número NUM (NUM es cualquier número)
+ H # Desplazarse al principio de la pantalla
+ M # Desplazarse a la mitad de la pantalla
+ L # Desplazarse al final de la pantalla
+```
+
+## Modos:
+
+Vim se basa en el concepto de **modos**.
+
+
+Modo Comando - Vim se pone en marcha en éste modo, se usa para navegar y escribir comandos
+Modo Inserción - Utilizado para realizar cambios en el archivo
+Modo Visual - Utilizado para resaltar texto y operar en ellos
+Modo Ex - Utilizado para ir hacia la parte inferior con ':' para introducir comandos
+
+
+```
+ i # Pone a Vim en modo de inserción, antes de la posición del cursor
+ a # Pone a Vim en modo de inserción, después de la posición del cursor
+ v # Pone a Vim en modo de visual
+ : # Pone a Vim en modo Ex
+ <esc> # Sale de cualquier modo en que se encuentre, al modo comando
+
+ # Copiando y pegando texto
+
+ y # Copia lo que se encuentre seleccionado
+ yy # Copia la linea actual
+ d # Elimina lo que se encuentre seleccionado
+ dd # Elimina la linea actual
+ p # Pega el texto copiado después de la posición del cursor
+ P # Pega el texto copiado antes de la posición del cursor
+ x # Elimina el carácter debajo de la posición del cursor
+```
+
+## La "Gramática" de vim
+
+Vim puede ser pensado como un conjunto de comandos en un
+formato "verbo-sustantivo-modificador ', donde:
+
+Verbo - La acción a realizar
+Modificador - Como vas hacer la acción
+Sustantivo - el objeto al que se le va a aplicar la acción
+
+Algunos ejemplos importantes de "Verbos", "Modificadores" y "Sustantivos":
+
+```
+ # 'Verbos'
+
+ d # Eliminar
+ c # Cambiar
+ y # Copiar
+ v # Seleccionar visualmente
+
+ # 'Modificadores'
+
+ i # Dentro
+ a # Alrededor
+ NUM # Número (NUM es cualquier número)
+ f # Busca algo y aterriza sobre el
+ t # Busca algo y se detiene antes de
+ / # Encuentra una cadena desde el cursor en adelante
+ ? # Encuentra una cadena antes del cursor
+
+ # 'Sustantivos'
+
+ w # Palabra
+ s # Oración
+ p # Párrafo
+ b # Bloque
+
+ # "Frases" de ejemplo o comandos
+
+ d2w # Elimina 2 palabras
+ cis # Cambia dentro de una oración
+ yip # Copia dentro de un párrafo (copia el párrafo donde estás)
+ ct< # Cambia para abrir un paréntesis
+ # Cambie el texto desde donde está a la siguiente paréntesis abierto
+ d$ # Eliminar hasta el final de la línea
+```
+
+## Algunos accesos directos y trucos
+
+```
+ > # Sangrar la selección por un bloque
+ < # Desangrar la selección por un bloque
+ :earlier 15m # Devuelve el documento de nuevo a como era hace 15 minutos
+ :later 15m # Deshace el comando anterior
+ ddp # Intercambia la posición de las lineas consecutivas, dd después p
+ . # Repite la acción previa
+```
+
+## Macros
+
+Las macros son, básicamente, las acciones que se pueden grabar.
+Cuando comienzas a grabar un macro, registra **todas** las acciones y comandos
+que se utilizan hasta que detenga la grabación. En la invocación de un macro,
+se aplica exactamente la misma secuencia de acciones y comandos de nuevo
+en la selección de texto.
+
+```
+ qa # Comienza a grabar un macro llamada 'a'
+ q # Detiene la grabación
+ @a # Comienza la reproducción del macro
+```
+
+### Configurando ~/.vimrc
+
+El archivo .vimrc puede ser usado para configurar Vim en el arranque.
+
+Aquí está un ejemplo de un archivo ~ / .vimrc:
+
+```
+" Ejemplo ~/.vimrc
+" 2015.10
+
+" Se requiere para que vim sea 'mejor'
+set nocompatible
+
+" Determina la extensión del archivo por el nombre para permitir el auto-indentado inteligente, etc...
+filetype indent plugin on
+
+" Habilita el resaltado de sintaxis
+syntax on
+
+" Mejor terminación de línea de comandos
+set wildmenu
+
+" Usa búsqueda sensible a mayúsculas excepto cuando se utilizan letras mayúsculas
+set ignorecase
+set smartcase
+
+" Al abrir una nueva línea, si la sangría especifica del archivo no está habilitada,
+" mantén la misma sangría que la línea que estás actualmente
+set autoindent
+
+" Despliega el número de línea a la izquierda
+set number
+
+" Opciones de sangría, cambialas de acuerdo a tus preferencias personales
+
+" Número de espacios visuales por tabulación
+set tabstop=4
+
+" Número de espacios de las tabulaciones al editar
+set softtabstop=4
+
+" Número de espacios sangrados cuando las operaciones de resangrado (>> y <<) son usadas
+set shiftwidth=4
+
+" Convertir tabulaciones en espacios
+set expandtab
+
+" Habilitar la tabulación inteligente y el espaciamiento para el sangrado y la alineación
+set smarttab
+```
+
+### Referencias
+
+[Vim | Home (EN)](http://www.vim.org/index.php)
+
+`$ vimtutor` Command
+
+[A vim Tutorial and Primer (EN)](https://danielmiessler.com/study/vim/)
+
+[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread) (EN)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about)
+
+[Arch Linux Wiki (EN)](https://wiki.archlinux.org/index.php/Vim) \ No newline at end of file
diff --git a/fr-fr/HTML-fr.html.markdown b/fr-fr/HTML-fr.html.markdown
index 4d2da921..b52fd34a 100644
--- a/fr-fr/HTML-fr.html.markdown
+++ b/fr-fr/HTML-fr.html.markdown
@@ -106,6 +106,8 @@ Cet article porte principalement sur la syntaxe et quelques astuces.
</tr>
</table>
+```
+
## Utilisation
Le HTML s'écrit dans des fichiers `.html`.
diff --git a/fr-fr/clojure-fr.html.markdown b/fr-fr/clojure-fr.html.markdown
index 63bc25b5..65747c0d 100644
--- a/fr-fr/clojure-fr.html.markdown
+++ b/fr-fr/clojure-fr.html.markdown
@@ -275,7 +275,7 @@ ressemblent à toutes les autres formes:
(let [name "Urkel"]
(print "Saying hello to " name)
(str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel")
-
+
; Utilisez les Threading Macros (-> et ->>) pour exprimer plus
; clairement vos transformations, en y pensant de manière multi-niveaux.
@@ -284,10 +284,10 @@ ressemblent à toutes les autres formes:
; de la forme suivante, constituant à chaque fois un nouvel étage
; de transformation. Par exemple:
(->
- {:a 1 :b 2}
+ {:a 1 :b 2}
(assoc :c 3) ;=> Génère ici (assoc {:a 1 :b 2} :c 3)
(dissoc :b)) ;=> Génère ici (dissoc (assoc {:a 1 :b 2} :c 3) :b)
-
+
; Cette expression est ré-écrite en:
; (dissoc (assoc {:a 1 :b 2} :c 3) :b)
; et est évaluée en : {:a 1 :c 3}
@@ -302,6 +302,14 @@ ressemblent à toutes les autres formes:
(into [])) ;=> Génère ici (into [] (filter odd? (map inc (range 10))), ce qui est évalué au final à;
; [1 3 5 7 9]
+; Quand vous êtes dans une situation où vous voulez plus de liberté pour choisir
+; où mettre le résultat des étages précédents, vous pouvez utiliser la
+; macro as->. Avec cette macro, donnez un nom spécifique au résultat de la transformation
+; précédente pour le placer, à votre guise, où bon vous semble dans l'étage courant:
+(as-> [1 2 3] input
+ (map inc input);=> Utilisation du résultat en dernière position
+ (nth input 4) ;=> et en deuxième position, dans la même expression
+ (conj [4 5 6] input [8 9 10])) ;=> ou au milieu !
; Modules
;;;;;;;;;;;;;;;
@@ -370,7 +378,7 @@ ressemblent à toutes les autres formes:
; STM
;;;;;;;;;;;;;;;;;
-; La mémoire logiciel transactionnelle ("Software Transactional Memory")
+; La mémoire logiciel transactionnelle ("Software Transactional Memory")
; est le mécanisme que Clojure utilise pour gérer les états persistents.
; Il y a plusieurs formes en Clojure qui utilisent cela.
@@ -384,7 +392,7 @@ ressemblent à toutes les autres formes:
(swap! my-atom assoc :a 1) ; Définit my-atom comme le résultat de (assoc {} :a 1)
(swap! my-atom assoc :b 2) ; Définit my-atom comme le résultat de (assoc {:a 1} :b 2)
-; Use '@' to dereference the atom and get the value
+; Use '@' to dereference the atom and get the value
my-atom ;=> Atom<#...> (Renvoie l'objet Atom)
@my-atom ; => {:a 1 :b 2}
diff --git a/fr-fr/rust-fr.html.markdown b/fr-fr/rust-fr.html.markdown
index 0fa16075..6ab559a3 100644
--- a/fr-fr/rust-fr.html.markdown
+++ b/fr-fr/rust-fr.html.markdown
@@ -176,7 +176,7 @@ fn main() {
    println!("{}", a_foo.get_bar()); // 1
    // Traits (connu sous le nom des interfaces ou des classes de types dans
- // d'elses langues).
+ // d'autres langues).
    trait Frobnicate<T> {
        fn frobnicate(self) -> Option<T>;
@@ -264,18 +264,18 @@ fn main() {
// Pointeur occasion - une seule chose peut "posséder" pointeur à un moment.
    // Cela signifie que lorsque le `Box` laisse son champ d'application, il
// peut être automatiquement libérée en toute sécurité.
-    let mut mien: Box<i32> = Box::new(3);
-    *mien = 5; // déréférencer
-    // Ici, `now_its_mine` prend possession de` mine`. En d'elses termes,
- // `mien` est déplacé.
-    let mut now_its_mine = mien;
+    let mut mine: Box<i32> = Box::new(3);
+    *mine = 5; // déréférencer
+    // Ici, `now_its_mine` prend possession de `mine`. En d'autres termes,
+ // `mine` est déplacé.
+    let mut now_its_mine = mine;
    *now_its_mine += 2;
    println!("{}", now_its_mine); // 7
-    // println!("{}", de la mine); // Cela ne compile pas parce
+    // println!("{}", now_its_mine); // Cela ne compile pas parce
// que `now_its_mine` possède maintenant le pointeur
-    // Référence - un pointeur immutable qui fait référence à d'elses données.
+    // Référence - un pointeur immutable qui fait référence à d'autres données.
    // Quand une référence est prise à une valeur, nous disons que la valeur
// a été "emprunté".
    // Même si une valeur est emprunté immutablement, il ne peut pas être
@@ -285,22 +285,22 @@ fn main() {
    var = 3;
    let ref_var: &i32 = &var;
-    println!("{}", var); // Contrairement `box`, `var` peut encore être utilisé
+    println!("{}", var); // Contrairement à `mine`, `var` peut encore être utilisé
    println!("{}", *ref_var);
    // Var = 5; // Cela ne compile pas parce que `var` est emprunté.
-    // *ref_var = 6; // Ce ne serait pas non plus, parce que `ref_var` est une
+    // *ref_var = 6; // Ce ne serait pas correct non plus, parce que `ref_var` est une
// référence immutable.
    // Référence Mutable
-    // Même si une valeur est mutably emprunté, il ne peut pas être
+    // Même si une valeur est empruntée de façon mutable, elle ne peut pas être
// accessible à tous.
    let mut var2 = 4;
    let ref_var2: &mut i32 = &mut var2;
// '*' est utilisé pour pointer vers le var2 mutably emprunté.
*ref_var2 += 2;
- println!("{}", * ref_var2); // 6, // var2 ne serait pas compiler.
-    // ref_var2 est de type &mut i32 donc stocke il référence à i32,
+ println!("{}", * ref_var2); // 6, // var2 ne compilerait pas.
+    // ref_var2 est de type &mut i32 donc stocke la référence à i32,
// pas la valeur.
    // var2 = 2; // Cela ne compile pas parce que `var2` est emprunté.
}
diff --git a/git.html.markdown b/git.html.markdown
index 47bac3ba..01dc92c1 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -573,6 +573,8 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1)
+* [Learn Git Branching - the most visual and interactive way to learn Git on the web](http://learngitbranching.js.org/)
+
* [Udemy Git Tutorial: A Comprehensive Guide](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/)
* [Git Immersion - A Guided tour that walks through the fundamentals of git](http://gitimmersion.com/)
diff --git a/html.html.markdown b/html.html.markdown
new file mode 100644
index 00000000..904fa5c2
--- /dev/null
+++ b/html.html.markdown
@@ -0,0 +1,120 @@
+---
+language: html
+filename: learnhtml.html
+contributors:
+ - ["Christophe THOMAS", "https://github.com/WinChris"]
+translators:
+ - ["Robert Steed", "https://github.com/robochat"]
+---
+
+HTML stands for HyperText Markup Language.
+It is a language which use to write pages for the world wide web.
+It is a markup language, it enables us to write to write webpages using code to indicate how text and data should be displayed.
+In fact, html files are simple text files.
+What is this markup? It is a method of organising the page's data by surrounding it with opening tags and closing tags.
+This markup serves to give significance to the text that it encloses.
+Like other computer languages, HTML has many versions. Here we will talk about HTML5.
+
+**NOTE :** You can test the different tags and elements as you progress through the tutorial on a site like [codepen](http://codepen.io/pen/) in order to see their effects, understand how they work and familiarise yourself with the language.
+This article is concerned principally with HTML syntax and some useful tips.
+
+
+```html
+<!-- Comments are enclosed like this line! -->
+
+<!-- #################### The Tags #################### -->
+
+<!-- Here is an example HTML file that we are going to analyse. -->
+
+<!doctype html>
+ <html>
+ <head>
+ <title>My Site</title>
+ </head>
+ <body>
+ <h1>Hello, world!</h1>
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Come look at what this shows</a>
+ <p>This is a paragraph.</p>
+ <p>This is another paragraph.</p>
+ <ul>
+ <li>This is an item in a non-enumerated list (bullet list)</li>
+ <li>This is another item</li>
+ <li>And this is the last item on the list</li>
+ </ul>
+ </body>
+ </html>
+
+<!-- An HTML file always starts by indicating to the browser that the page is HTML. -->
+<!doctype html>
+
+<!-- After this, it starts by opening an <html> tag. -->
+<html>
+
+<!-- that will be closed at the end of the file with </html>. -->
+</html>
+
+<!-- Nothing should appear after this final tag. -->
+
+<!-- Inside (between the opening and closing tags <html></html>), we find: -->
+
+<!-- A header defined by <head> (it must be closed with </head>). -->
+<!-- The header contains some description and additional information which are not displayed; this is metadata. -->
+
+<head>
+ <title>My Site</title><!-- The tag <title> indicates to the browser the title to show in browser window's title bar and tab name. -->
+</head>
+
+<!-- After the <head> section, we find the tag - <body> -->
+<!-- Until this point, nothing described will show up in the browser window. -->
+<!-- We must fill the body with the content to be displayed. -->
+
+<body>
+ <h1>Hello, world!</h1> <!-- The h1 tag creates a title. -->
+ <!-- There are also subtitles to <h1> from the most important (h2) to the most precise (h6). -->
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Come look at what this shows</a> <!-- a hyperlink to the url given by the attribute href="" -->
+ <p>This is a paragraph.</p> <!-- The tag <p> lets us include text in the html page. -->
+ <p>This is another paragraph.</p>
+ <ul> <!-- The tag <ul> creates a bullet list. -->
+ <!-- To have a numbered list instead we would use <ol> giving 1. for the first element, 2. for the second, etc. -->
+ <li>This is an item in a non-enumerated list (bullet list)</li>
+ <li>This is another item</li>
+ <li>And this is the last item on the list</li>
+ </ul>
+</body>
+
+<!-- And that's it, creating an HTML file can be simple. -->
+
+<!-- But it is possible to add many additional types of HTML tags. -->
+
+<!-- To insert an image. -->
+<img src="http://i.imgur.com/XWG0O.gif"/> <!-- The source of the image is indicated using the attribute src="" -->
+<!-- The source can be an URL or even path to a file on your computer. -->
+
+<!-- It is also possible to create a table. -->
+
+<table> <!-- We open a <table> element. -->
+ <tr> <!-- <tr> allows us to create a row. -->
+ <th>First Header</th> <!-- <th> allows us to give a title to a table column. -->
+ <th>Second Header</th>
+ </tr>
+ <tr>
+ <td>first row, first column</td> <!-- <td> allows us to create a table cell. -->
+ <td>first row, second column</td>
+ </tr>
+ <tr>
+ <td>second row, first column</td>
+ <td>second row, second column</td>
+ </tr>
+</table>
+
+```
+
+## Usage
+
+HTML is written in files ending with `.html`.
+
+## To Learn More
+
+* [wikipedia](https://en.wikipedia.org/wiki/HTML)
+* [HTML tutorial](https://developer.mozilla.org/en-US/docs/Web/HTML)
+* [W3School](http://www.w3schools.com/html/html_intro.asp)
diff --git a/id-id/asciidoc-id.html.markdown b/id-id/asciidoc-id.html.markdown
new file mode 100644
index 00000000..8da8af38
--- /dev/null
+++ b/id-id/asciidoc-id.html.markdown
@@ -0,0 +1,125 @@
+---
+language: asciidoc
+contributors:
+ - ["Ryan Mavilia", "http://unoriginality.rocks/"]
+translators:
+ - ["Rizky Luthfianto", "http://github.com/rilut"]
+filename: asciidoc-id.md
+lang: id-id
+---
+
+AsciiDoc adalah bahasa markup yang mirip dengan Markdown dan dapat digunakan untuk apa saja, untuk menulis buku maupun blog. Dibuat pada tahun 2002 oleh Stuart Rackham, bahasa ini sederhana tetapi memungkinkan sejumlah besar kustomisasi.
+
+Kepala Dokumen
+
+Kepala Dokumen adalah opsional dan tidak dapat berisi baris kosong. Harus diimbangi konten, setidaknya satu baris kosong.
+
+Hanya Judul
+
+```
+= Judul Dokumen
+
+Kalimat pertama dokumen.
+```
+
+Judul dan Penulis
+
+```
+= Judul Dokumen
+Pertama terakhir <first.last@learnxinyminutes.com>
+
+Awal dokumen ini.
+```
+
+Banyak Penulis
+
+```
+= Judul Dokumen
+John Doe <john@go.com>; Jane Doe <jane@yo.com>; Black Beard <beardy@pirate.com>
+
+Memulai dokumen dengan banyak penulis.
+```
+
+Garis Revisi (membutuhkan garis penulis)
+
+```
+= Judul Dokumen V1
+Manusia Kentang <keripik@renyah.com>
+v1.0, 2016/01/13
+
+Artikel tentang keripik ini akan menjadi menyenangkan.
+```
+
+Paragraf
+
+```
+Anda tidak perlu sesuatu yang istimewa untuk paragraf.
+
+Tambahkan baris kosong antara paragraf untuk memisahkan mereka.
+
+Untuk membuat baris kosong, tambahkan: +
+dan Anda akan mendapat satu baris kosong!
+```
+
+Memformat Teks
+
+```
+_underscore menciptakan miring_
+*Tanda bintang untuk tebal*
+*_Gabungkan biar makin asyik_*
+`Penggunaan tanda petik untuk menandakan monospace`
+`*Monospace tebal*`
+```
+
+Judul bagian
+
+```
+= Level 0 (hanya dapat digunakan dalam header dokumen)
+
+== Level 1 <h2>
+
+=== Level 2 <h3>
+
+==== Level 3 <h4>
+
+===== Level 4 <h5>
+
+====== Level 5 <h6>
+
+======= Level 6 <h7>
+
+```
+
+Daftar
+
+Untuk membuat daftar bullet, gunakan tanda bintang.
+
+```
+* foo
+* bar
+* baz
+```
+
+Untuk membuat daftar bernomor, gunakan titik.
+
+```
+. Item 1
+. item 2
+. Item 3
+```
+
+Anda bisa membuat daftar bersarang dengan menambahkan tanda bintang atau titik tambahan hingga lima kali.
+
+```
+* Foo 1
+** Foo 2
+*** Foo 3
+**** Foo 4
+***** Foo 5
+
+. foo 1
+.. Foo 2
+... Foo 3
+.... Foo 4
+..... Foo 5
+```
diff --git a/id-id/coffeescript-id.html.markdown b/id-id/coffeescript-id.html.markdown
new file mode 100644
index 00000000..7fa40bb6
--- /dev/null
+++ b/id-id/coffeescript-id.html.markdown
@@ -0,0 +1,106 @@
+---
+language: coffeescript
+contributors:
+ - ["Tenor Biel", "http://github.com/L8D"]
+ - ["Xavier Yao", "http://github.com/xavieryao"]
+filename: coffeescript-id.coffee
+translators:
+ - ["Rizky Luthfianto", "http://github.com/rilut"]
+lang: id-id
+---
+
+CoffeeScript adalah bahasa sederhana yang diterjemahkan saat kompilasi ke dalam JavaScript,
+dan bukan diterjemahkan pada saat *runtime*.
+CoffeeScript mencoba agar kode JavaScript yang dihasilkan tetap mudah dibaca
+dan kompatibel dengan semua *runtime* JavaScript.
+
+Lihat juga [website CoffeeScript](http://coffeescript.org/) yang memiliki tutorial lengkap tentang CoffeeScript.
+
+```CoffeeScript
+# CoffeeScript adalah bahasa hipster.
+# Mengikuti tren bahasa modern lainnya.
+# Sehingga, seperti Ruby dan Python, untuk komentar digunakan tanda pagar.
+
+###
+Ini adalah contoh blok komentar, yang nanti diterjemahkan langsung ke '/ *' dan '* /'
+pada kode JavaScript yang dihasilkan.
+
+Anda diharapkan sedikit memahami semantik JavaScript sebelum melanjutkan tutorial ini.
+###
+
+# Pengisian nilai variabel:
+angka = 42 #=> var angka = 42;
+kebalikan = true #=> var kebalikan = true;
+
+# Kondisi:
+angka = -42 if kebalikan #=> if(kebalikan) { angka = -42; }
+
+# Fungsi:
+kuadrat = (x) -> x * x #=> var kuadrat = function(x) { return x * x; }
+
+isi = (wadah, cairan = "kopi") ->
+ "Mengisi #{wadah} dengan #{cairan}..."
+#=>var isi;
+#
+#isi = function(wadah, cairan) {
+# if (cairan == null) {
+# cairan = "kopi";
+# }
+# return "Mengisi " + wadah + " dengan " + cairan + "...";
+#};
+
+# Rentang:
+list = [1..5] # => var list = [1, 2, 3, 4, 5];
+
+# Objek:
+fungsi_matematika =
+ akar: Math.sqrt
+ kuadrat: kuadrat
+ kubik: (x) -> x * kuadrat x
+#=> var fungsi_matematika = {
+# "akar": Math.sqrt,
+# "kuadrat": kuadrat,
+# "kubik": function(x) { return x * kuadrat(x); }
+# };
+
+# *Splat*:
+balapan = (pemenang, pelari...) ->
+ print pemenang, pelari
+#=>balapan = function() {
+# var pelari, pemenang;
+# pemenang = arguments[0], pelari = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
+# return print(pemenang, pelari);
+# };
+
+# Cek keberadaan:
+alert "Elvis ada!" if elvis?
+#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Elvis ada!"); }
+
+# Komprehensi *array*:
+kubik_kubik = (fungsi_matematika.kubik angka for angka in list)
+#=>kubik_kubik = (function() {
+# var _i, _len, _hasil;
+# _hasil = [];
+# for (_i = 0, _len = list.length; _i < _len; _i++) {
+# angka = list[_i];
+# _hasil.push(fungsi_matematika.kubik(angka));
+# }
+# return _hasil;
+#})();
+
+sayur_sayuran = ['brokoli', 'bayam', 'kemangi']
+makan sayuran for sayuran in sayur_sayuran when sayuran isnt 'kemangi'
+#=>sayur_sayuran = ['brokoli', 'bayam', 'kemangi'];
+#
+#for (_k = 0, _len2 = sayur_sayuran.length; _k < _len2; _k++) {
+# sayuran = sayur_sayuran[_k];
+# if (sayuran !== 'kemangi') {
+# makan(sayuran);
+# }
+#}
+```
+
+## Referensi Tambahan
+
+- [Smooth CoffeeScript (EN)] (http://autotelicum.github.io/Smooth-CoffeeScript/)
+- [CoffeeScript Ristretto (EN)] (https://leanpub.com/coffeescript-ristretto/read)
diff --git a/id-id/json-id.html.markdown b/id-id/json-id.html.markdown
index eef48c63..325e0ae2 100644
--- a/id-id/json-id.html.markdown
+++ b/id-id/json-id.html.markdown
@@ -4,7 +4,7 @@ contributors:
- ["Anna Harren", "https://github.com/iirelu"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
filename: learnjson-id.json
-translators
+translators:
- ["Rizky Luthfianto", "https://github.com/rilut"]
- ["Ahmad Zafrullah", "https://github.com/23Pstars"]
lang: id-id
diff --git a/id-id/markdown.html.markdown b/id-id/markdown.html.markdown
index 9a7c18cc..06ad1092 100644
--- a/id-id/markdown.html.markdown
+++ b/id-id/markdown.html.markdown
@@ -4,6 +4,7 @@ contributors:
- ["Dan Turkel", "http://danturkel.com/"]
translators:
- ["Tasya Aditya Rukmana", "http://github.com/tadityar"]
+lang: id-id
filename: markdown-id.md
---
diff --git a/id-id/pyqt-id.html.markdown b/id-id/pyqt-id.html.markdown
new file mode 100644
index 00000000..c4833d06
--- /dev/null
+++ b/id-id/pyqt-id.html.markdown
@@ -0,0 +1,83 @@
+---
+category: tool
+tool: PyQt
+language: Python
+filename: learnqt-id.py
+contributors:
+ - ["Nathan Hughes", "https://github.com/sirsharpest"]
+translators:
+ - ["Rizky Luthfianto", "http://github.com/rilut"]
+lang: id-id
+---
+
+**Qt** adalah framework terkenal untuk pengembangan perangkat lunak *cross-platform* yang dapat dijalankan pada berbagai platform perangkat lunak dan perangkat keras dengan sedikit atau tanpa perubahan dalam kode, dengan tetap memiliki kekuatan dan kecepatan aplikasi *native*. **Qt** ditulis dalam bahasa C++.
+
+
+Tulisan ini diadaptasi dari **Intro Qt untuk C++** oleh [Aleksey Kholovchuk](https://github.com/vortexxx192). Kode-kode yang tertulis di sini akan menghasilkan fungsionalitas yang sama. Bedanya, versi ini dibangun menggunakan **PyQt**!
+
+```Python
+import sys
+from PyQt4 import QtGui
+
+def window():
+# Buat objek aplikasi
+ app = QtGui.QApplication(sys.argv)
+# Buat sebuah widget, sebagai tempat di mana label kita akan ditempatkan
+ w = QtGui.QWidget()
+# Tambahkan label untuk widget
+ b = QtGui.QLabel(w)
+# Set teks untuk label
+ b.setText("Halo, Dunia!")
+# Set parameter penempatan dan ukuran
+ w.setGeometry(100, 100, 200, 50)
+ b.move(50, 20)
+# Set judul pada jendela
+ w.setWindowTitle("PyQt")
+# Tampilkan segalanya
+ w.show()
+# Jalankan apa yang telah kita atur. Setelah semua selesai kita atur.
+ sys.exit(app.exec_())
+
+if __name__ == '__main__':
+ window()
+```
+
+Untuk menunjukkan beberapa fitur yang lebih canggih di **PyQt**, kita akan membangun elemen tambahan.
+Di sini, kita akan membuat Kotak Popup Dialog, yang berguna untuk meminta pengguna untuk mengkonfirmasi keputusan atau untuk menampilkan informasi.
+
+```Python
+import sys
+from PyQt4.QtGui import *
+from PyQt4.QtCore import *
+
+
+def window():
+ app = QApplication(sys.argv)
+ w = QWidget()
+ # Buat tombol b dan tempelkan pada widget w
+ b = QPushButton(w)
+ b.setText("Tekan aku!")
+ b.move(50, 50)
+ # Perintahkan tombol b untuk memanggil fungsi ini ketika diklik
+ # Perhatikan bahwa kita tidak menggunakan simbol "()" pada pemanggilan fungsi kali ini
+ b.clicked.connect(ShowDialog)
+ w.setWindowTitle("Dialog PyQt")
+ w.show()
+ sys.exit(app.exec_())
+
+# Fungsi ini akan membuat jendela dialog dengan tombol
+# yang menunggu untuk diklik untuk keluar dari program
+def ShowDialog():
+ d = QDialog()
+ b1 = QPushButton("ok", d)
+ b1.move(50, 50)
+ d.setWindowTitle("Dialog")
+ # Modalitas ini memberitahu popup untuk memblokir induk saat ini aktif
+ d.setWindowModality(Qt.ApplicationModal)
+ # Pada klik, kita ingin seluruh proses untuk berhenti
+ b1.clicked.connect(sys.exit)
+ d.exec_()
+
+if __name__ == '__main__':
+ window()
+```
diff --git a/id-id/smallbasic-id.html.markdown b/id-id/smallbasic-id.html.markdown
new file mode 100644
index 00000000..d782c859
--- /dev/null
+++ b/id-id/smallbasic-id.html.markdown
@@ -0,0 +1,133 @@
+---
+language: SmallBASIC
+filename: learnsmallbasic-id.bas
+contributors:
+ - ["Chris Warren-Smith", "http://smallbasic.sourceforge.net"]
+translators:
+ - ["Rizky Luthfianto", "http://github.com/rilut"]
+lang: id-id
+---
+
+## Tentang
+
+SmallBASIC adalah *interpreter* bahasa BASIC yang mudah dan cepat dipelajari yang ideal untuk perhitungan sehari-hari, skrip dan prototipe. Fitur SmallBASIC termasuk trigonometri, matriks dan fungsi aljabar, yang dibangun di IDE, *library* string yang canggih, sistem, suara, dan perintah grafis bersama dengan sintaks pemrograman terstruktur.
+
+## Pengembangan
+
+SmallBASIC pada awalnya dikembangkan oleh Nicholas Christopoulos pada akhir tahun 1999 untuk Palm Pilot. pengembangan proyek telah dilanjutkan oleh Chris Warren-Smith sejak sekitar tahun 2005.
+
+Versi SmallBASIC telah dibuat untuk sejumlah perangkat genggam termasuk Franklin eBookman dan Nokia 770. Juga berbagai versi desktop yang telah dirilis berdasarkan berbagai GUI. Platform yang didukung saat ini adalah Linux dan Windows berbasis SDL2 dan Android berbasis NDK. Sebuah versi baris perintah pada desktop juga tersedia, meskipun tidak biasanya dirilis dalam bentuk biner.
+
+Sekitar tahun 2008, sebuah perusahaan merilis lingkungan pemrograman BASIC dengan nama yang mirip. SmallBASIC tidak berhubungan dengan itu.
+
+```
+REM ini adalah komentar
+'dan ini juga komentar
+
+REM mencetak kalimat
+print "halo"
+? "Tanda ? adalah singkatan dari PRINT"
+
+REM Struktur kontrol
+FOR index = 0 TO 10 STEP 2
+  ? "Ini adalah nomor baris"; indeks
+NEXT
+J=0
+REPEAT
+ J++
+UNTIL J=10
+WHILE J>0
+ J--
+WEND
+
+REM Pernyataan "Select case"
+Select Case "Cool"
+ Case "null", 1,2,3,4,5,6,7,8,"Cool","blah"
+ Case "Not cool"
+ PRINT "Epic fail"
+ Case Else
+ PRINT "Fail"
+End Select
+
+REM menangkap kesalahan dengan TRY / CATCH
+Try
+ fn = Freefile
+ Open filename For Input As #fn
+Catch err
+ Print "gagal membuka file"
+End Try
+
+REM Fungsi dan subrutin buatan pengguna
+func add2(x, y)
+  'Variabel dapat dinyatakan sebagai lokal dalam lingkup/scope dari SUB atau FUNC
+  local k
+  k = "k akan lenyap ketika FUNC ini mengembalikan nilai"
+  add2 = x + y
+akhir
+Print add2(5,5)
+sub cetak_ini(ini)
+ print ini
+end
+cetak_ini "INI"
+
+REM Menampilkan garis dan piksel
+At 0,ymax/2+txth("Q")
+Color 1: ? "sin(x)":
+Color 8: ? "cos(x)":
+Color 12: ? "tan(x)"
+Line 0,ymax/2,xmax,ymax/2
+For i=0 to xmax
+ Pset i,ymax/2-sin(i*2*pi/ymax)*ymax/4 color 1
+ Pset i,ymax/2-cos(i*2*pi/ymax)*ymax/4 color 8
+ Pset i,ymax/2-tan(i*2*pi/ymax)*ymax/4 color 12
+Next
+showpage
+
+REM SmallBASIC cocok untuk bereksperimen dengan fraktal dan efek menarik lainnya
+Delay 3000
+Randomize
+ff = 440.03
+For j = 0 to 20
+ r = rnd * 1000 % 255
+ b = rnd * 1000 % 255
+ g = rnd * 1000 % 255
+ c = rgb(r,b,g)
+ ff += 9.444
+ for i=0 to 25000
+ f += ff
+ x = min(xmax, -x + cos(f*i))
+ y = min(ymax, -y + sin(f*i))
+ pset x, y color c
+ if (i%1000==0) then
+ showpage
+ fi
+ next
+Next j
+
+REM Untuk sejarawan komputer, SmallBASIC dapat menjalankan program
+REM dari buku dan majalah komputer lama, misalnya:
+10 LET A=9
+20 LET B=7
+30 PRINT A*B
+40 PRINT A/B
+
+REM SmallBASIC juga memiliki dukungan untuk beberapa konsep modern seperti JSON
+aa = array("{\"kucing\":{\"nama\":\"harry\"},\"peliharaan\":\"true\"}")
+If (ismap(aa) == false) Then
+ throw "bukan tipe data map"
+End If
+Print aa
+
+PAUSE
+
+```
+
+## Artikel
+
+* [Persiapan](http://smallbasic.sourceforge.net/?q=node/1573)
+* [Selamat Datang di SmallBASIC](http://smallbasic.sourceforge.net/?q=node/838)
+
+## GitHub
+
+* [Source code](https://github.com/smallbasic/SmallBASIC)
+* [Referensi snapshot](http://smallbasic.github.io/)
diff --git a/it-it/bash-it.html.markdown b/it-it/bash-it.html.markdown
index d535babc..efc47969 100644
--- a/it-it/bash-it.html.markdown
+++ b/it-it/bash-it.html.markdown
@@ -10,6 +10,11 @@ contributors:
- ["Anton Strömkvist", "http://lutic.org/"]
- ["Rahil Momin", "https://github.com/iamrahil"]
- ["Gregrory Kielian", "https://github.com/gskielian"]
+ - ["Etan Reisner", "https://github.com/deryni"]
+ - ["Jonathan Wang", "https://github.com/Jonathansw"]
+ - ["Leo Rudberg", "https://github.com/LOZORD"]
+ - ["Betsy Lorton", "https://github.com/schbetsy"]
+ - ["John Detter", "https://github.com/jdetter"]
filename: LearnBash-it.sh
translators:
- ["Robert Margelli", "http://github.com/sinkswim/"]
@@ -50,6 +55,13 @@ echo '$Variabile'
# il suo nome senza $. Se vuoi usare il valore della variabile, devi usare $.
# Nota che ' (singolo apice) non espande le variabili!
+# Espansione dei parametri ${ }:
+echo ${Variabile}
+# Questo è un esempio semplice dell'espansione dei parametri.
+# L'espansione dei parametri prende il valore di una variabile, ed appunto lo "espande" o lo stampa.
+# Durante l'espansione il valore o il parametro passato possono essere modificati.
+# Sotto ci sono altri esempi che analizzano l'uso dell'espansione dei parametri.
+
# Sostituzione di stringhe nelle variabili
echo ${Variabile/Una/A}
# Questo sostituirà la prima occorrenza di "Una" con "La"
@@ -64,6 +76,12 @@ echo ${Foo:-"ValoreDiDefaultSeFooMancaOppureÈVuoto"}
# Questo funziona per null (Foo=), stringa vuota (Foo=""), zero (Foo=0) ritorna 0
# Nota: viene ritornato il valore di default, il contenuto della variabile pero' non cambia.
+# Espansione delle graffe { }
+# Viene usata per generare stringe in modo arbitrario
+echo {1..10}
+echo {a..z}
+# Con questi comandi viene stampato l'intervallo dal valore iniziale al valore finale (i numeri da 1 a 10, le lettere dell'alfabeto)
+
# Variabili builtin:
# Ci sono delle variabili builtin molto utili, come
echo "Valore di ritorno dell'ultimo programma eseguito: $?"
@@ -72,6 +90,18 @@ echo "Numero di argomenti: $#"
echo "Argomenti dello script: $@"
echo "Argomenti dello script separati in variabili distinte: $1 $2..."
+# Adesso che sappiamo come stampare a schermo, e come usare le variabili, possiamo andare avanti con le basi di bash!
+# Per conoscere la directory su cui siamo posizionati, è sufficiente usare `pwd`.
+# `pwd` è l'acronimo di "print working directory", ovvero "stampa la directory corrente".
+# Possiamo anche usare la variabile builtin `$PWD`.
+# Prova questi due esempi, e vedi che il risultato è lo stesso:
+echo "Sono dentro $(pwd)" # esegue `pwd` ed interpola l'output
+echo "Sono dentro $PWD" # interpola direttamente la variabile builtin
+
+# Se c'è troppo testo nel terminale, ottenuto scrivendo comandi oppure eseguendo uno script, il comando `clear` pulisce lo schermo
+clear
+# Puoi utilizzare anche Ctrl-L al posto di clear
+
# Leggere un valore di input:
echo "Come ti chiami?"
read Nome # Nota che non abbiamo dovuto dichiarare una nuova variabile
@@ -120,12 +150,52 @@ ls
# Questi comandi hanno opzioni che controllano la loro esecuzione:
ls -l # Elenca tutti i file e le cartelle su una riga separata
+ls -t # Ordina i contenuti della cartella in base all'ultima data di modifica (ordine decrescente)
+ls -R # Esegue `ls` in modo ricorsivo all'interno di questa cartella e tutte le sottocartelle
# I risultati del comando precedente possono essere passati al comando successivo come input.
# Il comando grep filtra l'input con il pattern passato. Ecco come possiamo elencare i
# file .txt nella cartella corrente:
ls -l | grep "\.txt"
+# Usa `cat` per stampare il contenuto dei file a schermo:
+cat file.txt
+
+# Possiamo leggere il contenuto di un file e memorizzarlo in una variabile, sempre usando `cat`:
+Contenuti=$(cat file.txt)
+echo "INIZIO DEL FILE\n$Contenuti\nFINE DEL FILE"
+
+# Usa `cp` per copiare file o cartelle da un punto all'altro del sistema.
+# `cp` crea NUOVE versioni dei file, quindi le modifiche della copia non hanno effetto sull'originale, e viceversa.
+# Nota che il file (o la cartella) di destinazione vengono sovrascritte se già esistono!
+cp fileSorgente.txt copia.txt
+cp -r cartellaSorgente/ destinazione/ # copia ricorsiva
+
+# Se hai bisogno di trasferire file tra computer, puoi usare `scp` o `sftp`.
+# `scp` ha una sintassi simile a `cp`.
+# `sftp` invece è più interattivo.
+
+# Usa `mv` per spostare file o cartella da un punto all'altro del sistema.
+# `mv` è simile a `cp`, ma cancella il file(o la cartella) sorgente.
+# `mv` è molto utile anche per rinominare i file!
+mv s0rg3nt3.txt dst.txt # mi spiace anonymous...
+
+# Dal momento che bash lavora nel contesto della cartella corrente, potresti voler eseguire il comando dentro a qualche altra cartella. Per fare questo si usa `cd`:
+cd ~ # va nella cartella Home
+cd .. # va nella cartella "padre"
+ # (ad esempio da /home/user/Download a /home/user)
+cd /home/user/Documenti # entra nella cartella specificata
+cd ~/Documenti/.. # siamo sempre nella cartella home... vero?
+
+# Usa le subshell per lavorare in cartelle diverse contemporaneamente
+(echo "All'inizio sono qua: $PWD") && (cd cartella; echo "Adesso invece sono qua: $PWD")
+pwd # siamo sempre nella prima cartella
+
+# Usa `mkdir` per creare nuove cartelle
+mkdir nuovaCartella
+# Il flag `-p` indica la creazione delle cartelle intermedie, se non esistono.
+mkdir nuovaCartella/con/tante/cartelle/intermedie
+
# Puoi redirezionare l'input e l'output del comando (stdin, stdout, e stderr).
# Leggi da stdin finchè ^EOF$ e sovrascrivi hello.py con le righe
# comprese tra "EOF":
@@ -164,7 +234,9 @@ echo "#helloworld" | cat > output.out
echo "#helloworld" | tee output.out >/dev/null
# Pulisci i file temporanei verbosamente (aggiungi '-i' per la modalità interattiva)
+# Attenzione: il comando `rm` non può essere annullato!
rm -v output.out error.err output-and-error.log
+rm -r cartellaTemporanea/ # cancella ricorsivamente
# I comandi possono essere sostituiti con altri comandi usando $( ):
# Il comando seguente mostra il numero di file e cartelle nella
@@ -255,10 +327,25 @@ sed -i 's/okay/great/g' file.txt
grep "^foo.*bar$" file.txt
# passa l'opzione "-c" per stampare invece il numero delle righe che soddisfano la regex
grep -c "^foo.*bar$" file.txt
+# Altre opzioni utili possono essere:
+grep -r "^foo.*bar$" someDir/ # esegue `grep` ricorsivamente nella cartella
+grep -n "^foo.*bar$" file.txt # stampa il numero delle righe del file
+grep -rI "^foo.*bar$" someDir/ # esegue `grep` ricorsivamente nella cartella, ignorando i file non testuali
+# Esegue la stessa ricerca iniziale, ma filtrando solo le righe che contengono la stringa "baz"
+grep "^foo.*bar$" file.txt | grep -v "baz"
+
# se vuoi letteralmente cercare la stringa,
# e non la regex, usa fgrep (o grep -F)
-fgrep "^foo.*bar$" file.txt
+fgrep "foobar" file.txt
+
+# Il comando trap permette di eseguire un comando quando un segnale viene ricevuto dal tuo script.
+# In questo esempio, trap eseguirà rm se uno dei tre segnali (SIGHUP, SIGINT o SIGTERM) viene ricevuto.
+trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM
+# `sudo` viene usato per eseguire comandi come superuser, ovvero come utente che ha maggiori privilegi all'interno del sistema
+$NOME1=$(whoami)
+$NOME2=$(sudo whoami)
+echo "Ero $NOME1, poi sono diventato più potente: $NOME2"
# Leggi la documentazione dei builtin di bash con il builtin 'help' di bash:
help
diff --git a/it-it/rust-it.html.markdown b/it-it/rust-it.html.markdown
index dd5005f2..6b379f93 100644
--- a/it-it/rust-it.html.markdown
+++ b/it-it/rust-it.html.markdown
@@ -2,6 +2,7 @@
language: rust
contributors:
- ["Carlo Milanesi", "http://github.com/carlomilanesi"]
+lang: it-it
filename: rust-it.html.markdown
---
@@ -287,7 +288,7 @@ fn main() {
var = 3;
let ref_var: &i32 = &var;
- println!("{}", var); // Diversamente da `box`, `var` può ancora essere usato
+ println!("{}", var); // Diversamente da `mio`, `var` può ancora essere usato
println!("{}", *ref_var);
// var = 5; // questo non compilerebbe, perché `var` è stato preso in prestito
// *ref_var = 6; // neanche questo, perché `ref_var` è un riferimento immutabile
diff --git a/java.html.markdown b/java.html.markdown
index 57c10390..6487d862 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -1,20 +1,21 @@
---
language: java
contributors:
- - ["Jake Prather", "http://github.com/JakeHP"]
- - ["Jakukyo Friel", "http://weakish.github.io"]
- - ["Madison Dickson", "http://github.com/mix3d"]
- - ["Simon Morgan", "http://sjm.io/"]
- - ["Zachary Ferguson", "http://github.com/zfergus2"]
- - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"]
+ - ["Jake Prather", "https://github.com/JakeHP"]
+ - ["Jakukyo Friel", "https://weakish.github.io"]
+ - ["Madison Dickson", "https://github.com/mix3d"]
+ - ["Simon Morgan", "https://sjm.io/"]
+ - ["Zachary Ferguson", "https://github.com/zfergus2"]
+ - ["Cameron Schermerhorn", "https://github.com/cschermerhorn"]
- ["Rachel Stiyer", "https://github.com/rstiyer"]
- - ["Michael Dähnert", "http://github.com/JaXt0r"]
+ - ["Michael Dähnert", "https://github.com/JaXt0r"]
+ - ["Rob Rose", "https://github.com/RobRoseKnows"]
filename: LearnJava.java
---
Java is a general-purpose, concurrent, class-based, object-oriented computer
programming language.
-[Read more here.](http://docs.oracle.com/javase/tutorial/java/)
+[Read more here.](https://docs.oracle.com/javase/tutorial/java/)
```java
// Single-line comments start with //
@@ -389,7 +390,32 @@ public class LearnJava {
System.out.println("You answered " + myAnswer);
break;
}
-
+
+
+ // Try-with-resources (Java 7+)
+ // Try-catch-finally statements work as expected in Java but in Java 7+
+ // the try-with-resources statement is also available. Try-with-resources
+ // simplifies try-catch-finally statements be closing resources
+ // automatically.
+
+ // In order to use a try-with-resources, include a an instance of a class
+ // in the try statement. The class must implement java.lang.AutoCloseable.
+ try(BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
+ // You can attempt to do something that could throw an exception.
+ System.out.println(br.readLine());
+ // In Java 7, the resource will always be closed, even if it throws
+ // an Exception.
+ } catch (Exception ex) {
+ //The resource will be closed before the catch statement executes.
+ System.out.println("readLine() failed.");
+ }
+ // No need for a finally statement in this case, the BufferedReader is
+ // already closed. This can be used to avoid certain edge cases where
+ // a finally statement might not be called.
+ // To learn more:
+ // https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
+
+
// Conditional Shorthand
// You can use the '?' operator for quick assignments or logic forks.
// Reads as "If (statement) is true, use <first value>, otherwise, use
@@ -418,7 +444,7 @@ public class LearnJava {
// Typecasting
// You can also cast Java objects, there's a lot of details and deals
// with some more intermediate concepts. Feel free to check it out here:
- // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
+ // https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
///////////////////////////////////////
// Classes And Functions
@@ -784,22 +810,22 @@ The links provided here below are just to get an understanding of the topic, fee
**Official Oracle Guides**:
-* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html)
+* [Java Tutorial Trail from Sun / Oracle](https://docs.oracle.com/javase/tutorial/index.html)
-* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
+* [Java Access level modifiers](https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
-* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html):
- * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)
- * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html)
- * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
+* [Object-Oriented Programming Concepts](https://docs.oracle.com/javase/tutorial/java/concepts/index.html):
+ * [Inheritance](https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)
+ * [Polymorphism](https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html)
+ * [Abstraction](https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
-* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html)
+* [Exceptions](https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html)
-* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)
+* [Interfaces](https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)
-* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html)
+* [Generics](https://docs.oracle.com/javase/tutorial/java/generics/index.html)
-* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html)
+* [Java Code Conventions](https://www.oracle.com/technetwork/java/codeconvtoc-136057.html)
**Online Practice and Tutorials**
@@ -813,6 +839,6 @@ The links provided here below are just to get an understanding of the topic, fee
* [Thinking in Java](http://www.mindview.net/Books/TIJ/)
-* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660)
+* [Objects First with Java](https://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660)
-* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300)
+* [Java The Complete Reference](https://www.amazon.com/gp/product/0071606300)
diff --git a/jquery.html.markdown b/jquery.html.markdown
new file mode 100644
index 00000000..013b75d7
--- /dev/null
+++ b/jquery.html.markdown
@@ -0,0 +1,138 @@
+---
+category: tool
+tool: jquery
+contributors:
+ - ["Sawyer Charles", "https://github.com/xssc"]
+filename: jquery.js
+---
+
+jQuery is a JavaScript library that helps you "do more, write less". It makes many common JavaScript tasks and makes them easier to write. jQuery is used by many big companies and developers everywhere. It makes AJAX, event handling, document manipulation, and much more, easier and faster.
+
+Because jQuery is a JavaScript library you should [learn JavaScript first](https://learnxinyminutes.com/docs/javascript/)
+
+```js
+
+
+///////////////////////////////////
+// 1. Selectors
+
+// Selectors in jQuery are used to select an element
+var page = $(window); // Selects the whole viewport
+
+// Selectors can also be CSS selector
+var paragraph = $('p'); // Selects all paragraph elements
+var table1 = $('#table1'); // Selects element with id 'table1'
+var squares = $('.square'); // Selects all elements with the class 'square'
+var square_p = $('p.square') // Selects paragraphs with the 'square' class
+
+
+///////////////////////////////////
+// 2. Events and Effects
+
+// A very common event used is the ready event on the document
+// You can use the 'ready' method to wait until the element has finished loading
+$(document).ready(function(){
+ // Code won't execute until the document is loaded
+});
+
+// jQuery is very good at triggering events
+// and also handling what happens when an event is triggered
+$('#button').click(); // Fires a click event on $('#button')
+$('#button').click(function(){
+ // Code here gets executed when the #button element is clicked
+});
+
+function onAction() {
+ // This is executed when the event is triggered
+}
+
+// Some other common events are:
+$('#btn').dblclick(onAction); // Double click
+$('#btn').hover(onAction); // Hovering over
+$('#btn').focus(onAction); // On focus
+$('#btn').blur(onAction); // Losses focus
+$('#btn').submit(onAction); // On submit
+$('#btn').select(onAction); // When an element is selected
+$('#btn').keydown(onAction); // When a key is pushed down
+$('#btn').keyup(onAction); // When a key is released
+$('#btn').keypress(onAction); // When a key is pressed
+$('#btn').mousemove(onAction); // When the mouse is moved
+$('#btn').mouseenter(onAction); // Mouse enters the element
+$('#btn').mouseleave(onAction); // Mouse leaves the element
+
+// You can also use an anonymous function
+$('#btn').hover(function(){
+ // Executed on hover
+});
+
+// These can all also trigger the event instead of handling it
+// by simply not giving any parameters
+$('#btn').dblclick(); // Fires double click on the element
+
+// You can handle multiple events while only using the selector once
+$('#btn').on(
+ {dblclick: myFunction1} // Triggered on double click
+ {blur: myFunction1} // Triggered on blur
+);
+
+// You can move and hide elements with some effect methods
+$('.table').hide(); # Hides the element(s)
+
+// Note: calling a function in these methods will still hide the element
+$('.table').hide(function(){
+ // Element hidden then function executed
+});
+
+// You can store selectors in variables
+var tables = $('.table');
+
+// Some basic document manipulation methods are:
+tables.hide(); // Hides element(s)
+tables.show(); // Shows (un-hides) element(s)
+tables.toggle(); // Changes the hide/show state
+tables.fadeOut(); // Fades out
+tables.fadeIn(); // Fades in
+tables.fadeToggle(); // Fades in or out
+tables.fadeTo(0.5); // Fades to an opacity (between 0 and 1)
+tables.slideUp(); // Slides up
+tables.slideDown(); // Slides down
+tables.slideToggle(); // Slides up or down
+
+// All of the above take a speed (milliseconds) and callback function
+tables.hide(1000, myFunction); // 1 second hide animation then function
+
+// fadeTo has a required opacity as its second parameter
+tables.fadeTo(2000, 0.1, myFunction); // 2 sec. fade to 0.1 opacity then function
+
+// You can get slightly more advanced with the animate method
+tables.animate({margin-top:"+=50", height: "100px"}, 500, myFunction);
+// The animate method takes an object of css and values to end with,
+// optional options parameter to tune the animation,
+// and of course the callback function
+
+///////////////////////////////////
+// 3. Manipulation
+
+// These are similar to effects but can do more
+$('div').addClass('div') // Adds class div to all div taming-slim-20
+
+// Common manipulation methods
+$('p').append('Hello world'); // Adds to end of element
+$('p').attr('class'); // Gets attribute
+$('p').attr('class', 'content'); // Sets attribute
+$('p').hasClass('div'); // Returns true if it has the class
+$('p').height(); // Gets height of element or sets height
+
+
+// For many manipulation methods, getting info on an element
+// will ONLY get the first matching element
+$('p').height(); // Gets only the first 'p' tag's height
+
+// You can use each to loop through all the elements
+var heights = [];
+$('p').each(function() {
+ heights.push($(this.height)); // Adds all 'p' tag heights to array
+});
+
+
+``
diff --git a/kotlin.html.markdown b/kotlin.html.markdown
index 605b1a63..d1f1aae6 100644
--- a/kotlin.html.markdown
+++ b/kotlin.html.markdown
@@ -9,7 +9,7 @@ Kotlin is a statically typed programming language for the JVM, Android and the
browser. It is 100% interoperable with Java.
[Read more here.](https://kotlinlang.org/)
-```java
+```kotlin
// Single-line comments start with //
/*
Multi-line comments look like this.
@@ -42,12 +42,12 @@ fun main(args: Array<String>) {
Strings can be represented in a similar way as in Java.
Escaping is done with a backslash.
*/
- val fooString = "My String Is Here!";
- val barString = "Printing on a new line?\nNo Problem!";
- val bazString = "Do you want to add a tab?\tNo Problem!";
- println(fooString);
- println(barString);
- println(bazString);
+ val fooString = "My String Is Here!"
+ val barString = "Printing on a new line?\nNo Problem!"
+ val bazString = "Do you want to add a tab?\tNo Problem!"
+ println(fooString)
+ println(barString)
+ println(bazString)
/*
A raw string is delimited by a triple quote (""").
@@ -87,7 +87,7 @@ fun helloWorld(val name : String) {
Function arguments can optionally have a default value.
The function return type, if required, is specified after the arguments.
*/
- fun hello(name: String = "world") : String {
+ fun hello(name: String = "world"): String {
return "Hello, $name!"
}
println(hello("foo")) // => Hello, foo!
@@ -119,16 +119,16 @@ fun helloWorld(val name : String) {
println(even(7)) // => false
// Functions can take functions as arguments and return functions.
- fun not(f: (Int) -> Boolean) : (Int) -> Boolean {
+ fun not(f: (Int) -> Boolean): (Int) -> Boolean {
return {n -> !f.invoke(n)}
}
// Named functions can be specified as arguments using the :: operator.
val notOdd = not(::odd)
val notEven = not(::even)
- // Anonymous functions can be specified as arguments.
+ // Lambda expressions can be specified as arguments.
val notZero = not {n -> n == 0}
/*
- If an anonymous function has only one parameter
+ If a lambda has only one parameter
then its declaration can be omitted (along with the ->).
The name of the single parameter will be "it".
*/
@@ -139,11 +139,11 @@ fun helloWorld(val name : String) {
// The "class" keyword is used to declare classes.
class ExampleClass(val x: Int) {
- fun memberFunction(y: Int) : Int {
+ fun memberFunction(y: Int): Int {
return x + y
}
- infix fun infixMemberFunction(y: Int) : Int {
+ infix fun infixMemberFunction(y: Int): Int {
return x * y
}
}
@@ -175,6 +175,17 @@ fun helloWorld(val name : String) {
// Objects can be destructured into multiple variables.
val (a, b, c) = fooCopy
println("$a $b $c") // => 1 100 4
+
+ // destructuring in "for" loop
+ for ((a, b, c) in listOf(fooData)) {
+ println("$a $b $c") // => 1 100 4
+ }
+
+ val mapData = mapOf("a" to 1, "b" to 2)
+ // Map.Entry is destructurable as well
+ for ((key, value) in mapData) {
+ println("$key -> $value")
+ }
// The "with" function is similar to the JavaScript "with" statement.
data class MutableDataClassExample (var x: Int, var y: Int, var z: Int)
@@ -217,16 +228,16 @@ fun helloWorld(val name : String) {
Sequences represent lazily-evaluated collections.
We can create a sequence using the "generateSequence" function.
*/
- val fooSequence = generateSequence(1, {it + 1})
+ val fooSequence = generateSequence(1, { it + 1 })
val x = fooSequence.take(10).toList()
println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// An example of using a sequence to generate Fibonacci numbers:
- fun fibonacciSequence() : Sequence<Long> {
+ fun fibonacciSequence(): Sequence<Long> {
var a = 0L
var b = 1L
- fun next() : Long {
+ fun next(): Long {
val result = a + b
a = b
b = result
@@ -261,6 +272,14 @@ fun helloWorld(val name : String) {
ctr++
} while (ctr < 10)
+ /*
+ "if" can be used as an expression that returns a value.
+ For this reason the ternary ?: operator is not needed in Kotlin.
+ */
+ val num = 5
+ val message = if (num % 2 == 0) "even" else "odd"
+ println("$num is $message") // => 5 is odd
+
// "when" can be used as an alternative to "if-else if" chains.
val i = 10
when {
@@ -309,6 +328,14 @@ fun helloWorld(val name : String) {
println(smartCastExample(0)) // => false
println(smartCastExample(true)) // => true
+ // Smartcast also works with when block
+ fun smartCastWhenExample(x: Any) = when (x) {
+ is Boolean -> x
+ is Int -> x > 0
+ is String -> x.isNotEmpty()
+ else -> false
+ }
+
/*
Extensions are a way to add new functionality to a class.
This is similar to C# extension methods.
@@ -329,15 +356,20 @@ enum class EnumExample {
/*
The "object" keyword can be used to create singleton objects.
-We cannot assign it to a variable, but we can refer to it by its name.
+We cannot instantiate it but we can refer to its unique instance by its name.
This is similar to Scala singleton objects.
*/
object ObjectExample {
- fun hello() : String {
+ fun hello(): String {
return "hello"
}
}
+fun useObject() {
+ ObjectExample.hello()
+ val someRef: Any = ObjectExample // we use objects name just as is
+}
+
```
### Further Reading
diff --git a/latex.html.markdown b/latex.html.markdown
index 81c0d24c..a3866892 100644
--- a/latex.html.markdown
+++ b/latex.html.markdown
@@ -5,6 +5,7 @@ contributors:
- ["Colton Kohnke", "http://github.com/voltnor"]
- ["Sricharan Chiruvolu", "http://sricharan.xyz"]
- ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"]
+ - ["Svetlana Golubeva", "https://attillax.github.io/"]
filename: learn-latex.tex
---
@@ -27,14 +28,17 @@ filename: learn-latex.tex
% If you want to include graphics, colored text, or
% source code from another language file into your document,
% you need to enhance the capabilities of LaTeX. This is done by adding packages.
-% I'm going to include the float and caption packages for figures.
+% I'm going to include the float and caption packages for figures
+% and hyperref package for hyperlinks
\usepackage{caption}
\usepackage{float}
+\usepackage{hyperref}
% We can define some other document properties too!
-\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu}
+\author{Chaitanya Krishna Ande, Colton Kohnke, Sricharan Chiruvolu \& \\
+Svetlana Golubeva}
\date{\today}
-\title{Learn LaTeX in Y Minutes!}
+\title{Learn \LaTeX \hspace{1pt} in Y Minutes!}
% Now we're ready to begin the document
% Everything before this line is called "The Preamble"
@@ -43,18 +47,28 @@ filename: learn-latex.tex
% create a title page for us.
\maketitle
+% If we have sections, we can create table of contents. We have to compile our
+% document twice to make it appear in right order.
+% It is a good practice to separate the table of contents form the body of the
+% document. To do so we use \newpage command
+\newpage
+\tableofcontents
+
+\newpage
+
% Most research papers have abstract, you can use the predefined commands for this.
% This should appear in its logical order, therefore, after the top matter,
% but before the main sections of the body.
% This command is available in the document classes article and report.
\begin{abstract}
- LaTeX documentation written as LaTeX! How novel and totally not my idea!
+ \LaTeX \hspace{1pt} documentation written as \LaTeX! How novel and totally not
+ my idea!
\end{abstract}
% Section commands are intuitive.
% All the titles of the sections are added automatically to the table of contents.
\section{Introduction}
-Hello, my name is Colton and together we're going to explore LaTeX!
+Hello, my name is Colton and together we're going to explore \LaTeX!
\section{Another section}
This is the text for another section. I think it needs a subsection.
@@ -72,12 +86,14 @@ Much better now.
However not all sections have to be numbered!
\section{Some Text notes}
-LaTeX is generally pretty good about placing text where it should go. If
-a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash to
-the source code. \\
+%\section{Spacing} % Need to add more information about space intervals
+\LaTeX \hspace{1pt} is generally pretty good about placing text where it should
+go. If
+a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash
+\hspace{1pt} to the source code. \\
\section{Lists}
-Lists are one of the easiest things to create in LaTeX! I need to go shopping
+Lists are one of the easiest things to create in \LaTeX! I need to go shopping
tomorrow, so let's make a grocery list.
\begin{enumerate} % This creates an "enumerate" environment.
% \item tells the enumerate to increment
@@ -93,15 +109,15 @@ tomorrow, so let's make a grocery list.
\section{Math}
-One of the primary uses for LaTeX is to produce academic articles or
-technical papers. Usually in the realm of math and science. As such,
+One of the primary uses for \LaTeX \hspace{1pt} is to produce academic articles
+or technical papers. Usually in the realm of math and science. As such,
we need to be able to add special symbols to our paper! \\
Math has many symbols, far beyond what you can find on a keyboard;
Set and relation symbols, arrows, operators, and Greek letters to name a few.\\
Sets and relations play a vital role in many mathematical research papers.
-Here's how you state all y that belong to X, $\forall$ x $\in$ X. \\
+Here's how you state all x that belong to X, $\forall$ x $\in$ X. \\
% Notice how I needed to add $ signs before and after the symbols. This is
% because when writing, we are in text-mode.
% However, the math symbols only exist in math-mode.
@@ -112,27 +128,27 @@ Here's how you state all y that belong to X, $\forall$ x $\in$ X. \\
\[a^2 + b^2 = c^2 \]
My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$.
-I haven't found a Greek letter that yet that LaTeX doesn't know about!
+I haven't found a Greek letter yet that \LaTeX \hspace{1pt} doesn't know
+about! \\
Operators are essential parts of a mathematical document:
trigonometric functions ($\sin$, $\cos$, $\tan$),
logarithms and exponentials ($\log$, $\exp$),
limits ($\lim$), etc.
have per-defined LaTeX commands.
-Let's write an equation to see how it's done: \\
-
-$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$
+Let's write an equation to see how it's done:
+$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ \\
-Fractions(Numerator-denominators) can be written in these forms:
+Fractions (Numerator-denominators) can be written in these forms:
% 10 / 7
-$^{10}/_{7}$
+$$ ^{10}/_{7} $$
% Relatively complex fractions can be written as
% \frac{numerator}{denominator}
-$\frac{n!}{k!(n - k)!}$ \\
+$$ \frac{n!}{k!(n - k)!} $$ \\
-We can also insert equations in an "equation environment".
+We can also insert equations in an ``equation environment''.
% Display math with the equation 'environment'
\begin{equation} % enters math-mode
@@ -185,12 +201,10 @@ We can also insert Tables in the same way as figures.
\end{tabular}
\end{table}
-% \section{Hyperlinks} % Coming soon
-
-\section{Getting LaTeX to not compile something (i.e. Source Code)}
-Let's say we want to include some code into our LaTeX document,
-we would then need LaTeX to not try and interpret that text and
-instead just print it to the document. We do this we a verbatim
+\section{Getting \LaTeX \hspace{1pt} to not compile something (i.e. Source Code)}
+Let's say we want to include some code into our \LaTeX \hspace{1pt} document,
+we would then need \LaTeX \hspace{1pt} to not try and interpret that text and
+instead just print it to the document. We do this with a verbatim
environment.
% There are other packages that exist (i.e. minty, lstlisting, etc.)
@@ -204,26 +218,46 @@ environment.
\section{Compiling}
By now you're probably wondering how to compile this fabulous document
-and look at the glorious glory that is a LaTeX pdf.
+and look at the glorious glory that is a \LaTeX \hspace{1pt} pdf.
(yes, this document actually does compile). \\
-Getting to the final document using LaTeX consists of the following steps:
+Getting to the final document using \LaTeX \hspace{1pt} consists of the following
+steps:
\begin{enumerate}
- \item Write the document in plain text (the "source code").
+ \item Write the document in plain text (the ``source code'').
\item Compile source code to produce a pdf.
- The compilation step looks something like this (in Linux): \\
+ The compilation step looks like this (in Linux): \\
\begin{verbatim}
- > pdflatex learn-latex.tex learn-latex.pdf
+ > pdflatex learn-latex.tex
\end{verbatim}
\end{enumerate}
-A number of LaTeX editors combine both Step 1 and Step 2 in the same piece of
-software. So, you get to see Step 1, but not Step 2 completely.
-Step 2 is still happening behind the scenes.
+A number of \LaTeX \hspace{1pt}editors combine both Step 1 and Step 2 in the
+same piece of software. So, you get to see Step 1, but not Step 2 completely.
+Step 2 is still happening behind the scenes\footnote{In cases, where you use
+references (like Eqn.~\ref{eq:pythagoras}), you may need to run Step 2
+multiple times, to generate an intermediary *.aux file.}.
+% Also, this is how you add footnotes to your document!
You write all your formatting information in plain text in Step 1.
The compilation part in Step 2 takes care of producing the document in the
format you defined in Step 1.
+\section{Hyperlinks}
+We can also insert hyperlinks in our document. To do so we need to include the
+package hyperref into preamble with the command:
+\begin{verbatim}
+ \usepackage{hyperref}
+\end{verbatim}
+
+There exists two main types of links: visible URL \\
+\url{https://learnxinyminutes.com/docs/latex/}, or
+\href{https://learnxinyminutes.com/docs/latex/}{shadowed by text}
+% You can not add extra-spaces or special symbols into shadowing text since it
+% will cause mistakes during the compilation
+
+This package also produces list of tumbnails in the output pdf document and
+active links in the table of contents.
+
\section{End}
That's all for now!
@@ -233,7 +267,8 @@ That's all for now!
\begin{thebibliography}{1}
% similar to other lists, the \bibitem command can be used to list items
% each entry can then be cited directly in the body of the text
- \bibitem{latexwiki} The amazing LaTeX wikibook: {\em https://en.wikibooks.org/wiki/LaTeX}
+ \bibitem{latexwiki} The amazing \LaTeX \hspace{1pt} wikibook: {\em
+https://en.wikibooks.org/wiki/LaTeX}
\bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com}
\end{thebibliography}
diff --git a/less.html.markdown b/less.html.markdown
index d88b6ee9..ee67c1bc 100644
--- a/less.html.markdown
+++ b/less.html.markdown
@@ -16,20 +16,20 @@ Less (and other preprocessors, such as [Sass](http://sass-lang.com/) help develo
/*Multi line comments are preserved. */
-/*Variables
-==============================*/
+/* Variables
+==============================*/
/* You can store a CSS value (such as a color) in a variable.
-Use the '@' symbol to create a variable. */
+ Use the '@' symbol to create a variable. */
@primary-color: #a3a4ff;
@secondary-color: #51527f;
@body-font: 'Roboto', sans-serif;
/* You can use the variables throughout your stylesheet.
-Now if you want to change a color, you only have to make the change once.*/
+ Now if you want to change a color, you only have to make the change once.*/
body {
background-color: @primary-color;
@@ -38,6 +38,7 @@ body {
}
/* This would compile to: */
+
body {
background-color: #a3a4ff;
color: #51527F;
@@ -46,16 +47,16 @@ body {
/* This is much more maintainable than having to change the color
-each time it appears throughout your stylesheet. */
+ each time it appears throughout your stylesheet. */
-/*Mixins
-==============================*/
+/* Mixins
+==============================*/
/* If you find you are writing the same code for more than one
-element, you might want to reuse that easily.*/
+ element, you might want to reuse that easily.*/
.center {
display: block;
@@ -72,7 +73,8 @@ div {
background-color: @primary-color;
}
-/*Which would compile to: */
+/* Which would compile to: */
+
.center {
display: block;
margin-left: auto;
@@ -105,7 +107,7 @@ div {
background-color: @primary-color;
}
-/*Which would compile to: */
+/* Which would compile to: */
div {
display: block;
margin-left: auto;
@@ -116,12 +118,12 @@ div {
}
-/*Nesting
-==============================*/
+/* Nesting
+==============================*/
-/*Less allows you to nest selectors within selectors */
+/* Less allows you to nest selectors within selectors */
ul {
list-style-type: none;
@@ -135,8 +137,8 @@ ul {
/* '&' will be replaced by the parent selector. */
/* You can also nest pseudo-classes. */
/* Keep in mind that over-nesting will make your code less maintainable.
-Best practices recommend going no more than 3 levels deep when nesting.
-For example: */
+ Best practices recommend going no more than 3 levels deep when nesting.
+ For example: */
ul {
list-style-type: none;
@@ -175,16 +177,17 @@ ul li a {
}
-/*Functions
-==============================*/
+/* Functions
+==============================*/
/* Less provides functions that can be used to accomplish a variety of
- tasks. Consider the following */
+ tasks. Consider the following: */
/* Functions can be invoked by using their name and passing in the
- required arguments */
+ required arguments. */
+
body {
width: round(10.25px);
}
@@ -215,11 +218,10 @@ body {
mixins. When trying to choose between a function or a mixin, remember
that mixins are best for generating CSS while functions are better for
logic that might be used throughout your Less code. The examples in
- the Math Operators' section are ideal candidates for becoming a reusable
+ the 'Math Operators' section are ideal candidates for becoming a reusable
function. */
-/* This function will take a target size and the parent size and calculate
- and return the percentage */
+/* This function calculates the average of two numbers: */
.average(@x, @y) {
@average-result: ((@x + @y) / 2);
@@ -236,11 +238,12 @@ div {
padding: 33px;
}
+
+
/*Extend (Inheritance)
==============================*/
-
/*Extend is a way to share the properties of one selector with another. */
.display {
@@ -269,11 +272,11 @@ div {
add unnecessary bloat to the files created by the Less compiler. */
+
/*Partials and Imports
==============================*/
-
/* Less allows you to create partial files. This can help keep your Less
code modularized. Partial files conventionally begin with an '_',
e.g. _reset.less. and are imported into a main less file that gets
@@ -314,9 +317,9 @@ body {
}
-/*Math Operations
-==============================*/
+/* Math Operations
+==============================*/
/* Less provides the following operators: +, -, *, /, and %. These can
@@ -377,9 +380,7 @@ If you want to play with Less in your browser, check out:
## Compatibility
-Less can be used in any project as long as you have a program to compile it
-into CSS. You'll want to verify that the CSS you're using is compatible
-with your target browsers.
+Less can be used in any project as long as you have a program to compile it into CSS. You'll want to verify that the CSS you're using is compatible with your target browsers.
[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility.
diff --git a/logtalk.html.markdown b/logtalk.html.markdown
new file mode 100644
index 00000000..385e38f9
--- /dev/null
+++ b/logtalk.html.markdown
@@ -0,0 +1,543 @@
+---
+language: Logtalk
+contributors:
+ - ["Paulo Moura", "http://github.com/pmoura"]
+filename: learnlogtalk.lgt
+---
+
+Logtalk is an object-oriented logic programming language that extends and leverages Prolog with modern code encapsulation and code reuse mechanisms without compromising its declarative programming features. Logtalk is implemented in highly portable code and can use most modern and standards compliant Prolog implementations as a back-end compiler.
+
+To keep its size reasonable, this tutorial necessarily assumes that the reader have a working knowledge of Prolog and is biased towards describing Logtalk object-oriented features.
+
+# Syntax
+
+Logtalk uses standard Prolog syntax with the addition of a few operators and directives for a smooth learning curve and wide portability. One important consequence is that Prolog code can be easily encapsulated in objects with little or no changes. Moreover, Logtalk can transparently interpret most Prolog modules as Logtalk objects.
+
+The main operators are:
+
+* `::/2` - sending a message to an object
+* `::/1` - sending a message to _self_ (i.e. to the object that received the message being processed)
+* `^^/1` - _super_ call (of an inherited or imported predicate)
+
+Some of the most important entity and predicate directives will be introduced in the next sections.
+
+# Entities and roles
+
+Logtalk provides _objects_, _protocols_, and _categories_ as first-class entities. Relations between entities define _patterns of code reuse_ and the _roles_ played by the entities. For example, when an object _instantiates_ another object, the first object plays the role of an instance and the second object plays the role of a class. An _extends_ relation between two objects implies that both objects play the role of prototypes, with one of them extending the other, its parent prototype.
+
+# Defining an object
+
+An object encapsulates predicate declarations and definitions. Objects can be created dynamically but are usually static and defined in source files. A single source file can contain any number of entity definitions. A simple object, defining a list member public predicate:
+
+```
+:- object(list).
+
+ :- public(member/2).
+ member(Head, [Head| _]).
+ member(Head, [_| Tail]) :-
+ member(Head, Tail).
+
+:- end_object.
+```
+
+# Compiling source files
+
+Assuming that the code above for the `list` object is saved in a `list.lgt` file, it can be compiled and loaded using the `logtalk_load/1` built-in predicate or its abbreviation, `{}/1`, with the file path as argument (the extension can be omitted):
+
+```
+?- {list}.
+yes
+```
+
+# Sending a message to an object
+
+The `::/2` infix operator is used to send a message to an object. As in Prolog, we can backtrack for alternative solutions:
+
+```
+?- list::member(X, [1,2,3]).
+X = 1 ;
+X = 2 ;
+X = 3
+yes
+```
+
+Encapsulation is enforced. A predicate can be declared _public_, _protected_, or _private_. It can also be _local_ when there is no scope directive for it. For example:
+
+```
+:- object(scopes).
+
+ :- private(bar/0).
+ bar.
+
+ local.
+
+:- end_object.
+```
+
+Assuming the object is saved in a `scopes.lgt` file:
+
+```
+?- {scopes}.
+yes
+
+?- catch(scopes::bar, Error, true).
+Error = error(
+ permission_error(access, private_predicate, bar/0),
+ logtalk(scopes::bar, user)
+)
+yes
+
+?- catch(scopes::local, Error, true).
+Error = error(
+ existence_error(predicate_declaration, local/0),
+ logtalk(scopes::local, user)
+)
+yes
+```
+
+When the predicate in a message is unknown for the object (the role it plays determines the lookup procedures), we also get an error. For example:
+
+```
+?- catch(scopes::unknown, Error, true).
+Error = error(
+ existence_error(predicate_declaration, unknown/0),
+ logtalk(scopes::unknown, user)
+)
+yes
+```
+
+A subtle point is that predicate scope directives specify predicate _calling_ semantics, not _definitions_ semantics. For example, if an object playing the role of a class declares a predicate private, the predicate can be defined in subclasses and instances *but* can only be called in its instances _from_ the class.
+
+# Defining and implementing a protocol
+
+Protocols contain predicate declarations that can be implemented by any number of objects and categories:
+
+```
+:- protocol(listp).
+
+ :- public(member/2).
+
+:- end_protocol.
+
+:- object(list,
+ implements(listp)).
+
+ member(Head, [Head| _]).
+ member(Head, [_| Tail]) :-
+ member(Head, Tail).
+
+:- end_object.
+```
+
+The scope of the protocol predicates can be restricted using protected or private implementation. For example:
+
+```
+:- object(stack,
+ implements(private::listp)).
+
+:- end_object.
+```
+
+In fact, all entity relations (in an entity opening directive) can be qualified as public (the default), protected, or private.
+
+# Prototypes
+
+An object without an _instantiation_ or _specialization_ relation with another object plays the role of a prototype. A prototype can _extend_ another object, its parent prototype.
+
+```
+% clyde, our prototypical elephant
+:- object(clyde).
+
+ :- public(color/1).
+ color(grey).
+
+ :- public(number_of_legs/1).
+ number_of_legs(4).
+
+:- end_object.
+
+% fred, another elephant, is like clyde, except that he's white
+:- object(fred,
+ extends(clyde)).
+
+ color(white).
+
+:- end_object.
+```
+
+When answering a message sent to an object playing the role of a prototype, we validate the message and look for an answer first in the prototype itself and, if not found, we delegate to the prototype parents if any:
+
+```
+?- fred::number_of_legs(N).
+N = 4
+yes
+
+?- fred::color(C).
+C = white
+yes
+```
+
+A message is valid if the corresponding predicate is declared (and the sender is within scope) but it will fail, rather then throwing an error, if the predicate is not defined. This is called the _closed-world assumption_. For example, consider the following object, saved in a `foo.lgt` file:
+
+```
+:- object(foo).
+
+ :- public(bar).
+
+:- end_object.
+```
+
+Loading the file and trying to call the `bar/0` predicate fails as expected. Note that this is different from calling an _unknown_ predicate, which results in an error:
+
+```
+?- {foo}.
+yes
+
+?- foo::bar.
+no
+
+?- catch(foo::baz, Error, true).
+Error = error(
+ existence_error(predicate_declaration, baz/0),
+ logtalk(foo::baz, user)
+)
+yes
+```
+
+# Classes and instances
+
+In order to define objects playing the role of classes and/or instances, an object must have at least an instantiation or a specialization relation with another object. Objects playing the role of meta-classes can be used when we need to see a class also as an instance. We use the following example to also illustrate how to dynamically create new objects at runtime:
+
+```
+% a simple, generic, metaclass defining a new/2 predicate for its instances
+:- object(metaclass,
+ instantiates(metaclass)).
+
+ :- public(new/2).
+ new(Instance, Clauses) :-
+ self(Class),
+ create_object(Instance, [instantiates(Class)], [], Clauses).
+
+:- end_object.
+
+% a simple class defining age/1 and name/1 predicate for its instances
+:- object(person,
+ instantiates(metaclass)).
+
+ :- public([
+ age/1, name/1
+ ]).
+
+ % a default value for age/1
+ age(42).
+
+:- end_object.
+
+% a static instance of the class person
+:- object(john,
+ instantiates(person)).
+
+ name(john).
+ age(12).
+
+:- end_object.
+```
+
+When answering a message sent to an object playing the role of an instance, we validate the message by starting in its class and going up to its class superclasses if necessary. Assuming that the message is valid, then we look for an answer starting in the instance itself:
+
+```
+?- person::new(Instance, [name(paulo)]).
+Instance = o1
+yes
+
+?- o1::name(Name).
+Name = paulo
+yes
+
+?- o1::age(Age).
+Age = 42
+yes
+
+?- john::age(Age).
+Age = 12
+yes
+```
+
+# Categories
+
+A category is a fine grained unit of code reuse, used to encapsulate a _cohesive_ set of predicate declarations and definitions, implementing a _single_ functionality, that can be imported into any object. A category can thus be seen as the dual concept of a protocol. In the following example, we define categories representing car engines and then import them into car objects:
+
+```
+% a protocol describing engine characteristics
+:- protocol(carenginep).
+
+ :- public([
+ reference/1,
+ capacity/1,
+ cylinders/1,
+ horsepower_rpm/2,
+ bore_stroke/2,
+ fuel/1
+ ]).
+
+:- end_protocol.
+
+% a typical engine defined as a category
+:- category(classic,
+ implements(carenginep)).
+
+ reference('M180.940').
+ capacity(2195).
+ cylinders(6).
+ horsepower_rpm(94, 4800).
+ bore_stroke(80, 72.8).
+ fuel(gasoline).
+
+:- end_category.
+
+% a souped up version of the previous engine
+:- category(sport,
+ extends(classic)).
+
+ reference('M180.941').
+ horsepower_rpm(HP, RPM) :-
+ ^^horsepower_rpm(ClassicHP, ClassicRPM), % "super" call
+ HP is truncate(ClassicHP*1.23),
+ RPM is truncate(ClassicRPM*0.762).
+
+:- end_category.
+
+% with engines (and other components), we may start "assembling" some cars
+:- object(sedan,
+ imports(classic)).
+
+:- end_object.
+
+:- object(coupe,
+ imports(sport)).
+
+:- end_object.
+```
+
+Categories are independently compiled and thus allow importing objects to be updated by simple updating the imported categories without requiring object recompilation. Categories also provide _runtime transparency_. I.e. the category protocol adds to the protocol of the objects importing the category:
+
+```
+?- sedan::current_predicate(Predicate).
+Predicate = reference/1 ;
+Predicate = capacity/1 ;
+Predicate = cylinders/1 ;
+Predicate = horsepower_rpm/2 ;
+Predicate = bore_stroke/2 ;
+Predicate = fuel/1
+yes
+```
+
+# Hot patching
+
+Categories can be also be used for hot-patching objects. A category can add new predicates to an object and/or replace object predicate definitions. For example, consider the following object:
+
+```
+:- object(buggy).
+
+ :- public(p/0).
+ p :- write(foo).
+
+:- end_object.
+```
+
+Assume that the object prints the wrong string when sent the message `p/0`:
+
+```
+?- {buggy}.
+yes
+
+?- buggy::p.
+foo
+yes
+```
+
+If the object source code is not available and we need to fix an application running the object code, we can simply define a category that fixes the buggy predicate:
+
+```
+:- category(patch,
+ complements(buggy)).
+
+ % fixed p/0 def
+ p :- write(bar).
+
+:- end_category.
+```
+
+After compiling and loading the category into the running application we will now get:
+
+```
+?- {patch}.
+yes
+
+?- buggy::p.
+bar
+yes
+```
+
+As hot-patching forcefully breaks encapsulation, there is a `complements` compiler flag that can be set (globally or on a per-object basis) to allow, restrict, or prevent it.
+
+# Parametric objects and categories
+
+Objects and categories can be parameterized by using as identifier a compound term instead of an atom. Object and category parameters are _logical variables_ shared with all encapsulated predicates. An example with geometric circles:
+
+```
+:- object(circle(_Radius, _Color)).
+
+ :- public([
+ area/1, perimeter/1
+ ]).
+
+ area(Area) :-
+ parameter(1, Radius),
+ Area is pi*Radius*Radius.
+
+ perimeter(Perimeter) :-
+ parameter(1, Radius),
+ Perimeter is 2*pi*Radius.
+
+:- end_object.
+```
+
+Parametric objects are used just as any other object, usually providing values for the parameters when sending a message:
+
+```
+?- circle(1.23, blue)::area(Area).
+Area = 4.75291
+yes
+```
+
+Parametric objects also provide a simple way of associating a set of predicates with a plain Prolog predicate. Prolog facts can be interpreted as _parametric object proxies_ when they have the same functor and arity as the identifiers of parametric objects. Handy syntax is provided to for working with proxies. For example, assuming the following clauses for a `circle/2` predicate:
+
+```
+circle(1.23, blue).
+circle(3.71, yellow).
+circle(0.39, green).
+circle(5.74, black).
+circle(8.32, cyan).
+```
+
+With these clauses loaded, we can easily compute for example a list with the areas of all the circles:
+
+```
+?- findall(Area, {circle(_, _)}::area(Area), Areas).
+Areas = [4.75291, 43.2412, 0.477836, 103.508, 217.468]
+yes
+```
+
+The `{Goal}::Message` construct proves `Goal`, possibly instantiating any variables in it, and sends `Message` to the resulting term.
+
+# Events and monitors
+
+Logtalk supports _event-driven programming_ by allowing defining events and monitors for those events. An event is simply the sending of a message to an object. Interpreting message sending as an atomic activity, a _before_ event and an _after_ event are recognized. Event monitors define event handler predicates, `before/3` and `after/3`, and can query, register, and delete a system-wide event registry that associates events with monitors. For example, a simple tracer for any message being sent using the `::/2` control construct can be defined as:
+
+```
+:- object(tracer,
+ implements(monitoring)). % built-in protocol for event handlers
+
+ :- initialization(define_events(_, _, _, _, tracer)).
+
+ before(Object, Message, Sender) :-
+ write('call: '), writeq(Object), write(' <-- '), writeq(Message),
+ write(' from '), writeq(Sender), nl.
+
+ after(Object, Message, Sender) :-
+ write('exit: '), writeq(Object), write(' <-- '), writeq(Message),
+ write(' from '), writeq(Sender), nl.
+
+:- end_object.
+```
+
+Assuming that the `tracer` object and the `list` object defined earlier are compiled and loaded, we can observe the event handlers in action by sending a message:
+
+```
+?- list::member(X, [1,2,3]).
+
+call: list <-- member(X, [1,2,3]) from user
+exit: list <-- member(1, [1,2,3]) from user
+X = 1 ;
+exit: list <-- member(2, [1,2,3]) from user
+X = 2 ;
+exit: list <-- member(3, [1,2,3]) from user
+X = 3
+yes
+```
+
+Events can be set and deleted dynamically at runtime by calling the `define_events/5` and `abolish_events/5` built-in predicates.
+
+Event-driven programming can be seen as a form of _computational reflection_. But note that events are only generated when using the `::/2` message-sending control construct.
+
+# Lambda expressions
+
+Logtalk supports lambda expressions. Lambda parameters are represented using a list with the `(>>)/2` infix operator connecting them to the lambda. Some simple examples using library meta-predicates:
+
+```
+?- {library(metapredicates_loader)}.
+yes
+
+?- meta::map([X,Y]>>(Y is 2*X), [1,2,3], Ys).
+Ys = [2,4,6]
+yes
+```
+
+Currying is also supported:
+
+```
+?- meta::map([X]>>([Y]>>(Y is 2*X)), [1,2,3], Ys).
+Ys = [2,4,6]
+yes
+```
+
+Lambda free variables can be expressed using the extended syntax `{Free1, ...}/[Parameter1, ...]>>Lambda`.
+
+# Macros
+
+Terms and goals in source files can be _expanded_ at compile time by specifying a _hook object_ that defines term-expansion and goal-expansion rules. For example, consider the following simple object, saved in a `source.lgt` file:
+
+```
+:- object(source).
+
+ :- public(bar/1).
+ bar(X) :- foo(X).
+
+ foo(a). foo(b). foo(c).
+
+:- end_object.
+```
+
+Assume the following hook object, saved in a `my_macros.lgt` file, that expands clauses and calls to the `foo/1` local predicate:
+
+```
+:- object(my_macros,
+ implements(expanding)). % built-in protocol for expanding predicates
+
+ term_expansion(foo(Char), baz(Code)) :-
+ char_code(Char, Code). % standard built-in predicate
+
+ goal_expansion(foo(X), baz(X)).
+
+:- end_object.
+```
+
+After loading the macros file, we can then expand our source file with it using the `hook` compiler flag:
+
+```
+?- logtalk_load(my_macros), logtalk_load(source, [hook(my_macros)]).
+yes
+
+?- source::bar(X).
+X = 97 ;
+X = 98 ;
+X = 99
+true
+```
+
+The Logtalk library provides support for combining hook objects using different workflows (for example, defining a pipeline of expansions).
+
+# Further information
+
+Visit the [Logtalk website](http://logtalk.org) for more information.
diff --git a/markdown.html.markdown b/markdown.html.markdown
index bdf42368..a1f5173b 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -96,7 +96,7 @@ I'm still in paragraph 2 too!
I'm in paragraph three!
```
-Should you ever want to insert an HTML <br /> tag, you can end a paragraph
+Should you ever want to insert an HTML `<br />` tag, you can end a paragraph
with two or more spaces and then begin a new paragraph.
```markdown
@@ -147,7 +147,7 @@ Ordered lists are done with a number followed by a period.
3. Item three
```
-You don't even have to label the items correctly and markdown will still
+You don't even have to label the items correctly and Markdown will still
render the numbers in order, but this may not be a good idea.
```markdown
diff --git a/meteor.html.markdown b/meteor.html.markdown
new file mode 100644
index 00000000..1685e0be
--- /dev/null
+++ b/meteor.html.markdown
@@ -0,0 +1,567 @@
+---
+category: tool
+tool: meteor.js
+Filename: meteor.html.markdown
+contributors:
+ - ["Mohammed Rafy", "https://github.com/IamRafy/"]
+---
+
+
+
+Meteor is an ultra-simple environment for building modern websites. What once took weeks, even with the best tools, now takes hours with Meteor.
+
+The web was originally designed to work in the same way that mainframes worked in the 70s. The application server rendered a screen and sent it over the network to a dumb terminal. Whenever the user did anything, that server rerendered a whole new screen. This model served the Web well for over a decade. It gave rise to LAMP, Rails, Django, PHP.
+
+But the best teams, with the biggest budgets and the longest schedules, now build applications in JavaScript that run on the client. These apps have stellar interfaces. They don't reload pages. They are reactive: changes from any client immediately appear on everyone's screen.
+
+They've built them the hard way. Meteor makes it an order of magnitude simpler, and a lot more fun. You can build a complete application in a weekend, or a sufficiently caffeinated hackathon. No longer do you need to provision server resources, or deploy API endpoints in the cloud, or manage a database, or wrangle an ORM layer, or swap back and forth between JavaScript and Ruby, or broadcast data invalidations to clients.
+Meteor Supports OS X, Windows, and Linux. // https://github.com/meteor/meteor/wiki/Supported-Platforms
+On Windows? https://install.meteor.com/windows
+On OS X or Linux? Install the latest official Meteor release from your terminal:
+$ curl https://install.meteor.com/ | sh
+The Windows installer supports Windows 7, Windows 8.1, Windows Server 2008, and Windows Server 2012. The command line installer supports Mac OS X 10.7 (Lion) and above, and Linux on x86 and x86_64 architectures.
+
+Once you've installed Meteor, create a project:
+meteor create myapp
+Run it locally:
+
+cd myapp
+meteor
+# Meteor server running on: http://localhost:3000/
+
+Then, open a new terminal tab and unleash it on the world (on a free server we provide):
+
+meteor deploy myapp.meteor.com
+
+Principles of Meteor
+
+* Data on the Wire. Meteor doesn't send HTML over the network. The server sends data and lets the client render it.
+
+* One Language. Meteor lets you write both the client and the server parts of your application in JavaScript.
+
+* Database Everywhere. You can use the same methods to access your database from the client or the server.
+
+* Latency Compensation. On the client, Meteor prefetches data and simulates models to make it look like server method calls return instantly.
+
+* Full Stack Reactivity. In Meteor, realtime is the default. All layers, from database to template, update themselves automatically when necessary.
+
+* Embrace the Ecosystem. Meteor is open source and integrates with existing open source tools and frameworks.
+
+* Simplicity Equals Productivity. The best way to make something seem simple is to have it actually be simple. Meteor's main functionality has clean, classically beautiful APIs.
+
+Developer Resources
+-------------------
+
+If anything in Meteor catches your interest, we hope you'll get involved with the project!
+
+TUTORIAL
+Get started fast with the official Meteor tutorial! https://www.meteor.com/install
+
+STACK OVERFLOW
+The best place to ask (and answer!) technical questions is on Stack Overflow. Be sure to add the meteor tag to your question.
+http://stackoverflow.com/questions/tagged/meteor
+
+FORUMS
+Visit the Meteor discussion forumsto announce projects, get help, talk about the community, or discuss changes to core.
+https://forums.meteor.com/
+
+GITHUB
+The core code is on GitHub. If you're able to write code or file issues, we'd love to have your help. Please read Contributing to Meteor for how to get started. https://github.com/meteor/meteor
+
+THE METEOR MANUAL
+In-depth articles about the core components of Meteor can be found on the Meteor Manual. The first article is about Tracker, our transparent reactivity framework. More articles (covering topics like Blaze, Unibuild, and DDP) are coming soon! http://manual.meteor.com/
+
+What is Meteor?
+---------------
+
+Meteor is two things:
+
+A library of packages: pre-written, self-contained modules that you might need in your app.
+
+There are about a dozen core Meteor packages that most any app will use. Two examples: webapp, which handles incoming HTTP connections, and templating, which lets you make HTML templates that automatically update live as data changes. Then there are optional packages like email, which lets your app send emails, or the Meteor Accounts series (accounts-password, accounts-facebook, accounts-ui, and others) which provide a full-featured user account system that you can drop right into your app. In addition to these "core" packages, there are thousands of community-written packages in Atmosphere, one of which might do just what you need.
+
+A command-line tool called meteor.
+
+meteor is a build tool analogous to make, rake, or the non-visual parts of Visual Studio. It gathers up all of the source files and assets in your application, carries out any necessary build steps (such as compiling CoffeeScript, minifying CSS, building npm modules, or generating source maps), fetches the packages used by your app, and outputs a standalone, ready-to-run application bundle. In development mode it can do all of this interactively, so that whenever you change a file you immediately see the changes in your browser. It's super easy to use out of the box, but it's also extensible: you can add support for new languages and compilers by adding build plugin packages to your app.
+
+The key idea in the Meteor package system is that everything should work identically in the browser and on the server (wherever it makes sense, of course: browsers can't send email and servers can't capture mouse events). Our whole ecosystem has been built from the ground up to support this.
+
+Structuring your application
+----------------------------
+
+A Meteor application is a mix of client-side JavaScript that runs inside a web browser or PhoneGap mobile app, server-side JavaScript that runs on the Meteor server inside a Node.js container, and all the supporting HTML templates, CSS rules, and static assets. Meteor automates the packaging and transmission of these different components, and it is quite flexible about how you choose to structure those components in your file tree.
+
+Special Directories
+-------------------
+
+By default, any JavaScript files in your Meteor folder are bundled and sent to the client and the server. However, the names of the files and directories inside your project can affect their load order, where they are loaded, and some other characteristics. Here is a list of file and directory names that are treated specially by Meteor:
+
+client
+
+Any directory named client is not loaded on the server. Similar to wrapping your code in if (Meteor.isClient) { ... }. All files loaded on the client are automatically concatenated and minified when in production mode. In development mode, JavaScript and CSS files are not minified, to make debugging easier. (CSS files are still combined into a single file for consistency between production and development, because changing the CSS file's URL affects how URLs in it are processed.)
+
+HTML files in a Meteor application are treated quite a bit differently from a server-side framework. Meteor scans all the HTML files in your directory for three top-level elements: <head>, <body>, and <template>. The head and body sections are separately concatenated into a single head and body, which are transmitted to the client on initial page load.
+
+server
+Any directory named server is not loaded on the client. Similar to wrapping your code in if (Meteor.isServer) { ... }, except the client never even receives the code. Any sensitive code that you don't want served to the client, such as code containing passwords or authentication mechanisms, should be kept in the server directory.
+
+Meteor gathers all your JavaScript files, excluding anything under the client, public, and private subdirectories, and loads them into a Node.js server instance. In Meteor, your server code runs in a single thread per request, not in the asynchronous callback style typical of Node. We find the linear execution model a better fit for the typical server code in a Meteor application.
+
+public
+
+All files inside a top-level directory called public are served as-is to the client. When referencing these assets, do not include public/ in the URL, write the URL as if they were all in the top level. For example, reference public/bg.png as <img src='/bg.png' />. This is the best place for favicon.ico, robots.txt, and similar files.
+
+private
+
+All files inside a top-level directory called private are only accessible from server code and can be loaded via the Assets API. This can be used for private data files and any files that are in your project directory that you don't want to be accessible from the outside.
+
+client/compatibility
+
+This folder is for compatibility JavaScript libraries that rely on variables declared with var at the top level being exported as globals. Files in this directory are executed without being wrapped in a new variable scope. These files are executed before other client-side JavaScript files.
+tests
+
+Any directory named tests is not loaded anywhere. Use this for any local test code.
+
+node_modules
+
+For compatibility with node.js tools used alongside Meteor, any directory named node_modules is not loaded anywhere. node.js packages installed into node_modules directories will not be available to your Meteor code. Use Npm.depends in your package package.js file for that.
+
+Files outside special directories
+---------------------------------
+
+All JavaScript files outside special directories are loaded on both the client and the server. That's the place for model definitions and other functions. Meteor provides the variables Meteor.isClient and Meteor.isServer (http://docs.meteor.com/#/full/meteor_isserver)so that your code can alter its behavior depending on whether it's running on the client or the server.
+
+CSS and HTML files outside special directories are loaded on the client only, and cannot be used from server code.
+
+Example File Structure
+
+The file structure of your Meteor app is very flexible. Here is an example layout that takes advantage of some of the special folders mentioned above.
+
+lib/ # common code like collections and utilities
+lib/methods.js # Meteor.methods definitions
+lib/constants.js # constants used in the rest of the code
+
+client/compatibility # legacy libraries that expect to be global
+client/lib/ # code for the client to be loaded first
+client/lib/helpers.js # useful helpers for your client code
+client/body.html # content that goes in the <body> of your HTML
+client/head.html # content for <head> of your HTML: <meta> tags, etc
+client/style.css # some CSS code
+client/<feature>.html # HTML templates related to a certain feature
+client/<feature>.js # JavaScript code related to a certain feature
+
+server/lib/permissions.js # sensitive permissions code used by your server
+server/publications.js # Meteor.publish definitions
+
+public/favicon.ico # app icon
+settings.json # configuration data to be passed to meteor --settings
+mobile-config.js # define icons and metadata for Android/iOS
+
+You can also model your directory structure after the example apps. Run meteor create --example todos and explore the directories to see where all the files in a real app could go.
+
+File Load Order
+---------------
+
+It is best to write your application in such a way that it is insensitive to the order in which files are loaded, for example by using Meteor.startup (http://docs.meteor.com/#/full/meteor_startup) , or by moving load order sensitive code into packages (http://docs.meteor.com/#/full/usingpackages) , which can explicitly control both the load order of their contents and their load order with respect to other packages. However, sometimes load order dependencies in your application are unavoidable.
+
+There are several load ordering rules. They are applied sequentially to all applicable files in the application, in the priority given below:
+
+HTML template files are always loaded before everything else
+Files beginning with main. are loaded last
+Files inside any lib/ directory are loaded next
+Files with deeper paths are loaded next
+Files are then loaded in alphabetical order of the entire path
+nav.html
+main.html
+client/lib/methods.js
+client/lib/styles.js
+lib/feature/styles.js
+lib/collections.js
+client/feature-y.js
+feature-x.js
+client/main.js
+For example, the files above are arranged in the correct load order. main.html is loaded second because HTML templates are always loaded first, even if it begins with main., since rule 1 has priority over rule 2. However, it will be loaded after nav.html because rule 2 has priority over rule 5.
+
+client/lib/styles.js and lib/feature/styles.js have identical load order up to rule 4; however, since client comes before lib alphabetically, it will be loaded first.
+
+Organizing Your Project
+-----------------------
+
+There are three main ways to organize your files into features or components. Let's say we have two types of objects in our project: apples and oranges.
+
+Method 1: Root-Level Folders
+Since the special client, server, and lib directories work if they are anywhere in the path, you can use top-level folders to organize code into modules:
+
+apples/lib/ # code for apple-related features
+apples/client/
+apples/server/
+
+oranges/lib/ # code for orange-related features
+oranges/client/
+oranges/server/
+
+Method 2: Folders inside client/ and server/
+
+lib/apples/ # common code for apples
+lib/oranges/ # and oranges
+
+client/apples/ # client code for apples
+client/oranges/ # and oranges
+
+server/apples/ # server code for apples
+server/oranges/ # and oranges
+
+Method 3: Packages
+
+This is the ultimate in code separation, modularity, and reusability. If you put the code for each feature in a separate package, the code for one feature won't be able to access the code for the other feature except through exports, making every dependency explicit. This also allows for the easiest independent testing of features. You can also publish the packages and use them in multiple apps with meteor add.
+
+packages/apples/package.js # files, dependencies, exports for apple feature
+packages/apples/<anything>.js # file loading is controlled by package.js
+
+packages/oranges/package.js # files, dependencies, exports for orange feature
+packages/oranges/<anything>.js # file loading is controlled by package.js
+
+Data and security
+-----------------
+
+Meteor makes writing distributed client code as simple as talking to a local database. It's a clean, simple, and secure approach that removes the need to implement individual RPC endpoints, manually cache data on the client to avoid slow roundtrips to the server, and carefully orchestrate invalidation messages to every client as data changes.
+
+In Meteor, the client and server share the same database API. The same exact application code — like validators and computed properties — can often run in both places. But while code running on the server has direct access to the database, code running on the client does not. This distinction is the basis for Meteor's data security model.
+
+By default, a new Meteor app includes the autopublish and insecure packages, which together mimic the effect of each client having full read/write access to the server's database. These are useful prototyping tools, but typically not appropriate for production applications. When you're ready, just remove the packages.
+
+Every Meteor client includes an in-memory database cache. To manage the client cache, the server publishes sets of JSON documents, and the client subscribes to those sets. As documents in a set change, the server patches each client's cache.
+
+Today most Meteor apps use MongoDB as their database because it is the best supported, though support for other databases is coming in the future. The Mongo.Collection class is used to declare Mongo collections and to manipulate them. Thanks to minimongo, Meteor's client-side Mongo emulator, Mongo.Collection can be used from both client and server code.
+
+// declare collections
+// this code should be included in both the client and the server
+Rooms = new Mongo.Collection("rooms");
+Messages = new Mongo.Collection("messages");
+Parties = new Mongo.Collection("parties");
+
+// server: populate collections with some initial documents
+Rooms.insert({name: "Conference Room A"});
+var myRooms = Rooms.find({}).fetch();
+Messages.insert({text: "Hello world", room: myRooms[0]._id});
+Parties.insert({name: "Super Bowl Party"});
+Each document set is defined by a publish function on the server. The publish function runs each time a new client subscribes to a document set. The data in a document set can come from anywhere, but the common case is to publish a database query.
+
+// server: publish all room documents
+Meteor.publish("all-rooms", function () {
+ return Rooms.find(); // everything
+});
+
+// server: publish all messages for a given room
+Meteor.publish("messages", function (roomId) {
+ check(roomId, String);
+ return Messages.find({room: roomId});
+});
+
+// server: publish the set of parties the logged-in user can see.
+Meteor.publish("parties", function () {
+ return Parties.find({$or: [{"public": true},
+ {invited: this.userId},
+ {owner: this.userId}]});
+});
+Publish functions can provide different results to each client. In the last example, a logged in user can only see Party documents that are public, that the user owns, or that the user has been invited to.
+
+Once subscribed, the client uses its cache as a fast local database, dramatically simplifying client code. Reads never require a costly round trip to the server. And they're limited to the contents of the cache: a query for every document in a collection on a client will only return documents the server is publishing to that client.
+
+// client: start a parties subscription
+Meteor.subscribe("parties");
+
+// client: return array of Parties this client can read
+return Parties.find().fetch(); // synchronous!
+Sophisticated clients can turn subscriptions on and off to control how much data is kept in the cache and manage network traffic. When a subscription is turned off, all its documents are removed from the cache unless the same document is also provided by another active subscription.
+
+When the client changes one or more documents, it sends a message to the server requesting the change. The server checks the proposed change against a set of allow/deny rules you write as JavaScript functions. The server only accepts the change if all the rules pass.
+
+// server: don't allow client to insert a party
+Parties.allow({
+ insert: function (userId, party) {
+ return false;
+ }
+});
+
+// client: this will fail
+var party = { ... };
+Parties.insert(party);
+If the server accepts the change, it applies the change to the database and automatically propagates the change to other clients subscribed to the affected documents. If not, the update fails, the server's database remains untouched, and no other client sees the update.
+
+Meteor has a cute trick, though. When a client issues a write to the server, it also updates its local cache immediately, without waiting for the server's response. This means the screen will redraw right away. If the server accepted the update — what ought to happen most of the time in a properly behaving client — then the client got a jump on the change and didn't have to wait for the round trip to update its own screen. If the server rejects the change, Meteor patches up the client's cache with the server's result.
+
+Putting it all together, these techniques accomplish latency compensation. Clients hold a fresh copy of the data they need, and never need to wait for a roundtrip to the server. And when clients modify data, those modifications can run locally without waiting for the confirmation from the server, while still giving the server final say over the requested change.
+
+The current release of Meteor supports MongoDB, the popular document database, and the examples in this section use the MongoDB API. Future releases will include support for other databases.
+
+Authentication and user accounts
+--------------------------------
+
+Meteor includes Meteor Accounts, a state-of-the-art authentication system. It features secure password login using the bcrypt algorithm, and integration with external services including Facebook, GitHub, Google, Meetup, Twitter, and Weibo. Meteor Accounts defines a Meteor.users collection where developers can store application-specific user data.
+
+Meteor also includes pre-built forms for common tasks like login, signup, password change, and password reset emails. You can add Accounts UI to your app with just one line of code. The accounts-ui package even provides a configuration wizard that walks you through the steps to set up the external login services you're using in your app.
+
+Input validation
+----------------
+
+Meteor allows your methods and publish functions to take arguments of any JSON type. (In fact, Meteor's wire protocol supports EJSON, an extension of JSON which also supports other common types like dates and binary buffers.) JavaScript's dynamic typing means you don't need to declare precise types of every variable in your app, but it's usually helpful to ensure that the arguments that clients are passing to your methods and publish functions are of the type that you expect.
+
+Meteor provides a lightweight library for checking that arguments and other values are the type you expect them to be. Simply start your functions with statements like check(username, String) or check(office, {building: String, room: Number}). The check call will throw an error if its argument is of an unexpected type.
+
+Meteor also provides an easy way to make sure that all of your methods and publish functions validate all of their arguments. Just run meteor add audit-argument-checks and any method or publish function which skips checking any of its arguments will fail with an exception.
+
+Reactivity
+----------
+
+Meteor embraces the concept of reactive programming (https://en.wikipedia.org/wiki/Reactive_programming). This means that you can write your code in a simple imperative style, and the result will be automatically recalculated whenever data changes that your code depends on.
+
+Tracker.autorun(function () {
+ Meteor.subscribe("messages", Session.get("currentRoomId"));
+});
+This example (taken from a chat room client) sets up a data subscription based on the session variable currentRoomId. If the value of Session.get("currentRoomId") changes for any reason, the function will be automatically re-run, setting up a new subscription that replaces the old one.
+
+This automatic recomputation is achieved by a cooperation between Session and Tracker.autorun. Tracker.autorun performs an arbitrary "reactive computation" inside of which data dependencies are tracked, and it will re-run its function argument as necessary. Data providers like Session, on the other hand, make note of the computation they are called from and what data was requested, and they are prepared to send an invalidation signal to the computation when the data changes.
+
+This simple pattern (reactive computation + reactive data source) has wide applicability. Above, the programmer is saved from writing unsubscribe/resubscribe calls and making sure they are called at the right time. In general, Meteor can eliminate whole classes of data propagation code which would otherwise clog up your application with error-prone logic.
+
+These Meteor functions run your code as a reactive computation:
+
+Templates
+Tracker.autorun
+Template.autorun
+Blaze.render and Blaze.renderWithData
+And the reactive data sources that can trigger changes are:
+
+Session variables
+Database queries on Collections
+Meteor.status
+The ready() method on a subscription handle
+Meteor.user
+Meteor.userId
+Meteor.loggingIn
+In addition, the following functions which return an object with a stop method, if called from a reactive computation, are stopped when the computation is rerun or stopped:
+
+Tracker.autorun (nested)
+Meteor.subscribe
+observe() and observeChanges() on cursors
+Meteor's implementation is a package called Tracker that is fairly short and straightforward. You can use it yourself to implement new reactive data sources.
+
+Live HTML templates
+-------------------
+
+HTML templating is central to web applications. With Blaze, Meteor's live page update technology, you can render your HTML reactively, meaning that it will update automatically to track changes in the data used to generate it.
+
+Meteor makes it easy to use your favorite HTML templating language along with Meteor's live page update technology. Just write your template as you normally would, and Meteor will take care of making it update in realtime.
+
+Meteor ships with a templating language called Spacebars (https://github.com/meteor/meteor/blob/master/packages/spacebars/README.md), inspired by Handlebars (http://handlebarsjs.com/). It shares some of the spirit and syntax of Handlebars, but it has been tailored to produce reactive Meteor templates when compiled.
+
+Today, the only templating system that ships with Meteor is Spacebars, though our community has created packages for other languages such as Jade.
+
+To define templates, create a file in your project with the .html extension. In the file, make a <template> tag and give it a name attribute. Put the template contents inside the tag. Meteor will precompile the template, ship it down to the client, and make it available as on the global Template object.
+
+When your app is loaded, it automatically renders the special template called <body>, which is written using the <body> element instead of a <template>. You insert a template inside another template by using the {{> inclusion}} operator.
+
+The easiest way to get data into templates is by defining helper functions in JavaScript. Define helpers with the Template.templateName.helpers({ ... }) function. Putting it all together:
+
+<!-- in myapp.html -->
+<body>
+ <h1>Today's weather!</h1>
+ {{> forecast}}
+</body>
+
+<template name="forecast">
+ <div>It'll be {{prediction}} tonight</div>
+</template>
+// in client/myapp.js: reactive helper function
+Template.forecast.helpers({
+ prediction: function () {
+ return Session.get("weather");
+ }
+});
+// in the JavaScript console
+> Session.set("weather", "cloudy");
+> document.body.innerHTML
+ => "<h1>Today's weather!</h1> <div>It'll be cloudy tonight</div>"
+
+> Session.set("weather", "cool and dry");
+> document.body.innerHTML
+ => "<h1>Today's weather!</h1> <div>It'll be cool and dry tonight</div>"
+To iterate over an array or database cursor, use {{#each}}:
+
+<!-- in myapp.html -->
+<template name="players">
+ {{#each topScorers}}
+ <div>{{name}}</div>
+ {{/each}}
+</template>
+// in myapp.js
+Template.players.helpers({
+ topScorers: function () {
+ return Users.find({score: {$gt: 100}}, {sort: {score: -1}});
+ }
+});
+In this case, the data is coming from a database query. When the database cursor is passed to {{#each}}, it will wire up all of the machinery to efficiently add and move DOM nodes as new results enter the query.
+
+Helpers can take arguments, and they receive the current template context data in this. Note that some block helpers change the current context (notably {{#each}} and {{#with}}):
+
+// in a JavaScript file
+Template.players.helpers({
+ leagueIs: function (league) {
+ return this.league === league;
+ }
+});
+<!-- in a HTML file -->
+<template name="players">
+ {{#each topScorers}}
+ {{#if leagueIs "junior"}}
+ <div>Junior: {{name}}</div>
+ {{/if}}
+ {{#if leagueIs "senior"}}
+ <div>Senior: {{name}}</div>
+ {{/if}}
+ {{/each}}
+</template>
+Helpers can also be used to pass in constant data.
+
+// Works fine with {{#each sections}}
+Template.report.helpers({
+ sections: ["Situation", "Complication", "Resolution"]
+});
+Finally, you can use the events function on a template to attach event handlers. The object passed into events is documented at Event Maps. The this argument to the event handler will be the data context of the element that triggered the event.
+
+<!-- myapp.html -->
+<template name="scores">
+ {{#each player}}
+ {{> playerScore}}
+ {{/each}}
+</template>
+
+<template name="playerScore">
+ <div>{{name}}: {{score}}
+ <span class="give-points">Give points</span>
+ </div>
+</template>
+// myapp.js
+Template.playerScore.events({
+ 'click .give-points': function () {
+ Users.update(this._id, {$inc: {score: 2}});
+ }
+});
+For more details about Spacebars, read the Spacebars README. (https://github.com/meteor/meteor/blob/master/packages/spacebars/README.md)
+
+Using packages
+--------------
+
+All of the functionality you've read about so far is implemented in standard Meteor packages. This is possible thanks to Meteor's unusually powerful isomorphic package and build system. Isomorphic means the same packages work in the web browser, in mobile apps, and on the server. Packages can also contain plugins that extend the build process, such as coffeescript (CoffeeScript compilation : http://coffeescript.org/) or templating (compiling HTML templates).
+
+Anyone can publish a Meteor package, and thousands of community-written packages have been published to date. The easiest way to browse these packages is Atmosphere, by Percolate Studio. You can also use the meteor search and meteor show commands.
+
+You can add packages to your project with meteor add and remove them with meteor remove. Additionally, meteor list will tell you what packages your project is using, and meteor update will update them to the newest versions when possible.
+
+By default all apps include the meteor-base package. This pulls in the packages that make up the core of the Meteor stack. Most apps will have this package.
+
+All new apps also start with a set of packages that allow a friendly development experience. For more information about these packages, check out the comments in the packages file.
+
+Meteor uses a single-loading packaging system, meaning that it loads just one version of every package. Before adding or upgrading to a particular version of a package, Meteor uses a constraint solver to check if doing so will cause other packages to break. By default, Meteor will choose conservatively. When adding transitive dependencies (packages that other packages, but not the application itself) depend on, Meteor will try to choose the earlier version.
+
+In addition to the packages in the official Meteor release being used by your app, meteor list and meteor add also search the packages directory at the top of your app. You can also use the packages directory to break your app into subpackages for your convenience, or to test packages that you might want to publish. See Writing Packages (http://docs.meteor.com/#/full/writingpackages) . If you wish to add packages outside of your app's folder structure, set the environment variable PACKAGE_DIRS to a colon-delimited list of paths.
+
+Namespacing
+-----------
+
+Meteor's namespacing support makes it easy to write large applications in JavaScript. Each package that you use in your app exists in its own separate namespace, meaning that it sees only its own global variables and any variables provided by the packages that it specifically uses. Here's how it works.
+
+When you declare a top-level variable, you have a choice. You can make the variable File Scope or Package Scope.
+
+// File Scope. This variable will be visible only inside this
+// one file. Other files in this app or package won't see it.
+var alicePerson = {name: "alice"};
+
+// Package Scope. This variable is visible to every file inside
+// of this package or app. The difference is that 'var' is
+// omitted.
+bobPerson = {name: "bob"};
+Notice that this is just the normal JavaScript syntax for declaring a variable that is local or global. Meteor scans your source code for global variable assignments and generates a wrapper that makes sure that your globals don't escape their appropriate namespace.
+
+In addition to File Scope and Package Scope, there are also Exports. An export is a variable that a package makes available to you when you use it. For example, the email package exports the Email variable. If your app uses the email package (and only if it uses the email package!) then your app can see Email and you can call Email.send. Most packages have only one export, but some packages might have two or three (for example, a package that provides several classes that work together).
+
+You see only the exports of the packages that you use directly. If you use package A, and package A uses package B, then you only see package A's exports. Package B's exports don't "leak" into your namespace just because you used package A. This keeps each namespace nice and tidy. Each app or package only sees their own globals plus the APIs of the packages that they specifically asked for.
+
+When debugging your app, your browser's JavaScript console behaves as if it were attached to your app's namespace. You see your app's globals and the exports of the packages that your app uses directly. You don't see the variables from inside those packages, and you don't see the exports of your transitive dependencies (packages that aren't used directly by your app, but that are used by packages that are used by your app).
+
+If you want to look inside packages from inside your in-browser debugger, you've got two options:
+
+Set a breakpoint inside package code. While stopped on that breakpoint, the console will be in the package's namespace. You'll see the package's package-scope variables, imports, and also any file-scope variables for the file you're stopped in.
+
+If a package foo is included in your app, regardless of whether your app uses it directly, its exports are available in Package.foo. For example, if the email package is loaded, then you can access Package.email.Email.send even from namespaces that don't use the email package directly.
+
+When declaring functions, keep in mind that function x () {} is just shorthand for var x = function x () {} in JavaScript. Consider these examples:
+
+// This is the same as 'var x = function x () ...'. So x() is
+// file-scope and can be called only from within this one file.
+function x () { ... }
+
+// No 'var', so x() is package-scope and can be called from
+// any file inside this app or package.
+x = function () { ... }
+Technically speaking, globals in an app (as opposed to in a package) are actually true globals. They can't be captured in a scope that is private to the app code, because that would mean that they wouldn't be visible in the console during debugging! This means that app globals actually end up being visible in packages. That should never be a problem for properly written package code (since the app globals will still be properly shadowed by declarations in the packages). You certainly shouldn't depend on this quirk, and in the future Meteor may check for it and throw an error if you do.
+
+Deploying
+---------
+
+Meteor is a full application server. We include everything you need to deploy your application on the internet: you just provide the JavaScript, HTML, and CSS.
+
+Running on Meteor's infrastructure
+----------------------------------
+
+The easiest way to deploy your application is to use meteor
+deploy. We provide it because it's what, personally, we've always wanted: an easy way to take an app idea, flesh it out over a weekend, and put it out there for the world to use, with nothing getting in the way of creativity.
+
+meteor deploy myapp.meteor.com
+Your application is now available at myapp.meteor.com. If this is the first time deploying to this hostname, Meteor creates a fresh empty database for your application. If you want to deploy an update, Meteor will preserve the existing data and just refresh the code.
+
+You can also deploy to your own domain. Just set up the hostname you want to use as a CNAME to origin.meteor.com, then deploy to that name.
+
+meteor deploy www.myapp.com
+We provide this as a free service so you can try Meteor. It is also helpful for quickly putting up internal betas, demos, and so on. For more information, see meteor deploy.
+
+Running on your own infrastructure
+----------------------------------
+
+You can also run your application on your own infrastructure or any hosting provider that can run Node.js apps.
+
+To get started, run
+
+meteor build my_directory
+This command will generate a fully-contained Node.js application in the form of a tarball. To run this application, you need to provide Node.js 0.10 and a MongoDB server. (The current release of Meteor has been tested with Node 0.10.40.) You can then run the application by invoking node, specifying the HTTP port for the application to listen on, and the MongoDB endpoint.
+
+cd my_directory
+(cd programs/server && npm install)
+env PORT=3000 MONGO_URL=mongodb://localhost:27017/myapp node main.js
+Some packages might require other environment variables. For example, the email package requires a MAIL_URL environment variable.
+
+Writing packages
+----------------
+
+Writing Meteor packages is easy. To initialize a meteor package, run meteor create --package username:packagename, where username is your Meteor Developer username. This will create a package from scratch and prefill the directory with a package.js control file and some javascript. By default, Meteor will take the package name from the name of the directory that contains the package.js file. Don't forget to run meteor add [packagename], even if the package is internal to the app, in order to use it.
+
+Meteor promises repeatable builds for both packages and applications. This means that, if you built your package on a machine, then checked the code into a repository and checked it out elsewhere, you should get the same result. In your package directory, you will find an automatically generated .versions file. This file specifies the versions of all packages used to build your package and is part of the source. Check it into version control to ensure repeatable builds across machines.
+
+Sometimes, packages do not just stand on their own, but function in the context of an app (specifically, packages in the packages directory of an app). In that case, the app's context will take precedence. Rather than using the .versions file as a guide, we will build the package with the same dependencies as used by the app (we think that, in practice, it would be confusing to find your local packages built with different versions of things).
+
+Meteor uses extended semver versioning for its packages: that means that the version number has three parts separated by dots: major version, minor version and patch version (for example: 1.2.3) with an optional pre-release version. You can read more about it on semver.org. Additionally, because some meteor packages wrap external libraries, Meteor supports the convention of using _ to denote a wrap number.
+
+You can read more about package.js (http://docs.meteor.com/#/full/packagejs) files in the API section.
+
+A word on testing: since testing is an important part of the development process, there are two common ways to test a package:
+
+Integration tests (putting a package directly into an application, and writing tests against the application) is the most common way to test a package. After creating your package, add it to your app's /packages directory and run meteor add. This will add your package to your app as a local package. You can then test and run your app as usual. Meteor will detect and respond to changes to your local package, just as it does to your app files.
+
+Unit tests are run with the command meteor test-packages package-name. As described in the package.js section, you can use the package.js file to specify where your unit tests are located. If you have a repository that contains only the package source, you can test your package by specifying the path to the package directory (which must contain a slash), such as meteor test-packages ./.
+
+To publish a package, run meteor publish from the package directory. There are some extra restrictions on published packages: they must contain a version (Meteor packages are versioned using strict semver versioning) and their names must be prefixed with the username of the author and a colon, like so: iron:router. This namespacing allows for more descriptive and on-topic package names.
+
+
+
+
diff --git a/perl6.html.markdown b/perl6.html.markdown
index b5a25a41..d31955f0 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -37,11 +37,11 @@ my $str = 'String';
# double quotes allow for interpolation (which we'll see later):
my $str2 = "String";
-# variable names can contain but not end with simple quotes and dashes,
-# and can contain (and end with) underscores :
+# Variable names can contain but not end with simple quotes and dashes,
+# and can contain (and end with) underscores :
# my $weird'variable-name_ = 5; # works !
-my $bool = True; # `True` and `False` are Perl 6's boolean
+my $bool = True; # `True` and `False` are Perl 6's boolean values.
my $inverse = !$bool; # You can invert a bool with the prefix `!` operator
my $forced-bool = so $str; # And you can use the prefix `so` operator
# which turns its operand into a Bool
@@ -56,28 +56,32 @@ my @array = 1, 2, 3;
say @array[2]; # Array indices start at 0 -- This is the third element
-say "Interpolate an array using [] : @array[]";
-#=> Interpolate an array using [] : 1 2 3
+say "Interpolate all elements of an array using [] : @array[]";
+#=> Interpolate all elements of an array using [] : 1 2 3
@array[0] = -1; # Assign a new value to an array index
@array[0, 1] = 5, 6; # Assign multiple values
my @keys = 0, 2;
-@array[@keys] = @letters; # Assign using an array
+@array[@keys] = @letters; # Assignment using an array containing index values
say @array; #=> a 6 b
## * Hashes, or key-value Pairs.
-# Hashes are actually arrays of Pairs
-# (you can construct a Pair object using the syntax `Key => Value`),
-# except they get "flattened" (hash context), removing duplicated keys.
+# Hashes are pairs of keys and values.
+# You can construct a Pair object using the syntax `Key => Value`.
+# Hash tables are very fast for lookup, and are stored unordered.
+# Keep in mind that keys get "flattened" in hash context, and any duplicated
+# keys are deduplicated.
my %hash = 1 => 2,
3 => 4;
my %hash = foo => "bar", # keys get auto-quoted
"some other" => "value", # trailing commas are okay
;
-my %hash = <key1 value1 key2 value2>; # you can also create a hash
- # from an even-numbered array
-my %hash = key1 => 'value1', key2 => 'value2'; # same as this
+# Even though hashes are internally stored differently than arrays,
+# Perl 6 allows you to easily create a hash from an even numbered array:
+my %hash = <key1 value1 key2 value2>;
+
+my %hash = key1 => 'value1', key2 => 'value2'; # same result as above
# You can also use the "colon pair" syntax:
# (especially handy for named parameters that you'll see later)
@@ -92,7 +96,8 @@ say %hash{'key1'}; # You can use {} to get the value from a key
say %hash<key2>; # If it's a string, you can actually use <>
# (`{key1}` doesn't work, as Perl6 doesn't have barewords)
-## * Subs (subroutines, or functions in most other languages).
+## * Subs: subroutines or functions as most other languages call them are
+# created with the `sub` keyword.
sub say-hello { say "Hello, world" }
sub say-hello-to(Str $name) { # You can provide the type of an argument
@@ -193,6 +198,15 @@ sub mutate($n is rw) {
say "\$n is now $n !";
}
+my $m = 42;
+mutate $m; # $n is now 43 !
+
+# This works because we are passing the container $m to mutate. If we try
+# to just pass a number instead of passing a variable it won't work because
+# there is no container being passed and integers are immutable by themselves:
+
+mutate 42; # Parameter '$n' expected a writable container, but got Int value
+
# If what you want a copy instead, use `is copy`.
# A sub itself returns a container, which means it can be marked as rw:
@@ -228,10 +242,15 @@ unless False {
say "Quite truthy" if True;
# - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages)
-my $a = $condition ?? $value-if-true !! $value-if-false;
+# returns $value-if-true if the condition is true and $value-if-false
+# if it is false.
+# my $result = $value condition ?? $value-if-true !! $value-if-false;
-# - `given`-`when` looks like other languages' `switch`, but much more
-# powerful thanks to smart matching and thanks to Perl 6's "topic variable", $_.
+my $age = 30;
+say $age > 18 ?? "You are an adult" !! "You are under 18";
+
+# - `given`-`when` looks like other languages' `switch`, but is much more
+# powerful thanks to smart matching and Perl 6's "topic variable", $_.
#
# This variable contains the default argument of a block,
# a loop's current iteration (unless explicitly named), etc.
@@ -242,6 +261,7 @@ my $a = $condition ?? $value-if-true !! $value-if-false;
# Since other Perl 6 constructs use this variable (as said before, like `for`,
# blocks, etc), this means the powerful `when` is not only applicable along with
# a `given`, but instead anywhere a `$_` exists.
+
given "foo bar" {
say $_; #=> foo bar
when /foo/ { # Don't worry about smart matching yet – just know `when` uses it.
@@ -336,16 +356,37 @@ if long-computation() -> $result {
# - `eqv` is canonical equivalence (or "deep equality")
(1, 2) eqv (1, 3);
-# - `~~` is smart matching
+# - Smart Match Operator: `~~`
+# Aliases the left hand side to $_ and then evaluates the right hand side.
+# Here are some common comparison semantics:
+
+# String or Numeric Equality
+
+'Foo' ~~ 'Foo'; # True if strings are equal.
+12.5 ~~ 12.50; # True if numbers are equal.
+
+# Regex - For matching a regular expression against the left side.
+# Returns a (Match) object, which evaluates as True if regexp matches.
+
+my $obj = 'abc' ~~ /a/;
+say $obj; # 「a」
+say $obj.WHAT; # (Match)
+
+# Hashes
+'key' ~~ %hash; # True if key exists in hash
+
+# Type - Checks if left side "has type" (can check superclasses and roles)
+
+1 ~~ Int; # True
+
+# Smart-matching against a boolean always returns that boolean (and will warn).
+
+1 ~~ True; # True
+False ~~ True; # True
+
+# # General syntax is $arg ~~ &bool-returning-function;
# For a complete list of combinations, use this table:
# http://perlcabal.org/syn/S03.html#Smart_matching
-'a' ~~ /a/; # true if matches regexp
-'key' ~~ %hash; # true if key exists in hash
-$arg ~~ &bool-returning-function; # `True` if the function, passed `$arg`
- # as an argument, returns `True`.
-1 ~~ Int; # "has type" (check superclasses and roles)
-1 ~~ True; # smart-matching against a boolean always returns that boolean
- # (and will warn).
# You also, of course, have `<`, `<=`, `>`, `>=`.
# Their string equivalent are also avaiable : `lt`, `le`, `gt`, `ge`.
@@ -386,18 +427,22 @@ my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99;
say @numbers; #=> 0 1 2 3 4 3 9 15 21 [...] 81 87
# (only 20 values)
-## * And, Or
+## * And &&, Or ||
3 && 4; # 4, which is Truthy. Calls `.Bool` on `4` and gets `True`.
0 || False; # False. Calls `.Bool` on `0`
## * Short-circuit (and tight) versions of the above
-$a && $b && $c; # Returns the first argument that evaluates to False,
- # or the last argument.
-$a || $b;
+# Returns the first argument that evaluates to False, or the last argument.
+
+my ( $a, $b, $c ) = 1, 0, 2;
+$a && $b && $c; # Returns 0, the first False value
+
+# || Returns the first argument that evaluates to True
+$b || $a; # 1
# And because you're going to want them,
# you also have compound assignment operators:
-$a *= 2; # multiply and assignment
+$a *= 2; # multiply and assignment. Equivalent to $a = $a * 2;
$b %%= 5; # divisible by and assignment
@array .= sort; # calls the `sort` method and assigns the result back
@@ -408,19 +453,19 @@ $b %%= 5; # divisible by and assignment
## Unpacking !
# It's the ability to "extract" arrays and keys (AKA "destructuring").
# It'll work in `my`s and in parameter lists.
-my ($a, $b) = 1, 2;
-say $a; #=> 1
-my ($, $, $c) = 1, 2, 3; # keep the non-interesting anonymous
-say $c; #=> 3
+my ($f, $g) = 1, 2;
+say $f; #=> 1
+my ($, $, $h) = 1, 2, 3; # keep the non-interesting anonymous
+say $h; #=> 3
my ($head, *@tail) = 1, 2, 3; # Yes, it's the same as with "slurpy subs"
my (*@small) = 1;
-sub foo(@array [$fst, $snd]) {
+sub unpack_array(@array [$fst, $snd]) {
say "My first is $fst, my second is $snd ! All in all, I'm @array[].";
# (^ remember the `[]` to interpolate the array)
}
-foo(@tail); #=> My first is 2, my second is 3 ! All in all, I'm 2 3
+unpack_array(@tail); #=> My first is 2, my second is 3 ! All in all, I'm 2 3
# If you're not using the array itself, you can also keep it anonymous,
@@ -579,66 +624,95 @@ multi with-or-without-you {
### Scoping
-# In Perl 6, contrarily to many scripting languages (like Python, Ruby, PHP),
-# you are to declare your variables before using them. You know `my`.
-# (there are other declarators, `our`, `state`, ..., which we'll see later).
+# In Perl 6, unlike many scripting languages, (such as Python, Ruby, PHP),
+# you must declare your variables before using them. The `my` declarator
+# you have learned uses "lexical scoping". There are a few other declarators,
+# (`our`, `state`, ..., ) which we'll see later.
# This is called "lexical scoping", where in inner blocks,
# you can access variables from outer blocks.
-my $foo = 'Foo';
-sub foo {
- my $bar = 'Bar';
- sub bar {
- say "$foo $bar";
+my $file_scoped = 'Foo';
+sub outer {
+ my $outer_scoped = 'Bar';
+ sub inner {
+ say "$file_scoped $outer_scoped";
}
- &bar; # return the function
+ &inner; # return the function
}
-foo()(); #=> 'Foo Bar'
+outer()(); #=> 'Foo Bar'
-# As you can see, `$foo` and `$bar` were captured.
+# As you can see, `$file_scoped` and `$outer_scoped` were captured.
# But if we were to try and use `$bar` outside of `foo`,
# the variable would be undefined (and you'd get a compile time error).
-# Perl 6 has another kind of scope : dynamic scope.
-# They use the twigil (composed sigil) `*` to mark dynamically-scoped variables:
-my $*a = 1;
-# Dyamically-scoped variables depend on the current call stack,
-# instead of the current block depth.
-sub foo {
- my $*foo = 1;
- bar(); # call `bar` in-place
+### Twigils
+
+# There are many special `twigils` (composed sigil's) in Perl 6.
+# Twigils define the variables' scope.
+# The * and ? twigils work on standard variables:
+# * Dynamic variable
+# ? Compile-time variable
+# The ! and the . twigils are used with Perl 6's objects:
+# ! Attribute (class member)
+# . Method (not really a variable)
+
+# `*` Twigil: Dynamic Scope
+# These variables use the`*` twigil to mark dynamically-scoped variables.
+# Dynamically-scoped variables are looked up through the caller, not through
+# the outer scope
+
+my $*dyn_scoped_1 = 1;
+my $*dyn_scoped_2 = 10;
+
+sub say_dyn {
+ say "$*dyn_scoped_1 $*dyn_scoped_2";
}
-sub bar {
- say $*foo; # `$*foo` will be looked in the call stack, and find `foo`'s,
- # even though the blocks aren't nested (they're call-nested).
- #=> 1
+
+sub call_say_dyn {
+ my $*dyn_scoped_1 = 25; # Defines $*dyn_scoped_1 only for this sub.
+ $*dyn_scoped_2 = 100; # Will change the value of the file scoped variable.
+ say_dyn(); #=> 25 100 $*dyn_scoped 1 and 2 will be looked for in the call.
+ # It uses he value of $*dyn_scoped_1 from inside this sub's lexical
+ # scope even though the blocks aren't nested (they're call-nested).
}
+say_dyn(); #=> 1 10
+call_say_dyn(); #=> 25 100
+ # Uses $*dyn_scoped_1 as defined in call_say_dyn even though
+ # we are calling it from outside.
+say_dyn(); #=> 1 100 We changed the value of $*dyn_scoped_2 in call_say_dyn
+ # so now its value has changed.
### Object Model
-# You declare a class with the keyword `class`, fields with `has`,
-# methods with `method`. Every attribute that is private is named `$!attr`.
-# Immutable public attributes are named `$.attr`
+# To call a method on an object, add a dot followed by the method name:
+# => $object.method
+# Classes are declared with the `class` keyword. Attributes are declared
+# with the `has` keyword, and methods declared with `method`.
+# Every attribute that is private uses the ! twigil for example: `$!attr`.
+# Immutable public attributes use the `.` twigil.
# (you can make them mutable with `is rw`)
+# The easiest way to remember the `$.` twigil is comparing it to how methods
+# are called.
# Perl 6's object model ("SixModel") is very flexible,
# and allows you to dynamically add methods, change semantics, etc ...
-# (this will not be covered here, and you should refer to the Synopsis).
+# (these will not all be covered here, and you should refer to:
+# https://docs.perl6.org/language/objects.html.
-class A {
- has $.field; # `$.field` is immutable.
- # From inside the class, use `$!field` to modify it.
- has $.other-field is rw; # You can mark a public attribute `rw`.
- has Int $!private-field = 10;
+class Attrib-Class {
+ has $.attrib; # `$.attrib` is immutable.
+ # From inside the class, use `$!attrib` to modify it.
+ has $.other-attrib is rw; # You can mark a public attribute `rw`.
+ has Int $!private-attrib = 10;
method get-value {
- $.field + $!private-field;
+ $.attrib + $!private-attrib;
}
- method set-value($n) {
- # $.field = $n; # As stated before, you can't use the `$.` immutable version.
- $!field = $n; # This works, because `$!` is always mutable.
+ method set-value($param) { # Methods can take parameters
+ $!attrib = $param; # This works, because `$!` is always mutable.
+ # $.attrib = $param; # Wrong: You can't use the `$.` immutable version.
- $.other-field = 5; # This works, because `$.other-field` is `rw`.
+ $.other-attrib = 5; # This works, because `$.other-attrib` is `rw`.
}
method !private-method {
@@ -646,33 +720,44 @@ class A {
}
};
-# Create a new instance of A with $.field set to 5 :
-# Note: you can't set private-field from here (more later on).
-my $a = A.new(field => 5);
-$a.get-value; #=> 15
-#$a.field = 5; # This fails, because the `has $.field` is immutable
-$a.other-field = 10; # This, however, works, because the public field
- # is mutable (`rw`).
-
-## Perl 6 also has inheritance (along with multiple inheritance)
-
-class A {
- has $.val;
-
- submethod not-inherited {
- say "This method won't be available on B.";
- say "This is most useful for BUILD, which we'll see later";
+# Create a new instance of Attrib-Class with $.attrib set to 5 :
+# Note: you can't set private-attribute from here (more later on).
+my $class-obj = Attrib-Class.new(attrib => 5);
+say $class-obj.get-value; #=> 15
+#$class-obj.attrib = 5; # This fails, because the `has $.attrib` is immutable
+$class-obj.other-attrib = 10; # This, however, works, because the public
+ # attribute is mutable (`rw`).
+
+## Object Inheritance
+# Perl 6 also has inheritance (along with multiple inheritance)
+# While `method`'s are inherited, `submethod`'s are not.
+# Submethods are useful for object construction and destruction tasks,
+# such as BUILD, or methods that must be overriden by subtypes.
+# We will learn about BUILD later on.
+
+class Parent {
+ has $.age;
+ has $.name;
+ # This submethod won't be inherited by Child.
+ submethod favorite-color {
+ say "My favorite color is Blue";
}
-
- method bar { $.val * 5 }
+ # This method is inherited
+ method talk { say "Hi, my name is $!name" }
}
-class B is A { # inheritance uses `is`
- method foo {
- say $.val;
- }
-
- method bar { $.val * 10 } # this shadows A's `bar`
+# Inheritance uses the `is` keyword
+class Child is Parent {
+ method talk { say "Goo goo ga ga" }
+ # This shadows Parent's `talk` method, This child hasn't learned to speak yet!
}
+my Parent $Richard .= new(age => 40, name => 'Richard');
+$Richard.favorite-color; #=> "My favorite color is Blue"
+$Richard.talk; #=> "Hi, my name is Richard"
+# # $Richard is able to access the submethod, he knows how to say his name.
+
+my Child $Madison .= new(age => 1, name => 'Madison');
+$Madison.talk; # prints "Goo goo ga ga" due to the overrided method.
+# $Madison.favorite-color does not work since it is not inherited
# When you use `my T $var`, `$var` starts off with `T` itself in it,
# so you can call `new` on it.
@@ -680,11 +765,7 @@ class B is A { # inheritance uses `is`
# `$a .= b` is the same as `$a = $a.b`)
# Also note that `BUILD` (the method called inside `new`)
# will set parent properties too, so you can pass `val => 5`.
-my B $b .= new(val => 5);
-# $b.not-inherited; # This won't work, for reasons explained above
-$b.foo; # prints 5
-$b.bar; #=> 50, since it calls B's `bar`
## Roles are supported too (also called Mixins in other languages)
role PrintableVal {
@@ -699,8 +780,8 @@ class Item does PrintableVal {
has $.val;
# When `does`-ed, a `role` literally "mixes in" the class:
- # the methods and fields are put together, which means a class can access
- # the private fields/methods of its roles (but not the inverse !):
+ # the methods and attributes are put together, which means a class can access
+ # the private attributes/methods of its roles (but not the inverse !):
method access {
say $!counter++;
}
@@ -717,34 +798,48 @@ class Item does PrintableVal {
### Exceptions
# Exceptions are built on top of classes, in the package `X` (like `X::IO`).
-# Unlike many other languages, in Perl 6, you put the `CATCH` block *within* the
-# block to `try`. By default, a `try` has a `CATCH` block that catches
-# any exception (`CATCH { default {} }`).
+# You can access the last exception with the special variable `$!`
+# (use `$_` in a `CATCH` block) Note: This has no relation to $!variables.
+
+# You can throw an exception using `die`:
+open 'foo' or die 'Error!'; #=> Error!
+# Or more explicitly:
+die X::AdHoc.new(payload => 'Error!');
+
+## Using `try` and `CATCH`
+# By using `try` and `CATCH` you can contain and handle exceptions without
+# disrupting the rest of the program.
+# Unlike many other languages, in Perl 6, you put the `CATCH` block *within*
+# the block to `try`. By default, a `try` has a `CATCH` block that catches
+# any exception (`CATCH { default {} }`).
+
+try { my $a = (0 %% 0); CATCH { say "Something happened: $_" } }
+ #=> Something happened: Attempt to divide by zero using infix:<%%>
+
# You can redefine it using `when`s (and `default`)
-# to handle the exceptions you want:
+# to handle the exceptions you want:
try {
open 'foo';
- CATCH {
- when X::AdHoc { say "unable to open file !" }
+ CATCH { # In the `CATCH` block, the exception is set to $_
+ when X::AdHoc { say "Error: $_" }
+ #=>Error: Failed to open file /dir/foo: no such file or directory
+
# Any other exception will be re-raised, since we don't have a `default`
- # Basically, if a `when` matches (or there's a `default`) marks the exception as
- # "handled" so that it doesn't get re-thrown from the `CATCH`.
+ # Basically, if a `when` matches (or there's a `default`) marks the
+ # exception as
+ # "handled" so that it doesn't get re-thrown from the `CATCH`.
# You still can re-throw the exception (see below) by hand.
}
}
-# You can throw an exception using `die`:
-die X::AdHoc.new(payload => 'Error !');
-
-# You can access the last exception with `$!` (use `$_` in a `CATCH` block)
-
-# There are also some subtelties to exceptions. Some Perl 6 subs return a `Failure`,
-# which is a kind of "unthrown exception". They're not thrown until you tried to look
-# at their content, unless you call `.Bool`/`.defined` on them - then they're handled.
-# (the `.handled` method is `rw`, so you can mark it as `False` back yourself)
+# There are also some subtleties to exceptions. Some Perl 6 subs return a
+# `Failure`, which is a kind of "unthrown exception". They're not thrown until
+# you tried to look at their content, unless you call `.Bool`/`.defined` on
+# them - then they're handled.
+# (the `.handled` method is `rw`, so you can mark it as `False` back yourself)
#
-# You can throw a `Failure` using `fail`. Note that if the pragma `use fatal` is on,
-# `fail` will throw an exception (like `die`).
+# You can throw a `Failure` using `fail`. Note that if the pragma `use fatal`
+# is on, `fail` will throw an exception (like `die`).
fail "foo"; # We're not trying to access the value, so no problem.
try {
fail "foo";
@@ -764,22 +859,26 @@ try {
# and `enum`) are actually packages. (Packages are the lowest common denominator)
# Packages are important - especially as Perl is well-known for CPAN,
# the Comprehensive Perl Archive Network.
-# You're not supposed to use the package keyword, usually:
-# you use `class Package::Name::Here;` to declare a class,
-# or if you only want to export variables/subs, you can use `module`:
+
+# You can use a module (bring its declarations into scope) with `use`
+use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module
+say from-json('[1]').perl; #=> [1]
+
+# Declare your own packages like this:
+# `class Package::Name::Here;` to declare a class, or if you only want to
+# export variables/subs, you can use `module`. If you're coming from Perl 5
+# please note you're not usually supposed to use the `package` keyword.
+
module Hello::World { # Bracketed form
# If `Hello` doesn't exist yet, it'll just be a "stub",
# that can be redeclared as something else later.
# ... declarations here ...
}
unit module Parse::Text; # file-scoped form
+
grammar Parse::Text::Grammar { # A grammar is a package, which you could `use`
}
-# You can use a module (bring its declarations into scope) with `use`
-use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module
-say from-json('[1]').perl; #=> [1]
-
# As said before, any part of the six model is also a package.
# Since `JSON::Tiny` uses (its own) `JSON::Tiny::Actions` class, you can use it:
my $actions = JSON::Tiny::Actions.new;
@@ -1088,10 +1187,11 @@ sub add($a, $b) { $a + $b }
say [[&add]] 1, 2, 3; #=> 6
## * Zip meta-operator
-# This one is an infix meta-operator than also can be used as a "normal" operator.
-# It takes an optional binary function (by default, it just creates a pair),
-# and will pop one value off of each array and call its binary function on these
-# until it runs out of elements. It returns an array with all of these new elements.
+# This one is an infix meta-operator than also can be used as a "normal"
+# operator. It takes an optional binary function (by default, it just creates
+# a pair), and will pop one value off of each array and call its binary function
+# on these until it runs out of elements. It returns an array with all of these
+# new elements.
(1, 2) Z (3, 4); # ((1, 3), (2, 4)), since by default, the function makes an array
1..3 Z+ 4..6; # (5, 7, 9), using the custom infix:<+> function
@@ -1165,7 +1265,8 @@ say so 'a' ~~ / a /; # More readable with some spaces!
# returning a `Match` object. They know how to respond to list indexing,
# hash indexing, and return the matched string.
# The results of the match are available as `$/` (implicitly lexically-scoped).
-# You can also use the capture variables (`$0`, `$1`, ... starting at 0, not 1 !).
+# You can also use the capture variables which start at 0:
+# `$0`, `$1', `$2`...
#
# You can also note that `~~` does not perform start/end checking
# (meaning the regexp can be matched with just one char of the string),
diff --git a/pl-pl/ruby-pl.html.markdown b/pl-pl/ruby-pl.html.markdown
index 73b1a7d8..7ab47847 100644
--- a/pl-pl/ruby-pl.html.markdown
+++ b/pl-pl/ruby-pl.html.markdown
@@ -1,6 +1,6 @@
---
language: ruby
-filename: learnruby.rb
+filename: learnruby-pl.rb
contributors:
- ["David Underwood", "http://theflyingdeveloper.com"]
- ["Joel Walden", "http://joelwalden.net"]
diff --git a/pt-br/amd.html.markdown b/pt-br/amd.html.markdown
index 690fc8da..38c1f70f 100644
--- a/pt-br/amd.html.markdown
+++ b/pt-br/amd.html.markdown
@@ -5,7 +5,7 @@ contributors:
- ["Frederik Ring", "https://github.com/m90"]
translators:
- ["Felipe Tarijon", "http://nanoincub.com/"]
-lang: ptr-br
+lang: pt-br
filename: learnamd-pt.js
---
diff --git a/pt-br/binary-search-pt.html.markdown b/pt-br/binary-search-pt.html.markdown
new file mode 100644
index 00000000..d3060506
--- /dev/null
+++ b/pt-br/binary-search-pt.html.markdown
@@ -0,0 +1,77 @@
+---
+category: Algorithms & Data Structures
+name: Binary Search
+contributors:
+ - ["Abhishek Jaisingh", "http://github.com/abhishekjiitr"]
+translators:
+ - ["Claudson Martins", "https://github.com/claudsonm"]
+lang: pt-br
+---
+
+# Busca Binária
+
+## Por Que Busca Binária?
+
+Operações de busca são um dos principais problemas na Ciência da Computação.
+Atualmente existem mais de 1 trilhão de buscas por ano, e nós precisamos de
+algoritmos que possam realizá-las rapidamente. Busca binária é um dos algoritmos
+fundamentais em ciência da computação. A fim de explorá-la, iremos primeiro
+construir um conhecimento teórico, e então utilizá-lo para implementar o
+algoritmo apropriadamente.
+
+## Introdução
+
+Uma abordagem simples para implementar uma busca é realizar uma busca linear,
+mas algoritmos nessa abordagem levam muito tempo, o qual cresce linearmente de
+acordo com a quantidade ou número de dados. Por exemplo, iniciando do elemento
+mais a esquerda de arr[] e um a um comparar x com cada elemento de arr[], se x
+coincide com um elemento, retornar seu índice. Se x não coincide com nenhum dos
+elementos, retornar -1.
+
+```
+Busca Linear: O (n) Tempo Linear
+
+Busca Binária: O ( log(n) ) Tempo Logarítmico
+
+```
+```
+def busca(arr, x):
+
+ for i in range(len(arr)):
+
+ if arr[i] == x:
+ return i
+
+ return -1
+
+```
+## Algoritmo de Busca Binária
+
+O pré-requisito básico para que uma busca binária funcione é que os dados que se
+desejam buscar devem estar ordenados (em qualquer ordem).
+
+### Pseudocódigo
+
+```
+A ideia da busca binária é usar a informação de que o array está ordenado e
+reduzir a complexidade de tempo para O(Log n). Nós basicamente ignoramos metade
+dos elementos após uma comparação.
+
+1) Compare x com o elemento do meio.
+2) Se x coincide com o elemento do meio, retorne o índice do meio.
+3) Senão Se x é maior que o elemento do meio, então x só pode estar no lado
+direito do elemento do meio. Portanto nós pulamos para a metade direita.
+4) Senão (x é menor) pulamos para a metade esquerda.
+
+Essa é a ideia da implementação recursiva da busca binária.
+
+```
+
+### Considerações Finais
+
+Existem outras formas de busca binária que são muito úteis.
+
+## Recursos Online
+
+* [GeeksforGeeks](http://www.geeksforgeeks.org/the-ubiquitous-binary-search-set-1/)
+* [Topcoder Tutorial](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/)
diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown
index 2c274f12..0af553c8 100644
--- a/pt-br/c-pt.html.markdown
+++ b/pt-br/c-pt.html.markdown
@@ -28,7 +28,7 @@ Funcionam no C89 também.
*/
// Constantes: #define <palavra-chave>
-#definie DAY_IN_YEAR 365
+#define DAY_IN_YEAR 365
//enumerações também são modos de definir constantes.
enum day {DOM = 1, SEG, TER, QUA, QUI, SEX, SAB};
diff --git a/pt-br/clojure-macros-pt.html.markdown b/pt-br/clojure-macros-pt.html.markdown
index dbc0c25c..d56840e0 100644
--- a/pt-br/clojure-macros-pt.html.markdown
+++ b/pt-br/clojure-macros-pt.html.markdown
@@ -142,6 +142,8 @@ Você vai querer estar familiarizado com Clojure. Certifique-se de entender tudo
(inline-2 (1 + (3 / 2) - (1 / 2) + 1))
; -> 3 (Na verdade, 3N, desde que o numero ficou convertido em uma fração racional com /
+```
+
### Leitura adicional
Escrevendo Macros de [Clojure para o Brave e True](http://www.braveclojure.com/)
diff --git a/pt-br/dynamic-programming-pt.html.markdown b/pt-br/dynamic-programming-pt.html.markdown
new file mode 100644
index 00000000..8de9bee6
--- /dev/null
+++ b/pt-br/dynamic-programming-pt.html.markdown
@@ -0,0 +1,76 @@
+---
+category: Algorithms & Data Structures
+name: Dynamic Programming
+contributors:
+ - ["Akashdeep Goel", "http://github.com/akashdeepgoel"]
+translators:
+ - ["Claudson Martins", "https://github.com/claudsonm"]
+lang: pt-br
+---
+
+# Programação Dinâmica
+
+## Introdução
+
+Programação Dinâmica é uma técnica poderosa utilizada para resolver uma classe
+particular de problemas como veremos. A ideia é bastante simples, se você
+solucionou um problema com uma dada entrada, então salve o resultado para
+referência futura, e também para evitar resolver o mesmo problema novamente.
+
+Sempre se lembre!!
+"Aqueles que não conseguem lembrar o passado estão condenados a repeti-lo"
+
+## Maneiras de Solucionar tais Problemas
+
+1. Top-Down (De cima para baixo): Começe solucionando o problema quebrando-o em
+partes. Se você perceber que o problema já foi resolvido, então simplemente
+pegue a resposta salva. Se ainda não foi resolvido, solucione-o e salve a
+resposta. Isso é geralmente fácil de pensar e muito intuitivo. É geralmente
+referenciado como Memorização.
+
+2. Bottom-Up (De baixo para cima): Analise o problema e veja a ordem em que os
+subproblemas são resolvidos e começe a solucionar dos problemas mais triviais,
+até o problema dado. Neste processo, é garantido que os subproblemas são
+resolvidos antes de resoler o problema. Isto é referenciado como Programação Dinâmica.
+
+## Exemplo de Programação Dinâmica
+
+O problema da subsequência crescente máxima consiste em encontrar a maior
+subsequência crescente de uma dada sequência. Dada uma sequência
+S= {a1 , a2 , a3, a4, ... , an-1, an} nós temos que encontrar o maior subconjunto
+de forma que para todo j e i, j < i no subconjunto aj < ai. Antes de mais nada
+nós temos que encontrar o valor das maiores subsequências (LSi) para cada índice
+i com o último elemento da sequência sendo ai. Então a maior LSi será a maior
+subsequência na sequência dada. Para começar LSi é atribuído a um pois ai é
+elemento da sequência (último elemento). Então para todo j tal que j < i e aj <
+ai, nós procuramos o maior LSj e o adicionamos a LSi. Portanto o algoritmo tem
+complexidade de tempo O(n2). O pseudocódigo para procurar o comprimento da
+subsequência crescente máxima: A complexidade desse algoritmo poderia ser
+reduzida utilizando uma estrutura de dados melhor que um array. Armazenando o
+array antecedente e uma variável como maiorSequenciasAteAgora e seu índice
+ajudariam a poupar muito tempo.
+Um conceito similar poderia ser aplicado ao procurar o maior caminho em um
+grafo acíclico dirigido.
+---------------------------------------------------------------------------
+```
+ for i=0 to n-1
+ LS[i]=1
+ for j=0 to i-1
+ if (a[i] > a[j] and LS[i]<LS[j])
+ LS[i] = LS[j]+1
+ for i=0 to n-1
+ if (largest < LS[i])
+```
+
+### Alguns Problemas Famosos de Programação Dinâmica
+```
+Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code
+
+Integer Knapsack Problem - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem
+
+Longest Common Subsequence - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence
+```
+
+## Recursos Online (EN)
+
+* [codechef](https://www.codechef.com/wiki/tutorial-dynamic-programming)
diff --git a/pt-br/elixir.html.markdown b/pt-br/elixir.html.markdown
index b4ca8a52..f8c56101 100644
--- a/pt-br/elixir.html.markdown
+++ b/pt-br/elixir.html.markdown
@@ -5,6 +5,7 @@ contributors:
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
translators:
- ["Rodrigo Muniz", "http://github.com/muniz95"]
+lang: pt-br
filename: learnelixir-pt.ex
---
diff --git a/pt-br/elm-pt.html.markdown b/pt-br/elm-pt.html.markdown
new file mode 100644
index 00000000..78a4f1b7
--- /dev/null
+++ b/pt-br/elm-pt.html.markdown
@@ -0,0 +1,384 @@
+---
+language: Elm
+contributors:
+ - ["Max Goldstein", "http://maxgoldste.in/"]
+translators:
+ - ["Marcel dos Santos", "https://twitter.com/marcelgsantos"]
+lang: pt-br
+filename: learnelm-pt.elm
+---
+
+Elm é uma linguagem de programação funcional reativa que compila para (client-side)
+JavaScript. Elm é estaticamente tipada, significando que o compilador captura a
+maioria dos erros imediatamente e fornece uma mensagem de erro limpa e compreensível.
+Elm é excelente para projetar interfaces de usuário e jogos para a web.
+
+
+```haskell
+-- Comentários de uma linha começam com dois traços.
+{- Comentários de múltiplas linhas podem ser delimitados em um bloco como este.
+{- Eles podem ser aninhados. -}
+-}
+
+{-- O Básico --}
+
+-- Operações Aritméticas
+1 + 1 -- 2
+8 - 1 -- 7
+10 * 2 -- 20
+
+-- Cada número literal sem um ponto decimal pode ser um Int ou um Float.
+33 / 2 -- 16.5 com divisão de ponto flutuante
+33 // 2 -- 16 com divisão inteira
+
+-- Exponenciação
+5 ^ 2 -- 25
+
+-- Booleanos
+not True -- False
+not False -- True
+1 == 1 -- True
+1 /= 1 -- False
+1 < 10 -- True
+
+-- Strings e caracteres
+"Esta é uma string porque ela utiliza aspas duplas."
+'a' -- caracteres entre aspas simples
+
+-- Strings podem ser anexadas.
+"Olá " ++ "mundo!" -- "Olá mundo!"
+
+{-- Listas, Tuplas e Registros --}
+
+-- Cada elemento em uma lista deve ter o mesmo tipo.
+["the", "quick", "brown", "fox"]
+[1, 2, 3, 4, 5]
+-- O segundo exemplo também pode ser escrito com dois pontos.
+[1..5]
+
+-- Junte listas da mesma forma que strings.
+[1..5] ++ [6..10] == [1..10] -- True
+
+-- Para adicionar um item utilize "cons".
+0 :: [1..5] -- [0, 1, 2, 3, 4, 5]
+
+-- A cabeça e a cauda de uma lista são retornadas como uma Maybe. Em vez de
+-- verificar cada valor para ver se ele é nulo, você lida com os valores
+-- faltantes explicitamente.
+List.head [1..5] -- Just 1
+List.tail [1..5] -- Just [2, 3, 4, 5]
+List.head [] -- Nothing
+-- List.functionName siginifica que a função faz parte do módulo List.
+
+-- Cada elemento em uma tupla pode ser de um tipo diferente, mas uma tupla
+-- tem um comprimento fixo.
+("elm", 42)
+
+-- Acesse os elementos de um par com as funções first e second.
+-- (Este é um atalho; nós iremos para o "caminho real" em breve.)
+fst ("elm", 42) -- "elm"
+snd ("elm", 42) -- 42
+
+-- Uma tupla vazia ou "unidade" às vezes é utilizada como um placeholder.
+-- É o único valor de seu tipo, também chamado de "Unit".
+()
+
+-- Registros são como tuplas mas os campos possuem nomes. A ordem dos campos
+-- não importa. Observe que os valores dos registros utilizam sinais de igual,
+-- e não dois-pontos.
+{ x = 3, y = 7 }
+
+-- Acesse um campo com um ponto e o nome do campo.
+{ x = 3, y = 7 }.x -- 3
+
+-- Ou com uma função acessora, que é um ponto e o nome do próprio campo.
+.y { x = 3, y = 7 } -- 7
+
+-- Atualiza os campos de um registro. (Ele já deve ter os campos.)
+{ person |
+ name = "George" }
+
+-- Atualiza vários campos de uma só vez utilizando os valores atuais.
+{ particle |
+ position = particle.position + particle.velocity,
+ velocity = particle.velocity + particle.acceleration }
+
+{-- Fluxo de Controle --}
+
+-- Declarações if sempre devem ter um else e os valores devem ser do mesmo tipo.
+if powerLevel > 9000 then
+ "WHOA!"
+else
+ "meh"
+
+-- Declarações if podem ser encadeadas.
+if n < 0 then
+ "n é negativo"
+else if n > 0 then
+ "n é positivo"
+else
+ "n é zero"
+
+-- Utilize declarações case para casar padrões entre diferentes possibilidades.
+case aList of
+ [] -> "casa com uma lista vazia"
+ [x]-> "casa com uma lista de exatamente um item, " ++ toString x
+ x::xs -> "casa com uma lista de pelo menos um item cuja cabeça é " ++ toString x
+-- O casamento do padrão acontece na ordem. Se colocarmos [x] por último, ele
+-- nunca iria casar porque x::xs também casa (xs seria a lista vazia). Os
+-- casamentos não "falham".
+-- O compilador irá alertá-lo sobre casos faltantes ou extras.
+
+-- Casa padrão com um Maybe.
+case List.head aList of
+ Just x -> "A cabeça é " ++ toString x
+ Nothing -> "A lista estava vazia."
+
+{-- Funções --}
+
+-- A sintaxe do Elm é muito mínima, baseando-se principalmente em espaços em
+-- branco em vez de parênteses e chaves. Não existe a palavra-chave "return".
+
+-- Define uma função com seu nome, argumentos, um sinal de igual e o corpo.
+multiply a b =
+ a * b
+
+-- Aplica (chama) uma função passando seus argumentos (vírgulas não necessárias).
+multiply 7 6 -- 42
+
+-- Aplica parcialmente uma função passando somente alguns de seus argumentos.
+-- Dando, em seguida, um novo nome a função.
+double =
+ multiply 2
+
+-- Constantes são semelhantes, exceto que não há argumentos.
+answer =
+ 42
+
+-- Passa funções como argumentos para outras funções.
+List.map double [1..4] -- [2, 4, 6, 8]
+
+-- Ou escreva uma função anônima.
+List.map (\a -> a * 2) [1..4] -- [2, 4, 6, 8]
+
+-- Você pode casar um padrão na definição de funções quando há somente um caso.
+-- Esta função recebe uma tupla em vez de dois argumentos.
+-- Esta é a maneira que você normalmente vai desempacotar/extrair valores de tuplas.
+area (width, height) =
+ width * height
+
+area (6, 7) -- 42
+
+-- Utilize chaves para casar o padrão de nomes de campos de um registro.
+-- Utilize let para definir valores intermediários.
+volume {width, height, depth} =
+ let
+ area = width * height
+ in
+ area * depth
+
+volume { width = 3, height = 2, depth = 7 } -- 42
+
+-- Funções podem ser recursivas.
+fib n =
+ if n < 2 then
+ 1
+ else
+ fib (n - 1) + fib (n - 2)
+
+List.map fib [0..8] -- [1, 1, 2, 3, 5, 8, 13, 21, 34]
+
+-- Outra função recursiva (utilize List.length em um código de verdade).
+listLength aList =
+ case aList of
+ [] -> 0
+ x::xs -> 1 + listLength xs
+
+-- Chamadas de funções acontecem antes de qualquer operador infixo.
+-- Os parênteses indicam a precendência.
+cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1
+-- Primeiro degrees é aplicada em 30, então o resultado é passado para as
+-- funções de trigonometria, que então é elevado ao quadrado e, por fim, a
+-- adição acontece.
+
+{-- Tipos e Anotações de Tipos --}
+
+-- O compilador irá inferir o tipo de cada valor em seu programa.
+-- Tipos iniciam com letra maiúscula. Leia x : T como "x é do tipo T".
+-- Alguns tipos comuns que você pode ver no REPL do Elm.
+5 : Int
+6.7 : Float
+"hello" : String
+True : Bool
+
+-- Funções têm tipos também. Leia -> como "vai para". Pense no tipo mais à
+-- direita como o tipo do valor de retorno e os outros como argumentos.
+not : Bool -> Bool
+round : Float -> Int
+
+-- Quando você define um valor, é uma boa prática escrever seu tipo acima dele.
+-- A anotação é uma forma de documentação, que é verifica pelo compilador.
+double : Int -> Int
+double x = x * 2
+
+-- Argumentos de uma função são passados entre parênteses.
+-- Tipos com letra minúscula são tipos variáveis: eles podem ser de qualquer
+-- tipo, desde que cada chamada seja consistente.
+List.map : (a -> b) -> List a -> List b
+-- "List.map é do tipo a-vai-para-b, vai para lista de a e vai para lista de b."
+
+-- Existem três tipos especiais com minúsculas: number, comparable e appendable.
+-- Numbers permite que você utilize aritmética em Ints e Floats.
+-- Comparable permite você ordenar números e strings, como a < b.
+-- Appendable permite que coisas possam ser combinadas com a ++ b.
+
+{-- Type Aliases e Union Types --}
+
+-- Quando você escreve um registro ou uma tupla, seu tipo já existe.
+-- (Observe que os tipos de um registro utilizam dois-pontos e os valores de um
+-- registro utilizam igual.)
+origin : { x : Float, y : Float, z : Float }
+origin =
+ { x = 0, y = 0, z = 0 }
+
+-- Você pode dar um bom nome para tipos existentes com um type alias.
+type alias Point3D =
+ { x : Float, y : Float, z : Float }
+
+-- Se você cria um alias para um registro, você pode usar o nome como uma
+-- função construtora.
+otherOrigin : Point3D
+otherOrigin =
+ Point3D 0 0 0
+
+-- Mas ele ainda é do mesmo tipo, então você pode compará-los.
+origin == otherOrigin -- True
+
+-- Por outro lado, a definição de um union type cria um tipo que não existia
+-- antes. Um union type é chamado assim porque ele pode ser uma de muitas
+-- possibilidades. Cada uma das possibilidades é representada como uma "tag".
+type Direction =
+ North | South | East | West
+
+-- As tags podem levar outros valores de tipos conhecidos. Isso pode trabalhar
+-- recursivamente.
+type IntTree =
+ Leaf | Node Int IntTree IntTree
+-- "Leaf" e "Node" são as tags. Tudo após uma tag é um tipo.
+
+-- As tags podem ser usadas como valores ou funções.
+root : IntTree
+root =
+ Node 7 Leaf Leaf
+
+-- Union types (e type aliases) podem utilizar tipos variáveis.
+type Tree a =
+ Leaf | Node a (Tree a) (Tree a)
+-- "O tipo árvore-de-a é uma folha ou um nó de a, árvore-de-a e árvore-de-a."
+
+-- Casa padrão com union tags. As tags maiúsculas serão casadas de maneira exa-
+-- ta. As variáveis minúsculas irão casar com qualquer coisa. Sublinhado também
+-- casa com qualquer coisa, mas siginifica que você não o está utilizando.
+leftmostElement : Tree a -> Maybe a
+leftmostElement tree =
+ case tree of
+ Leaf -> Nothing
+ Node x Leaf _ -> Just x
+ Node _ subtree _ -> leftmostElement subtree
+
+-- Isso é praticamente a própria linguagem. Agora vamos ver como organizar e
+-- executar seu código.
+
+{-- Módulos e Imports --}
+
+-- As bibliotecas internas são organizadas em módulos, assim como quaisquer
+-- bibliotecas de terceiros que você possa utilizar. Para grandes projetos,
+-- você pode definir seus próprios módulos.
+
+-- Coloque isso no topo do arquivo. Se for omitido, você está no Main.
+module Name where
+
+-- Por padrão, tudo é exportado. Você pode especificar as exportações de forma
+-- explícita.
+module Name (MyType, myValue) where
+
+-- Um padrão comum é exportar um union type mas não suas tags. Isto é conhecido
+-- como "tipo opaco" e é frequentemente utilizado em bibliotecas.
+
+-- Importe código de outros módulos para utilizá-lo no seu código.
+-- Coloque Dict no escopo para você poder chamar Dict.insert.
+import Dict
+
+-- Importe o módulo Dict e o tipo Dict para que suas anotações não tenham que
+-- dizer Dict.Dict. Você ainda pode utilizar Dict.insert.
+import Dict exposing (Dict)
+
+-- Renomeie um import.
+import Graphics.Collage as C
+
+{-- Portas --}
+
+-- Uma porta indica que você estará se comunicando com o mundo exterior.
+-- Portas são permitidas somente no módulo Main.
+
+-- Uma porta de entrada é apenas uma assinatura de tipo.
+port clientID : Int
+
+-- Uma porta de saída tem uma definição.
+port clientOrders : List String
+port clientOrders = ["Books", "Groceries", "Furniture"]
+
+-- Não vamos entrar em detalhes, mas você configura callbacks no JavaScript
+-- para enviar nas portas de entrada e receber nas portas de saída.
+
+{-- Ferramentas de Linha de Comando --}
+
+-- Compila um arquivo.
+$ elm make MyFile.elm
+
+-- A primeira vez que você fizer isso, o Elm instalará as bibliotecas internas
+-- e criará o elm-package.json, onde a informação sobre seu projeto é mantida.
+
+-- O reactor é um servidor que compila e roda seus arquivos.
+-- Clique na chave ao lado dos nomes de arquivo para entrar no depurador de
+-- viagem no tempo.
+$ elm reactor
+
+-- Teste expressões simples no Read-Eval-Print Loop.
+$ elm repl
+
+-- Pacotes são identificados pelo usuário e nome do repositório no GitHub.
+-- Instale um novo pacote e registre-o no elm-package.json.
+$ elm package install evancz/elm-html
+
+-- Veja o que mudou entre as versões de um pacote.
+$ elm package diff evancz/elm-html 3.0.0 4.0.2
+-- O gerenciador de pacotes do Elm obriga o versionamento semântico, logo
+-- mudanças de versões no minor nunca quebrará o seu build!
+```
+
+A linguagem Elm é supreendentemente pequena. Agora você pode olhar para quase
+qualquer código-fonte em Elm e ter uma ideia aproximada do que está acontecendo.
+No entanto, as possibilidades para código resistente a erros e de fácil
+refatoração são infinitas!
+
+Aqui estão algumas referências utéis.
+
+* O [site do Elm](http://elm-lang.org/). Ele inclui:
+ * Links para os [instaladores](http://elm-lang.org/install)
+ * [Documentação](http://elm-lang.org/docs), incluindo [a referência de sintaxe](http://elm-lang.org/docs/syntax)
+ * Muitos [exemplos](http://elm-lang.org/examples) úteis
+
+* Documentação para as [bibliotecas internas do Elm](http://package.elm-lang.org/packages/elm-lang/core/latest/). Tome nota de:
+ * [Basics](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics), que é importada por padrão
+ * [Maybe](http://package.elm-lang.org/packages/elm-lang/core/latest/Maybe) e seu primo [Result](http://package.elm-lang.org/packages/elm-lang/core/latest/Result), comumente utilizados para valores faltantes e manipulação de erros
+ * Estruturas de dados como [List](http://package.elm-lang.org/packages/elm-lang/core/latest/List), [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict) e [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set)
+ * [Codificação](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Encode) e [decodificação](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode) JSON
+
+* [A Arquitetura Elm](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). Uma dissertação pelo criador do Elm com exemplos sobre como organizar código em componentes.
+
+* A [lista de e-mail do Elm](https://groups.google.com/forum/#!forum/elm-discuss). Todos são amigáveis e solícitos.
+
+* [Escopo em Elm](https://github.com/elm-guides/elm-for-js/blob/master/Scope.md#scope-in-elm) e [Como Ler uma Anotação de Tipo](https://github.com/elm-guides/elm-for-js/blob/master/How%20to%20Read%20a%20Type%20Annotation.md#how-to-read-a-type-annotation). Mais sobre guias da comunidade sobre o básico de Elm escrito por desenvolvedores JavaScript.
+
+Saia e escreva algum código Elm!
diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown
index 907892b1..e59ba901 100644
--- a/pt-br/git-pt.html.markdown
+++ b/pt-br/git-pt.html.markdown
@@ -2,7 +2,7 @@
category: tool
tool: git
lang: pt-br
-filename: LearnGit.txt
+filename: LearnGit-br.txt
contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
- ["Leo Rudberg" , "http://github.com/LOZORD"]
diff --git a/pt-br/julia-pt.html.markdown b/pt-br/julia-pt.html.markdown
new file mode 100644
index 00000000..48d97e58
--- /dev/null
+++ b/pt-br/julia-pt.html.markdown
@@ -0,0 +1,748 @@
+---
+language: Julia
+filename: learnjulia-pt.jl
+contributors:
+ - ["Leah Hanson", "http://leahhanson.us"]
+translators:
+ - ["Davidson Mizael", "https://github.com/davidsonmizael"]
+lang: pt-br
+---
+
+Julia é uma linguagem homoiconic funcional focada na computação tecnica. Ao mesmo tempo que ela tem todo o poder dos homoiconic macros, funções de primeira classe, e controle de baixo nivel, Julia é tão facil para aprender e usar quanto Python.
+
+Este tutorial é baseado no Julia 0.3.
+
+```ruby
+# Linhas únicas de comentários começam com o simbolo hash(jogo da velha).
+#= Comentários de multiplas linhas podem ser escritos
+ colocando '#=' antes do texto e '=#'
+ após o texto. Eles também podem ser agrupados
+=#
+
+####################################################
+## 1. Tipos primitivos e operadores
+####################################################
+
+# Tudo em Julia é uma expressão.
+
+# Há muitos tipos básicos de numeros.
+3 # => 3 (Int64)
+3.2 # => 3.2 (Float64)
+2 + 1im # => 2 + 1im (Complex{Int64})
+2//3 # => 2//3 (Rational{Int64})
+
+# Todos os operadores inseguros normais estão disponiveis.
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+35 / 5 # => 7.0
+5 / 2 # => 2.5 # dividir um Int por um Int resulta em um float
+div(5, 2) # => 2 # para um restultado truncado, use div
+5 \ 35 # => 7.0
+2 ^ 2 # => 4 # elevado,não o opeardor binário xor
+12 % 10 # => 2
+
+# Impõe a priodidade nos parenteses
+(1 + 3) * 2 # => 8
+
+# Operadores binarios
+~2 # => -3 # not
+3 & 5 # => 1 # and
+2 | 4 # => 6 # or
+2 $ 4 # => 6 # xor
+2 >>> 1 # => 1 # deslocamento lógico de bits a direita
+2 >> 1 # => 1 # deslocamento aritmético de bits a direita
+2 << 1 # => 4 # deslocamento lógico/aritmético de bits a esquerda
+
+# Você pode usar a função bits para ver a representação binária de um numero.
+bits(12345)
+# => "0000000000000000000000000000000000000000000000000011000000111001"
+bits(12345.0)
+# => "0100000011001000000111001000000000000000000000000000000000000000"
+
+# Valores booleanos são primitivos.
+true
+false
+
+# Operadores booleanos
+!true # => false
+!false # => true
+1 == 1 # => true
+2 == 1 # => false
+1 != 1 # => false
+2 != 1 # => true
+1 < 10 # => true
+1 > 10 # => false
+2 <= 2 # => true
+2 >= 2 # => true
+# Comparações podem ser encadeadas
+1 < 2 < 3 # => true
+2 < 3 < 2 # => false
+
+# Strings são criadas com "
+"Isso é uma String."
+
+# Caracteres literais são escritos com '
+'a'
+
+# Uma string pode ser indexada como um vetor de caracteres
+"Isso é uma string"[1] # => 'I' # Julia começa a indexar a partir do 1
+# Porém isso não funcionará direito com strings em UTF8,
+# portanto é recomendado usar iterações sobre uma string (map, loops com for, etc).
+
+# $ pode ser usado para interpolação de string:
+"2 + 2 = $(2 + 2)" # => "2 + 2 = 4"
+# Você pode usar qualquer expressão Julia dentro dos parenteses.
+
+# Outro jeito de formatar strings é com um macro no printf.
+@printf "%d é menor que %f" 4.5 5.3 # 5 é menor que 5.300000
+
+# Escrever na tela é fácil
+println("Eu sou Julia. Prazer em conhece-lo!")
+
+####################################################
+## 2. Variáveis e coleções
+####################################################
+
+#Você não declara variáveis antes de atribui-lás.
+some_var = 5 # => 5
+some_var # => 5
+
+# Acessando a variável anterior não iniciada é um erro
+try
+ some_other_var # => ERROR: some_other_var não definida
+catch e
+ println(e)
+end
+
+# Nomes de variáveis começam com uma letra.
+# Depois disso, você pode usar letras, digitos, underscores e pontos de exclamação.
+SomeOtherVar123! = 6 # => 6
+
+# Você também pode usar caractéres unicode
+☃ = 8 # => 8
+# Estes são especialmente reservados para notações matemáticas.
+2 * π # => 6.283185307179586
+
+# Uma nota na convenção de nomes em Julia:
+#
+# * A separação de palavras pode ser feita por underscores ('_'), mas o uso
+# de underscore é desencorajado a menos que o nome da variável seja dificil
+# de ler.
+#
+# * Os nomes de tipos começam com letra maiúscula e a separação de letras é
+# feita a partir de CamelCase no lugar de underscores.
+#
+# * Nomes de funções e macros são em minúsculo, sem underscore.
+#
+# * Funções que modificam a própria entrada tem nomes que terminam em !. Estas
+# funções são chamadas as vezes de funções de mutação ou função in-place.
+
+# Vetores armazenam uma sequencia de valores indexados por integer de 1 a n:
+a = Int64[] # => 0-element Int64 Array
+
+# 1-Vetores dimensionais literais podem ter seus valores separados por virgula.
+b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6]
+b[1] # => 4
+b[end] # => 6
+
+# 2-Vetores dimensionais usam espaço para separar valores e ponto e virgula para linhas.
+matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4]
+
+# Adiciona-se coisas ao final de uma lista com push! e append!
+push!(a,1) # => [1]
+push!(a,2) # => [1,2]
+push!(a,4) # => [1,2,4]
+push!(a,3) # => [1,2,4,3]
+append!(a,b) # => [1,2,4,3,4,5,6]
+
+# Remove-se do final com pop!
+pop!(b) # => 6 e 'b' agora é [4,5]
+
+# Vamos coloca-lo de novo
+push!(b,6) # 'b' agora é [4,5,6] de novo.
+
+a[1] # => 1 # lembre-se que Julia indexa a partir de 1, não 0.
+
+# end é um atalho para a ultima posição. Pode ser usada em qualquer
+# expressão indexada.
+a[end] # => 6
+
+# nós também temos shift e unshift
+shift!(a) # => 1 e 'a' agora é [2,4,3,4,5,6]
+unshift!(a,7) # => [7,2,4,3,4,5,6]
+
+# Funções que terminam com ponto de exclamação indicam que elas modificam
+# seus argumentos.
+arr = [5,4,6] # => 3-element Int64 Array: [5,4,6]
+sort(arr) # => [4,5,6]; 'arr' continua [5,4,6]
+sort!(arr) # => [4,5,6]; 'arr' agora é [4,5,6]
+
+# Olhar além dos limites é um BoundsError
+try
+ a[0] # => ERROR: BoundsError() in getindex at array.jl:270
+ a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270
+catch e
+ println(e)
+end
+
+# Erros listam a linha e o nome do arquivo que ele está, mesmo se for uma
+# biblioteca padrão. Se você construiu Julia pelo source, você pode olhar na
+# pasta base dentro da pasta do Julia para encontrar esses arquivos.
+
+# Você pode inicializar vetores com limites
+a = [1:5;] # => 5-element Int64 Array: [1,2,3,4,5]
+
+# Você pode ver até um limite com a sintaxe separada
+a[1:3] # => [1, 2, 3]
+a[2:end] # => [2, 3, 4, 5]
+
+# Remova elementos de um array pelo index com splice!
+arr = [3,4,5]
+splice!(arr,2) # => 4 ; arr is now [3,5]
+
+# Concatene listas com append!
+b = [1,2,3]
+append!(a,b) # 'a' agora é [1, 2, 3, 4, 5, 1, 2, 3]
+
+# Cheque se um valor existe me uma lista com in
+in(1, a) # => true
+
+# Veja o tamanho com lenght
+length(a) # => 8
+
+# Tuples não podem ser mudados.
+tup = (1, 2, 3) # => (1,2,3) # um tuple (Int64,Int64,Int64).
+tup[1] # => 1
+try:
+ tup[1] = 3 # => ERROR: não há metodo setindex!((Int64,Int64,Int64),Int64,Int64)
+catch e
+ println(e)
+end
+
+# Muitas litas de funções também trabalham com tuples
+length(tup) # => 3
+tup[1:2] # => (1,2)
+in(2, tup) # => true
+
+#Você pode desempacotar tuples para variáveis.
+a, b, c = (1, 2, 3) # => (1,2,3) # 'a' agora é 1, 'b' agora é 2 e 'c' agora é 3
+
+# Tuplas são criados mesmo se você deixar fora dos parenteses
+d, e, f = 4, 5, 6 # => (4,5,6)
+
+# Uma tupla de um elemento é diferente do valor que ele contém
+(1,) == 1 # => false
+(1) == 1 # => true
+
+# Olhe como é facil pra trocar dois valores
+e, d = d, e # => (5,4) # 'd' agora é 5 e 'e' agora é 4
+
+# Dicionários armazenam mapeamentos
+empty_dict = Dict() # => Dict{Any,Any}()
+
+# Você pode criar um dicionário usando um literal
+filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3]
+# => Dict{ASCIIString,Int64}
+
+# Veja os valores com []
+filled_dict["one"] # => 1
+
+# Pegue todas as chaves
+keys(filled_dict)
+# => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2])
+# Nota - as chaves dos dicionários não são ordenadas nem estão na ordem que você as inseriu.
+
+# Pegue todos os valores
+values(filled_dict)
+# => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2])
+# Nota - A mesma coisa que na nota acima sobre a ordenação das chaves.
+
+# Cheque pela existencia de chaves em um dicionário com in e haskey
+in(("one", 1), filled_dict) # => true
+in(("two", 3), filled_dict) # => false
+haskey(filled_dict, "one") # => true
+haskey(filled_dict, 1) # => false
+
+# Procurar por uma chave não existente irá gerar um erro
+try
+ filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489
+catch e
+ println(e)
+end
+
+# Use o método get para escapar desse erro passando um valor padrão
+# get(dictionary,key,default_value)
+get(filled_dict,"one",4) # => 1
+get(filled_dict,"four",4) # => 4
+
+# Use sets para representar coleções de valores unicos e não ordenados
+empty_set = Set() # => Set{Any}()
+# Inicialize um set com valores
+filled_set = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4)
+
+# Adicione mais valores para um set
+push!(filled_set,5) # => Set{Int64}(5,4,2,3,1)
+
+# Cheque se um valor está no set
+in(2, filled_set) # => true
+in(10, filled_set) # => false
+
+# Não há funções para interseção de set, união e diferença.
+other_set = Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3)
+intersect(filled_set, other_set) # => Set{Int64}(3,4,5)
+union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6)
+setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4)
+
+####################################################
+## 3. Controle de fluxo
+####################################################
+
+# Vamos fazer uma variável
+some_var = 5
+
+# Aqui está um if. Identação nao é importante em Julia.
+if some_var > 10
+ println("some_var é totalmente maior que 10.")
+elseif some_var < 10 # Essa clausula elseif é opcional.
+ println("some_var é menor que 10.")
+else # A clausula else é opcional também.
+ println("some_var é literalmente 10.")
+end
+# => exibe "some_var é menor que 10"
+
+# Loops for repetem sobre variaveis iteráveis.
+# Tipos iterativos incluem Range, Array, set Dict e String.
+for animal=["dog", "cat", "mouse"]
+ println("$animal is a mammal")
+ # Você pode interpolar variáveis usando $ ou expressões em strings
+end
+# exibe:
+# dog is a mammal
+# cat is a mammal
+# mouse is a mammal
+
+# Você pode usar 'in' no lugar de '='.
+for animal in ["dog", "cat", "mouse"]
+ println("$animal is a mammal")
+end
+# exibe:
+# dog is a mammal
+# cat is a mammal
+# mouse is a mammal
+
+for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"]
+ println("$(a[1]) is a $(a[2])")
+end
+# exibe:
+# dog is a mammal
+# cat is a mammal
+# mouse is a mammal
+
+for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"]
+ println("$k is a $v")
+end
+# exibe:
+# dog is a mammal
+# cat is a mammal
+# mouse is a mammal
+
+# Loops while circulam enquanto a condição é true
+x = 0
+while x < 4
+ println(x)
+ x += 1 # Abreveação para x = x + 1
+end
+# exibe:
+# 0
+# 1
+# 2
+# 3
+
+# Trate exceções com um bloco try/catch
+try
+ error("help")
+catch e
+ println("caught it $e")
+end
+# => caught it ErrorException("help")
+
+
+####################################################
+## 4. Funções
+####################################################
+
+# A palavra chave 'function' cria novas funções
+#function name(arglist)
+# corpo...
+#end
+function add(x, y)
+ println("x is $x and y is $y")
+
+ # Funções retornam o valor da sua ultima declaração
+t x + y
+end
+
+add(5, 6) # => 11 after printing out "x is 5 and y is 6"
+
+# Você pode definir funções que tomam um numero incerto de
+# argumentos
+function varargs(args...)
+ return args
+ # use a palavra chave return para retornar um valor em qualquer parte da função
+end
+# => varargs (generic function with 1 method)
+
+varargs(1,2,3) # => (1,2,3)
+
+# O ... é chamado de splat.
+# Nós apenas o usamos na definição de uma função.
+# Também pode ser usado na chamada de uma função,
+# onde ela vai abrir um Array ou o conteúdo de um Tuple na lista de argumentos.
+Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # produz um Set de Arrays
+Set([1,2,3]...) # => Set{Int64}(1,2,3) # isso é equivalente a Set(1,2,3)
+
+x = (1,2,3) # => (1,2,3)
+Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # um Set de Tuples
+Set(x...) # => Set{Int64}(2,3,1)
+
+# Você pode definir funções com argumentos posicionais opcionais.
+function defaults(a,b,x=5,y=6)
+ return "$a $b and $x $y"
+end
+
+defaults('h','g') # => "h g and 5 6"
+defaults('h','g','j') # => "h g and j 6"
+defaults('h','g','j','k') # => "h g and j k"
+try
+ defaults('h') # => ERROR: no method defaults(Char,)
+ defaults() # => ERROR: no methods defaults()
+catch e
+ println(e)
+end
+
+# Você pode definir funções que tomam argumentos como palavras chaves
+function keyword_args(;k1=4,name2="hello") # note the ;
+ return ["k1"=>k1,"name2"=>name2]
+end
+
+keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4]
+keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"]
+keyword_args() # => ["name2"=>"hello","k1"=>4]
+
+# Você pode combinar todos os tipos de argumentos em uma só função
+function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo")
+ println("normal arg: $normal_arg")
+ println("optional arg: $optional_positional_arg")
+ println("keyword arg: $keyword_arg")
+end
+
+all_the_args(1, 3, keyword_arg=4)
+# exibe:
+# normal arg: 1
+# optional arg: 3
+# keyword arg: 4
+
+# Julia tem funções de primeira classe
+function create_adder(x)
+ adder = function (y)
+ return x + y
+ end
+ return adder
+end
+
+# Isso é "sintexe furiosa de lambda" pra criar funções anônimas.
+(x -> x > 2)(3) # => true
+
+#Esta função é identica a implementação da create_adder acima.
+function create_adder(x)
+ y -> x + y
+end
+
+# Você também pode nomear funções internas, se você quiser
+function create_adder(x)
+ function adder(y)
+ x + y
+ end
+ adder
+end
+
+add_10 = create_adder(10)
+add_10(3) # => 13
+
+
+# Há
+# There are built-in higher order functions
+map(add_10, [1,2,3]) # => [11, 12, 13]
+filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+
+# Nós podemos usar listas de compreensão para melhores mapeamentos
+[add_10(i) for i=[1, 2, 3]] # => [11, 12, 13]
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+
+####################################################
+## 5. Tipos
+####################################################
+
+#Julia tem um sistema de tipos.
+# Todo valor tem um tipo. Variaveis não tem tipos próprios.
+# Você pode usar a função 'typeof' para pegar o valor.
+typeof(5) # => Int64
+
+# Tipos são valores de primeira classe.
+typeof(Int64) # => DataType
+typeof(DataType) # => DataType
+# DataType é o tipo que representa tipos, incluindo ele mesmo.
+
+# Tipos são usados para documentação, optimização e envio
+# Eles não são estaticamente checados.
+
+# Usuários podem definir tipos
+# Eles são como records ou structs em outras linguagens.
+# Novos tipos são definidos usando a palavra chave 'type'
+
+# type Name
+# field::OptionalType
+# ...
+# end
+type Tiger
+ taillength::Float64
+ coatcolor # não incluindo uma notação type é o mesmo que '::Any'
+end
+
+# Os argumentos padrões de um construtor são as propriedades
+# do tipo na ordem que eles são listados na definição.
+tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange")
+
+# O tipo double como construtor de função para valores desse tipo
+# The type doubles as the constructor function for values of that type
+sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire")
+
+# Esses tipos no estilo struct são chamados tipos concretos
+# Eles podem ser instanciados, mas não podem ter subtipos.
+# O outro tipo de tipos são os tipos abstratos.
+
+# abstract Name
+abstract Cat # apenas um nome e um ponto na hierarquia de tipo
+
+# Tipos abstratos podem ser instanciados, mas não podem ter subtipos.
+# Por exemplo, Number é um tipo abstrato
+subtypes(Number) # => 6-element Array{Any,1}:
+ # Complex{Float16}
+ # Complex{Float32}
+ # Complex{Float64}
+ # Complex{T<:Real}
+ # ImaginaryUnit
+ # Real
+subtypes(Cat) # => 0-element Array{Any,1}
+
+# Todo tipo tem um super tipo; use a função 'super' para pegá-lo.
+typeof(5) # => Int64
+super(Int64) # => Signed
+super(Signed) # => Real
+super(Real) # => Number
+super(Number) # => Any
+super(super(Signed)) # => Number
+super(Any) # => Any
+# Todos esss tipos, exceto o Int64, são abstratos.
+
+# <: é o operador de subtipagem
+type Lion <: Cat # Lion é um subtipo de Cat
+ mane_color
+ roar::String
+end
+
+# Você pode definir mais construtores para seu tipo
+# É só definir uma função com o mesmo nome do tipo
+# e chamar um construtor existente para pegar o valor do tipo correto
+Lion(roar::String) = Lion("green",roar)
+# Isso é um construtor externo porque ele está fora da definição do tipo
+
+type Panther <: Cat # Panther também é um subtipo de Cat
+ eye_color
+ Panther() = new("green")
+# Panthers terão apenas esse construtor, e não construtor padrão.
+end
+# Usando construtores internos, como Panther faz, lhe da o controle
+# sobre como os valores dos tipos são criados.
+# Quando possivel, você deve usar construtores externos mais do que internos.
+
+####################################################
+## 6. Multiple-Dispatch
+####################################################
+
+
+# Em Julia todas as funções nomeadas são funções genericas
+# Isso significa que elas são construidas de muitos métodos pequenos
+# Cada construtor para Lion é um metodo da função genérica Lion.Lion.
+
+# Para um exemplo sem construtor, vamos fazer a função meow
+
+# Definição para Lion, Panther e Tiger
+function meow(animal::Lion)
+ animal.roar #propriedades do tipo de acesso usando a notação ponto '.'
+end
+
+function meow(animal::Panther)
+ "grrr"
+end
+
+function meow(animal::Tiger)
+ "rawwwr"
+end
+
+# Testando a função meow
+meow(tigger) # => "rawwr"
+meow(Lion("brown","ROAAR")) # => "ROAAR"
+meow(Panther()) # => "grrr"
+
+# Revendo o tipo local de hierarchy
+issubtype(Tiger,Cat) # => false
+issubtype(Lion,Cat) # => true
+issubtype(Panther,Cat) # => true
+
+# Definindo uma função que recebe Cats
+function pet_cat(cat::Cat)
+ println("The cat says $(meow(cat))")
+end
+
+pet_cat(Lion("42")) # => exibe "The cat says 42"
+try
+ pet_cat(tigger) # => ERROR: no method pet_cat(Tiger,)
+catch e
+ println(e)
+end
+
+# Em linguagens orientadas a objeto, envio unico é comúm
+# isso significa que o método é selecionado baseado no tipo do seu primeiro argumento
+# Em Julia todos os tipos de argumentos contribuem na seleção do melhor método
+
+
+# Vamos definir uma função com mais argumentos, então poderemos ver a diferença
+function fight(t::Tiger,c::Cat)
+ println("The $(t.coatcolor) tiger wins!")
+end
+# => fight (generic function with 1 method)
+
+fight(tigger,Panther()) # => exibe The orange tiger wins!
+fight(tigger,Lion("ROAR")) # => exibir The orange tiger wins!
+
+# Vamos mudar o comportamento quando o gato é especificamente um leão
+fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!")
+# => fight (generic function with 2 methods)
+
+fight(tigger,Panther()) # => exobe The orange tiger wins!
+fight(tigger,Lion("ROAR")) # => exobe The green-maned lion wins!
+
+# Nós não precisamos de um tigre para brigar
+fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))")
+# => fight (generic function with 3 methods)
+
+fight(Lion("balooga!"),Panther()) # => exibe The victorious cat says grrr
+try
+ fight(Panther(),Lion("RAWR")) # => ERROR: no method fight(Panther,Lion)
+catch
+end
+
+# Aliás, vamos deixar o gato ir primeiro
+fight(c::Cat,l::Lion) = println("The cat beats the Lion")
+# => Warning: New definition
+# fight(Cat,Lion) at none:1
+# is ambiguous with
+# fight(Lion,Cat) at none:2.
+# Make sure
+# fight(Lion,Lion)
+# is defined first.
+#fight (generic function with 4 methods)
+
+# Este aviso é porque não está claro qual método fight será chamado em:
+fight(Lion("RAR"),Lion("brown","rarrr")) # => exibe The victorious cat says rarrr
+# O resultado pode ser diferente em outras versões de Julia
+
+fight(l::Lion,l2::Lion) = println("The lions come to a tie")
+fight(Lion("RAR"),Lion("brown","rarrr")) # => exibe The lions come to a tie
+
+
+# Embaixo dos panos
+# Você pode olhar o llvm e o código assembly gerado.
+
+square_area(l) = l * l # square_area (generic function with 1 method)
+
+square_area(5) #25
+
+# O que acontece quando alimentamos square_area com um inteiro?
+# What happens when we feed square_area an integer?
+code_native(square_area, (Int32,))
+ # .section __TEXT,__text,regular,pure_instructions
+ # Filename: none
+ # Source line: 1 # Prólogo
+ # push RBP
+ # mov RBP, RSP
+ # Source line: 1
+ # movsxd RAX, EDI # Busca l na memoria?
+ # imul RAX, RAX # Faz o quadrado de l e armazena o resultado em RAX
+ # pop RBP # Restaura o ponteiro de base antigo
+ # ret # O resultado continua em RAX
+
+code_native(square_area, (Float32,))
+ # .section __TEXT,__text,regular,pure_instructions
+ # Filename: none
+ # Source line: 1
+ # push RBP
+ # mov RBP, RSP
+ # Source line: 1
+ # vmulss XMM0, XMM0, XMM0 # Múltiplicação escalar unica de precisão (AVX)
+ # pop RBP
+ # ret
+
+code_native(square_area, (Float64,))
+ # .section __TEXT,__text,regular,pure_instructions
+ # Filename: none
+ # Source line: 1
+ # push RBP
+ # mov RBP, RSP
+ # Source line: 1
+ # vmulsd XMM0, XMM0, XMM0 # Duplicação ecalar de precisão multipla(AVX)
+ # pop RBP
+ # ret
+ #
+# Note que Julia usará instruções de ponto flutuante se quaser um dos
+# argumentos forem float
+# Vamos calcular a área de um circulo
+circle_area(r) = pi * r * r # circle_area (generic function with 1 method)
+circle_area(5) # 78.53981633974483
+
+code_native(circle_area, (Int32,))
+ # .section __TEXT,__text,regular,pure_instructions
+ # Filename: none
+ # Source line: 1
+ # push RBP
+ # mov RBP, RSP
+ # Source line: 1
+ # vcvtsi2sd XMM0, XMM0, EDI # Carrega inteiro (r) da memória
+ # movabs RAX, 4593140240 # Carrega pi
+ # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r
+ # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r
+ # pop RBP
+ # ret
+ #
+
+code_native(circle_area, (Float64,))
+ # .section __TEXT,__text,regular,pure_instructions
+ # Filename: none
+ # Source line: 1
+ # push RBP
+ # mov RBP, RSP
+ # movabs RAX, 4593140496
+ # Source line: 1
+ # vmulsd XMM1, XMM0, QWORD PTR [RAX]
+ # vmulsd XMM0, XMM1, XMM0
+ # pop RBP
+ # ret
+ #
+```
+
+## Extras
+
+Você pode ver mais um monte de detalhes no [manual de Julia] (http://docs.julialang.org/en/latest/manual/)
+O melhor lugar pra pedir ajuda em Julia é a (muito amigável) [mailing list](https://groups.google.com/forum/#!forum/julia-users).
diff --git a/pt-br/python3-pt.html.markdown b/pt-br/python3-pt.html.markdown
index c5a3c020..9b6bd1b6 100644
--- a/pt-br/python3-pt.html.markdown
+++ b/pt-br/python3-pt.html.markdown
@@ -7,7 +7,7 @@ contributors:
- ["Zachary Ferguson", "http://github.com/zfergus2"]
translators:
- ["Paulo Henrique Rodrigues Pinheiro", "http://www.sysincloud.it"]
-language: pt-br
+lang: pt-br
filename: learnpython3-pt.py
---
diff --git a/pt-br/self-pt.html.markdown b/pt-br/self-pt.html.markdown
new file mode 100644
index 00000000..2fb2953b
--- /dev/null
+++ b/pt-br/self-pt.html.markdown
@@ -0,0 +1,165 @@
+---
+language: self
+contributors:
+ - ["Russell Allen", "http://github.com/russellallen"]
+translators:
+ - ["Ricardo de Almeida Gonzaga", "http://github.com/ricardotk"]
+lang: pt-br
+filename: learnself-br.self
+---
+
+Self é um protótipo rápido baseado em linguagem orientada a objeto a qual roda em sua própria JIT vm. A maior parte do desenvolvimento é feito através de interações com objetos ativos, através de um ambiente visual de desenvolvimento chamado *morphic* com navegador e depurador integrados.
+
+Tudo em Self é um objeto. Toda computação é feita através do envio de mensagens para objetos. Objetos em Self podem ser compreendidos como conjuntos de slots de chave-valor.
+
+# Construindo objetos
+
+O analisador interno de Self pode construir objetos, incluindo objetos método.
+
+```
+"Isto é um comentario"
+
+"A string:"
+'Isto é uma string com caracteres \'escapados\'.\n'
+
+"Um inteiro de 30 bits"
+23
+
+"Um float de 30 bits"
+3.2
+
+"-20"
+-14r16
+
+"Um objeto o qual entende apenas uma menssagem, 'x' que retorna 20"
+(|
+ x = 20.
+|)
+
+"Um objeto o qual tambem entende 'x', que atribui o slot x"
+(|
+ x <- 20.
+|)
+
+"Um objeto o qual entende o método 'doubleX' que
+dobra o valor de x e então retorna o objeto"
+(|
+ x <- 20.
+ doubleX = (x: x * 2. self)
+|)
+
+"Um objeto o qual entende todas as mensagens
+que 'traits point' entende". O analisador
+procura 'traits point' enviando as mensagens
+'traits' e 'point' para um objeto conhecido
+chamado de 'lobby'. Ele procura pelo objeto
+'true' também enviando a mensagem 'true'
+para o 'lobby'.""
+(| parent* = traits point.
+ x = 7.
+ y <- 5.
+ isNice = true.
+|)
+```
+
+# Enviando mensagens para objetos
+
+Mensagens podem ser unárias, binárias ou palavras-chave. Precedência é nesta ordem. Diferentemente de Smalltalk, a precedência de mensagens binárias precisam ser especificadas, e todas as palavras-chave após a primeira devem começar com letra maiúscula. Mensagens são separadas de seu destinatário através de espaço em branco.
+
+```
+"mensagem unária, envia 'printLine' para o objeto '23'
+o qual escreve a string '23' para stdout e retorna o objeto recebido (ie 23)"
+23 printLine
+
+"envia a mensagem '+' com '7' para '23', em seguida a mensagem '*' com '8' para o resultado"
+(23 + 7) * 8
+
+"envia 'power:' para '2' com '8' retorna 256"
+2 power: 8
+
+"envia 'keyOf:IfAbsent:' para 'hello' com argumentos 'e' e '-1'.
+Retorna 1, o índice de 'e' em 'hello'."
+'hello' keyOf: 'e' IfAbsent: -1
+```
+
+# Blocos
+
+Self define controle de fluxo assim como Smalltalk e Ruby por meio de blocos. Blocos são computações atrasadas da forma:
+
+```
+[|:x. localVar| x doSomething with: localVar]
+```
+
+Exemplos do uso de um bloco:
+
+```
+"retorna 'HELLO'"
+'hello' copyMutable mapBy: [|:c| c capitalize]
+
+"retorna 'Nah'"
+'hello' size > 5 ifTrue: ['Yay'] False: ['Nah']
+
+"retorna 'HaLLO'"
+'hello' copyMutable mapBy: [|:c|
+ c = 'e' ifTrue: [c capitalize]
+ False: ['a']]
+```
+
+Múltiplas expressões são separadas por ponto final. ^ retorna imediatamente.
+
+```
+"retorna An 'E'! How icky!"
+'hello' copyMutable mapBy: [|:c. tmp <- ''|
+ tmp: c capitalize.
+ tmp = 'E' ifTrue: [^ 'An \'E\'! How icky!'].
+ c capitalize
+ ]
+```
+
+Blocos são realizados (completados) ao enviá-los a mensagem 'value' e herdando (imcumbir a) seus contextos:
+```
+"retorna 0"
+[|x|
+ x: 15.
+ "Repetidamente envia 'value' para o primeiro bloco enquanto o resultado do
+ envio de 'value' para o segundo bloco é o objeto 'true'"
+ [x > 0] whileTrue: [x: x - 1].
+ x
+] value
+```
+
+# Métodos
+
+Métodos são como blocos, porém eles não estão dentro de um contexto, ao invés disto são armazenados como valores de slots. Diferentemente de Smalltalk, métodos por padrão retornam o seu valor final e não 'self'.
+
+```
+"Aqui está um objeto com um slot atribuível 'x' e um método 'reduceXTo: y'.
+Enviar a mensagem 'reduceXTo: 10' para este objeto colocará
+o objeto '10' no slot 'x' e retornará o objeto original"
+(|
+ x <- 50.
+ reduceXTo: y = (
+ [x > y] whileTrue: [x: x - 1].
+ self)
+|)
+.
+```
+
+# Protótipos
+
+Não existem classes em Self. A maneira de obter um objeto é encontrar um protótipo e copia-lo.
+
+```
+| d |
+d: dictionary copy.
+d at: 'hello' Put: 23 + 8.
+d at: 'goodbye' Put: 'No!.
+"Imprime No!"
+( d at: 'goodbye' IfAbsent: 'Yes! ) printLine.
+"Imprime 31"
+( d at: 'hello' IfAbsent: -1 ) printLine.
+```
+
+# Informações adicionais
+
+O [Manual do Self](http://handbook.selflanguage.org) tem muito mais informações, e nada melhor do que por a mão na massa com Self através de sua [homepage](http://www.selflanguage.org).
diff --git a/pt-br/swift-pt.html.markdown b/pt-br/swift-pt.html.markdown
index e840b8cf..4ad67a06 100644
--- a/pt-br/swift-pt.html.markdown
+++ b/pt-br/swift-pt.html.markdown
@@ -353,7 +353,7 @@ internal class Rect: Shape {
func shrink() {
if sideLength > 0 {
- --sideLength
+ sideLength -= 1
}
}
diff --git a/pt-br/vim-pt.html.markdown b/pt-br/vim-pt.html.markdown
new file mode 100644
index 00000000..4f70079a
--- /dev/null
+++ b/pt-br/vim-pt.html.markdown
@@ -0,0 +1,239 @@
+---
+category: tool
+tool: vim
+contributors:
+ - ["RadhikaG", "https://github.com/RadhikaG"]
+translators:
+ - ["David Lima", "https://github.com/davelima"]
+lang: pt-br
+filename: LearnVim-pt.txt
+---
+
+
+[Vim](www.vim.org)
+(Vi IMproved - Vi Melhorado) é um clone do editor vi para Unix. Ele é um
+editor de texto projetado para ter velocidade e produtividade, e está presente
+na maioria dos systemas UNIX. O editor tem um grande número de atalhos de teclado
+para agilizar a navegação para pontos específicos no arquivo, além de edição rápida.
+
+## Navegação do Vim: o básico
+
+```
+ vim <nome-do-arquivo> # Abre <nome-do-arquivo> no vim
+ :q # Fecha o vim
+ :w # Salva o arquivo atual
+ :wq # Salva o arquivo e fecha o vim
+ :q! # Fecha o vim e descarta as alterações no arquivo
+ # ! *força* :q a executar, fechando o vim sem salvar antes
+ :x # Salvar o arquivo e fechao vim (atalho para :wq)
+
+ u # Desfazer
+ CTRL+R # Refazer
+
+ h # Move o cursor para a esquerda
+ j # Move o cursor para baixo
+ k # Move o cursor para cima
+ l # Move o cursor para a direita
+
+ # Movendo o cursor dentro da linha
+
+ 0 # Move para o início da linha
+ $ # Move para o final da linha
+ ^ # Move para o primeiro caractere da linha (ignora caracteres em branco)
+
+ # Pesquisa no texto
+
+ /palavra # Destaca todas as ocorrências de 'palavra' após o cursor
+ ?palavra # Destaca todas as ocorrências de 'palavra' antes do cursor
+ n # Move o cursor para a próxima ocorrência após a pesquisa
+ N # Move o cursor para a ocorrência anterior após a pesquisa
+
+ :%s/foo/bar/g # Substitui 'foo' por 'bar' no arquivo inteiro
+ :s/foo/bar/g # Substitui 'foo' por 'bar' na linha atual
+
+ # Pulando para caracteres específicos
+
+ f<caracter> # Posiciona o cursor no próximo <caracter>
+ t<character> # Posiciona o cursor antes do próximo <caracter>
+
+ # Por exemplo,
+ f< # Posiciona o cursor no <
+ t< # Posiciona o cursor logo antes do <
+
+ # Movendo por palavras
+
+ w # Move o cursor uma palavra a diante
+ b # Move o cursor uma palavra atrás
+ e # Move o cursor ao fim da palavra atual
+
+ # Outros caracteres para mover o cursor no arquivo
+
+ gg # Move para o topo do arquivo
+ G # Move para o final do arquivo
+ :NUM # Move para a linha NUM (NUM é qualquer número)
+ H # Move para o topo da tela visível
+ M # Move para o meio da tela visível
+ L # Move para o final da tela visível
+```
+
+## Modos:
+
+O Vim é baseado no conceito de **modos**.
+
+Modo Comando - usado para navegar e escrever comandos - o Vim já inicia nesse modo
+Modo Inserção - usado para fazer alterações no arquivo
+Modo Visual - usado para destacar textos e executar comandos neles
+Modo Ex - usado para ir a linha com ':' no final da tela para executar comandos
+
+```
+ i # Coloca o Vim no Modo Inserção, logo antes do cursor
+ a # Coloca o Vim no Modo Inserção, logo após o cursor
+ v # Coloca o Vim no Modo Visual
+ : # Coloca o Vim no Modo Ex
+ <esc> # Sai de qualquer modo que você estiver, e coloca o Vim no Modo Comando
+
+ # Copiando e colando texto
+
+ y # Coloca a seleção atual na área de transferência
+ yy # Coloca a linha atual na área de transferência
+ d # Deleta a seleção tual
+ dd # Deleta a linha atual
+ p # Cola o texto copiado após a posição do cursor
+ P # Cola o texto copiado antes da posição do cursor
+ x # Deleta o caractere que está na posição do cursor
+```
+
+## A 'Gramática' do Vim
+
+Podemos pensar no Vim como uma série de comendos
+em um formato 'Verbo-Modificador-Nome', onde:
+
+Verbo - sua ação
+Modificador - como você executará sua ação
+Nome - o objeto onde você vai executar sua acão
+
+Alguns exemplos importantes de 'Verbos', 'Modificadores' e 'Nomes':
+
+```
+ # 'Verbos'
+
+ d # Apagar (Delete)
+ c # Alterar (Change)
+ y # Copiar (Yank)
+ v # Seleção Visual
+
+ # 'Modificadores'
+
+ i # Dentro (Inside)
+ a # Em torno de (Around)
+ NUM # Número (NUM qualquer número)
+ f # Pesquisa algo e posiciona o cursor acima do resultado
+ t # Pesquisa algo e posiciona o cursor logo antes do resultado
+ / # Encontra algo a frente do cursor
+ ? # Encontra algo antes do cursor
+
+ # 'Nomes'
+
+ w # Palavra (word)
+ s # Sentência
+ p # Parágrafo
+ b # Bloco
+
+ # Exemplos de comandos
+
+ d2w # Apaga 2 palavras
+ cis # Altera dentro de uma sentência
+ yip # Coloca o parágrafo atual da área de transferência)
+ ct< # Altera para '<'
+ # Altera todo o texto a partir da posição do cursor até o próximo '<'
+ d$ # Apaga tudo da posição do cursor até o final da linha
+```
+
+## Alguns atalhos e dicas
+
+ <!--TODO: Adicionar mais!-->
+```
+ > # Adiciona um bloco de indentação
+ < # Remove um bloco de indentação
+ :earlier 15m # Reverte o documento para como ele estava há 15 minutos atrás
+ :later 15m # Reverte o comando acima
+ ddp # Troca linhas consecutivas de posição, dd e depois p
+ . # Repete a última ação
+```
+
+## Macros
+
+Macros, basicamente, são ações graváveis.
+Quando você começa a gravar uma macro, ele salva **toda** ação e comando
+que você usar, até que você pare de gravar. Ao executar uma macro, ele aplica
+exatamente a mesma sequencia de ações e comandos na seleção atual.
+
+```
+ qa # Inicia a gravação de uma macro chamado 'a'
+ q # Para a gravação
+ @a # Executa a macro
+```
+
+### Configurando o ~/.vimrc
+
+O arquivo .vimrc pode ser usado para configurar o Vim no seu início.
+
+Exemplo de arquivo ~/.vimrc
+
+```
+" Exemplo de ~/.vimrc
+" 2015.10
+
+" Obrigatório para rodar apenas no Vim (Vi Improved)
+set nocompatible
+
+" Determina o tipo de arquivo pelo nome para habilitar indentação automática, etc
+filetype indent plugin on
+
+" Habilita sintaxe colorida
+syntax on
+
+" Ativa um 'auto-completar' melhor para a linha de comando
+set wildmenu
+
+" Faz as buscas não diferenciarem maiúsculas-minúsculas (case insensitive)
+" Exceto quando você usar letras maiúsculas
+set ignorecase
+set smartcase
+
+" Quando criar uma nova linha e a indentação por tipo de arquivo estiver
+" desabilitada, mantem a mesma indentação da linha atual
+set autoindent
+
+" Mostra o número das linhas à esquerda
+set number
+
+" Opções de indentação, aqui você pode mudar como preferir
+
+" Número de espaços visíveis por TAB
+set tabstop=4
+
+" Número de espaços por TAB ao editar um arquivo
+set softtabstop=4
+
+" Número de espaços usados nas funções de indentação (>> e <<)
+set shiftwidth=4
+
+" Converte TABs em espaços
+set expandtab
+
+" Habilita indentação/alinhamento inteligente
+set smarttab
+```
+
+### Referências
+
+[Vim | Home](http://www.vim.org/index.php) (EN)
+
+`$ vimtutor pt`
+
+[Vim: um tutorial/cartilha](https://danielmiessler.com/study/vim/) (EN)
+
+[O que são as partes sombrias do Vim que sua mãe nunca te explicou? (tópico no Stack Overflow)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about) (EN)
+
+[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim) (EN)
diff --git a/pt-pt/git-pt.html.markdown b/pt-pt/git-pt.html.markdown
index a85c9704..bd0f0fc5 100644
--- a/pt-pt/git-pt.html.markdown
+++ b/pt-pt/git-pt.html.markdown
@@ -2,7 +2,7 @@
category: tool
tool: git
lang: pt-pt
-filename: LearnGit.txt
+filename: LearnGit-pt.txt
contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
translators:
diff --git a/pt-pt/swift.html.markdown b/pt-pt/swift.html.markdown
index 2a964bde..9462ee1c 100644
--- a/pt-pt/swift.html.markdown
+++ b/pt-pt/swift.html.markdown
@@ -379,7 +379,7 @@ internal class Rect: Shape {
func shrink() {
if sideLength > 0 {
- --sideLength
+ sideLength -= 1
}
}
diff --git a/pyqt.html.markdown b/pyqt.html.markdown
new file mode 100644
index 00000000..c317db1b
--- /dev/null
+++ b/pyqt.html.markdown
@@ -0,0 +1,82 @@
+---
+category: tool
+tool: PyQT
+filename: learnqt.py
+contributors:
+ - ["Nathan Hughes", "https://github.com/sirsharpest"]
+---
+
+**Qt** is a widely-known framework for developing cross-platform software that can be run on various software and hardware platforms with little or no change in the code, while having the power and speed of native applications. Though **Qt** was originally written in *C++*.
+
+
+This is an adaption on the C++ intro to QT by [Aleksey Kholovchuk](https://github.com/vortexxx192
+), some of the code examples should result in the same functionality
+this version just having been done using pyqt!
+
+```Python
+import sys
+from PyQt4 import QtGui
+
+def window():
+ # Create an application object
+ app = QtGui.QApplication(sys.argv)
+ # Create a widget where our label will be placed in
+ w = QtGui.QWidget()
+ # Add a label to the widget
+ b = QtGui.QLabel(w)
+ # Set some text for the label
+ b.setText("Hello World!")
+ # Give some size and placement information
+ w.setGeometry(100, 100, 200, 50)
+ b.move(50, 20)
+ # Give our window a nice title
+ w.setWindowTitle("PyQt")
+ # Have everything display
+ w.show()
+ # Execute what we have asked for, once all setup
+ sys.exit(app.exec_())
+
+if __name__ == '__main__':
+ window()
+
+```
+
+In order to get some of the more advanced features in **pyqt** we need to start looking at building additional elements.
+Here we show how to introduce a dialog popup box, useful for asking the user to confirm a decision or to provide information.
+
+```Python
+import sys
+from PyQt4.QtGui import *
+from PyQt4.QtCore import *
+
+
+def window():
+ app = QApplication(sys.argv)
+ w = QWidget()
+ # Create a button and attach to widget w
+ b = QPushButton(w)
+ b.setText("Press me")
+ b.move(50, 50)
+ # Tell b to call this function when clicked
+ # notice the lack of "()" on the function call
+ b.clicked.connect(showdialog)
+ w.setWindowTitle("PyQt Dialog")
+ w.show()
+ sys.exit(app.exec_())
+
+# This function should create a dialog window with a button
+# that waits to be clicked and then exits the program
+def showdialog():
+ d = QDialog()
+ b1 = QPushButton("ok", d)
+ b1.move(50, 50)
+ d.setWindowTitle("Dialog")
+ # This modality tells the popup to block the parent whilst it's active
+ d.setWindowModality(Qt.ApplicationModal)
+ # On click I'd like the entire process to end
+ b1.clicked.connect(sys.exit)
+ d.exec_()
+
+if __name__ == '__main__':
+ window()
+```
diff --git a/python3.html.markdown b/python3.html.markdown
index 6b3486a6..9ce7790b 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -38,7 +38,7 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea
8 - 1 # => 7
10 * 2 # => 20
-# Except division which returns floats, real numbers, by default
+# Except division which defaults to rounding down
35 / 5 # => 7.0
# Result of integer division truncated down both for positive and negative.
@@ -47,8 +47,12 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
-# When you use a float, results are floats
-3 * 2.0 # => 6.0
+# When one of the inputs is a float, result is a float
+10.0 / 3 # => 3.3333333333333335
+
+# to force this behavior on integers, use
+from __future__ import division
+10 / 3 # => 3.3333333333333335
# Modulo operation
7 % 3 # => 1
@@ -602,7 +606,7 @@ list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7]
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
# You can construct set and dict comprehensions as well.
-{x for x in 'abcddeef' if x in 'abc'} # => {'d', 'e', 'f'}
+{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}
@@ -761,8 +765,13 @@ if __name__ == '__main__':
print(b.say('hello'))
print(b.fly)
+# To take advantage of modularization by file you could place the classes above in their own files,
+# say, human.py and bat.py
+# to import functions from other files use the following format
# from "filename-without-extension" import "function-or-class"
+
+# superhero.py
from human import Human
from bat import Bat
@@ -887,21 +896,14 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
### Free Online
* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
-* [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/)
-* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
* [Python Course](http://www.python-course.eu/index.php)
* [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](http://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](http://cscircles.cemc.uwaterloo.ca/)
-
-### Dead Tree
-
-* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
-* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
-* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
+* [Dive Into Python 3](http://www.diveintopython3.net/index.html)
+* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718)
diff --git a/qt.html.markdown b/qt.html.markdown
index 71d12909..a9c855a6 100644
--- a/qt.html.markdown
+++ b/qt.html.markdown
@@ -8,9 +8,9 @@ contributors:
lang: en
---
-**Qt** is a widely-known framework for developing cross-platform software that can be run on various software and hardware platforms with little or no change in the code, while having the power and speed of native applications. Though **Qt** was originally written in *C++*, there are its ports to other languages: *PyQt*, *QtRuby*, *PHP-Qt*, etc.
+**Qt** is a widely-known framework for developing cross-platform software that can be run on various software and hardware platforms with little or no change in the code, while having the power and speed of native applications. Though **Qt** was originally written in *C++*, there are its ports to other languages: *[PyQt](https://learnxinyminutes.com/docs/pyqt/)*, *QtRuby*, *PHP-Qt*, etc.
-**Qt** is beautiful for creating applications with graphical user interface (GUI). This tutorial is how to do it in *C++*.
+**Qt** is great for creating applications with graphical user interface (GUI). This tutorial is how to do it in *C++*.
```c++
/*
@@ -83,7 +83,7 @@ Notice that *QObject::connect* part. This method is used to connect *SIGNALS* of
**Slots** are *actions* that might be performed in response to received signals.
-[READ MORE ABOUT SLOTS AND SIGNALS](http://doc.qt.io/qt-4.8/signalsandslots.html)
+[READ MORE ABOUT SLOTS AND SIGNALS](http://doc.qt.io/qt-5/signalsandslots.html)
Next, let's learn that we can not only use standard widgets but also extend their behaviour using inheritance. Let's create a button and count how many times it was pressed. For this purpose we define our own class *CounterLabel*. It must be declared in separate file because of specific Qt architecture.
@@ -149,9 +149,11 @@ int main(int argc, char *argv[]) {
}
```
-## Furter reading
-That's it! Of course Qt framework is much much larger than the part that was covered in this tutorial, so be ready to read and practice.
+That's it! Of course, Qt framework is much much larger than the part that was covered in this tutorial, so be ready to read and practice.
-[READ MORE ABOUT QT](http://doc.qt.io/qt-4.8/tutorials.html)
+## Further reading
-Good luck and have fun
+- [Qt 4.8 tutorials](http://doc.qt.io/qt-4.8/tutorials.html)
+- [Qt 5 tutorials](http://doc.qt.io/qt-5/qtexamplesandtutorials.html)
+
+Good luck and have fun!
diff --git a/ru-ru/binary-search-ru.html.markdown b/ru-ru/binary-search-ru.html.markdown
new file mode 100644
index 00000000..9ed62cb8
--- /dev/null
+++ b/ru-ru/binary-search-ru.html.markdown
@@ -0,0 +1,64 @@
+---
+category: Algorithms & Data Structures
+name: Binary Search
+contributors:
+ - ["Abhishek Jaisingh", "http://github.com/abhishekjiitr"]
+translators:
+ - ["Evan K.", "https://github.com/justblah"]
+lang: ru-ru
+---
+
+# Двоичный (бинарный) поиск
+
+## Зачем использовать двоичный поиск?
+
+Поиск является одной из главных проблем в области вычислительной техники. На сегодняшний день осуществляется более одного триллиона поисковых запросов в год, поэтому нам нужны алгоритмы, которые могут делать это очень быстро. Двоичный поиск является одним из фундаментальных алгоритмов в информатике. Для его изучения мы освоим теорию, а затем используем её для реализации алгоритма.
+
+## Вступление
+
+Самый простой вариант поиска – линейный поиск, но этот подход занимает много времени, и растет линейно, пропорционально набору данных. Пример реализации – начинаем с крайнего левого элемента массива S, один за другим сравниваем искомое значение X с каждым элементом массива S, если X совпадает с элементом S, возвращаем индекс. Если X не совпадает ни с одним из элементов массива S, возвращаем -1.
+
+```
+Линейный поиск: O (n) Линейная сложность
+
+Двоичный поиск: O ( log(n) ) Логарифмическая сложность
+
+```
+```
+def search(arr, x):
+
+ for i in range(len(arr)):
+
+ if arr[i] == x:
+ return i
+
+ return -1
+
+```
+
+## Алгоритм двоичного поиска
+
+Для корректной работы двоичного поиска набор данных для поиска должен быть отсортирован (в любом порядке).
+
+### Алгоритм
+
+```
+Главная идея двоичного поиска заключается в использовании информации о том, что массив уже отсортирован,
+что и позволяет упростить сложность алгоритма до O(Logn). Мы попросту отбрасываем половину элементов набора сразу после одного сравнения.
+1) Сравнить X с элементом в середине набора S.
+2) Если X равен элементу в середине - возвращаем индекс среднего элемента.
+3) Если значение X больше, чем средний элемент набора, значит X находится в правой части набора. Повторяем алгоритм для правой половины набора.
+4) В противном случае (X меньше) повторяем алгоритм для левой половины набора.
+Это и есть рекурсивная реализация двоичного поиска.
+
+```
+
+### На заметку
+
+Существует и другая форма двоичного поиска, которая можеть быть полезна.
+
+## На почитать
+
+* [Проектирование, реализация и примеры](https://ru.wikipedia.org/wiki/%D0%94%D0%B2%D0%BE%D0%B8%D1%87%D0%BD%D1%8B%D0%B9_%D0%BF%D0%BE%D0%B8%D1%81%D0%BA)
+* [Описание алгоритма ИТМО](http://neerc.ifmo.ru/wiki/index.php?title=%D0%A6%D0%B5%D0%BB%D0%BE%D1%87%D0%B8%D1%81%D0%BB%D0%B5%D0%BD%D0%BD%D1%8B%D0%B9_%D0%B4%D0%B2%D0%BE%D0%B8%D1%87%D0%BD%D1%8B%D0%B9_%D0%BF%D0%BE%D0%B8%D1%81%D0%BA)
+* [Ошибки при реализации бинарного поиска](https://habrahabr.ru/post/146228/)
diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown
index 5e967181..ab4be57e 100644
--- a/ru-ru/c-ru.html.markdown
+++ b/ru-ru/c-ru.html.markdown
@@ -145,7 +145,7 @@ int main() {
f1 / f2; // => 0.5, плюс-минус погрешность потому что,
// цифры с плавающей точкой вычисляются неточно!
- // Модуль
+ // Остаток от деления
11 % 3; // => 2
// Операции сравнения вам уже знакомы, но в Си нет булевого типа.
@@ -286,7 +286,7 @@ int main() {
// => Напечатает "8, 4" в 64 битной системе
// Для того, чтобы получить значение по адресу, напечатайте * перед именем.
- // Да, использование * при объявлении указателя и получении значения по адресу
+ // Да, * используется при объявлении указателя и для получении значения по адресу
// немного запутано, но вы привыкнете.
printf("%d\n", *px); // => Напечаатет 0, значение перемененной x
@@ -305,8 +305,9 @@ int main() {
// Объявление указателя на int с адресом массива.
int* x_ptr = x_array;
// x_ptr сейчас указывает на первый элемент массива (со значением 20).
- // Это рабоатет, потому что имя массива возвращает указатель на первый элемент.
- // Например, когда массив передаётся в функцию или назначается указателю, он
+ // Это работает, потому что при обращении к имени массива возвращается
+ // указатель на первый элемент.
+ // Например, когда массив передаётся в функцию или присваивается указателю, он
// невявно преобразуется в указатель.
// Исключения: когда массив является аргументом для оператор '&':
int arr[10];
diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown
index 54499f46..1f1ffce6 100644
--- a/ru-ru/javascript-ru.html.markdown
+++ b/ru-ru/javascript-ru.html.markdown
@@ -359,6 +359,7 @@ myFunc(); // = undefined
// И наоборот, функция может быть присвоена объекту и получать доступ к нему
// через this, даже если она не была прикреплена к нему при объявлении.
var myOtherFunc = function() {
+ return this.myString.toUpperCase();
}
myObj.myOtherFunc = myOtherFunc;
myObj.myOtherFunc(); // = "ПРИВЕТ, МИР!"
diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown
index 42c4d360..b5feb105 100644
--- a/ru-ru/php-ru.html.markdown
+++ b/ru-ru/php-ru.html.markdown
@@ -58,7 +58,8 @@ $int1 = 12; // => 12
$int2 = -12; // => -12
$int3 = 012; // => 10 (ведущий 0 обозначает восьмеричное число)
$int4 = 0x0F; // => 15 (ведущие символы 0x означают шестнадцатеричное число)
-
+// Двоичная запись integer доступна начиная с PHP 5.4.0.
+$int5 = 0b11111111; // 255 (0b в начале означает двоичное число)
// Дробные числа
$float = 1.234;
$float = 1.2e3;
@@ -86,8 +87,9 @@ $dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.'
// Специальные (escape) символы работают только в двойных кавычках
$escaped = "This contains a \t tab character.";
$unescaped = 'This just contains a slash and a t: \t';
-
// Заключайте переменные в фигурные скобки, если это необходимо
+$apples = "I have {$number} apples to eat.";
+$oranges = "I have ${number} oranges to eat.";
$money = "I have $${number} in the bank.";
// Начиная с PHP 5.3, синтаксис nowdocs может использоваться для
@@ -140,11 +142,20 @@ $associative = array('One' => 1, 'Two' => 2, 'Three' => 3);
$associative = ['One' => 1, 'Two' => 2, 'Three' => 3];
echo $associative['One']; // печатает 1
+// Добавить элемент в ассоциативный массив
+$associative['Four'] = 4;
+
// Список тоже содержит целочисленные ключи
$array = ['One', 'Two', 'Three'];
echo $array[0]; // => "One"
+// Добавить элемент в конец массива
+$array[] = 'Four';
+// или
+array_push($array, 'Five');
+// удалить элемент из массива
+unset($array[3]);
/********************************
* Вывод
@@ -184,6 +195,10 @@ $y = 0;
echo $x; // => 2
echo $z; // => 0
+// Вывести тип и значение переменной в stdout
+var_dump($z); // печатает int(0)
+// Напечатать переменную в stdout в удобочитаемом виде
+print_r($array); // печатает: Array ( [0] => One [1] => Two [2] => Three )
/********************************
* Логические выражения
@@ -204,12 +219,21 @@ assert($c > $b); // больше
assert($a <= $b); // меньше или равно
assert($c >= $d); // больше или равно
-// Следующие утверждения истинны, если переменные имеют одинаковый тип.
+// Следующие утверждения истинны, если переменные имеют одинаковые тип.
assert($c === $d);
assert($a !== $d);
assert(1 == '1');
assert(1 !== '1');
+// 'Spaceship' оператор (с PHP 7) используется для сравнения двух выражений.
+// Возвращает -1, 0 или 1, когда выражение слева меньше, равно или больше
+// выражения справа.
+$a = 100;
+$b = 1000;
+
+echo $a <=> $a; // 0, выражения равны
+echo $a <=> $b; // -1, $a < $b
+echo $b <=> $a; // 1, $b > $a
// Переменные могут изменять тип в зависимости от их использования.
$integer = 1;
echo $integer + $integer; // => 2
@@ -265,6 +289,11 @@ if (false) {
// Тернарный оператор
print (false ? 'Does not get printed' : 'Does');
+// сокращенная запись тернарного оператора с PHP 5.3
+// эквивалентно "$x ? $x : 'Does'"
+$x = false;
+print($x ?: 'Does');
+
$x = 0;
if ($x === '0') {
print 'Does not print';
diff --git a/ru-ru/qt-ru.html.markdown b/ru-ru/qt-ru.html.markdown
new file mode 100644
index 00000000..d0a70c9d
--- /dev/null
+++ b/ru-ru/qt-ru.html.markdown
@@ -0,0 +1,158 @@
+---
+category: tool
+tool: Qt Framework
+language: c++
+filename: learnqt-ru.cpp
+contributors:
+ - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"]
+translators:
+ - ["Evan K.", "https://github.com/justblah"]
+lang: ru-ru
+---
+
+**Qt** является широко известным фреймворком для разработки кросс-платформенного программного обеспечения, которое может быть запущено на различных программно-аппаратных платформах практически без изменений в коде, сохраняя при этом мощность и скорость нативных приложений. Хоть **Qt** и был изначально написан на *C++*, у него есть реализации и на других языках: *PyQt*, *QtRuby*, *PHP-Qt* и т.д.
+
+**Qt** отлично подходит для создания приложений с графическим пользовательским интерфейсом (GUI). Это руководство о том, как сделать это на *C++*.
+
+```c++
+/*
+ * Начнём по-старинке
+ */
+
+// все header файлы импортированные из Qt начинаются с заглавной 'Q'
+#include <QApplication>
+#include <QLineEdit>
+
+int main(int argc, char *argv[]) {
+ // создаем объект для управления данными приложения
+ QApplication app(argc, argv);
+
+ // создаем редактируемую строку и отобразим её на экране
+ QLineEdit lineEdit("Hello world!");
+ lineEdit.show();
+
+ // запускаем цикл для обработки событий (event loop)
+ return app.exec();
+}
+```
+
+GUI часть **Qt** полностью состоит из *виджетов* и *связей* между ними.
+
+[(EN) ПОДРОБНЕЕ О ВИДЖЕТАХ](http://doc.qt.io/qt-5/qtwidgets-index.html)
+
+```c++
+/*
+ * В этом примере мы отобразим надпись с кнопкой.
+ * Надпись будет появляться после нажатия на кнопку.
+ *
+ * Код на Qt говорит сам за себя.
+ */
+
+#include <QApplication>
+#include <QDialog>
+#include <QVBoxLayout>
+#include <QPushButton>
+#include <QLabel>
+
+int main(int argc, char *argv[]) {
+ QApplication app(argc, argv);
+
+ QDialog dialogWindow;
+ dialogWindow.show();
+
+ // добавляем вертикальное расположение
+ QVBoxLayout layout;
+ dialogWindow.setLayout(&layout);
+
+ QLabel textLabel("Thanks for pressing that button");
+ layout.addWidget(&textLabel);
+ textLabel.hide();
+
+ QPushButton button("Press me");
+ layout.addWidget(&button);
+
+ // отображаем скрытую надпись после нажатия на кнопку
+ QObject::connect(&button, &QPushButton::pressed,
+ &textLabel, &QLabel::show);
+
+ return app.exec();
+}
+```
+Обратите внимание на метод *QObject::connect*. Этот метод соединяет *СИГНАЛЫ* одного объекта со *СЛОТАМИ* другого.
+
+**Сигналы** отправляются когда с объектами происходят отпределённые события, например, сигнал *нажатие* отправляется когда пользователь нажимает на объект типа QPushButton.
+
+**Слоты** это *действия*, которые могут быть выполнены в ответ на полученные сигналы.
+
+[(EN) ПОДРОБНЕЕ О СЛОТАХ И СИГНАЛАХ](http://doc.qt.io/qt-4.8/signalsandslots.html)
+
+
+Далее рассмотрим, как можно не только использовать стандартные виджеты, но и расширять их поведение с помощью наследования. Давайте создадим кнопку и посчитаем, сколько раз она была нажата. Для этого мы определяем наш собственный класс *CounterLabel*. Он должен быть объявлен в отдельном файле из-за специфической архитектуры Qt.
+
+```c++
+// counterlabel.hpp
+
+#ifndef COUNTERLABEL
+#define COUNTERLABEL
+
+#include <QLabel>
+
+class CounterLabel : public QLabel {
+ Q_OBJECT // макрос Qt, обязателен для всех виджетов
+
+public:
+ CounterLabel() : counter(0) {
+ setText("Counter has not been increased yet"); // метод QLabel
+ }
+
+public slots:
+ // действие, которое будет вызвано в ответ на нажатие
+ void increaseCounter() {
+ setText(QString("Counter value: %1").arg(QString::number(++counter)));
+ }
+
+private:
+ int counter;
+};
+
+#endif // COUNTERLABEL
+```
+
+```c++
+// main.cpp
+// Почти тоже самое, что и в предыдущем примере
+
+#include <QApplication>
+#include <QDialog>
+#include <QVBoxLayout>
+#include <QPushButton>
+#include <QString>
+#include "counterlabel.hpp"
+
+int main(int argc, char *argv[]) {
+ QApplication app(argc, argv);
+
+ QDialog dialogWindow;
+ dialogWindow.show();
+
+ QVBoxLayout layout;
+ dialogWindow.setLayout(&layout);
+
+ CounterLabel counterLabel;
+ layout.addWidget(&counterLabel);
+
+ QPushButton button("Push me once more");
+ layout.addWidget(&button);
+ QObject::connect(&button, &QPushButton::pressed,
+ &counterLabel, &CounterLabel::increaseCounter);
+
+ return app.exec();
+}
+```
+
+## На почитать
+Это всё! Конечно, фреймворк Qt намного объемнее, чем часть, которая была рассмотрена в этом руководстве, так что будьте готовы читать и практиковаться.
+
+[(EN) ДОКУМЕНТАЦИЯ](http://wiki.qt.io/Main/ru)
+
+Удачи!
diff --git a/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown
index 77987bb3..7ff660e1 100644
--- a/ru-ru/swift-ru.html.markdown
+++ b/ru-ru/swift-ru.html.markdown
@@ -4,9 +4,11 @@ contributors:
- ["Grant Timmerman", "http://github.com/grant"]
- ["Christopher Bess", "http://github.com/cbess"]
- ["Joey Huang", "http://github.com/kamidox"]
+ - ["Alexey Nazaroff", "http://github.com/rogaven"]
filename: learnswift-ru.swift
translators:
- ["Dmitry Bessonov", "https://github.com/TheDmitry"]
+ - ["Alexey Nazaroff", "https://github.com/rogaven"]
lang: ru-ru
---
@@ -21,6 +23,8 @@ Swift - это язык программирования, созданный к
Смотрите еще [начальное руководство](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html) Apple, которое содержит полное учебное пособие по Swift.
```swift
+// Версия Swift: 3.0
+
// импорт модуля
import UIKit
@@ -31,10 +35,14 @@ import UIKit
// Xcode поддерживает маркеры, чтобы давать примечания своему коду
// и вносить их в список обозревателя (Jump Bar)
// MARK: Метка раздела
+// MARK: - Метка с разделителем
// TODO: Сделайте что-нибудь вскоре
// FIXME: Исправьте этот код
-println("Привет, мир")
+// Начиная со второй версии Swift, println и print объединены в методе print.
+// Перенос строки теперь добавляется в конец автоматически.
+print("Привет, мир!") // println – теперь просто print
+print("Привет, мир!", terminator: "") // вывод текста без переноса строки
// переменные (var), значение которых можно изменить после инициализации
// константы (let), значение которых нельзя изменить после инициализации
@@ -56,12 +64,12 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Вставка переменны
// Сборка особых значений
// используя ключ -D сборки конфигурации
#if false
- println("Не печатается")
+ print("Не печатается")
let buildValue = 3
#else
let buildValue = 7
#endif
-println("Значение сборки: \(buildValue)") // Значение сборки: 7
+print("Значение сборки: \(buildValue)") // Значение сборки: 7
/*
Опционалы - это особенность языка Swift, которая допускает вам сохранять
@@ -79,35 +87,45 @@ var someOptionalString2: Optional<String> = "опционал"
if someOptionalString != nil {
// я не nil
if someOptionalString!.hasPrefix("opt") {
- println("содержит префикс")
+ print("содержит префикс")
}
-
+
let empty = someOptionalString?.isEmpty
}
someOptionalString = nil
+/*
+Использование ! для доступа к несуществующему опциональному значению генерирует
+рантайм ошибку. Всегда проверяйте, что опционал содержит не пустое значение,
+перед тем как раскрывать его через !.
+*/
+
// неявная развертка опциональной переменной
var unwrappedString: String! = "Ожидаемое значение."
// как и выше, только ! - постфиксный оператор (с еще одним синтаксическим сахаром)
var unwrappedString2: ImplicitlyUnwrappedOptional<String> = "Ожидаемое значение."
+// If let конструкции -
+// If let это специальная конструкция в Swift, которая позволяет проверить Optional
+// справа от `=` непустой, и если это так - разворачивает его и присваивает левой части.
if let someOptionalStringConstant = someOptionalString {
- // имеется некоторое значение, не nil
+ // имеется некоторое (`Some`) значение, не `nil`
if !someOptionalStringConstant.hasPrefix("ok") {
// нет такого префикса
}
}
// Swift поддерживает сохранение значения любого типа
+// Для этих целей есть два ключевых слова `Any` и `AnyObject`
// AnyObject == id
-// В отличие от `id` в Objective-C, AnyObject работает с любым значением (Class,
-// Int, struct и т.д.)
-var anyObjectVar: AnyObject = 7
-anyObjectVar = "Изменять значение на строку не является хорошей практикой, но возможно."
+// `Any` же, в отличие от `id` в Objective-C, `Any` работает с любым значением (Class, Int, struct и т.д.)
+var anyVar: Any = 7
+anyVar = "Изменять значение на строку не является хорошей практикой, но возможно."
+let anyObjectVar: AnyObject = Int(1) as NSNumber
/*
Комментируйте здесь
-
+
/*
Вложенные комментарии тоже поддерживаются
*/
@@ -129,6 +147,7 @@ shoppingList[1] = "бутылка воды"
let emptyArray = [String]() // let == неизменный
let emptyArray2 = Array<String>() // как и выше
var emptyMutableArray = [String]() // var == изменяемый
+var explicitEmptyMutableStringArray: [String] = [] // так же как и выше
// Словарь
@@ -140,31 +159,39 @@ occupations["Jayne"] = "Связи с общественностью"
let emptyDictionary = [String: Float]() // let == неизменный
let emptyDictionary2 = Dictionary<String, Float>() // как и выше
var emptyMutableDictionary = [String: Float]() // var == изменяемый
+var explicitEmptyMutableDictionary: [String: Float] = [:] // то же
//
// MARK: Поток управления
//
+// С помощью "," можно указать дополнительные условия для раскрытия
+// опциональных значений.
+let someNumber = Optional<Int>(7)
+if let num = someNumber, num > 3 {
+ print("Больше 3х")
+}
+
// цикл for для массива
let myArray = [1, 1, 2, 3, 5]
for value in myArray {
if value == 1 {
- println("Один!")
+ print("Один!")
} else {
- println("Не один!")
+ print("Не один!")
}
}
// цикл for для словаря
var dict = ["один": 1, "два": 2]
for (key, value) in dict {
- println("\(key): \(value)")
+ print("\(key): \(value)")
}
// цикл for для диапазона чисел
for i in -1...shoppingList.count {
- println(i)
+ print(i)
}
shoppingList[1...2] = ["бифштекс", "орехи пекан"]
// используйте ..< для исключения последнего числа
@@ -176,8 +203,8 @@ while i < 1000 {
}
// цикл do-while
-do {
- println("привет")
+repeat {
+ print("привет")
} while 1 == 2
// Переключатель
@@ -204,7 +231,7 @@ default: // обязательный (чтобы предусмотреть вс
// Функции являются типом первого класса, т.е. они могут быть вложены в функциях
// и могут передаваться между собой
-// Функция с документированным заголовком Swift (формат reStructedText)
+// Функция с документированным заголовком Swift (формат Swift-модифицированный Markdown)
/**
Операция приветствия
@@ -212,20 +239,20 @@ default: // обязательный (чтобы предусмотреть вс
- Маркер в документировании
- Еще один маркер в документации
- :param: name - это имя
- :param: day - это день
- :returns: Строка, содержащая значения name и day.
+ - Parameter name : Это имя
+ - Parameter day : Это день
+ - Returns : Строка, содержащая значения name и day.
*/
func greet(name: String, day: String) -> String {
return "Привет \(name), сегодня \(day)."
}
-greet("Боб", "вторник")
+greet(name: "Боб", day: "вторник")
// как и выше, кроме обращения параметров функции
-func greet2(#requiredName: String, externalParamName localParamName: String) -> String {
- return "Привет \(requiredName), сегодня \(localParamName)"
+func greet2(name: String, externalParamName localParamName: String) -> String {
+ return "Привет \(name), сегодня \(localParamName)"
}
-greet2(requiredName:"Иван", externalParamName: "воскресенье")
+greet2(name: "Иван", externalParamName: "Воскресенье")
// Функция, которая возвращает множество элементов в кортеже
func getGasPrices() -> (Double, Double, Double) {
@@ -235,8 +262,31 @@ let pricesTuple = getGasPrices()
let price = pricesTuple.2 // 3.79
// Пропускайте значения кортежей с помощью подчеркивания _
let (_, price1, _) = pricesTuple // price1 == 3.69
-println(price1 == pricesTuple.1) // вывод: true
-println("Цена газа: \(price)")
+print(price1 == pricesTuple.1) // вывод: true
+print("Цена газа: \(price)")
+
+// Именованные параметры кортежа
+func getGasPrices2() -> (lowestPrice: Double, highestPrice: Double, midPrice: Double) {
+ return (1.77, 37.70, 7.37)
+}
+let pricesTuple2 = getGasPrices2()
+let price2 = pricesTuple2.lowestPrice
+let (_, price3, _) = pricesTuple2
+print(pricesTuple2.highestPrice == pricesTuple2.1) // вывод: true
+print("Самая высокая цена за газ: \(pricesTuple2.highestPrice)")
+
+// guard утверждения
+func testGuard() {
+ // guards обеспечивают прерывание дальнейшего выполнения функции,
+ // позволяя держать обработчики ошибок рядом с проверкой условия
+ // Объявляемая переменная находится в той же области видимости, что и guard.
+ guard let aNumber = Optional<Int>(7) else {
+ return
+ }
+
+ print("число равно \(aNumber)")
+}
+testGuard()
// Переменное число аргументов
func setup(numbers: Int...) {
@@ -246,7 +296,7 @@ func setup(numbers: Int...) {
}
// Передача и возврат функций
-func makeIncrementer() -> (Int -> Int) {
+func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
@@ -256,15 +306,15 @@ var increment = makeIncrementer()
increment(7)
// передача по ссылке
-func swapTwoInts(inout a: Int, inout b: Int) {
+func swapTwoInts(a: inout Int, b: inout Int) {
let tempA = a
a = b
b = tempA
}
var someIntA = 7
var someIntB = 3
-swapTwoInts(&someIntA, &someIntB)
-println(someIntB) // 7
+swapTwoInts(a: &someIntA, b: &someIntB)
+print(someIntB) // 7
//
@@ -291,13 +341,13 @@ numbers = numbers.map({ number in 3 * number })
print(numbers) // [3, 6, 18]
// Хвостовое замыкание
-numbers = sorted(numbers) { $0 > $1 }
+numbers = numbers.sorted { $0 > $1 }
print(numbers) // [18, 6, 3]
// Суперсокращение, поскольку оператор < выполняет логический вывод типов
-numbers = sorted(numbers, < )
+numbers = numbers.sorted(by: <)
print(numbers) // [3, 6, 18]
@@ -307,8 +357,8 @@ print(numbers) // [3, 6, 18]
// Структуры и классы имеют очень похожие характеристики
struct NamesTable {
- let names = [String]()
-
+ let names: [String]
+
// Пользовательский индекс
subscript(index: Int) -> String {
return names[index]
@@ -316,9 +366,48 @@ struct NamesTable {
}
// У структур автогенерируемый (неявно) инициализатор
-let namesTable = NamesTable(names: ["Me", "Them"])
+let namesTable = NamesTable(names: ["Иван", "Яков"])
let name = namesTable[1]
-println("Name is \(name)") // Name is Them
+print("Имя :\(name)") // Имя: Яков
+
+//
+// MARK: Обработка ошибок
+//
+
+// Протокол `Error` используется для перехвата выбрасываемых ошибок
+enum MyError: Error {
+ case BadValue(msg: String)
+ case ReallyBadValue(msg: String)
+}
+
+// фунции помеченные словом `throws` должны вызываться с помощью `try`
+func fakeFetch(value: Int) throws -> String {
+ guard 7 == value else {
+ throw MyError.ReallyBadValue(msg: "Действительно плохое значение")
+ }
+
+ return "тест"
+}
+
+func testTryStuff() {
+ // предполагается, что не будет выброшено никаких ошибок,
+ // в противном случае мы получим рантайм исключение
+ let _ = try! fakeFetch(value: 7)
+
+ // Если возникает ошибка, то выполнение продолжится. Но если значение равно nil,
+ // то результат будет опционалом
+ let _ = try? fakeFetch(value: 7)
+
+ do {
+ // обычно try оператор, позволяющий обработать ошибку в `catch` блоке
+ try fakeFetch(value: 1)
+ } catch MyError.BadValue(let msg) {
+ print("Ошибка: \(msg)")
+ } catch {
+ // все остальное
+ }
+}
+testTryStuff()
//
// MARK: Классы
@@ -329,7 +418,7 @@ println("Name is \(name)") // Name is Them
public class Shape {
public func getArea() -> Int {
- return 0;
+ return 0
}
}
@@ -339,7 +428,7 @@ public class Shape {
internal class Rect: Shape {
var sideLength: Int = 1
-
+
// Пользовательский сеттер и геттер
private var perimeter: Int {
get {
@@ -350,12 +439,17 @@ internal class Rect: Shape {
sideLength = newValue / 4
}
}
-
+
+ // Вычисляемые свойства должны быть объявлены с помощью `var`, ведь они могут меняться
+ var smallestSideLength: Int {
+ return self.sideLength - 1
+ }
+
// Ленивая загрузка свойства
// свойство subShape остается равным nil (неинициализированным),
// пока не вызовется геттер
lazy var subShape = Rect(sideLength: 4)
-
+
// Если вам не нужны пользовательские геттеры и сеттеры,
// но все же хотите запустить код перед и после вызовов геттера или сеттера
// свойств, вы можете использовать `willSet` и `didSet`
@@ -365,19 +459,19 @@ internal class Rect: Shape {
print(someIdentifier)
}
}
-
+
init(sideLength: Int) {
self.sideLength = sideLength
// последним всегда вызывается super.init, когда init с параметрами
super.init()
}
-
+
func shrink() {
if sideLength > 0 {
- --sideLength
+ sideLength -= 1
}
}
-
+
override func getArea() -> Int {
return sideLength * sideLength
}
@@ -400,7 +494,7 @@ let aShape = mySquare as Shape
// сравнение экземпляров, в отличие от ==, которая проверяет эквивалентность
if mySquare === mySquare {
- println("Ага, это mySquare")
+ print("Ага, это mySquare")
}
// Опциональная инициализация (init)
@@ -409,13 +503,13 @@ class Circle: Shape {
override func getArea() -> Int {
return 3 * radius * radius
}
-
+
// Поместите постфиксный знак вопроса после `init` - это и будет опциональная инициализация,
// которая может вернуть nil
init?(radius: Int) {
self.radius = radius
super.init()
-
+
if radius <= 0 {
return nil
}
@@ -423,13 +517,13 @@ class Circle: Shape {
}
var myCircle = Circle(radius: 1)
-println(myCircle?.getArea()) // Optional(3)
-println(myCircle!.getArea()) // 3
+print(myCircle?.getArea()) // Optional(3)
+print(myCircle!.getArea()) // 3
var myEmptyCircle = Circle(radius: -1)
-println(myEmptyCircle?.getArea()) // "nil"
+print(myEmptyCircle?.getArea()) // "nil"
if let circle = myEmptyCircle {
// не будет выполняться, поскольку myEmptyCircle равен nil
- println("circle не nil")
+ print("circle не nil")
}
@@ -456,12 +550,13 @@ enum Suit {
// указывать тип перечисления, когда переменная объявляется явно
var suitValue: Suit = .Hearts
-// Нецелочисленные перечисления требуют прямого указания значений
+// Значения нецелочисленных перечислений должны быть указаны явно
+// или могут выводится с помощью функции `rawValue` из имени
enum BookName: String {
- case John = "Иоанн"
+ case John
case Luke = "Лука"
}
-println("Имя: \(BookName.John.rawValue)")
+print("Имя: \(BookName.John.rawValue)")
// Перечисление (enum) со связанными значениями
enum Furniture {
@@ -469,7 +564,7 @@ enum Furniture {
case Desk(height: Int)
// Связать с типами String и Int
case Chair(String, Int)
-
+
func description() -> String {
switch self {
case .Desk(let height):
@@ -481,9 +576,9 @@ enum Furniture {
}
var desk: Furniture = .Desk(height: 80)
-println(desk.description()) // "Письменный стол высотой 80 см."
+print(desk.description()) // "Письменный стол высотой 80 см."
var chair = Furniture.Chair("Foo", 40)
-println(chair.description()) // "Стул марки Foo высотой 40 см."
+print(chair.description()) // "Стул марки Foo высотой 40 см."
//
@@ -500,23 +595,24 @@ protocol ShapeGenerator {
}
// Протоколы, объявленные с @objc, допускают необязательные функции,
-// которые позволяют вам проверять на соответствие
+// которые позволяют вам проверять на соответствие. Для функций также необходимо указать @objc
@objc protocol TransformShape {
- optional func reshaped()
- optional func canReshape() -> Bool
+ @objc optional func reshape()
+ @objc optional func canReshape() -> Bool
}
class MyShape: Rect {
var delegate: TransformShape?
-
+
func grow() {
sideLength += 2
+
// Размещайте знак вопроса перед опционным свойством, методом
// или индексом, чтобы не учитывать nil-значение и возвратить nil
// вместо выбрасывания ошибки выполнения (т.н. "опционная цепочка")
- if let allow = self.delegate?.canReshape?() {
+ if let reshape = self.delegate?.canReshape?(), reshape {
// проверка делегата на выполнение метода
- self.delegate?.reshaped?()
+ self.delegate?.reshape?()
}
}
}
@@ -528,42 +624,42 @@ class MyShape: Rect {
// `extension`s: Добавляет расширенный функционал к существующему типу
-// Класс Square теперь "соответствует" протоколу `Printable`
-extension Square: Printable {
+// Класс Square теперь "соответствует" протоколу `CustomStringConvertible`
+extension Square: CustomStringConvertible {
var description: String {
return "Площадь: \(self.getArea()) - ID: \(self.identifier)"
}
}
-println("Объект Square: \(mySquare)")
+print("Объект Square: \(mySquare)")
// Вы также можете расширить встроенные типы
extension Int {
var customProperty: String {
return "Это \(self)"
}
-
+
func multiplyBy(num: Int) -> Int {
return num * self
}
}
-println(7.customProperty) // "Это 7"
-println(14.multiplyBy(3)) // 42
+print(7.customProperty) // "Это 7"
+print(14.multiplyBy(num: 3)) // 42
// Обобщения: Подобно языкам Java и C#. Используйте ключевое слово `where`,
// чтобы определить условия обобщений.
func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
- for (index, value) in enumerate(array) {
+ for (index, value) in array.enumerated() {
if value == valueToFind {
return index
}
}
return nil
}
-let foundAtIndex = findIndex([1, 2, 3, 4], 3)
-println(foundAtIndex == 2) // вывод: true
+let foundAtIndex = findIndex(array: [1, 2, 3, 4], valueToFind: 3)
+print(foundAtIndex == 2) // вывод: true
// Операторы:
// Пользовательские операторы могут начинаться с символов:
@@ -571,19 +667,33 @@ println(foundAtIndex == 2) // вывод: true
// или
// Unicode- знаков математики, символов, стрелок, декорации и линий/кубов,
// нарисованных символов.
-prefix operator !!! {}
+prefix operator !!!
// Префиксный оператор, который утраивает длину стороны, когда используется
-prefix func !!! (inout shape: Square) -> Square {
+prefix func !!! (shape: inout Square) -> Square {
shape.sideLength *= 3
return shape
}
// текущее значение
-println(mySquare.sideLength) // 4
+print(mySquare.sideLength) // 4
// Используя пользовательский оператор !!!, изменится длина стороны
// путем увеличения размера в 3 раза
!!!mySquare
-println(mySquare.sideLength) // 12
+print(mySquare.sideLength) // 12
+
+// Операторы также могут быть обобщенными
+infix operator <->
+func <-><T: Equatable> (a: inout T, b: inout T) {
+ let c = a
+ a = b
+ b = c
+}
+
+var foo: Float = 10
+var bar: Float = 20
+
+foo <-> bar
+print("foo это \(foo), bar это \(bar)") // "foo = 20.0, bar = 10.0"
```
diff --git a/rust-pt.html.markdown b/rust-pt.html.markdown
new file mode 100644
index 00000000..79f69269
--- /dev/null
+++ b/rust-pt.html.markdown
@@ -0,0 +1,332 @@
+---
+language: rust
+filename: rust-pt.rs
+contributors:
+ - ["Paulo Henrique Rodrigues Pinheiro", "https://about.me/paulohrpinheiro"]
+filename: learnrust.rs
+lang: pt-br
+---
+
+Rust é uma linguagem de programação desenvolvida pelo Mozilla Research. Rust
+combina controle de baixo nível sobre o desempenho com facilidades de alto
+nível e garantias de segurança.
+
+Ele atinge esse objetico sem necessitar de um coletor de lixo ou um processo
+*runtime*, permitindo que se use bibliotecas Rust em substituição a bibliotecas
+em C.
+
+A primeira versão de Rust, 0.1, apareceu em janeiro de 2012, e por três anos o
+desenvolvimento correu tão rapidamente que que até recentemente o uso de
+versões estáveis foi desencorajado e em vez disso a recomendação era usar as
+versões empacotadas toda noite.
+
+Em 15 de maio de 2015, a versão 1.0 de Rust foi liberada com a garantia total
+de compatibilidade reversa. Melhorias no tempo de compilação e em outros
+aspectos do compilador estão disponíveis atualmente nas versões empacotadas à
+noite. Rust adotou um modelo de versões *train-based* com novas versões
+regularmente liberadas a cada seis semanas. A versão 1.1 beta de Rust foi
+disponibilizada ao mesmo tempo que a versão 1.0.
+
+Apesar de Rust ser uma linguagem mais e baixo nível, Rust tem alguns conceitos
+funcionais geralmente encontradas em linguagens de alto nível. Isso faz Rust
+não apenas rápido, mas também fácil e eficiente para programar.
+
+```rust
+// Isso é um comentário. Linhas de comentários são assim...
+// e múltiplas linhas se parecem assim.
+
+/// Comentários para documentação são assim e permitem notação em markdown.
+/// # Exemplos
+///
+/// ```
+/// let five = 5
+/// ```
+
+///////////////
+// 1. Básico //
+///////////////
+
+// Funções
+// `i32` é o tipo para inteiros com sinal de 32 bits
+fn add2(x: i32, y: i32) -> i32 {
+ // Implicit return (no semicolon)
+ x + y
+}
+
+// Função main
+fn main() {
+ // Números //
+
+ // Immutable bindings
+ let x: i32 = 1;
+
+ // Inteiros/Sufixos para ponto flutuante
+ let y: i32 = 13i32;
+ let f: f64 = 1.3f64;
+
+ // Inferência de tipos
+ // Em geral, o compilador Rust consegue inferir qual o tipo de uma
+ // variável, então você não tem que escrever uma anotação explícita de tipo.
+ // Ao longo desse tutorial, os tipos serão explicitamente anotados em
+ // muitos lugares, mas apenas com propóstico demonstrativo. A inferência de
+ // tipos pode gerenciar isso na maioria das vezes.
+ let implicit_x = 1;
+ let implicit_f = 1.3;
+
+ // Aritmética
+ let sum = x + y + 13;
+
+ // Variáveis mutáveis
+ let mut mutable = 1;
+ mutable = 4;
+ mutable += 2;
+
+ // Strings //
+
+ // String literais
+ let x: &str = "hello world!";
+
+ // Imprimindo
+ println!("{} {}", f, x); // 1.3 hello world
+
+ // Uma `String` – uma String alocada no heap
+ let s: String = "hello world".to_string();
+
+ // Uma String slice - uma visão imutável em outra string.
+ // Basicamente, isso é um par imutável de ponteiros para uma string - ele
+ // não contém o conteúdo de uma strinf, apenas um ponteiro para o começo e
+ // um ponteiro para o fim da área de memória para a string, estaticamente
+ // alocada ou contida em outro objeto (nesse caso, `s`)
+ let s_slice: &str = &s;
+
+ println!("{} {}", s, s_slice); // hello world hello world
+
+ // Vetores/arrays //
+
+ // Um array de tamanho fixo
+ let four_ints: [i32; 4] = [1, 2, 3, 4];
+
+ // Um array dinâmico (vetor)
+ let mut vector: Vec<i32> = vec![1, 2, 3, 4];
+ vector.push(5);
+
+ // Uma fatia – uma visão imutável em um vetor ou array
+ // Isso é como um string slice, mas para vetores
+ let slice: &[i32] = &vector;
+
+ // Use `{:?}` para imprimir alguma coisa no estilo de depuração
+ println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
+
+ // Tuplas //
+
+ // Uma tupla é um conjunto de tamanho fixo de valores de tipos
+ // possivelmente diferentes
+ let x: (i32, &str, f64) = (1, "hello", 3.4);
+
+ // Desestruturando `let`
+ let (a, b, c) = x;
+ println!("{} {} {}", a, b, c); // 1 hello 3.4
+
+ // Indexando
+ println!("{}", x.1); // hello
+
+ //////////////
+ // 2. Tipos //
+ //////////////
+
+ // Struct
+ struct Point {
+ x: i32,
+ y: i32,
+ }
+
+ let origin: Point = Point { x: 0, y: 0 };
+
+ // Uma estrutura com campos sem nome, chamada 'estrutura em tupla'
+ struct Point2(i32, i32);
+
+ let origin2 = Point2(0, 0);
+
+ // enum básico com na linguagem C
+ enum Direction {
+ Left,
+ Right,
+ Up,
+ Down,
+ }
+
+ let up = Direction::Up;
+
+ // Enum com campos
+ enum OptionalI32 {
+ AnI32(i32),
+ Nothing,
+ }
+
+ let two: OptionalI32 = OptionalI32::AnI32(2);
+ let nothing = OptionalI32::Nothing;
+
+ // Generics //
+
+ struct Foo<T> { bar: T }
+
+ // Isso é definido na biblioteca padrão como um `Option`
+ enum Optional<T> {
+ SomeVal(T),
+ NoVal,
+ }
+
+ // Methods //
+
+ impl<T> Foo<T> {
+ // Métodos recebem um parâmetro `self` explícito
+ fn get_bar(self) -> T {
+ self.bar
+ }
+ }
+
+ let a_foo = Foo { bar: 1 };
+ println!("{}", a_foo.get_bar()); // 1
+
+ // Traits (conhecidos como interfaces ou typeclasses em outras linguagens)//
+
+ trait Frobnicate<T> {
+ fn frobnicate(self) -> Option<T>;
+ }
+
+ impl<T> Frobnicate<T> for Foo<T> {
+ fn frobnicate(self) -> Option<T> {
+ Some(self.bar)
+ }
+ }
+
+ let another_foo = Foo { bar: 1 };
+ println!("{:?}", another_foo.frobnicate()); // Some(1)
+
+ //////////////////////////////////
+ // 3. Reconhecimento de padrões //
+ //////////////////////////////////
+
+ let foo = OptionalI32::AnI32(1);
+ match foo {
+ OptionalI32::AnI32(n) => println!("it’s an i32: {}", n),
+ OptionalI32::Nothing => println!("it’s nothing!"),
+ }
+
+ // Reconhecimento avançado de padrões
+ struct FooBar { x: i32, y: OptionalI32 }
+ let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) };
+
+ match bar {
+ FooBar { x: 0, y: OptionalI32::AnI32(0) } =>
+ println!("The numbers are zero!"),
+ FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m =>
+ println!("The numbers are the same"),
+ FooBar { x: n, y: OptionalI32::AnI32(m) } =>
+ println!("Different numbers: {} {}", n, m),
+ FooBar { x: _, y: OptionalI32::Nothing } =>
+ println!("The second number is Nothing!"),
+ }
+
+ //////////////////////////
+ // 4. Controle de fluxo //
+ //////////////////////////
+
+ // `for` laços de repetição/iteração
+ let array = [1, 2, 3];
+ for i in array.iter() {
+ println!("{}", i);
+ }
+
+ // Ranges
+ for i in 0u32..10 {
+ print!("{} ", i);
+ }
+ println!("");
+ // prints `0 1 2 3 4 5 6 7 8 9 `
+
+ // `if`
+ if 1 == 1 {
+ println!("Maths is working!");
+ } else {
+ println!("Oh no...");
+ }
+
+ // `if` como expressão
+ let value = if true {
+ "good"
+ } else {
+ "bad"
+ };
+
+ // laço `while` de repetição
+ while 1 == 1 {
+ println!("The universe is operating normally.");
+ }
+
+ // Repetição infinita
+ loop {
+ println!("Hello!");
+ }
+
+ ////////////////////////////////////////
+ // 5. Proteção de memória & ponteiros //
+ ////////////////////////////////////////
+
+ // Ponteiro com dono - somente uma coisa pode 'possuir' esse ponteiro por
+ // vez.
+ // Isso significa que quando `Box` perde seu escopo, ele pode ser
+ // automaticamente desalocado com segurança.
+ let mut mine: Box<i32> = Box::new(3);
+ *mine = 5; // dereference
+ // Aqui, `now_its_mine` possui o controle exclusivo de `mine`. Em outras
+ // palavras, `mine` tem o controle transferido.
+ let mut now_its_mine = mine;
+ *now_its_mine += 2;
+
+ println!("{}", now_its_mine); // 7
+ // println!("{}", mine); // não compila porque `now_its_mine` é o dono
+
+ // Referência - um ponteiro imutável que referencia outro dado
+ // Quando uma referência é dada a um valor, nós dizemos que o valor foi
+ // emprestado 'borrowed'.
+ // Quando um valor é emprestado sem ser mutável, ele não pode ser alterado
+ // ou ter a sua propriedade transferida.
+ // Um empréstimo finaliza quando o escopo em que ele foi criado termina.
+
+ let mut var = 4;
+ var = 3;
+ let ref_var: &i32 = &var;
+
+ println!("{}", var); // AO contrário de `mine`, `var` ainda pode ser usado
+ println!("{}", *ref_var);
+ // var = 5; // não compila porque `var` é emprestado
+ // *ref_var = 6; // não compila, porque `ref_var` é uma referência imutável
+
+ // Referência mutável
+ // Quando um valor mutável é emprestado, ele não pode ser acessado.
+ let mut var2 = 4;
+ let ref_var2: &mut i32 = &mut var2;
+ *ref_var2 += 2; // '*' aponta para var2, que é mutável e emprestada
+
+ println!("{}", *ref_var2); // 6 , // var2 não compila.
+ // ref_var2 é do tipo &mut i32, que guarda uma referência i32, não o valor.
+ // var2 = 2; // não compila porque `var2` é empretada.
+}
+```
+
+## Outras leituras
+
+Existe muita coisa sobre Rust - isto aqui é apenas o básico para que você possa
+entender as coisas mais importantes. Para aprender mais sobre Rust, leia [The
+Rust Programming Language](http://doc.rust-lang.org/book/index.html) e
+acompanhe [/r/rust](http://reddit.com/r/rust). A galera no canal #rust do
+irc.mozilla.org também estão sempre dispostos a ajudar os novatos.
+
+Você pode brincar com outras característica de Rust com um compilador online
+no portal oficial do projeto [Rust playpen](http://play.rust-lang.org), or ler
+mais na página oficial [Rust website](http://rust-lang.org).
+
+No Brasil acompanhe os encontros do [Meetup Rust São Paulo]
+(http://www.meetup.com/pt-BR/Rust-Sao-Paulo-Meetup/).
+
diff --git a/rust.html.markdown b/rust.html.markdown
index f1b62ef4..6b75fa87 100644
--- a/rust.html.markdown
+++ b/rust.html.markdown
@@ -286,7 +286,7 @@ fn main() {
var = 3;
let ref_var: &i32 = &var;
- println!("{}", var); // Unlike `box`, `var` can still be used
+ println!("{}", var); // Unlike `mine`, `var` can still be used
println!("{}", *ref_var);
// var = 5; // this would not compile because `var` is borrowed
// *ref_var = 6; // this would not either, because `ref_var` is an immutable reference
diff --git a/sass.html.markdown b/sass.html.markdown
index 802b40f4..860e550a 100644
--- a/sass.html.markdown
+++ b/sass.html.markdown
@@ -95,7 +95,7 @@ Useful for checking variables while debugging your SCSS. */
/* @for is a control loop that iterates through a range of values.
Particularly useful for setting styles on a collection of items.
-There are two forms, "through" and "to." The former includes the last value,
+There are two forms, "through" and "to". The former includes the last value,
the latter stops at the last value. */
@for $c from 1 to 4 {
@@ -206,7 +206,7 @@ $social-links: facebook twitter linkedin reddit;
}
-/*Mixins
+/* Mixins
==============================*/
/* If you find you are writing the same code for more than one
@@ -301,7 +301,7 @@ body {
mixins. When trying to choose between a function or a mixin, remember
that mixins are best for generating CSS while functions are better for
logic that might be used throughout your Sass code. The examples in
- the Math Operators' section are ideal candidates for becoming a reusable
+ the 'Math Operators' section are ideal candidates for becoming a reusable
function. */
/* This function will take a target size and the parent size and calculate
@@ -577,9 +577,7 @@ You can use either syntax, just go into the settings and select either Sass or S
## Compatibility
-Sass can be used in any project as long as you have a program to compile it
-into CSS. You'll want to verify that the CSS you're using is compatible
-with your target browsers.
+Sass can be used in any project as long as you have a program to compile it into CSS. You'll want to verify that the CSS you're using is compatible with your target browsers.
[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility.
diff --git a/sk-sk/LearnGit-sk.txt b/sk-sk/LearnGit-sk.txt
deleted file mode 100644
index 070a0489..00000000
--- a/sk-sk/LearnGit-sk.txt
+++ /dev/null
@@ -1,208 +0,0 @@
-$ git init
-
-# Zobraz a Nastav Základné Konfiguračné Premenné (Globálne)
-$ git config --global user.email "MôjEmail@Zoho.com"
-$ git config --global user.name "Moje Meno
-
-# Rýchlo zobraz všetky dostupné príkazy
-$ git help
-
-# Zobraz všetky dostupné príkazy
-$ git help -a
-
-# Zobraz konkrétnu pomoc - použivateľský manuál
-# git help <príkaz_tu>
-$ git help add
-$ git help commit
-$ git help init
-# alebo git <príkaz_tu> --help
-$ git add --help
-$ git commit --help
-$ git init --help
-
-# Zobrazí vetvu, nesledované súbory, zmeny a ostatné rozdiely
-$ git status
-# Zistí iné vychytávky o git statuse
-$ git help status
-
-# pridá súbor z tvojho pracovného adresára
-$ git add HelloWorld.java
-
-# pridá súbor z iného adresára
-$ git add /cesta/k/súboru/HelloWorld.c
-
-# Môžeš použiť regulárne výrazy!
-$ git add ./*.java
-
-# zobraz existujúce vetvy a vzdialené repozitáre
-$ git branch -a
-
-# vytvor novú vetvu
-$ git branch myNewBranch
-
-# vymaž vetvu
-$ git branch -d myBranch
-
-# premenuj vetvu
-# git branch -m <starémeno> <novémeno>
-$ git branch -m mojaStaraVetva mojaNovaVetva
-
-# zmeň opis vetvy
-$ git branch myBranchName --edit-description
-
-# Zobrazí tagy
-$ git tag
-# Vytvorí tag so správou
-# -m špecifikuje správu, ktorá bude s tagom uložená.
-# Ak nešpeficikuješ správu pri tagu so správou,
-# Git spustí tvoj editor, aby si ju napísal.
-$ git tag -a v2.0 -m 'moja verzia 2.0'
-
-# Ukáž informácie o tagu
-# Zobrazí zadané informácie, dátum tagnutia commitu
-# a správu pred zobrazením informácií o commite.
-$ git show v2.0
-
-# Zverejní (pushne) jediný tag do vzdialeného repozitára
-$ git push origin v2.0
-
-# Zverejní viacero tagov do vzdialeného repozitára
-$ git push origin --tags
-
-# Aktualizuj strom, aby odpovedal (predvolene)
-# hlavnej vetve repozitáru (master branch)
-$ git checkout
-
-# Aktualizuj strom, aby odpovedal konrkétnej vetve
-$ git checkout menoVetvy
-
-# Vytvor novú vetvu & prepni sa na ňu
-# ekvivalentný príkaz: "git branch <meno>; git checkout <meno>"
-$ git checkout -b nováVetva
-
-# Naklonuj learnxinyminutes-docs
-$ git clone https://github.com/adambard/learnxinyminutes-docs.git
-
-# povrchné klonovanie - rýchlejšie, uloží iba najnovšiu snímku
-$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git
-
-# naklonuj iba konkrétnu vetvu
-$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch
-
-# commitni so správou
-$ git commit -m "Pridal som multiplyNumbers() funkciu do HelloWorld.c"
-
-# automaticky pridaj zmenené a vymazané súbory do staging indexu, potom ich commitni.
-$ git commit -a -m "Zmenil som foo.php a vymazal bar.php"
-
-# zmeň posledný commit (toto nahradí predchádzajúci commit novým)
-$ git commit --amend -m "Správna správa"
-
-# Ukáž rozdiel medzi pracovným repozitárom a indexom.
-$ git diff
-
-# Ukáž rozdiely medzi indexom a najnovším commitom.
-$ git diff --cached
-
-# Ukáž rozdiely medzi pracovným adresárom a najnovším commitom.
-$ git diff HEAD
-
-# Nastav, aby sa vo výsledkoch vyhľadávania zobrazovalo číslo riadku
-$ git config --global grep.lineNumber true
-
-# Urob výsledky vyhľadávania čitateľnejšie, vrátane zoskupovania
-$ git config --global alias.g "grep --break --heading --line-number"
-
-# Vďaka Travisovi Jefferymu za túto sekciu
-# Hľadaj "názovPremennej" vo všetkých java súboroch
-$ git grep 'názovPremennej' -- '*.java'
-
-# Hľadaj riadok, ktorý obsahuje "názovPoľa" a "add" alebo "remove"
-$ git grep -e 'arrayListName' --and \( -e add -e remove \)
-
-# Zobraz všetky commity
-$ git log
-
-# Zobraz iba správy a referencie commitov
-$ git log --oneline
-
-# Zobraz zlúčené (merged) commity
-$ git log --merges
-
-# Zobraz všetky commity vo forme ASCII grafu
-$ git log --graph
-
-# Zlúč vybranú vetvu do aktuálnej.
-$ git merge názovVetvy
-
-# Vždy vytvor zlučovací commit
-$ git merge --no-ff názovVetvy
-
-# Premenuj súbor
-$ git mv HelloWorld.c HelloNewWorld.c
-
-# Presuň súbor
-$ git mv HelloWorld.c ./nová/cesta/HelloWorld.c
-
-# "Nasilu" premenuj, alebo presuň
-# "existujúciSúbor" už v adresári existuje, bude prepísaný
-$ git mv -f môjSúbor existujúciSúbor
-
-# Aktualizuje tvoj lokálny repozitár zlúčením nových zmien
-# zo vzdialených "origin" a "master" vetiev.
-# git pull <alias-vzdialeného-repo> <vetva>
-$ git pull origin master
-
-# Predvolene, git pull aktualizuje tvoju aktuálnu vetvu
-# zlúčením nových zmien zo vzdialenej vetvy
-$ git pull
-
-# Zlúč zmeny zo vzdialenej vetvy a presuň vetvu do nového základného commitu (rebase)
-# vetva commitne na tvoj lokálny repozitár, ekvivalentný príkaz: "git pull <alias-vzdialeného-repo> <vrstva>, git rebase <branch>"
-$ git pull origin master --rebase
-
-# Zverejni a zlúč zmeny z lokálneho repozitára do
-# vzdialených vetiev s názvom "origin" a "master".
-# git push <vzdialené> <vetvy>
-$ git push origin master
-
-# Predvolene git zverejní a zlúči zmeny z
-# aktuálnej vetvy do vzdialenej vetvy s ňou spojenej
-$ git push
-
-# Na spojenie lokálnej vetvy so vzdialenou pridaj -u:
-$ git push -u origin master
-# Kedykoľvek budeš chcieť zverejniť z rovnakej lokálnej vetvy, použi príkaz:
-$ git push
-
-# Aplikuj commity z experimentálnej vetvy na master
-# git rebase <základnáVetva> <ináVetva>
-$ git rebase master experimentBranch
-
-# Resetni index (vrstvu medzi pracovným stromom a Git repozitárom), aby odpovedal najnovšiemu commitu (adresár ostane nezmenený)
-$ git reset
-
-# Resetni index, aby odpovedal najnovšiemu commitu (adresár sa prepíše)
-$ git reset --hard
-
-# Presunie vrchol aktuálnuej vetvy do konkrétneho commitu (adresár ostane nezmenený)
-# všetky zmeny sú zachované v adresári.
-$ git reset 31f2bb1
-
-# Vezmi späť konkrétny commit
-$ git revert <commit>
-
-# odstráň HelloWorld.c
-$ git rm HelloWorld.c
-
-# Odstráň súbor z vnoreného adresára
-$ git rm /pather/to/the/file/HelloWorld.c
-
-
-
-
-
-
-
-
-
diff --git a/sk-sk/ruby.html.markdown b/sk-sk/ruby.html.markdown
new file mode 100644
index 00000000..799865b0
--- /dev/null
+++ b/sk-sk/ruby.html.markdown
@@ -0,0 +1,553 @@
+---
+language: ruby
+filename: learnruby-sk.rb
+contributors:
+ - ["David Underwood", "http://theflyingdeveloper.com"]
+ - ["Joel Walden", "http://joelwalden.net"]
+ - ["Luke Holder", "http://twitter.com/lukeholder"]
+ - ["Tristan Hume", "http://thume.ca/"]
+ - ["Nick LaMuro", "https://github.com/NickLaMuro"]
+ - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
+ - ["Dzianis Dashkevich", "https://github.com/dskecse"]
+ - ["Levi Bostian", "https://github.com/levibostian"]
+ - ["Rahil Momin", "https://github.com/iamrahil"]
+translators:
+ - ["Juraj Kostolanský", "http://www.kostolansky.sk"]
+lang: sk-sk
+---
+
+```ruby
+# Toto je komentár
+
+=begin
+Toto je viacriadkový komentár
+Nikto ho nepoužíva
+Ani ty by si nemal
+=end
+
+# V prvom rade: Všetko je objekt.
+
+# Čísla sú objekty
+
+3.class #=> Fixnum
+
+3.to_s #=> "3"
+
+
+# Základná aritmetika
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+2**5 #=> 32
+
+# Aritmetika je iba syntaktickým cukrom
+# pre volanie metódy nad objektom
+1.+(3) #=> 4
+10.* 5 #=> 50
+
+# Špeciálne hodnoty sú objektami
+nil # nič
+true # pravda
+false # lož
+
+nil.class #=> NilClass
+true.class #=> TrueClass
+false.class #=> FalseClass
+
+# Rovnosť
+1 == 1 #=> true
+2 == 1 #=> false
+
+# Nerovnosť
+1 != 1 #=> false
+2 != 1 #=> true
+
+# Okrem samotného false, nil je jedinou ďalšou 'nepravdivou' hodnotou
+
+!nil #=> true
+!false #=> true
+!0 #=> false
+
+# Ďalšie porovnania
+1 < 10 #=> true
+1 > 10 #=> false
+2 <= 2 #=> true
+2 >= 2 #=> true
+
+# Logické operácie
+true && false #=> false
+true || false #=> true
+!true #=> false
+
+# Existujú aj alternatívne verzie logických operátorov s nižšou prioritou.
+# Tie sa využívajú ako konštrukcie pre riadenie toku na reťazenie výrazov
+# kým jeden z nich nevráti true alebo false.
+
+# `sprav_nieco_ine` sa vykoná ak bude `sprav_nieco` úspešné (vráti true)
+sprav_nieco() and sprav_nieco_ine()
+# `zaznamenaj_chybu` sa vykoná ak `sprav_nieco` neuspeje (vráti false)
+sprav_nieco() or zaznamenaj_chybu()
+
+
+# Reťazce sú objekty
+
+'Ja som reťazec'.class #=> String
+"Ja som tiež reťazec".class #=> String
+
+retazec = 'použiť interpoláciu reťazca'
+"Môžem #{retazec} pri použití dvojitých úvodzoviek"
+#=> "Môžem použiť interpoláciu reťazca pri použití dvojitých úvodzoviek"
+
+# Preferuj jednoduché úvodzovky pred dvojitými, ak je to možné
+# Dvojité úvodzovky totiž vyžadujú ďalšie výpočty
+
+# Kombinuj reťazce, ale nie s číslami
+'ahoj ' + 'svet' #=> "ahoj svet"
+'ahoj ' + 3 #=> TypeError: can't convert Fixnum into String
+'ahoj ' + 3.to_s #=> "ahoj 3"
+
+# Výpis na štandardný výstup
+puts "Píšem!"
+
+
+# Premenné
+x = 25 #=> 25
+x #=> 25
+
+# Všimni si, že priradenie vracia priradenú hodnotu
+# To umožňuje viacnásobné priradenie:
+
+x = y = 10 #=> 10
+x #=> 10
+y #=> 10
+
+# Podľa konvencie sa pre mená premenných využíva snake_case
+snake_case = true
+
+# Používaj správne (opisné) mená premenných
+cesta_ku_korenovemu_adresaru = '/dobre/meno/'
+cesta = '/zle/meno/'
+
+
+# Symboly (sú objektami)
+# Symboly sú nemenné znovupoužiteľné konštanty, ktoré sú interne
+# reprezentované ako číslo. Často sa používajú namiesto reťazcov
+# pre efektívnu reprezentáciu špecifickej hodnoty.
+
+:cakajuci.class #=> Symbol
+
+status = :cakajuci
+
+status == :cakajuci #=> true
+
+status == 'cakajuci' #=> false
+
+status == :schvaleny #=> false
+
+
+# Polia
+
+# Toto je pole
+pole = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+
+# Polia môžu obsahovať rôzne typy objektov
+
+[1, 'ahoj', false] #=> [1, "ahoj", false]
+
+# Polia môžu byť indexované
+# Od začiatku
+pole[0] #=> 1
+pole[12] #=> nil
+
+# Podobne ako pri aritmetike, prístup prostredníctvom [var]
+# je iba syntaktickým cukrom pre volanie metódy [] nad objektom
+pole.[] 0 #=> 1
+pole.[] 12 #=> nil
+
+# Od konca
+pole[-1] #=> 5
+
+# Pomocou počiatočného indexu a dĺžky
+pole[2, 3] #=> [3, 4, 5]
+
+# Alebo rozsahom
+pole[1..3] #=> [2, 3, 4]
+
+# Pridanie prvku do pola
+pole << 6 #=> [1, 2, 3, 4, 5, 6]
+# Alebo takto
+pole.push(6) #=> [1, 2, 3, 4, 5, 6]
+
+# Skontroluje, či už je objekt v poli
+pole.include?(1) #=> true
+
+
+# Asociatívne polia (hash) sú slovníkmi s dvojicami kľúč-hodnota.
+# Asociatívne polia sú označované kučeravými zátvorkami:
+asoc_pole = { 'farba' => 'zelena', 'cislo' => 5 }
+
+asoc_pole.keys #=> ['farba', 'cislo']
+
+# V asociatívnych poliach sa rýchlo vyhľadáva pomocou kľúča
+asoc_pole['farba'] #=> 'zelena'
+asoc_pole['cislo'] #=> 5
+
+# Asking a hash for a key that doesn't exist returns nil:
+asoc_pole['nic tu nie je'] #=> nil
+
+# Od verzie Ruby 1.9 existuje špeciálna syntax,
+# pri ktorej sa využíva symbol ako kľúč
+
+nove_asoc_pole = { defcon: 3, akcia: true }
+nove_asoc_pole.keys #=> [:defcon, :akcia]
+
+# Skontroluje existenciu kľúča a hodnoty v asociatívnom poli
+nove_asoc_pole.has_key?(:defcon) #=> true
+nove_asoc_pole.has_value?(3) #=> true
+
+# Tip: Polia aj asociatívne polia sú vypočítateľné (Enumerable)
+# Zdieľajú veľa užitočných metód ako each, map, count a ďalšie
+
+
+# Štruktúry riadenia
+
+if true
+ 'if podmienka'
+elsif false
+ 'else if, voliteľná vetva'
+else
+ 'else, tiež voliteľná vetva'
+end
+
+for pocitadlo in 1..5
+ puts "iterácia #{pocitadlo}"
+end
+#=> iterácia 1
+#=> iterácia 2
+#=> iterácia 3
+#=> iterácia 4
+#=> iterácia 5
+
+# NIKTO však nepoužíva for cyklus
+# Aj ty by si mal preferovať metódu "each" a podať jej blok
+# Blok kus kódu, ktorý môžeš podať metódam ako "each"
+# Je podobný lambdám alebo anonymným funkciám v iných jazykoch
+#
+# Metóda "each" pre rozsah spustí blokpre každý element tohto rozsahu
+# Blok získava počítadlo ako parameter
+# Volanie metódy "each" s blokomvyzerá takto:
+
+(1..5).each do |pocitadlo|
+ puts "iterácia #{pocitadlo}"
+end
+#=> iterácia 1
+#=> iterácia 2
+#=> iterácia 3
+#=> iterácia 4
+#=> iterácia 5
+
+# Blok môže byť uzavretý aj v kučeravých záítvorkách:
+(1..5).each { |pocitadlo| puts "iterácia #{pocitadlo}" }
+
+# Obsah dátových štruktúr môže byť tiež prechádzaný pomocou metódy "each"
+pole.each do |prvok|
+ puts "#{prvok} je súčasťou pola"
+end
+asoc_pole.each do |kluc, hodnota|
+ puts "#{kluc} je #{hodnota}"
+end
+
+pocitadlo = 1
+while pocitadlo <= 5 do
+ puts "iterácia #{pocitadlo}"
+ pocitadlo += 1
+end
+#=> iterácia 1
+#=> iterácia 2
+#=> iterácia 3
+#=> iterácia 4
+#=> iterácia 5
+
+znamka = 'B'
+
+case znamka
+when 'A'
+ puts 'Len tak ďalej, chlapče'
+when 'B'
+ puts 'Viac šťastia nabudúce'
+when 'C'
+ puts 'Zvládneš to aj lepšie'
+when 'D'
+ puts 'S odratými ušami'
+when 'F'
+ puts 'Zlyhal si!'
+else
+ puts 'Iný systém známkovania, čo?'
+end
+#=> "Viac šťastia nabudúce"
+
+# prípady (cases) môžu tiež využívať rozsahy
+znamka = 82
+case znamka
+when 90..100
+ puts 'Hurá!'
+when 80...90
+ puts 'Dobrá práca'
+else
+ puts 'Zlyhal si!'
+end
+#=> "Dobrá práca"
+
+# Zaobchádzanie s výnimkami
+begin
+ # kód, ktorý môže vyhodiť výnimku
+ raise NoMemoryError, 'Došla ti pamäť.'
+rescue NoMemoryError => premenna_vynimky
+ puts 'Nastala vynimka NoMemoryError', premenna_vynimky
+rescue RuntimeError => ina_premenna_vynimky
+ puts 'Nastala vynimka RuntimeError'
+else
+ puts 'Toto sa spustí, ak nenastala žiadna výnimka'
+ensure
+ puts 'Táto časť kódu sa spustí vždy'
+end
+
+# Funkcie
+
+def zdvojnasob(x)
+ x * 2
+end
+
+# Funkcie (a bloky) implicitne vracajú hodnotu posledného výrazu
+zdvojnasob(2) #=> 4
+
+# Zátvorky sú voliteľné ak je výsledok jednoznačný
+zdvojnasob 3 #=> 6
+
+zdvojnasob zdvojnasob 3 #=> 12
+
+def suma(x, y)
+ x + y
+end
+
+# Argumenty metódy sa oddeľujú čiarkami
+suma 3, 4 #=> 7
+
+suma suma(3, 4), 5 #=> 12
+
+# yield
+# Všetky metódy majú implicitný, voliteľný parameter bloku
+# môže byť zavolaný ako kľúčové slovo 'yield'
+
+def obal
+ puts '{'
+ yield
+ puts '}'
+end
+
+obal { puts 'ahoj svet' }
+
+# {
+# ahoj svet
+# }
+
+
+# Funkcii môžeš odovzdať blok
+# "&" označuje referenciu na tento blok
+def hostia(&blok)
+ blok.call 'nejake argumenty'
+end
+
+# Tiež môžeš odovzdať zoznam argumentov, ktoré sa prevedú na pole
+# Na to sa využíva operátor "*"
+def hostia(*pole)
+ pole.each { |host| puts host }
+end
+
+
+# Trieda sa definuje kľúčovým slovom class
+class Clovek
+
+ # Premenná triedy. Je zdieľaná všetkými inštanciami tejto triedy.
+ @@druh = 'H. sapiens'
+
+ # Jednoduchý inicializátor
+ def initialize(meno, vek = 0)
+ # Priradí argument k premennej inštancie "meno"
+ @meno = meno
+ # Ak nie je uvedený vek, použije sa špecifikovaná predvolená hodnota
+ @vek = vek
+ end
+
+ # Jednoduchá metóda pre nastavenie hodnoty premennej
+ def meno=(meno)
+ @meno = meno
+ end
+
+ # Jednoduchá metóda pre získanie hodnoty premennej
+ def meno
+ @meno
+ end
+
+ # Vyššie uvedená funkcionalita môže byť zapúzdrená použitím
+ # metódy attr_accessor
+ attr_accessor :meno
+
+ # Metódy pre nastavenie a získanie hodnoty premennej môžu byť vytvorené
+ # aj individuálne
+ attr_reader :meno
+ attr_writer :meno
+
+ # Metóda triedy používa kľúčové slovo self pre odlíšenie
+ # od metód inštancií. Môže byť volaná iba nad triedou, nie inštanciou.
+ def self.povedz(sprava)
+ puts sprava
+ end
+
+ def druh
+ @@druh
+ end
+end
+
+
+# Vytvorenie inštancie triedy
+jim = Clovek.new('Jim Halpert')
+
+dwight = Clovek.new('Dwight K. Schrute')
+
+# Skúsme zavolať zopár metód
+jim.druh #=> "H. sapiens"
+jim.meno #=> "Jim Halpert"
+jim.meno = "Jim Halpert II" #=> "Jim Halpert II"
+jim.meno #=> "Jim Halpert II"
+dwight.druh #=> "H. sapiens"
+dwight.meno #=> "Dwight K. Schrute"
+
+# Volanie metódy triedy
+Clovek.povedz('Ahoj') #=> "Ahoj"
+
+# Rozsah platnosti premennej je definovaná spôsobom, akým ju nazveme.
+# Premenné začínajúce znakom $ majú globálnu platnosť.
+$premenna = "Ja som globálna premenná"
+defined? $premenna #=> "global-variable"
+
+# Premenné začínajúce znakom @ majú platnosť v rámci inštancie
+@premenna = "Ja som premenná inštancie"
+defined? @premenna #=> "instance-variable"
+
+# Premenné začínajúce znakmi @@ majú platnosť v rámci triedy
+@@premenna= "Ja som premenná triedy"
+defined? @@premenna #=> "class variable"
+
+# Premenné začínajúce veľkým písmenom sú konštanty
+Premenna = "Ja som konštanta"
+defined? Premenna #=> "constant"
+
+# Trieda je tiež objektom v ruby, takže aj ona môže mať premenné inštancie.
+# Premenná triedy je zdieľaná triedou a jej nasledovníkmi.
+
+# Základná trieda
+class Clovek
+ @@foo = 0
+
+ def self.foo
+ @@foo
+ end
+
+ def self.foo=(hodnota)
+ @@foo = hodnota
+ end
+end
+
+# Odvodená trieda
+class Pracovnik < Clovek
+end
+
+Clovek.foo # 0
+Pracovnik.foo # 0
+
+Clovek.foo = 2 # 2
+Pracovnik.foo # 2
+
+# Premenné inštancie triedy nie sú zdieľané jej nasledovníkmi.
+
+class Clovek
+ @bar = 0
+
+ def self.bar
+ @bar
+ end
+
+ def self.bar=(hodnota)
+ @bar = hodnota
+ end
+end
+
+class Doktor < Clovek
+end
+
+Clovek.bar # 0
+Doktor.bar # nil
+
+module PrikladModulu
+ def foo
+ 'foo'
+ end
+end
+
+# Vloženie modulu (include) previaže jeho metódy s inštanciou triedy.
+# Rozšírenie modulu (extend) previaže jeho metódy so samotnou triedou.
+
+class Osoba
+ include PrikladModulu
+end
+
+class Kniha
+ extend PrikladModulu
+end
+
+Osoba.foo # => NoMethodError: undefined method `foo' for Osoba:Class
+Osoba.new.foo # => 'foo'
+Kniha.foo # => 'foo'
+Kniha.new.foo # => NoMethodError: undefined method `foo'
+
+# Spätné volania sú vykonané pri vložení alebo rozšírení modulu
+
+module PrikladKoncernu
+ def self.included(zaklad)
+ zaklad.extend(MetodyTriedy)
+ zaklad.send(:include, MetodyInstancie)
+ end
+
+ module MetodyTriedy
+ def bar
+ 'bar'
+ end
+ end
+
+ module MetodyInstancie
+ def qux
+ 'qux'
+ end
+ end
+end
+
+class Nieco
+ include PrikladKoncernu
+end
+
+Nieco.bar # => 'bar'
+Nieco.qux # => NoMethodError: undefined method `qux'
+Nieco.new.bar # => NoMethodError: undefined method `bar'
+Nieco.new.qux # => 'qux'
+```
+
+## Ďalšie zdroje
+
+- [Nauč sa ruby v príkladoch s úlohami](http://www.learneroo.com/modules/61/nodes/338) - Variácia tejto referencie s úlohami v prehliadači.
+- [Oficiálna dokumentácia](http://www.ruby-doc.org/core-2.1.1/)
+- [Ruby z iných jazykov](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
+- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Staršia [bezplatná edícia](http://ruby-doc.com/docs/ProgrammingRuby/) je dostupná online.
+- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Komunitná príručka odporúčaných štýlov programovania v Ruby.
diff --git a/solidity.html.markdown b/solidity.html.markdown
index 9bf5bf4d..0ad8af32 100644
--- a/solidity.html.markdown
+++ b/solidity.html.markdown
@@ -230,9 +230,9 @@ mapping (string => uint) public balances;
balances["charles"] = 1;
console.log(balances["ada"]); // is 0, all non-set key values return zeroes
// 'public' allows following from another contract
-contractName.balances("claude"); // returns 1
+contractName.balances("charles"); // returns 1
// 'public' created a getter (but not setter) like the following:
-function balances(address _account) returns (uint balance) {
+function balances(string _account) returns (uint balance) {
return balances[_account];
}
diff --git a/swift.html.markdown b/swift.html.markdown
index e921e7ea..b6554dc6 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -7,6 +7,7 @@ contributors:
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
- ["Clayton Walker", "https://github.com/cwalk"]
- ["Fernando Valverde", "http://visualcosita.xyz"]
+ - ["Alexey Nazaroff", "https://github.com/rogaven"]
filename: learnswift.swift
---
@@ -94,7 +95,7 @@ var unwrappedString: String! = "Value is expected."
// same as above, but ! is a postfix operator (more syntax candy)
var unwrappedString2: ImplicitlyUnwrappedOptional<String> = "Value is expected."
-// If let structure -
+// If let structure -
// If let is a special structure in Swift that allows you to check if an Optional rhs holds a value, and in case it does - unwraps and assigns it to the lhs.
if let someOptionalStringConstant = someOptionalString {
// has `Some` value, non-nil
@@ -104,10 +105,12 @@ if let someOptionalStringConstant = someOptionalString {
}
// Swift has support for storing a value of any type.
-// AnyObject == id
-// Unlike Objective-C `id`, AnyObject works with any value (Class, Int, struct, etc.)
-var anyObjectVar: AnyObject = 7
-anyObjectVar = "Changed value to a string, not good practice, but possible."
+// For that purposes there is two keywords: `Any` and `AnyObject`
+// `AnyObject` == `id` from Objective-C
+// `Any` – also works with any scalar values (Class, Int, struct, etc.)
+var anyVar: Any = 7
+anyVar = "Changed value to a string, not good practice, but possible."
+let anyObjectVar: AnyObject = Int(1) as NSNumber
/*
Comment here
@@ -151,11 +154,11 @@ var explicitEmptyMutableDictionary: [String: Float] = [:] // same as above
// MARK: Control Flow
//
-// Condition statements support "where" clauses, which can be used
+// Condition statements support "," (comma) clauses, which can be used
// to help provide conditions on optional values.
-// Both the assignment and the "where" clause must pass.
+// Both the assignment and the "," clause must pass.
let someNumber = Optional<Int>(7)
-if let num = someNumber where num > 3 {
+if let num = someNumber, num > 3 {
print("num is greater than 3")
}
@@ -230,13 +233,13 @@ A greet operation
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
-greet("Bob", day: "Tuesday")
+greet(name: "Bob", day: "Tuesday")
// similar to above except for the function parameter behaviors
-func greet2(requiredName requiredName: String, externalParamName localParamName: String) -> String {
- return "Hello \(requiredName), the day is \(localParamName)"
+func greet2(name: String, externalParamName localParamName: String) -> String {
+ return "Hello \(name), the day is \(localParamName)"
}
-greet2(requiredName: "John", externalParamName: "Sunday")
+greet2(name: "John", externalParamName: "Sunday")
// Function that returns multiple items in a tuple
func getGasPrices() -> (Double, Double, Double) {
@@ -279,7 +282,7 @@ func setup(numbers: Int...) {
}
// Passing and returning functions
-func makeIncrementer() -> (Int -> Int) {
+func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
@@ -289,14 +292,14 @@ var increment = makeIncrementer()
increment(7)
// pass by ref
-func swapTwoInts(inout a: Int, inout b: Int) {
+func swapTwoInts(a: inout Int, b: inout Int) {
let tempA = a
a = b
b = tempA
}
var someIntA = 7
var someIntB = 3
-swapTwoInts(&someIntA, b: &someIntB)
+swapTwoInts(a: &someIntA, b: &someIntB)
print(someIntB) // 7
@@ -324,7 +327,7 @@ numbers = numbers.map({ number in 3 * number })
print(numbers) // [3, 6, 18]
// Trailing closure
-numbers = numbers.sort { $0 > $1 }
+numbers = numbers.sorted { $0 > $1 }
print(numbers) // [18, 6, 3]
@@ -351,8 +354,8 @@ print("Name is \(name)") // Name is Them
// MARK: Error Handling
//
-// The `ErrorType` protocol is used when throwing errors to catch
-enum MyError: ErrorType {
+// The `Error` protocol is used when throwing errors to catch
+enum MyError: Error {
case BadValue(msg: String)
case ReallyBadValue(msg: String)
}
@@ -368,15 +371,15 @@ func fakeFetch(value: Int) throws -> String {
func testTryStuff() {
// assumes there will be no error thrown, otherwise a runtime exception is raised
- let _ = try! fakeFetch(7)
+ let _ = try! fakeFetch(value: 7)
// if an error is thrown, then it proceeds, but if the value is nil
// it also wraps every return value in an optional, even if its already optional
- let _ = try? fakeFetch(7)
+ let _ = try? fakeFetch(value: 7)
do {
// normal try operation that provides error handling via `catch` block
- try fakeFetch(1)
+ try fakeFetch(value: 1)
} catch MyError.BadValue(let msg) {
print("Error message: \(msg)")
} catch {
@@ -443,7 +446,7 @@ internal class Rect: Shape {
func shrink() {
if sideLength > 0 {
- --sideLength
+ sideLength -= 1
}
}
@@ -570,10 +573,11 @@ protocol ShapeGenerator {
}
// Protocols declared with @objc allow optional functions,
-// which allow you to check for conformance
+// which allow you to check for conformance. These functions must be
+// marked with @objc also.
@objc protocol TransformShape {
- optional func reshape()
- optional func canReshape() -> Bool
+ @objc optional func reshape()
+ @objc optional func canReshape() -> Bool
}
class MyShape: Rect {
@@ -585,7 +589,7 @@ class MyShape: Rect {
// Place a question mark after an optional property, method, or
// subscript to gracefully ignore a nil value and return nil
// instead of throwing a runtime error ("optional chaining").
- if let reshape = self.delegate?.canReshape?() where reshape {
+ if let reshape = self.delegate?.canReshape?(), reshape {
// test for delegate then for method
self.delegate?.reshape?()
}
@@ -620,20 +624,20 @@ extension Int {
}
print(7.customProperty) // "This is 7"
-print(14.multiplyBy(3)) // 42
+print(14.multiplyBy(num: 3)) // 42
// Generics: Similar to Java and C#. Use the `where` keyword to specify the
// requirements of the generics.
-func findIndex<T: Equatable>(array: [T], _ valueToFind: T) -> Int? {
- for (index, value) in array.enumerate() {
+func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
+ for (index, value) in array.enumerated() {
if value == valueToFind {
return index
}
}
return nil
}
-let foundAtIndex = findIndex([1, 2, 3, 4], 3)
+let foundAtIndex = findIndex(array: [1, 2, 3, 4], valueToFind: 3)
print(foundAtIndex == 2) // true
// Operators:
@@ -641,10 +645,10 @@ print(foundAtIndex == 2) // true
// / = - + * % < > ! & | ^ . ~
// or
// Unicode math, symbol, arrow, dingbat, and line/box drawing characters.
-prefix operator !!! {}
+prefix operator !!!
// A prefix operator that triples the side length when used
-prefix func !!! (inout shape: Square) -> Square {
+prefix func !!! (shape: inout Square) -> Square {
shape.sideLength *= 3
return shape
}
@@ -657,8 +661,8 @@ print(mySquare.sideLength) // 4
print(mySquare.sideLength) // 12
// Operators can also be generics
-infix operator <-> {}
-func <-><T: Equatable> (inout a: T, inout b: T) {
+infix operator <->
+func <-><T: Equatable> (a: inout T, b: inout T) {
let c = a
a = b
b = c
diff --git a/tmux.html.markdown b/tmux.html.markdown
index ae73d912..1214a5ba 100644
--- a/tmux.html.markdown
+++ b/tmux.html.markdown
@@ -116,7 +116,7 @@ like how .vimrc or init.el are used.
```
# Example tmux.conf
-# 2014.10
+# 2015.12
### General
@@ -129,7 +129,7 @@ set -g history-limit 2048
set -g base-index 1
# Mouse
-set-option -g mouse-select-pane on
+set-option -g -q mouse on
# Force reload of config file
unbind r
@@ -204,8 +204,6 @@ setw -g window-status-bg black
setw -g window-status-current-fg green
setw -g window-status-bell-attr default
setw -g window-status-bell-fg red
-setw -g window-status-content-attr default
-setw -g window-status-content-fg yellow
setw -g window-status-activity-attr default
setw -g window-status-activity-fg yellow
@@ -246,6 +244,4 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] |
[Display CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux)
-[tmuxinator - Manage complex tmux sessions](https://github.com/tmuxinator/tmuxinator)
-
-
+[tmuxinator - Manage complex tmux sessions](https://github.com/tmuxinator/tmuxinator)
diff --git a/toml.html.markdown b/toml.html.markdown
new file mode 100755
index 00000000..980563f9
--- /dev/null
+++ b/toml.html.markdown
@@ -0,0 +1,274 @@
+---
+language: toml
+filename: learntoml.toml
+contributors:
+ - ["Alois de Gouvello", "https://github.com/aloisdg"]
+---
+
+TOML stands for Tom's Obvious, Minimal Language. It is a data serialisation language designed to be a minimal configuration file format that's easy to read due to obvious semantics.
+
+It is an alternative to YAML and JSON. It aims to be more human friendly than JSON and simpler that YAML. TOML is designed to map unambiguously to a hash table. TOML should be easy to parse into data structures in a wide variety of languages.
+
+Be warned, TOML's spec is still changing a lot. Until it's marked as 1.0, you
+should assume that it is unstable and act accordingly. This document follows TOML v0.4.0.
+
+```toml
+# Comments in TOML look like this.
+
+################
+# SCALAR TYPES #
+################
+
+# Our root object (which continues for the entire document) will be a map,
+# which is equivalent to a dictionary, hash or object in other languages.
+
+# The key, equals sign, and value must be on the same line
+# (though some values can be broken over multiple lines).
+key = "value"
+string = "hello"
+number = 42
+float = 3.14
+boolean = true
+dateTime = 1979-05-27T07:32:00-08:00
+scientificNotation = 1e+12
+"key can be quoted" = true # Both " and ' are fine
+"key may contains" = "letters, numbers, underscores, and dashes"
+
+# A bare key must be non-empty, but an empty quoted key is allowed
+"" = "blank" # VALID but discouraged
+'' = 'blank' # VALID but discouraged
+
+##########
+# String #
+##########
+
+# All strings must contain only valid UTF-8 characters.
+# We can escape characters and some of them have a compact escape sequence.
+# For example, \t add a tabulation. Refers to the spec to get all of them.
+basicString = "are surrounded by quotation marks. \"I'm quotable\". Name\tJos"
+
+multiLineString = """
+are surrounded by three quotation marks
+on each side and allow newlines."""
+
+literalString = 'are surrounded by single quotes. Escaping are not allowed.'
+
+multiLineLiteralString = '''
+are surrounded by three single quotes on each side
+and allow newlines. Still no escaping.
+The first newline is trimmed in raw strings.
+ All other whitespace
+ is preserved. #! are preserved?
+'''
+
+# For binary data it is recommended that you use Base64, another ASCII or UTF8
+# encoding. The handling of that encoding will be application specific.
+
+###########
+# Integer #
+###########
+
+## Integers can start with a +, a - or nothing.
+## Leading zeros are not allowed. Hex, octal, and binary forms are not allowed.
+## Values that cannot be expressed as a series of digits are not allowed.
+int1 = +42
+int2 = 0
+int3 = -21
+integerRange = 64
+
+## You can use underscores to enhance readability. Each
+## underscore must be surrounded by at least one digit.
+int4 = 5_349_221
+int5 = 1_2_3_4_5 # VALID but discouraged
+
+#########
+# Float #
+#########
+
+# Floats are an integer followed by a fractional and/or an exponent part.
+flt1 = 3.1415
+flt2 = -5e6
+flt3 = 6.626E-34
+
+###########
+# Boolean #
+###########
+
+bool1 = true
+bool2 = false
+boolMustBeLowercase = true
+
+############
+# Datetime #
+############
+
+date1 = 1979-05-27T07:32:00Z # follows the RFC 3339 spec
+date2 = 1979-05-27T07:32:00 # without offset
+date3 = 1979-05-27 # without offset nor time
+
+####################
+# COLLECTION TYPES #
+####################
+
+#########
+# Array #
+#########
+
+array1 = [ 1, 2, 3 ]
+array2 = [ "Commas", "are", "delimiters" ]
+array3 = [ "Don't mixed", "different", "types" ]
+array4 = [ [ 1.2, 2.4 ], ["all", 'strings', """are the same""", '''type'''] ]
+array5 = [
+ "Whitespace", "is", "ignored"
+]
+
+#########
+# Table #
+#########
+
+# Tables (or hash tables or dictionaries) are collections of key/value
+# pairs. They appear in square brackets on a line by themselves.
+# Empty tables are allowed and simply have no key/value pairs within them.
+[table]
+
+# Under that, and until the next table or EOF are the key/values of that table.
+# Key/value pairs within tables are not guaranteed to be in any specific order.
+[table-1]
+key1 = "some string"
+key2 = 123
+
+[table-2]
+key1 = "another string"
+key2 = 456
+
+# Dots are prohibited in bare keys because dots are used to signify nested tables.
+# Naming rules for each dot separated part are the same as for keys.
+[dog."tater.man"]
+type = "pug"
+
+# In JSON land, that would give you the following structure:
+# { "dog": { "tater.man": { "type": "pug" } } }
+
+# Whitespace around dot-separated parts is ignored, however, best practice is to
+# not use any extraneous whitespace.
+[a.b.c] # this is best practice
+[ d.e.f ] # same as [d.e.f]
+[ j . "ʞ" . 'l' ] # same as [j."ʞ".'l']
+
+# You don't need to specify all the super-tables if you don't want to. TOML knows
+# how to do it for you.
+# [x] you
+# [x.y] don't
+# [x.y.z] need these
+[x.y.z.w] # for this to work
+
+# As long as a super-table hasn't been directly defined and hasn't defined a
+# specific key, you may still write to it.
+[a.b]
+c = 1
+
+[a]
+d = 2
+
+# You cannot define any key or table more than once. Doing so is invalid.
+
+# DO NOT DO THIS
+[a]
+b = 1
+
+[a]
+c = 2
+
+# DO NOT DO THIS EITHER
+[a]
+b = 1
+
+[a.b]
+c = 2
+
+# All table names must be non-empty.
+[] # INVALID
+[a.] # INVALID
+[a..b] # INVALID
+[.b] # INVALID
+[.] # INVALID
+
+################
+# Inline table #
+################
+
+inlineTables = { areEnclosedWith = "{ and }", mustBeInline = true }
+point = { x = 1, y = 2 }
+
+###################
+# Array of Tables #
+###################
+
+# An array of tables can be expressed by using a table name in double brackets.
+# Each table with the same double bracketed name will be an item in the array.
+# The tables are inserted in the order encountered.
+
+[[products]]
+name = "array of table"
+sku = 738594937
+emptyTableAreAllowed = true
+
+[[products]]
+
+[[products]]
+name = "Nail"
+sku = 284758393
+color = "gray"
+
+# You can create nested arrays of tables as well. Each double-bracketed
+# sub-table will belong to the nearest table element above it.
+
+[[fruit]]
+ name = "apple"
+
+ [fruit.Geometry]
+ shape = "round"
+ note = "I am an fruit's property"
+
+ [[fruit.color]]
+ name = "red"
+ note = "I am an array's item in apple"
+
+ [[fruit.color]]
+ name = "green"
+ note = "I am in the same array than red"
+
+[[fruit]]
+ name = "banana"
+
+ [[fruit.color]]
+ name = "yellow"
+ note = "I am an array's item too but banana's one"
+```
+
+In JSON land, this code will be:
+
+```json
+{
+ "fruit": [
+ {
+ "name": "apple",
+ "geometry": { "shape": "round", "note": "..."},
+ "color": [
+ { "name": "red", "note": "..." },
+ { "name": "green", "note": "..." }
+ ]
+ },
+ {
+ "name": "banana",
+ "color": [
+ { "name": "yellow", "note": "..." }
+ ]
+ }
+ ]
+}
+```
+
+### More Resources
+
++ [TOML official repository](https://github.com/toml-lang/toml)
diff --git a/uk-ua/json-ua.html.markdown b/uk-ua/json-ua.html.markdown
index a860e9a7..c9a3d3fb 100644
--- a/uk-ua/json-ua.html.markdown
+++ b/uk-ua/json-ua.html.markdown
@@ -1,24 +1,30 @@
---
language: json
-filename: learnjson-ru.json
+filename: learnjson-ua.json
contributors:
- ["Anna Harren", "https://github.com/iirelu"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
translators:
- ["Ehreshi Ivan", "https://github.com/IvanEh"]
+ - ["Serhii Maksymchuk", "https://github.com/Serg-Maximchuk"]
lang: uk-ua
---
-JSON - це надзвичайно простий формат обміну даними. Це мабуть буде найлегшим курсом
-"Learn X in Y Minutes".
+JSON - це надзвичайно простий формат обміну даними. Згідно з [json.org](http://json.org), для людей він легкий в написанні і читанні, а для комп’ютерів в розборі та генерації.
-В загальному випадку в JSON немає коментарів, але більшість парсерів дозволяють
-використовувати коментарі в С-стилі(//, /\* \*/). Можна залишити кому після останнього
-поля, але все-таки краще такого уникати для кращої сумісності
+JSON підтримує наступні структури даних:
+
+* Колекція пар ключ/значення (`{ "ключ": "значення" }`). У різних мовах програмування реалізується як об’єкт, запис, структура, словник, хеш-таблиця, іменований список або асоціативний масив.
+* Впорядкований список значень (`[ "елемент0", "елемент1" ]`). У різних мовах програмування реалізується як масив, вектор, список або послідовність.
+* Рядки: `"привіт"`, `"\"Лапки\""`, `"\u0abe"`, `"Новий рядок.\n"`
+* Числа: `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4`
+* Інші: `true`, `false`, `null`
+
+JSON в чистій формі не містить коментарів, але більшість парсерів підтримують коментарі в C-стилі (`//`, `/* */`). Деякі парсери також не звертають уваги на кому після останнього поля, але їх варто уникати для кращої сумісності.
```json
{
- "ключ": "значеннь",
+ "ключ": "значення",
"ключі": "завжди мають бути обгорнуті в подвійні лапки",
"числа": 0,
@@ -50,9 +56,9 @@ JSON - це надзвичайно простий формат обміну да
]
],
- "альтернативнтй стиль": {
+ "альтернативний стиль": {
"коментар": "Гляньте!"
- , "позиція коми": "неважлива, поки вона знаходиться до наступного поля"
+ , "позиція коми": "неважлива, коректно якщо вона знаходиться перед наступним полем"
, "інший коментар": "класно"
},
diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown
index e1551e2b..d71aa8d6 100644
--- a/zh-cn/c++-cn.html.markdown
+++ b/zh-cn/c++-cn.html.markdown
@@ -188,7 +188,7 @@ int main()
cout << "Your favorite number is " << myInt << "\n";
// 显示“Your favorite number is <myInt>”
- cerr << "Used for error messages";
+ cerr << "Used for error messages";
}
/////////
@@ -322,7 +322,7 @@ int main() {
Dog myDog; // 此时显示“A dog has been constructed”
myDog.setName("Barkley");
myDog.setWeight(10);
- myDog.printDog(); // 显示“Dog is Barkley and weighs 10 kg”
+ myDog.print(); // 显示“Dog is Barkley and weighs 10 kg”
return 0;
} // 显示“Goodbye Barkley”
diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown
index 14d38137..2d181de0 100644
--- a/zh-cn/ruby-cn.html.markdown
+++ b/zh-cn/ruby-cn.html.markdown
@@ -10,6 +10,7 @@ contributors:
- ["ftwbzhao", "https://github.com/ftwbzhao"]
translators:
- ["Lin Xiangyu", "https://github.com/oa414"]
+ - ["Jiang Haiyun", "https://github.com/haiiiiiyun"]
---
```ruby
@@ -35,6 +36,13 @@ translators:
8 - 1 #=> 7
10 * 2 #=> 20
35 / 5 #=> 7
+2**5 #=> 32
+5 % 3 #=> 2
+
+# 位运算符
+3 & 5 #=> 1
+3 | 5 #=> 7
+3 ^ 5 #=> 6
# 算术符号只是语法糖而已
# 实际上是调用对象的方法
@@ -42,7 +50,7 @@ translators:
10.* 5 #=> 50
# 特殊的值也是对象
-nil # 空
+nil # 相当于其它语言中的 null
true # 真
false # 假
@@ -54,13 +62,11 @@ false.class #=> FalseClass
1 == 1 #=> true
2 == 1 #=> false
-# 不等运算符
+# 不相等运算符
1 != 1 #=> false
2 != 1 #=> true
-!true #=> false
-!false #=> true
-# 除了false自己,nil是唯一的值为false的对象
+# 除了false自己,nil是唯一的另一个值为false的对象
!nil #=> true
!false #=> true
@@ -72,6 +78,26 @@ false.class #=> FalseClass
2 <= 2 #=> true
2 >= 2 #=> true
+
+# 组合比较运算符
+1 <=> 10 #=> -1
+10 <=> 1 #=> 1
+1 <=> 1 #=> 0
+
+# 逻辑运算符
+true && false #=> false
+true || false #=> true
+!true #=> false
+
+# 也有优先级更低的逻辑运算符
+# 它们用于控制流结构中,用来串接语句,直到返回true或false。
+
+# `do_something_else` 只当 `do_something` 返回true时才会被调用
+do_something() and do_something_else()
+# `log_error` 只当 `do_something` 返回false时才会被调用
+do_something() or log_error()
+
+
# 字符串是对象
'I am a string'.class #=> String
@@ -81,9 +107,28 @@ placeholder = "use string interpolation"
"I can #{placeholder} when using double quoted strings"
#=> "I can use string interpolation when using double quoted strings"
+# 尽可能优先使用单引号的字符串
+# 双引号的字符串会进行一些额外的内部处理
+
+# 合并字符串,但不能和数字合并
+'hello ' + 'world' #=> "hello world"
+'hello ' + 3 #=> TypeError: can't convert Fixnum into String
+'hello ' + 3.to_s #=> "hello 3"
+
+# 合并字符串及其运算符
+'hello ' * 3 #=> "hello hello hello "
+
+# 字符串追加
+'hello' << ' world' #=> "hello world"
-# 输出值
+# 打印输出,并在末尾加换行符
puts "I'm printing!"
+#=> I'm printing!
+#=> nil
+
+# 打印输出,不加换行符
+print "I'm printing!"
+#=> I'm printing! => nil
# 变量
x = 25 #=> 25
@@ -96,17 +141,16 @@ x = y = 10 #=> 10
x #=> 10
y #=> 10
-# 按照惯例,用 snake_case 作为变量名
+# 按照惯例,使用类似snake_case风格的变量名
snake_case = true
-# 使用具有描述性的运算符
+# 使用有意义的变量名
path_to_project_root = '/good/name/'
path = '/bad/name/'
# 符号(Symbols,也是对象)
-# 符号是不可变的,内部用整数类型表示的可重用的值。
-# 通常用它代替字符串来有效地表示有意义的值。
-
+# 符号是不可变的,内部用整数值表示的可重用的常数
+# 通常用它代替字符串来有效地表示有意义的值
:pending.class #=> Symbol
@@ -132,26 +176,36 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
array[0] #=> 1
array[12] #=> nil
-# 像运算符一样,[var]形式的访问
-# 也就是一个语法糖
-# 实际上是调用对象的[] 方法
+# 像运算符一样,[var] 形式的访问
+# 也只是语法糖
+# 实际上是调用对象的 [] 方法
array.[] 0 #=> 1
array.[] 12 #=> nil
# 从尾部开始
array[-1] #=> 5
+array.last #=> 5
# 同时指定开始的位置和长度
array[2, 3] #=> [3, 4, 5]
-# 或者指定一个范围
+# 将数组逆序
+a=[1,2,3]
+a.reverse! #=> [3,2,1]
+
+# 或者指定一个区间
array[1..3] #=> [2, 3, 4]
# 像这样往数组增加一个元素
array << 6 #=> [1, 2, 3, 4, 5, 6]
+# 或者像这样
+array.push(6) #=> [1, 2, 3, 4, 5, 6]
-# 哈希表是Ruby的键值对的基本数据结构
-# 哈希表由大括号定义
+# 检查元素是否包含在数组中
+array.include?(1) #=> true
+
+# 哈希表是 Ruby 的主要键/值对表示法
+# 哈希表由大括号表示
hash = {'color' => 'green', 'number' => 5}
hash.keys #=> ['color', 'number']
@@ -163,19 +217,14 @@ hash['number'] #=> 5
# 查询一个不存在地键将会返回nil
hash['nothing here'] #=> nil
-# 用 #each 方法来枚举哈希表:
-hash.each do |k, v|
- puts "#{k} is #{v}"
-end
-
-# 从Ruby 1.9开始, 用符号作为键的时候有特别的记号表示:
+# 从Ruby 1.9开始,用符号作为键的时候有特别的记号表示:
-new_hash = { defcon: 3, action: true}
+new_hash = { defcon: 3, action: true }
new_hash.keys #=> [:defcon, :action]
# 小贴士:数组和哈希表都是可枚举的
-# 它们可以共享一些有用的方法,比如each, map, count 等等
+# 它们共享一些有用的方法,比如each,map,count等等
# 控制流
@@ -196,9 +245,15 @@ end
#=> iteration 4
#=> iteration 5
-# 然而
-# 没人用for循环
-# 用`each`来代替,就像这样
+
+# 但是,没有人用for循环。
+# 你应该使用"each"方法,然后再传给它一个块。
+# 所谓块就是可以传给像"each"这样的方法的代码段。
+# 它类似于其它语言中的lambdas, 匿名函数或闭包。
+#
+# 区间上的"each"方法会对区间中的每个元素运行一次块代码。
+# 我们将counter作为一个参数传给了块。
+# 调用带有块的"each"方法看起来如下:
(1..5).each do |counter|
puts "iteration #{counter}"
@@ -209,6 +264,23 @@ end
#=> iteration 4
#=> iteration 5
+# 你也可以将块包含在一个大括号中:
+(1..5).each { |counter| puts "iteration #{counter}" }
+
+# 数据结构中的内容也可以使用each来遍历。
+array.each do |element|
+ puts "#{element} is part of the array"
+end
+hash.each do |key, value|
+ puts "#{key} is #{value}"
+end
+
+# 如果你还需要索引值,可以使用"each_with_index",并且定义
+# 一个索引变量
+array.each_with_index do |element, index|
+ puts "#{element} is number #{index} in the array"
+end
+
counter = 1
while counter <= 5 do
puts "iteration #{counter}"
@@ -220,6 +292,20 @@ end
#=> iteration 4
#=> iteration 5
+# Ruby 中还有很多有用的循环遍历函数,
+# 如"map","reduce","inject"等等。
+# 以map为例,它会遍历数组,并根据你在
+# 块中定义的逻辑对它进行处理,然后返回
+# 一个全新的数组。
+array = [1,2,3,4,5]
+doubled = array.map do |element|
+ element * 2
+end
+puts doubled
+#=> [2,4,6,8,10]
+puts array
+#=> [1,2,3,4,5]
+
grade = 'B'
case grade
@@ -236,6 +322,33 @@ when 'F'
else
puts "Alternative grading system, eh?"
end
+#=> "Better luck next time"
+
+# case也可以用区间
+grade = 82
+case grade
+when 90..100
+ puts 'Hooray!'
+when 80...90
+ puts 'OK job'
+else
+ puts 'You failed!'
+end
+#=> "OK job"
+
+# 异常处理:
+begin
+ # 这里的代码可能会抛出异常
+ raise NoMemoryError, 'You ran out of memory.'
+rescue NoMemoryError => exception_variable
+ puts 'NoMemoryError was raised', exception_variable
+rescue RuntimeError => other_exception_variable
+ puts 'RuntimeError was raised now'
+else
+ puts 'This runs if no exceptions were thrown at all'
+ensure
+ puts 'This code always runs no matter what'
+end
# 函数
@@ -243,7 +356,7 @@ def double(x)
x * 2
end
-# 函数 (以及所有的方法块) 隐式地返回了最后语句的值
+# 函数 (以及所有的块) 隐式地返回最后语句的值
double(2) #=> 4
# 当不存在歧义的时候括号是可有可无的
@@ -261,8 +374,8 @@ sum 3, 4 #=> 7
sum sum(3,4), 5 #=> 12
# yield
-# 所有的方法都有一个隐式的块参数
-# 可以用yield参数调用
+# 所有的方法都有一个隐式的,可选的块参数
+# 可以用 'yield' 关键字调用
def surround
puts "{"
@@ -276,45 +389,84 @@ surround { puts 'hello world' }
# hello world
# }
+# 可以向函数传递一个块
+# "&"标记传递的块是一个引用
+def guests(&block)
+ block.call 'some_argument'
+end
-# 用class关键字定义一个类
-class Human
-
- # 一个类变量,它被这个类地所有实例变量共享
- @@species = "H. sapiens"
+# 可以传递多个参数,这些参数会转成一个数组,
+# 这也是使用星号符 ("*") 的原因:
+def guests(*array)
+ array.each { |guest| puts guest }
+end
- # 构造函数
- def initialize(name, age=0)
- # 将参数name的值赋给实例变量@name
- @name = name
- # 如果没有给出age, 那么会采用参数列表中地默认地值
- @age = age
- end
+# 如果函数返回一个数组,在赋值时可以进行拆分:
+def foods
+ ['pancake', 'sandwich', 'quesadilla']
+end
+breakfast, lunch, dinner = foods
+breakfast #=> 'pancake'
+dinner #=> 'quesadilla'
- # 基本的 setter 方法
- def name=(name)
- @name = name
- end
+# 按照惯例,所有返回布尔值的方法都以?结尾
+5.even? # false
+5.odd? # true
- # 基本地 getter 方法
- def name
- @name
- end
+# 如果方法名末尾有!,表示会做一些破坏性的操作,比如修改调用者自身。
+# 很多方法都会有一个!的版本来进行修改,和一个非!的版本
+# 只用来返回更新了的结果
+company_name = "Dunder Mifflin"
+company_name.upcase #=> "DUNDER MIFFLIN"
+company_name #=> "Dunder Mifflin"
+company_name.upcase! # we're mutating company_name this time!
+company_name #=> "DUNDER MIFFLIN"
- # 一个类方法以self.开头
- # 它可以被类调用,但不能被类的实例调用
- def self.say(msg)
- puts "#{msg}"
- end
- def species
- @@species
- end
+# 用class关键字定义一个类
+class Human
+ # 一个类变量,它被这个类的所有实例变量共享
+ @@species = "H. sapiens"
+
+ # 基本构造函数
+ def initialize(name, age = 0)
+ # 将参数值赋给实例变量"name"
+ @name = name
+ # 如果没有给出age,那么会采用参数列表中的默认值
+ @age = age
+ end
+
+ # 基本的setter方法
+ def name=(name)
+ @name = name
+ end
+
+ # 基本地getter方法
+ def name
+ @name
+ end
+
+ # 以上的功能也可以用下面的attr_accessor来封装
+ attr_accessor :name
+
+ # Getter/setter方法也可以像这样单独创建
+ attr_reader :name
+ attr_writer :name
+
+ # 类方法通过使用self与实例方法区别开来。
+ # 它只能通过类来调用,不能通过实例调用。
+ def self.say(msg)
+ puts "#{msg}"
+ end
+
+ def species
+ @@species
+ end
end
-# 类的例子
+# 初始化一个类
jim = Human.new("Jim Halpert")
dwight = Human.new("Dwight K. Schrute")
@@ -327,7 +479,132 @@ jim.name #=> "Jim Halpert II"
dwight.species #=> "H. sapiens"
dwight.name #=> "Dwight K. Schrute"
-# 调用对象的方法
-Human.say("Hi") #=> "Hi"
+# 调用类方法
+Human.say('Hi') #=> "Hi"
+
+# 变量的作用域由它们的名字格式定义
+# 以$开头的变量具有全局域
+$var = "I'm a global var"
+defined? $var #=> "global-variable"
+
+# 以@开头的变量具有实例作用域
+@var = "I'm an instance var"
+defined? @var #=> "instance-variable"
+
+# 以@@开头的变量具有类作用域
+@@var = "I'm a class var"
+defined? @@var #=> "class variable"
+
+# 以大写字母开头的变量是常数
+Var = "I'm a constant"
+defined? Var #=> "constant"
+
+# 类也是对象。因此类也可以有实例变量。
+# 类变量在类以及其继承者之间共享。
+
+# 基类
+class Human
+ @@foo = 0
+
+ def self.foo
+ @@foo
+ end
+
+ def self.foo=(value)
+ @@foo = value
+ end
+end
+
+# 派生类
+class Worker < Human
+end
+
+Human.foo # 0
+Worker.foo # 0
+
+Human.foo = 2 # 2
+Worker.foo # 2
+
+# 类实例变量不能在继承类间共享。
+
+class Human
+ @bar = 0
+
+ def self.bar
+ @bar
+ end
+
+ def self.bar=(value)
+ @bar = value
+ end
+end
+
+class Doctor < Human
+end
+
+Human.bar # 0
+Doctor.bar # nil
+
+module ModuleExample
+ def foo
+ 'foo'
+ end
+end
+
+# '包含'模块后,模块的方法会绑定为类的实例方法
+# '扩展'模块后,模块的方法会绑定为类方法
+
+class Person
+ include ModuleExample
+end
+
+class Book
+ extend ModuleExample
+end
+
+Person.foo # => NoMethodError: undefined method `foo' for Person:Class
+Person.new.foo # => 'foo'
+Book.foo # => 'foo'
+Book.new.foo # => NoMethodError: undefined method `foo'
+
+# 当包含或扩展一个模块时,相应的回调代码会被执行。
+module ConcernExample
+ def self.included(base)
+ base.extend(ClassMethods)
+ base.send(:include, InstanceMethods)
+ end
+
+ module ClassMethods
+ def bar
+ 'bar'
+ end
+ end
+
+ module InstanceMethods
+ def qux
+ 'qux'
+ end
+ end
+end
+
+class Something
+ include ConcernExample
+end
+
+Something.bar # => 'bar'
+Something.qux # => NoMethodError: undefined method `qux'
+Something.new.bar # => NoMethodError: undefined method `bar'
+Something.new.qux # => 'qux'
```
+
+
+## 其它资源
+
+- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.
+- [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Learn Ruby through a series of interactive tutorials.
+- [Official Documentation](http://ruby-doc.org/core)
+- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
+- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
+- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
+- [Try Ruby](http://tryruby.org) - Learn the basic of Ruby programming language, interactive in the browser.
diff --git a/zh-cn/rust-cn.html.markdown b/zh-cn/rust-cn.html.markdown
index 17a897df..5d3fc693 100644
--- a/zh-cn/rust-cn.html.markdown
+++ b/zh-cn/rust-cn.html.markdown
@@ -268,7 +268,7 @@ fn main() {
var = 3;
let ref_var: &i32 = &var;
- println!("{}", var); //不像 `box`, `var` 还可以继续使用
+ println!("{}", var); //不像 `mine`, `var` 还可以继续使用
println!("{}", *ref_var);
// var = 5; // 编译报错,因为 `var` 被借用了
// *ref_var = 6; // 编译报错,因为 `ref_var` 是不可变引用
diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown
index 017a7812..cba9252d 100644
--- a/zh-cn/swift-cn.html.markdown
+++ b/zh-cn/swift-cn.html.markdown
@@ -373,7 +373,7 @@ internal class Rect: Shape {
func shrink() {
if sideLength > 0 {
- --sideLength
+ sideLength -= 1
}
}
diff --git a/zh-cn/visualbasic-cn.html.markdown b/zh-cn/visualbasic-cn.html.markdown
index 95f01ed6..59f18fe2 100644
--- a/zh-cn/visualbasic-cn.html.markdown
+++ b/zh-cn/visualbasic-cn.html.markdown
@@ -3,7 +3,7 @@ language: Visual Basic
contributors:
- ["Brian Martin", "http://brianmartin.biz"]
translators:
- - ["Abner Chou", "http://github.com/NoahDragon"]
+ - ["Abner Chou", "http://cn.abnerchou.me"]
lang: zh-cn
filename: learnvisualbasic.vb-cn
---