summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorBohdan Shtepan <winsatana@ya.ru>2016-04-05 20:27:09 +0300
committerBohdan Shtepan <winsatana@ya.ru>2016-04-05 20:27:09 +0300
commit8abfffd183d34c6b76dd117351a879e8b093f8c1 (patch)
tree2ded23445aff1b22c53078e13efc7054ce8fddde
parentaad2d2b6f2e44f7647d0512dea263029c1d4d1fa (diff)
parent8ddf7b5178524ab84f9e59b3e9d48343805d8ca0 (diff)
Merge remote-tracking branch 'adambard/master'
-rw-r--r--.gitignore16
-rw-r--r--CONTRIBUTING.markdown70
-rw-r--r--PULL_REQUEST_TEMPLATE.md4
-rw-r--r--README.markdown101
-rw-r--r--asciidoc.html.markdown122
-rw-r--r--asymptotic-notation.html.markdown151
-rw-r--r--bash.html.markdown17
-rw-r--r--bf.html.markdown (renamed from brainfuck.html.markdown)2
-rw-r--r--c++.html.markdown132
-rw-r--r--c.html.markdown49
-rw-r--r--chapel.html.markdown2
-rw-r--r--coldfusion.html.markdown50
-rw-r--r--common-lisp.html.markdown4
-rw-r--r--cs-cz/brainfuck.html.markdown87
-rw-r--r--cs-cz/elm.html.markdown373
-rw-r--r--cs-cz/json.html.markdown62
-rw-r--r--cs-cz/markdown.html.markdown14
-rw-r--r--cs-cz/python3.html.markdown2
-rw-r--r--cs-cz/sass.html.markdown439
-rw-r--r--csharp.html.markdown35
-rw-r--r--css.html.markdown57
-rw-r--r--d.html.markdown2
-rw-r--r--de-de/bash-de.html.markdown4
-rw-r--r--de-de/d-de.html.markdown250
-rw-r--r--de-de/git-de.html.markdown14
-rw-r--r--de-de/go-de.html.markdown51
-rw-r--r--de-de/hack-de.html.markdown322
-rw-r--r--de-de/haml-de.html.markdown156
-rw-r--r--de-de/haskell-de.html.markdown14
-rw-r--r--de-de/latex-de.html.markdown91
-rw-r--r--de-de/lua-de.html.markdown426
-rw-r--r--de-de/make-de.html.markdown260
-rw-r--r--de-de/markdown-de.html.markdown10
-rw-r--r--de-de/tcl-de.html.markdown475
-rw-r--r--edn.html.markdown2
-rw-r--r--elixir.html.markdown4
-rw-r--r--elm.html.markdown367
-rw-r--r--es-es/bf-es.html.markdown (renamed from es-es/brainfuck-es.html.markdown)2
-rw-r--r--es-es/c++-es.html.markdown2
-rw-r--r--es-es/forth-es.html.markdown226
-rw-r--r--es-es/hack-es.html.markdown307
-rw-r--r--es-es/javascript-es.html.markdown4
-rw-r--r--es-es/latex-es.html.markdown213
-rw-r--r--es-es/markdown-es.html.markdown10
-rw-r--r--es-es/objective-c-es.html.markdown851
-rw-r--r--es-es/php-es.html.markdown825
-rw-r--r--es-es/python-es.html.markdown14
-rw-r--r--es-es/r-es.html.markdown717
-rw-r--r--es-es/rust-es.html.markdown324
-rw-r--r--es-es/yaml-es.html.markdown189
-rw-r--r--fa-ir/bf-fa.html.markdown (renamed from fa-ir/brainfuck-fa.html.markdown)2
-rw-r--r--fa-ir/css-fa.html.markdown307
-rw-r--r--factor.html.markdown182
-rw-r--r--fi-fi/markdown-fi.html.markdown12
-rw-r--r--fi-fi/ruby-fi.html.markdown608
-rw-r--r--forth.html.markdown2
-rw-r--r--fr-fr/HTML-fr.html.markdown3
-rw-r--r--fr-fr/bf-fr.html.markdown (renamed from fr-fr/brainfuck-fr.html.markdown)2
-rw-r--r--fr-fr/d.html.markdown12
-rw-r--r--fr-fr/go-fr.html.markdown2
-rw-r--r--fr-fr/make-fr.html.markdown268
-rw-r--r--fr-fr/markdown.html.markdown10
-rw-r--r--fr-fr/objective-c-fr.html.markdown3
-rw-r--r--fr-fr/typescript-fr.html.markdown58
-rw-r--r--fr-fr/wolfram-fr.html.markdown167
-rw-r--r--fsharp.html.markdown8
-rw-r--r--git.html.markdown100
-rw-r--r--groovy.html.markdown6
-rw-r--r--haskell.html.markdown41
-rw-r--r--hu-hu/ruby-hu.html.markdown4
-rw-r--r--hu-hu/yaml-hu.html.markdown147
-rw-r--r--hy.html.markdown42
-rw-r--r--id-id/json-id.html.markdown5
-rw-r--r--id-id/php-id.html.markdown848
-rw-r--r--id-id/ruby-id.html.markdown622
-rw-r--r--id-id/xml-id.html.markdown79
-rw-r--r--inform7.html.markdown195
-rw-r--r--it-it/bash-it.html.markdown2
-rw-r--r--it-it/bf-it.html.markdown (renamed from it-it/brainfuck-it.html.markdown)2
-rw-r--r--it-it/coffeescript-it.html.markdown2
-rw-r--r--it-it/git-it.html.markdown498
-rw-r--r--it-it/python-it.html.markdown647
-rw-r--r--it-it/ruby-ecosystem-it.html.markdown145
-rw-r--r--ja-jp/bash-jp.html.markdown4
-rw-r--r--ja-jp/php-jp.html.markdown777
-rw-r--r--java.html.markdown97
-rw-r--r--julia.html.markdown39
-rw-r--r--ko-kr/bf-kr.html.markdown (renamed from ko-kr/brainfuck-kr.html.markdown)2
-rw-r--r--ko-kr/erlang-kr.html.markdown333
-rw-r--r--ko-kr/lua-kr.html.markdown2
-rw-r--r--kotlin.html.markdown322
-rw-r--r--latex.html.markdown6
-rw-r--r--less.html.markdown4
-rw-r--r--lt-lt/json-lt.html.markdown2
-rw-r--r--make.html.markdown23
-rw-r--r--markdown.html.markdown78
-rw-r--r--ms-my/bash-my.html.markdown284
-rw-r--r--ms-my/json-my.html.markdown102
-rw-r--r--ms-my/sass-my.html.markdown232
-rw-r--r--ms-my/xml-my.html.markdown130
-rw-r--r--nim.html.markdown2
-rw-r--r--nl-nl/amd-nl.html.markdown235
-rw-r--r--nl-nl/bf.html.markdown (renamed from nl-nl/brainfuck-nl.html.markdown)2
-rw-r--r--nl-nl/coffeescript-nl.html.markdown11
-rw-r--r--nl-nl/json-nl.html.markdown71
-rw-r--r--nl-nl/json.html.markdown61
-rw-r--r--nl-nl/typescript-nl.html.markdown174
-rw-r--r--nl-nl/xml-nl.html.markdown134
-rw-r--r--ocaml.html.markdown4
-rw-r--r--paren.html.markdown15
-rw-r--r--perl.html.markdown145
-rw-r--r--perl6.html.markdown9
-rw-r--r--php.html.markdown55
-rw-r--r--pl-pl/bf-pl.html.markdown (renamed from pl-pl/brainfuck-pl.html.markdown)2
-rw-r--r--pl-pl/perl-pl.html.markdown8
-rw-r--r--pl-pl/xml-pl.html.markdown137
-rw-r--r--powershell.html.markdown14
-rw-r--r--pt-br/amd.html.markdown218
-rw-r--r--pt-br/asymptotic-notation-pt.html.markdown159
-rw-r--r--pt-br/bash-pt.html.markdown282
-rw-r--r--pt-br/bf.html.markdown (renamed from pt-br/brainfuck-pt.html.markdown)2
-rw-r--r--pt-br/csharp.html.markdown896
-rw-r--r--pt-br/git-pt.html.markdown32
-rw-r--r--pt-br/hy-pt.html.markdown2
-rw-r--r--pt-br/java-pt.html.markdown44
-rw-r--r--pt-br/javascript-pt.html.markdown6
-rw-r--r--pt-br/markdown-pt.html.markdown8
-rw-r--r--pt-br/paren-pt.html.markdown196
-rw-r--r--pt-br/ruby-ecosystem-pt.html.markdown147
-rw-r--r--pt-br/ruby-pt.html.markdown12
-rw-r--r--pt-br/yaml-pt.html.markdown142
-rw-r--r--pt-pt/bf.html.markdown (renamed from pt-pt/brainfuck-pt.html.markdown)0
-rw-r--r--purescript.html.markdown7
-rw-r--r--python.html.markdown41
-rw-r--r--python3.html.markdown21
-rw-r--r--pythonstatcomp.html.markdown110
-rw-r--r--ro-ro/bash-ro.html.markdown159
-rw-r--r--ro-ro/bf-ro.html.markdown90
-rw-r--r--ro-ro/coffeescript-ro.html.markdown102
-rw-r--r--ro-ro/json-ro.html.markdown61
-rw-r--r--ro-ro/latex.html.markdown258
-rw-r--r--ro-ro/python-ro.html.markdown17
-rw-r--r--ro-ro/xml-ro.html.markdown133
-rw-r--r--ru-ru/bf.html.markdown (renamed from ru-ru/brainfuck-ru.html.markdown)2
-rw-r--r--ru-ru/d-ru.html.markdown754
-rw-r--r--ru-ru/java-ru.html.markdown46
-rw-r--r--ru-ru/markdown-ru.html.markdown300
-rw-r--r--ru-ru/objective-c-ru.html.markdown27
-rw-r--r--ru-ru/php-ru.html.markdown57
-rw-r--r--ru-ru/tmux-ru.html.markdown252
-rw-r--r--ru-ru/typescript-ru.html.markdown173
-rw-r--r--ruby.html.markdown25
-rw-r--r--scala.html.markdown29
-rw-r--r--self.html.markdown2
-rw-r--r--smalltalk.html.markdown6
-rw-r--r--solidity.html.markdown795
-rw-r--r--sv-se/json-sv.html.markdown62
-rw-r--r--swift.html.markdown12
-rw-r--r--ta_in/css-ta.html.markdown6
-rw-r--r--ta_in/javascript-ta.html.markdown4
-rw-r--r--ta_in/xml-ta.html.markdown4
-rw-r--r--tmux.html.markdown4
-rw-r--r--tr-tr/bf-tr.html.markdown (renamed from tr-tr/brainfuck-tr.html.markdown)2
-rw-r--r--tr-tr/markdown-tr.html.markdown8
-rw-r--r--tr-tr/swift-tr.html.markdown13
-rw-r--r--typescript.html.markdown8
-rw-r--r--ua-ua/bash-ua.html.markdown296
-rw-r--r--ua-ua/json-ua.html.markdown67
-rw-r--r--uk-ua/java-ua.html.markdown783
-rw-r--r--uk-ua/json-ua.html.markdown8
-rw-r--r--vi-vn/objective-c-vi.html.markdown2
-rw-r--r--vi-vn/ruby-ecosystem-vi.html.markdown148
-rw-r--r--wolfram.html.markdown137
-rw-r--r--zfs.html.markdown18
-rw-r--r--zh-cn/bf-cn.html.markdown (renamed from zh-cn/brainfuck-cn.html.markdown)2
-rw-r--r--zh-cn/common-lisp-cn.html.markdown2
-rw-r--r--zh-cn/java-cn.html.markdown4
-rw-r--r--zh-cn/lua-cn.html.markdown31
-rw-r--r--zh-cn/markdown-cn.html.markdown8
-rw-r--r--zh-cn/scala-cn.html.markdown2
-rw-r--r--zh-cn/swift-cn.html.markdown43
-rw-r--r--zh-cn/tmux-cn.html.markdown253
-rw-r--r--zh-cn/typescript-cn.html.markdown173
-rw-r--r--zh-tw/python-tw.html.markdown727
184 files changed, 23173 insertions, 1735 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..dd41ec4a
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,16 @@
+**/*~
+**/*#
+**/#*#
+**/*.swp
+**/*.swo
+**/*.bak
+**/*.log*
+**/*.sublime-workspace
+**/.DS_Store
+**/.DS_Store?
+**/._*
+**/.Spotlight-V100
+**/.Trashes
+**/ehthumbs.db
+**/Thumbs.db
+**/desktop.ini \ No newline at end of file
diff --git a/CONTRIBUTING.markdown b/CONTRIBUTING.markdown
new file mode 100644
index 00000000..9ee33ebc
--- /dev/null
+++ b/CONTRIBUTING.markdown
@@ -0,0 +1,70 @@
+# Contributing
+
+All contributions are welcome, from the tiniest typo to a brand new article.
+Translations in all languages are welcome (or, for that matter, original
+articles in any language). Send a pull request or open an issue any time of day
+or night.
+
+**Please prepend the tag `[language/lang-code]` to your issues and pull
+requests.** For example, `[python/en]` for English Python. This will help
+everyone pick out things they care about.
+
+We're happy for any contribution in any form, but if you're making more than one
+major change (i.e. translations for two different languages) it would be super
+cool of you to make a separate pull request for each one so that someone can
+review them more effectively and/or individually.
+
+## Style Guidelines
+
+- **Keep lines of under 80 chars**
+ + Try to keep **line length in code blocks to 80 characters or fewer**.
+ + Otherwise, the text will overflow and look odd.
+- **Prefer example to exposition**
+ + Try to use as few words as possible.
+ + Code examples are preferred over exposition in all cases.
+- **Eschew surplusage**
+ + We welcome newcomers, but the target audience for this site is programmers
+ with some experience.
+ + Try to avoid explaining basic concepts except for those specific to the
+ language in question.
+ + Keep articles succinct and scannable. We all know how to use Google here.
+- **Use UTF-8**
+ + For translations (or EN articles with non-ASCII characters) please make sure
+ your file is UTF-8 encoded.
+ + Try to leave out the byte-order-mark at the start of the file. (`:set nobomb`
+ in Vim)
+
+
+### Header configuration
+
+The actual site uses Middleman to generate HTML files from these Markdown ones.
+Middleman, or at least the custom scripts underpinning the site, requires that
+some key information be defined in the header.
+
+The following fields are necessary for English articles about programming
+languages:
+
+- **language** The *programming language* in question
+- **contributors** A list of [author, URL] lists to credit
+
+Other fields:
+
+- **filename**: The filename for this article's code. It will be fetched, mashed
+ together, and made downloadable.
+ + For non-English articles, *filename* should have a language-specific
+ suffix.
+- **lang**: For translations, the human language this article is in. For
+ categorization, mostly.
+
+Here's an example header for an Esperanto translation of Ruby:
+
+```yaml
+---
+language: ruby
+filename: learnruby-epo.ruby
+contributors:
+ - ["Doktor Esperanto", "http://example.com/"]
+ - ["Someone else", "http://someoneelseswebsite.com/"]
+lang: ep-ep
+---
+```
diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 00000000..3f55e3fb
--- /dev/null
+++ b/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,4 @@
+- [ ] PR touches only one file (or a set of logically related files with similar changes made)
+- [ ] Content changes are aimed at *intermediate to experienced programmers* (this is a poor format for explaining fundamental programming concepts)
+- [ ] YAML Frontmatter formatted according to [CONTRIBUTING.md](https://github.com/adambard/learnxinyminutes-docs/blob/master/CONTRIBUTING.markdown)
+ - [ ] Seriously, look at it now. Watch for quotes and double-check field names.
diff --git a/README.markdown b/README.markdown
index 94afbcbe..a71e85bd 100644
--- a/README.markdown
+++ b/README.markdown
@@ -1,88 +1,45 @@
-# [Learn X in Y minutes](http://learnxinyminutes.com)
+# [Learn X in Y minutes][1]
Whirlwind tours of (several, hopefully many someday) popular and
-ought-to-be-more-popular programming languages, presented as valid,
-commented code and explained as they go.
+ought-to-be-more-popular programming languages, presented as valid, commented
+code and explained as they go.
## We need YOU!...
-... to write more inline code tutorials. Just grab an existing file from
-this repo and copy the formatting (don't worry, it's all very simple).
-Make a new file, send a pull request, and if it passes muster I'll get it up pronto.
-Remember to fill in the "contributors" fields so you get credited
-properly!
+... to write more inline code tutorials. Just grab an existing file from this
+repo and copy the formatting (don't worry, it's all very simple). Make a new
+file, send a pull request, and if it passes muster I'll get it up pronto.
+Remember to fill in the "contributors" fields so you get credited properly!
## Contributing
-All contributions are welcome, from the tiniest typo to a brand new article. Translations
-in all languages are welcome (or, for that matter, original articles in any language).
-Send a pull request or open an issue any time of day or night.
+All contributions are welcome, from the tiniest typo to a brand new article.
+Translations in all languages are welcome (or, for that matter, original
+articles in any language). Send a pull request or open an issue any time of day
+or night.
-**Please tag your issues and pull requests with [language/lang-code] at the beginning**
-**(e.g. [python/en] for English Python).** This will help everyone pick out things they
-care about.
+**Please prepend the tag `[language/lang-code]` to your issues and pull
+requests.** For example, `[python/en]` for English Python. This will help
+everyone pick out things they care about.
-We're happy for any contribution in any form, but if you're making more than one major change
-(i.e. translations for two different languages) it would be super cool of you to make a
-separate pull request for each one so that someone can review them more effectively and/or
-individually.
+We're happy for any contribution in any form, but if you're making more than one
+major change (i.e. translations for two different languages) it would be super
+cool of you to make a separate pull request for each one so that someone can
+review them more effectively and/or individually.
-### Style Guidelines
+For a detailed style guide, please review the full [CONTRIBUTING][2] guidelines.
-* **Keep lines under 80 chars**
-* **Prefer example to exposition**
-* **Eschew surplusage**
-* **Use UTF-8**
-
-Long version:
-
-* Try to keep **line length in code blocks to 80 characters or fewer**, or they'll overflow
- and look odd.
-
-* Try to use as few words as possible. Code examples are preferred over exposition in all cases.
-
-* We welcome newcomers, but the target audience for this site is programmers with some experience.
- So, try to avoid explaining basic concepts except for those specific to the language in question,
- to keep articles succinct and scannable. We all know how to use Google here.
-
-* For translations (or English articles with non-ASCII characters), please make sure your file is
- UTF-8 encoded, and try to leave out the byte-order-mark at the start of the file. (`:set nobomb` in Vim)
-
-### Header configuration
-
-The actual site uses Middleman to generate HTML files from these Markdown ones. Middleman, or at least
-the custom scripts underpinning the site, required that some key information be defined in the header.
-
-The following fields are necessary for English articles about programming languages:
-
-* **language** The *programming language* in question
-* **contributors** A list of [author, URL] lists to credit
-
-Other fields:
-
-* **filename**: The filename for this article's code. It will be fetched, mashed together, and made downloadable.
- For non-English articles, *filename* should have a language-specific suffix.
-* **lang**: For translations, the human language this article is in. For categorization, mostly.
-
-Here's an example header for an Esperanto translation of Ruby:
+## License
-```yaml
----
-language: ruby
-filename: learnruby-epo.ruby
-contributors:
- - ["Doktor Esperanto", "http://example.com/"]
- - ["Someone else", "http://someoneelseswebsite.com/"]
-lang: ep-ep
----
-```
+Contributors retain copyright to their work, and can request removal at any
+time. By uploading a doc here, you agree to publish your work under the default
+[Creative Commons Attribution-ShareAlike 3.0 Unported][3] licensing included on
+each doc page.
-## License
+Anything not covered by the above -- basically, this README -- you can use as
+you wish, I guess.
-Contributors retain copyright to their work, and can request removal at any time.
-By uploading a doc here, you agree to publish your work under the default
-[Creative Commons Attribution-ShareAlike 3.0 Unported](http://creativecommons.org/licenses/by-sa/3.0/deed.en_US)
-licensing included on each doc page.
-Anything not covered by the above -- basically, this README -- you can use
-as you wish, I guess.
+[1]: http://learnxinyminutes.com
+[2]: /CONTRIBUTING.markdown
+[3]: http://creativecommons.org/licenses/by-sa/3.0/deed.en_US
diff --git a/asciidoc.html.markdown b/asciidoc.html.markdown
new file mode 100644
index 00000000..8326c581
--- /dev/null
+++ b/asciidoc.html.markdown
@@ -0,0 +1,122 @@
+---
+language: asciidoc
+contributors:
+ - ["Ryan Mavilia", "http://unoriginality.rocks/"]
+filename: asciidoc.md
+---
+
+AsciiDoc is a markup language similar to Markdown and it can be used for anything from books to blogs. Created in 2002 by Stuart Rackham the language is simple but it allows for a great amount of customization.
+
+Document Header
+
+Headers are optional and can't contain blank lines. It must be offset from content by at least one blank line.
+
+Title Only
+
+```
+= Document Title
+
+First sentence of document.
+```
+
+Title and Author
+
+```
+= Document Title
+First Last <first.last@learnxinyminutes.com>
+
+Start of this document.
+```
+
+Multiple Authors
+
+```
+= Document Title
+John Doe <john@go.com>; Jane Doe<jane@yo.com>; Black Beard <beardy@pirate.com>
+
+Start of a doc with multiple authors.
+```
+
+Revision Line (requires an author line)
+
+```
+= Doc Title V1
+Potato Man <chip@crunchy.com>
+v1.0, 2016-01-13
+
+This article about chips is going to be fun.
+```
+
+Paragraphs
+
+```
+You don't need anything special for paragraphs.
+
+Add a blank line between paragraphs to separate them.
+
+To create a line blank add a +
+and you will receive a line break!
+```
+
+Formatting Text
+
+```
+_underscore creates italics_
+*asterisks for bold*
+*_combine for extra fun_*
+`use ticks to signify monospace`
+`*bolded monospace*`
+```
+
+Section Titles
+
+```
+= Level 0 (may only be used in document's header)
+
+== Level 1 <h2>
+
+=== Level 2 <h3>
+
+==== Level 3 <h4>
+
+===== Level 4 <h5>
+
+====== Level 5 <h6>
+
+======= Level 6 <h7>
+
+```
+
+Lists
+
+To create a bulleted list use asterisks.
+
+```
+* foo
+* bar
+* baz
+```
+
+To create a numbered list use periods.
+
+```
+. item 1
+. item 2
+. item 3
+```
+
+You can nest lists by adding extra asterisks or periods up to five times.
+
+```
+* foo 1
+** foo 2
+*** foo 3
+**** foo 4
+***** foo 5
+
+. foo 1
+.. foo 2
+... foo 3
+.... foo 4
+..... foo 5
+```
diff --git a/asymptotic-notation.html.markdown b/asymptotic-notation.html.markdown
index a516737e..a23ef1c8 100644
--- a/asymptotic-notation.html.markdown
+++ b/asymptotic-notation.html.markdown
@@ -3,41 +3,52 @@ category: Algorithms & Data Structures
name: Asymptotic Notation
contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
+ - ["Divay Prakash", "http://github.com/divayprakash"]
---
# Asymptotic Notations
## What are they?
-Asymptotic Notations are languages that allow us to analyze an algorithm's running time by
-identifying its behavior as the input size for the algorithm increases. This is also known as
-an algorithm's growth rate. Does the algorithm suddenly become incredibly slow when the input
-size grows? Does it mostly maintain its quick run time as the input size increases?
-Asymptotic Notation gives us the ability to answer these questions.
+Asymptotic Notations are languages that allow us to analyze an algorithm's
+running time by identifying its behavior as the input size for the algorithm
+increases. This is also known as an algorithm's growth rate. Does the
+algorithm suddenly become incredibly slow when the input size grows? Does it
+mostly maintain its quick run time as the input size increases? Asymptotic
+Notation gives us the ability to answer these questions.
## Are there alternatives to answering these questions?
-One way would be to count the number of primitive operations at different input sizes.
-Though this is a valid solution, the amount of work this takes for even simple algorithms
-does not justify its use.
+One way would be to count the number of primitive operations at different
+input sizes. Though this is a valid solution, the amount of work this takes
+for even simple algorithms does not justify its use.
-Another way is to physically measure the amount of time an algorithm takes to complete
-given different input sizes. However, the accuracy and relativity (times obtained would
-only be relative to the machine they were computed on) of this method is bound to
-environmental variables such as computer hardware specifications, processing power, etc.
+Another way is to physically measure the amount of time an algorithm takes to
+complete given different input sizes. However, the accuracy and relativity
+(times obtained would only be relative to the machine they were computed on)
+of this method is bound to environmental variables such as computer hardware
+specifications, processing power, etc.
## Types of Asymptotic Notation
-In the first section of this doc we described how an Asymptotic Notation identifies the
-behavior of an algorithm as the input size changes. Let us imagine an algorithm as a function
-f, n as the input size, and f(n) being the running time. So for a given algorithm f, with input
-size n you get some resultant run time f(n). This results in a graph where the Y axis is the
-runtime, X axis is the input size, and plot points are the resultants of the amount of time
-for a given input size.
-
-You can label a function, or algorithm, with an Asymptotic Notation in many different ways.
-Some examples are, you can describe an algorithm by its best case, worse case, or equivalent case.
-The most common is to analyze an algorithm by its worst case. You typically don't evaluate by best case because those conditions aren't what you're planning for. A very good example of this is sorting algorithms; specifically, adding elements to a tree structure. Best case for most algorithms could be as low as a single operation. However, in most cases, the element you're adding will need to be sorted appropriately through the tree, which could mean examining an entire branch. This is the worst case, and this is what we plan for.
+In the first section of this doc we described how an Asymptotic Notation
+identifies the behavior of an algorithm as the input size changes. Let us
+imagine an algorithm as a function f, n as the input size, and f(n) being
+the running time. So for a given algorithm f, with input size n you get
+some resultant run time f(n). This results in a graph where the Y axis is the
+runtime, X axis is the input size, and plot points are the resultants of the
+amount of time for a given input size.
+
+You can label a function, or algorithm, with an Asymptotic Notation in many
+different ways. Some examples are, you can describe an algorithm by its best
+case, worse case, or equivalent case. The most common is to analyze an
+algorithm by its worst case. You typically don't evaluate by best case because
+those conditions aren't what you're planning for. A very good example of this
+is sorting algorithms; specifically, adding elements to a tree structure. Best
+case for most algorithms could be as low as a single operation. However, in
+most cases, the element you're adding will need to be sorted appropriately
+through the tree, which could mean examining an entire branch. This is the
+worst case, and this is what we plan for.
### Types of functions, limits, and simplification
@@ -45,16 +56,25 @@ The most common is to analyze an algorithm by its worst case. You typically don'
Logarithmic Function - log n
Linear Function - an + b
Quadratic Function - an^2 + bn + c
-Polynomial Function - an^z + . . . + an^2 + a*n^1 + a*n^0, where z is some constant
+Polynomial Function - an^z + . . . + an^2 + a*n^1 + a*n^0, where z is some
+constant
Exponential Function - a^n, where a is some constant
```
-These are some basic function growth classifications used in various notations. The list starts at the slowest growing function (logarithmic, fastest execution time) and goes on to the fastest growing (exponential, slowest execution time). Notice that as 'n', or the input, increases in each of those functions, the result clearly increases much quicker in quadratic, polynomial, and exponential, compared to logarithmic and linear.
-
-One extremely important note is that for the notations about to be discussed you should do your best to use simplest terms. This means to disregard constants, and lower order terms, because as the input size (or n in our f(n)
-example) increases to infinity (mathematical limits), the lower order terms and constants are of little
-to no importance. That being said, if you have constants that are 2^9001, or some other ridiculous,
-unimaginable amount, realize that simplifying will skew your notation accuracy.
+These are some basic function growth classifications used in various
+notations. The list starts at the slowest growing function (logarithmic,
+fastest execution time) and goes on to the fastest growing (exponential,
+slowest execution time). Notice that as 'n', or the input, increases in each
+of those functions, the result clearly increases much quicker in quadratic,
+polynomial, and exponential, compared to logarithmic and linear.
+
+One extremely important note is that for the notations about to be discussed
+you should do your best to use simplest terms. This means to disregard
+constants, and lower order terms, because as the input size (or n in our f(n)
+example) increases to infinity (mathematical limits), the lower order terms
+and constants are of little to no importance. That being said, if you have
+constants that are 2^9001, or some other ridiculous, unimaginable amount,
+realize that simplifying will skew your notation accuracy.
Since we want simplest form, lets modify our table a bit...
@@ -67,10 +87,13 @@ Exponential - a^n, where a is some constant
```
### Big-O
-Big-O, commonly written as O, is an Asymptotic Notation for the worst case, or ceiling of growth
-for a given function. Say `f(n)` is your algorithm runtime, and `g(n)` is an arbitrary time complexity
-you are trying to relate to your algorithm. `f(n)` is O(g(n)), if for any real constant c (c > 0),
-`f(n)` <= `c g(n)` for every input size n (n > 0).
+Big-O, commonly written as **O**, is an Asymptotic Notation for the worst
+case, or ceiling of growth for a given function. It provides us with an
+_**asymptotic upper bound**_ for the growth rate of runtime of an algorithm.
+Say `f(n)` is your algorithm runtime, and `g(n)` is an arbitrary time
+complexity you are trying to relate to your algorithm. `f(n)` is O(g(n)), if
+for some real constant c (c > 0), `f(n)` <= `c g(n)` for every input size
+n (n > 0).
*Example 1*
@@ -114,19 +137,62 @@ Is there some constant c that satisfies this for all n?
No, there isn't. `f(n)` is NOT O(g(n)).
### Big-Omega
-Big-Omega, commonly written as Ω, is an Asymptotic Notation for the best case, or a floor growth rate
-for a given function.
+Big-Omega, commonly written as **Ω**, is an Asymptotic Notation for the best
+case, or a floor growth rate for a given function. It provides us with an
+_**asymptotic lower bound**_ for the growth rate of runtime of an algorithm.
+
+`f(n)` is Ω(g(n)), if for some real constant c (c > 0), `f(n)` is >= `c g(n)`
+for every input size n (n > 0).
+
+### Note
+
+The asymptotic growth rates provided by big-O and big-omega notation may or
+may not be asymptotically tight. Thus we use small-o and small-omega notation
+to denote bounds that are not asymptotically tight.
+
+### Small-o
+Small-o, commonly written as **o**, is an Asymptotic Notation to denote the
+upper bound (that is not asymptotically tight) on the growth rate of runtime
+of an algorithm.
+
+`f(n)` is o(g(n)), if for any real constant c (c > 0), `f(n)` is < `c g(n)`
+for every input size n (n > 0).
+
+The definitions of O-notation and o-notation are similar. The main difference
+is that in f(n) = O(g(n)), the bound f(n) <= g(n) holds for _**some**_
+constant c > 0, but in f(n) = o(g(n)), the bound f(n) < c g(n) holds for
+_**all**_ constants c > 0.
+
+### Small-omega
+Small-omega, commonly written as **ω**, is an Asymptotic Notation to denote
+the lower bound (that is not asymptotically tight) on the growth rate of
+runtime of an algorithm.
+
+`f(n)` is ω(g(n)), if for any real constant c (c > 0), `f(n)` is > `c g(n)`
+for every input size n (n > 0).
+
+The definitions of Ω-notation and ω-notation are similar. The main difference
+is that in f(n) = Ω(g(n)), the bound f(n) >= g(n) holds for _**some**_
+constant c > 0, but in f(n) = ω(g(n)), the bound f(n) > c g(n) holds for
+_**all**_ constants c > 0.
+
+### Theta
+Theta, commonly written as **Θ**, is an Asymptotic Notation to denote the
+_**asymptotically tight bound**_ on the growth rate of runtime of an algorithm.
+
+`f(n)` is Θ(g(n)), if for some real constants c1, c2 (c1 > 0, c2 > 0),
+`c1 g(n)` is < `f(n)` is < `c2 g(n)` for every input size n (n > 0).
-`f(n)` is Ω(g(n)), if for any real constant c (c > 0), `f(n)` is >= `c g(n)` for every input size n (n > 0).
+∴ `f(n)` is Θ(g(n)) implies `f(n)` is O(g(n)) as well as `f(n)` is Ω(g(n)).
-Feel free to head over to additional resources for examples on this. Big-O is the primary notation used
-for general algorithm time complexity.
+Feel free to head over to additional resources for examples on this. Big-O
+is the primary notation use for general algorithm time complexity.
### Ending Notes
-It's hard to keep this kind of topic short, and you should definitely go through the books and online
-resources listed. They go into much greater depth with definitions and examples.
-More where x='Algorithms & Data Structures' is on its way; we'll have a doc up on analyzing actual
-code examples soon.
+It's hard to keep this kind of topic short, and you should definitely go
+through the books and online resources listed. They go into much greater depth
+with definitions and examples. More where x='Algorithms & Data Structures' is
+on its way; we'll have a doc up on analyzing actual code examples soon.
## Books
@@ -137,3 +203,4 @@ code examples soon.
* [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)
+* [Big-O Cheatsheet](http://bigocheatsheet.com/) - common structures, operations, and algorithms, ranked by complexity.
diff --git a/bash.html.markdown b/bash.html.markdown
index 211d2944..f3c9cccc 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -83,7 +83,7 @@ echo Hello, $Name!
# We have the usual if structure:
# use 'man test' for more info about conditionals
-if [ $Name -ne $USER ]
+if [ $Name != $USER ]
then
echo "Your name isn't your username"
else
@@ -91,12 +91,12 @@ else
fi
# NOTE: if $Name is empty, bash sees the above condition as:
-if [ -ne $USER ]
+if [ != $USER ]
# which is invalid syntax
# so the "safe" way to use potentially empty variables in bash is:
-if [ "$Name" -ne $USER ] ...
+if [ "$Name" != $USER ] ...
# which, when $Name is empty, is seen by bash as:
-if [ "" -ne $USER ] ...
+if [ "" != $USER ] ...
# which works as expected
# There is also conditional execution
@@ -130,6 +130,15 @@ ls -l # Lists every file and directory on a separate line
# .txt files in the current directory:
ls -l | grep "\.txt"
+# Since bash works in the context of a current directory, you might want to
+# run your command in some other directory. We have cd for changing location:
+cd ~ # change to home directory
+cd .. # go up one directory
+ # (^^say, from /home/username/Downloads to /home/username)
+cd /home/username/Documents # change to specified directory
+cd ~/Documents/.. # still in home directory..isn't it??
+
+
# You can redirect command input and output (stdin, stdout, and stderr).
# Read from stdin until ^EOF$ and overwrite hello.py with the lines
# between "EOF":
diff --git a/brainfuck.html.markdown b/bf.html.markdown
index a76169c8..c8bbee61 100644
--- a/brainfuck.html.markdown
+++ b/bf.html.markdown
@@ -1,5 +1,5 @@
---
-language: brainfuck
+language: bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]
diff --git a/c++.html.markdown b/c++.html.markdown
index 6b452b1b..a02e7e5b 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -149,7 +149,7 @@ namespace First {
namespace Second {
void foo()
{
- printf("This is Second::foo\n")
+ printf("This is Second::foo\n");
}
}
@@ -330,7 +330,7 @@ ECarTypes GetPreferredCarType()
}
// As of C++11 there is an easy way to assign a type to the enum which can be
-// useful in serialization of data and converting enums back-and-forth between
+// useful in serialization of data and converting enums back-and-forth between
// the desired type and their respective constants
enum ECarTypes : uint8_t
{
@@ -352,7 +352,7 @@ void WritePreferredCarTypeToFile(ECarTypes InputCarType)
}
// On the other hand you may not want enums to be accidentally cast to an integer
-// type or to other enums so it is instead possible to create an enum class which
+// type or to other enums so it is instead possible to create an enum class which
// won't be implicitly converted
enum class ECarTypes : uint8_t
{
@@ -468,7 +468,7 @@ int main() {
// Inheritance:
// This class inherits everything public and protected from the Dog class
-// as well as private but may not directly access private members/methods
+// as well as private but may not directly access private members/methods
// without a public or protected method for doing so
class OwnedDog : public Dog {
@@ -820,6 +820,76 @@ std::map<Foo, int, compareFunction> fooMap;
fooMap[Foo(1)] = 1;
fooMap.find(Foo(1)); //true
+///////////////////////////////////////
+// Lambda Expressions (C++11 and above)
+///////////////////////////////////////
+
+// lambdas are a convenient way of defining an anonymous function
+// object right at the location where it is invoked or passed as
+// an argument to a function.
+
+// For example, consider sorting a vector of pairs using the second
+// value of the pair
+
+vector<pair<int, int> > tester;
+tester.push_back(make_pair(3, 6));
+tester.push_back(make_pair(1, 9));
+tester.push_back(make_pair(5, 0));
+
+// Pass a lambda expression as third argument to the sort function
+// sort is from the <algorithm> header
+
+sort(tester.begin(), tester.end(), [](const pair<int, int>& lhs, const pair<int, int>& rhs) {
+ return lhs.second < rhs.second;
+ });
+
+// Notice the syntax of the lambda expression,
+// [] in the lambda is used to "capture" variables
+// The "Capture List" defines what from the outside of the lambda should be available inside the function body and how.
+// It can be either:
+// 1. a value : [x]
+// 2. a reference : [&x]
+// 3. any variable currently in scope by reference [&]
+// 4. same as 3, but by value [=]
+// Example:
+
+vector<int> dog_ids;
+// number_of_dogs = 3;
+for(int i = 0; i < 3; i++) {
+ dog_ids.push_back(i);
+}
+
+int weight[3] = {30, 50, 10};
+
+// Say you want to sort dog_ids according to the dogs' weights
+// So dog_ids should in the end become: [2, 0, 1]
+
+// Here's where lambda expressions come in handy
+
+sort(dog_ids.begin(), dog_ids.end(), [&weight](const int &lhs, const int &rhs) {
+ return weight[lhs] < weight[rhs];
+ });
+// Note we captured "weight" by reference in the above example.
+// More on Lambdas in C++ : http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11
+
+///////////////////////////////
+// Range For (C++11 and above)
+///////////////////////////////
+
+// You can use a range for loop to iterate over a container
+int arr[] = {1, 10, 3};
+
+for(int elem: arr){
+ cout << elem << endl;
+}
+
+// You can use "auto" and not worry about the type of the elements of the container
+// For example:
+
+for(auto elem: arr) {
+ // Do something with each element of arr
+}
+
/////////////////////
// Fun stuff
/////////////////////
@@ -870,20 +940,50 @@ Foo f1;
f1 = f2;
-// How to truly clear a container:
-class Foo { ... };
-vector<Foo> v;
-for (int i = 0; i < 10; ++i)
- v.push_back(Foo());
+///////////////////////////////////////
+// Tuples (C++11 and above)
+///////////////////////////////////////
+
+#include<tuple>
+
+// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members ,
+// its elements are accessed by their order in the tuple.
+
+// We start with constructing a tuple.
+// Packing values into tuple
+auto first = make_tuple(10, 'A');
+const int maxN = 1e9;
+const int maxL = 15;
+auto second = make_tuple(maxN, maxL);
+
+// printing elements of 'first' tuple
+cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A
+
+// printing elements of 'second' tuple
+cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 15
+
+// Unpacking tuple into variables
+
+int first_int;
+char first_char;
+tie(first_int, first_char) = first;
+cout << first_int << " " << first_char << "\n"; // prints : 10 A
+
+// We can also create tuple like this.
+
+tuple<int, char, double> third(11, 'A', 3.14141);
+// tuple_size returns number of elements in a tuple (as a constexpr)
+
+cout << tuple_size<decltype(third)>::value << "\n"; // prints: 3
+
+// tuple_cat concatenates the elements of all the tuples in the same order.
-// Following line sets size of v to 0, but destructors don't get called
-// and resources aren't released!
-v.empty();
-v.push_back(Foo()); // New value is copied into the first Foo we inserted
+auto concatenated_tuple = tuple_cat(first, second, third);
+// concatenated_tuple becomes = (10, 'A', 1e9, 15, 11, 'A' ,3.14141)
-// Truly destroys all values in v. See section about temporary objects for
-// explanation of why this works.
-v.swap(vector<Foo>());
+cout << get<0>(concatenated_tuple) << "\n"; // prints: 10
+cout << get<3>(concatenated_tuple) << "\n"; // prints: 15
+cout << get<5>(concatenated_tuple) << "\n"; // prints: 'A'
```
Further Reading:
diff --git a/c.html.markdown b/c.html.markdown
index 7c2386ef..2fad5348 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -36,7 +36,6 @@ Multi-line comments don't nest /* Be careful */ // comment ends on this line...
enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT};
// MON gets 2 automatically, TUE gets 3, etc.
-
// Import headers with #include
#include <stdlib.h>
#include <stdio.h>
@@ -76,7 +75,7 @@ int main (int argc, char** argv)
///////////////////////////////////////
// Types
///////////////////////////////////////
-
+
// All variables MUST be declared at the top of the current block scope
// we declare them dynamically along the code for the sake of the tutorial
@@ -114,7 +113,6 @@ int main (int argc, char** argv)
// sizeof(obj) yields the size of the expression (variable, literal, etc.).
printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words)
-
// If the argument of the `sizeof` operator is an expression, then its argument
// is not evaluated (except VLAs (see below)).
// The value it yields in this case is a compile-time constant.
@@ -130,7 +128,6 @@ int main (int argc, char** argv)
int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes
// (assuming 4-byte words)
-
// You can initialize an array to 0 thusly:
char my_array[20] = {0};
@@ -146,9 +143,9 @@ int main (int argc, char** argv)
// can be declared as well. The size of such an array need not be a compile
// time constant:
printf("Enter the array size: "); // ask the user for an array size
- int size;
- fscanf(stdin, "%d", &size);
- int var_length_array[size]; // declare the VLA
+ int array_size;
+ fscanf(stdin, "%d", &array_size);
+ int var_length_array[array_size]; // declare the VLA
printf("sizeof array = %zu\n", sizeof var_length_array);
// Example:
@@ -239,7 +236,7 @@ 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";
+ char *s = "ILoveC";
int j = 0;
s[j++]; // => "i". Returns the j-th item of s THEN increments value of j.
j = 0;
@@ -313,9 +310,15 @@ int main (int argc, char** argv)
case 1:
printf("Huh, 'a' equals 1!\n");
break;
+ // Be careful - without a "break", execution continues until the
+ // next "break" is reached.
+ case 3:
+ case 4:
+ printf("Look at that.. 'a' is either 3, or 4\n");
+ break;
default:
// if `some_integral_expression` didn't match any of the labels
- fputs("error!\n", stderr);
+ fputs("Error!\n", stderr);
exit(-1);
break;
}
@@ -340,8 +343,7 @@ int main (int argc, char** argv)
https://ideone.com/GuPhd6
this will print out "Error occured at i = 52 & j = 99."
*/
-
-
+
///////////////////////////////////////
// Typecasting
///////////////////////////////////////
@@ -380,7 +382,6 @@ int main (int argc, char** argv)
// (%p formats an object pointer of type void *)
// => Prints some address in memory;
-
// Pointers start with * in their declaration
int *px, not_a_pointer; // px is a pointer to an int
px = &x; // Stores the address of x in px
@@ -426,7 +427,6 @@ int main (int argc, char** argv)
printf("%zu, %zu\n", sizeof arraythethird, sizeof ptr);
// probably prints "40, 4" or "40, 8"
-
// Pointers are incremented and decremented based on their type
// (this is called pointer arithmetic)
printf("%d\n", *(x_ptr + 1)); // => Prints 19
@@ -440,7 +440,7 @@ int main (int argc, char** argv)
for (xx = 0; xx < 20; xx++) {
*(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx
} // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints)
-
+
// Note that there is no standard way to get the length of a
// dynamically allocated array in C. Because of this, if your arrays are
// going to be passed around your program a lot, you need another variable
@@ -491,7 +491,7 @@ int add_two_ints(int x1, int x2)
/*
Functions are call by value. When a function is called, the arguments passed to
-≈the function are copies of the original arguments (except arrays). Anything you
+the function are copies of the original arguments (except arrays). Anything you
do to the arguments in the function do not change the value of the original
argument where the function was called.
@@ -572,8 +572,6 @@ void testFunc2() {
}
//**You may also declare functions as static to make them private**
-
-
///////////////////////////////////////
// User-defined types and structs
///////////////////////////////////////
@@ -690,6 +688,7 @@ typedef void (*my_fnp_type)(char *);
"%o"; // octal
"%%"; // prints %
*/
+
///////////////////////////////////////
// Order of Evaluation
///////////////////////////////////////
@@ -716,13 +715,13 @@ typedef void (*my_fnp_type)(char *);
/******************************* Header Files **********************************
-Header files are an important part of c as they allow for the connection of c
-source files and can simplify code and definitions by seperating them into
-seperate files.
+Header files are an important part of c as they allow for the connection of c
+source files and can simplify code and definitions by separating them into
+separate files.
-Header files are syntaxtically similar to c source files but reside in ".h"
-files. They can be included in your c source file by using the precompiler
-command #include "example.h", given that example.h exists in the same directory
+Header files are syntactically similar to c source files but reside in ".h"
+files. They can be included in your c source file by using the precompiler
+command #include "example.h", given that example.h exists in the same directory
as the c file.
*/
@@ -758,7 +757,7 @@ enum traffic_light_state {GREEN, YELLOW, RED};
Node createLinkedList(int *vals, int len);
/* Beyond the above elements, other definitions should be left to a c source */
-/* file. Excessive includeds or definitions should, also not be contained in */
+/* file. Excessive includes or definitions should, also not be contained in */
/* a header file but instead put into separate headers or a c file. */
#endif /* End of the if precompiler directive. */
@@ -780,4 +779,4 @@ Readable code is better than clever code and fast code. For a good, sane coding
Other than that, Google is your friend.
-[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member
+[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file
diff --git a/chapel.html.markdown b/chapel.html.markdown
index 866e92d2..9c1daf40 100644
--- a/chapel.html.markdown
+++ b/chapel.html.markdown
@@ -1066,7 +1066,7 @@ The more information you give the Chapel development team about issues you encou
Feel free to email the team and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman).
If you're really interested in the development of the compiler or contributing to the project,
-[check out the master Github repository](https://github.com/chapel-lang/chapel).
+[check out the master GitHub repository](https://github.com/chapel-lang/chapel).
It is under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0).
Installing the Compiler
diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown
index d49ad254..482612fe 100644
--- a/coldfusion.html.markdown
+++ b/coldfusion.html.markdown
@@ -233,40 +233,38 @@ ColdFusion started as a tag-based language. Almost all functionality is availabl
<em>Code for reference (Functions must return something to support IE)</em>
-<pre>
-&lt;cfcomponent&gt;
- &lt;cfset this.hello = "Hello" /&gt;
- &lt;cfset this.world = "world" /&gt;
-
- &lt;cffunction name="sayHello"&gt;
- &lt;cfreturn this.hello & ", " & this.world & "!" /&gt;
- &lt;/cffunction&gt;
+<cfcomponent>
+ <cfset this.hello = "Hello" />
+ <cfset this.world = "world" />
+
+ <cffunction name="sayHello">
+ <cfreturn this.hello & ", " & this.world & "!" />
+ </cffunction>
- &lt;cffunction name="setHello"&gt;
- &lt;cfargument name="newHello" type="string" required="true" /&gt;
+ <cffunction name="setHello">
+ <cfargument name="newHello" type="string" required="true" />
- &lt;cfset this.hello = arguments.newHello /&gt;
+ <cfset this.hello = arguments.newHello />
- &lt;cfreturn true /&gt;
- &lt;/cffunction&gt;
+ <cfreturn true />
+ </cffunction>
- &lt;cffunction name="setWorld"&gt;
- &lt;cfargument name="newWorld" type="string" required="true" /&gt;
+ <cffunction name="setWorld">
+ <cfargument name="newWorld" type="string" required="true" />
- &lt;cfset this.world = arguments.newWorld /&gt;
+ <cfset this.world = arguments.newWorld />
- &lt;cfreturn true /&gt;
- &lt;/cffunction&gt;
+ <cfreturn true />
+ </cffunction>
- &lt;cffunction name="getHello"&gt;
- &lt;cfreturn this.hello /&gt;
- &lt;/cffunction&gt;
+ <cffunction name="getHello">
+ <cfreturn this.hello />
+ </cffunction>
- &lt;cffunction name="getWorld"&gt;
- &lt;cfreturn this.world /&gt;
- &lt;/cffunction&gt;
-&lt;/cfcomponent&gt;
-</pre>
+ <cffunction name="getWorld">
+ <cfreturn this.world />
+ </cffunction>
+</cfcomponent>
<cfset this.hello = "Hello" />
<cfset this.world = "world" />
diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown
index 2b1f5de4..9a23bc26 100644
--- a/common-lisp.html.markdown
+++ b/common-lisp.html.markdown
@@ -339,7 +339,7 @@ nil ; for false - and the empty list
;; The () in the above is the list of arguments for the function
(defun hello (name)
- (format nil "Hello, ~a " name))
+ (format nil "Hello, ~a" name))
(hello "Steve") ; => "Hello, Steve"
@@ -430,7 +430,7 @@ nil ; for false - and the empty list
(defun walker (n)
(if (zerop n)
:walked
- (walker (1- n))))
+ (walker (- n 1))))
(walker 5) ; => :walked
diff --git a/cs-cz/brainfuck.html.markdown b/cs-cz/brainfuck.html.markdown
new file mode 100644
index 00000000..29abc21f
--- /dev/null
+++ b/cs-cz/brainfuck.html.markdown
@@ -0,0 +1,87 @@
+---
+language: brainfuck
+contributors:
+ - ["Prajit Ramachandran", "http://prajitr.github.io/"]
+ - ["Mathias Bynens", "http://mathiasbynens.be/"]
+translators:
+ - ["Vojta Svoboda", "https://github.com/vojtasvoboda/"]
+filename: learnbrainfuck-cz.bf
+lang: cs-cz
+---
+
+Brainfuck (psaný bez kapitálek s vyjímkou začátku věty) je extrémně minimální
+Turingovsky kompletní (ekvivalentní) programovací jazyk a má pouze 8 příkazů.
+
+Můžete si ho vyzkoušet přímo v prohlížeči s [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/).
+
+```
+Jakýkoliv znak mimo "><+-.,[]" (bez uvozovek) je ignorován.
+
+Brainfuck je reprezentován jako pole, které má 30.000 buněk s počátkem v nule
+a datovým ukazatelem na aktuální buňce.
+
+Můžeme využít těchto osm příkazů:
++ : Přičte k aktuální buňce jedničku.
+- : Odečte od aktuální buňky jedničku.
+> : Posune datový ukazatel na další buňku, která je napravo.
+< : Posune datový ukazatel na předchozí buňku, která je nalevo.
+. : Vytiskne ASCII hodnotu aktuální buňky (například 65 = 'A').
+, : Načte jeden znak do aktuální buňky.
+[ : Pokud je hodnota aktuální buňky nulová, přeskočí na buňku odpovídající ] .
+ Jinak skočí na další instrukci.
+] : Pokud je hodnota aktuální buňky nulova, přeskočí na další instrukci.
+ Jinak skočí zpět na instrukci odpovídající [ .
+
+[ a ] tak tvoří 'while' smyčku a tyto symboly musí tak být v páru.
+
+Pojďme se mrknout na některé brainfuck programy.
+
+++++++ [ > ++++++++++ < - ] > +++++ .
+
+Tento program vypíše písmeno 'A' (v ASCII je to číslo 65). Nejdříve navýší
+buňku #1 na hodnotu 6. Buňka #1 bude použita pro smyčku. Potom program vstoupí
+do smyčky ([) a sníží hodnotu buňky #1 o jedničku. Ve smyčce zvýší hodnotu
+buňky #2 desetkrát, vrátí ze zpět na buňku #1 a sníží její hodnotu o jedničku.
+Toto se stane šestkrát (je potřeba šestkrát snížit hodnotu buňky #1, aby byla
+nulová a program přeskočil na konec cyklu označený znakem ].
+
+Na konci smyčky, kdy jsme na buňce #1 (která má hodnotu 0), tak má buňka #2
+hodnotu 60. Přesuneme se na buňku #2 a pětkrát zvýšíme její hodnotu o jedničku
+na hodnotu 65. Na konci vypíšeme hodnotu buňky #2 - 65, což je v ASCII znak 'A'
+na terminálu.
+
+
+, [ > + < - ] > .
+
+Tento program přečte znak z uživatelského vstupu a zkopíruje ho do buňky #1.
+Poté začne smyčka - přesun na buňku #2, zvýšení hodnoty buňky #2 o jedničku,
+přesun zpět na buňku #1 a snížení její hodnoty o jedničku. Takto smyčka pokračuje
+do té doby, než je buňka #1 nulová a buňka #2 nabyde původní hodnotu buňky #1.
+Protože jsme na buňce #1, přesuneme se na buňku #2 a vytiskneme její hodnotu
+v ASCII.
+
+Je dobré vědět, že mezery jsou v programu uvedené pouze z důvodu čitelnosti.
+Program je možné klidně zapsat i takto:
+
+,[>+<-]>.
+
+
+Nyní se podívejte na tento program a zkuste zjistit co dělá:
+
+,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >>
+
+Tento program vezme dvě čísla ze vstupu a vynásobí je.
+
+Program nejdříve načte dvě vstupní hodnoty. Poté začíná smyčka řízená hodnotou
+v buňce #1 - přesun na buňku #2 a start druhé vnořené smyčky, která je řízená
+hodnotou v buňce #2 a zvyšuje hodnotu v buňce #3. Nicméně je zde problém
+kdy na konci vnitřní smyčky je v buňce #2 nula a smyčka by tak znovu
+napokračovala. Vyřešíme to tak, že zvyšujeme o jedničku i buňku #4 a její
+hodnotu poté překopírujeme do buňky #2. Na konci programu je v buňce #3
+výsledek.
+```
+
+A to je brainbuck. Zase tak složitý není, co? Zkuste si nyní napsat nějaký
+vlastní brainfuck program a nebo interpretr v jiném jazyce, což není zase
+tak složité, ale pokud jste opravdový masochista, zkuste si naprogramovat
+interpretr jazyka brainfuck v jazyce... brainfuck :)
diff --git a/cs-cz/elm.html.markdown b/cs-cz/elm.html.markdown
new file mode 100644
index 00000000..babd46a2
--- /dev/null
+++ b/cs-cz/elm.html.markdown
@@ -0,0 +1,373 @@
+---
+language: Elm
+contributors:
+ - ["Max Goldstein", "http://maxgoldste.in/"]
+translators:
+ - ["Robin Pokorný", "http://robinpokorny.com/"]
+filename: learnelm-cz.elm
+lang: cs-cz
+---
+
+Elm je funkcionální reaktivní jazyk, který se kompiluje do (klientského) JavaScriptu.
+Elm je silně typovaný, díky tomu je překladač schopen zachytit většinu chyb okamžitě a
+vypsat snadno srozumitelná chybová hlášení.
+Elm se hodí k tvorbě webových uživatelských rozhraní a her.
+
+
+```haskell
+-- Jednořádkové komentáře začínají dvěma pomlčkami.
+{- Víceřádkové komentáře mohou být takto uzavřeny do bloku.
+{- Mohou být i zanořeny. -}
+-}
+
+{-- Základy --}
+
+-- Aritmetika
+1 + 1 -- 2
+8 - 1 -- 7
+10 * 2 -- 20
+
+-- Každé číslo bez desetinné tečky je typu Int nebo Float.
+33 / 2 -- 16.5 s reálným dělením
+33 // 2 -- 16 s celočíselným dělením
+
+-- Umocňování
+5 ^ 2 -- 25
+
+-- Pravdivostní proměnné
+not True -- False
+not False -- True
+1 == 1 -- True
+1 /= 1 -- False
+1 < 10 -- True
+
+-- Řetězce a znaky
+"Toto je textový řetězec, protože používá dvojité uvozovky."
+'a' -- znak v jednoduchých uvozovkách
+
+-- Řetězce lze spojovat.
+"Ahoj " ++ "světe!" -- "Ahoj světe!"
+
+{-- Seznamy (List), n-tice (Tuple) a Záznamy (Record) --}
+
+-- Každá položka seznamu musí být stejného typu.
+["příliš", "žluťoučký", "kůň", "úpěl"]
+[1, 2, 3, 4, 5]
+-- Druhý příklad lze zapsat také pomocí dvou teček.
+[1..5]
+
+-- Spojovat seznamy lze stejně jako řetězce.
+[1..5] ++ [6..10] == [1..10] -- True
+
+-- K přidání položky do seznamu použijte funkci "cons".
+0 :: [1..5] -- [0, 1, 2, 3, 4, 5]
+
+-- Funkce "head" pro získání první položky seznamu i funkce "tail" pro získání následujích položek
+-- vrací typ Maybe. Místo zjišťování, jestli nějaká položka není null,
+-- se s chybějcími hodnotami vypořádáme explicitně.
+List.head [1..5] -- Just 1
+List.tail [1..5] -- Just [2, 3, 4, 5]
+List.head [] -- Nothing
+-- List.nazevFunkce odkazuje na funkci, která žije v modulu List.
+
+-- Každý prvek v n-tici může být jiného typu, ale n-tice má pevný počet prvků.
+("elm", 42)
+
+-- K získání hodnot z dvojice použijte funkce first a second.
+-- (Toto je pouze zkratka. Brzy si ukážeme, jak na to "správně".)
+fst ("elm", 42) -- "elm"
+snd ("elm", 42) -- 42
+
+-- Prázná n-tice, neboli "unit", se občas používá jako zástupný symbol.
+-- Je to jediná hodnota svého typu, který se také nazývá "Unit".
+()
+
+-- Záznamy jsou podobné n-ticím, ale prvky jsou pojmenovány. Na pořadí nezáleží.
+-- Povšimněte si, že hodnoty vlastností se přiřazují rovnítky, ne dvojtečkami.
+{ x = 3, y = 7 }
+
+-- K hodnotám se přistupuje pomocí tečky a názvu vlastnosti.
+{ x = 3, y = 7 }.x -- 3
+
+-- Nebo využitím přístupové funkce, což je jen tečka a název vlastnosti.
+.y { x = 3, y = 7 } -- 7
+
+-- Změna hodnoty vlastnosti v záznamu. (Záznam tuto vlastnost už musí mít.)
+{ osoba |
+ jmeno = "Jiří" }
+
+-- Změna více vlastností s využitím aktuálních hodnot.
+{ hmotnyBod |
+ poloha = hmotnyBod.poloha + hmotnyBod.rychlost,
+ rychlost = hmotnyBod.rychlost + hmotnyBod.zrychleni }
+
+{-- Řídicí struktury --}
+
+-- Podmínky vždy musí mít větev "else" a obě větve musí být stejného typu.
+if powerLevel > 9000 then
+ "PÁNI!"
+else
+ "hmm"
+
+-- Podmínky lze skládat za sebe.
+if n < 0 then
+ "n je záporné"
+else if n > 0 then
+ "n je kladné"
+else
+ "n je nula"
+
+-- Použíjte příkaz "case" k nalezení shody vzoru a různých možností.
+case seznam of
+ [] -> "odpovídá práznému seznamu"
+ [x]-> "odpovídá seznamu o právě jedné položce, " ++ toString x
+ x::xs -> "odpovídá seznamu o alespoň jedné položce, jehož prvním prvkem je " ++ toString x
+-- Shody se vyhodnocují v zapsaném pořadí. Kdybychom umístili [x] poslední, nikdy by nenastala shoda,
+-- protože x::xs také odpovídá (xs by byl prázdný seznam). Shody "nepropadají".
+-- Překladač vždy upozorní na chybějící nebo přebývající větve.
+
+-- Větvení typu Maybe.
+case List.head seznam of
+ Just x -> "První položka je " ++ toString x
+ Nothing -> "Seznam byl prázdný."
+
+{-- Funkce --}
+
+-- Syntaxe funkcí je v Elmu velmi úsporná, založená spíše na mezerách
+-- než na závorkách. Neexistuje tu klíčové slovo "return".
+
+-- Funkci definujeme jejím jménem, parametry, rovnítkem a tělem.
+vynasob a b =
+ a * b
+
+-- Funkci voláme předáním parametrů (bez oddělujících čárek).
+vynasob 7 6 -- 42
+
+-- Částečně aplikované funkci předáme pouze některé parametry.
+-- Poté zvolíme nové jméno.
+zdvoj =
+ vynasob 2
+
+-- Konstanty jsou podobné, ale nepřijímají žádné parametry.
+odpoved =
+ 42
+
+-- Předejte funkci jako parametr jiným funkcím.
+List.map zdvoj [1..4] -- [2, 4, 6, 8]
+
+-- Nebo použijte anonymní funkci.
+List.map (\a -> a * 2) [1..4] -- [2, 4, 6, 8]
+
+-- V definici funkce lze zapsat vzor, může-li nastat pouze jeden případ.
+-- Tato funkce přijímá jednu dvojici místo dvou parametrů.
+obsah (sirka, delka) =
+ sirka * delka
+
+obsah (6, 7) -- 42
+
+-- Složenými závorkami vytvořte vzor pro názvy vlastností v záznamu.
+-- Použijte "let" k definici lokálních proměnných.
+objem {sirka, delka, hloubka} =
+ let
+ obsah = sirka * delka
+ in
+ obsah * hloubka
+
+objem { sirka = 3, delka = 2, hloubka = 7 } -- 42
+
+-- Funkce mohou být rekurzivní.
+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]
+
+-- Jiná rekurzivní funkce (v praxi použijte List.length).
+delkaSeznamu seznam =
+ case seznam of
+ [] -> 0
+ x::xs -> 1 + delkaSeznamu xs
+
+-- Funkce se volají před jakýmkoli infixovým operátorem. Závorky určují prioritu.
+cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1
+-- Nejprve se aplikuje "degrees" na číslo 30, výsledek je pak předán trigonometrickým
+-- funkcím, které jsou následně umocněny na druhou, na závěr proběhne sčítání.
+
+{-- Typy a typové anotace --}
+
+-- Překladač odvodí typ každé hodnoty ve vašem programu.
+-- Typy vždy začínají velkým písmenem. Čtete x : T jako "x je typu T".
+-- Některé běžné typy, které můžete videt v Elmovém REPLu.
+5 : Int
+6.7 : Float
+"ahoj" : String
+True : Bool
+
+-- Funkce mají také typy. Čtěte "->" jako "vrací".
+-- O typu na konci uvažujte jako návratovém typu, o ostatních jako typech argumentů.
+not : Bool -> Bool
+round : Float -> Int
+
+-- Když definujete hodnotu, je dobrým zvykem zapsat nad ni její typ.
+-- Anotace je formou dokumentace, která je ověřována překladačem.
+zdvoj : Int -> Int
+zdvoj x = x * 2
+
+-- Funkce jako parametr je uzavřena v závorkách.
+-- Typy s malým počátečním písmenem jsou typové proměnné:
+-- mohou být libovolného typu, ale v každém volání musí být stejné.
+List.map : (a -> b) -> List a -> List b
+-- "List tečka map je typu a-vrací-b, vrací seznam-položek-typu-a, vrací seznam-položek-typu-b."
+
+-- Existují tři speciální typové proměnné:
+-- číslo (number), porovnatelné (comparable), and spojitelné (appendable).
+-- Čísla dovolují použít aritmetiku na Int a Float.
+-- Porovnatelné dovolují uspořádat čísla a řetězce, např. a < b.
+-- Spojitelné lze zřetězit pomocí a ++ b.
+
+{-- Typové aliasy a výčtové typy --}
+
+-- Pro záznamy a n-tice již typy automaticky existují.
+-- (Povšimněte si, že typ vlatnosti záznamu přiřazujeme dvojtečkou a hodnotu rovnítkem.)
+pocatek : { x : Float, y : Float, z : Float }
+pocatek =
+ { x = 0, y = 0, z = 0 }
+
+-- Stávajícím typům lze dávat jména využitím aliasů.
+type alias Bod3D =
+ { x : Float, y : Float, z : Float }
+
+-- Alias pro záznam funguje také jako jeho konstruktor.
+jinyPocatek : Bod3D
+jinyPocatek =
+ Bod3D 0 0 0
+
+-- Jedná se stále o stejný typ, lze je tedy porovnat.
+pocatek == jinyPocatek -- True
+
+-- Oproti tomu výčtový (union) typ definuje zcela nový typ.
+-- Výčtový typ se takto jmenuje, protože může být jedním z několika vybraných možností.
+-- Každá možnost je reprezentována jako "tag".
+type Smer =
+ Sever | Jih | Vychod | Zapad
+
+-- Tagy mohou obsahovat další hodnoty známých typů. Lze využít i rekurze.
+type IntStrom =
+ Vrchol | Uzel Int IntStrom IntStrom
+-- "Vrchol" i "Uzel" jsou tagy. Vše, co následuje za tagem, je typ.
+
+-- Tagy lze použít jako hodnoty funkcí.
+koren : IntStrom
+koren =
+ Vrchol 7 List List
+
+-- Výčtové typy (a typové aliasy) mohou obsahovat typové proměnné.
+type Strom a =
+ Vrchol | Uzel a (Strom a) (Strom a)
+-- "Typ strom-prvků-a je vrchol, nebo uzel obsahující a, strom-prvků-a a strom-prvků-a."
+
+-- Vzory se shodují s tagy. Tagy s velkým počátečním písmenem odpovídají přesně.
+-- Proměnné malým písmem odpovídají čemukoli. Podtržítko také odpovídá čemukoli,
+-- ale určuje, že tuto hodnotu dále nechceme používat.
+nejviceVlevo : Strom a -> Maybe a
+nejviceVlevo strom =
+ case strom of
+ Vrchol -> Nothing
+ Uzel x Vrchol _ -> Just x
+ Uzel _ podstrom _ -> nejviceVlevo podstrom
+
+-- To je víceméně vše o jazyku samotném.
+-- Podívejme se nyní, jak organizovat a spouštět náš kód.
+
+{-- Moduly a importování --}
+
+-- Standardní knihovny jsou organizovány do modulů, stejně jako knihovny třetích stran,
+-- které můžete využívat. Ve větších projektech můžete definovat vlastní moduly.
+
+-- Vložte toto na začátek souboru. Pokud nic neuvedete, předpokládá se "Main".
+module Jmeno where
+
+-- Výchozím chováním je, že se exportuje vše.
+-- Případně můžete definovat exportované vlastnosti explicitně.
+module Jmeno (MujTyp, mojeHodnota) where
+
+-- Běžný návrhový vzor je expotovat pouze výčtový typ bez jeho tagů.
+-- Tento vzor je znám jako krycí typ a často se využívá v knihovnách.
+
+-- Z jiných modulů lze importovat kód a použít jej v aktuálním modulu.
+-- Nasledující umístí Dict do aktuálního scope, takže lze volat Dict.insert.
+import Dict
+
+-- Importuje modul Dict a typ Dict, takže v anotacích není nutné psát Dict.Dict.
+-- Stále lze volat Dict.insert.
+import Dict exposing (Dict)
+
+-- Přejmenování importu.
+import Graphics.Collage as C
+
+{-- Porty --}
+
+-- Port oznamuje, že budete komunikovat s vnějším světem.
+-- Porty jsou dovoleny pouze v modulu Main.
+
+-- Příchozí port je jen typová anotace.
+port idKlienta : Int
+
+-- Odchozí port má definici.
+port objednavkaKlienta : List String
+port objednavkaKlienta = ["Knihy", "Potraviny", "Nábytek"]
+
+-- Nebudeme zacházet do detailů, ale v JavaScriptu se dají nastavit
+-- callbacky pro zasílání na příchozí porty a čtení z odchozích portů.
+
+{-- Nástroje pro příkazovou řádku --}
+
+-- Kompilace souboru.
+$ elm make MujSoubor.elm
+
+-- Při prvním spuštění nainstaluje Elm standardní knihovny a vytvoří soubor
+-- elm-package.json, kde jsou uloženy informace o vašem projektu.
+
+-- Elm reactor je server, který překládá a spouští vaše soubory.
+-- Kliknutím na klíč vedle názvu souboru spustíte debugger s cestovám v čase!
+$ elm reactor
+
+-- Zkoušejte si jednoduché příkazy v Read-Eval-Print Loop.
+$ elm repl
+
+-- Balíčky jsou určeny uživatelským jménem na GitHubu a názvem repozitáře.
+-- Nainstalujte nový balíček a uložte jej v souboru elm-package.json.
+$ elm package install evancz/elm-html
+
+-- Porovnejte změny mezi verzemi jednoho balíčku.
+$ elm package diff evancz/elm-html 3.0.0 4.0.2
+-- Správce balíčků v Elmu vyžaduje sémantické verzování,
+-- takže minor verze nikdy nerozbije váš build.
+```
+
+Jazyk Elm je překvapivě malý. Nyní se můžete podívat do skoro jakéhokoli zdrojového kódu
+v Elmu a budete mít zběžnou představu o jeho fungování.
+Ovšem možnosti, jak psát kód, který je odolný vůči chybám a snadno se refaktoruje, jsou neomezené!
+
+Zde jsou některé užitečné zdroje (v angličtině).
+
+* [Hlavní stránka Elmu](http://elm-lang.org/). Obsahuje:
+ * Odkazy na [instalátory](http://elm-lang.org/install)
+ * [Documentaci](http://elm-lang.org/docs), včetně [popisu syntaxe](http://elm-lang.org/docs/syntax)
+ * Spoustu nápomocných [příkladů](http://elm-lang.org/examples)
+
+* Documentace pro [standardní knihovny Elmu](http://package.elm-lang.org/packages/elm-lang/core/latest/). Povšimněte si:
+ * [Základy](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics), které jsou automaticky importovány
+ * Typ [Maybe](http://package.elm-lang.org/packages/elm-lang/core/latest/Maybe) a jeho bratranec typ [Result](http://package.elm-lang.org/packages/elm-lang/core/latest/Result), které se běžně používají pro chybějící hodnoty a ošetření chyb.
+ * Datové struktury jako [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) a [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set)
+ * JSON [enkódování](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Encode) a [dekódování](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode)
+
+* [Architektura Elmu](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). Esej od tvůrce Elmu s příklady, jak organizovat kód do komponent.
+
+* [Elm mailing list](https://groups.google.com/forum/#!forum/elm-discuss). Všichni jsou přátelští a nápomocní.
+
+* [Scope v Elmu](https://github.com/elm-guides/elm-for-js/blob/master/Scope.md#scope-in-elm) a [Jak číst typové anotace](https://github.com/elm-guides/elm-for-js/blob/master/How%20to%20Read%20a%20Type%20Annotation.md#how-to-read-a-type-annotation). Další komunitní návody o základech Elmu, psáno pro JavaScriptové vývojáře.
+
+Běžte si zkusit něco napsat v Elmu!
diff --git a/cs-cz/json.html.markdown b/cs-cz/json.html.markdown
new file mode 100644
index 00000000..5972da5e
--- /dev/null
+++ b/cs-cz/json.html.markdown
@@ -0,0 +1,62 @@
+---
+language: json
+contributors:
+ - ["Anna Harren", "https://github.com/iirelu"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+translators:
+ - ["Vojta Svoboda", "https://github.com/vojtasvoboda/"]
+filename: learnjson-cz.json
+lang: cs-cz
+---
+
+JSON je exterémně jednoduchý datově nezávislý formát a bude asi jeden z
+nejjednodušších 'Learn X in Y Minutes' ze všech.
+
+JSON nemá ve své nejzákladnější podobě žádné komentáře, ale většina parserů
+umí pracovat s komentáři ve stylu jazyka C (`//`, `/* */`). Pro tyto účely
+však budeme používat 100% validní JSON bez komentářů. Pojďme se podívat na
+syntaxi formátu JSON:
+
+```json
+{
+ "klic": "value",
+
+ "hodnoty": "Musí být vždy uvozený v dvojitých uvozovkách",
+ "cisla": 0,
+ "retezce": "Hellø, wørld. Všechny unicode znaky jsou povolené, společně s \"escapováním\".",
+ "pravdivostni_hodnota": true,
+ "prazdna_hodnota": null,
+
+ "velke_cislo": 1.2e+100,
+
+ "objekt": {
+ "komentar": "Most of your structure will come from objects.",
+
+ "pole": [0, 1, 2, 3, "Pole nemusí být pouze homogenní.", 5],
+
+ "jiny_objekt": {
+ "comment": "Je povolené jakkoli hluboké zanoření."
+ }
+ },
+
+ "cokoli": [
+ {
+ "zdroje_drasliku": ["banány"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "neo"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "alternativni_styl_zapisu": {
+ "komentar": "Mrkni se na toto!"
+ , "pozice_carky": "Na pozici čárky nezáleží - pokud je před hodnotou, ať už je kdekoli, tak je validní."
+ , "dalsi_komentar": "To je skvělé."
+ },
+
+ "to_bylo_rychle": "A tím jsme hotový. Nyní již víte vše, co může formát JSON nabídnout!"
+}
+```
diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown
index 637f0ab6..568e4343 100644
--- a/cs-cz/markdown.html.markdown
+++ b/cs-cz/markdown.html.markdown
@@ -1,10 +1,12 @@
---
language: markdown
+lang: cs-cz
contributors:
- ["Dan Turkel", "http://danturkel.com/"]
translators:
- ["Michal Martinek", "https://github.com/MichalMartinek"]
-filename: markdown.md
+filename: markdown-cz.md
+lang: cs-cz
---
Markdown byl vytvořen Johnem Gruberem v roce 2004. Je zamýšlen jako lehce čitelná
@@ -51,7 +53,7 @@ __Stejně jako tento.__
**_Jako tento!_**
*__A tento!__*
-<!-- Ve verzi Markdownu od Githubu, máme k dispozici taky prošktrnutí: -->
+<!-- Ve verzi Markdownu od GitHubu, máme k dispozici taky prošktrnutí: -->
~~Tento text je prošktrnutý.~~
@@ -150,7 +152,7 @@ Tento box bude zašktrnutý
Jan nevědel, jak se dělá `go_to()` funkce!
-<!-- V Markdownu od Githubu , můžete použít speciální syntaxi pro kód -->
+<!-- V Markdownu od GitHubu , můžete použít speciální syntaxi pro kód -->
\`\`\`ruby <!-- vyjma zpětných lomítek, jenom ```ruby ! -->
def neco
@@ -158,7 +160,7 @@ def neco
end
\`\`\` <!-- zde taky, žádné zpětná lomítka, pouze ``` -->
-<!-- Text výše nepotřebuje odsazení a navíc Github použije zvýraznění označeného
+<!-- Text výše nepotřebuje odsazení a navíc GitHub použije zvýraznění označeného
jazyka. -->
<!-- Horizontální čára (<hr />) -->
@@ -230,13 +232,13 @@ Dejte text, který chcete zobrazit, do [] následovaný url v závorkách () a j
Chci napsat *tento text obklopený hvězdičkami*, ale nechci aby to bylo kurzívou, tak udělám: \*tento text obklopený hvězdičkami\*.
<!-- Klávesové zkratky -->
-<!-- V Markdownu od Githubu, můžete použít tag <kbd> k reprezentování klaves na počítači -->
+<!-- V Markdownu od GitHubu, můžete použít tag <kbd> k reprezentování klaves na počítači -->
Váš počítač přestal pracovat? Zkuste
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
<!-- Tabulky -->
-<!-- Tabulky jsou povolené pouze v Markdownu od Githubu a jsou trochu podivně,
+<!-- Tabulky jsou povolené pouze v Markdownu od GitHubu a jsou trochu podivně,
ale když je opravdu chcete: -->
| Sloupec1 | Sloupec2 | Sloupec3 |
diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown
index b498046a..581ed3a3 100644
--- a/cs-cz/python3.html.markdown
+++ b/cs-cz/python3.html.markdown
@@ -7,7 +7,7 @@ contributors:
- ["Tomáš Bedřich", "http://tbedrich.cz"]
translators:
- ["Tomáš Bedřich", "http://tbedrich.cz"]
-filename: learnpython3.py
+filename: learnpython3-cz.py
lang: cs-cz
---
diff --git a/cs-cz/sass.html.markdown b/cs-cz/sass.html.markdown
new file mode 100644
index 00000000..0d2fca64
--- /dev/null
+++ b/cs-cz/sass.html.markdown
@@ -0,0 +1,439 @@
+---
+language: sass
+filename: learnsass-cz.scss
+contributors:
+ - ["Laura Kyle", "https://github.com/LauraNK"]
+ - ["Sean Corrales", "https://github.com/droidenator"]
+translators:
+ - ["Michal Martinek", "https://github.com/MichalMartinek"]
+lang: cs-cz
+---
+
+Sass je rozšíření jazyka CSS, který přidává nové vlastnosti jako proměnné, zanořování, mixiny a další.
+Sass (a další preprocesory, jako [Less](http://lesscss.org/)) pomáhají vývojářům psát udržovatelný a neopakující (DRY) kód.
+
+Sass nabízí dvě možnosti syntaxe. SCSS, které je stejná jako CSS, akorát obsahuje nové vlastnosti Sassu. Nebo Sass, který používá odsazení místo složených závorek a středníků.
+Tento tutoriál bude používat syntaxi CSS.
+
+
+Pokud jste již obeznámeni s CSS3, budete schopni používat Sass relativně rychle. Nezprostředkovává nějaké úplně nové stylové možnosti, spíše nátroje, jak psát Vás CSS kód více efektivně, udržitelně a jednoduše.
+
+```scss
+
+
+//Jednořádkové komentáře jsou ze Sassu při kompilaci vymazány
+
+/*Víceřádkové komentáře jsou naopak zachovány */
+
+
+
+/*Proměnné
+==============================*/
+
+
+
+/* Můžete uložit CSS hodnotu (jako třeba barvu) do proměnné.
+Použijte symbol '$' k jejímu vytvoření. */
+
+$hlavni-barva: #A3A4FF;
+$sekundarni-barva: #51527F;
+$body-font: 'Roboto', sans-serif;
+
+/* Můžete používat proměnné napříč vaším souborem.
+Teď, když chcete změnit barvu, stačí ji změnit pouze jednou.*/
+
+body {
+ background-color: $hlavni-barva;
+ color: $sekundarni-barva;
+ font-family: $body-font;
+}
+
+/* Toto se zkompiluje do: */
+body {
+ background-color: #A3A4FF;
+ color: #51527F;
+ font-family: 'Roboto', sans-serif;
+}
+
+
+/* Toto je o hodně více praktické, než měnit každý výskyt barvy. */
+
+
+
+/*Mixiny
+==============================*/
+
+
+
+/* Pokud zjistíte, že píšete kód pro více než jeden element, můžete jej uložit do mixinu.
+
+Použijte '@mixin' direktivu, plus jméno vašeho mixinu.*/
+
+@mixin na-stred {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+/* Mixin vložíte pomocí '@include' a jména mixinu */
+
+div {
+ @include na-stred;
+ background-color: $hlavni-barva;
+}
+
+/*Což se zkompiluje do: */
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #A3A4FF;
+}
+
+
+/* Můžete využít mixiny i třeba pro takovéto ušetření práce: */
+
+@mixin velikost($sirka, $vyska) {
+ width: $sirka;
+ height: $vyska;
+}
+
+/*Stačí vložit argumenty: */
+
+.obdelnik {
+ @include velikost(100px, 60px);
+}
+
+.ctverec {
+ @include velikost(40px, 40px);
+}
+
+/* Toto se zkompiluje do: */
+.obdelnik {
+ width: 100px;
+ height: 60px;
+}
+
+.ctverec {
+ width: 40px;
+ height: 40px;
+}
+
+
+
+/*Funkce
+==============================*/
+
+
+
+/* Sass obsahuje funkce, které vám pomůžou splnit různé úkoly. */
+
+/* Funkce se spouštějí pomocí jejich jména, které následuje seznam argumentů uzavřený v kulatých závorkách. */
+body {
+ width: round(10.25px);
+}
+
+.footer {
+ background-color: fade_out(#000000, 0.25)
+}
+
+/* Se zkompiluje do: */
+
+body {
+ width: 10px;
+}
+
+.footer {
+ background-color: rgba(0, 0, 0, 0.75);
+}
+
+/* Můžete také definovat vlastní funkce. Funkce jsou velmi podobné mixinům.
+ Když se snažíte vybrat mezi funkcí a mixinem, mějte na paměti, že mixiny
+ jsou lepší pro generování CSS kódu, zatímco funkce jsou lepší pro logiku.
+ Příklady ze sekce Matematické operátory jsou skvělí kandidáti na
+ znovupoužitelné funkce. */
+
+/* Tato funkce vrací poměr k velikosti rodiče v procentech.
+@function vypocitat-pomer($velikost, $velikost-rodice) {
+ @return $velikost / $velikost-rodice * 100%;
+}
+
+$hlavni obsah: vypocitat-pomer(600px, 960px);
+
+.hlavni-obsah {
+ width: $hlavni-obsah;
+}
+
+.sloupec {
+ width: vypocitat-pomer(300px, 960px);
+}
+
+/* Zkompiluje do: */
+
+.hlavni-obsah {
+ width: 62.5%;
+}
+
+.sloupec {
+ width: 31.25%;
+}
+
+
+
+/*Dědění
+==============================*/
+
+
+
+/*Dědění je způsob jak používat vlastnosti pro jeden selektor ve druhém. */
+
+.oznameni {
+ @include velikost(5em, 5em);
+ border: 5px solid $sekundarni-barva;
+}
+
+.oznameni-uspech {
+ @extend .oznameni;
+ border-color: #22df56;
+}
+
+/* Zkompiluje do: */
+.oznameni, .oznameni-uspech {
+ width: 5em;
+ height: 5em;
+ border: 5px solid #51527F;
+}
+
+.oznameni-uspech {
+ border-color: #22df56;
+}
+
+
+/* Dědění CSS výrazů je preferováno před vytvořením mixinu kvůli způsobu,
+ jakým způsobem Sass dává dohromady třídy, které sdílejí stejný kód.
+ Kdyby to bylo udělané pomocí mixinu, tak výška, šířka, rámeček by byl v
+ každém výrazu, který by volal mixin. I když tohle neovlivní vaše workflow,
+ přidá to kód navíc do souborů. */
+
+
+/*Zanořování
+==============================*/
+
+
+
+/*Sass vám umožňuje zanořovat selektory do selektorů */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: #FF0000;
+ }
+}
+
+/* '&' nahradí rodičovský element. */
+/* Můžete také zanořovat pseudo třídy. */
+/* Pamatujte, že moc velké zanoření do hloubky snižuje čitelnost.
+ Doporučuje se používat maximálně trojité zanoření.
+ Na příklad: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: red;
+
+ &:hover {
+ background-color: blue;
+ }
+
+ a {
+ color: white;
+ }
+ }
+}
+
+/* Zkompiluje do: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+}
+
+ul li {
+ background-color: red;
+}
+
+ul li:hover {
+ background-color: blue;
+}
+
+ul li a {
+ color: white;
+}
+
+
+
+/*Částečné soubory a importy
+==============================*/
+
+
+
+/* Sass umožňuje vytvářet částečné soubory. Tyto soubory pomahájí udržovat váš
+ kód modulární. Tyto soubory by měli začínat vždy '_', např. _reset.css.
+ Částečné soubory se nepřevádí do CSS. */
+
+/* Toto je kód, který si uložíme do souboru _reset.css */
+
+html,
+body,
+ul,
+ol {
+ margin: 0;
+ padding: 0;
+}
+
+/* Sass obsahuje @import, které může být použit pro import částečných souborů.
+ Toto se liší od klasického CSS @import, který dělá HTTP požadavek na stáhnutí
+ souboru. Sass vezme importovaný soubor a vloží ho do kompilovaného kódu. */
+
+@import 'reset';
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+/* Zkompiluje do: */
+
+html, body, ul, ol {
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+
+
+/*Zástupné selektory
+==============================*/
+
+
+
+/* Zástupné selektory jsou užitečné, když vytváříte CSS výraz, ze kterého
+ chcete později dědit. Když chcete vytvořit výraz, ze kterého je možné pouze
+ dědit pomocí @extend, vytvořte zástupný selektor s CSS výrazem. Ten začíná
+ symbolem '%' místo '.' nebo '#'. Tyto výrazy se neobjeví ve výsledném CSS */
+
+%okno-obsahu {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.okno-zpravy {
+ @extend %okno-obsahu;
+ background-color: #0000ff;
+}
+
+/* Zkompiluje do: */
+
+.okno-zpravy {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.okno-zpravy {
+ background-color: #0000ff;
+}
+
+
+
+/*Matematické operace
+==============================*/
+
+
+
+/* Sass obsahuje následující operátory: +, -, *, /, and %. Tyto operátory
+ můžou být velmi užitečné pro počítání hodnot přímo ve vašem souboru Sass.
+ Níže je příklad, jak udělat jednoduchý dvousloupcový layout. */
+
+$oblast-obsahu: 960px;
+$hlavni-obsah: 600px;
+$vedlejsi-sloupec: 300px;
+
+$obsah-velikost: $hlavni-obsah / $oblast-obsahu * 100%;
+$vedlejsi-sloupec-velikost: $vedlejsi-sloupec / $oblast-obsahu * 100%;
+$zbytek-velikost: 100% - ($main-size + $vedlejsi-sloupec-size);
+
+body {
+ width: 100%;
+}
+
+.hlavni-obsah {
+ width: $obsah-velikost;
+}
+
+.vedlejsi-sloupec {
+ width: $vedlejsi-sloupec-velikost;
+}
+
+.zbytek {
+ width: $zbytek-velikost;
+}
+
+/* Zkompiluje do: */
+
+body {
+ width: 100%;
+}
+
+.hlavni-obsah {
+ width: 62.5%;
+}
+
+.vedlejsi-sloupec {
+ width: 31.25%;
+}
+
+.gutter {
+ width: 6.25%;
+}
+
+
+```
+
+
+
+## SASS nebo Sass?
+Divili jste se někdy, jestli je Sass zkratka nebo ne? Pravděpodobně ne, ale řeknu vám to stejně. Jméno tohoto jazyka je slovo, "Sass", a ne zkratka.
+Protože to lidé konstatně píší jako "SASS", nazval ho autor jazyka jako "Syntactically Awesome StyleSheets" (Syntaktický úžasně styly).
+
+
+## Procvičování Sassu
+Pokud si chcete hrát se Sassem ve vašem prohlížeči, navštivte [SassMeister](http://sassmeister.com/).
+Můžete používát oba dva způsoby zápisu, stačí si vybrat v nastavení SCSS nebo SASS.
+
+
+## Kompatibilita
+
+Sass může být použit v jakémkoliv projektu, jakmile máte program, pomocí kterého ho zkompilujete do CSS. Pokud si chcete ověřit, že CSS, které Sass produkuje je kompatibilní s prohlížeči:
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) a [CanIUse](http://caniuse.com) jsou skvělé stránky pro kontrolu kompatibility.
+
+
+## Kam dál?
+* [Oficiální dokumentace](http://sass-lang.com/documentation/file.SASS_REFERENCE.html)
+* [The Sass Way](http://thesassway.com/) obsahuje tutoriál a řadu skvělých článků
diff --git a/csharp.html.markdown b/csharp.html.markdown
index 677c2591..7be34fb9 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -24,10 +24,12 @@ Multi-line comments look like this
/// This is an XML documentation comment which can be used to generate external
/// documentation or provide context help within an IDE
/// </summary>
-//public void MethodOrClassOrOtherWithParsableHelp() {}
+/// <param name="firstParam">This is some parameter documentation for firstParam</param>
+/// <returns>Information on the returned value of a function</returns>
+//public void MethodOrClassOrOtherWithParsableHelp(string firstParam) {}
// Specify the namespaces this source code will be using
-// The namespaces below are all part of the standard .NET Framework Class Libary
+// The namespaces below are all part of the standard .NET Framework Class Library
using System;
using System.Collections.Generic;
using System.Dynamic;
@@ -421,7 +423,7 @@ on a new line! ""Wow!"", the masses cried";
// Item is an int
Console.WriteLine(item.ToString());
}
-
+
// YIELD
// Usage of the "yield" keyword indicates that the method it appears in is an Iterator
// (this means you can use it in a foreach loop)
@@ -437,7 +439,7 @@ on a new line! ""Wow!"", the masses cried";
foreach (var counter in YieldCounter())
Console.WriteLine(counter);
}
-
+
// you can use more than one "yield return" in a method
public static IEnumerable<int> ManyYieldCounter()
{
@@ -446,7 +448,7 @@ on a new line! ""Wow!"", the masses cried";
yield return 2;
yield return 3;
}
-
+
// you can also use "yield break" to stop the Iterator
// this method would only return half of the values from 0 to limit.
public static IEnumerable<int> YieldCounterWithBreak(int limit = 10)
@@ -482,7 +484,7 @@ on a new line! ""Wow!"", the masses cried";
// ?? is syntactic sugar for specifying default value (coalesce)
// in case variable is null
int notNullable = nullable ?? 0; // 0
-
+
// ?. is an operator for null-propagation - a shorthand way of checking for null
nullable?.Print(); // Use the Print() extension method if nullable isn't null
@@ -630,7 +632,7 @@ on a new line! ""Wow!"", the masses cried";
public static class Extensions
{
- // EXTENSION FUNCTIONS
+ // EXTENSION METHODS
public static void Print(this object obj)
{
Console.WriteLine(obj.ToString());
@@ -692,7 +694,10 @@ on a new line! ""Wow!"", the masses cried";
public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type
// Decorate an enum with the FlagsAttribute to indicate that multiple values can be switched on
- [Flags] // Any class derived from Attribute can be used to decorate types, methods, parameters etc
+ // Any class derived from Attribute can be used to decorate types, methods, parameters etc
+ // Bitwise operators & and | can be used to perform and/or operations
+
+ [Flags]
public enum BikeAccessories
{
None = 0,
@@ -879,8 +884,8 @@ on a new line! ""Wow!"", the masses cried";
bool Broken { get; } // interfaces can contain properties as well as methods & events
}
- // Class can inherit only one other class, but can implement any amount of interfaces, however
- // the base class name must be the first in the list and all interfaces follow
+ // Classes can inherit only one other class, but can implement any amount of interfaces,
+ // however the base class name must be the first in the list and all interfaces follow
class MountainBike : Bicycle, IJumpable, IBreakable
{
int damage = 0;
@@ -913,17 +918,17 @@ on a new line! ""Wow!"", the masses cried";
public DbSet<Bicycle> Bikes { get; set; }
}
-
+
// Classes can be split across multiple .cs files
// A1.cs
- public partial class A
+ public partial class A
{
public static void A1()
{
Console.WriteLine("Method A1 in class A");
}
}
-
+
// A2.cs
public partial class A
{
@@ -932,9 +937,9 @@ on a new line! ""Wow!"", the masses cried";
Console.WriteLine("Method A2 in class A");
}
}
-
+
// Program using the partial class "A"
- public class Program
+ public class Program
{
static void Main()
{
diff --git a/css.html.markdown b/css.html.markdown
index 8ee4f4b9..5dae06ca 100644
--- a/css.html.markdown
+++ b/css.html.markdown
@@ -7,16 +7,23 @@ contributors:
- ["Connor Shea", "https://github.com/connorshea"]
- ["Deepanshu Utkarsh", "https://github.com/duci9y"]
- ["Tyler Mumford", "https://tylermumford.com"]
+
filename: learncss.css
---
-Web pages are built with HTML, which specifies the content of a page. CSS (Cascading Style Sheets) is a separate language which specifies a page's **appearance**.
+Web pages are built with HTML, which specifies the content of a page.
+CSS (Cascading Style Sheets) is a separate language which specifies
+a page's **appearance**.
-CSS code is made of static *rules*. Each rule takes one or more *selectors* and gives specific *values* to a number of visual *properties*. Those properties are then applied to the page elements indicated by the selectors.
+CSS code is made of static *rules*. Each rule takes one or more *selectors* and
+gives specific *values* to a number of visual *properties*. Those properties are
+then applied to the page elements indicated by the selectors.
-This guide has been written with CSS 2 in mind, which is extended by the new features of CSS 3.
+This guide has been written with CSS 2 in mind, which is extended by the new
+features of CSS 3.
-**NOTE:** Because CSS produces visual results, in order to learn it, you need to try everything in a CSS playground like [dabblet](http://dabblet.com/).
+**NOTE:** Because CSS produces visual results, in order to learn it, you need to
+try everything in a CSS playground like [dabblet](http://dabblet.com/).
The main focus of this article is on the syntax and some general tips.
## Syntax
@@ -66,7 +73,7 @@ div { }
[otherAttr~='foo'] { }
[otherAttr~='bar'] { }
-/* or contains a value in a dash-separated list, ie, "-" (U+002D) */
+/* or contains a value in a dash-separated list, e.g., "-" (U+002D) */
[otherAttr|='en'] { font-size:smaller; }
@@ -113,7 +120,8 @@ selector:first-child {}
/* any element that is the last child of its parent */
selector:last-child {}
-/* Just like pseudo classes, pseudo elements allow you to style certain parts of a document */
+/* Just like pseudo classes, pseudo elements allow you to style certain parts of
+ a document */
/* matches a virtual first child of the selected element */
selector::before {}
@@ -132,9 +140,9 @@ selector::after {}
#################### */
selector {
-
+
/* Units of length can be absolute or relative. */
-
+
/* Relative units */
width: 50%; /* percentage of parent element width */
font-size: 2em; /* multiples of element's original font-size */
@@ -143,14 +151,14 @@ selector {
font-size: 2vh; /* or its height */
font-size: 2vmin; /* whichever of a vh or a vw is smaller */
font-size: 2vmax; /* or greater */
-
+
/* Absolute units */
width: 200px; /* pixels */
font-size: 20pt; /* points */
width: 5cm; /* centimeters */
min-width: 50mm; /* millimeters */
max-width: 5in; /* inches */
-
+
/* Colors */
color: #F6E; /* short hex format */
color: #FF66EE; /* long hex format */
@@ -161,10 +169,10 @@ selector {
color: transparent; /* equivalent to setting the alpha to 0 */
color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */
color: hsla(0, 100%, 50%, 0.3); /* as hsl percentages with alpha */
-
+
/* Images as backgrounds of elements */
background-image: url(/img-path/img.jpg); /* quotes inside url() optional */
-
+
/* Fonts */
font-family: Arial;
/* if the font family name has a space, it must be quoted */
@@ -195,7 +203,13 @@ Save a CSS stylesheet with the extension `.css`.
## Precedence or Cascade
-An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Rules with a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one.
+An element may be targeted by multiple selectors and may have a property set on
+it in more than once. In these cases, one of the rules takes precedence over
+others. Rules with a more specific selector take precedence over a less specific
+one, and a rule occurring later in the stylesheet overwrites a previous one
+(which also means that if two different linked stylesheets contain rules for an
+element and if the rules are of the same specificity, then order of linking
+would take precedence and the sheet linked latest would govern styling) .
This process is called cascading, hence the name Cascading Style Sheets.
@@ -224,18 +238,25 @@ and the following markup:
<p style='/*F*/ property:value;' class='class1 class2' attr='value' />
```
-The precedence of style is as follows. Remember, the precedence is for each **property**, not for the entire block.
+The precedence of style is as follows. Remember, the precedence is for each
+**property**, not for the entire block.
-* `E` has the highest precedence because of the keyword `!important`. It is recommended that you avoid its usage.
+* `E` has the highest precedence because of the keyword `!important`. It is
+recommended that you avoid its usage.
* `F` is next, because it is an inline style.
-* `A` is next, because it is more "specific" than anything else. It has 3 specifiers: The name of the element `p`, its class `class1`, an attribute `attr='value'`.
-* `C` is next, even though it has the same specificity as `B`. This is because it appears after `B`.
+* `A` is next, because it is more "specific" than anything else. It has 3
+ specifiers: The name of the element `p`, its class `class1`, an attribute
+ `attr='value'`.
+* `C` is next, even though it has the same specificity as `B`.
+ This is because it appears after `B`.
* `B` is next.
* `D` is the last one.
## Compatibility
-Most of the features in CSS 2 (and many in CSS 3) are available across all browsers and devices. But it's always good practice to check before using a new feature.
+Most of the features in CSS 2 (and many in CSS 3) are available across all
+browsers and devices. But it's always good practice to check before using
+a new feature.
## Resources
diff --git a/d.html.markdown b/d.html.markdown
index 6f88cf84..edb3bff5 100644
--- a/d.html.markdown
+++ b/d.html.markdown
@@ -254,7 +254,7 @@ void main() {
// Use an index, access every array element by reference (because we're
// going to change each element) and just call parallel on the array!
foreach(i, ref elem; parallel(arr)) {
- ref = sqrt(i + 1.0);
+ elem = sqrt(i + 1.0);
}
}
```
diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown
index 541d28bb..654fcdd4 100644
--- a/de-de/bash-de.html.markdown
+++ b/de-de/bash-de.html.markdown
@@ -92,12 +92,12 @@ echo "immer ausgeführt" || echo "Nur ausgeführt wenn der erste Befehl fehlschl
echo "immer ausgeführt" && echo "Nur ausgeführt wenn der erste Befehl Erfolg hat"
# Um && und || mit if statements zu verwenden, braucht man mehrfache Paare eckiger Klammern:
-if [ $NAME == "Steve" ] && [ $Alter -eq 15 ]
+if [ "$NAME" == "Steve" ] && [ "$Alter" -eq 15 ]
then
echo "Wird ausgeführt wenn $NAME gleich 'Steve' UND $Alter gleich 15."
fi
-if [ $Name == "Daniya" ] || [ $Name == "Zach" ]
+if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ]
then
echo "Wird ausgeführt wenn $NAME gleich 'Daniya' ODER $NAME gleich 'Zach'."
fi
diff --git a/de-de/d-de.html.markdown b/de-de/d-de.html.markdown
new file mode 100644
index 00000000..ae036d70
--- /dev/null
+++ b/de-de/d-de.html.markdown
@@ -0,0 +1,250 @@
+---
+language: D
+filename: learnd-de.d
+contributors:
+ - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"]
+translators:
+ - ["Dominik Süß", "www.thesuess.me"]
+lang: de-de
+---
+
+```c
+// Es war klar dass das kommt...
+module hello;
+
+import std.stdio;
+
+// argumente sind optional
+void main(string[] args) {
+ writeln("Hello, World!");
+}
+```
+
+Wenn du so wie ich bist und viel zeit im Internet verbringst stehen die Chancen gut
+das du schonmal über [D](http://dlang.org/) gehört hast.
+Die D-Sprache ist eine moderne, überall einsetzbare programmiersprache die von Low bis
+High Level verwendet werden kann und dabei viele Stile anbietet.
+
+D wird aktiv von Walter Bright und Andrei Alexandrescu entwickelt, zwei super schlaue,
+richtig coole leute. Da das jetzt alles aus dem weg ist - auf zu den Beispielen!
+
+```c
+import std.stdio;
+
+void main() {
+
+ // Logische Ausdrücke und Schleifen funktionieren wie erwartet
+ for(int i = 0; i < 10000; i++) {
+ writeln(i);
+ }
+
+ auto n = 1; // auto um den typ vom Compiler bestimmen zu lassen
+
+ // Zahlenliterale können _ verwenden für lesbarkeit
+ while(n < 10_000) {
+ n += n;
+ }
+
+ do {
+ n -= (n / 2);
+ } while(n > 0);
+
+ // For und while sind ja schön und gut aber D bevorzugt foreach
+ // .. erstellt eine spanne von zahlen, exklusive dem Ende
+ foreach(i; 1..1_000_000) {
+ if(n % 2 == 0)
+ writeln(i);
+ }
+
+ foreach_reverse(i; 1..int.max) {
+ if(n % 2 == 1) {
+ writeln(i);
+ } else {
+ writeln("No!");
+ }
+ }
+}
+```
+
+Neue Typen können mit `struct`, `class`, `union`, und `enum` definiert werden. Structs und unions
+werden as-value (koppiert) an methoden übergeben wogegen Klassen als Referenz übergeben werden.
+Templates können verwendet werden um alle typen zu parameterisieren.
+
+```c
+// Hier, T ist ein Type-Parameter, Er funktioniert wie Generics in C#/Java/C++
+struct LinkedList(T) {
+ T data = null;
+ LinkedList!(T)* next; // Das ! wird verwendet um T zu übergeben. (<T> in C#/Java/C++)
+}
+
+class BinTree(T) {
+ T data = null;
+
+ // Wenn es nur einen T parameter gibt können die Klammern um ihn weggelassen werden
+ BinTree!T left;
+ BinTree!T right;
+}
+
+enum Day {
+ Sunday,
+ Monday,
+ Tuesday,
+ Wednesday,
+ Thursday,
+ Friday,
+ Saturday,
+}
+
+// Aliase können verwendet werden um die Entwicklung zu erleichtern
+
+alias IntList = LinkedList!int;
+alias NumTree = BinTree!double;
+
+// Funktionen können genau so Templates beinhalten
+
+T max(T)(T a, T b) {
+ if(a < b)
+ return b;
+
+ return a;
+}
+
+// Steht ref vor einem Parameter wird sichergestellt das er als Referenz übergeben wird.
+// Selbst bei werten wird es immer eine Referenz sein.
+void swap(T)(ref T a, ref T b) {
+ auto temp = a;
+
+ a = b;
+ b = temp;
+}
+
+// Templates können ebenso werte parameterisieren.
+class Matrix(uint m, uint n, T = int) {
+ T[m] rows;
+ T[n] columns;
+}
+
+auto mat = new Matrix!(3, 3); // Standardmäßig ist T vom typ Integer
+
+```
+
+Wo wir schon bei Klassen sind - Wie wäre es mit Properties! Eine Property
+ist eine Funktion die wie ein Wert agiert. Das gibt uns viel klarere Syntax
+im Stil von `structure.x = 7` was gleichgültig wäre zu `structure.setX(7)`
+
+```c
+// Diese Klasse ist parameterisiert mit T, U
+
+class MyClass(T, U) {
+ T _data;
+ U _other;
+
+}
+
+// Ihre Getter und Setter Methoden sehen so aus
+class MyClass(T, U) {
+ T _data;
+ U _other;
+
+ // Konstruktoren heißen immer `this`
+ this(T t, U u) {
+ data = t;
+ other = u;
+ }
+
+ // getters
+ @property T data() {
+ return _data;
+ }
+
+ @property U other() {
+ return _other;
+ }
+
+ // setters
+ // @property kann genauso gut am ende der Methodensignatur stehen
+ void data(T t) @property {
+ _data = t;
+ }
+
+ void other(U u) @property {
+ _other = u;
+ }
+}
+// Und so kann man sie dann verwenden
+
+void main() {
+ auto mc = MyClass!(int, string);
+
+ mc.data = 7;
+ mc.other = "seven";
+
+ writeln(mc.data);
+ writeln(mc.other);
+}
+```
+
+Mit properties können wir sehr viel logik hinter unseren gettern
+und settern hinter einer schönen syntax verstecken
+
+Other object-oriented goodies at our disposal
+Andere Objektorientierte features sind beispielsweise
+`interface`s, `abstract class` und `override`.
+Vererbung funktioniert in D wie in Java:
+Erben von einer Klasse, so viele interfaces wie man will.
+
+Jetzt haben wir Objektorientierung in D gesehen aber schauen
+wir uns noch was anderes an.
+D bietet funktionale programmierung mit _first-class functions_
+puren funktionen und unveränderbare daten.
+Zusätzlich können viele funktionale Algorithmen wie z.B
+map, filter, reduce und friends im `std.algorithm` Modul gefunden werden!
+
+```c
+import std.algorithm : map, filter, reduce;
+import std.range : iota; // builds an end-exclusive range
+
+void main() {
+ // Wir wollen die summe aller quadratzahlen zwischen
+ // 1 und 100 ausgeben. Nichts leichter als das!
+
+ // Einfach eine lambda funktion als template parameter übergeben
+ // Es ist genau so gut möglich eine normale funktion hier zu übergeben
+ // Lambdas bieten sich hier aber an.
+ auto num = iota(1, 101).filter!(x => x % 2 == 0)
+ .map!(y => y ^^ 2)
+ .reduce!((a, b) => a + b);
+
+ writeln(num);
+}
+```
+
+Ist dir aufgefallen wie wir eine Haskell-Style pipeline gebaut haben
+um num zu berechnen?
+Das war möglich durch die Uniform Function Call Syntax.
+Mit UFCS können wir auswählen ob wir eine Funktion als Methode oder
+als freie Funktion aufrufen. Walters artikel dazu findet ihr
+[hier.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
+Kurzgesagt kann man Funktionen deren erster parameter vom typ A ist, als
+Methode auf A anwenden.
+
+Parrallel Computing ist eine Tolle sache, findest du nicht auch?
+
+```c
+import std.stdio;
+import std.parallelism : parallel;
+import std.math : sqrt;
+
+void main() {
+ // Wir wollen die Wurzel von jeder Zahl in unserem Array berechnen
+ // und dabei alle Kerne verwenden die wir zur verfügung haben
+ auto arr = new double[1_000_000];
+
+ // Wir verwenden den index und das element als referenz
+ // und rufen einfach parallel auf!
+ foreach(i, ref elem; parallel(arr)) {
+ ref = sqrt(i + 1.0);
+ }
+}
+
+```
diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown
index dea329d5..61f7bb67 100644
--- a/de-de/git-de.html.markdown
+++ b/de-de/git-de.html.markdown
@@ -33,6 +33,7 @@ Eine Versionsverwaltung erfasst die Änderungen einer Datei oder eines Verzeichn
* Ist offline einsetzbar.
* Einfache Kollaboration!
* Branching ist einfach!
+* Branching ist schnell!
* Merging ist einfach!
* Git ist schnell.
* Git ist flexibel.
@@ -53,11 +54,11 @@ Das .git-Verzeichnis enthält alle Einstellung, Logs, Branches, den HEAD und meh
### Arbeitsverzeichnis (Teil des Repositorys)
-Dies sind die Verzeichnisse und Dateien in deinem Repository.
+Dies sind die Verzeichnisse und Dateien in deinem Repository, also z.B. dein Programmcode.
### Index (Teil des .git-Verzeichnisses)
-Der Index ist die die Staging-Area von Git. Es ist im Grunde eine Ebene, die Arbeitsverzeichnis vom Repository trennt. Sie gibt Entwicklern mehr Einfluss darüber, was ins Git-Repository eingeht.
+Der Index ist die Staging-Area von Git. Es ist im Grunde eine Ebene, die Arbeitsverzeichnis vom Repository trennt. Sie gibt Entwicklern mehr Einfluss darüber, was ins Git-Repository eingeht.
### Commit
@@ -84,7 +85,7 @@ Ein *head* ist ein Pointer, der auf einen beliebigen Commit zeigt. Ein Reposito
### init
-Erstelle ein leeres Git-Repository. Die Einstellungen, gespeicherte Informationen und mehr zu diesem Git-Repository werden in einem Verzeichnis namens *.git* angelegt.
+Erstelle ein leeres Git-Repository im aktuellen Verzeichnis. Die Einstellungen, gespeicherte Informationen und mehr zu diesem Git-Repository werden in einem Verzeichnis namens *.git* angelegt.
```bash
$ git init
@@ -180,6 +181,8 @@ Bringt alle Dateien im Arbeitsverzeichnis auf den Stand des Index oder des angeg
```bash
# Ein Repo auschecken - wenn nicht anders angegeben ist das der master
$ git checkout
+# Eine Datei auschecken - sie befindet sich dann auf dem aktuellen Stand im Repository
+$ git checkout /path/to/file
# Einen bestimmten Branch auschecken
$ git checkout branchName
# Erstelle einen neuen Branch und wechsle zu ihm. Wie: "git branch <name>; git checkout <name>"
@@ -217,6 +220,9 @@ $ git diff --cached
# Unterschiede zwischen deinem Arbeitsverzeichnis und dem aktuellsten Commit anzeigen
$ git diff HEAD
+
+# Unterschiede zwischen dem Index und dem aktuellsten Commit (betrifft nur Dateien im Index)
+$ git diff --staged
```
### grep
@@ -374,3 +380,5 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
* [GitGuys](http://www.gitguys.com/)
+
+* [gitflow - Ein Modell um mit Branches zu arbeiten](http://nvie.com/posts/a-successful-git-branching-model/)
diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown
index d3a192fe..dca88f01 100644
--- a/de-de/go-de.html.markdown
+++ b/de-de/go-de.html.markdown
@@ -4,17 +4,17 @@ filename: learngo-de.go
contributors:
- ["Joseph Adams", "https://github.com/jcla1"]
- ["Dennis Keller", "https://github.com/denniskeller"]
+translators:
+ - ["Jerome Meinke", "https://github.com/jmeinke"]
lang: de-de
---
-Go wurde entwickelt, um Probleme zu lösen. Sie ist zwar nicht der neueste Trend in
-der Informatik, aber sie ist einer der neuesten und schnellsten Wege, um Aufgabe in
-der realen Welt zu lösen.
-
-Sie hat vertraute Elemente von imperativen Sprachen mit statischer Typisierung
-und kann schnell kompiliert und ausgeführt werden. Verbunden mit leicht zu
-verstehenden Parallelitäts-Konstrukten, um die heute üblichen mehrkern
-Prozessoren optimal nutzen zu können, eignet sich Go äußerst gut für große
-Programmierprojekte.
+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
+für die Unterstützung von Nebenläufigkeit. Durch den Fokus auf einen schnellen
+Kompilierprozess wird außerdem die Softwareentwicklung in Großprojekten
+erleichtert.
Außerdem beinhaltet Go eine gut ausgestattete Standardbibliothek und hat eine
aktive Community.
@@ -24,7 +24,7 @@ aktive Community.
/* Mehr-
zeiliger Kommentar */
-// Eine jede Quelldatei beginnt mit einer Paket-Klausel.
+// Wie bei Java gehört jede Quelldatei einem Paket an (Modularisierung).
// "main" ist ein besonderer Paketname, da er ein ausführbares Programm
// einleitet, im Gegensatz zu jedem anderen Namen, der eine Bibliothek
// deklariert.
@@ -40,7 +40,7 @@ import (
// Es folgt die Definition einer Funktion, in diesem Fall von "main". Auch hier
// ist der Name wieder besonders. "main" markiert den Eintrittspunkt des
-// Programms. Vergessen Sie nicht die geschweiften Klammern!
+// Programms.
func main() {
// Println gibt eine Zeile zu stdout aus.
// Der Prefix "fmt" bestimmt das Paket aus welchem die Funktion stammt.
@@ -50,8 +50,8 @@ func main() {
beyondHello()
}
-// Funktionen können Parameter akzeptieren, diese werden in Klammern deklariert,
-// die aber auch bei keinen Parametern erforderlich sind.
+// Funktionen können Parameter akzeptieren. Diese werden in Klammern deklariert,
+// die aber auch ohne Parameter erforderlich sind.
func beyondHello() {
var x int // Deklaration einer Variable, muss vor Gebrauch geschehen.
x = 3 // Zuweisung eines Werts.
@@ -99,7 +99,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ
// "slices" haben eine dynamische Größe. Arrays und Slices haben beide ihre
// Vorzüge, aber slices werden viel häufiger verwendet
s3 := []int{4, 5, 9} // Vergleichen Sie mit a3, hier: keine Ellipse
- s4 := make([]int, 4) // Weist Speicher für 4 ints zu, alle mit Initialwert 0
+ s4 := make([]int, 4) // Weist Speicher für 4 ints zu, alle mit Wert 0
var d2 [][]float64 // Nur eine Deklaration, keine Speicherzuweisung
bs := []byte("eine slice") // Umwandlungs-Syntax
@@ -201,7 +201,8 @@ type pair struct {
x, y int
}
-// Definiere eine Methode von "pair". Dieser Typ erfüllt jetzt das Stringer interface.
+// Definiere eine Methode von "pair".
+// Dieser Typ erfüllt jetzt das Stringer interface.
func (p pair) String() string { // p ist der Empfänger
// Sprintf ist eine weitere öffentliche Funktion von fmt.
// Der Syntax mit Punkt greift auf die Felder zu.
@@ -255,8 +256,9 @@ func learnConcurrency() {
// Die selbe "make"-Funktion wie vorhin. Sie initialisiert Speicher für
// maps, slices und Kanäle.
c := make(chan int)
- // Starte drei parallele "Goroutines". Die Zahlen werden parallel (concurrently)
- // erhöht. Alle drei senden ihr Ergebnis in den gleichen Kanal.
+ // Starte drei parallele "Goroutines".
+ // Die Zahlen werden parallel (concurrently) erhöht.
+ // Alle drei senden ihr Ergebnis in den gleichen Kanal.
go inc(0, c) // "go" ist das Statement zum Start einer neuen Goroutine
go inc(10, c)
go inc(-805, c)
@@ -306,14 +308,13 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
```
## Weitere Resourcen
-Alles zu Go finden Sie auf der [offiziellen Go Webseite](http://golang.org/).
-Dort können sie dem Tutorial folgen, interaktiv Quelltext ausprobieren und viel
-Dokumentation lesen.
+Informationen zu Go findet man auf der [offiziellen Go Webseite](http://golang.org/).
+Dort gibt es unter anderem ein Tutorial und interaktive Quelltext-Beispiele, vor
+allem aber Dokumentation zur Sprache und den Paketen.
Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr
-kurz und auch gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen
-ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/).
-Gut dokumentiert, demonstriert sie leicht zu verstehendes und im idiomatischen Stil
-verfasstes Go. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen
+kurz und gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen
+ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/)
+einzusehen. Dieser kann als Referenz für leicht zu verstehendes und im idiomatischen Stil
+verfasstes Go dienen. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen
in der [offiziellen Dokumentation von Go](http://golang.org/pkg/).
-
diff --git a/de-de/hack-de.html.markdown b/de-de/hack-de.html.markdown
new file mode 100644
index 00000000..42428130
--- /dev/null
+++ b/de-de/hack-de.html.markdown
@@ -0,0 +1,322 @@
+---
+language: Hack
+lang: de-de
+contributors:
+ - ["Stephen Holdaway", "https://github.com/stecman"]
+ - ["David Lima", "https://github.com/davelima"]
+translators:
+ - ["Jerome Meinke", "https://github.com/jmeinke"]
+filename: learnhack-de.hh
+---
+
+Hack ist eine von Facebook neu entwickelte Programmiersprache auf Basis von PHP.
+Sie wird von der HipHop Virtual Machine (HHVM) ausgeführt. Die HHVM kann
+aufgrund der Ähnlichkeit der Programmiersprachen nicht nur Hack, sondern auch
+PHP-Code ausführen. Der wesentliche Unterschied zu PHP besteht in der statischen
+Typisierung der Sprache, die eine wesentlich höhere Performance erlaubt.
+
+
+Hier werden nur Hack-spezifische Eigenschaften beschrieben. Details über PHP's
+Syntax findet man im [PHP Artikel](http://learnxinyminutes.com/docs/php/) dieser
+Seite.
+
+```php
+<?hh
+
+// Hack-Syntax ist nur für Dateien aktiv, die mit dem <?hh Prefix starten.
+// Der <?hh Prefix kann nicht wie <?php mit HTML gemischt werden.
+// Benutzung von "<?hh //strict" aktiviert den Strikt-Modus des Type-Checkers.
+
+
+// Typisierung für Funktions-Argumente
+function repeat(string $word, int $count)
+{
+ $word = trim($word);
+ return str_repeat($word . ' ', $count);
+}
+
+// Typisierung für Rückgabewerte
+function add(...$numbers) : int
+{
+ return array_sum($numbers);
+}
+
+// Funktionen ohne Rückgabewert, werden mit "void" typisiert
+function truncate(resource $handle) : void
+{
+ // ...
+}
+
+// Typisierung unterstützt die explizit optionale Ein- / Ausgabe von "null"
+function identity(?string $stringOrNull) : ?string
+{
+ return $stringOrNull;
+}
+
+// Typisierung von Klassen-Eigenschaften
+class TypeHintedProperties
+{
+ public ?string $name;
+
+ protected int $id;
+
+ private float $score = 100.0;
+
+ // Hack erfordert es, dass typisierte Eigenschaften (also "non-null")
+ // einen Default-Wert haben oder im Konstruktor initialisiert werden.
+ public function __construct(int $id)
+ {
+ $this->id = $id;
+ }
+}
+
+
+// Kurzgefasste anonyme Funktionen (lambdas)
+$multiplier = 5;
+array_map($y ==> $y * $multiplier, [1, 2, 3]);
+
+
+// Weitere, spezielle Felder (Generics)
+// Diese kann man sich als ein zugreifbares Interface vorstellen
+class Box<T>
+{
+ protected T $data;
+
+ public function __construct(T $data) {
+ $this->data = $data;
+ }
+
+ public function getData(): T {
+ return $this->data;
+ }
+}
+
+function openBox(Box<int> $box) : int
+{
+ return $box->getData();
+}
+
+
+// Formen
+//
+// Hack fügt das Konzept von Formen hinzu, wie struct-ähnliche arrays
+// mit einer typ-geprüften Menge von Schlüsseln
+type Point2D = shape('x' => int, 'y' => int);
+
+function distance(Point2D $a, Point2D $b) : float
+{
+ return sqrt(pow($b['x'] - $a['x'], 2) + pow($b['y'] - $a['y'], 2));
+}
+
+distance(
+ shape('x' => -1, 'y' => 5),
+ shape('x' => 2, 'y' => 50)
+);
+
+
+// Typen-Definition bzw. Aliasing
+//
+// Hack erlaubt es Typen zu definieren und sorgt somit für bessere Lesbarkeit
+newtype VectorArray = array<int, Vector<int>>;
+
+// Ein Tupel mit zwei Integern
+newtype Point = (int, int);
+
+function addPoints(Point $p1, Point $p2) : Point
+{
+ return tuple($p1[0] + $p2[0], $p1[1] + $p2[1]);
+}
+
+addPoints(
+ tuple(1, 2),
+ tuple(5, 6)
+);
+
+
+// Erstklassige Aufzählungen (enums)
+enum RoadType : int
+{
+ Road = 0;
+ Street = 1;
+ Avenue = 2;
+ Boulevard = 3;
+}
+
+function getRoadType() : RoadType
+{
+ return RoadType::Avenue;
+}
+
+
+// Automatische Erstellung von Klassen-Eigenschaften durch Konstruktor-Argumente
+//
+// Wiederkehrende Definitionen von Klassen-Eigenschaften können durch die Hack-
+// Syntax vermieden werden. Hack erlaubt es die Klassen-Eigenschaften über
+// Argumente des Konstruktors zu definieren.
+class ArgumentPromotion
+{
+ public function __construct(public string $name,
+ protected int $age,
+ private bool $isAwesome) {}
+}
+
+class WithoutArgumentPromotion
+{
+ public string $name;
+
+ protected int $age;
+
+ private bool $isAwesome;
+
+ public function __construct(string $name, int $age, bool $isAwesome)
+ {
+ $this->name = $name;
+ $this->age = $age;
+ $this->isAwesome = $isAwesome;
+ }
+}
+
+
+// Kooperatives Multitasking
+//
+// Die Schlüsselworte "async" and "await" führen Multitasking ein.
+// Achtung, hier werden keine Threads benutzt, sondern nur Aktivität getauscht.
+async function cooperativePrint(int $start, int $end) : Awaitable<void>
+{
+ for ($i = $start; $i <= $end; $i++) {
+ echo "$i ";
+
+ // Geben anderen Tasks die Möglichkeit aktiv zu werden
+ await RescheduleWaitHandle::create(RescheduleWaitHandle::QUEUE_DEFAULT, 0);
+ }
+}
+
+// Die Ausgabe von folgendem Code ist "1 4 7 2 5 8 3 6 9"
+AwaitAllWaitHandle::fromArray([
+ cooperativePrint(1, 3),
+ cooperativePrint(4, 6),
+ cooperativePrint(7, 9)
+])->getWaitHandle()->join();
+
+
+// Attribute
+//
+// Attribute repräsentieren eine Form von Metadaten für Funktionen.
+// Hack bietet Spezial-Attribute, die nützliche Eigenschaften mit sich bringen.
+
+// Das __Memoize Attribut erlaubt es die Ausgabe einer Funktion zu cachen.
+<<__Memoize>>
+function doExpensiveTask() : ?string
+{
+ return file_get_contents('http://example.com');
+}
+
+// Der Funktionsrumpf wird im Folgenden nur ein einziges mal ausgeführt:
+doExpensiveTask();
+doExpensiveTask();
+
+
+// Das __ConsistentConstruct Attribut signalisiert dem type-checker, dass
+// die Funktionsdeklaration von __construct für alle Unterklassen dieselbe ist.
+<<__ConsistentConstruct>>
+class ConsistentFoo
+{
+ public function __construct(int $x, float $y)
+ {
+ // ...
+ }
+
+ public function someMethod()
+ {
+ // ...
+ }
+}
+
+class ConsistentBar extends ConsistentFoo
+{
+ public function __construct(int $x, float $y)
+ {
+ // Der Type-checker erzwingt den Aufruf des Eltern-Klassen-Konstruktors
+ parent::__construct($x, $y);
+
+ // ...
+ }
+
+ // Das __Override Attribut ist ein optionales Signal an den Type-Checker,
+ // das erzwingt, dass die annotierte Methode die Methode der Eltern-Klasse
+ // oder des Traits verändert.
+ <<__Override>>
+ public function someMethod()
+ {
+ // ...
+ }
+}
+
+class InvalidFooSubclass extends ConsistentFoo
+{
+ // Wenn der Konstruktor der Eltern-Klasse nicht übernommen wird,
+ // wird der Type-Checker einen Fehler ausgeben:
+ //
+ // "This object is of type ConsistentBaz. It is incompatible with this object
+ // of type ConsistentFoo because some of their methods are incompatible"
+ //
+ public function __construct(float $x)
+ {
+ // ...
+ }
+
+ // Auch bei der Benutzung des __Override Attributs für eine nicht veränderte
+ // Methode wird vom Type-Checker eine Fehler ausgegeben:
+ //
+ // "InvalidFooSubclass::otherMethod() is marked as override; no non-private
+ // parent definition found or overridden parent is defined in non-<?hh code"
+ //
+ <<__Override>>
+ public function otherMethod()
+ {
+ // ...
+ }
+}
+
+// Ein Trait ist ein Begriff aus der objektorientierten Programmierung und
+// beschreibt eine wiederverwendbare Sammlung von Methoden und Attributen,
+// ähnlich einer Klasse.
+
+// Anders als in PHP können Traits auch als Schnittstellen (Interfaces)
+// implementiert werden und selbst Schnittstellen implementieren.
+interface KittenInterface
+{
+ public function play() : void;
+}
+
+trait CatTrait implements KittenInterface
+{
+ public function play() : void
+ {
+ // ...
+ }
+}
+
+class Samuel
+{
+ use CatTrait;
+}
+
+
+$cat = new Samuel();
+$cat instanceof KittenInterface === true; // True
+
+```
+
+## Weitere Informationen
+
+Die Hack [Programmiersprachen-Referenz](http://docs.hhvm.com/manual/de/hacklangref.php)
+erklärt die neuen Eigenschaften der Sprache detailliert auf Englisch. Für
+allgemeine Informationen kann man auch die offizielle Webseite [hacklang.org](http://hacklang.org/)
+besuchen.
+
+Die offizielle Webseite [hhvm.com](http://hhvm.com/) bietet Infos zum Download
+und zur Installation der HHVM.
+
+Hack's [nicht-untersützte PHP Syntax-Elemente](http://docs.hhvm.com/manual/en/hack.unsupported.php)
+werden im offiziellen Handbuch beschrieben.
diff --git a/de-de/haml-de.html.markdown b/de-de/haml-de.html.markdown
new file mode 100644
index 00000000..7272b365
--- /dev/null
+++ b/de-de/haml-de.html.markdown
@@ -0,0 +1,156 @@
+---
+language: haml
+filename: learnhaml-de.haml
+contributors:
+ - ["Simon Neveu", "https://github.com/sneveu"]
+ - ["Sol Bekic", "https://github.com/S0lll0s"]
+lang: de-de
+---
+
+Haml ist eine Markup- und Templatingsprache, aufgesetzt auf Ruby, mit der HTML Dokumente einfach beschrieben werden können.
+
+Haml vermindert Wiederholung und Fehleranfälligkeit, indem es Tags basierend auf der Markup-Struktur schließt und schachtelt.
+Dadurch ergibt sich kurzes, präzises und logisches Markup.
+
+Haml kann außerhalb eines Ruby-projekts verwendet werden. Mit dem installierten Haml gem kann man das Terminal benutzen um Haml zu HTML umzuwandeln:
+
+$ haml input_file.haml output_file.html
+
+
+```haml
+/ -------------------------------------------
+/ Einrückung
+/ -------------------------------------------
+
+/
+ Einrückung ist ein wichtiges Element des Haml Syntax, deswegen ist es
+ wichtig ein konsequentes Schema zu verwenden. Meistens werden zwei spaces
+ verwendet, solange die Einrückungen das gleiche Schema verfolgen können
+ aber auch andere Breiten und Tabs verwendet werden
+
+
+/ -------------------------------------------
+/ Kommentare
+/ -------------------------------------------
+
+/ Kommentare beginnen mit einem Slash
+
+/
+ Mehrzeilige Kommentare werden eingerückt und mit einem Slash
+ eingeführt
+
+-# Diese Zeile ist ein "stummes" Kommentar, es wird nicht mitgerendert
+
+
+/ -------------------------------------------
+/ HTML Elemente
+/ -------------------------------------------
+
+/ Tags werden durch ein Prozentzeichen und den Tagnamen erzeugt
+%body
+ %header
+ %nav
+
+/ Die Zeilen oben würden folgendes ergeben:
+ <body>
+ <header>
+ <nav></nav>
+ </header>
+ </body>
+
+/ Text kann direkt nach dem Tagnamen eingefügt werden:
+%h1 Headline copy
+
+/ Mehrzeilige Inhalte müssen stattdessen eingerückt werden:
+%p
+ This is a lot of content that we could probably split onto two
+ separate lines.
+
+/
+ HTML kann mit &= escaped werden. So werden HTML-sensitive Zeichen
+ enkodiert. Zum Beispiel:
+
+%p
+ &= "Ja & Nein"
+
+/ würde 'Ja &amp; Nein' ergeben
+
+/ HTML kann mit != dekodiert werden:
+%p
+ != "so schreibt man ein Paragraph-Tag: <p></p>"
+
+/ ...was 'This is how you write a paragraph tag <p></p>' ergeben würde
+
+/ CSS Klassen können mit '.classname' an Tags angehängt werden:
+%div.foo.bar
+
+/ oder über einen Ruby Hash:
+%div{:class => 'foo bar'}
+
+/ Das div Tag wird standardmäßig verwendet, divs können also verkürzt werden:
+.foo
+
+/ andere Attribute können über den Hash angegeben werden:
+%a{:href => '#', :class => 'bar', :title => 'Bar'}
+
+/ Booleesche Attribute können mit 'true' gesetzt werden:
+%input{:selected => true}
+
+/ data-Attribute können in einem eigenen Hash im :data key angegeben werden:
+%div{:data => {:attribute => 'foo'}}
+
+
+/ -------------------------------------------
+/ Verwendung von Ruby
+/ -------------------------------------------
+
+/ Mit dem = Zeichen können Ruby-werte evaluiert und als Tag-text verwendet werden:
+
+%h1= book.name
+
+%p
+ = book.author
+ = book.publisher
+
+
+/ Code nach einem Bindestrich wird ausgeführt aber nicht gerendert:
+- books = ['book 1', 'book 2', 'book 3']
+
+/ So können zum Beispiel auch Blöcke verwendet werden:
+- books.shuffle.each_with_index do |book, index|
+ %h1= book
+
+ if book do
+ %p This is a book
+
+/
+ Auch hier werden wieder keine End-Tags benötigt!
+ Diese ergeben sich aus der Einrückung.
+
+
+/ -------------------------------------------
+/ Inline Ruby / Ruby Interpolation
+/ -------------------------------------------
+
+/ Ruby variablen können mit #{} in Text interpoliert werden:
+%p dein bestes Spiel ist #{best_game}
+
+
+/ -------------------------------------------
+/ Filter
+/ -------------------------------------------
+
+/
+ Mit dem Doppelpinkt können Haml Filter benutzt werden.
+ Zum Beispiel gibt es den :javascript Filter, mit dem inline JS
+ geschrieben werden kann:
+
+:javascript
+ console.log('Dies ist ein <script>');
+
+```
+
+## Weitere Resourcen
+
+- [What is HAML?](http://haml.info/) - Eine gute Einleitung auf der Haml homepage (englisch)
+- [Official Docs](http://haml.info/docs/yardoc/file.REFERENCE.html) - Die offizielle Haml Referenz (englisch)
diff --git a/de-de/haskell-de.html.markdown b/de-de/haskell-de.html.markdown
index d1a0008e..5d17ccc7 100644
--- a/de-de/haskell-de.html.markdown
+++ b/de-de/haskell-de.html.markdown
@@ -100,7 +100,7 @@ not False -- True
[1..] !! 999 -- 1000
-- Haskell evaluiert nun die ersten 1 - 1000 Elemente, aber der Rest der Liste
--- bleibt unangetastet. Haskell wird sie solange nicht weiterevalieren
+-- bleibt unangetastet. Haskell wird sie solange nicht weiterevaluieren
-- bis es muss.
-- Zwei Listen konkatenieren
@@ -115,7 +115,7 @@ tail [1..5] -- [2, 3, 4, 5]
init [1..5] -- [1, 2, 3, 4]
last [1..5] -- 5
--- list comprehensions | Listen erschaffen
+-- Listen erschaffen ("list comprehensions")
[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10]
-- Mit Bedingungen
@@ -179,7 +179,7 @@ myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7]
-- Fold (`inject` in einigen Sprachen)
-- Foldl1 bedeutet: fold von links nach rechts und nehme den ersten
--- Wert der Liste als Basiswert f[r den Akkumulator.
+-- Wert der Liste als Basiswert für den Akkumulator.
foldl1 (\acc x -> acc + x) [1..5] -- 15
----------------------------------------------------
@@ -201,7 +201,7 @@ foo 5 -- 15
-- Funktionskomposition
-- Die (.) Funktion verkettet Funktionen.
--- Zum Beispiel, die Funktion Foo nimmt ein Argument addiert 10 dazu und
+-- Zum Beispiel, die Funktion Foo nimmt ein Argument, addiert 10 dazu und
-- multipliziert dieses Ergebnis mit 4.
foo = (*4) . (+10)
@@ -212,7 +212,7 @@ foo 5 -- 60
-- Haskell hat einen Operator `$`, welcher Funktionsapplikation durchführt.
-- Im Gegenzug zu der Standard-Funktionsapplikation, welche linksassoziativ ist
-- und die höchstmögliche Priorität von "10" hat, ist der `$`-Operator
--- rechtsassoziativ und hat die Priorität 0. Dieses hat (idr.) den Effekt,
+-- rechtsassoziativ und hat die Priorität 0. Dieses hat (i.d.R.) den Effekt,
-- dass der `komplette` Ausdruck auf der rechten Seite als Parameter für die
-- Funktion auf der linken Seite verwendet wird.
-- Mit `.` und `$` kann man sich so viele Klammern ersparen.
@@ -283,7 +283,7 @@ for [0..5] $ \i -> show i
for [0..5] show
-- foldl oder foldr reduziren Listen auf einen Wert.
--- foldl <fn> <initial value> <list>
+-- foldl <Funktion> <initialer Wert> <Liste>
foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43
-- die Abarbeitung sieht so aus:
@@ -435,7 +435,7 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater
```
Haskell ist sehr einfach zu installieren.
-Hohl es dir von [hier](http://www.haskell.org/platform/).
+Hol es dir von [hier](http://www.haskell.org/platform/).
Eine sehr viele langsamere Einführung findest du unter:
[Learn you a Haskell](http://learnyouahaskell.com/) oder
diff --git a/de-de/latex-de.html.markdown b/de-de/latex-de.html.markdown
index 2c18b8fd..ee9c6e3e 100644
--- a/de-de/latex-de.html.markdown
+++ b/de-de/latex-de.html.markdown
@@ -6,19 +6,19 @@ contributors:
- ["Sricharan Chiruvolu", "http://sricharan.xyz"]
translators:
- ["Moritz Kammerer", "https://github.com/phxql"]
+ - ["Jerome Meinke", "https://github.com/jmeinke"]
lang: de-de
filename: latex-de.tex
---
```
-% Alle Kommentare starten fangen mit % an
-% Es gibt keine Kommentare über mehrere Zeilen
+% Alle Kommentare starten mit einem Prozentzeichen %
-% LateX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B.
+% LaTeX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B.
% MS Word oder OpenOffice Writer
-% Jedes LateX-Kommando startet mit einem Backslash (\)
+% Jedes LaTeX-Kommando startet mit einem Backslash (\)
-% LateX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen
+% LaTeX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen
% Weitere Dokumententypen sind z.B. book, report, presentations, etc.
% Optionen des Dokuments stehen zwischen den eckigen Klammern []. In diesem Fall
% wollen wir einen 12 Punkte-Font verwenden.
@@ -26,7 +26,7 @@ filename: latex-de.tex
% Als nächstes definieren wir die Pakete, die wir verwenden wollen.
% Wenn du z.B. Grafiken, farbigen Text oder Quelltext in dein Dokument einbetten möchtest,
-% musst du die Fähigkeiten von Latex durch Hinzufügen von Paketen erweitern.
+% musst du die Fähigkeiten von LaTeX durch Hinzufügen von Paketen erweitern.
% Wir verwenden die Pakete float und caption für Bilder.
\usepackage{caption}
\usepackage{float}
@@ -34,30 +34,41 @@ filename: latex-de.tex
% Mit diesem Paket können leichter Umlaute getippt werden
\usepackage[utf8]{inputenc}
+% Es gibt eigentlich keine Kommentare über mehrere Zeilen, solche kann man
+% aber selbst durch die Angabe eigener Kommandos definieren.
+% Dieses Kommando kann man später benutzen.
+\newcommand{\comment}[1]{}
+
% Es können durchaus noch weitere Optione für das Dokument gesetzt werden!
\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu}
\date{\today}
-\title{Learn LaTeX in Y Minutes!}
+\title{Learn \LaTeX\ in Y Minutes!}
% Nun kann's losgehen mit unserem Dokument.
% Alles vor dieser Zeile wird die Preamble genannt.
-\begin{document}
+\begin{document}
+
+\comment{
+ Dies ist unser selbst-definierter Befehl
+ für mehrzeilige Kommentare.
+}
+
% Wenn wir den Autor, das Datum und den Titel gesetzt haben, kann
-% LateX für uns eine Titelseite generieren
+% LaTeX für uns eine Titelseite generieren
\maketitle
-% Die meisten Paper haben ein Abstract. LateX bietet dafür einen vorgefertigen Befehl an.
+% Die meisten Paper haben ein Abstract. LaTeX bietet dafür einen vorgefertigen Befehl an.
% Das Abstract sollte in der logischen Reihenfolge, also nach dem Titel, aber vor dem
% Inhalt erscheinen.
% Dieser Befehl ist in den Dokumentenklassen article und report verfügbar.
\begin{abstract}
- LateX documentation geschrieben in LateX! Wie ungewöhnlich und garantiert nicht meine Idee!
+ \LaTeX -Documentation geschrieben in \LaTeX ! Wie ungewöhnlich und garantiert nicht meine Idee!
\end{abstract}
% Section Befehle sind intuitiv.
% Alle Titel der sections werden automatisch in das Inhaltsverzeichnis übernommen.
\section{Einleitung}
-Hi, mein Name ist Moritz und zusammen werden wir LateX erforschen!
+Hi, mein Name ist Moritz und zusammen werden wir \LaTeX\ erforschen!
\section{Noch eine section}
Das hier ist der Text für noch eine section. Ich glaube, wir brauchen eine subsection.
@@ -71,16 +82,16 @@ So ist's schon viel besser.
% Wenn wir den Stern nach section schreiben, dann unterdrückt LateX die Nummerierung.
% Das funktioniert auch bei anderen Befehlen.
-\section*{Das ist eine unnummerierte section}
-Es müssen nicht alle sections nummeriert sein!
+\section*{Das ist eine unnummerierte section}
+Es müssen nicht alle Sections nummeriert sein!
\section{Ein paar Notizen}
-LateX ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht.
+\LaTeX\ ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht.
Falls eine Zeile \\ mal \\ woanders \\ umgebrochen \\ werden \\ soll, füge
\textbackslash\textbackslash in den Code ein.\\
\section{Listen}
-Listen sind eine der einfachsten Dinge in LateX. Ich muss morgen einkaufen gehen,
+Listen sind eine der einfachsten Dinge in \LaTeX. Ich muss morgen einkaufen gehen,
also lass uns eine Einkaufsliste schreiben:
\begin{enumerate} % Dieser Befehl erstellt eine "enumerate" Umgebung.
% \item bringt enumerate dazu, eins weiterzuzählen.
@@ -96,7 +107,7 @@ also lass uns eine Einkaufsliste schreiben:
\section{Mathe}
-Einer der Haupteinsatzzwecke von LateX ist das Schreiben von akademischen
+Einer der Haupteinsatzzwecke von \LaTeX\ ist das Schreiben von akademischen
Artikeln oder Papern. Meistens stammen diese aus dem Bereich der Mathe oder
anderen Wissenschaften. Und deswegen müssen wir in der Lage sein, spezielle
Symbole zu unserem Paper hinzuzufügen! \\
@@ -106,18 +117,18 @@ Symbole für Mengen und relationen, Pfeile, Operatoren und Griechische Buchstabe
um nur ein paar zu nennen.\\
Mengen und Relationen spielen eine sehr wichtige Rolle in vielen mathematischen
-Papern. So schreibt man in LateX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\
+Papern. So schreibt man in \LaTeX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\
-% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LateX schreiben,
+% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LaTeX schreiben,
% geschieht dies standardmäßig im Textmodus. Die Mathe-Symbole existieren allerdings
% nur im Mathe-Modus. Wir können den Mathe-Modus durch das $ Zeichen aktivieren und
% ihn mit $ wieder verlassen. Variablen können auch im Mathe-Modus angezeigt werden.
Mein Lieblingsbuchstabe im Griechischen ist $\xi$. Ich mag auch $\beta$, $\gamma$ und $\sigma$.
-Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den LateX nicht kennt!
+Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den \LaTeX nicht kennt!
Operatoren sind ebenfalls wichtige Bestandteile von mathematischen Dokumenten:
-Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$),
+Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$),
Logarithmus und Exponenten ($\log$, $\exp$),
Grenzwerte ($\lim$), etc. haben vordefinierte Befehle.
Lass uns eine Gleichung schreiben: \\
@@ -127,7 +138,7 @@ $\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$\\
Brüche (Zähler / Nenner) können so geschrieben werden:
% 10 / 7
-$^{10}/_{7}$
+$^{10}/_{7}$
% Komplexere Brüche können so geschrieben werden:
% \frac{Zähler}{Nenner}
@@ -142,19 +153,19 @@ Wir können Gleichungen auch in einer equation Umgebung verwenden.
\end{equation} % Alle \begin Befehle müssen einen \end Befehl besitzen
Wir können nun unsere Gleichung referenzieren!
-Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in
+Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in
Abschnitt ~\ref{subsec:pythagoras} behandelt. Es können sehr viele Sachen mit Labels versehen werden:
Grafiken, Gleichungen, Sections, etc.
Summen und Integrale können mit den sum und int Befehlen dargestellt werden:
-% Manche LateX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen
-\begin{equation}
+% Manche LaTeX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen
+\begin{equation}
\sum_{i=0}^{5} f_{i}
-\end{equation}
-\begin{equation}
+\end{equation}
+\begin{equation}
\int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
-\end{equation}
+\end{equation}
\section{Grafiken}
@@ -164,7 +175,7 @@ Aber keine Sorge, ich muss auch jedes mal nachschauen, welche Option wie wirkt.
\begin{figure}[H] % H ist die Platzierungsoption
\centering % Zentriert die Grafik auf der Seite
% Fügt eine Grafik ein, die auf 80% der Seitenbreite einnimmt.
- %\includegraphics[width=0.8\linewidth]{right-triangle.png}
+ %\includegraphics[width=0.8\linewidth]{right-triangle.png}
% Auskommentiert, damit es nicht im Dokument auftaucht.
\caption{Dreieck mit den Seiten $a$, $b$, $c$}
\label{fig:right-triangle}
@@ -177,7 +188,7 @@ Wir können Tabellen genauso wie Grafiken einfügen.
\caption{Überschrift der Tabelle.}
% Die {} Argumente geben an, wie eine Zeile der Tabelle dargestellt werden soll.
% Auch hier muss ich jedes Mal nachschauen. Jedes. einzelne. Mal.
- \begin{tabular}{c|cc}
+ \begin{tabular}{c|cc}
Nummer & Nachname & Vorname \\ % Spalten werden durch & getrennt
\hline % Eine horizontale Linie
1 & Biggus & Dickus \\
@@ -187,36 +198,36 @@ Wir können Tabellen genauso wie Grafiken einfügen.
% \section{Links} % Kommen bald!
-\section{Verhindern, dass LateX etwas kompiliert (z.B. Quelltext)}
-Angenommen, wir wollen Quelltext in unserem LateX-Dokument. LateX soll
-in diesem Fall nicht den Quelltext als LateX-Kommandos interpretieren,
+\section{Verhindern, dass \LaTeX\ etwas kompiliert (z.B. Quelltext)}
+Angenommen, wir wollen Quelltext in unserem \LaTeX-Dokument. \LaTeX\ soll
+in diesem Fall nicht den Quelltext als \LaTeX-Kommandos interpretieren,
sondern es einfach ins Dokument schreiben. Um das hinzubekommen, verwenden
wir eine verbatim Umgebung.
% Es gibt noch weitere Pakete für Quelltexte (z.B. minty, lstlisting, etc.)
% aber verbatim ist das simpelste.
-\begin{verbatim}
+\begin{verbatim}
print("Hello World!")
a%b; % Schau dir das an! Wir können % im verbatim verwenden!
random = 4; #decided by fair random dice roll
\end{verbatim}
-\section{Kompilieren}
+\section{Kompilieren}
Ich vermute, du wunderst dich, wie du dieses tolle Dokument in ein PDF
verwandeln kannst. (Ja, dieses Dokument kompiliert wirklich!) \\
Dafür musst du folgende Schritte durchführen:
\begin{enumerate}
- \item Schreibe das Dokument. (den LateX-Quelltext).
- \item Kompiliere den Quelltext in ein PDF.
+ \item Schreibe das Dokument. (den \LaTeX -Quelltext).
+ \item Kompiliere den Quelltext in ein PDF.
Das Kompilieren sieht so ähnlich wie das hier aus (Linux): \\
- \begin{verbatim}
- $pdflatex learn-latex.tex learn-latex.pdf
+ \begin{verbatim}
+ $pdflatex learn-latex.tex learn-latex.pdf
\end{verbatim}
\end{enumerate}
-Manche LateX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt
+Manche \LaTeX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt
2 wird unsichtbar im Hintergrund ausgeführt.
Alle Formatierungsoptionen werden in Schritt 1 in den Quelltext geschrieben. Schritt 2 verwendet
diff --git a/de-de/lua-de.html.markdown b/de-de/lua-de.html.markdown
new file mode 100644
index 00000000..83f8506c
--- /dev/null
+++ b/de-de/lua-de.html.markdown
@@ -0,0 +1,426 @@
+---
+language: Lua
+contributors:
+ - ["Tyler Neylon", "http://tylerneylon.com/"]
+translators:
+ - ["Martin Schimandl", "https://github.com/Git-Jiro"]
+filename: learnlua-de.lua
+lang: de-de
+---
+
+```lua
+-- Zwei Gedankenstriche starten ein einzeiliges Kommentar.
+
+--[[
+ Fügt man zwei '[' und ']' hinzu,
+ erzeugt man einen mehrzeiligen Kommentar.
+--]]
+--------------------------------------------------------------------------------
+-- 1. Variablen und Fluß-Kontrolle.
+--------------------------------------------------------------------------------
+
+num = 42 -- Alle Nummern sind vom Typ: Double.
+-- Werd nicht nervös, 64-Bit Double haben 52 Bits zum Speichern von exakten
+-- Ganzzahlen; Maschinen-Genauigkeit ist kein Problem für Ganzzahlen kleiner als
+-- 52 Bit.
+
+s = 'walternate' -- Zeichenketten sind unveränderlich, wie bei Python.
+t = "Doppelte Anführungszeichen sind auch OK"
+u = [[ Doppelte eckige Klammern
+ beginnen und beenden
+ mehrzeilige Zeichenketten.]]
+t = nil -- Undefineren von t; Lua hat einen Garbage Collection.
+
+-- Blöcke werden durch Schlüsselwörter wie do/end markiert:
+while num < 50 do
+ num = num + 1 -- Es gibt Keine Operatoren wie ++ oder +=
+end
+
+-- If Bedingungen:
+if num > 40 then
+ print('over 40')
+elseif s ~= 'walternate' then -- ~= bedeutet ungleich
+ -- Gleichheits-Check == wie bei Python; OK für Zeichenketten.
+ io.write('not over 40\n') -- Standard ist stdout.
+else
+ -- Variablen sind standardmäßig global.
+ thisIsGlobal = 5 -- Camel case ist üblich.
+
+ -- So macht man eine Variable lokal:
+ local line = io.read() -- Lies die nächste Zeile von stdin.
+
+ -- Zeichenketten zusammenführen mit dem .. Operator:
+ print('Winter is coming, ' .. line)
+end
+
+-- Undefinierte Variablen geben nil zurück.
+-- Das ist kein Fehler:
+foo = anUnknownVariable -- Nun ist foo = nil.
+
+aBoolValue = false
+
+-- Nur nil und false sind unwahr; 0 and '' sind wahr!
+if not aBoolValue then print('was false') end
+
+-- 'or' und 'and' sind "kurz-geschlossen". Das ist so ähnlich wie der a?b:c
+-- operator in C/js:
+-- in C/js:
+ans = aBoolValue and 'yes' or 'no' --> 'no'
+
+karlSum = 0
+for i = 1, 100 do -- Ein Bereich inkludiert beide Enden.
+ karlSum = karlSum + i
+end
+
+-- Verwende "100, 1, -1" als Breich für Countdowns:
+fredSum = 0
+for j = 100, 1, -1 do fredSum = fredSum + j end
+
+-- Im Allgemeinen besteht ein Bereich aus: Anfang, Ende, [, Schrittweite].
+
+-- Ein anderes Schleifen-Konstrukt:
+repeat
+ print('Der Weg der Zukunft')
+ num = num - 1
+until num == 0
+
+--------------------------------------------------------------------------------
+-- 2. Funktionen.
+--------------------------------------------------------------------------------
+
+function fib(n)
+ if n < 2 then return n end
+ return fib(n - 2) + fib(n - 1)
+end
+
+-- Closures und anonyme Funktionen sind ok:
+function adder(x)
+ -- Die zurückgegebene Funktion wird erzeugt wenn addr aufgerufen wird und merkt
+ -- sich den Wert von x:
+ return function (y) return x + y end
+end
+a1 = adder(9)
+a2 = adder(36)
+print(a1(16)) --> 25
+print(a2(64)) --> 100
+
+-- Rückgabewerte, Funktions-Aufrufe und Zuweisungen funktionieren alle mit
+-- Listen die nicht immer gleich lang sein müssen. Überzählige Empfänger
+-- bekommen nil; überzählige Sender werden ignoriert.
+
+x, y, z = 1, 2, 3, 4
+-- Nun ist x = 1, y = 2, z = 3, und 4 wird ignoriert.
+
+function bar(a, b, c)
+ print(a, b, c)
+ return 4, 8, 15, 16, 23, 42
+end
+
+x, y = bar('zaphod') --> prints "zaphod nil nil"
+-- Nun ist x = 4, y = 8, die Werte 15..42 werden ignoriert.
+
+-- Funktionen sind erste Klasse, und können lokal oder global sein.
+-- Das ist alles das Gleiche:
+function f(x) return x * x end
+f = function (x) return x * x end
+
+-- Das auch:
+local function g(x) return math.sin(x) end
+local g = function(x) return math.sin(x) end
+-- Äquivalent zu local function g(x)..., außer das Referenzen auf g im
+-- Funktions-Körper nicht wie erwartet funktionieren.
+local g; g = function (x) return math.sin(x) end
+-- Die Deklaration 'local g' macht Selbst-Referenzen auf g OK.
+
+-- Nebenbei gesagt, Trigonometrie-Funktionen verwenden Radianten.
+
+-- Funktionsaufrufe mit nur einem Zeichenketten-Parameter brauch keine runden
+-- Klammern.
+print 'hello' -- Funktioniert wunderbar.
+
+-- Funktionsaufrufe mit einem Tabellen-Parameter brauchen auch keine runden
+-- Klammern. Mehr zu Tabellen kommt später.
+print {} -- Funktioniert auch wunderbar.
+
+--------------------------------------------------------------------------------
+-- 3. Tabellen.
+--------------------------------------------------------------------------------
+
+-- Tabellen sind die einzige zusammengesetzte Struktur in Lua. Sie sind
+-- assoziative Arrays. Sie sind so ähnlich wie PHP arrays oder JavaScript
+-- Objekte. Sie sind Hash-Lookup-Dictionaries die auch als Listen verwendet
+-- werden können.
+
+-- Verwenden von Tabellen als Dictionaries oder Maps:
+
+-- Dict-Literale haben standardmäßig Zeichenketten als Schlüssel:
+t = {key1 = 'value1', key2 = false}
+
+-- Zeichenketten-Schlüssel verwenden eine JavaScript ähnliche Punkt-Notation.
+print(t.key1) -- Ausgabe 'value1'.
+t.newKey = {} -- Neues Schlüssel/Wert-Paar hinzufügen.
+t.key2 = nil -- key2 aus der Tabelle entfernen.
+
+-- Literale notation für jeden (nicht-nil) Wert als Schlüssel:
+u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
+print(u[6.28]) -- Ausgabe "tau"
+
+-- Schlüssel-Vergleiche funktionieren per Wert für Nummern und Zeichenketten,
+-- aber über die Identität bei Tabellen.
+a = u['@!#'] -- Nun ist a = 'qbert'.
+b = u[{}] -- Wir würden 1729 erwarten, aber es ist nil:
+-- b = nil weil der Lookup fehlschlägt. Er schlägt Fehl, weil der Schlüssel
+-- den wir verwendet haben nicht das gleiche Objekt ist das wir verwendet
+-- haben um den original Wert zu speichern. Zahlen und Zeichnkette sind daher
+-- die praktischeren Schlüssel.
+
+-- Eine Funktion mit nur einem Tabellen-Parameter benötigt keine Klammern.
+function h(x) print(x.key1) end
+h{key1 = 'Sonmi~451'} -- Ausgabe 'Sonmi~451'.
+
+for key, val in pairs(u) do -- Tabellen-Iteration.
+ print(key, val)
+end
+
+-- _G ist eine spezielle Tabelle die alles Globale enthält.
+print(_G['_G'] == _G) -- Ausgabe 'true'.
+
+-- Verwenden von Tabellen als Listen/Arrays:
+
+-- Listen-Literale verwenden implizit Ganzzahlen als Schlüssel:
+v = {'value1', 'value2', 1.21, 'gigawatts'}
+for i = 1, #v do -- #v ist die Größe von v für Listen.
+ print(v[i]) -- Indices beginnen mit 1 !! SO VERRÜCKT!
+end
+-- Eine 'Liste' ist kein echter Typ. v ist nur eine Tabelle mit fortlaufenden
+-- Ganzzahlen als Schlüssel, die behandelt wird wie eine Liste.
+
+--------------------------------------------------------------------------------
+-- 3.1 Metatabellen und Metamethoden
+--------------------------------------------------------------------------------
+
+-- Eine Tabelle kann eine Metatabelle haben. Diese verleiht ihr so etwas wie
+-- Tabellen-Operator-Überladungs-Verhalten. Später sehen wir wie
+-- Metatabellen js-prototypen artiges Verhalten unterstützen.
+
+f1 = {a = 1, b = 2} -- Repräsentiert den Bruch a/b.
+f2 = {a = 2, b = 3}
+
+-- Dies würde Fehlschlagen:
+-- s = f1 + f2
+
+metafraction = {}
+function metafraction.__add(f1, f2)
+ local sum = {}
+ sum.b = f1.b * f2.b
+ sum.a = f1.a * f2.b + f2.a * f1.b
+ return sum
+end
+
+setmetatable(f1, metafraction)
+setmetatable(f2, metafraction)
+
+s = f1 + f2 -- Rufe __add(f1, f2) vom der Metatabelle von f1 auf.
+
+-- f1 und f2 haben keine Schlüssel für ihre Metatabellen, anders als bei js
+-- Prototypen. Daher muss mithilfe von getmetatable(f1) darauf zugegriffen
+-- werden. Eine Metatabelle ist wie eine normale Tabelle mit Schlüsseln die
+-- Lua bekannt sind, so wie __add.
+
+
+-- Die nächste Zeile schlägt fehl weil s keine Metatabelle hat:
+-- t = s + s
+-- Mihilfe von Klassen ähnlichen Mustern kann das gelöst werden.
+-- Siehe weiter unten.
+
+-- Ein __index einer Metatabelle überlädt Punkt-Lookups:
+defaultFavs = {animal = 'gru', food = 'donuts'}
+myFavs = {food = 'pizza'}
+setmetatable(myFavs, {__index = defaultFavs})
+eatenBy = myFavs.animal -- Funktioniert dank Metatabelle!
+
+--------------------------------------------------------------------------------
+-- Direkte Tabellen-Lookups die fehlschlagen werden mithilfe von __index der
+-- Metatabelle wiederholt. Das geschieht rekursiv.
+
+-- __index kann auch eine Funktion mit der Form function(tbl, key) sein.
+-- Damit kann man Lookups weiter anpassen.
+
+-- Werte wie __index,add, .. werden Metamethoden genannt.
+-- HIer eine vollständige Liste aller Metamethoden.
+
+-- __add(a, b) für a + b
+-- __sub(a, b) für a - b
+-- __mul(a, b) für a * b
+-- __div(a, b) für a / b
+-- __mod(a, b) für a % b
+-- __pow(a, b) für a ^ b
+-- __unm(a) für -a
+-- __concat(a, b) für a .. b
+-- __len(a) für #a
+-- __eq(a, b) für a == b
+-- __lt(a, b) für a < b
+-- __le(a, b) für a <= b
+-- __index(a, b) <fn or a table> für a.b
+-- __newindex(a, b, c) für a.b = c
+-- __call(a, ...) für a(...)
+
+--------------------------------------------------------------------------------
+-- 3.2 Klassen-Artige Tabellen und Vererbung.
+--------------------------------------------------------------------------------
+
+-- Klassen sind in Lua nicht eingebaut. Es gibt verschieden Wege sie mithilfe
+-- von Tabellen und Metatabellen zu erzeugen.
+
+-- Die Erklärund des Beispiels erfolgt unterhalb.
+
+Dog = {} -- 1.
+
+function Dog:new() -- 2.
+ local newObj = {sound = 'woof'} -- 3.
+ self.__index = self -- 4.
+ return setmetatable(newObj, self) -- 5.
+end
+
+function Dog:makeSound() -- 6.
+ print('I say ' .. self.sound)
+end
+
+mrDog = Dog:new() -- 7.
+mrDog:makeSound() -- 'I say woof' -- 8.
+
+-- 1. Dog verhält sich wie eine Klasse; Ist aber eine Tabelle.
+-- 2. "function tablename:fn(...)" ist das gleiche wie
+-- "function tablename.fn(self, ...)", Der : fügt nur ein Argument namens
+-- self hinzu. Siehe 7 & 8 um zu sehen wie self seinen Wert bekommt.
+-- 3. newObj wird eine Instanz von Dog.
+-- 4. "self" ist die zu Instanzierende Klasse. Meistern ist self = Dog, aber
+-- dies kann durch Vererbung geändert werden. newObj bekommt die Funktionen
+-- von self wenn wir die Metatabelle von newObj und __index von self auf
+-- self setzen.
+-- 5. Zur Erinnerung: setmetatable gibt sein erstes Argument zurück.
+-- 6. Der Doppelpunkt funktioniert wie bei 2, aber dieses Mal erwarten wir das
+-- self eine Instanz ist und keine Klasse.
+-- 7. Das Selbe wie Dog.new(Dog), also self = Dog in new().
+-- 8. Das Selbe wie mrDog.makeSound(mrDog); self = mrDog.
+
+--------------------------------------------------------------------------------
+
+-- Vererbungs-Beispiel:
+
+LoudDog = Dog:new() -- 1.
+
+function LoudDog:makeSound()
+ local s = self.sound .. ' ' -- 2.
+ print(s .. s .. s)
+end
+
+seymour = LoudDog:new() -- 3.
+seymour:makeSound() -- 'woof woof woof' -- 4.
+
+--------------------------------------------------------------------------------
+-- 1. LoudDog bekommt die Methoden und Variablen von Dog.
+-- 2. self hat einen 'sound' Schlüssel von new(), siehe 3.
+-- 3. Das Gleiche wie "LoudDog.new(LoudDog)", und umgewandelt zu "Dog.new(LoudDog)"
+-- denn LoudDog hat keinen 'new' Schlüssel, aber "__index = Dog" steht in der
+-- Metatabelle.
+-- Ergebnis: Die Metatabelle von seymour ist LoudDog und "LoudDog.__index = Dog".
+-- Daher ist seymour.key gleich seymour.key, LoudDog.key, Dog.key, je nachdem
+-- welche Tabelle als erstes einen passenden Schlüssel hat.
+-- 4. Der 'makeSound' Schlüssel wird in LoudDog gefunden: Das ist das Gleiche
+-- wie "LoudDog.makeSound(seymour)".
+
+-- Wenn nötig, sieht new() einer Sub-Klasse genau so aus wie new() der
+-- Basis-Klasse:
+function LoudDog:new()
+ local newObj = {}
+ -- set up newObj
+ self.__index = self
+ return setmetatable(newObj, self)
+end
+
+--------------------------------------------------------------------------------
+-- 4. Module.
+--------------------------------------------------------------------------------
+
+
+--[[ Dieser Abschnitt ist auskommentiert damit der Rest des Skripts lauffähig
+-- bleibt.
+```
+
+```lua
+-- Angenommen mod.lua sieht so aus:
+local M = {}
+
+local function sayMyName()
+ print('Hrunkner')
+end
+
+function M.sayHello()
+ print('Why hello there')
+ sayMyName()
+end
+
+return M
+
+-- Eine andere Datei könnte die Funktionen in mod.lua so verwenden:
+local mod = require('mod') -- Führe mod.lua aus.
+
+-- require ist der Standard-Weg um Module zu inkludieren.
+-- require verhält sich wie: (Wenn nicht gecached wird; siehe später)
+local mod = (function ()
+ <Inhalt von mod.lua>
+end)()
+-- Es ist als ob mod.lua eine Funktion wäre, sodass lokale Variablen in
+-- mod.lua ausserhalb unsichtbar sind.
+
+-- Das funktioniert weil mod hier das Gleiche wie M in mod.lua ist:
+mod.sayHello() -- Says hello to Hrunkner.
+
+-- Das ist Falsch: sayMyName existiert nur in mod.lua:
+mod.sayMyName() -- Fehler
+
+-- Der Rückgabe-Wert von require wird zwischengespeichert. Sodass Module nur
+-- einmal abgearbeitet werden, auch wenn sie mit require öfters eingebunden
+-- werden.
+
+-- Nehmen wir an mod2.lua enthält "print('Hi!')".
+local a = require('mod2') -- Ausgabe Hi!
+local b = require('mod2') -- Keine Ausgabe; a=b.
+
+-- dofile ist wie require aber ohne Zwischenspeichern.
+dofile('mod2') --> Hi!
+dofile('mod2') --> Hi! (läuft nochmal, nicht wie require)
+
+-- loadfile ladet eine lua Datei aber die Datei wird noch nicht abgearbeitet.
+f = loadfile('mod2') -- Sobald f() aufgerufen wird läuft mod2.lua.
+
+-- loadstring ist loadfile für Zeichenketten
+g = loadstring('print(343)') -- Gibt eine Funktion zurück..
+g() -- Ausgabe 343; Vorher kam keine Ausgabe.
+
+--]]
+
+```
+## Referenzen
+
+Ich war so begeistert Lua zu lernen, damit ich Spiele mit <a href="http://love2d.org/">Love 2D game engine</a> programmieren konnte.
+
+Ich habe angefangen mit <a href="http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/">BlackBulletIV's Lua for programmers</a>.
+Danach habe ich das offizielle Lua Buch gelesen: <a href="http://www.lua.org/pil/contents.html">Programming in Lua</a>
+
+Es kann auch hilfreich sein hier vorbeizuschauen: <a href="http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf">Lua short
+reference</a>
+
+Wichtige Themen die hier nicht angesprochen wurden; die Standard-Bibliotheken:
+
+* <a href="http://lua-users.org/wiki/StringLibraryTutorial">string library</a>
+* <a href="http://lua-users.org/wiki/TableLibraryTutorial">table library</a>
+* <a href="http://lua-users.org/wiki/MathLibraryTutorial">math library</a>
+* <a href="http://lua-users.org/wiki/IoLibraryTutorial">io library</a>
+* <a href="http://lua-users.org/wiki/OsLibraryTutorial">os library</a>
+
+Übrigends, die gesamte Datei ist gültiges Lua. Speichere sie als learn.lua und
+starte sie als "lua learn.lua" !
+
+Die Erstfassung ist von tylerneylon.com, und ist auch hier verfügbar: <a href="https://gist.github.com/tylerneylon/5853042">github gist</a>. Viel Spaß mit Lua!
diff --git a/de-de/make-de.html.markdown b/de-de/make-de.html.markdown
new file mode 100644
index 00000000..22c14a69
--- /dev/null
+++ b/de-de/make-de.html.markdown
@@ -0,0 +1,260 @@
+---
+language: make
+contributors:
+ - ["Robert Steed", "https://github.com/robochat"]
+translators:
+ - ["Martin Schimandl", "https://github.com/Git-Jiro"]
+filename: Makefile-de
+lang: de-de
+---
+
+Eine Makefile definiert einen Graphen von Regeln um ein Ziel (oder Ziele)
+zu erzeugen. Es dient dazu die geringste Menge an Arbeit zu verrichten um
+ein Ziel in einklang mit dem Quellcode zu bringen. Make wurde berühmterweise
+von Stuart Feldman 1976 übers Wochenende geschrieben. Make ist noch immer
+sehr verbreitet (vorallem im Unix umfeld) obwohl es bereits sehr viel
+Konkurrenz und Kritik zu Make gibt.
+
+Es gibt eine vielzahl an Varianten von Make, dieser Artikel beschäftig sich
+mit der Version GNU Make. Diese Version ist standard auf Linux.
+
+```make
+
+# Kommentare können so geschrieben werden.
+
+# Dateien sollten Makefile heißen, denn dann können sie als `make <ziel>`
+# aufgerufen werden. Ansonsten muss `make -f "dateiname" <ziel>` verwendet
+# werden.
+
+# Warnung - Es sollten nur TABULATOREN zur Einrückung im Makefile verwendet
+# werden. Niemals Leerzeichen!
+
+#-----------------------------------------------------------------------
+# Grundlagen
+#-----------------------------------------------------------------------
+
+# Eine Regel - Diese Regel wird nur abgearbeitet wenn die Datei file0.txt
+# nicht existiert.
+file0.txt:
+ echo "foo" > file0.txt
+ # Selbst Kommentare in der 'Rezept' Sektion werden an die Shell
+ # weitergegeben. Versuche `make file0.txt` oder einfach `make`
+ # die erste Regel ist die Standard-Regel.
+
+
+# Diese Regel wird nur abgearbeitet wenn file0.txt aktueller als file1.txt ist.
+file1.txt: file0.txt
+ cat file0.txt > file1.txt
+ # Verwende die selben Quoting-Regeln wie die Shell
+ @cat file0.txt >> file1.txt
+ # @ unterdrückt die Ausgabe des Befehls an stdout.
+ -@echo 'hello'
+ # - bedeutet das Make die Abarbeitung fortsetzt auch wenn Fehler passieren.
+ # Versuche `make file1.txt` auf der Kommandozeile.
+
+# Eine Regel kann mehrere Ziele und mehrere Voraussetzungen haben.
+file2.txt file3.txt: file0.txt file1.txt
+ touch file2.txt
+ touch file3.txt
+
+# Make wird sich beschweren wenn es mehrere Rezepte für die gleiche Regel gibt.
+# Leere Rezepte zählen nicht und können dazu verwendet werden weitere
+# Voraussetzungen hinzuzufügen.
+
+#-----------------------------------------------------------------------
+# Phony-Ziele
+#-----------------------------------------------------------------------
+
+# Ein Phony-Ziel ist ein Ziel das keine Datei ist.
+# Es wird nie aktuell sein, daher wird Make immer versuchen es abzuarbeiten
+all: maker process
+
+# Es ist erlaubt Dinge ausserhalb der Reihenfolge zu deklarieren.
+maker:
+ touch ex0.txt ex1.txt
+
+# Um das Fehlschlagen von Phony-Regeln zu vermeiden wenn eine echte Datei den
+# selben namen wie ein Phony-Ziel hat:
+.PHONY: all maker process
+# Das ist ein spezielles Ziel. Es gibt noch ein paar mehr davon.
+
+# Eine Regel mit einem Phony-Ziel als Voraussetzung wird immer abgearbeitet
+ex0.txt ex1.txt: maker
+
+# Häufige Phony-Ziele sind: all make clean install ...
+
+#-----------------------------------------------------------------------
+# Automatische Variablen & Wildcards
+#-----------------------------------------------------------------------
+
+process: file*.txt # Eine Wildcard um Dateinamen zu Vergleichen
+ @echo $^ # $^ ist eine Variable die eine Liste aller
+ # Voraussetzungen enthält.
+ @echo $@ # Namen des Ziels ausgeben.
+ #(Bei mehreren Ziel-Regeln enthält $@ den Verursacher der Abarbeitung
+ #der Regel.)
+ @echo $< # Die erste Voraussetzung aus der Liste
+ @echo $? # Nur die Voraussetzungen die nicht aktuell sind.
+ @echo $+ # Alle Voraussetzungen inklusive Duplikate (nicht wie Üblich)
+ #@echo $| # Alle 'order only' Voraussetzungen
+
+# Selbst wenn wir die Voraussetzungen der Regel aufteilen, $^ wird sie finden.
+process: ex1.txt file0.txt
+# ex1.txt wird gefunden werden, aber file0.txt wird dedupliziert.
+
+#-----------------------------------------------------------------------
+# Muster
+#-----------------------------------------------------------------------
+
+# Mit Mustern kann man make beibringen wie Dateien in andere Dateien
+# umgewandelt werden.
+
+%.png: %.svg
+ inkscape --export-png $^
+
+# Muster-Vergleichs-Regeln werden nur abgearbeitet wenn make entscheidet das Ziel zu
+# erzeugen
+
+# Verzeichnis-Pfade werden normalerweise bei Muster-Vergleichs-Regeln ignoriert.
+# Aber make wird versuchen die am besten passende Regel zu verwenden.
+small/%.png: %.svg
+ inkscape --export-png --export-dpi 30 $^
+
+# Make wird die letzte Version einer Muster-Vergleichs-Regel verwenden die es
+# findet.
+%.png: %.svg
+ @echo this rule is chosen
+
+# Allerdings wird make die erste Muster-Vergleicher-Regel verwenden die das
+# Ziel erzeugen kann.
+%.png: %.ps
+ @echo this rule is not chosen if *.svg and *.ps are both present
+
+# Make hat bereits ein paar eingebaute Muster-Vergleichs-Regelen. Zum Beispiel
+# weiß Make wie man aus *.c Dateien *.o Dateien erzeugt.
+
+# Ältere Versionen von Make verwenden möglicherweise Suffix-Regeln anstatt
+# Muster-Vergleichs-Regeln.
+.png.ps:
+ @echo this rule is similar to a pattern rule.
+
+# Aktivieren der Suffix-Regel
+.SUFFIXES: .png
+
+#-----------------------------------------------------------------------
+# Variablen
+#-----------------------------------------------------------------------
+# auch Makros genannt.
+
+# Variablen sind im Grunde genommen Zeichenketten-Typen.
+
+name = Ted
+name2="Sarah"
+
+echo:
+ @echo $(name)
+ @echo ${name2}
+ @echo $name # Das funktioniert nicht, wird als $(n)ame behandelt.
+ @echo $(name3) # Unbekannte Variablen werden als leere Zeichenketten behandelt.
+
+# Es git 4 Stellen um Variablen zu setzen.
+# In Reihenfolge der Priorität von höchster zu niedrigster:
+# 1: Befehls-Zeilen Argumente
+# 2: Makefile
+# 3: Shell Umbebungs-Variablen - Make importiert diese automatisch.
+# 3: MAke hat einige vordefinierte Variablen.
+
+name4 ?= Jean
+# Setze die Variable nur wenn es eine gleichnamige Umgebungs-Variable noch
+# nicht gibt.
+
+override name5 = David
+# Verhindert das Kommando-Zeilen Argumente diese Variable ändern können.
+
+name4 +=grey
+# Werte an eine Variable anhängen (inkludiert Leerzeichen).
+
+# Muster-Spezifische Variablen Werte (GNU Erweiterung).
+echo: name2 = Sara # Wahr innerhalb der passenden Regel und auch innerhalb
+ # rekursiver Voraussetzungen (ausser wenn es den Graphen zerstören
+ # kann wenn es zu kompilizert wird!)
+
+# Ein paar Variablen die von Make automatisch definiert werden.
+echo_inbuilt:
+ echo $(CC)
+ echo ${CXX)}
+ echo $(FC)
+ echo ${CFLAGS)}
+ echo $(CPPFLAGS)
+ echo ${CXXFLAGS}
+ echo $(LDFLAGS)
+ echo ${LDLIBS}
+
+#-----------------------------------------------------------------------
+# Variablen 2
+#-----------------------------------------------------------------------
+
+# Der erste Typ von Variablen wird bei jeder verwendung ausgewertet.
+# Das kann aufwendig sein, daher exisitert ein zweiter Typ von Variablen.
+# Diese werden nur einmal ausgewertet. (Das ist eine GNU make Erweiterung)
+
+var := hello
+var2 ::= $(var) hello
+#:= und ::= sind äquivalent.
+
+# Diese Variablen werden prozedural ausgwertet (in der Reihenfolge in der sie
+# auftauchen), die stehen daher im wiederspruch zum Rest der Sprache!
+
+# Das funktioniert nicht
+var3 ::= $(var4) and good luck
+var4 ::= good night
+
+#-----------------------------------------------------------------------
+# Funktionen
+#-----------------------------------------------------------------------
+
+# Make verfügt über eine vielzahl von Funktionen.
+
+sourcefiles = $(wildcard *.c */*.c)
+objectfiles = $(patsubst %.c,%.o,$(sourcefiles))
+
+# Das Format ist $(func arg0,arg1,arg2...)
+
+# Ein paar Beispiele
+ls: * src/*
+ @echo $(filter %.txt, $^)
+ @echo $(notdir $^)
+ @echo $(join $(dir $^),$(notdir $^))
+
+#-----------------------------------------------------------------------
+# Direktiven
+#-----------------------------------------------------------------------
+
+# Inkludiere andere Makefile, sehr praktisch für platformspezifischen Code
+include foo.mk
+
+sport = tennis
+# Konditionale kompiliereung
+report:
+ifeq ($(sport),tennis)
+ @echo 'game, set, match'
+else
+ @echo "They think it's all over; it is now"
+endif
+
+# Es gibt auch ifneq, ifdef, ifndef
+
+foo = true
+
+ifdef $(foo)
+bar = 'hello'
+endif
+```
+
+
+### Mehr Resourcen
+
++ [gnu make documentation](https://www.gnu.org/software/make/manual/)
++ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/)
++ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)
+
diff --git a/de-de/markdown-de.html.markdown b/de-de/markdown-de.html.markdown
index 6a90980b..2c838660 100644
--- a/de-de/markdown-de.html.markdown
+++ b/de-de/markdown-de.html.markdown
@@ -56,7 +56,7 @@ __Genau wie dieser.__
**_Dieser auch!_**
*__Und dieser genau so!__*
-<!-- In "Github Flavored Markdown", dem von Github verwendeten Dialekt / Parser,
+<!-- In "GitHub Flavored Markdown", dem von GitHub verwendeten Dialekt / Parser,
gibt es auch noch durchgestrichenen Text: -->
~~Dieser Text wird durchgestrichen dargestellt.~~
@@ -148,7 +148,7 @@ indem du eine Zeile mit vier Leerzeichen oder einem Tabulator einrückst -->
Hermann hatte nicht die leiseste Ahnung, was dieses `go_to()` bedeuten könnte!
-<!-- In "Github Flavored Markdown" gibt es für Code nocheinmal eine
+<!-- In "GitHub Flavored Markdown" gibt es für Code nocheinmal eine
besondere Syntax -->
\`\`\`ruby <!-- in "echt" musst du die Backslashes entfernen: ```ruby ! -->
@@ -157,7 +157,7 @@ def foobar
end
\`\`\` <!-- hier auch keine Backslashes, nur ``` -->
-<-- der obige Block muss nicht extra eingerückt werden, außerdem fügt Github
+<-- der obige Block muss nicht extra eingerückt werden, außerdem fügt GitHub
Syntax-Highlighting für die nach dem ``` angegebene Sprache hinzu -->
<!-- Horizontale Linie (<hr />) -->
@@ -233,7 +233,7 @@ Ich würde *diesen Teil gerne mit Sternen umschließen*, doch ohne dass er kursi
wird. Also mache ich folgendes: \*Ich umschließe diesen Text mit Sternen\*!
<!-- Tabellen -->
-<!-- Tabellen gibt es bis jetzt nur in "Github Flavored Markdown".
+<!-- Tabellen gibt es bis jetzt nur in "GitHub Flavored Markdown".
Zudem sind sie ziemlich mühselig, aber wenn du es wirklich wissen willst: -->
| Spalte1 | Spalte2 | Spalte3 |
@@ -253,4 +253,4 @@ Ganz schön hässlich | vielleicht doch lieber | wieder aufhören
Mehr Informationen gibt es in [John Gruber's offiziellem Blog-Post](http://daringfireball.net/projects/markdown/syntax)
und bei Adam Pritchards [grandiosem Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
-Infos zu Github Flavored Markdown [gibt es hier](https://help.github.com/articles/github-flavored-markdown). \ No newline at end of file
+Infos zu GitHub Flavored Markdown [gibt es hier](https://help.github.com/articles/github-flavored-markdown). \ No newline at end of file
diff --git a/de-de/tcl-de.html.markdown b/de-de/tcl-de.html.markdown
new file mode 100644
index 00000000..4f3b8820
--- /dev/null
+++ b/de-de/tcl-de.html.markdown
@@ -0,0 +1,475 @@
+---
+language: Tcl
+contributors:
+ - ["Poor Yorick", "http://pooryorick.com/"]
+translators:
+ - ["Martin Schimandl", "https://github.com/Git-Jiro"]
+filename: learntcl-de.tcl
+lang: de-de
+---
+
+Tcl wurde kreiert von [John Ousterhout](http://wiki.tcl.tk/John Ousterout) als
+eine wiederverwendbare Script-Sprache für Chip-Design Werkzeuge die er kreiert
+hat. Im Jahre 1997 wurde er mit dem [ACM Software System
+Award](http://en.wikipedia.org/wiki/ACM_Software_System_Award) für Tcl
+ausgezeichnet. Tcl kann sowohl als eingebettete Scipt-Sprache als auch als
+allgemeine Programmier-Sprache verwendet werden. Tcl kann auch als portable
+C-Bibliothek verwendet werden. Sogar in Fällen in denen die Script-Fähigkeiten
+nicht nötig sind. Denn Tcl stellt Daten-Strukturen wie dynamische Zeichenketten,
+Listen und Hash-Tabellen bereit. Die C-Bilbiothek stellt auch portable
+Funktionen zur Verfügung: Laden von dynamischen Bibliotheken, Zeichenketten
+formatierung und Code Konversion, Dateisystem Operationen, Netzwerk Operationen
+und mehr.
+
+
+Verschiedenste herausragende Fähigkeiten von Tcl:
+
+* Praktische Cross-Platform Netzwerk-API
+
+* Vollständig virtualisiertes Dateisystem
+
+* Stapelbare I/O Kanäle
+
+* Asynchron bis zum Kern
+
+* Vollständige Ko-Routinen
+
+* Robustes und einfach zu verwendendes Thread-Modell
+
+
+Wenn Lisp ein Listen-Prozessor ist, dann ist TCl ein Zeichenketten-Prozessor.
+Alle Werte sind Zeichenketten. Eine Liste ist ein Zeichenketten-Format. Eine
+Prozedur-Definition ist ein Zeichenketten-Format. Um leistungsfähig zu sein,
+werden Tcl-intern diese Zeichenketten in Strukutierter-Form gepuffert. Ein
+Beispiel: Der "list" Befehl arbeitet mit diesen internen gepufferten
+Repräsentationen. Tcl kümmert sich selbständig darum die String-Repräsentationen
+zu aktualisieren, falls dies im Skript benötigt werden sollten. Das Kopieren-
+beim-Schreiben-Design von Tcl erlaubt es Skript-Authoren mit großen Daten-
+Strukturen zu arbeiten ohne zuätzlichen Speicher-Overhead. Prozeduren werden
+automatisch byte-kompiliert außer sie verwenden dynamsiche Befehle wie zum
+Beispiel "uplevel", "upvar und "trace".
+
+Es ist eine freude in Tcl zu programmieren. Hacker-Typen werden gefallen daran
+finden, wenn sie Lisp, Forth oder Smalltalk interessant finden. Tcl wird auch
+Ingenieuren und Wissenshaftlern gefallen die nur den Job erledigen wollen,
+und zwar mit Werkzeugen die sich ihrem Willen anpassen. Bei Tcl ist jegliche
+funktionalität in Befehlen ausgeführt, selbst Dinge wie Schleifen und
+Mathematische-Funktionen die bei anderen Sprachen normalerweise Teil der Syntax
+sind. Das erlaubt Tcl in den Hintergrund von Domänen spezischen Sprachen zu
+treten die das jeweilige Projekt gerade benötigt. Die Tcl-Syntax ist sehr
+leichtgewichtig. Sie ist selbst leichtgewichtiger als die Syntax von Lisp.
+Tcl steht dir einfach nicht im Weg.
+
+
+```tcl
+#! /bin/env tclsh
+
+################################################################################
+## 1. Richtlinien
+################################################################################
+
+# Tcl ist nicht Bash oder C! Das muss gesagt werden, denn standard Shell-Quoting
+# funktioniert fast mit Tcl. Daher glauben viele sie können diese Syntax für
+# Tcl übernehmen. Am Beginn funktioniert das meist, führt aber schnell zu
+# Frustrationen wenn die Skripte komplexer werden.
+
+# Eckige-Klammern sind nur Quoting-Mechanismen, keine Code-Block-Konstruktoren
+# und auch keine Listen-Konstruktoren. In Tcl gibt es diese beiden Dinge nicht.
+# Eckige-Klammern werden verwendet um Spezial-Zeichen in Prozeduren zu escapen
+# und in Zeichenketten die als Listen formattiert sind.
+
+################################################################################
+## 2. Syntax
+################################################################################
+
+# Jede Zeile ist ein Befehl. Das erste Wort ist der Name des Befehls, jedes
+# weitere Wort ist ein Argument des Befehls. Wörter sind begrenzt durch
+# Leerzeichen. Da jedes Wort auch ein String ist, sind keine speziellen
+# auszeichnungen wie Anführungs-Zeichen, Klammern oder Backslashes nötig.
+# Selbst wenn Anführungs-Zeichen verwendet werden, denn sie sind ja keine
+# String-Konstruktoren, sondern nur Escape-Zeichen.
+
+set greeting1 Sal
+set greeting2 ut
+set greeting3 ations
+
+
+# Strichpunkte begrenzen auch Befehle
+set greeting1 Sal; set greeting2 ut; set greeting3 ations
+
+
+# Das Dollar-Zeichen zeigt eine Variablen-Substitution an.
+set greeting $greeting1$greeting2$greeting3
+
+
+# Eckige-Klammern zeigen Befehls-Substitionen an. Das Ergebnis des Befehls wird an
+# Stelle des Klammern-Ausdrucks eingefügt. Wenn man dem "set" Befehl nur den
+# Namen einer Variablen übergibt, gibt er den Wert der Variablen zurück.
+set greeting $greeting1$greeting2[set greeting3]
+
+
+# Befehls-Substitution sollte eigentlich Script-Substitution heißen, denn ein
+# komplettes Script, und nicht nur ein Befehl, kann zwischen die Eckigen-Klammern
+# geschrieben werden. Der "incr" Befehl erhöht den Wert einer Variable um 1
+# und gibt den neuen Wert der Variable zurück.
+set greeting $greeting[
+ incr i
+ incr i
+ incr i
+]
+
+
+# Der Backslash unterdrück die Bedeutung von Sonderzeichen
+set amount \$16.42
+
+
+# Der Backslash macht bestimmte Zeichen zu Sonderzeichen
+puts lots\nof\n\n\n\n\n\nnewlines
+
+# Ein Wort das in geschweiften Klammern eingeschlossen wurde ist von jeglichen
+# speziellen Interpretationen ausgeschlossen. Eine Ausnahme bilden Backslashes
+# vor geschweiften Klammern, hiermit wird die geschweifte Klammer von der Suche
+# nach der schließenden geschweiften Klammer ausgeschlossen.
+set somevar {
+ Das ist ein literales $ Zeichen, diese geschweifte Klammer \} wird nicht
+ als Ende interpretiert.
+}
+
+
+# Bei einem Wort das in doppelten Anführungszeichen steht verlieren Leerzeichen
+# ihre spezielle Bedeutung.
+set name Neo
+set greeting "Hallo, $name"
+
+
+#Variablen-Namen können irgend eine Zeichenkette sein.
+set {first name} New
+
+
+# Die Geschweifte-Klammern-Form der Variablen-Substitution kann sehr komplexe
+# Variblen-Namen handhaben.
+set greeting "Hello, ${first name}"
+
+
+# Der "set" Befehl kann immer anstatt einer Variablen-Substition verwendet
+# werden.
+set greeting "Hello, [set {first name}]"
+
+
+# Mit dem Expansions-Operator "{*}" werden Wörter innerhalb eines Wortes wieder
+# individuell als Teile des aktuellen Befehls behandelt.
+set {*}{name Neo}
+
+# Ist Äquivalent zu
+set name Neo
+
+
+# Ein Array ist eine spezielle Varible die also Kontainer für andere Variablen
+# dient.
+set person(name) Neo
+set person(gender) male
+set greeting "Hello, $person(name)"
+
+
+# Ein Namensraum enthält Befehle und Variablen
+namespace eval people {
+ namespace eval person1 {
+ variable name Neo
+ }
+}
+
+
+#Der volle Name einer Variablen beihaltet den/die umschließenden
+# Namensraum/Namensräume begrenzt durch zwei Doppelpunkte.
+set greeting "Hello $people::person1::name"
+```
+
+```tcl
+################################################################################
+## 3. Einige Notizen
+################################################################################
+
+# Jede weitere Funktion ist über Befehle implementiert. Von nun an kommt keine
+# neue Syntax hinzu. Alles weitere das es über Tcl zu lernen gibt ist das
+# Verhalten individueller Befehle und die bedeutung ihrer Argumente.
+
+
+# Um einen Interpreter zu bekommen mit dem man nichts mehr machen kann, lösche
+# einfach den globalen Namensraum. Das ist nicht sehr sinnvoll, zeigt aber die
+# Natur von Tcl.
+namespace delete ::
+
+
+# Wegen des Verhaltens der Namens-Auflösung ist es sicherer den "variable"
+# Befehl zu verwenden um in einem Namensraum einen Wert zu deklarieren oder
+# zuzuweisen. Wenn eine Variable mit dem namen "name" bereits im globalen
+# Namensraum existiert, bewirkt der "set" Befehl das der globalen Variable ein
+# Wert zugewiesen wird, anstatt eine Variable im lokalen Namensraum zu erzeugen
+namespace eval people {
+ namespace eval person1 {
+ variable name Neo
+ }
+}
+
+
+# Es kann immer der vollständige Name einer Variable verwendet werden, falls
+# gewünscht.
+set people::person1::name Neo
+
+
+
+################################################################################
+## 4. Befehle
+################################################################################
+
+# Berechnungen werde mit dem "expr" Befehl durchgeführt.
+set a 3
+set b 4
+set c [expr {$a + $b}]
+
+# Since "expr" performs variable substitution on its own, brace the expression
+# to prevent Tcl from performing variable substitution first. See
+
+# Da der "expr" Befehl eigene Variablen-Substitutionen durchführt, setze den
+# zu berechnenden Ausdruck in Eckige-Klammern. Das hindert Tcl daran Variablen-
+# Substitutionen durchzuführen. Für Details siehe:
+# "http://wiki.tcl.tk/Brace%20your%20#%20expr-essions"
+
+
+# Der "expr" Befehl versteht Variablen- und Befehls-Substitutionen
+set c [expr {$a + [set b]}]
+
+
+# Der "expr" Befehl stellt Mathematische-Funktionen zur Verfügung.
+set c [expr {pow($a,$b)}]
+
+
+# Mathematische Operatoren sind als Befehle auch im Namensraum
+# ::tcl::mathop verfügbar.
+::tcl::mathop::+ 5 3
+
+# Befehle können aus anderen Namensräumen importiert werden.
+namespace import ::tcl::mathop::+
+set result [+ 5 3]
+
+
+# Neu Befehle werden mit dem "proc" Befehl gebildet.
+proc greet name {
+ return "Hello, $name!"
+}
+
+#Es können mehrere Parameter spezifiziert werden.
+proc greet {greeting name} {
+ return "$greeting, $name!"
+}
+
+
+# Wie bereits erwähnt, geschwungene Klammern erzeugen keinen Code-Block.
+# Jeder Wert, sogar das dritte Argument für den "proc" Befehl ist eine
+# Zeichenkette. Der vorherige Befehl kann daher auch ohne
+# geschwungene Klammern geschrieben werden:
+proc greet greeting\ name return\ \"Hello,\ \$name!
+
+
+
+# Wenn der letzte Parameter der literale Wert "args" ist, sammelt dieser Wert
+# alle übrigen Argumente des Befehls ein wenn dieser aufgerufen wird.
+proc fold {cmd args} {
+ set res 0
+ foreach arg $args {
+ set res [$cmd $res $arg]
+ }
+}
+fold ::tcl::mathop::* 5 3 3 ;# -> 45
+
+
+# Bedingte Ausführung ist auch als Befehl implementiert
+if {3 > 4} {
+ puts {This will never happen}
+} elseif {4 > 4} {
+ puts {This will also never happen}
+} else {
+ puts {This will always happen}
+}
+
+
+# Auch Schleifen sind Befehle. Das erste, zweite und dritte Argument des "for"
+# Befehls wird als mathematischer Ausdruck behandelt.
+for {set i 0} {$i < 10} {incr i} {
+ set res [expr {$res + $i}]
+}
+
+
+# Das erste Argument des "while" Befehls wird auch als mathematischer Ausdruck
+# behandelt.
+set i 0
+while {$i < 10} {
+ incr i 2
+}
+
+
+# Eine Liste ist eine speziell formatierte Zeichenkette. Im einfachsten Fall
+# genügen Leerzeichen als Trennzeichen zwischen den einzelnen Werten.
+set amounts 10\ 33\ 18
+set amount [lindex $amounts 1]
+
+
+# Geschwungene Klammern und Backslashes können verwendet werden um komplexe
+# Werte in einer Liste zu formatieren. Eine Liste sieht aus wie ein Skript,
+# allerdings verlieren verlieren Zeilenumbrüche und Doppelüunkte ihre
+# besondere Bedeutung. Diese Funktionalität macht Tcl homoikonisch. Die
+# folgende Liste enhtält drei Elemente.
+set values {
+
+ one\ two
+
+ {three four}
+
+ five\{six
+
+}
+
+
+# Da Listen auch Zeichenketten sind, kann man Zeichenketten-Operationen auf
+# ihnen anwenden. Allerdings mit dem Risiko die Formatierung der Liste zu
+# beschädigen.
+set values {one two three four}
+set values [string map {two \{} $values] ;# $values is no-longer a \
+ properly-formatted listwell-formed list
+
+
+# Der sicherste Weg korrekt formatierte Liste zu erzeugen, ist den "list"
+# Befehl zu verwenden.
+set values [list one \{ three four]
+lappend values { } ;# Ein Leerzeichen als Element der Liste hinzufügen
+
+
+# Mit "eval" können Werte als Skripts evaluiert weden.
+eval {
+ set name Neo
+ set greeting "Hello, $name"
+}
+
+
+# Eine Liste kann immer an "eval" übergeben werden, solange die Liste einen
+# einzigen Befehl entält.
+eval {set name Neo}
+eval [list set greeting "Hello, $name"]
+
+
+# Daher: Wenn "eval" verwendet wird, verwende [list] um den gewünschten Befehl
+# aufzubauen.
+set command {set name}
+lappend command {Archibald Sorbisol}
+eval $command
+
+
+# Es ist ein häufiger Fehler die Listen funktionen beim Aufbauen von Listen
+# nicht zu verwenden.
+set command {set name}
+append command { Archibald Sorbisol}
+eval $command ;# Hier passiert eine Fehler, denn der "set" Befehl hat nun zu \
+ viele Argumente {set name Archibald Sorbisol}
+
+
+# Dieser Fehler kann auch leicht beim "subst" Befehl passieren.
+set replacement {Archibald Sorbisol}
+set command {set name $replacement}
+set command [subst $command]
+eval $command ;# The same error as before: too many arguments to "set" in \
+ {set name Archibald Sorbisol}
+
+
+# Die korrekte Vorgangsweise ist es den substituierten Wert mit dem "list"
+# Befehl zu formatieren.
+set replacement [list {Archibald Sorbisol}]
+set command {set name $replacement}
+set command [subst $command]
+eval $command
+
+
+# Der "list" Befehl wird sehr häufig verwendet um Werte zu formatieren die
+# in Tcl Skript Vorlagen substituiert werden. Es gibt dazu viele Beispiele,
+# siehe unterhalb.
+
+
+# Der "apply" Befehl evaluiert eine Zeichenkette als Befehl.
+set cmd {{greeting name} {
+ return "$greeting, $name!"
+}}
+apply $cmd Whaddup Neo
+
+
+# Der "uplevel" Befehl evaluiert ein Skript in einem höher liegenden
+Gültigkeitsbereich.
+proc greet {} {
+ uplevel {puts "$greeting, $name"}
+}
+
+proc set_double {varname value} {
+ if {[string is double $value]} {
+ uplevel [list variable $varname $value]
+ } else {
+ error [list {not a double} $value]
+ }
+}
+
+
+# Der "upvar" Befehl verknüpft eine Variable im aktuellen Gültigkeitsbereich
+# mit einer Variable in einem höher liegenden Gültigkeitsbereich.
+proc set_double {varname value} {
+ if {[string is double $value]} {
+ upvar 1 $varname var
+ set var $value
+ } else {
+ error [list {not a double} $value]
+ }
+}
+
+
+# Werde den eingebauten "while" Befehl los.
+rename ::while {}
+
+
+# Definieren einen neuen "while" Befehl mit hilfe des "proc" Befehls.
+# Ausführlichere Fehler-Behandlung wird dem Leser als Übung überlassen.
+proc while {condition script} {
+ if {[uplevel 1 [list expr $condition]]} {
+ uplevel 1 $script
+ tailcall [namespace which while] $condition $script
+ }
+}
+
+
+# Der "coroutine" Befehl erzeugt einen separaten Call-Stack, zusammen mit einem
+# Befehl um diesem Call-Stack zu verwenden. Der "yield" Befehl unterbricht
+# die Ausführung des aktuellen Call-Stacks.
+proc countdown {} {
+ #send something back to the initial "coroutine" command
+ yield
+
+ set count 3
+ while {$count > 1} {
+ yield [incr count -1]
+ }
+ return 0
+}
+coroutine countdown1 countdown
+coroutine countdown2 countdown
+puts [countdown 1] ;# -> 2
+puts [countdown 2] ;# -> 2
+puts [countdown 1] ;# -> 1
+puts [countdown 1] ;# -> 0
+puts [coundown 1] ;# -> invalid command name "countdown1"
+puts [countdown 2] ;# -> 1
+
+
+```
+
+## Referenzen
+
+[Official Tcl Documentation](http://www.tcl.tk/man/tcl/)
+
+[Tcl Wiki](http://wiki.tcl.tk)
+
+[Tcl Subreddit](http://www.reddit.com/r/Tcl)
diff --git a/edn.html.markdown b/edn.html.markdown
index d0bdddfc..ca04df89 100644
--- a/edn.html.markdown
+++ b/edn.html.markdown
@@ -14,7 +14,7 @@ Clojure, there are implementations of EDN for many other languages.
The main benefit of EDN over JSON and YAML is that it is extensible. We
will see how it is extended later on.
-```Clojure
+```clojure
; Comments start with a semicolon.
; Anything after the semicolon is ignored.
diff --git a/elixir.html.markdown b/elixir.html.markdown
index 720e080c..eb708576 100644
--- a/elixir.html.markdown
+++ b/elixir.html.markdown
@@ -170,7 +170,7 @@ case {:one, :two} do
{:four, :five} ->
"This won't match"
{:one, x} ->
- "This will match and bind `x` to `:two`"
+ "This will match and bind `x` to `:two` in this clause"
_ ->
"This will match any value"
end
@@ -411,7 +411,7 @@ self() #=> #PID<0.27.0>
## References
-* [Getting started guide](http://elixir-lang.org/getting_started/1.html) from [elixir webpage](http://elixir-lang.org)
+* [Getting started guide](http://elixir-lang.org/getting-started/introduction.html) from the [Elixir website](http://elixir-lang.org)
* [Elixir Documentation](http://elixir-lang.org/docs/master/)
* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) by Dave Thomas
* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf)
diff --git a/elm.html.markdown b/elm.html.markdown
new file mode 100644
index 00000000..fa10671f
--- /dev/null
+++ b/elm.html.markdown
@@ -0,0 +1,367 @@
+---
+language: Elm
+contributors:
+ - ["Max Goldstein", "http://maxgoldste.in/"]
+---
+
+Elm is a functional reactive programming language that compiles to (client-side)
+JavaScript. Elm is statically typed, meaning that the compiler catches most
+errors immediately and provides a clear and understandable error message. Elm is
+great for designing user interfaces and games for the web.
+
+
+```haskell
+-- Single line comments start with two dashes.
+{- Multiline comments can be enclosed in a block like this.
+{- They can be nested. -}
+-}
+
+{-- The Basics --}
+
+-- Arithmetic
+1 + 1 -- 2
+8 - 1 -- 7
+10 * 2 -- 20
+
+-- Every number literal without a decimal point can be either an Int or a Float.
+33 / 2 -- 16.5 with floating point division
+33 // 2 -- 16 with integer division
+
+-- Exponents
+5 ^ 2 -- 25
+
+-- Booleans
+not True -- False
+not False -- True
+1 == 1 -- True
+1 /= 1 -- False
+1 < 10 -- True
+
+-- Strings and characters
+"This is a string because it uses double quotes."
+'a' -- characters in single quotes
+
+-- Strings can be appended.
+"Hello " ++ "world!" -- "Hello world!"
+
+{-- Lists, Tuples, and Records --}
+
+-- Every element in a list must have the same type.
+["the", "quick", "brown", "fox"]
+[1, 2, 3, 4, 5]
+-- The second example can also be written with two dots.
+[1..5]
+
+-- Append lists just like strings.
+[1..5] ++ [6..10] == [1..10] -- True
+
+-- To add one item, use "cons".
+0 :: [1..5] -- [0, 1, 2, 3, 4, 5]
+
+-- The head and tail of a list are returned as a Maybe. Instead of checking
+-- every value to see if it's null, you deal with missing values explicitly.
+List.head [1..5] -- Just 1
+List.tail [1..5] -- Just [2, 3, 4, 5]
+List.head [] -- Nothing
+-- List.functionName means the function lives in the List module.
+
+-- Every element in a tuple can be a different type, but a tuple has a
+-- fixed length.
+("elm", 42)
+
+-- Access the elements of a pair with the first and second functions.
+-- (This is a shortcut; we'll come to the "real way" in a bit.)
+fst ("elm", 42) -- "elm"
+snd ("elm", 42) -- 42
+
+-- The empty tuple, or "unit", is sometimes used as a placeholder.
+-- It is the only value of its type, also called "Unit".
+()
+
+-- Records are like tuples but the fields have names. The order of fields
+-- doesn't matter. Notice that record values use equals signs, not colons.
+{ x = 3, y = 7 }
+
+-- Access a field with a dot and the field name.
+{ x = 3, y = 7 }.x -- 3
+
+-- Or with an accessor function, which is a dot and the field name on its own.
+.y { x = 3, y = 7 } -- 7
+
+-- Update the fields of a record. (It must have the fields already.)
+{ person |
+ name = "George" }
+
+-- Update multiple fields at once, using the current values.
+{ particle |
+ position = particle.position + particle.velocity,
+ velocity = particle.velocity + particle.acceleration }
+
+{-- Control Flow --}
+
+-- If statements always have an else, and the branches must be the same type.
+if powerLevel > 9000 then
+ "WHOA!"
+else
+ "meh"
+
+-- If statements can be chained.
+if n < 0 then
+ "n is negative"
+else if n > 0 then
+ "n is positive"
+else
+ "n is zero"
+
+-- Use case statements to pattern match on different possibilities.
+case aList of
+ [] -> "matches the empty list"
+ [x]-> "matches a list of exactly one item, " ++ toString x
+ x::xs -> "matches a list of at least one item whose head is " ++ toString x
+-- Pattern matches go in order. If we put [x] last, it would never match because
+-- x::xs also matches (xs would be the empty list). Matches do not "fall through".
+-- The compiler will alert you to missing or extra cases.
+
+-- Pattern match on a Maybe.
+case List.head aList of
+ Just x -> "The head is " ++ toString x
+ Nothing -> "The list was empty."
+
+{-- Functions --}
+
+-- Elm's syntax for functions is very minimal, relying mostly on whitespace
+-- rather than parentheses and curly brackets. There is no "return" keyword.
+
+-- Define a function with its name, arguments, an equals sign, and the body.
+multiply a b =
+ a * b
+
+-- Apply (call) a function by passing it arguments (no commas necessary).
+multiply 7 6 -- 42
+
+-- Partially apply a function by passing only some of its arguments.
+-- Then give that function a new name.
+double =
+ multiply 2
+
+-- Constants are similar, except there are no arguments.
+answer =
+ 42
+
+-- Pass functions as arguments to other functions.
+List.map double [1..4] -- [2, 4, 6, 8]
+
+-- Or write an anonymous function.
+List.map (\a -> a * 2) [1..4] -- [2, 4, 6, 8]
+
+-- You can pattern match in function definitions when there's only one case.
+-- This function takes one tuple rather than two arguments.
+area (width, height) =
+ width * height
+
+area (6, 7) -- 42
+
+-- Use curly brackets to pattern match record field names.
+-- Use let to define intermediate values.
+volume {width, height, depth} =
+ let
+ area = width * height
+ in
+ area * depth
+
+volume { width = 3, height = 2, depth = 7 } -- 42
+
+-- Functions can be recursive.
+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]
+
+-- Another recursive function (use List.length in real code).
+listLength aList =
+ case aList of
+ [] -> 0
+ x::xs -> 1 + listLength xs
+
+-- Function calls happen before any infix operator. Parens indicate precedence.
+cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1
+-- First degrees is applied to 30, then the result is passed to the trig
+-- functions, which is then squared, and the addition happens last.
+
+{-- Types and Type Annotations --}
+
+-- The compiler will infer the type of every value in your program.
+-- Types are always uppercase. Read x : T as "x has type T".
+-- Some common types, which you might see in Elm's REPL.
+5 : Int
+6.7 : Float
+"hello" : String
+True : Bool
+
+-- Functions have types too. Read -> as "goes to". Think of the rightmost type
+-- as the type of the return value, and the others as arguments.
+not : Bool -> Bool
+round : Float -> Int
+
+-- When you define a value, it's good practice to write its type above it.
+-- The annotation is a form of documentation, which is verified by the compiler.
+double : Int -> Int
+double x = x * 2
+
+-- Function arguments are passed in parentheses.
+-- Lowercase types are type variables: they can be any type, as long as each
+-- call is consistent.
+List.map : (a -> b) -> List a -> List b
+-- "List dot map has type a-goes-to-b, goes to list of a, goes to list of b."
+
+-- There are three special lowercase types: number, comparable, and appendable.
+-- Numbers allow you to use arithmetic on Ints and Floats.
+-- Comparable allows you to order numbers and strings, like a < b.
+-- Appendable things can be combined with a ++ b.
+
+{-- Type Aliases and Union Types --}
+
+-- When you write a record or tuple, its type already exists.
+-- (Notice that record types use colon and record values use equals.)
+origin : { x : Float, y : Float, z : Float }
+origin =
+ { x = 0, y = 0, z = 0 }
+
+-- You can give existing types a nice name with a type alias.
+type alias Point3D =
+ { x : Float, y : Float, z : Float }
+
+-- If you alias a record, you can use the name as a constructor function.
+otherOrigin : Point3D
+otherOrigin =
+ Point3D 0 0 0
+
+-- But it's still the same type, so you can equate them.
+origin == otherOrigin -- True
+
+-- By contrast, defining a union type creates a type that didn't exist before.
+-- A union type is so called because it can be one of many possibilities.
+-- Each of the possibilities is represented as a "tag".
+type Direction =
+ North | South | East | West
+
+-- Tags can carry other values of known type. This can work recursively.
+type IntTree =
+ Leaf | Node Int IntTree IntTree
+-- "Leaf" and "Node" are the tags. Everything following a tag is a type.
+
+-- Tags can be used as values or functions.
+root : IntTree
+root =
+ Node 7 Leaf Leaf
+
+-- Union types (and type aliases) can use type variables.
+type Tree a =
+ Leaf | Node a (Tree a) (Tree a)
+-- "The type tree-of-a is a leaf, or a node of a, tree-of-a, and tree-of-a."
+
+-- Pattern match union tags. The uppercase tags will be matched exactly. The
+-- lowercase variables will match anything. Underscore also matches anything,
+-- but signifies that you aren't using it.
+leftmostElement : Tree a -> Maybe a
+leftmostElement tree =
+ case tree of
+ Leaf -> Nothing
+ Node x Leaf _ -> Just x
+ Node _ subtree _ -> leftmostElement subtree
+
+-- That's pretty much it for the language itself. Now let's see how to organize
+-- and run your code.
+
+{-- Modules and Imports --}
+
+-- The core libraries are organized into modules, as are any third-party
+-- libraries you may use. For large projects, you can define your own modules.
+
+-- Put this at the top of the file. If omitted, you're in Main.
+module Name where
+
+-- By default, everything is exported. You can specify exports explicity.
+module Name (MyType, myValue) where
+
+-- One common pattern is to export a union type but not its tags. This is known
+-- as an "opaque type", and is frequently used in libraries.
+
+-- Import code from other modules to use it in this one.
+-- Places Dict in scope, so you can call Dict.insert.
+import Dict
+
+-- Imports the Dict module and the Dict type, so your annotations don't have to
+-- say Dict.Dict. You can still use Dict.insert.
+import Dict exposing (Dict)
+
+-- Rename an import.
+import Graphics.Collage as C
+
+{-- Ports --}
+
+-- A port indicates that you will be communicating with the outside world.
+-- Ports are only allowed in the Main module.
+
+-- An incoming port is just a type signature.
+port clientID : Int
+
+-- An outgoing port has a definition.
+port clientOrders : List String
+port clientOrders = ["Books", "Groceries", "Furniture"]
+
+-- We won't go into the details, but you set up callbacks in JavaScript to send
+-- on incoming ports and receive on outgoing ports.
+
+{-- Command Line Tools --}
+
+-- Compile a file.
+$ elm make MyFile.elm
+
+-- The first time you do this, Elm will install the core libraries and create
+-- elm-package.json, where information about your project is kept.
+
+-- The reactor is a server that compiles and runs your files.
+-- Click the wrench next to file names to enter the time-travelling debugger!
+$ elm reactor
+
+-- Experiment with simple expressions in a Read-Eval-Print Loop.
+$ elm repl
+
+-- Packages are identified by GitHub username and repo name.
+-- Install a new package, and record it in elm-package.json.
+$ elm package install evancz/elm-html
+
+-- See what changed between versions of a package.
+$ elm package diff evancz/elm-html 3.0.0 4.0.2
+-- Elm's package manager enforces semantic versioning, so minor version bumps
+-- will never break your build!
+```
+
+The Elm language is surprisingly small. You can now look through almost any Elm
+source code and have a rough idea of what is going on. However, the possibilities
+for error-resistant and easy-to-refactor code are endless!
+
+Here are some useful resources.
+
+* The [Elm website](http://elm-lang.org/). Includes:
+ * Links to the [installers](http://elm-lang.org/install)
+ * [Documentation guides](http://elm-lang.org/docs), including the [syntax reference](http://elm-lang.org/docs/syntax)
+ * Lots of helpful [examples](http://elm-lang.org/examples)
+
+* Documentation for [Elm's core libraries](http://package.elm-lang.org/packages/elm-lang/core/latest/). Take note of:
+ * [Basics](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics), which is imported by default
+ * [Maybe](http://package.elm-lang.org/packages/elm-lang/core/latest/Maybe) and its cousin [Result](http://package.elm-lang.org/packages/elm-lang/core/latest/Result), commonly used for missing values or error handling
+ * Data structures like [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), and [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set)
+ * JSON [encoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Encode) and [decoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode)
+
+* [The Elm Architecture](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). An essay by Elm's creator with examples on how to organize code into components.
+
+* The [Elm mailing list](https://groups.google.com/forum/#!forum/elm-discuss). Everyone is friendly and helpful.
+
+* [Scope in Elm](https://github.com/elm-guides/elm-for-js/blob/master/Scope.md#scope-in-elm) and [How to Read a Type Annotation](https://github.com/elm-guides/elm-for-js/blob/master/How%20to%20Read%20a%20Type%20Annotation.md#how-to-read-a-type-annotation). More community guides on the basics of Elm, written for JavaScript developers.
+
+Go out and write some Elm!
diff --git a/es-es/brainfuck-es.html.markdown b/es-es/bf-es.html.markdown
index 550511da..c93b8c3a 100644
--- a/es-es/brainfuck-es.html.markdown
+++ b/es-es/bf-es.html.markdown
@@ -1,5 +1,5 @@
---
-language: brainfuck
+language: bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]
diff --git a/es-es/c++-es.html.markdown b/es-es/c++-es.html.markdown
index bcc775e5..07c8bc03 100644
--- a/es-es/c++-es.html.markdown
+++ b/es-es/c++-es.html.markdown
@@ -1,6 +1,6 @@
---
language: c++
-filename: learncpp.cpp
+filename: learncpp-es.cpp
contributors:
- ["Steven Basart", "http://github.com/xksteven"]
- ["Matt Kline", "https://github.com/mrkline"]
diff --git a/es-es/forth-es.html.markdown b/es-es/forth-es.html.markdown
new file mode 100644
index 00000000..edc5d38c
--- /dev/null
+++ b/es-es/forth-es.html.markdown
@@ -0,0 +1,226 @@
+---
+language: forth
+contributors:
+ - ["Horse M.D.", "http://github.com/HorseMD/"]
+translators:
+ - ["Zach Larsen", "http://zachariahlarsen.com/"]
+lang: es-es
+filename: learnforth-es.fs
+---
+
+Forth fue criado por Charles H. Moore en los 70s. Forth es un lenguaje imperativo, basado en pila y entorno de programación, siendo usado en proyectos como Open Firmware. También esta usado por NASA.
+
+Nota: Este articulo enfoca predominantemente en la Gforth implementación de Forth, pero casi todo
+de lo que esta escrito aquí debe funcionar en otro sitio.
+
+```
+\ Este es un comentario
+( Este es un comentario también pero solo esta usado cuando definiendo palabras. )
+
+\ --------------------------------- Precursor ----------------------------------
+
+\ Todo programación en Forth se hace manipulando el parámetro pila (mas
+\ común se refiere como "el pila").
+5 2 3 56 76 23 65 \ ok
+
+\ estos números se añadieron al pila desde izquierda a derecho.
+.s \ <7> 5 2 3 56 76 23 65 ok
+
+\ En Forth, todo es o una palabra o un numero.
+
+\ ------------------------------ Básico Aritmética ------------------------------
+
+\ Aritmética (de hecho casi todas palabras que requieren datos) funciona manipulando datos
+\ en el pila.
+5 4 + \ ok
+
+\ `.` saca lo alto resulto desde el pila:
+. \ 9 ok
+
+\ Mas ejemplos de aritmética:
+6 7 * . \ 42 ok
+1360 23 - . \ 1337 ok
+12 12 / . \ 1 ok
+13 2 mod . \ 1 ok
+
+99 negate . \ -99 ok
+-99 abs . \ 99 ok
+52 23 max . \ 52 ok
+52 23 min . \ 23 ok
+
+\ ----------------------------- Pila Manipulación -----------------------------
+
+\ Naturalmente, cuando trabajaremos con el pila, querremos algunos metidos útiles:
+
+3 dup - \ duplicar el primero articulo (1ra ahora igual a 2da): 3 - 3
+2 5 swap / \ intercambiar la primera con la segunda elemento: 5 / 2
+6 4 5 rot .s \ rotar los tres primero elementos: 4 5 6
+4 0 drop 2 / \ sacar el primero articulo (no imprima a la pantalla): 4 / 2
+1 2 3 nip .s \ sacar el segundo articulo (similar a drop): 1 3
+
+\ ---------------------- Mas Avanzado Pila Manipulación ----------------------
+
+1 2 3 4 tuck \ duplicar el primero articulo en el segundo hueco: 1 2 4 3 4 ok
+1 2 3 4 over \ duplicar el segundo articulo a la primera del pila: 1 2 3 4 3 ok
+1 2 3 4 2 roll \ *mover* el articulo en este posición a la primera del pila: 1 3 4 2 ok
+1 2 3 4 2 pick \ *duplicar* el articulo en este posición a la primera del pila: 1 2 3 4 2 ok
+
+\ Cuando refiere a pila indices, ellos son basado en cero.
+
+\ ------------------------------ Creando Palabras --------------------------------
+
+\ La `:` palabra hace que Forth entra modo de compilar hasta que se ve la `;` palabra.
+: cuadrado ( n -- n ) dup * ; \ ok
+5 cuadrado . \ 25 ok
+
+\ Podemos ver lo que hace una palabra también.:
+see cuadrado \ : cuadrado dup * ; ok
+
+\ -------------------------------- Condicionales --------------------------------
+
+\ -1 == cierto, 0 == falso. No obstante, valores que no son cero es usualmente tratado como
+\ siendo cierto:
+42 42 = \ -1 ok
+12 53 = \ 0 ok
+
+\ `if` es una palabra que solamente compila. `if` <cosas para hacer> `then` <los de mas del programa>.
+: ?>64 ( n -- n ) dup 64 > if ." Mas que 64!" then ; \ ok
+100 ?>64 \ Mas que 64! ok
+
+\ Else:
+: ?>64 ( n -- n ) dup 64 > if ." Mas que 64!" else ." Menos que 64!" then ;
+100 ?>64 \ Mas que 64! ok
+20 ?>64 \ Menos que 64! ok
+
+\ ------------------------------------ Loops -----------------------------------
+
+\ `do` también es una palabra que solamente compila.
+: miloop ( -- ) 5 0 do cr ." Hola!" loop ; \ ok
+miloop
+\ Hola!
+\ Hola!
+\ Hola!
+\ Hola!
+\ Hola! ok
+
+\ `do` espera dos números en el pila: el último numero y el primero numero.
+
+\ Podemos recibir el valor del indice mientras damos vuelta con `i`:
+: uno-a-12 ( -- ) 12 0 do i . loop ; \ ok
+uno-a-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok
+
+\ `?do` funciona similarmente, pero salta el loop si el último y primero
+\ números son iguales.
+: cuadrados ( n -- ) 0 ?do i cuadrado . loop ; \ ok
+10 cuadrado \ 0 1 4 9 16 25 36 49 64 81 ok
+
+\ cambiar el "paso" con `+loop`:
+: treces ( n n -- ) ?do i . 3 +loop ; \ ok
+15 0 treces \ 0 3 6 9 12 ok
+
+\ Indefinido loops empiezan `begin` <cosas para hacer> <bandera> `until`:
+: death ( -- ) begin ." Ya hemos llegado?" 0 until ; \ ok
+
+\ ---------------------------- Variables y Memoria ----------------------------
+
+\ Use `variable` declarar `edad` ser un variable.
+variable edad \ ok
+
+\ Ahora escribimos 21 a edad con la palabra `!`.
+21 edad ! \ ok
+
+\ Por fin podemos imprimir nuestro variable usando la "leer" palabra `@`, que agregue el
+\ valor a la pila, or usa `?` que lee y imprime todo juntos.
+edad @ . \ 21 ok
+edad ? \ 21 ok
+
+\ Constantes son muy similar, pero no nos importa los direcciones de memoria:
+100 constant PUNTA-QUE-AQUA-HIERVA \ ok
+PUNTA-QUE-AQUA-HIERVA . \ 100 ok
+
+\ ----------------------------------- Arrays -----------------------------------
+
+\ Creando arrays es similar a variables, pero necesitamos alocar mas
+\ memoria a ellos.
+
+\ Puede usar `2 cells allot` para crear un array que es sea 3 cédulas de tamaño:
+variable minumeros 2 cells allot \ ok
+
+\ Inicializar todos los valores a 0
+minumeros 3 cells erase \ ok
+
+\ Alternativamente podemos usar `fill`:
+minumeros 3 cells 0 fill
+
+\ o podemos saltar todo arriba y inicializar con valores específicos:
+create minumeros 64 , 9001 , 1337 , \ ok (el último `,` es importante!)
+
+\ ...que es equivalente a:
+
+\ Manualmente escribiendo valores a cada indice:
+64 minumeros 0 cells + ! \ ok
+9001 minumeros 1 cells + ! \ ok
+1337 minumeros 2 cells + ! \ ok
+
+\ Leyendo valores en particular array indices:
+0 cells minumeros + ? \ 64 ok
+1 cells minumeros + ? \ 9001 ok
+
+\ Podemos simplificar un poco cuando hacemos una palabra que ayuda cuando manipulando arrays:
+: de-arr ( n n -- n ) cells + ; \ ok
+minumeros 2 de-arr ? \ 1337 ok
+
+\ Que podemos usar cuando escribimos también:
+20 minumeros 1 de-arr ! \ ok
+minumeros 1 de-arr ? \ 20 ok
+
+\ ------------------------------ El Pila de Regreso ------------------------------
+
+\ El pila de regreso se usa para retener punteros a cosas cuando palabras están
+\ ejecutando otras palabras como loops.
+
+\ Ya hemos visto un uso de esto: `i`, que duplica el primero del pila
+\ de regreso. `i` es equivalente a `r@`.
+: miloop ( -- ) 5 0 do r@ . loop ; \ ok
+
+\ También como leyendo, podemos agregar al pila de regreso y sacarlo:
+5 6 4 >r swap r> .s \ 6 5 4 ok
+
+\ NOTA: Porque Forth usa el pila de regreso por punteros de palabras, `>r` debe
+\ siempre ser seguido por un `r>`.
+
+\ ------------------------- Flotante Punto Operaciones --------------------------
+
+\ La mayoría Forths evitan el uso de flotante punto operaciones.
+8.3e 0.8e f+ f. \ 9.1 ok
+
+\ Usualmente agregamos al frente palabras con 'f' cuando usando flotantes:
+variable miflotantevar \ ok
+4.4e miflotantevar f! \ ok
+miflotantevar f@ f. \ 4.4 ok
+
+\ --------------------------------- Notas al Final --------------------------------
+
+\ Usando una palabra que no existe vaciara el pila. No obstante, también hay una palabra
+\ específicamente por esto:
+clearstack
+
+\ vaciar la pantalla:
+page
+
+\ Cargando Forth archivos:
+\ s" archivodeforth.fs" included
+
+\ Puede listar cada palabra en el diccionario de Forth (pero es una lista gigante!):
+\ words
+
+\ Terminando Gforth:
+\ bye
+
+```
+
+##Listo Para Mas?
+
+* [Starting Forth](http://www.forth.com/starting-forth/)
+* [Simple Forth](http://www.murphywong.net/hello/simple.htm)
+* [Thinking Forth](http://thinking-forth.sourceforge.net/)
diff --git a/es-es/hack-es.html.markdown b/es-es/hack-es.html.markdown
new file mode 100644
index 00000000..1059117a
--- /dev/null
+++ b/es-es/hack-es.html.markdown
@@ -0,0 +1,307 @@
+---
+language: Hack
+contributors:
+ - ["Stephen Holdaway", "https://github.com/stecman"]
+ - ["David Lima", "https://github.com/davelima"]
+translators:
+ - ["César Suárez", "https://github.com/csuarez"]
+lang: es-es
+filename: learnhack-es.hh
+---
+
+Hack es un superconjunto de PHP que se ejecuta en una máquina virtual llamada HHVM. Hack es casi totalmente compatible con código PHP ya existente y añade varias características típicas de los lenguajes de programación estáticamente tipados.
+
+En este artículo sólo se cubren las características específicas de Hack. Los detalles sobre la sintaxis de PHP están en el [artículo sobre PHP](http://learnxinyminutes.com/docs/php/) de esta misma web.
+
+```php
+<?hh
+
+// La sintaxis de Hack sólo se habilita para los ficheros que comienzan con
+// un marcador <?hh. Estos marcadores no pueden intercalarse con código HTML,
+// tal como se puede hacer con <?php. Al usar el marcador "<?hh //strict" el
+// comprobador de tipado en modo estricto se pone en modo estricto.
+
+// Indicando el tipo de parámetros escalares
+function repeat(string $word, int $count)
+{
+ $word = trim($word);
+ return str_repeat($word . ' ', $count);
+}
+
+// Indicando el tipo que devuelve una función
+function add(...$numbers) : int
+{
+ return array_sum($numbers);
+}
+
+// Las funciones que no devuelven nada usan el tipo "void"
+function truncate(resource $handle) : void
+{
+ // ...
+}
+
+// Al determinar un tipo, hay que indicar explícitamente si permite el valor
+// NULL
+function identity(?string $stringOrNull) : ?string
+{
+ return $stringOrNull;
+}
+
+// Se puede especificar el tipo de las propiedades de una clase
+class TypeHintedProperties
+{
+ public ?string $name;
+
+ protected int $id;
+
+ private float $score = 100.0;
+
+ // El comprobador de tipos de Hack fuerza que las propiedades tipadas
+ // tengan un valor por defecto o que estén asignadas en el constructor
+ public function __construct(int $id)
+ {
+ $this->id = $id;
+ }
+}
+
+
+// Funciones anónimas concisas (lambdas)
+$multiplier = 5;
+array_map($y ==> $y * $multiplier, [1, 2, 3]);
+
+
+// Genéricos
+class Box<T>
+{
+ protected T $data;
+
+ public function __construct(T $data) {
+ $this->data = $data;
+ }
+
+ public function getData(): T {
+ return $this->data;
+ }
+}
+
+function openBox(Box<int> $box) : int
+{
+ return $box->getData();
+}
+
+
+// Shapes
+//
+// Hack añade el concepto de shape para definir estructuras similares a
+// vectores, pero con un conjunto de claves garantizado y tipado
+type Point2D = shape('x' => int, 'y' => int);
+
+function distance(Point2D $a, Point2D $b) : float
+{
+ return sqrt(pow($b['x'] - $a['x'], 2) + pow($b['y'] - $a['y'], 2));
+}
+
+distance(
+ shape('x' => -1, 'y' => 5),
+ shape('x' => 2, 'y' => 50)
+);
+
+
+// Alias de tipos
+//
+// Hack permite crear alias para hacer que los tipos complejos sean más legibles
+newtype VectorArray = array<int, Vector<int>>;
+
+// Una tupla que contiene dos enteros
+newtype Point = (int, int);
+
+function addPoints(Point $p1, Point $p2) : Point
+{
+ return tuple($p1[0] + $p2[0], $p1[1] + $p2[1]);
+}
+
+addPoints(
+ tuple(1, 2),
+ tuple(5, 6)
+);
+
+
+// Enumerados de primera clase
+enum RoadType : int
+{
+ Road = 0;
+ Street = 1;
+ Avenue = 2;
+ Boulevard = 3;
+}
+
+function getRoadType() : RoadType
+{
+ return RoadType::Avenue;
+}
+
+
+// Promoción de argumentos en constructores
+//
+// Para evitar repetir una y otra vez la definición de constructores que
+// sólo asignan propiedades, Hack añade una sintaxis concisa para definir
+// propiedades junto al constructor.
+class ArgumentPromotion
+{
+ public function __construct(public string $name,
+ protected int $age,
+ private bool $isAwesome) {}
+}
+
+class WithoutArgumentPromotion
+{
+ public string $name;
+
+ protected int $age;
+
+ private bool $isAwesome;
+
+ public function __construct(string $name, int $age, bool $isAwesome)
+ {
+ $this->name = $name;
+ $this->age = $age;
+ $this->isAwesome = $isAwesome;
+ }
+}
+
+
+// Multitarea cooperativa
+//
+// "async" y "await" son dos palabras claves nuevas para realizar multi-tarea.
+// Esto no implica que se usen hilos, sólo permiten transferir el control de la
+// ejecución.
+{
+ for ($i = $start; $i <= $end; $i++) {
+ echo "$i ";
+
+ // Da a otras tareas la oportunidad de hacer algo
+ await RescheduleWaitHandle::create(RescheduleWaitHandle::QUEUE_DEFAULT, 0);
+ }
+}
+
+// Esto imprime "1 4 7 2 5 8 3 6 9"
+AwaitAllWaitHandle::fromArray([
+ cooperativePrint(1, 3),
+ cooperativePrint(4, 6),
+ cooperativePrint(7, 9)
+])->getWaitHandle()->join();
+
+
+// Atributos
+//
+// Los atributos son una especie de metadatos para funciones. Hack implementa
+// algunos atributos especiales para introducir esta característica.
+
+// El atributo especial __Memoize hace que el resultado de la función se cacheé.
+<<__Memoize>>
+function doExpensiveTask() : ?string
+{
+ return file_get_contents('http://example.com');
+}
+
+// Esta función se va a ejecutar sólo una vez:
+doExpensiveTask();
+doExpensiveTask();
+
+
+// El atributo __ConsistentConstruct indica al comprobador de tipos de Hack que
+// asegure que la signatura de __construct sea la misma para todas las
+// subclases.
+<<__ConsistentConstruct>>
+class ConsistentFoo
+{
+ public function __construct(int $x, float $y)
+ {
+ // ...
+ }
+
+ public function someMethod()
+ {
+ // ...
+ }
+}
+
+class ConsistentBar extends ConsistentFoo
+{
+ public function __construct(int $x, float $y)
+ {
+ // El comprobador de tipos de Hack fuerza que los constructores de
+ // los padres sean llamados.
+ parent::__construct($x, $y);
+
+ // ...
+ }
+
+ // La anotación __Override es un atributo opcional para que el comprobador
+ // de tipos fuerce que ese método esté sobrecargando un método de un padre
+ // o de un trait. Sino, fallará.
+ <<__Override>>
+ public function someMethod()
+ {
+ // ...
+ }
+}
+
+class InvalidFooSubclass extends ConsistentFoo
+{
+ // Este constructor no coincide con el padre y causará el siguiente error:
+ //
+ // "This object is of type ConsistentBaz. It is incompatible with this
+ // object of type ConsistentFoo because some of their methods are
+ // incompatible"
+ public function __construct(float $x)
+ {
+ // ...
+ }
+
+ // Usando la anotación __Override en un método que no sobrecarga nada se
+ // producirá el siguiente error:
+ //
+ // "InvalidFooSubclass::otherMethod() is marked as override; no non-private
+ // parent definition found or overridden parent is defined in non-<?hh
+ // code"
+ <<__Override>>
+ public function otherMethod()
+ {
+ // ...
+ }
+}
+
+
+// Los traits pueden implementar interfaces (PHP no soporta esto).
+interface KittenInterface
+{
+ public function play() : void;
+}
+
+trait CatTrait implements KittenInterface
+{
+ public function play() : void
+ {
+ // ...
+ }
+}
+
+class Samuel
+{
+ use CatTrait;
+}
+
+
+$cat = new Samuel();
+$cat instanceof KittenInterface === true; // True
+
+```
+
+## Más información
+
+Para obtener una explicación más detallada de las características que añade Hack a PHP visita la página de [referencia de Hack](http://docs.hhvm.com/manual/en/hacklangref.php) o la [página oficial de Hack](http://hacklang.org/) para información de caracter más general.
+
+Visita la [página oficial de HHVM](http://hhvm.com/) para ver las instrucciones de su instalación.
+
+También puedes visitar la [sección de características de PHP no soportadas por Hack](http://docs.hhvm.com/manual/en/hack.unsupported.php) para más detalles sobre la retrocompatibilidad entre Hack y PHP.
diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown
index 9ef0c63e..34428f42 100644
--- a/es-es/javascript-es.html.markdown
+++ b/es-es/javascript-es.html.markdown
@@ -23,7 +23,9 @@ Aunque JavaScript no sólo se limita a los navegadores web: Node.js, Un proyecto
[adam@brenecki.id.au](mailto:adam@brenecki.id.au).
```js
-// Los comentarios son como en C. Los comentarios de una sola línea comienzan con //,
+// Los comentarios en JavaScript son los mismos como comentarios en C.
+
+//Los comentarios de una sola línea comienzan con //,
/* y los comentarios multilínea comienzan
y terminan con */
diff --git a/es-es/latex-es.html.markdown b/es-es/latex-es.html.markdown
new file mode 100644
index 00000000..aff3c603
--- /dev/null
+++ b/es-es/latex-es.html.markdown
@@ -0,0 +1,213 @@
+---
+language: latex
+lang: es-es
+contributors:
+ - ["Chaitanya Krishna Ande", "http://icymist.github.io"]
+ - ["Colton Kohnke", "http://github.com/voltnor"]
+ - ["Sricharan Chiruvolu", "http://sricharan.xyz"]
+translators:
+ - ["Mario Pérez", "https://github.com/MarioPerezEsteso"]
+filename: learn-latex-es.tex
+---
+
+```tex
+% Todas las líneas comentadas comienzan con %
+% No existen los comentarios multilínea
+
+% LaTeX NO es un software de procesamiento de texto que cumple con
+% "Lo que ves es lo que tienes" como MS Word u OpenOffice
+
+% Todos los comandos de LaTeX comienzan con una contrabarra (\)
+
+% Los documentos LaTeX comienzan definiendo el tipo de documento que se va a
+% compilar. Algunos tipos de documentos son libros, informes, presentaciones,
+% etc. Las opciones para el documento comienzan en los corchetes []. En este
+% caso, se especifica que queremos utilizar una fuente de tamaño 12pt.
+\documentclass[12pt]{article}
+
+% A continuación, definimos los paquetes que utilizará el documento.
+% Si quieres incluir gráficos, texto coloreado o código fuente de otro lenguaje,
+% debes extender las funciones de LaTeX. Esto se consigue añadiendo paquetes.
+% A continuación se incluirán los paquetes float y caption para figuras.
+\usepackage{caption}
+\usepackage{float}
+
+% También podemos definir otras propiedades en el documento
+\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu}
+\date{\today}
+\title{Learn LaTeX in Y Minutes!}
+
+% Ahora estamos preparados para comenzar el documento
+% Todo lo que se encuentre antes de esta línea se llama "El Preámbulo"
+\begin{document}
+% Si especificamos el autor, fecha y título, LaTeX creará una página como título
+% por nosotros
+\maketitle
+
+% La mayoría de los artículos de investigación tienen un abstract. Es posible
+% utilizar comandos predefinidos para ello.
+% Esto debería aparecer en su orden lógico. Tras el título pero antes de las
+% secciones principales del cuerpo.
+% Este comando está disponible en los tipos de documentos article y report.
+\begin{abstract}
+ Documentación de LaTex escrita en LaTex.
+\end{abstract}
+
+% Los comandos de sección son intuitivos.
+% Todos los títulos de secciones son añadidos automáticamente a la tabla de contenidos.
+\section{Introducción}
+Hola, mi nombre es Mario Pérez y estoy traduciendo este documento para aprender LaTex.
+
+\section{Otra sección}
+Este es el texto de otra sección. Creo que necesitará una subsección.
+
+\subsection{Esto es una subsección} % Las subsecciones también son fáciles.
+Creo que necesitamos otra más.
+
+\subsubsection{Pitágoras}
+Mejor ahora.
+\label{subsec:pitagoras}
+
+% Utilizando el asterisco podemos decirle a LaTeX que no ponga los números de secciones y subsecciones.
+% Esto también funciona con otros comandos de LaTeX.
+\section*{Esto es una sección no numerada}
+¡No todas las secciones tienen que estar numeradas!
+
+\section{Algunas notas}
+LaTeX es generalmente bastante bueno situando el texto donde debe ir. Si una lína \\ necesita \\ ser \\ rota \\ puedes poner \textbackslash\textbackslash en el código fuente. \\
+
+\section{Listas}
+Las listas son de las cosas más fáciles de crear en LaTeX. Necesito ir a comprar mañana, así que vamos a crear una lista de la compra.
+\begin{enumerate} % Esto crea una lista numerada.
+ % \item crea un elemento
+ \item Ensalada.
+ \item 27 sandías.
+ \item Pescado.
+ % podemos incluso sobreescribir el número del ítem usando []
+ \item[cuántos?] Plátanos.
+
+ No es un ítem de la lista, pero sigue siendo parte de la enumeración.
+
+\end{enumerate} % Todos los contextos deben tener un final.
+
+\section{Matemáticas}
+
+Uno de los usos principales de LaTeX es la producción de artículos académicos o técnicos. Normalmente relacionados con la ciencia y las matemáticas. Debido a esto, necesitamos poder añadir símbolos especiales a nuestro artículo.\\
+
+En matemáticas hay muchos símbolos. Más de los que podemos encontrar en un teclado. Flechas o letras por nombrar un par.\\
+
+Algunos símbolos juegan un papel fundamental en muchos artículos de investigación matemática. Así es como se establece que todo Y pertenece a X: $\forall$ x $\in$ X. \\
+He necesitado añadir el signo $ antes de los símbolos. Esto se debe a que cuando escribimos, estamos en modo texto. Sin embargo, los símbolos solo pueden utilizarse en modo matemático, al cual se entra con el signo $.
+% Lo opuesto también se cumple. Una variable también puede ser mostrada en modo matemático, al que también se puede entrar con \[\]
+
+\[a^2 + b^2 = c^2 \]
+
+Mi letra griega favorita es $\xi$. También me gustan $\beta$, $\gamma$ y $\sigma$.
+Todavía no he encontrado una letra griega que LaTeX no conozca.
+
+Los operadores son también una parte esencial de un documento matemático:
+funciones trigonométricas ($\sin$, $\cos$, $\tan$), logaritmos y exponenciales ($\log$, $\exp$), límites ($\lim$), etc. tienen comandos predefinidos en LaTeX.
+
+Vamos a escribir una ecuación para ver cómo se hace: \\
+
+$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$
+
+Las fracciones (numeradores-denominadores) pueden escribirse de la siguiente forma:
+
+% 10 / 7
+$^{10}/_{7}$
+
+% Las fracciones relativamente complejas pueden escribirse como
+% \frac{numerador}{denominador}
+$\frac{n!}{k!(n - k)!}$ \\
+
+También podemos insertar ecuaciones en un contexto de ecuación.
+
+% Mostrar matemáticas en el contexto de ecuaciones
+\begin{equation} % entra en modo matemático
+ c^2 = a^2 + b^2.
+ \label{eq:pitagoras} % para referencias
+\end{equation} % Todos los contextos deben tener un final.
+
+Podemos referenciar nuestra nueva ecuación.
+Ecuación ~\ref{eq:pythagoras} también se conoce como el Teorema de Pitágoras, el cual también se encuentra en la sección ~\ref{subsec:pythagoras}. Muchas cosas pueden ser etiquetadas: figures, equations, sections, etc.
+
+Los sumatorios e integrales son escritor son los comandos sum e int:
+
+% Algunos compiladores de LaTeX se quejarán si hay líneas en blanco
+% En un contexto de ecuación.
+\begin{equation}
+ \sum_{i=0}^{5} f_{i}
+\end{equation}
+\begin{equation}
+ \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
+\end{equation}
+
+\section{Figuras}
+
+Vamos a insertar una figura. Situarla puede ser algo complicado.
+
+\begin{figure}[H] % H aquí establece la situación de la figura.
+ \centering % centra la figura en la página
+ % Inserta una figura escalada por 0.8 el ancho de la página.
+ %\includegraphics[width=0.8\linewidth]{right-triangle.png}
+ % La línea anterior ha sido comentada para poder compilar este archivo. Por favor, usa tu imaginación.
+ \caption{Triángulo con lados $a$, $b$, $c$}
+ \label{fig:right-triangle}
+\end{figure}
+
+\subsection{Tablas}
+También podemos insertar tablas de la misma manera que las figuras.
+
+\begin{table}[H]
+ \caption{Título para la tabla.}
+ % los argumentos en {} describen cómo cada fila va a ser representada.
+ \begin{tabular}{c|cc}
+ Número & Nombre & Apellido \\
+ \hline % una línea horizontal
+ 1 & Biggus & Dickus \\
+ 2 & Monty & Python
+ \end{tabular}
+\end{table}
+
+% \section{Hyperlinks} % En construcción
+
+\section{Haciendo que LaTeX no compile algo (por ejemplo, código fuente)}
+Digamos que queremos incluir código fuente dentro de nuestro documento LaTex. En ese caso, debemos indicarle a LaTeX que no trate de compilarlo y simplemente lo muestre en el documento. Esto lo realizamos en el contexto verbatim.
+
+% Hay otros paquetes para esta misma tarea, pero verbatim es el más básico.
+\begin{verbatim}
+ print("Hola Mundo!")
+ a%b; % Podemos usar los signos % en verbatim.
+ aleatorio = 4; # Número aleatorio
+\end{verbatim}
+
+\section{Compilación}
+
+Ahora mismo te estarás preguntando cómo compilar este fabuloso documento y obtener un documento PDF.\\
+Para obtener el documento final utilizando LaTeX hay que seguir los siguientes pasos:
+ \begin{enumerate}
+ \item Escribe el documento en texto plano.
+ \item Compila el código para producir un PDF.
+ Los pasos de compilación serán algo parecido a esto (en Linux): \\
+ \begin{verbatim}
+ $pdflatex learn-latex.tex learn-latex.pdf
+ \end{verbatim}
+ \end{enumerate}
+
+Un gran número de editores LaTeX combinan ambos pasos para que sea más sencillo obtener el documento.
+
+Escribe toda la información de formato en el paso 1 y con el paso 2 obtendrás el documento que has definido en el paso anterior.
+
+\section{End}
+
+Esto es todo por ahora.
+
+% fin del documento
+\end{document}
+```
+
+## Más información sobre LaTeX
+
+* El wikilibro LaTeX: [https://es.wikibooks.org/wiki/Manual_de_LaTeX](https://es.wikibooks.org/wiki/Manual_de_LaTeX)
+* Un tutorial real: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown
index bc481df7..0505b4cb 100644
--- a/es-es/markdown-es.html.markdown
+++ b/es-es/markdown-es.html.markdown
@@ -57,8 +57,8 @@ __Al igual que este texto.__
**_Al igual que este!_**
*__¡Y este!__*
-<!-- En Github Flavored Markdown, el cual es usado para mostrar archivos
-Markdown en Github, también tenemos: -->
+<!-- En GitHub Flavored Markdown, el cual es usado para mostrar archivos
+Markdown en GitHub, también tenemos: -->
~~Este texto está tachado.~~
@@ -150,7 +150,7 @@ para indentar dentro del código -->
¡John no sabía lo que la función `go_to()` hacía!
-<!-- Con Github Flavored Markdown, puedes usar una sintaxis especial para código -->
+<!-- Con GitHub Flavored Markdown, puedes usar una sintaxis especial para código -->
\`\`\`ruby <!-- quita esas comillas cuando lo hagas, deja sólo ```ruby ! -->
def foobar
@@ -158,7 +158,7 @@ def foobar
end
\`\`\` <!-- aquí también, sin comillas, sólo ``` -->
-<!-- El texto de arriba no necesita indentación, aparte Github usará
+<!-- El texto de arriba no necesita indentación, aparte GitHub usará
resaltará la sintaxis del lenguaje que especifiques después de ``` -->
<!-- Regla horizontal (<hr />) -->
@@ -231,7 +231,7 @@ Quiero escribir *este texto rodeado por asteriscos* pero no quiero que esté en
así que hago esto: \*Este texto está rodeado de asteriscos\*.
<!-- Tablas -->
-<!-- Las tablas sólo están disponibles en Github Flavored Markdown y son un poco pesadas,
+<!-- Las tablas sólo están disponibles en GitHub Flavored Markdown y son un poco pesadas,
pero si de verdad las quieres: -->
| Col1 | Col2 | Col3 |
diff --git a/es-es/objective-c-es.html.markdown b/es-es/objective-c-es.html.markdown
new file mode 100644
index 00000000..bdbce524
--- /dev/null
+++ b/es-es/objective-c-es.html.markdown
@@ -0,0 +1,851 @@
+---
+language: Objective-C
+contributors:
+ - ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
+ - ["Yannick Loriot", "https://github.com/YannickL"]
+ - ["Levi Bostian", "https://github.com/levibostian"]
+translators:
+ - ["David Hsieh", "http://github.com/deivuh"]
+lang: es-es
+filename: LearnObjectiveC-es.m
+---
+Objective C es el lenguaje de programación principal utilizado por Apple para los sistemas operativos OS X y iOS y sus respectivos frameworks, Cocoa y Cocoa Touch.
+Es un lenguaje de programación para propósito general que le agrega al lenguaje de programación C una mensajería estilo "Smalltalk".
+
+
+```objective_c
+// Los comentarios de una sola línea inician con //
+
+/*
+Los comentarios de múltiples líneas se ven así.
+*/
+
+// Importa los encabezados de Foundation con #import
+// Utiliza <> para importar archivos globales (generalmente frameworks)
+// Utiliza "" para importar archivos locales (del proyecto)
+#import <Foundation/Foundation.h>
+#import "MyClass.h"
+
+// Si habilitas módulos para proyectos de iOS >= 7.0 u OS X >= 10.9 en
+// Xcode 5, puedes importarlos de la siguiente manera:
+@import Foundation;
+
+// El punto de entrada de tu programa es una función llamada
+// main con un tipo de retorno entero.
+int main (int argc, const char * argv[])
+{
+ // Crear un autorelease pool para manejar la memoria al programa
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+ // Si se utiliza el conteo automático de referencias (ARC),
+ // utiliza @autoreleasepool:
+ @autoreleasepool {
+
+ // Utiliza NSLog para imprimir líneas a la consola
+ NSLog(@"Hello World!"); // Imprimir el string "Hello World!"
+
+ ///////////////////////////////////////
+ // Tipos y variables
+ ///////////////////////////////////////
+
+ // Declaraciones de primitivos
+ int myPrimitive1 = 1;
+ long myPrimitive2 = 234554664565;
+
+ // Declaraciones de objetos
+ // Pon el * como prefijo de los nombre de las variables para declaraciones
+ // de objetos de tipos fuertes
+ MyClass *myObject1 = nil; // Tipo fuerte
+ id myObject2 = nil; // Tipo débil
+ // %@ es un objeto
+ // 'description' es una convención para mostrar el valor de los objetos
+ NSLog(@"%@ and %@", myObject1, [myObject2 description]);
+ // imprime => "(null) and (null)"
+
+ // String
+ NSString *worldString = @"World";
+ NSLog(@"Hello %@!", worldString); // imprime => "Hello World!"
+ // NSMutableString es una versión mutable del objeto NSString
+ NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"];
+ [mutableString appendString:@" World!"];
+ NSLog(@"%@", mutableString); // imprime => "Hello World!"
+
+ // Literales de caracteres
+ NSNumber *theLetterZNumber = @'Z';
+ char theLetterZ = [theLetterZNumber charValue]; // o 'Z'
+ NSLog(@"%c", theLetterZ);
+
+ // Literales de enteros
+ NSNumber *fortyTwoNumber = @42;
+ int fortyTwo = [fortyTwoNumber intValue]; // o 42
+ NSLog(@"%i", fortyTwo);
+
+ NSNumber *fortyTwoUnsignedNumber = @42U;
+ unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // o 42
+ NSLog(@"%u", fortyTwoUnsigned);
+
+ NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42];
+ short fortyTwoShort = [fortyTwoShortNumber shortValue]; // o 42
+ NSLog(@"%hi", fortyTwoShort);
+
+ NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41];
+ unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // o 41
+ NSLog(@"%u", fortyOneUnsigned);
+
+ NSNumber *fortyTwoLongNumber = @42L;
+ long fortyTwoLong = [fortyTwoLongNumber longValue]; // o 42
+ NSLog(@"%li", fortyTwoLong);
+
+ NSNumber *fiftyThreeLongNumber = @53L;
+ unsigned long fiftyThreeUnsigned = [fiftyThreeLongNumber unsignedLongValue]; // o 53
+ NSLog(@"%lu", fiftyThreeUnsigned);
+
+ // Literales de punto flotante
+ NSNumber *piFloatNumber = @3.141592654F;
+ float piFloat = [piFloatNumber floatValue]; // o 3.141592654f
+ NSLog(@"%f", piFloat); // imprime => 3.141592654
+ NSLog(@"%5.2f", piFloat); // imprime => " 3.14"
+
+ NSNumber *piDoubleNumber = @3.1415926535;
+ double piDouble = [piDoubleNumber doubleValue]; // o 3.1415926535
+ NSLog(@"%f", piDouble);
+ NSLog(@"%4.2f", piDouble); // imprime => "3.14"
+
+ // NSDecimalNumber es una clase de punto-fijo que es más preciso que float o double
+ NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"];
+ NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"];
+ // NSDecimalNumber no tiene la capacidad de utilizar los operadores estándares
+ // +, -, * , /, por lo que cuenta con sus propios operadores:
+ [oneDecNum decimalNumberByAdding:twoDecNum];
+ [oneDecNum decimalNumberBySubtracting:twoDecNum];
+ [oneDecNum decimalNumberByMultiplyingBy:twoDecNum];
+ [oneDecNum decimalNumberByDividingBy:twoDecNum];
+ NSLog(@"%@", oneDecNum); // imprime => 10.99 como NSDecimalNumber es inmutable
+
+ // Literales BOOL
+ NSNumber *yesNumber = @YES;
+ NSNumber *noNumber = @NO;
+ // o
+ BOOL yesBool = YES;
+ BOOL noBool = NO;
+ NSLog(@"%i", yesBool); // prints => 1
+
+ // Objecto arreglo
+ // Puede contener diferentes tipos de datos, pero deben de ser un objeto de
+ // Objective-C
+ NSArray *anArray = @[@1, @2, @3, @4];
+ NSNumber *thirdNumber = anArray[2];
+ NSLog(@"Third number = %@", thirdNumber); // imprime => "Third number = 3"
+ // NSMutableArray es una versión mutable de NSArray, permitiendo el cambio
+ // de los elementos del arreglo y el agrandado o encojimiento del objeto arreglo.
+ // Conveniente, pero no tan eficiente como NSArray en cuanto a rendimiento.
+ NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2];
+ [mutableArray addObject:@"Hello"];
+ [mutableArray addObject:@"World"];
+ [mutableArray removeObjectAtIndex:0];
+ NSLog(@"%@", [mutableArray objectAtIndex:0]); // imprime => "World"
+
+ // Objecto Diccionario
+ NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" };
+ NSObject *valueObject = aDictionary[@"A Key"];
+ NSLog(@"Object = %@", valueObject); // imprime => "Object = (null)"
+ // NSMutableDictionary también está disponible como un objeto mutable
+ NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2];
+ [mutableDictionary setObject:@"value1" forKey:@"key1"];
+ [mutableDictionary setObject:@"value2" forKey:@"key2"];
+ [mutableDictionary removeObjectForKey:@"key1"];
+
+ // Objeto de Set
+ NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil];
+ NSLog(@"%@", set); // imprime => {(Hello, World)} (el orden puede variar)
+ // NSMutableSet también está disponible como un objeto mutable
+ NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2];
+ [mutableSet addObject:@"Hello"];
+ [mutableSet addObject:@"Hello"];
+ NSLog(@"%@", mutableSet); // prints => {(Hello)}
+
+ ///////////////////////////////////////
+ // Operadores
+ ///////////////////////////////////////
+
+ // Los operadores funcionan como en el lenguaje C
+ // Por ejemplo:
+ 2 + 5; // => 7
+ 4.2f + 5.1f; // => 9.3f
+ 3 == 2; // => 0 (NO)
+ 3 != 2; // => 1 (YES)
+ 1 && 1; // => 1 (and lógico)
+ 0 || 1; // => 1 (or lógico)
+ ~0x0F; // => 0xF0 (negación bitwise)
+ 0x0F & 0xF0; // => 0x00 (AND bitwise)
+ 0x01 << 1; // => 0x02 (acarreamiento a la izquierda bitwise (por 1))
+
+ ///////////////////////////////////////
+ // Estructuras de control
+ ///////////////////////////////////////
+
+ // Declaraciones If-Else
+ if (NO)
+ {
+ NSLog(@"I am never run");
+ } else if (0)
+ {
+ NSLog(@"I am also never run");
+ } else
+ {
+ NSLog(@"I print");
+ }
+
+ // Declaración Switch
+ switch (2)
+ {
+ case 0:
+ {
+ NSLog(@"I am never run");
+ } break;
+ case 1:
+ {
+ NSLog(@"I am also never run");
+ } break;
+ default:
+ {
+ NSLog(@"I print");
+ } break;
+ }
+
+ // Declaración de ciclos While
+ int ii = 0;
+ while (ii < 4)
+ {
+ NSLog(@"%d,", ii++); // ii++ incrementa ii en la misma línea, luego de
+ // utilizar su valor
+ } // imprime => "0,"
+ // "1,"
+ // "2,"
+ // "3,"
+
+ // Declaración de ciclos For
+ int jj;
+ for (jj=0; jj < 4; jj++)
+ {
+ NSLog(@"%d,", jj);
+ } // imprime => "0,"
+ // "1,"
+ // "2,"
+ // "3,"
+
+ // Declaraciones foreach
+ NSArray *values = @[@0, @1, @2, @3];
+ for (NSNumber *value in values)
+ {
+ NSLog(@"%@,", value);
+ } // imprime => "0,"
+ // "1,"
+ // "2,"
+ // "3,"
+
+ // Objeto de ciclos For. Puede ser utilizado con cualquier tipo de objecto de
+ // Objective-C
+ for (id item in values) {
+ NSLog(@"%@,", item);
+ } // imprime => "0,"
+ // "1,"
+ // "2,"
+ // "3,"
+
+ // Declaraciones Try-Catch-Finally
+ @try
+ {
+ // Tus declaraciones aquí
+ @throw [NSException exceptionWithName:@"FileNotFoundException"
+ reason:@"File Not Found on System" userInfo:nil];
+ } @catch (NSException * e) // utiliza: @catch (id exceptionName) para atrapar
+ // todos los objetos
+ {
+ NSLog(@"Exception: %@", e);
+ } @finally
+ {
+ NSLog(@"Finally. Time to clean up.");
+ } // imprime => "Exception: File Not Found on System"
+ // "Finally. Time to clean up."
+
+ // Los objetos NSError son útiles para argumentos de función para los
+ // errores de usuario.
+ NSError *error = [NSError errorWithDomain:@"Invalid email." code:4 userInfo:nil];
+
+ ///////////////////////////////////////
+ // Objetos
+ ///////////////////////////////////////
+
+ // Crea una instancia de objeto alocando memoria e inicializándola
+ // Un objeto no es completamente funcional hasta que ambos pasos hayan sido
+ // completados
+ MyClass *myObject = [[MyClass alloc] init];
+
+ // El modelo de programación orientada a objetos de Objective-C es basada en
+ // el envío de mensajes a instancias de objetos
+ // En Objective-C no se llama a un método; se envía un mensaje
+ [myObject instanceMethodWithParameter:@"Steve Jobs"];
+
+ // Limpiar la memoria que se utilizó en el programa
+ [pool drain];
+
+ // Fin de @autoreleasepool
+ }
+
+ // Fin del programa
+ return 0;
+}
+
+///////////////////////////////////////
+// Clases y funciones
+///////////////////////////////////////
+
+// Declara tu clase en archivo de encabezado (MyClass.h)
+// Sintaxis de declaración de clase:
+// @interface NombreDeClase : NombreDeClasePadre <ProtocolosImplementados>
+// {
+// type nombre; <= declaraciones de variables;
+// }
+// @property tipo nombre; <= declaración de propiedades
+// -/+ (tipo) Declaración de método; <= Declaración de método
+// @end
+@interface MyClass : NSObject <MyProtocol> // NSObject es la clase de objeto
+ // base de Objective-C.
+{
+ // Declaraciones de variables de instancia (puede existir en el archivo de
+ // interfaz o de implementación)
+ int count; // Acceso protegido por defecto.
+ @private id data; // Acceso privado (Más conveniente de declarar en el
+ // archivo de implementación)
+ NSString *name;
+}
+// Notación conveneinte para acceso público de las variables para generar un
+// método setter
+// Por defecto, el nombre del método setter 'set' seguido del nombre de
+// variable @property
+@property int propInt; // Nombre del método 'setter' = 'setPropInt'
+@property (copy) id copyId; // (copy) => Copia el objeto durante la asignación
+// (readonly) => No se le puede asignar un valor fuera de @interface
+@property (readonly) NSString *roString; // utiliza @synthesize en
+ // @implementation para crear un accesor
+// Puedes personalizar el nombre del getter y del setter en lugar de utilizar
+// el nombre por defecto "set".
+@property (getter=lengthGet, setter=lengthSet:) int length;
+
+// Métodos
++/- (return type)methodSignature:(Parameter Type *)parameterName;
+
+// + Para métodos de clase:
++ (NSString *)classMethod;
++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight;
+
+// - Para métodos de instancia:
+- (NSString *)instanceMethodWithParameter:(NSString *)string;
+- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number;
+
+// Métodos de constructor con argumentos
+- (id)initWithDistance:(int)defaultDistance;
+// Los nombres de los métodos de Objective-C son muy descriptivos.
+// Siempre nombra los métodos de acuerdo con sus argumentos
+
+@end // Define el final de la interfaz
+
+
+// Para acceder a las variables públicas desde el archivo de implementación,
+// @property genera un método setter automáticamente. El nombre del método
+// es 'set' seguido de un nombre de variable @property:
+MyClass *myClass = [[MyClass alloc] init]; // Crea una instancia del objeto MyClass
+[myClass setCount:10];
+NSLog(@"%d", [myClass count]); // imprime => 10
+// O utilizando los métodos getter y setter personalizados en @interface:
+[myClass lengthSet:32];
+NSLog(@"%i", [myClass lengthGet]); // imprime => 32
+// Por conveniencia, puedes utilizar la notación de punto para asignar y
+// acceder a las variables de una instancia de objeto.
+myClass.count = 45;
+NSLog(@"%i", myClass.count); // imprime => 45
+
+// Llama a métodos de clase:
+NSString *classMethodString = [MyClass classMethod];
+MyClass *classFromName = [MyClass myClassFromName:@"Hello"];
+
+// Llama a métodos de instancia:
+MyClass *myClass = [[MyClass alloc] init]; // Crea una instancia de objeto Myclass
+NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hello"];
+
+// Selectors
+// Una forma dinámica de representar métodos. Utilizados para llamar métodos
+// de una clase, pasar métodos a través de funciones para avisar a otras clases
+// para que lo llamen, y para guardar métodos como una variable.
+// SEL es el tipo de dato. @selector() devuelve un selector del nombre de
+// método proveído methodAparameterAsString:andAParameterAsNumber: es un nombre
+// para un método en MyClass
+SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:);
+if ([myClass respondsToSelector:selectorVar]) { // Revisa si la clase contiene el método
+ // Debe de poner todos los argumentos de método en un solo objeto para mandar una
+ // función performSelector.
+ NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil];
+ [myClass performSelector:selectorVar withObject:arguments]; // Calls the method
+} else {
+ // NSStringFromSelector() devuelve un NSString del nombre de método de un selector dado
+ NSLog(@"MyClass does not have method: %@", NSStringFromSelector(selectedVar));
+}
+
+// Implementa los métodos de un archivo de implementación (MyClass.m):
+@implementation MyClass {
+ long distance; // Variable de instancia de acceso privado
+ NSNumber height;
+}
+
+// Para acceder a una variable pública del archivo de interfaz, utiliza '_' seguido del
+// nombre de la variable:
+_count = 5; // Hace referencia a "int count" de la interfaz de MyClass
+// Accede variables definidas en el archivo de implementación:
+distance = 18; // Hace referencia a "long distance" de la implementación de MyClass
+// Para utilizar una variable @property en el archivo de implementación, utiliza
+// @synthesize para crear una variable de acceso:
+@synthesize roString = _roString; // _roString ahora está disponible en @implementation
+
+// Lamado antes de llamar algún método o instanciar cualquier objeto
++ (void)initialize
+{
+ if (self == [MyClass class]) {
+ distance = 0;
+ }
+}
+
+// Contraparte para inicializar un método. Llamado cuando el contador de referencias
+// del objeto es cero
+- (void)dealloc
+{
+ [height release]; // Si no utilizas ARC, asegúrate de liberar las variables de
+ // objeto de las clases
+ [super dealloc]; // y llama el método dealloc de la clase padre
+}
+
+// Los constructores son una manera de crear instancias de una clase
+// Este es el constructor por defecto que es llamado cuando el objeto es inicializado.
+- (id)init
+{
+ if ((self = [super init])) // 'super' es utilizado para acceder a los
+ // métodos de la clase padre.
+ {
+ self.count = 1; // 'self' es utilizado para que el objeto se llame a sí mismo.
+ }
+ return self;
+}
+// Se pueden crear constructores que contiene argumentos
+- (id)initWithDistance:(int)defaultDistance
+{
+ distance = defaultDistance;
+ return self;
+}
+
++ (NSString *)classMethod
+{
+ return @"Some string";
+}
+
++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight
+{
+ height = defaultHeight;
+ return [[self alloc] init];
+}
+
+- (NSString *)instanceMethodWithParameter:(NSString *)string
+{
+ return @"New string";
+}
+
+- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number
+{
+ return @42;
+}
+
+// Objective-C no tiene declaraciones de métodos privados, pero pueden ser simulados.
+// Para simular un método privado, crea un método en @implementation pero no en @interface.
+- (NSNumber *)secretPrivateMethod {
+ return @72;
+}
+[self secretPrivateMethod]; // Calls private method
+
+// Métodos declarados dentro de MyProtocol
+- (void)myProtocolMethod
+{
+ // statements
+}
+
+@end // Declara el final de la implementación
+
+///////////////////////////////////////
+// Categorías
+///////////////////////////////////////
+// Una categoría es un grupo de métodos diseñados para extender una clase.
+// Te permiten agregar nuevos métodos a una clase existente por propósitos
+// de organización. Éstos no deben de serconfundidos con subclases.
+// Las subclases existen para CAMBIAR la funcionalidad de un objeto mientras
+// que las categoríasle AGREGAN funcionalidad de un objeto.
+// Las categorías te permiten:
+// -- Agregar métodos a una clase existente por propósitos de oganización.
+// -- Extender clases de objetos de Objective-C (ejemplo: NSString) para
+// agregar tus propios métodos.
+// -- Agregar la habilidad de crear métodos protegidos y privados para las clases.
+// NOTA: No sobreescribas los métodos de las clases base en una categoría
+// aunque tengas la habilidad de poder hacerlo. Sobreescribir métodos puede
+// causar errores en la compilación después entre diferentes categorías y
+// puede arruinar el propósito de las categorías de solo AGREGAR funcionalidad.
+// Utiliza subclass para sobreescribir métodos.
+
+// Aquí una clase base simple, Car.
+@interface Car : NSObject
+
+@property NSString *make;
+@property NSString *color;
+
+- (void)turnOn;
+- (void)accelerate;
+
+@end
+
+// Y la implementación de la clase simple, Car
+#import "Car.h"
+
+@implementation Car
+
+@synthesize make = _make;
+@synthesize color = _color;
+
+- (void)turnOn {
+ NSLog(@"Car is on.");
+}
+- (void)accelerate {
+ NSLog(@"Accelerating.");
+}
+
+@end
+
+// Ahora, si quisieramos crear un objeto Truck (Camión), crearíamos una
+// subclase de Car (Carro) como si le cambiaramos de funcionalidad de Car
+// para que se comporte como un camión. Pero digamos que únicamente queremos
+// agregar funcionalidad al Car (Carro) existente. Un buen ejemplo sería
+// limpiar el carro. Así que crearíamos una cateog®iea para agregar los
+// métodos de limpieza:
+// Archivo @interface: Car+Clean.h (NombreBaseDeClase+NombreDeCategoria.h)
+#import "Car.h" // Asegúrate de improtar la clase que deseas extener.
+
+@interface Car (Clean) // El nombre de la categoría está dentro de (),
+ // seguido del nombre de la clase base
+
+- (void)washWindows; // Nombres de los nuevos métodos que le agregamos
+ // a nuestro objeto Car
+- (void)wax;
+
+@end
+
+// Archivo @implementation: Car+Clean.m (NombreBaseDeClase+NombreDeCategoria.m)
+#import "Car+Clean.h" // Importa el archivo de @interface de la categoría Clean
+
+@implementation Car (Clean)
+
+- (void)washWindows {
+ NSLog(@"Windows washed.");
+}
+- (void)wax {
+ NSLog(@"Waxed.");
+}
+
+@end
+
+// Cualquier instancia del objeto Car tiene la habilidad de utilizar una
+// categoría. Todo lo que necesitan es importarlo:
+#import "Car+Clean.h" // Importa todas las diferentes categorías que
+ // necesites utilizar
+#import "Car.h" // También debes de importar la clase base para su
+ // funcionalidad original
+
+int main (int argc, const char * argv[]) {
+ @autoreleasepool {
+ Car *mustang = [[Car alloc] init];
+ mustang.color = @"Red";
+ mustang.make = @"Ford";
+
+ [mustang turnOn]; // Utiliza métodos de la clase base Car.
+ [mustang washWindows]; // Utiliza métodos de la categoría Clean de Car.
+ }
+ return 0;
+}
+
+// Objective-C no tiene declaraciones para métodos protegidos, pero los puedes
+// simular. Crea una categoría conteniendo todos los métodos protegidos,
+// luego importa ÚNICAMENTE al archivo @implementation de una clase que
+// pertenece a la clase Car.
+@interface Car (Protected) // Nombrando la categoría 'Protected' para
+ // recordar que los métodos están protegidos
+
+- (void)lockCar; // Los métodos enlistados aquí solo puedens ser creados
+ // por objetos Car
+
+@end
+// Para utilizar los métodos protegidos, importa la categoría,
+// luego implementa sus métodos:
+#import "Car+Protected.h" // Recuerda, importa únicamente el archivo
+ // de @implementation
+
+@implementation Car
+
+- (void)lockCar {
+ NSLog(@"Car locked."); // Las instancias de Car no puede utilizar
+ // lockCar porque no se encuentra en @interface
+}
+
+@end
+
+///////////////////////////////////////
+// Extensiones
+///////////////////////////////////////
+// Las Extensions te permiten sobreescribir atributos de propiedades de
+// acceso público y métodos de un @interface
+// Archivo @interface: Shape.h
+@interface Shape : NSObject
+
+@property (readonly) NSNumber *numOfSides;
+
+- (int)getNumOfSides;
+
+@end
+// Puedes sobreescribir la variable numOfSides o el métodos getNumOfSlides
+// para modificarlos con una extensión:
+// Archivo @implementation: Shape.m
+#import "Shape.h"
+// Las extensiones se encuentran en el mismo archivo que el archivo
+// de @implementation
+@interface Shape () // () después del nombre de la clase base declara
+ // una extensión
+
+@property (copy) NSNumber *numOfSides; // Hacer numOfSlides copy en lugar
+ // de readonly.
+-(NSNumber)getNumOfSides; // Hacer que getNumOfSides devuelva un NSNumber
+ // en lugar de un int.
+-(void)privateMethod; // También puedes crear una nuevos métodos privados
+ // dentro de las extensiones
+
+@end
+// @implementation principal:
+@implementation Shape
+
+@synthesize numOfSides = _numOfSides;
+
+-(NSNumber)getNumOfSides { // Todas las declaraciones dentro de extensions
+ // deben de ser dentro de @implementation
+ return _numOfSides;
+}
+-(void)privateMethod {
+ NSLog(@"Private method created by extension. Shape instances cannot call me.");
+}
+
+@end
+
+///////////////////////////////////////
+// Protocolos
+///////////////////////////////////////
+// Un protocolo declara métodos que pueden ser implementados por cualquier otra
+// clase. Los protocolos no son clases. Simplementen define una interfaz que
+// otros objetos deben de implementar.
+// Archivo @protocol: "CarUtilities.h"
+@protocol CarUtilities <NSObject> // <NSObject> => Nombre de otro protocolo
+ // que se incluye en éste
+ @property BOOL engineOn; // La clase que lo adopta debe de utilizar
+ // @synthesize para todas las @properties definidas
+ - (void)turnOnEngine; // y todos los métodos definidos
+@end
+// A continuación una clase ejemplo que implementa el protcolo
+#import "CarUtilities.h" // Importar el archivo @protocol.
+
+@interface Car : NSObject <CarUtilities> // El nombre del protocolo dentro de <>
+ // No necesitas los nombres de @property o métodos aquí para CarUtilities.
+ // Estos solo es requerido por @implementation.
+- (void)turnOnEngineWithUtilities:(id <CarUtilities>)car; // También Puedes
+ // utilizar protocolos
+ // como datos.
+@end
+// El @implementation necesita que se implementen @properties y métodos
+// del protocolo.
+@implementation Car : NSObject <CarUtilities>
+
+@synthesize engineOn = _engineOn; // Crear una declaración @synthesize para el
+ // @property engineOn.
+
+- (void)turnOnEngine { // Implementa turnOnEngine como quieras. Los
+ // protocolos no definen
+ _engineOn = YES; // cómo implementas un método, con tal de que lo implementes.
+}
+// Puedes utilizar un protocolo como data mientras sepas quee métodos y variables
+// tiene implementado.
+- (void)turnOnEngineWithCarUtilities:(id <CarUtilities>)objectOfSomeKind {
+ [objectOfSomeKind engineOn]; // Tienes acceso a las variables
+ [objectOfSomeKind turnOnEngine]; // y los métodos del objeto
+ [objectOfSomeKind engineOn]; // Puede o no puede ser YES. La clase lo
+ // implementa como se quiera.
+}
+
+@end
+// Las instancias de Car ahora tienen acceso al protocolo.
+Car *carInstance = [[Car alloc] init];
+[carInstance setEngineOn:NO];
+[carInstance turnOnEngine];
+if ([carInstance engineOn]) {
+ NSLog(@"Car engine is on."); // imprime => "Car engine is on."
+}
+// Asegúrate de revisar si un objeto de tipo 'id' implementa un protocolo antes
+// de llamar a sus métodos:
+if ([myClass conformsToProtocol:@protocol(CarUtilities)]) {
+ NSLog(@"This does not run as the MyClass class does not implement the CarUtilities protocol.");
+} else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) {
+ NSLog(@"This does run as the Car class implements the CarUtilities protocol.");
+}
+// Las categorías también pueden implementar protcolos: @interface Car
+// (CarCategory) <CarUtilities>
+// Puedes implementar varios protocolos:
+// @interface Car : NSObject <CarUtilities, CarCleaning>
+// NOTA: Si dos o más protocolos dependen entre sí, asegúrate de declararlos
+// de manera adelantada:
+#import "Brother.h"
+
+@protocol Brother; // Declaración adelantada. Sin ésto, el compilador
+ // tira un error.
+
+@protocol Sister <NSObject>
+
+- (void)beNiceToBrother:(id <Brother>)brother;
+
+@end
+
+// Ver si el problema es que Sister depende de Brother,
+// y Brother dependa de Sister.
+#import "Sister.h"
+
+@protocol Sister; // Estas líneas detienen la recursión, resolviendo el problema.
+
+@protocol Brother <NSObject>
+
+- (void)beNiceToSister:(id <Sister>)sister;
+
+@end
+
+
+///////////////////////////////////////
+// Bloques
+///////////////////////////////////////
+// Los bloques son declaraciones de código, tal como una función, pueden
+// ser utilizados como data.
+// A continuación un bloque simple con un argumento entero que devuelve
+// un el argumento más 4.
+int (^addUp)(int n); // Declarar una variable para almacenar el bloque.
+void (^noParameterBlockVar)(void); // Ejemplo de una declaración de variable
+ // de bloque sin argumentos.
+// Los bloques tienen acceso a variables del mismo ámbito. Pero las variables
+// son solo readonly y el valor pasado al bloque es el valor de la variable
+// cuando el bloque es creado.
+int outsideVar = 17; // Si modificamos outsideVar después de declarar addUp,
+ // outsideVar AÚN es 17.
+__block long mutableVar = 3; // __block hace que las variables se puedan
+ // escribir en bloques.
+addUp = ^(int n) { // Remueve (int n) para tener un bloque que no recibe
+ // ningún parámetro
+ NSLog(@"You may have as many lines in a block as you would like.");
+ NSSet *blockSet; // También puedes declarar variables locales.
+ mutableVar = 32; // Asignar un nuevo valor a la variable __block.
+ return n + outsideVar; // Declaraciones de retorno son opcionales.
+}
+int addUp = add(10 + 16); // Llama al bloque de código con argumentos.
+// Los bloques son usualmente utilizados como argumentos a funciones que
+// son llamados más adelante o para callbacks.
+@implementation BlockExample : NSObject
+
+ - (void)runBlock:(void (^)(NSString))block {
+ NSLog(@"Block argument returns nothing and takes in a NSString object.");
+ block(@"Argument given to block to execute."); // Calling block.
+ }
+
+ @end
+
+
+///////////////////////////////////////
+// Manejo de memoria
+///////////////////////////////////////
+/*
+Para cada objeto utilizado en una aplicación, la memoria debe de ser alocada
+para ese objeto. Cuando la aplicación termina de utilizar ese objeto, la
+memoria debe de ser desalocada para asegurar la eficiencia de la aplicación.
+Objetive-C no utiliza garbage collection, y en lugar de eso utiliza conteos
+de referencias. Mientras haya al menos una referencia del objeto (también
+conocido como tener un objeto de adueñado), entonces el objeto estará
+disponible para su uso.
+
+Cuando una instancia es dueña un objeto, su contador de referencia incrementa
+por uno. Cuando el objeto es liberado, el contador de referencia decrementa uno.
+Cuando el conteo de referencia es cero, el objeto es removido de la memoria.
+
+Con todas las interacciones de los objetos, sigue el patrón de:
+(1) Crear e lobjeto, (2) utiliza el objeto, (3) libera el objeto de la memoria.
+*/
+
+MyClass *classVar = [MyClass alloc]; // 'alloc' asigna uno al conteo de
+ // referencias de classVar. Devuelve un
+ // puntero al objeto
+[classVar release]; // Decrementa el conteo de referencias de classVar's
+// 'retain'
+// 'retain' adueña la instancia de objeto existente e incrementa el conteo de
+// referencia por uno. Devuelve un puntero al objeto.
+MyClass *newVar = [classVar retain]; // Si classVar es liberado, el objeto
+ // aún se queda en memoria porque newVar
+ // es el dueño.
+[classVar autorelease]; // Remueve el adueñamiento de un objeto al final del
+ // bloque @autoreleasepool. Devuelve un puntero al objeto.
+
+// @property puede utilizar 'retain' y 'assign' también para pequeñas
+// definiciones convenientes
+@property (retain) MyClass *instance; // Libera el valor viejo y retiene
+ // uno nuevo (referencia fuerte)
+@property (assign) NSSet *set; // Apunta a un nuevo valor sin retener/liberar
+ // una referencia vieja (débil)
+
+// Conteo Automático de Referencias (ARC)
+// Debido a que el manejo de memoria puede ser un dolor, en Xcode 4.2 y iOS 4
+// se introdujo el Conteo Automático de Referencias (ARC).
+// ARC es una funcionalidad del compilador que agrega retain, release y
+// autorealase automáticamente, así que al
+// utilizar ARC, no se debe de utilizar retain, release o autorelease.
+MyClass *arcMyClass = [[MyClass alloc] init];
+// ... código utilizando arcMyClass
+// Sin ARC, necesitarás llamar: [arcMyClass release] luego de terminar de
+// utilizar arcMyClass. Pero con ARC, no hay necesidad. Insertará
+// automáticamente la declaración de liberación.
+
+// Mientras que para los atributos de @property 'assign' y 'retain', con ARC
+// utilizarás 'weak' y 'strong'
+@property (weak) MyClass *weakVar; // 'weak' no adueña el objeto. El conteo de
+ // referencias de la instancia original
+// es fijado a ceor, weakVar automáticamente recibe el valor de nil para
+// evitar cualquier 'crashing'.
+@property (strong) MyClass *strongVar; // 'strong' se adueña del objeto.
+ // Asegura que el objeto se quede en memoria.
+
+// Para variables regulares (no variables de @property), utiliza lo siguiente:
+__strong NSString *strongString; // Por defecto. La variables de retenida en
+ // memoria hasta que se salga del ámbito.
+__weak NSSet *weakSet; // Referencia débil a un objeto existente. Cuando el
+ // objeto existente es liberado, weakSet le es asginado
+ // un valor nil
+__unsafe_unretained NSArray *unsafeArray; // Como __weak, pero unsafeArray no
+ // es asginado a nil cuando el objeto
+ // existente es liberado.
+
+```
+## Lecturas sugeridas
+
+[Wikipedia Objective-C](http://es.wikipedia.org/wiki/Objective-C)
+
+[Programming with Objective-C. Libro PDF de Apple](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf)
+
+[iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started)
diff --git a/es-es/php-es.html.markdown b/es-es/php-es.html.markdown
new file mode 100644
index 00000000..fa52353c
--- /dev/null
+++ b/es-es/php-es.html.markdown
@@ -0,0 +1,825 @@
+---
+language: PHP
+contributors:
+ - ["Malcolm Fell", "http://emarref.net/"]
+ - ["Trismegiste", "https://github.com/Trismegiste"]
+translators:
+ - ["Mario Pérez", "https://github.com/MarioPerezEsteso"]
+lang: es-es
+filename: learnphp-es.php
+---
+
+Este documento explica el funcionamiento de PHP 5+.
+
+```php
+<?php // El código PHP debe estar dentro de etiquetas <?php
+
+// Si tu fichero php solo contiene código php, es una buena práctica
+// omitir la etiqueta de cierre php para prevenir salidas acidentales.
+
+// Dos barras comienzan un comentario de una línea.
+
+# También lo hará una almohadilla, pero // es más común
+
+/*
+ Escribir texto entre una barra-asterisco y asterisco-barra
+ crea un comentario multilínea.
+*/
+
+// Utiliza "echo" o "print" para imprimir por pantalla
+print('Hola '); // Imprime "Hola " sin salto de línea
+
+// () son opcionales para print y echo
+echo "Mundo\n"; // Imprime "Mundo" con un salto de línea
+// (todas las sentencias deben finalizar con un punto y coma)
+
+// Cualquier cosa fuera de las etiquetas <?php se imprime automáticamente
+?>
+¡Hola Mundo de nuevo!
+<?php
+
+
+/************************************
+ * Tipos y variables
+ */
+
+// Las variables comienzan con el símbolo $.
+// Una variable válida comienza con una letra o guión bajo,
+// seguida de cualquier cantidad de letras, números o guiones bajos.
+
+// Las variables booleanas no distinguen entre mayúsculas o minúsculas
+$boolean = true; // o TRUE o True
+$boolean = false; // o FALSE o False
+
+// Enteros
+$int1 = 12; // => 12
+$int2 = -12; // => -12
+$int3 = 012; // => 10 (un 0 al comienzo declara un número octal)
+$int4 = 0x0F; // => 15 (un 0x al comienzo declara un hexadecimal)
+
+// Floats (también conocidos como doubles)
+$float = 1.234;
+$float = 1.2e3;
+$float = 7E-10;
+
+// Eliminar variable
+unset($int1);
+
+// Operaciones aritméticas
+$suma = 1 + 1; // 2
+$diferencia = 2 - 1; // 1
+$producto = 2 * 2; // 4
+$cociente = 2 / 1; // 2
+
+// Operaciones aritméticas de escritura rápida
+$numero = 0;
+$numero += 1; // Incrementa $numero en 1
+echo $numero++; // Imprime 1 (incremento después la evaluación)
+echo ++$numero; // Imprime 3 (incremento antes de la evaluación)
+$numero /= $float; // Divide y asigna el cociente a $numero
+
+// Las cadenas de caracteres deben declararse entre comillas simples
+$sgl_quotes = '$String'; // => '$String'
+
+// Evita utilizar comillas dobles excepto para embeber otras variables
+$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.'
+
+// Los caracteres especiales solo son válidos entre comillas dobles
+$escaped = "Esto contiene \t un caracter tabulador.";
+$unescaped = 'Esto solo contiene una barra y una t: \t';
+
+// Rodea una variable entre corchetes si es necesario
+$dinero = "Tengo $${numero} en el banco.";
+
+// Desde PHP 5.3, los nowdocs pueden ser utilizados para multilíneas no interpoladas
+$nowdoc = <<<'END'
+Multi line
+string
+END;
+
+// Heredocs interpola cadenas de caracteres
+$heredoc = <<<END
+Multi line
+$sgl_quotes
+END;
+
+// La concatenación de cadenas de caracteres se realiza con .
+echo 'Esta cadena de caracteres ' . 'está concatenada';
+
+// Las cadenas de caracteres pueden ser pasadas como parámetros en un echo
+echo 'Multiples', 'Parametros', 'Validos'; // Devuelve 'MultiplesParametrosValidos'
+
+
+/********************************
+ * Constantes
+ */
+
+// Una constante se define utilizando define()
+// y nunca puede ser cambiada en tiempo de ejecución
+
+// un nombre válido para una constante debe comenzar con una letra o guión bajo,
+// seguido por cualquier número de letras, números o guiones bajos.
+define("FOO", "algo");
+
+// el acceso a una constante se puede realizar llamando a la variable elegida sin un símbolo de $
+echo FOO; // Devuelve 'algo'
+echo 'Esto imprime '.FOO; // Devuelve 'Esto imprime algo'
+
+
+
+/********************************
+ * Arrays
+ */
+
+// Todos los arrays en PHP son asociativos (hashmaps),
+
+// Los arrays asociativos son conocidos como hashmaps en algunos lenguajes.
+
+// Funciona con todas las versiones de php
+$asociativo = array('Uno' => 1, 'Dos' => 2, 'Tres' => 3);
+
+// PHP 5.4 introdujo una nueva sintaxis
+$asociativo = ['Uno' => 1, 'Dos' => 2, 'Tres' => 3];
+
+echo $asociativo['Uno']; // imprime 1
+
+// Lista literales implícitamente asignados con claves enteras
+$array = ['Uno', 'Dos', 'Tres'];
+echo $array[0]; // => "Uno"
+
+// Añadir un elemento al final de un array
+$array[] = 'Cuatro';
+// o
+array_push($array, 'Cinco');
+
+// Eliminar un elemento de un array
+unset($array[3]);
+
+/********************************
+ * Salidas por pantalla
+ */
+
+echo('¡Hola Mundo!');
+// Imprime ¡Hola Mundo! en stdout.
+// Stdout es la página web si se está ejecutando en un navegador.
+
+print('!Hola Mundo!'); // Es lo mismo que echo
+
+// No es necesario el paréntesis en echo y print
+echo '¡Hola Mundo!';
+print '¡Hola Mundo!';
+
+$parrafo = 'parrafo';
+
+echo 100; // Haz echo de escalares directamente
+echo $parrafo; // o de variables
+
+// Si las etiquetas cortas estás configuradas y tu versión de PHP es
+// la 5.4.0 o superior, puede utilizar la sintaxis abreviada de echo
+?>
+<p><?= $parrafo?></p>
+<?php
+
+$x = 1;
+$y = 2;
+$x = $y; // $x ahora contiene el mismo valor que $y
+$z = &$y;
+// $z contiene ahora una referencia a $y. Un cambio en el valor de
+// $z cambiará también el valor de $y, y viceversa.
+// $x sin embargo, tendrá el valor original de $y
+
+echo $x; // => 2
+echo $z; // => 2
+$y = 0;
+echo $x; // => 2
+echo $z; // => 0
+
+// Dump muestra el tipo y valor de una variable en stdout
+var_dump($z); // imprime int(0)
+
+// Para mostrar el valor de una variable en un formato legible para humanos
+print_r($array); // imprime: Array ( [0] => Uno [1] => Dos [2] => Tres )
+
+/********************************
+ * Lógica
+ */
+$a = 0;
+$b = '0';
+$c = '1';
+$d = '1';
+
+// assert lanza una advertencia si su argumento no es verdadero
+
+// Estas comparaciones siempre serán verdaderas, incluso si los tipos no son los mismos.
+assert($a == $b); // igualdad
+assert($c != $a); // desigualdad
+assert($c <> $a); // desigualdad alternativa
+assert($a < $c);
+assert($c > $b);
+assert($a <= $b);
+assert($c >= $d);
+
+// Los siguiente solo será verdadero si los valores coinciden y son del mismo tipo.
+assert($c === $d);
+assert($a !== $d);
+assert(1 === '1');
+assert(1 !== '1');
+
+// Operador 'Spaceship' (desde PHP 7)
+// Devuelve 0 si ambos valores son iguales
+// Devuelve 1 si el valor de la izquierda es mayor
+// Devuelve -1 si el valor de la derecha es mayor
+
+$a = 100;
+$b = 1000;
+
+echo $a <=> $a; // 0 porque son iguales
+echo $a <=> $b; // -1 porque $a < $b
+echo $b <=> $a; // 1 porque $b > $a
+
+// Las variables pueden ser convertidas entre tipos, dependiendo de su uso.
+
+$entero = 1;
+echo $entero + $entero; // => 2
+
+$string = '1';
+echo $string + $string; // => 2 (los strings son convertidos a enteros)
+
+$string = 'uno';
+echo $string + $string; // => 0
+// Muestra un 0 porque el operador + no puede convertir la cadena de caracteres 'uno' a un número
+
+// La conversión de tipos puede ser utilizada para tratar a una variable como otro tipo
+
+$boolean = (boolean) 1; // => true
+
+$cero = 0;
+$boolean = (boolean) $cero; // => false
+
+// También hay funciones dedicadas a la conversión de tipos
+$entero = 5;
+$string = strval($entero);
+
+$var = null; // Valor nulo
+
+
+/********************************
+ * Estructuras de control
+ */
+
+if (true) {
+ print 'He sido imprimido';
+}
+
+if (false) {
+ print 'Yo no';
+} else {
+ print 'He sido imprimido';
+}
+
+if (false) {
+ print 'No se imprime';
+} elseif(true) {
+ print 'Sí se imprime';
+}
+
+// operador ternario
+print (false ? 'No se imprime' : 'Sí se imprime');
+
+// atajo para el operador ternario desde PHP 5.3
+// equivalente de "$x ? $x : 'Sí'""
+$x = false;
+print($x ?: 'Sí');
+
+// operador 'no definido' desde php 7
+$a = null;
+$b = 'Imprime';
+echo $a ?? 'a no está definido'; // imprime 'a no está definido'
+echo $b ?? 'b no está definido'; // imprime 'Imprime'
+
+
+$x = 0;
+if ($x === '0') {
+ print 'No imprime';
+} elseif($x == '1') {
+ print 'No imprime';
+} else {
+ print 'Imprime';
+}
+
+
+
+// Esta sintaxis alternativa se utiliza para plantillas:
+?>
+
+<?php if ($x): ?>
+Esto se muestra si la evaluación es verdadera.
+<?php else: ?>
+En otro caso, se muestra esto.
+<?php endif; ?>
+
+<?php
+
+// Utiliza el switch para tener algo más de lógica.
+switch ($x) {
+ case '0':
+ print 'Switch does type coercion';
+ break; // Debes incluir un break para no seguir con los casos 'Dos' y 'Tres'
+ case 'Dos':
+ case 'Tres':
+ // Hacer algo si la variables es 'Dos' o 'Tres'
+ break;
+ default:
+ // Hacer algo por defecto
+}
+
+// Los bucles While, do...while y for te serán familiares
+$i = 0;
+while ($i < 5) {
+ echo $i++;
+}; // Imprime "01234"
+
+echo "\n";
+
+$i = 0;
+do {
+ echo $i++;
+} while ($i < 5); // Imprime "01234"
+
+echo "\n";
+
+for ($x = 0; $x < 10; $x++) {
+ echo $x;
+} // Imprime "0123456789"
+
+echo "\n";
+
+$ruedas = ['bicicleta' => 2, 'coche' => 4];
+
+// Los bucles foreach pueden iterar por arrays
+foreach ($ruedas as $numero_ruedas) {
+ echo $numero_ruedas;
+} // Imprime "24"
+
+echo "\n";
+
+// También se puede iterar sobre las claves, así como sobre los valores
+foreach ($ruedas as $vehiculo => $numero_ruedas) {
+ echo "Un $vehiculo tiene $numero_ruedas ruedas";
+}
+
+echo "\n";
+
+$i = 0;
+while ($i < 5) {
+ if ($i === 3) {
+ break; // Sale fuera del bucle while
+ }
+ echo $i++;
+} // Imprime "012"
+
+for ($i = 0; $i < 5; $i++) {
+ if ($i === 3) {
+ continue; // Se salta esta iteración del bucle
+ }
+ echo $i;
+} // Imprime "0124"
+
+
+/********************************
+ * Funciones
+ */
+
+// Define una función con "function":
+function mi_funcion () {
+ return 'Hola';
+}
+
+echo mi_funcion(); // => "Hola"
+
+// Un nombre válido de función comienza con una letra o guión bajo, seguido de cualquier
+// número de letras, números o guiones bajos.
+
+function anadir ($x, $y = 1) { // $y es opcional y por defecto es 1
+ $resultado = $x + $y;
+ return $resultado;
+}
+
+echo anadir(4); // => 5
+echo anadir(4, 2); // => 6
+
+// $resultado no es accesible fuera de la función
+// print $resultado; // Devuelve una advertencia.
+
+// Desde PHP 5.3 se pueden declarar funciones anónimas
+$inc = function ($x) {
+ return $x + 1;
+};
+
+echo $inc(2); // => 3
+
+function foo ($x, $y, $z) {
+ echo "$x - $y - $z";
+}
+
+// Las funciones pueden devolver funciones
+function bar ($x, $y) {
+ // Utiliza 'use' para meter variables de fuera de la función
+ return function ($z) use ($x, $y) {
+ foo($x, $y, $z);
+ };
+}
+
+$bar = bar('A', 'B');
+$bar('C'); // Imprime "A - B - C"
+
+// Puedes llamar a funciones utilizando cadenas de caracteres
+$nombre_funcion = 'add';
+echo $nombre_funcion(1, 2); // => 3
+// Es útil para determinarl qué función ejecutar.
+// O, utiliza call_user_func(callable $callback [, $parameter [, ... ]]);
+
+
+// Puedes obtener todos los parámetros pasados a una función
+function parametros() {
+ $numero_argumentos = func_num_args();
+ if ($numero_argumentos > 0) {
+ echo func_get_arg(0) . ' | ';
+ }
+ $args_array = func_get_args();
+ foreach ($args_array as $key => $arg) {
+ echo $key . ' - ' . $arg . ' | ';
+ }
+}
+
+parametros('Hola', 'Mundo'); // Hola | 0 - Hola | 1 - Mundo |
+
+// Desde PHP 5.6 se puede obtener un número variable de argumentos
+function variable($palabra, ...$lista) {
+ echo $palabra . " || ";
+ foreach ($lista as $item) {
+ echo $item . ' | ';
+ }
+}
+
+variable("Separa", "Hola", "Mundo") // Separa || Hola | Mundo |
+
+/********************************
+ * Includes
+ */
+
+<?php
+// Los ficheros PHP incluidos deben comenzar también con la etiqueta de <?php
+
+include 'mi-fichero.php';
+// El código de mi-fichero.php ya está disponible en el entorno actual.
+// Si el fichero no puede ser incluido (por ejemplo porque no se ha encontrado),
+// se muestra una advertencia.
+
+include_once 'mi-fichero.php';
+// Si el código del fichero mi-fichero.php ya ha sido incluido, ya no se
+// incluirá de nuevo. Este previene errores por múltiples declaraciones.
+
+require 'mi-fichero.php';
+require_once 'mi-fichero.php';
+// Es lo mismo que el include(), pero require() causará un error fatal si el archivo
+// no ha podido ser incluido.
+
+// Contenido de mi-include.php:
+<?php
+
+return 'Cualquier cosa.';
+// acabar archivo
+
+// Los include y require también pueden devolver un valor.
+$valor = include 'mi-include.php';
+
+// Los archivos son incluidos en función de la ruta data o, si ninguna ruta es
+// especificada se utilizará la directiva de configuración de include_path. Si el
+// fichero no se encuentra en el include_path, include comprobará la ruta del código
+// que lo llama antes de fallar.
+/* */
+
+/********************************
+ * Clases
+ */
+
+// Las clases son definidas con la palabra clave class
+
+class MiClase
+{
+ const MI_CONSTANTE = 'valor'; // Una constante
+
+ static $staticVar = 'static';
+
+ // Las variables estáticas y su visibilidad
+ public static $publicStaticVar = 'publicStatic';
+ // Accesible solo dentro de su clase
+ private static $privateStaticVar = 'privateStatic';
+ // Accesible desde la clase y las subclases
+ protected static $protectedStaticVar = 'protectedStatic';
+
+ // Las propiedades deben declarar su visibilidad
+ public $propiedad = 'public';
+ public $instanceProp;
+ protected $prot = 'protected'; // Accesible desde la clase y las subclases
+ private $priv = 'private'; // Accesible solo desde la clase
+
+ // Crear un constructor con __construct
+ public function __construct($instanceProp) {
+ // Accede a las variables de la instancia con $this
+ $this->instanceProp = $instanceProp;
+ }
+
+ // Los métodos son declarados como funciones dentro de una clase
+ public function miMetodo()
+ {
+ print 'MiClase';
+ }
+
+ // la palabra clave final hará una función no sobreescribible
+ final function noMePuedesSobreEscribir()
+ {
+ }
+
+/*
+ * Declarar propiedades de clase o métodos como estáticos los hace accesibles sin
+ * necesidad de instanciar la clase. Una propiedad declarada como estática no
+ * puede ser accedida mediante una instancia de la clase, pero sí mediante un
+ * método estático.
+ */
+
+ public static function miMetodoEstatico()
+ {
+ print 'Soy estático';
+ }
+}
+
+// Las constantes de una clase siempre pueden ser accedidas estáticamente
+echo MiClase::MI_CONSTANTE; // Muestra 'valor';
+
+echo MiClase::$staticVar; // Muestra 'static';
+MiClase::miMetodoEstatico(); // Muestra 'Soy estático';
+
+// Instancia una clase usando new
+$mi_clase = new MiClase('Una instancia');
+// Los paréntesis son opcionales si no se pasa ningún argumento.
+
+// Accede a los miembros de una clase utilizando ->
+echo $mi_clase->propiedad; // => "public"
+echo $mi_clase->instanceProp; // => "Una instancia"
+$mi_clase->miMetodo(); // => "MiClase"
+
+
+// Extender clases utilizando "extends"
+class MiOtraClase extends MiClase
+{
+ function imprimePropiedadProtegida()
+ {
+ echo $this->prot;
+ }
+
+ // Sobreescribe un método
+ function miMetodo()
+ {
+ parent::miMetodo();
+ print ' > MiOtraClase';
+ }
+}
+
+$mi_otra_clase = new MiOtraClase('Propiedad de instancia');
+$mi_otra_clase->imprimePropiedadProtegida(); // => Imprime "protected"
+$mi_otra_clase->miMetodo(); // Imprime "MiClase > MiOtraClase"
+
+final class NoMePuedesExtender
+{
+}
+
+// Puedes utilizar "métodos mágicos" para crear los getters y setters
+class MiClaseMapeada
+{
+ private $propiedad;
+
+ public function __get($key)
+ {
+ return $this->$key;
+ }
+
+ public function __set($key, $value)
+ {
+ $this->$key = $value;
+ }
+}
+
+$x = new MiClaseMapeada();
+echo $x->propiedad; // Utilizará el método __get()
+$x->propiedad = 'Algo'; // Utilizará el método __set()
+
+// Las clases pueden ser abstractas (utilizando la palabra clave abstract) o
+// implementando interfaces (utilizando la palabra clave implements).
+// Una interfaz puede ser declarada con la palabra clave interface.
+
+interface InterfazUno
+{
+ public function hazAlgo();
+}
+
+interface InterfazDos
+{
+ public function hazOtraCosa();
+}
+
+// las interfaces pueden ser extendidas
+interface InterfazTres extends InterfazDos
+{
+ public function hazCualquierOtraCosa();
+}
+
+abstract class MiClaseAbstracta implements InterfazUno
+{
+ public $x = 'hazAlgo';
+}
+
+class MiOtraClase extends MiClaseAbstracta implements InterfazDos
+{
+ public function hazAlgo()
+ {
+ echo $x;
+ }
+
+ public function hazOtraCosa()
+ {
+ echo 'hazOtraCosa';
+ }
+}
+
+
+// Las clases pueden implementar más de una interfaz
+class CualquierOtraClase implements InterfazUno, InterfazDos
+{
+ public function hazAlgo()
+ {
+ echo 'hazAlgo';
+ }
+
+ public function hazOtraCosa()
+ {
+ echo 'hazOtraCosa';
+ }
+}
+
+
+/********************************
+ * Traits
+ */
+
+// Los traits están disponibles desde PHP 5.4.0 y son declarados utilizando "trait"
+
+trait MiTrait
+{
+ public function miMetodoTrait()
+ {
+ print 'Tengo trait';
+ }
+}
+
+class MiClaseTrait
+{
+ use MiTrait;
+}
+
+$cls = new MiClaseTrait();
+$cls->miMetodoTrait(); // Imprime "Tengo trait"
+
+
+/********************************
+ * Namespaces
+ */
+
+// Esta sección está separada porque una declaración de namespace debe
+// ser la primera sentencia en un archivo. Vamos a suponer que no es el caso
+
+<?php
+
+// Por defecto, las clases existen en el namespace global y pueden ser llamadas
+// explícitamente con una contrabarra.
+
+$cls = new \MiClase();
+
+
+
+// Estableder el namespace para un archivo
+namespace Mi\Namespace;
+
+class MiClase
+{
+}
+
+// (de otro archivo)
+$cls = new Mi\Namespace\MiClase;
+
+// O de otro namespace.
+namespace Mi\Otro\Namespace;
+
+use Mi\Namespace\MiClase;
+
+$cls = new MiClase();
+
+// O se puede asignar un ales al namespace
+
+namespace Mi\Otro\Namespace;
+
+use Mi\Namespace as OtroNamespace;
+
+$cls = new OtroNamespace\MiClase();
+
+
+/**********************
+* Late Static Binding
+*
+*/
+
+class ClasePadre {
+ public static function quien() {
+ echo "Soy una " . __CLASS__ . "\n";
+ }
+ public static function test() {
+ // Auto referencia a la clase en la que el método está definido
+ self::quien();
+ // Referencia estáticamente a la clase donde el método ha sido llamado
+ static::quien();
+ }
+}
+
+ClasePadre::test();
+/*
+Soy una ClasePadre
+Soy una ClasePadre
+*/
+
+class ClaseHija extends ClasePadre {
+ public static function quien() {
+ echo "Pero soy una " . __CLASS__ . "\n";
+ }
+}
+
+ClaseHija::test();
+/*
+Soy una ClasePadre
+Pero soy una ClaseHija
+*/
+
+
+/**********************
+* Manejo de errores
+*
+*/
+
+// Una simple gestión de errores puede ser realizada con un bloque try catch
+
+try {
+ // Haz algo
+} catch (Exception $e) {
+ // Maneja la excepción
+}
+
+// Cuando se utilicen bloques try catch en un entorno con namespaces hay que
+// usar lo siguiente
+
+try {
+ // Haz algo
+} catch (\Exception $e) {
+ // Maneja la excepción
+}
+
+// Excepciones personalizadas
+
+class MiExcepcion extends Exception {}
+
+try {
+
+ $condicion = true;
+
+ if ($condicion) {
+ throw new MiExcepcion('Ha pasado algo');
+ }
+
+} catch (MiExcepcion $e) {
+ // Manejar la excepción
+}
+
+```
+
+## Más información
+
+Visita la [documentación oficial de PHP](http://www.php.net/manual/) para más referencias
+y apoyo de la comunidad.
+
+Si estás interesado en buenas prácticas, visita
+[PHP The Right Way](http://www.phptherightway.com/).
+
+Si vienes de un lenguaje con una buena gestión de paquetes, visita
+[Composer](http://getcomposer.org/).
+
+Para estándares comunes, visita el PHP Framework Interoperability Group
+[PSR standards](https://github.com/php-fig/fig-standards).
diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown
index 4930eebc..a27203d1 100644
--- a/es-es/python-es.html.markdown
+++ b/es-es/python-es.html.markdown
@@ -9,8 +9,8 @@ lang: es-es
filename: learnpython-es.py
---
-Python fue creado por Guido Van Rossum en el principio de los 90'. Ahora es uno
-de los lenguajes más populares en existencia. Me enamoré de Python por su claridad sintáctica.
+Python fue creado por Guido Van Rossum en el principio de los 90. Ahora es uno
+de los lenguajes más populares que existen. Me enamoré de Python por su claridad sintáctica.
Es básicamente pseudocódigo ejecutable.
¡Comentarios serán muy apreciados! Pueden contactarme en [@louiedinh](http://twitter.com/louiedinh) o louiedinh [at] [servicio de email de google]
@@ -19,8 +19,8 @@ Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser apl
```python
# Comentarios de una línea comienzan con una almohadilla (o signo gato)
-""" Strings multilinea pueden escribirse
- usando tres "'s, y comunmente son usados
+""" Strings multilínea pueden escribirse
+ usando tres "'s, y comúnmente son usados
como comentarios.
"""
@@ -48,7 +48,7 @@ Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser apl
# Resultado de la división de enteros truncada para positivos y negativos
5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # funciona con números en coma flotante
+5.0 // 3.0 # => 1.0 # funciona con números de coma flotante
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
@@ -436,7 +436,7 @@ class Humano(object):
def get_especie(cls):
return cls.especie
- # Un metodo estatico es llamado sin la clase o instancia como referencia
+ # Un metodo estático es llamado sin la clase o instancia como referencia
@staticmethod
def roncar():
return "*roncar*"
@@ -507,7 +507,7 @@ def duplicar_numeros(iterable):
# Nota: xrange es un generador que hace lo mismo que range.
# Crear una lista de 1 a 900000000 lleva mucho tiempo y ocupa mucho espacio.
# xrange crea un generador, mientras que range crea toda la lista.
-# Añadimos un guion bajo a los nombres de variable que coinciden con palabras
+# Añadimos un guión bajo a los nombres de variable que coinciden con palabras
# reservadas de python.
xrange_ = xrange(1, 900000000)
diff --git a/es-es/r-es.html.markdown b/es-es/r-es.html.markdown
new file mode 100644
index 00000000..2b710b27
--- /dev/null
+++ b/es-es/r-es.html.markdown
@@ -0,0 +1,717 @@
+---
+language: R
+contributors:
+ - ["e99n09", "http://github.com/e99n09"]
+ - ["isomorphismes", "http://twitter.com/isomorphisms"]
+translators:
+ - ["David Hsieh", "http://github.com/deivuh"]
+lang: es-es
+filename: learnr-es.r
+---
+
+R es un lenguaje de computación estadística. Tiene muchas librerías para cargar
+y limpiar sets de datos, ejecutar procedimientos estadísticos y generar
+gráficas. También puedes ejecutar comandos `R` dentro de un documento de
+LaTeX.
+
+```r
+
+# Los comentariso inician con símbolos numéricos.
+
+# No puedes hacer comentarios de múltiples líneas
+# pero puedes agrupar múltiples comentarios de esta manera.
+
+# En Windows puedes utilizar CTRL-ENTER para ejecutar una línea.
+# En Mac utilizas COMMAND-ENTER
+
+
+#############################################################################
+# Cosas que puedes hacer sin entender nada acerca de programación
+#############################################################################
+
+# En esta sección, mostramos algunas cosas chileras / cool que puedes hacer en
+# R sin entender nada de programación. No te preocupes en entender nada
+# de lo que hace este código. Solo disfruta!
+
+data() # Examinar sets de datos pre-cargados
+data(rivers) # Obtiene este: Lengths of Major North American Rivers"
+ls() # Fijarse que "rivers" ahora aparece en el workspace
+head(rivers) # Echarle un ojo al set de datos
+# 735 320 325 392 524 450
+
+length(rivers) # ¿Cuántos ríos fueron medidos?
+# 141
+summary(rivers) # ¿Cuáles son algunas estadísticas generales?
+# Min. 1st Qu. Median Mean 3rd Qu. Max.
+# 135.0 310.0 425.0 591.2 680.0 3710.0
+
+# Generar una gráfica tallo-y-hoja (Visualización de datos tipo histograma)
+stem(rivers)
+
+# El punto decimal son 2 dígitos a la derecha de |
+#
+# 0 | 4
+# 2 | 011223334555566667778888899900001111223333344455555666688888999
+# 4 | 111222333445566779001233344567
+# 6 | 000112233578012234468
+# 8 | 045790018
+# 10 | 04507
+# 12 | 1471
+# 14 | 56
+# 16 | 7
+# 18 | 9
+# 20 |
+# 22 | 25
+# 24 | 3
+# 26 |
+# 28 |
+# 30 |
+# 32 |
+# 34 |
+# 36 | 1
+
+stem(log(rivers)) # Fijarse que la data no es normal ni log-normal!
+# Toma eso, fundamentalistas de la curva de campana!
+
+# El punto decimal está a 1 dígito a la izquierda del |
+#
+# 48 | 1
+# 50 |
+# 52 | 15578
+# 54 | 44571222466689
+# 56 | 023334677000124455789
+# 58 | 00122366666999933445777
+# 60 | 122445567800133459
+# 62 | 112666799035
+# 64 | 00011334581257889
+# 66 | 003683579
+# 68 | 0019156
+# 70 | 079357
+# 72 | 89
+# 74 | 84
+# 76 | 56
+# 78 | 4
+# 80 |
+# 82 | 2
+
+# Generar un histograma:
+hist(rivers, col="#333333", border="white", breaks=25) # Juega con los estos parámetros
+hist(log(rivers), col="#333333", border="white", breaks=25) # Generarás más gráficas después
+
+# Aquí hay otro set de datos pre-cargado. R tiene bastantes de éstos.
+data(discoveries)
+plot(discoveries, col="#333333", lwd=3, xlab="Year",
+ main="Number of important discoveries per year")
+plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year",
+ main="Number of important discoveries per year")
+
+# En lugar de dejar el orden por defecto (por año),
+# podemos ordenar de tal manera que muestre qué es típico:
+sort(discoveries)
+# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2
+# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3
+# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4
+# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12
+
+stem(discoveries, scale=2)
+#
+# El punto decimal se encuentra en |
+#
+# 0 | 000000000
+# 1 | 000000000000
+# 2 | 00000000000000000000000000
+# 3 | 00000000000000000000
+# 4 | 000000000000
+# 5 | 0000000
+# 6 | 000000
+# 7 | 0000
+# 8 | 0
+# 9 | 0
+# 10 | 0
+# 11 |
+# 12 | 0
+
+max(discoveries)
+# 12
+summary(discoveries)
+# Min. 1st Qu. Median Mean 3rd Qu. Max.
+# 0.0 2.0 3.0 3.1 4.0 12.0
+
+# Tirar los dados varias veces
+round(runif(7, min=.5, max=6.5))
+# 1 4 6 1 4 6 4
+# Tus números será diferente de los míos, a menos que tengamos el mismo valor
+# de random.seed(31337)
+
+# Dibuja de un Gaussian 9 veces
+rnorm(9)
+# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271
+# [7] -0.59975593 0.57629164 1.08455362
+
+
+
+##################################################
+# Tipos de datos y aritmética básica
+##################################################
+
+# Ahora para la parte de programación orientada a objetos del tutorial.
+# En esta sección conocerás los tipos de datos importantes de R:
+# Enteros, numéricos, caracteres, lógicos, y factores.
+# Hay otros, pero esos son los que menos necesitas para empezar.
+
+# ENTEROS
+# Enteros de almacenamiento largo son escritos con L
+5L # 5
+class(5L) # "integer"
+# (Try ?class para más información en la función class().)
+# En R, cada valor único, como 5L, es considerado un vector de logitud 1
+length(5L) # 1
+# También puedes tener un vector de enteros con longitud > 1:
+c(4L, 5L, 8L, 3L) # 4 5 8 3
+length(c(4L, 5L, 8L, 3L)) # 4
+class(c(4L, 5L, 8L, 3L)) # "integer"
+
+# NUMÉRICOS
+# Un "numérico" es un número de punto flotante de doble precisión.
+5 # 5
+class(5) # "numeric"
+# Nuevamente, todo en R es un vector;
+# puedes hacer un vector numérico con más de un elemento
+c(3,3,3,2,2,1) # 3 3 3 2 2 1
+# También puedes utilizar el notación científica
+5e4 # 50000
+6.02e23 # Número de Avogadro
+1.6e-35 # Logintud Planck
+# También puedes tener números infinitamente grandes o pequeños
+class(Inf) # "numeric"
+class(-Inf) # "numeric"
+# Puede que uses "Inf", por ejemplo, en integrate(dnorm, 3, Inf);
+# esto obvia las tablas de puntos Z.
+
+# ARITMÉTICA BÁSICA
+# Puedes hacer aritmética con números
+# Haciendo aritmética en un mix de enteros y numéricos, te da otro numérico
+10L + 66L # 76 # entero mas entero da entero
+53.2 - 4 # 49.2 # entero menos entero da numérico
+2.0 * 2L # 4 # numérico veces entero da numérico
+3L / 4 # 0.75 # entero sobre numérico da numérico
+3 %% 2 # 1 # el residuo de dos numéricos es otro numérico
+# La aritmética ilegal rinde un "not-a-number"
+0 / 0 # NaN
+class(NaN) # "numeric"
+# Puedes hacer aritmética con dos vectores con longitud mayor a 1,
+# siempre que la longitud del vector mayor es un entero múltiplo del menor.
+c(1,2,3) + c(1,2,3) # 2 4 6
+
+# CARACTERES
+# No hay diferencia entre strings y caracteres en R
+"Horatio" # "Horatio"
+class("Horatio") # "character"
+class('H') # "character"
+# Ambos eran vectores de caracteres de longitud 1
+# Aquí hay uno más largo:
+c('alef', 'bet', 'gimmel', 'dalet', 'he')
+# =>
+# "alef" "bet" "gimmel" "dalet" "he"
+length(c("Call","me","Ishmael")) # 3
+# Puedes hacer operaciones regex en vectores de caracteres:
+substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis "
+gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis."
+# R tiene varios vectores predefinidos de caracteres
+letters
+# =>
+# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
+# [20] "t" "u" "v" "w" "x" "y" "z"
+month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
+
+# LÓGICOS
+# En R, un "logical" es un boolean
+class(TRUE) # "logical"
+class(FALSE) # "logical"
+# Ese comportamiento es normal
+TRUE == TRUE # TRUE
+TRUE == FALSE # FALSE
+FALSE != FALSE # FALSE
+FALSE != TRUE # TRUE
+# El dato faltante (NA) es lógico también
+class(NA) # "logical"
+# Utiliza | y & para operaciones lógicas
+# OR
+TRUE | FALSE # TRUE
+# AND
+TRUE & FALSE # FALSE
+# Puedes probar si x es TRUE (verdadero)
+isTRUE(TRUE) # TRUE
+# Aquí tenemos un vector lógico con varios elementos:
+c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE
+c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE
+
+# FACTORES
+# La clase factor es para datos de categoría
+# Los factores pueden ser ordenados (como las calificaciones de los niños)
+# o sin orden (como el género)
+factor(c("female", "female", "male", NA, "female"))
+# female female male <NA> female
+# Levels: female male
+# Los "levels" son los valores que los datos categóricos pueden tener
+# Tomar nota que los datos faltantes no entran a los niveles
+levels(factor(c("male", "male", "female", NA, "female"))) # "female" "male"
+# Si un vector de factores tiene longitud 1, sus niveles también tendrán
+# una longitud de 1 también
+
+length(factor("male")) # 1
+length(levels(factor("male"))) # 1
+# Los factores son comúnmente vistos en marcos de dato, y una estructura de
+# datos que cubriremos después
+data(infert) # "Infertility after Spontaneous and Induced Abortion"
+levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs"
+
+# NULL
+# "NULL" es uno raro; utilízalo para "limpiar" un vector
+class(NULL) # NULL
+parakeet = c("beak", "feathers", "wings", "eyes")
+parakeet
+# =>
+# [1] "beak" "feathers" "wings" "eyes"
+parakeet <- NULL
+parakeet
+# =>
+# NULL
+
+# COERCIÓN DE TIPO
+# La coerción de tipos es cuando forzas un valor diferente tipo al que puede tomar.
+as.character(c(6, 8)) # "6" "8"
+as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE
+# Si pones elementos de diferentes tipos en un vector, coerciones raras pasan:
+c(TRUE, 4) # 1 4
+c("dog", TRUE, 4) # "dog" "TRUE" "4"
+as.numeric("Bilbo")
+# =>
+# [1] NA
+# Warning message:
+# NAs introduced by coercion
+
+# También tomar nota: Esos solo eran datos de tipos básicos
+# Hay mucho más tipos de datos, como las fechas, series de tiempo, etc.
+
+
+##################################################
+# Variables, ciclos, condiciones (if/else)
+##################################################
+
+# A variable is like a box you store a value in for later use.
+# We call this "assigning" the value to the variable.
+# Having variables lets us write loops, functions, and if/else statements
+
+# VARIABLES
+# Muchas maneras de asignar valores:
+x = 5 # esto es posible
+y <- "1" # esto es preferido
+TRUE -> z # estos funciona pero es raro
+
+# CICLOS
+# Tenemos ciclos 'for'
+for (i in 1:4) {
+ print(i)
+}
+# Tenemos ciclos 'while'
+a <- 10
+while (a > 4) {
+ cat(a, "...", sep = "")
+ a <- a - 1
+}
+# Ten en mente que los ciclos 'for' y 'while' son lentos en R
+# Operaciones con vectores enteros (i.e. una fila o columna completa)
+# o tipos de función apply() (que discutiremos después) son preferidos
+
+# CONDICIONES (IF/ELSE)
+# De nuevo, bastante normal
+if (4 > 3) {
+ print("4 is greater than 3")
+} else {
+ print("4 is not greater than 3")
+}
+# =>
+# [1] "4 is greater than 3"
+
+# FUNCIONES
+# Definidos de la siguiente manera:
+jiggle <- function(x) {
+ x = x + rnorm(1, sd=.1) #agregar un poco de ruido (controlado)
+ return(x)
+}
+# Llamados como cualquier otra función de R
+jiggle(5) # 5±ε. luego de set.seed(2716057), jiggle(5)==5.005043
+
+
+
+###########################################################################
+# Estructura de datos: Vectores, matrices, marcos da datos y arreglos
+###########################################################################
+
+# UNIDIMENSIONAL
+
+# Empecemos desde el principio, y con algo que ya conoces: vectores.
+vec <- c(8, 9, 10, 11)
+vec # 8 9 10 11
+# Preguntamos por elementos específicos poniendo un subconjunto en corchetes
+# (Toma nota de que R empieza los conteos desde 1)
+vec[1] # 8
+letters[18] # "r"
+LETTERS[13] # "M"
+month.name[9] # "September"
+c(6, 8, 7, 5, 3, 0, 9)[3] # 7
+# También podes buscar por los índices de componentes específicos,
+which(vec %% 2 == 0) # 1 3
+# obtener la primera o las últimas entradas de un vector,
+head(vec, 1) # 8
+tail(vec, 2) # 10 11
+# o averiguar si cierto valor se encuentra dentro de un vector
+any(vec == 10) # TRUE
+# Si un índice "se pasa", obtendrás un NA:
+vec[6] # NA
+# Puedes encontrar la longitud de un vector con length()
+length(vec) # 4
+# Puedes realizar operaciones con vectores enteros o con subconjuntos de vectores
+vec * 4 # 16 20 24 28
+vec[2:3] * 5 # 25 30
+any(vec[2:3] == 8) # FALSE
+# y R tiene muchas funciones pre-definidas para resumir vectores
+mean(vec) # 9.5
+var(vec) # 1.666667
+sd(vec) # 1.290994
+max(vec) # 11
+min(vec) # 8
+sum(vec) # 38
+# Otras funciones pre-definidas:
+5:15 # 5 6 7 8 9 10 11 12 13 14 15
+seq(from=0, to=31337, by=1337)
+# =>
+# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707
+# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751
+
+# BIDIMENCIONAL (TODO EN UNA CLASE)
+
+# Puedes hacer una matriz de las entradas todos de un mismo tipo como:
+mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6))
+mat
+# =>
+# [,1] [,2]
+# [1,] 1 4
+# [2,] 2 5
+# [3,] 3 6
+# A diferencia de un vector, una clase matriz es una 'matriz',
+# sin importar qué contiene
+class(mat) # => "matrix"
+# Consulta la primera fila
+mat[1,] # 1 4
+# Realiza una operación en la primera columna
+3 * mat[,1] # 3 6 9
+# Consulta por una celda específica
+mat[3,2] # 6
+
+# Transpone una matriz entera
+t(mat)
+# =>
+# [,1] [,2] [,3]
+# [1,] 1 2 3
+# [2,] 4 5 6
+
+# Multiplicación de matrices
+mat %*% t(mat)
+# =>
+# [,1] [,2] [,3]
+# [1,] 17 22 27
+# [2,] 22 29 36
+# [3,] 27 36 45
+
+# cbind() une vectores como columnas para hacer una matriz
+mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog"))
+mat2
+# =>
+# [,1] [,2]
+# [1,] "1" "dog"
+# [2,] "2" "cat"
+# [3,] "3" "bird"
+# [4,] "4" "dog"
+class(mat2) # matrix
+# De nuevo, ten en cuenta lo que sucedió
+# Debido a que las matrices deben de contener todas las entradas del mismo tipo,
+# todo fue convertido a la clase caracter
+c(class(mat2[,1]), class(mat2[,2]))
+
+# rbind() une vectores como filas para hacer una matriz
+mat3 <- rbind(c(1,2,4,5), c(6,7,0,4))
+mat3
+# =>
+# [,1] [,2] [,3] [,4]
+# [1,] 1 2 4 5
+# [2,] 6 7 0 4
+# Ah, todo es de la misma clase. No hay coerciones. Mucho mejor.
+
+# BIDIMENSIONAL (DIFERENTES CLASES)
+
+# Para columnas de tipos diferentes, utiliza un data frame
+# Esta estructura de datos es muy útil para programación estadística,
+# una versión de ésta fue agregada a Python en el paquete "pandas".
+
+students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"),
+ c(3,2,2,1,0,-1),
+ c("H", "G", "G", "R", "S", "G"))
+names(students) <- c("name", "year", "house") # name the columns
+class(students) # "data.frame"
+students
+# =>
+# name year house
+# 1 Cedric 3 H
+# 2 Fred 2 G
+# 3 George 2 G
+# 4 Cho 1 R
+# 5 Draco 0 S
+# 6 Ginny -1 G
+class(students$year) # "numeric"
+class(students[,3]) # "factor"
+# encontrar las dimensiones
+nrow(students) # 6
+ncol(students) # 3
+dim(students) # 6 3
+# La función data.frame() convierte vectores de caracteres en vectores
+# de factores por defecto; deshabilita este atributo
+# stringsAsFactors = FALSE cuando vayas a crear el data.frame
+?data.frame
+
+# Hay otras formas de hacer subconjuntos de data frames
+students$year # 3 2 2 1 0 -1
+students[,2] # 3 2 2 1 0 -1
+students[,"year"] # 3 2 2 1 0 -1
+
+# Una versión aumentada de la estructura data.frame es el data.table
+# Si estás trabajando huge o panel data, o necesitas unificar algunos
+# subconjuntos de datos, data.table puede ser una buena elección.
+# Aquí un tour:
+install.packages("data.table") # Descarga el paquete de CRAN
+require(data.table) # Cárgalo
+students <- as.data.table(students)
+students # Tomar en cuenta la diferencia de la impresión
+# =>
+# name year house
+# 1: Cedric 3 H
+# 2: Fred 2 G
+# 3: George 2 G
+# 4: Cho 1 R
+# 5: Draco 0 S
+# 6: Ginny -1 G
+students[name=="Ginny"] # obtener filas con name == "Ginny"
+# =>
+# name year house
+# 1: Ginny -1 G
+students[year==2] # obtener filas con year == 2
+# =>
+# name year house
+# 1: Fred 2 G
+# 2: George 2 G
+# data.table hace que la unificación de dos sets de datos sea fácil
+# Hagamos otro data.table para unifiar a los estudiantes
+founders <- data.table(house=c("G","H","R","S"),
+ founder=c("Godric","Helga","Rowena","Salazar"))
+founders
+# =>
+# house founder
+# 1: G Godric
+# 2: H Helga
+# 3: R Rowena
+# 4: S Salazar
+setkey(students, house)
+setkey(founders, house)
+students <- founders[students] # Unifica los dos sets de datos comparando "house"
+setnames(students, c("house","houseFounderName","studentName","year"))
+students[,order(c("name","year","house","houseFounderName")), with=F]
+# =>
+# studentName year house houseFounderName
+# 1: Fred 2 G Godric
+# 2: George 2 G Godric
+# 3: Ginny -1 G Godric
+# 4: Cedric 3 H Helga
+# 5: Cho 1 R Rowena
+# 6: Draco 0 S Salazar
+
+# data.table hace que sea fácil obtener resúmenes de las tablas
+students[,sum(year),by=house]
+# =>
+# house V1
+# 1: G 3
+# 2: H 3
+# 3: R 1
+# 4: S 0
+
+# Para eliminar una columna de un data.frame o data.table,
+# asignarle el valor NULL.
+students$houseFounderName <- NULL
+students
+# =>
+# studentName year house
+# 1: Fred 2 G
+# 2: George 2 G
+# 3: Ginny -1 G
+# 4: Cedric 3 H
+# 5: Cho 1 R
+# 6: Draco 0 S
+
+# Elimina una fila poniendo un subconjunto
+# Usando data.table:
+students[studentName != "Draco"]
+# =>
+# house studentName year
+# 1: G Fred 2
+# 2: G George 2
+# 3: G Ginny -1
+# 4: H Cedric 3
+# 5: R Cho 1
+# Usando data.frame:
+students <- as.data.frame(students)
+students[students$house != "G",]
+# =>
+# house houseFounderName studentName year
+# 4 H Helga Cedric 3
+# 5 R Rowena Cho 1
+# 6 S Salazar Draco 0
+
+# MULTI-DIMENSIONAL (TODOS LOS ELEMENTOS DE UN TIPO)
+
+# Arreglos crean una tabla de dimensión n
+# Todos los elementos deben de ser del mismo tipo
+# Puedes hacer una tabla bi-dimensional (como una matriz)
+array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4))
+# =>
+# [,1] [,2] [,3] [,4]
+# [1,] 1 4 8 3
+# [2,] 2 5 9 6
+# Puedes utilizar un arreglo para hacer una matriz tri-dimensional también
+array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2))
+# =>
+# , , 1
+#
+# [,1] [,2]
+# [1,] 2 8
+# [2,] 300 9
+# [3,] 4 0
+#
+# , , 2
+#
+# [,1] [,2]
+# [1,] 5 66
+# [2,] 60 7
+# [3,] 0 847
+
+# LISTAS (MULTI-DIMENSIONAL, POSIBLEMENTE DESIGUALES, DE DIFERENTES TIPOS)
+
+# Finalmente, R tiene listas (de vectores)
+list1 <- list(time = 1:40)
+list1$price = c(rnorm(40,.5*list1$time,4)) # aleatorio
+list1
+# Puedes obtener elementos de una lista de la siguiente manera
+list1$time # Una manera
+list1[["time"]] # Otra manera
+list1[[1]] # Y otra manera
+# =>
+# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
+# [34] 34 35 36 37 38 39 40
+# Puedes crear una lista de subconjuntos como cualquier otro vector
+list1$price[4]
+
+# Las listas no son la estructura de datos más eficiente para trabajar en R;
+# a menos de que tengas una buena razón, deberías de quedarte con data.frames
+# Las listas son usualmente devueltas por funciones que realizan regresiones
+# lineales
+
+##################################################
+# La familia de funciones apply()
+##################################################
+
+# Te recuerdas de mat?
+mat
+# =>
+# [,1] [,2]
+# [1,] 1 4
+# [2,] 2 5
+# [3,] 3 6
+# Utiliza apply(X, MARGIN, FUN) paraaplicar una función FUN a la matriz X
+# sobre las filas (MAR = 1) o las columnas (MAR = 2)
+# Eso es, R aplica FUN sobre cada fila (o columna) de X, mucho más rápido que
+# lo que haría un ciclo 'for' o 'loop'
+apply(mat, MAR = 2, jiggle)
+# =>
+# [,1] [,2]
+# [1,] 3 15
+# [2,] 7 19
+# [3,] 11 23
+# Otras funciones: ?lapply, ?sapply
+
+# No te sientas muy intimidado; todos están de acuerdo que son confusas
+
+# El paquete plyr busca reemplazar (y mejorar) la familiar *apply()
+install.packages("plyr")
+require(plyr)
+?plyr
+
+
+
+#########################
+# Carga de datos
+#########################
+
+# "pets.csv" es un archivo en internet
+# (pero puede ser tan fácil como tener el archivo en tu computadora)
+pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv")
+pets
+head(pets, 2) # primeras dos filas
+tail(pets, 1) # última fila
+
+# Para guardar un data frame o una matriz como un archivo .csv
+write.csv(pets, "pets2.csv") # para hacer un nuevo archivo .csv
+# definir el directorio de trabajo con setwd(), búscalo con getwd()
+
+# Prueba ?read.csv ?write.csv para más información
+
+
+#########################
+# Gráficas
+#########################
+
+# FUNCIONES PREDEFINIDAS DE GRAFICACIÓN
+# Gráficos de dispersión!
+plot(list1$time, list1$price, main = "fake data")
+# Regresiones!
+linearModel <- lm(price ~ time, data = list1)
+linearModel # Muestra el resultado de la regresión
+# Grafica la línea de regresión
+abline(linearModel, col = "red")
+# Obtiene una veridad de diagnósticos
+plot(linearModel)
+# Histogramas!
+hist(rpois(n = 10000, lambda = 5), col = "thistle")
+# Barras!
+barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow"))
+
+# GGPLOT2
+# Pero éstas no son las gráficas más bonitas de R
+# Prueba el paquete ggplot2 para mayor variedad y mejores gráficas
+install.packages("ggplot2")
+require(ggplot2)
+?ggplot2
+pp <- ggplot(students, aes(x=house))
+pp + geom_histogram()
+ll <- as.data.table(list1)
+pp <- ggplot(ll, aes(x=time,price))
+pp + geom_point()
+# ggplot2 tiene una excelente documentación
+# (disponible en http://docs.ggplot2.org/current/)
+
+
+
+```
+
+## ¿Cómo obtengo R?
+
+* Obtén R y R GUI de [http://www.r-project.org/](http://www.r-project.org/)
+* [RStudio](http://www.rstudio.com/ide/) es otro GUI
diff --git a/es-es/rust-es.html.markdown b/es-es/rust-es.html.markdown
new file mode 100644
index 00000000..b43cb815
--- /dev/null
+++ b/es-es/rust-es.html.markdown
@@ -0,0 +1,324 @@
+---
+language: rust
+contributors:
+ - ["P1start", "http://p1start.github.io/"]
+translators:
+ - ["Razican", "https://www.razican.com/"]
+filename: learnrust-es.rs
+lang: es-es
+---
+
+Rust es un lenguaje de programación desarrollado por Mozzilla Research. Rust
+combina el control del rendimiento a bajo nivel con la comodidad del alto nivel
+y garantías de seguridad.
+
+Consigue cumplir estos objetivos sin necesidad de un recolector de basura o
+runtime, haciendo posible usar las librerías de Rust como sustituto de C.
+
+La primera versión de Rust, la 0.1, fue lanzada en enero de 2012, y durante 3
+años el desarrollo fue tan rápido que hasta hace poco el uso de las versiones
+estables no era recomendable, y se aconsejaba usar las compilaciones nocturnas.
+
+El 15 de mayo de 2015 se lanzó Rust 1.0, con una garantía completa de
+retrocompatibilidad. A día de hoy los tiempos de compilación han mejorado mucho
+desde ese lanzamiento, así como otros aspectos del lenguaje y el compilador.
+Rust ha adoptado un modelo de desarrollo por series de publicaciones periódicas,
+con lanzamientos cada 6 semanas. Junto con cada lanzamiento, se lanza la beta de
+la siguiente versión.
+
+A pesar de que Rust es un lenguaje relativamente de bajo nivel, tiene conceptos
+funcionales que generalmente se encuentran en lenguajes de más alto nivel. Esto
+hace que Rust sea rápido y al mismo tiempo fácil y eficiente a la hora de
+programar.
+
+```rust
+// Esto es un comentario. Los comentarios de una sola línea se hacen así...
+/* ...y los de múltiples líneas así */
+
+//////////////////////////
+// 1. Conceptos básicos //
+//////////////////////////
+
+// Funciones
+// `i32` es el tipo para enteros de 32 bits con signo
+fn suma2(x: i32, y: i32) -> i32 {
+ // Retorno implícito (sin punto y coma)
+ x + y
+}
+
+// Función principal
+fn main() {
+ // N;umeros //
+
+ // Bindings (variables) inmutables
+ let x: i32 = 1;
+
+ // Sufijos para enteros / floats
+ let y: i32 = 13i32;
+ let f: f64 = 1.3f64;
+
+ // Inferencia de tipos
+ // La mayor parte del tiempo, el compilador de Rust puede inferir el tipo de
+ // una variable, por lo que no necesitas escribir una anotación de tipo
+ // explícita. A lo largo de este tutorial, los tipos están anotados
+ // explícitamente en varios sitios, pero solo con propósito demostrativo. La
+ // inferencia de tipos puede manejar esto por ti la mayor parte del tiempo.
+ let x_implicita = 1;
+ let f_implicita = 1.3;
+
+ // Aritmética
+ let sum = x + y + 13;
+
+ // Variable mutable
+ let mut mutable = 1;
+ mutable = 4;
+ mutable += 2;
+
+ // Strings (cadenas de caracteres) //
+
+ // Strings literales
+ let x: &str = "hola mundo!";
+
+ // Impresión por consola
+ println!("{} {}", f, x); // 1.3 hola mundo!
+
+ // Un `String` – una cadena en memoria dinámica (heap)
+ let s: String = "hola mundo".to_string();
+
+ // Una porión de cadena (slice) – una vista inmutable a otra cadena
+ // Esto es básicamente un puntero inmutable a un string string – en realidad
+ // no contiene los caracteres de la cadena, solo un puntero a algo que los
+ // tiene (en este caso, `s`)
+ let s_slice: &str = &s;
+
+ println!("{} {}", s, s_slice); // hola mundo hola mundo
+
+ // Vectores/arrays //
+
+ // A fixed-size array
+ let cuatro_enteros: [i32; 4] = [1, 2, 3, 4];
+
+ // Un array dinámico (vector)
+ let mut vector: Vec<i32> = vec![1, 2, 3, 4];
+ vector.push(5);
+
+ // Una porción (slice) – una vista inmutable a un vector o array
+ // Esto es parecido a un slice de un string, pero para vectores
+ let slice: &[i32] = &vector;
+
+ // Usa `{:?}` para imprimir algo en estilo debug
+ println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
+
+ // Tuplas //
+
+ // Una tupla es un conjunto de tamaño fijo de valores. Pueden ser de diferente tipo.
+ let x: (i32, &str, f64) = (1, "hola", 3.4);
+
+ // Desestructurando `let`
+ let (a, b, c) = x;
+ println!("{} {} {}", a, b, c); // 1 hola 3.4
+
+ // Indexando
+ println!("{}", x.1); // hola
+
+ //////////////
+ // 2. Tipos //
+ //////////////
+
+ // Estructuras
+ struct Punto {
+ x: i32,
+ y: i32,
+ }
+
+ let origen: Punto = Punto { x: 0, y: 0 };
+
+ // Una estructura con campos sin nombre, una ‘estructura de tupla’
+ struct Punto2(i32, i32);
+
+ let origen2 = Punto2(0, 0);
+
+ // Enums básicos como en C
+ enum Direccion {
+ Izquierda,
+ Derecha,
+ Arriba,
+ Abajo,
+ }
+
+ let arriba = Direccion::Arriba;
+
+ // Enum con campos
+ enum OpcionalI32 {
+ UnI32(i32),
+ Nada,
+ }
+
+ let dos: OpcionalI32 = OpcionalI32::UnI32(2);
+ let nada = OpcionalI32::Nada;
+
+ // Genéricos //
+
+ struct Foo<T> { bar: T }
+
+ // Esto está definido en la librería estándar como `Option`
+ enum Opcional<T> {
+ AlgunVal(T),
+ SinVal,
+ }
+
+ // Métodos //
+
+ impl<T> Foo<T> {
+ // Los métodos reciben un parámetro explícito `self`
+ fn get_bar(self) -> T {
+ self.bar
+ }
+ }
+
+ let un_foo = Foo { bar: 1 };
+ println!("{}", un_foo.get_bar()); // 1
+
+ // Traits (conocidos como interfaces o typeclasses en otros lenguajes) //
+
+ trait Frobnicate<T> {
+ fn frobnicate(self) -> Option<T>;
+ }
+
+ impl<T> Frobnicate<T> for Foo<T> {
+ fn frobnicate(self) -> Option<T> {
+ Some(self.bar)
+ }
+ }
+
+ let otro_foo = Foo { bar: 1 };
+ println!("{:?}", otro_foo.frobnicate()); // Some(1)
+
+ /////////////////////////////////
+ // 3. Comparación con patrones //
+ /////////////////////////////////
+
+ let foo = OpcionalI32::UnI32(1);
+ match foo {
+ OpcionalI32::UnI32(n) => println!("es un i32: {}", n),
+ OpcionalI32::Nada => println!("no es nada!"),
+ }
+
+ // comparación de patrones avanzada
+ struct FooBar { x: i32, y: OpcionalI32 }
+ let bar = FooBar { x: 15, y: OpcionalI32::UnI32(32) };
+
+ match bar {
+ FooBar { x: 0, y: OpcionalI32::UnI32(0) } =>
+ println!("Los números son cero!"),
+ FooBar { x: n, y: OpcionalI32::UnI32(m) } if n == m =>
+ println!("Los números son iguales"),
+ FooBar { x: n, y: OpcionalI32::UnI32(m) } =>
+ println!("Números diferentes: {} {}", n, m),
+ FooBar { x: _, y: OpcionalI32::Nada } =>
+ println!("El segudo número no es nada!"),
+ }
+
+ /////////////////////////
+ // 4. Flujo de control //
+ /////////////////////////
+
+ // bucles `for`
+ let array = [1, 2, 3];
+ for i in array.iter() {
+ println!("{}", i);
+ }
+
+ // Rangos
+ for i in 0u32..10 {
+ print!("{} ", i);
+ }
+ println!("");
+ // imprime `0 1 2 3 4 5 6 7 8 9 `
+
+ // `if`
+ if 1 == 1 {
+ println!("Las matemáticas funcionan!");
+ } else {
+ println!("Oh no...");
+ }
+
+ // `if` como una expresión
+ let valor = if true {
+ "bueno"
+ } else {
+ "malo"
+ };
+
+ // bucle `while`
+ while 1 == 1 {
+ println!("El universo está funcionando correctamente.");
+ }
+
+ // Bucle infinito
+ loop {
+ println!("Hola!");
+ }
+
+ ////////////////////////////////////////
+ // 5. Seguridad de memoria y punteros //
+ ////////////////////////////////////////
+
+ // Posesión de punteros – solo uno puede ‘poseer’ un puntero en cada momento
+ // Esto significa que cuando la `Box` queda fuera del ámbito, puede ser
+ // liberada automáticamente de manera segura.
+ let mut mio: Box<i32> = Box::new(3);
+ *mio = 5; // dereferenciar
+ // Aquí, `ahora_es_mio`, toma posesión de `mio`. En otras palabras, `mio` se
+ // mueve.
+ let mut ahora_es_mio = mio;
+ *ahora_es_mio += 2;
+
+ println!("{}", ahora_es_mio); // 7
+ // println!("{}", mio); // esto no compilaría, porque `now_its_mine` es el
+ // que posee el puntero
+
+ // Referencia – un puntero inmutable que referencia a otro dato
+ // Cuando se crea una referencia a un valor, decimos que el valor ha sido
+ // ‘tomado prestado’.
+ // Mientras un valor está prestado como inmutable, no puede ser modificado o
+ // movido.
+ // Una prestación dura hasta el fin del ámbito en el que se creó.
+ let mut var = 4;
+ var = 3;
+ let ref_var: &i32 = &var;
+
+ println!("{}", var); // A diferencia de `mio`, `var` se puede seguir usando
+ println!("{}", *ref_var);
+ // var = 5; // esto no compilaría, porque `var` está prestada
+ // *ref_var = 6; // esto tampoco, porque `ref_var` es una referencia
+ // inmutable
+
+ // Referencia mutable
+ // Mientras que un valor está prestado como mutable, no puede ser accedido
+ // desde ningún otro sitio.
+ let mut var2 = 4;
+ let ref_var2: &mut i32 = &mut var2;
+ *ref_var2 += 2; // '*' se usa para apuntar al var2 prestado como mutable
+
+ println!("{}", *ref_var2); // 6 , //var2 no compilaría. //ref_var2 es de
+ // tipo &mut i32, por lo que guarda una
+ // referencia a un i32 no el valor.
+ // var2 = 2; // esto no compilaría porque `var2` está prestado
+}
+```
+
+## Lectura adicional
+
+Rust es mucho más que esto. Esto es solo lo más básico para que puedas entender
+las cosas más importantes. Para aprender más sobre Rust, lee [The Rust
+Programming Language](http://doc.rust-lang.org/book/index.html) y echa un
+vistazo al subreddit [/r/rust](http://reddit.com/r/rust). Los compañeros en el
+canal #rust en irc.mozilla.org también son muy buenos con los recien llegados.
+También puedes acceder a [Rust users](https://users.rust-lang.org/) a pedir
+ayuda o a [Rust internals](https://internals.rust-lang.org/) para aprender más
+sobre el lenguaje y colaborar en su desarrollo.
+
+También puedes probar Rust con un compilador online en el oficial [Rust
+playpen](http://play.rust-lang.org) o en la [web principal de
+Rust](http://rust-lang.org).
diff --git a/es-es/yaml-es.html.markdown b/es-es/yaml-es.html.markdown
index a5157b5d..cd3143fb 100644
--- a/es-es/yaml-es.html.markdown
+++ b/es-es/yaml-es.html.markdown
@@ -4,6 +4,7 @@ lang: es-es
filename: learnyaml-es.yaml
contributors:
- ["Adam Brenecki", "https://github.com/adambrenecki"]
+ - ["Everardo Medina","https://github.com/everblut"]
translators:
- ["Daniel Zendejas","https://github.com/DanielZendejas"]
---
@@ -14,7 +15,7 @@ leído y escrito por humanos.
Basa su funcionalidad en JSON, con la adición de líneas nuevas
e indentación inspirada en Python. A diferencia de Python, YAML
-no permite tabs literales.
+no permite tabulaciones literales.
```yaml
# Los comentarios en YAML se ven así.
@@ -38,97 +39,177 @@ llave con espacios: valor
llave: "Un string, entre comillas."
"Las llaves tambien pueden estar entre comillas.": "valor entre comillas"
-# Los strings de líneas múltiples pueden ser escritos
+# Los strings de líneas múltiples pueden ser escritos
# como un 'bloque literal' (usando pipes |)
# o como un 'bloque doblado' (usando >)
bloque_literal: |
Este bloque completo de texto será preservado como el valor de la llave
'bloque_literal', incluyendo los saltos de línea.
-
- Se continúa guardando la literal hasta que se cese la indentación.
+
+ Se continúa guardando la literal hasta que se cese la indentación.
Cualquier línea que tenga más indentación, mantendrá los espacios dados
(por ejemplo, estas líneas se guardarán con cuatro espacios)
-nloque_doblado: >
+bloque_doblado: >
De la misma forma que el valor de 'bloque_literal', todas estas
líneas se guardarán como una sola literal, pero en esta ocasión todos los
saltos de línea serán reemplazados por espacio.
- Las líneas en blanco, como la anterior, son convertidos a un salto de línea.
+ Las líneas en blanco, como la anterior, son convertidas a un salto de línea.
Las líneas con mayor indentación guardan sus saltos de línea.
Esta literal ocuparán dos líneas.
-########################
-# TIPOS DE COLECCIONES #
-########################
-
-# La indentación se usa para anidar.
+# La indentación se usa para anidar elementos
un_mapa_indentado:
llave: valor
otra_llave: otro valor
otro_mapa_indentado:
llave_interna: valor_interno
-# Las llaves de los mapas no deben ser strings necesariamente
+# Las llaves de los mapas no requieren ser strings necesariamente
0.25: una llave numérica
-# Las llaves también pueden ser objetos de multi línea, usando ? para indicar
-# el inicio de una llave
+# Las llaves también pueden ser objetos de multiples líneas,
+# usando ? para indicar el inicio de una llave
? |
Esto es una llave
que tiene múltiples líneas
: y este es su valor
-# YAML tambien permite colecciones como llaves, pero muchos lenguajes de
+########################
+# TIPOS DE COLECCIONES #
+########################
+
+# Las colecciones en YAML usan la indentación para delimitar el alcance
+# y cada elemento de la colección inicia en su propia línea.
+# YAML tambien permite colecciones como llaves, pero muchos lenguajes de
# programación se quejarán.
# Las secuencias (equivalentes a listas o arreglos) se ven así:
-una_secuencia:
- - Item 1
- - Item 2
- - 0.5 # las secuencias pueden tener distintos tipos en su contenido.
- - Item 4
- - llave: valor
- otra_llave: otro_valor
+- Amarillo
+- Verde
+- Azul
+
+# Se puede usar una secuencia como valor para una llave.
+secuencia:
+ - Elemento 1
+ - Elemento 2
+ - Elemento 3
+ - Elemento 4
+
+# Las secuencias pueden contener secuencias como elementos.
+- [Uno, Dos, Tres]
+- [Domingo, Lunes, Martes]
+- [Luna, Marte, Tierra]
+
+# Las secuencias pueden tener distintos tipos en su contenido.
+secuencia_combinada:
+ - texto
+ - 5
+ - 0.6
+ - llave: valor # se convierte en un json dentro de la secuencia
-
- Esta es una secuencia
- ...dentro de otra secuencia
-# Dado que todo JSON está incluído dentro de YAML, también puedes escribir
-# mapas con la sintaxis de JSON y secuencias:
-mapa_de_json: {"llave": "valor"}
-secuencia_de_json: [3, 2, 1, "despegue"]
+# Dado que todo JSON está incluído dentro de YAML, también puedes escribir
+# mapas con la sintaxis de JSON y secuencias:
+mapa_de_json_1: {"llave": "valor"}
+mapa_de_json_2:
+ llave: valor
+
+# Las secuencias tambien se pueden escribir como un arreglo al estilo JSON
+secuencia_de_json_1: [3, 2, 1, "despegue"]
+secuencia_de_json_2:
+ - 3
+ - 2
+ - 1
+ - "despegue"
+
+# YAML también soporta conjuntos usando el simbolo ?
+# y se ven de la siguiente forma:
+set:
+ ? item1
+ ? item2
+ ? item3
+
+# Se puede usar el tag !!set
+# Al igual que Python, los conjuntos sólo son mapas con valores nulos.
+# El ejemplo de arriba es equivalente a:
+set2:
+ item1: null
+ item2: null
+ item3: null
##################################
# CARACTERÍSTICAS EXTRAS DE YAML #
##################################
+# YAML usa tres guiones (---) para diferenciar entre directivas
+# y contenido del documento.
+# Por otra parte, tres puntos (...) se utilizan para indicar
+# el final del documento en casos especiales.
+
# YAML tiene funciones útiles llamadas 'anchors' (anclas), que te permiten
-# duplicar fácilmente contenido a lo largo de tu documento. En el ejemplo
-# a continuación, ambas llaves tendrán el mismo valor:
-contenido_anclado: &nombre_del_ancla Este string será el valor de las llaves
-otra_ancla: *nombre_del_ancla
-
-# YAML también tiene tags, que puedes usar para declarar tipos explícitamente.
-string_explícito: !!str 0.5
-# Algunos parseadores implementar tags específicas del lenguaje, como el
+# duplicar fácilmente contenido a lo largo de tu documento.
+# El ampersand indica la declaración del ancla,
+declara_ancla: &texto texto de la llave
+# el asterisco indica el uso de dicha ancla.
+usa_ancla: *texto # tendrá el valor "texto de la llave"
+
+################
+# TAGS EN YAML #
+################
+
+# En YAML, los nodos que no tienen un tag obtienen su tipo
+# según la aplicación que los use, al usar un tag
+# se pueden declarar tipos explícitamente.
+string_explicito: !!str 0.5 # !!str para declarar un string
+integer_explicito: !!int 5 # !!int para declarar un integer
+float_explicito: !!float 1.2 # !!float para declarar un float
+conjunto_explicito: !!set # !!set para declarar un conjunto
+ ? Uno
+ ? Dos
+ ? Tres
+mapa_ordenado_explicito: !!omap # !!omap para declarar un mapa ordenado
+- Primero: 1
+- Segundo: 2
+- Tercero: 3
+- Cuarto: 4
+
+# Tags para los numeros enteros
+llave_canonica: 5222
+llave_decimal: +5222
+llave_octal: 010
+llave_hexadecimal: 0xC
+
+#Tags para los numeros flotantes
+llave_canonica: 1.215e+3
+llave_exponencial: 12.3555e+02
+llave_fija: 12.15
+llave_negativa_infinita: -.inf
+llave_numero_invalido: .NaN
+
+# Tags para las fechas y horas
+llave_canonica: 2001-12-15T02:59:43.1Z
+llave_iso8601: 2001-12-14t21:59:43.10-05:00
+llave_con_espacios: 2001-12-14 21:59:43.10 -5
+llave_fecha: 2002-12-14
+
+# Además existen tags para
+null: #valor nulo
+booleans: [ true, false ] # Valores booleanos
+string: '012345' # Valor en string
+
+
+# Algunos parseadores implementan tags específicas del lenguaje, como el
# que se muestra a continuación, encargado de manejar números complejos en
# Python:
numero_complejo_python: !!python/complex 1+2j
-########################
-# TIPOS EXTRAS EN YAML #
-########################
-
-# Stirngs y números no son los únicos escalares que YAML puede entener.
-# YAML también puede parsear fechas en formato ISO .
-fechaHora: 2001-12-15T02:59:43.1Z
-fechaHora_con_espacios: 2001-12-14 21:59:43.10 -5
-fecha: 2002-12-14
-
-# La tag !!binary indica que un string es, en realidad, un blob
+# El tag !!binary indica que un string es en realidad un blob
# representado en base-64.
archivo_gif: !!binary |
R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
@@ -136,16 +217,10 @@ archivo_gif: !!binary |
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
-# YAML también tiene un tipo set, que se ve de la siguiente forma:
-set:
- ? item1
- ? item2
- ? item3
-
-# Al igual que Python, los sets sólo son mapas con valores nulos.
-# El ejemplo de arriba es equivalente a:
-set2:
- item1: null
- item2: null
- item3: null
```
+
+### Recursos adicionales
+
++ [Sitio oficial de YAML](http://yaml.org/)
++ [Parser en línea de de YAML](http://yaml-online-parser.appspot.com/)
++ [Validador en línea de YAML](http://codebeautify.org/yaml-validator)
diff --git a/fa-ir/brainfuck-fa.html.markdown b/fa-ir/bf-fa.html.markdown
index ef2bcba3..bc5d8dc4 100644
--- a/fa-ir/brainfuck-fa.html.markdown
+++ b/fa-ir/bf-fa.html.markdown
@@ -1,5 +1,5 @@
---
-language: brainfuck
+language: bf
contributors:
- ["Mohammad Valipour", "https://github.com/mvalipour"]
lang: fa-ir
diff --git a/fa-ir/css-fa.html.markdown b/fa-ir/css-fa.html.markdown
new file mode 100644
index 00000000..4e222eb2
--- /dev/null
+++ b/fa-ir/css-fa.html.markdown
@@ -0,0 +1,307 @@
+---
+language: css
+contributors:
+ - ["Mohammad Valipour", "https://github.com/mvalipour"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["Geoffrey Liu", "https://github.com/g-liu"]
+ - ["Connor Shea", "https://github.com/connorshea"]
+ - ["Deepanshu Utkarsh", "https://github.com/duci9y"]
+ - ["Tyler Mumford", "https://tylermumford.com"]
+translators:
+ - ["Arashk", "https://github.com/Arashk-A"]
+lang: fa-ir
+filename: learncss-fa.css
+---
+
+<p dir='rtl'>در روزهای آغازین وب هیچگونه عنصر بصری مشاهده نمیشد و محتوا به صورت متن خالی بود. </p>
+<p dir='rtl'>اما با توسعه بیشتر مرورگرها صفحات وب کاملاً تصویری نیز رایج شد</p>
+<p dir='rtl'>CSS زبان استانداردی که موجودیت آن برای حفظ جدایی بین محتوا (HTML) و نگاه و احساس از</p>
+<p dir='rtl'>صفحات وب است.</p>
+
+<p dir='rtl'>به طور خلاصه, کاری که CSS انجام میدهد ارائه نحوه ایست که شما را قادر به هدف قرار دادن</p>
+<p dir='rtl'>عناصر مختلف در یک صفحه HTML کرده و امکان اختصاص خواص متفاوت بصری به آنها را میدهد.</p>
+
+
+<p dir='rtl'>مانند هر زبانی, CSS نسخه های زیادی دارد که در اینجا توجه ما روی CSS2.0 است. با وجودی که این نسخه جدیدترین نسخه نمیباشد اما بیشترین پشتیبانی و سازگاری را در میان نسخه های مختلف را دارد</p>
+
+<p dir='rtl'><strong>توجه: </strong> برای مشاهده برخی از نتایج جلوه های تصویری CSS به منظور یادگیری بیشتر شما باید چیزهای گوناگونی در محیطی مثل [dabblet](http://dabblet.com/) امتحان کنید. توجه اصلی این مقاله روی دستورات و برخی از نکات عمومی است.</p>
+
+
+<p dir='rtl'>در CSS همه توضیحات داخل ستاره-بروم نوشته میشوند زیرا CSS دستوری برای توضیحات تک خطی مثل C ندارد</p>
+
+```CSS
+/* comments appear inside slash-asterisk, just like this line!
+ there are no "one-line comments"; this is the only comment style */
+```
+
+<p dir='rtl'>به طور کلی دستورات CSS بسیار ساده هستند که در آن یک انتخابگر (selector) عنصری را در روی صفحه هدف قرار میدهد.</p>
+
+```CSS
+selector { property: value; /* more properties...*/ }
+```
+
+<p dir='rtl'>با استفاده از ستاره می توان برای همه عناصر روی صفحه استایل تعریف کرد</p>
+
+
+```CSS
+* { color:red; }
+```
+
+<p dir='rtl'>فرض کنید عنصری مثل این بر روی صفحه قرار دارد</p>
+
+```html
+<div class='some-class class2' id='someId' attr='value' otherAttr='en-us foo bar' />
+```
+<p dir='rtl'>شما میتوانید با استفاده از نام کلاس آنرا انتخاب کنید</p>
+
+
+```CSS
+.some-class { }
+```
+
+<p dir='rtl'>یا با استفاده از نام دو کلاس</p>
+
+```CSS
+.some-class.class2 { }
+```
+
+<p dir='rtl'>یا با استفاده از نام id</p>
+
+```CSS
+#someId { }
+```
+
+<p dir='rtl'>یا با استفاده از نام خود عنصر</p>
+
+```CSS
+div { }
+```
+
+<p dir='rtl'>یا با استفاده از `attr`</p>
+
+```CSS
+[attr] { font-size:smaller; }
+```
+
+<p dir='rtl'>یا با استفاده از ارزشی که برای `attr` مشخص شده</p>
+
+```CSS
+[attr='value'] { font-size:smaller; }
+```
+
+<p dir='rtl'>با استفاده از ارزشی که برای `attr` مشخص شده و آن ارزش با `val` شروع میشود در CSS3</p>
+
+```CSS
+[attr^='val'] { font-size:smaller; }
+```
+
+<p dir='rtl'>با استفاده از ارزشی که برای `attr` مشخص شده و آن ارزش با `ue` به پایان میرسد در CSS3</p>
+
+```CSS
+[attr$='ue'] { font-size:smaller; }
+```
+
+<p dir='rtl'>یا با انتخاب بوسیله یکی از ارزشهایی که در لیست `otherAttr` بوسیله فاصله از هم جدا شده اند در CSS3</p>
+
+```CSS
+[attr$='ue'] { font-size:smaller; }
+```
+
+<p dir='rtl'>یا ارزش(`value`) دقیقاً خود ارزش(`value`) یا بوسیله `-` که یونیکد (U+002D) از حرف بعدی جدا شود</p>
+
+```CSS
+[otherAttr|='en'] { font-size:smaller; }
+```
+
+<p dir='rtl'>و مهمتر از همه اینکه میتوان آنها را ترکیب کرد. نکته مهمی که در اینجا باید مد نظر داشته باشید این است که هنگام ترکیب نباید هیچگونه فاصله ای بین آنها قرار گیرد زیرا در این حالت معنای دستور تغییر میکند</p>
+
+```CSS
+div.some-class[attr$='ue'] { }
+```
+
+<p dir='rtl'>CSS این امکان را به شما میدهد که یک عنصر را بوسیله والدین آن انتخاب کنید</p>
+<p dir='rtl'>برای مثال دستور زیر همه عناصری را که نام کلاس آنها <span dir="ltr">`.class-name`</span> و دارای پدر و مادری با این مشخصه <span dir="ltr">`div.some-parent`</span> هستند را انتخاب میکند.</p>
+
+```CSS
+div.some-parent > .class-name {}
+```
+
+
+<p dir='rtl'>یا دستور زیر که همه عناصری را که نام کلاس آنها <span dir="ltr">`.class-name`</span> و داخل عنصری با مشخصه <span dir="ltr">`div.some-parent`</span> هستند را در هر عمقی که باشند (یعنی فرزندی از فرزندان <span dir="ltr">`div.some-parent`</span><span dir="ltr"> باشند) انتخاب میکند.</p>
+
+```CSS
+div.some-parent .class-name {}
+```
+
+<p dir='rtl'>نکته ای که در اینجا باید به آن توجه کنید این است که این رستور با فاصله ای بین نام دو کلاس همراه است و با مثال زیر که در بالا هم ذکر شد تفاوت دارد.</p>
+
+```CSS
+div.some-parent.class-name {}
+```
+
+<p dir='rtl'>دستور زیر همه عناصری را که نام کلاس آنها <span dir="ltr">`.this-element`</span> و بلافاصله بعد از عنصری با مشخصه <span dir="ltr">`.i-am-before`</span> قرار دارد را انتخاب میکند.</p>
+
+```CSS
+.i-am-before + .this-element { }
+```
+
+<p dir='rtl'>هر خواهر یا برادری که بعد از <span dir="ltr">`.i-am-before`</span> بیاید در اینجا لازم نیست بلافاصله بعد از هم قرار بگیرند ولی باید دارای پدر و مادری یکسان باشند.</p>
+
+```CSS
+.i-am-any-before ~ .this-element {}
+```
+<p dir='rtl'>در زیر چند نمونه از شبه کلاسها را معرفی میکنیم که به شما اجازه میدهد عناصر را بر اساس رفتار آنها در صفحه انتخاب کنید.</p>
+<p dir='rtl'>برای مثال زمانی که اشاره گر ماوس روی عنصری بر روی صفحه قرار دارد.</p>
+
+```CSS
+selector:hover {}
+```
+
+<p dir='rtl'>یا زمانی از یک لینک بازید کردید.</p>
+
+```CSS
+selected:visited {}
+```
+
+<p dir='rtl'>یا زمانی از لینکی بازید نشده است.</p>
+
+```CSS
+selected:link {}
+```
+
+<p dir='rtl'>یا زمانی که روی یک عنصر ورودی متمرکز شده.</p>
+
+```CSS
+selected:focus {}
+```
+
+<h3 dir='rtl'>واحدها</h3>
+
+```CSS
+selector {
+
+ /* واحدها اندازه */
+ width: 50%; /* در اساس درصد */
+ font-size: 2em; /* بر اساس اندازه font-size یعنی دو برابر اندازه فونت فعلی */
+ width: 200px; /* بر اساس پیکسل */
+ font-size: 20pt; /* بر اساس points (نکات) */
+ width: 5cm; /* بر اساس سانتیمتر */
+ min-width: 50mm; /* بر اساس میلیمتر */
+ max-width: 5in; /* بر اساس اینچ. max-(width|height) */
+ height: 0.2vh; /* بر اساس ارتفاع دید `vh = نسبت به 1٪ از ارتفاع دید` (CSS3) */
+ width: 0.4vw; /* بر اساس عرض دید `vw = نسبت به 1٪ از عرض دید` (CSS3) */
+ min-height: 0.1vmin; /* بر اساس کوچکترین مقدار از ارتفاع یا عرض دید (CSS3) */
+ max-width: 0.3vmax; /* مانند مثال بالا برای بیشترین مقدار (CSS3) */
+
+ /* رنگها */
+ background-color: #F6E; /* بر اساس short hex */
+ background-color: #F262E2; /* بر اساس long hex format */
+ background-color: tomato; /* بر اساس نام رنگ */
+ background-color: rgb(255, 255, 255); /* بر اساس rgb */
+ background-color: rgb(10%, 20%, 50%); /* بر اساس درصد rgb , (rgb percent) */
+ background-color: rgba(255, 0, 0, 0.3); /* بر اساس rgba (نیمه شفاف) , (semi-transparent rgb) (CSS3) */
+ background-color: transparent; /* شفاف */
+ background-color: hsl(0, 100%, 50%); /* بر اساس hsl format (CSS3). */
+ background-color: hsla(0, 100%, 50%, 0.3); /* بر اساس hsla ,مثل RGBAکه میتوان شفافیت را در آخر انتخاب کرد (CSS3) */
+
+
+ /* عکسها */
+ background-image: url(/path-to-image/image.jpg); /* گذاشتن نقل قول داخل url() اختیاری است*/
+
+ /* فونتها */
+ font-family: Arial;
+ font-family: "Courier New"; /* اگر اسم فونت با فاصله همراه باشد باید داخل نقل قول یک یا دو نوشته شود */
+ font-family: "Courier New", Trebuchet, Arial, sans-serif; /* اگر فونت اولی پیدا نشد مرورگر به سراغ نام بعدی میرود */
+}
+```
+
+<h2 dir='rtl'>نحوه استفاده</h2>
+
+<p dir='rtl'>هر دستور CSS را که می خواهید در فایلی با پسوند <span dir="ltr">.css</span> ذخیره کنید </p>
+<p dir='rtl'>حالا با استفاده از کد زیر آنرا در قسمت `head` داخل فایل html خود تعریف کنید </p>
+
+```html
+<link rel='stylesheet' type='text/css' href='path/to/style.css' />
+```
+
+<p dir='rtl'>یا میتوان با استفاده از تگ `style` درون `head` دستورات CSS را به صورت درون برنامه ای تعریف کرد اما توسیه میشود تا جای ممکن از این کار اجتناب کنید. </p>
+
+```html
+<style>
+ a { color: purple; }
+</style>
+```
+
+<p dir='rtl'>همچنین شما میتوانید دستورات CSS را به عنوان یک مشخصه برای عنصر تعریف کنید ولی تا جای ممکن باید از این کار اجتناب کنید.</p>
+
+```html
+<div style="border: 1px solid red;">
+</div>
+```
+
+<h2 dir='rtl'>حق تقدم یا اولویت</h2>
+
+<p dir='rtl'>همانگونه که مشاهده کردید یک مشخصه می تواند به وسیله چندین انتخابگر انتخاب گردد.</p>
+<p dir='rtl'>و همچنین یک ویژگی میتواند چندین بار برای یک عنصر تعریف شود.</p>
+<p dir='rtl'>در این صورت یک دستور میتواند بر دستورات دیگر حق تقدم یا اولویت پیدا کند.</p>
+
+<p dir='rtl'>به مثال زیر توجه کنید:</p>
+
+```CSS
+/*A*/
+p.class1[attr='value']
+
+/*B*/
+p.class1 {}
+
+/*C*/
+p.class2 {}
+
+/*D*/
+p {}
+
+/*E*/
+p { property: value !important; }
+
+```
+
+<p dir='rtl'>و همچنین به کد زیر:</p>
+
+```html
+<p style='/*F*/ property:value;' class='class1 class2' attr='value'>
+</p>
+
+```
+‍‍
+<p dir='rtl'>حق تقدم یا اولویت برای مثال بالا به این صورت است:</p>
+<p dir='rtl'>توجه داشته باشید که حق تقدم برای هر کدام از ویژگیها است نه برای کل مجموعه.</p>
+
+<p dir='rtl'>E دارای بیشترین الویت برای اینکه از <span dir="ltr">`!important`</span> استفاده کرده.</p>
+<p dir='rtl'>اما توصیه میشود تا جای ممکن از این کار اجتناب کنید مگر اینکه اینکار ضرورت داشته باشد</p>
+<p dir='rtl'>اولویت بعدی با F است زیرا که از روش درون برنامه ای استفاده کرده </p>
+<p dir='rtl'>اولویت بعدی با A است زیرا که بیشتر از بقیه مشخص تر تعریف شپه </p>
+<p dir='rtl'>مشخص تر = مشخص کننده بیشتر. دارای ۳ مشخص کننده: ۱ تگ <span dir="ltr">`p`</span> + ۱ کلاس با نام <span dir="ltr">`class1`</span> + ۱ خاصیت <span dir="ltr">`attr="value"`</span></p>
+<p dir='rtl'>اولویت بعدی با C است که مشخصه یکسانی با B دارد ولی بعد از آن تعریف شده است.</p>
+<p dir='rtl'>اولویت بعدی با B</p>
+<p dir='rtl'>و در آخر D</p>
+
+<h2 dir='rtl'>سازگاری</h2>
+
+<p dir='rtl'>بسیار از ویژگیهای CSS2 (و به تدریج CSS3) بر روی تمام مرورگرها و دستگاه ها سازگارند.اما همیشه حیاتی است که سازگاری CSS مورد استفاده خود را با مرورگر هدف چک کنید.</p>
+
+<p dir='rtl'> یک منبع خوب برای این کار است</p>
+[QuirksMode CSS](http://www.quirksmode.org/css/)
+
+<p dir='rtl'>برای یک تست سازگاری سریع, منبع زیر میتواند کمک بزرگی برای این کار باشد.</p>
+[CanIUse](http://caniuse.com/)
+
+<h2 dir='rtl'> منابع دیگر </h2>
+
+
+[Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
+
+[QuirksMode CSS](http://www.quirksmode.org/css/)
+
+[Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
+
+
diff --git a/factor.html.markdown b/factor.html.markdown
new file mode 100644
index 00000000..79596d83
--- /dev/null
+++ b/factor.html.markdown
@@ -0,0 +1,182 @@
+---
+language: factor
+contributors:
+ - ["hyphz", "http://github.com/hyphz/"]
+filename: learnfactor.factor
+---
+
+Factor is a modern stack-based language, based on Forth, created by Slava Pestov.
+
+Code in this file can be typed into Factor, but not directly imported because the vocabulary and import header would make the beginning thoroughly confusing.
+
+```
+! This is a comment
+
+! Like Forth, all programming is done by manipulating the stack.
+! Stating a literal value pushes it onto the stack.
+5 2 3 56 76 23 65 ! No output, but stack is printed out in interactive mode
+
+! Those numbers get added to the stack, from left to right.
+! .s prints out the stack non-destructively.
+.s ! 5 2 3 56 76 23 65
+
+! Arithmetic works by manipulating data on the stack.
+5 4 + ! No output
+
+! `.` pops the top result from the stack and prints it.
+. ! 9
+
+! More examples of arithmetic:
+6 7 * . ! 42
+1360 23 - . ! 1337
+12 12 / . ! 1
+13 2 mod . ! 1
+
+99 neg . ! -99
+-99 abs . ! 99
+52 23 max . ! 52
+52 23 min . ! 23
+
+! A number of words are provided to manipulate the stack, collectively known as shuffle words.
+
+3 dup - ! duplicate the top item (1st now equals 2nd): 3 - 3
+2 5 swap / ! swap the top with the second element: 5 / 2
+4 0 drop 2 / ! remove the top item (don't print to screen): 4 / 2
+1 2 3 nip .s ! remove the second item (similar to drop): 1 3
+1 2 clear .s ! wipe out the entire stack
+1 2 3 4 over .s ! duplicate the second item to the top: 1 2 3 4 3
+1 2 3 4 2 pick .s ! duplicate the third item to the top: 1 2 3 4 2 3
+
+! Creating Words
+! The `:` word sets Factor into compile mode until it sees the `;` word.
+: square ( n -- n ) dup * ; ! No output
+5 square . ! 25
+
+! We can view what a word does too.
+! \ suppresses evaluation of a word and pushes its identifier on the stack instead.
+\ square see ! : square ( n -- n ) dup * ;
+
+! After the name of the word to create, the declaration between brackets gives the stack effect.
+! We can use whatever names we like inside the declaration:
+: weirdsquare ( camel -- llama ) dup * ;
+
+! Provided their count matches the word's stack effect:
+: doubledup ( a -- b ) dup dup ; ! Error: Stack effect declaration is wrong
+: doubledup ( a -- a a a ) dup dup ; ! Ok
+: weirddoubledup ( i -- am a fish ) dup dup ; ! Also Ok
+
+! Where Factor differs from Forth is in the use of quotations.
+! A quotation is a block of code that is pushed on the stack as a value.
+! [ starts quotation mode; ] ends it.
+[ 2 + ] ! Quotation that adds 2 is left on the stack
+4 swap call . ! 6
+
+! And thus, higher order words. TONS of higher order words.
+2 3 [ 2 + ] dip .s ! Pop top stack value, run quotation, push it back: 4 3
+3 4 [ + ] keep .s ! Copy top stack value, run quotation, push the copy: 7 4
+1 [ 2 + ] [ 3 + ] bi .s ! Run each quotation on the top value, push both results: 3 4
+4 3 1 [ + ] [ + ] bi .s ! Quotations in a bi can pull values from deeper on the stack: 4 5 ( 1+3 1+4 )
+1 2 [ 2 + ] bi@ .s ! Run the quotation on first and second values
+2 [ + ] curry ! Inject the given value at the start of the quotation: [ 2 + ] is left on the stack
+
+! Conditionals
+! Any value is true except the built-in value f.
+! A built-in value t does exist, but its use isn't essential.
+! Conditionals are higher order words as with the combinators above.
+
+5 [ "Five is true" . ] when ! Five is true
+0 [ "Zero is true" . ] when ! Zero is true
+f [ "F is true" . ] when ! No output
+f [ "F is false" . ] unless ! F is false
+2 [ "Two is true" . ] [ "Two is false" . ] if ! Two is true
+
+! By default the conditionals consume the value under test, but starred variants
+! leave it alone if it's true:
+
+5 [ . ] when* ! 5
+f [ . ] when* ! No output, empty stack, f is consumed because it's false
+
+
+! Loops
+! You've guessed it.. these are higher order words too.
+
+5 [ . ] each-integer ! 0 1 2 3 4
+4 3 2 1 0 5 [ + . ] each-integer ! 0 2 4 6 8
+5 [ "Hello" . ] times ! Hello Hello Hello Hello Hello
+
+! Here's a list:
+{ 2 4 6 8 } ! Goes on the stack as one item
+
+! Loop through the list:
+{ 2 4 6 8 } [ 1 + . ] each ! Prints 3 5 7 9
+{ 2 4 6 8 } [ 1 + ] map ! Leaves { 3 5 7 9 } on stack
+
+! Loop reducing or building lists:
+{ 1 2 3 4 5 } [ 2 mod 0 = ] filter ! Keeps only list members for which quotation yields true: { 2 4 }
+{ 2 4 6 8 } 0 [ + ] reduce . ! Like "fold" in functional languages: prints 20 (0+2+4+6+8)
+{ 2 4 6 8 } 0 [ + ] accumulate . . ! Like reduce but keeps the intermediate values in a list: prints { 0 2 6 12 } then 20
+1 5 [ 2 * dup ] replicate . ! Loops the quotation 5 times and collects the results in a list: { 2 4 8 16 32 }
+1 [ dup 100 < ] [ 2 * dup ] produce ! Loops the second quotation until the first returns false and collects the results: { 2 4 8 16 32 64 128 }
+
+! If all else fails, a general purpose while loop:
+1 [ dup 10 < ] [ "Hello" . 1 + ] while ! Prints "Hello" 10 times
+ ! Yes, it's hard to read
+ ! That's what all those variant loops are for
+
+! Variables
+! Usually Factor programs are expected to keep all data on the stack.
+! Using named variables makes refactoring harder (and it's called Factor for a reason)
+! Global variables, if you must:
+
+SYMBOL: name ! Creates name as an identifying word
+"Bob" name set-global ! No output
+name get-global . ! "Bob"
+
+! Named local variables are considered an extension but are available
+! In a quotation..
+[| m n ! Quotation captures top two stack values into m and n
+ | m n + ] ! Read them
+
+! Or in a word..
+:: lword ( -- ) ! Note double colon to invoke lexical variable extension
+ 2 :> c ! Declares immutable variable c to hold 2
+ c . ; ! Print it out
+
+! In a word declared this way, the input side of the stack declaration
+! becomes meaningful and gives the variable names stack values are captured into
+:: double ( a -- result ) a 2 * ;
+
+! Variables are declared mutable by ending their name with a shriek
+:: mword2 ( a! -- x y ) ! Capture top of stack in mutable variable a
+ a ! Push a
+ a 2 * a! ! Multiply a by 2 and store result back in a
+ a ; ! Push new value of a
+5 mword2 ! Stack: 5 10
+
+! Lists and Sequences
+! We saw above how to push a list onto the stack
+
+0 { 1 2 3 4 } nth ! Access a particular member of a list: 1
+10 { 1 2 3 4 } nth ! Error: sequence index out of bounds
+1 { 1 2 3 4 } ?nth ! Same as nth if index is in bounds: 2
+10 { 1 2 3 4 } ?nth ! No error if out of bounds: f
+
+{ "at" "the" "beginning" } "Append" prefix ! { "Append" "at" "the" "beginning" }
+{ "Append" "at" "the" } "end" suffix ! { "Append" "at" "the" "end" }
+"in" 1 { "Insert" "the" "middle" } insert-nth ! { "Insert" "in" "the" "middle" }
+"Concat" "enate" append ! "Concatenate" - strings are sequences too
+"Concatenate" "Reverse " prepend ! "Reverse Concatenate"
+{ "Concatenate " "seq " "of " "seqs" } concat ! "Concatenate seq of seqs"
+{ "Connect" "subseqs" "with" "separators" } " " join ! "Connect subseqs with separators"
+
+! And if you want to get meta, quotations are sequences and can be dismantled..
+0 [ 2 + ] nth ! 2
+1 [ 2 + ] nth ! +
+[ 2 + ] \ - suffix ! Quotation [ 2 + - ]
+
+
+```
+
+##Ready For More?
+
+* [Factor Documentation](http://docs.factorcode.org/content/article-help.home.html)
diff --git a/fi-fi/markdown-fi.html.markdown b/fi-fi/markdown-fi.html.markdown
index 14b0f1d9..c5ee52b0 100644
--- a/fi-fi/markdown-fi.html.markdown
+++ b/fi-fi/markdown-fi.html.markdown
@@ -50,8 +50,8 @@ __Kuten on tämäkin teksti.__
**_Kuten tämäkin!_**
*__Kuten tämäkin!__*
-<!-- Github-tyylisessä Markdownissa, jota käytetään tiedostojen esittämiseksi
-Githubissa, meillä on käytössämme myös yliviivaus: -->
+<!-- GitHub-tyylisessä Markdownissa, jota käytetään tiedostojen esittämiseksi
+GitHubissa, meillä on käytössämme myös yliviivaus: -->
~~Tämä teksti on yliviivattua.~~
@@ -150,7 +150,7 @@ rivin neljällä välilyönnillä tai tabulaattorilla. -->
John ei tiennyt edes mitä `go_to()` -funktio teki!
-<!-- Githubin Markdownissa voit käyttää erityissyntaksia koodille. -->
+<!-- GitHubin Markdownissa voit käyttää erityissyntaksia koodille. -->
\`\`\`ruby <!-- paitsi että poista nuo kenoviivat, vain ```ruby ! -->
def foobar
@@ -158,7 +158,7 @@ def foobar
end
\`\`\` <!-- tästä myös, ei kenoviivoja, vain ``` -->
-<!-- Yllä oleva teksti ei vaadi sisennystä. Lisäksi Github käyttää ``` jälkeen
+<!-- Yllä oleva teksti ei vaadi sisennystä. Lisäksi GitHub käyttää ``` jälkeen
mainitsemasi kielen syntaksin korostusta -->
<!-- Vaakaviiva (<hr />) -->
@@ -231,13 +231,13 @@ haluan kirjoittaa *tämän tekstin jonka ympärillä on asteriskit* mutta en hal
sen kursivoituvan, joten teen näin: \*tämän tekstin ympärillä on asteriskit\*.
<!-- Näppäimistön näppäimet -->
-<!-- Githubin Markdownissa, voit käyttää <kbd> -tagia esittämään näppäimiä -->
+<!-- GitHubin Markdownissa, voit käyttää <kbd> -tagia esittämään näppäimiä -->
Tietokoneesi kaatui? Kokeile painaa
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
<!-- Taulukot -->
-<!-- Taulukot ovat saatavilla vain Githubin markdownissa ja ne ovat melko
+<!-- Taulukot ovat saatavilla vain GitHubin markdownissa ja ne ovat melko
vaivalloisia käyttää, mutta jos todella haluat: -->
| Kolumni1 | Kolumni2 | Kolumni3 |
diff --git a/fi-fi/ruby-fi.html.markdown b/fi-fi/ruby-fi.html.markdown
new file mode 100644
index 00000000..52c60182
--- /dev/null
+++ b/fi-fi/ruby-fi.html.markdown
@@ -0,0 +1,608 @@
+---
+language: ruby
+filename: learnruby-fi.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"]
+ - ["Gabriel Halley", "https://github.com/ghalley"]
+ - ["Persa Zula", "http://persazula.com"]
+ - ["Jake Faris", "https://github.com/farisj"]
+translators:
+ - ["Oliver Vartiainen", "https://github.com/firoxer"]
+lang: fi-fi
+---
+
+```ruby
+# Tässä yhden rivin kommentti
+
+=begin
+Tässä usean rivin kommentti
+Näitä ei kylläkään käytetä
+Joten käytetään vastedes vain yksirivisiä
+=end
+
+# Tärkeintä on muistaa, että Rubyssa kaikki pohjautuu olioihin.
+
+# Luvutkin ovat olioita:
+
+3.class #=> Fixnum
+
+3.to_s #=> "3"
+
+# Peruslaskutoimituksia:
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+2**5 #=> 32
+5 % 3 #=> 2
+
+# Bittioperaatioita:
+3 & 5 #=> 1
+3 | 5 #=> 7
+3 ^ 5 #=> 6
+
+# Laskutoimitukset ovat vain syntaksisokeria lukuolion laskumetodin kutsulle:
+1.+(3) #=> 4
+10.* 5 #=> 50
+
+# Erityisarvotkin ovat olioita:
+
+nil # vastaa joidenkin kielten "null"-arvoa
+true # tosi
+false # epätosi
+
+nil.class #=> NilClass
+true.class #=> TrueClass
+false.class #=> FalseClass
+
+# Samanvertaisuuden testaus:
+1 == 1 #=> true
+2 == 1 #=> false
+
+# ...ja sama eriarvoisuudelle:
+1 != 1 #=> false
+2 != 1 #=> true
+
+# "nil" ja "false" ovat ainoat epätodet arvot; kaikki muu ymmärretään todeksi:
+!nil #=> true
+!false #=> true
+!0 #=> false
+
+# Lisää vertailuoperaatioita:
+1 < 10 #=> true
+1 > 10 #=> false
+2 <= 2 #=> true
+2 >= 2 #=> true
+
+# Kahdensuuntainen vertailuoperaattori:
+1 <=> 10 #=> -1
+10 <=> 1 #=> 1
+1 <=> 1 #=> 0
+
+# Logiikkaoperaattorit:
+true && false #=> false
+true || false #=> true
+!true #=> false
+
+# Merkkipohjaisten logiikkaoperaattorien vaihtoehtona on sanalliset muodot,
+# joilla on hyvin matala presedenssi. Niillä voi muokata ohjelman kulkua
+# esimerkiksi väitelausekkeita ketjuttaen.
+
+# Metodia `do_something_else` kutsutaan vain, jos `do_something` onnistuu:
+do_something() and do_something_else()
+# Metodia `log_error` kutsutaan vain, jos `do_something` epäonnistuu:
+do_something() or log_error()
+
+# Merkkijonot ovat olioita:
+
+'Tässä on merkkijono'.class #=> String
+"Rajaavat lainausmerkit voivat olla yksin- tai kaksinkertaisia".class #=> String
+
+täyte = 'sisällyttää muita merkkijonoja'
+"Kaksinkertaisilla lainausmerkeillä voi #{täyte}"
+#=> "Kaksinkertaisilla lainausmerkeillä voi sisällyttää muita merkkijonoja"
+
+# Yksinkertaisia lainausmerkkejä kannattaa silti suosia, sillä kaksinkertaiset
+# merkit saattavat aiheuttaa turhia kielensisäisiä tarkistuksia.
+
+# Merkkijonoja voi yhdistellä toisiinsa:
+'hello ' + 'world' #=> "hello world"
+
+# ...mutta luvut vaativat ensin tyyppimuunnoksen:
+'hello ' + 3 #=> TypeError: can't convert Fixnum into String
+'hello ' + 3.to_s #=> "hello 3"
+
+# Merkkijonoja voi soveltaa laskutoimituksiin... odotettavin seurauksin:
+'hello ' * 3 #=> "hello hello hello "
+
+# Merkkijonoa voi jatkaa toisella:
+'hello' << ' world' #=> "hello world"
+
+# Tulosteen luonti kera rivinvaihdon:
+puts "I'm printing!"
+#=> I'm printing!
+#=> nil
+
+# ...ja ilman rivinvaihtoa:
+print "I'm printing!"
+#=> I'm printing! => nil
+
+# Muuttujien määrittely:
+x = 25 #=> 25
+x #=> 25
+
+# Arvon asettaminen palauttaa arvon itsensä, joten usean muuttujan arvon
+# yhtäaikainen määrittely käy vaivatta:
+x = y = 10 #=> 10
+x #=> 10
+y #=> 10
+
+# Muuttujien sanaerottimena käytetään alaviivaa:
+snake_case = true
+
+# Lisäksi Rubyssa suositaan ytimekkäitä nimiä:
+path_to_project_root = '/good/name/'
+path = '/bad/name/'
+
+# Symbolit
+
+# Symbolit ovat muuttumattomia, uudelleenkäytettäviä vakioita.
+# Niitä käytetään merkkijonojen sijaan, kun tarkoitus on viitata arvoon,
+# jolla on tietty, pysyvä merkitys:
+
+:pending.class #=> Symbol
+
+status = :pending
+
+status == :pending #=> true
+
+status == 'pending' #=> false
+
+status == :approved #=> false
+
+# Taulukot
+
+# Tässä taulukko:
+array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+
+# Taulukko saa koostua erityyppisistä arvoista:
+[1, 'hello', false] #=> [1, "hello", false]
+
+# Taulukon alkioihin voi viitata järjestysnumerolla nollasta alkaen:
+array[0] #=> 1
+array.first #=> 1
+array[12] #=> nil
+
+# Kuten laskutoimituksissa nähty syntaksisokeri on myös taulukon alkioiden haku
+# pohjimmiltaan vain taulukko-olioon kuuluvan "[]"-metodin kutsu:
+array.[] 0 #=> 1
+array.[] 12 #=> nil
+
+# Haku käy myös lopustapäin:
+array[-1] #=> 5
+array.last #=> 5
+
+# Alitaulukon haku käy indeksiparilla...
+array[2, 3] #=> [3, 4, 5]
+
+# ...tai määrittelemällä väli:
+array[1..3] #=> [2, 3, 4]
+
+# Taulukon voi kääntää:
+a=[1,2,3]
+a.reverse! #=> [3,2,1]
+
+# Ja sitä voi jatkaa näin...
+array << 6 #=> [1, 2, 3, 4, 5, 6]
+
+# ...tai näin:
+array.push(6) #=> [1, 2, 3, 4, 5, 6]
+
+# Alkion olemassaolon tarkistus:
+array.include?(1) #=> true
+
+# Hashit eli assosiaatiotaulut ovat Rubyn tärkein avain-/arvoparirakenne.
+# Hash luodaan aaltosulkeilla:
+hash = { 'color' => 'green', 'number' => 5 }
+
+hash.keys #=> ['color', 'number']
+
+# Hash toimii erityisen nopeasti, kun haetaan arvoa avaimen perusteella:
+hash['color'] #=> 'green'
+hash['number'] #=> 5
+
+# Jos hashistä ei löyty avainta vastaavaa arvoa, palautetaan nil-arvo:
+hash['nothing here'] #=> nil
+
+# Symbolihashin määrittelylle on oma syntaksinsa (alkaen Rubyn versiosta 1.9):
+new_hash = { defcon: 3, action: true }
+new_hash.keys #=> [:defcon, :action]
+
+# Hashin avaimen ja arvon olemassaolon tarkistus:
+new_hash.key?(:defcon) #=> true
+new_hash.value?(3) #=> true
+
+# Vinkki! Sekä taulukot että hashit sisältävät Enumerable-moduulin,
+# johon kuuluu useita hyödyllisiä iterointimetodeja kuten .each, .map,
+# .reduce ja .count
+
+# Rakenteita
+
+if true
+ 'if statement'
+elsif false
+ 'else if, optional'
+else
+ 'else, also optional'
+end
+
+for counter in 1..5
+ puts "iteration #{counter}"
+end
+#=> iteration 1
+#=> iteration 2
+#=> iteration 3
+#=> iteration 4
+#=> iteration 5
+
+# HUOMAA, että for-rakennetta kannattaa välttää, sillä Rubyssa suosittu
+# each-metodi ajaa saman asian idiomaattisemmin. Each-metodi ottaa ainoana
+# argumenttinaan lohkon. Lohkot toimivat pitkälti samoin kuin muiden kielten
+# anonyymit funktiot, lambdat tai sulkeumat.
+
+# Lukuvälit vastaavat each-metodiin, jolloin sille annettu lohko ajetaan
+# kerran jokaiselle välin kokonaisluvulle.
+# Lukuvälin each-rakenne lohkoineen näyttää tältä:
+
+(1..5).each do |counter|
+ puts "iteration #{counter}"
+end
+#=> iteration 1
+#=> iteration 2
+#=> iteration 3
+#=> iteration 4
+#=> iteration 5
+
+# Lohkoa ympäröivät do/end-avainsanat voi korvata myös aaltosulkeilla:
+(1..5).each { |counter| puts "iteration #{counter}" }
+
+# Lukuvälien lisäksi myös tietorakenteita voidaan iteroida each-metodilla:
+array.each do |element|
+ puts "#{element} is part of the array"
+end
+hash.each do |key, value|
+ puts "#{key} is #{value}"
+end
+
+# Taulukoita voi iteroida metodilla each_with_index, jolloin lohko saa
+# argumenteikseen sekä alkion että indeksin:
+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}"
+ counter += 1
+end
+#=> iteration 1
+#=> iteration 2
+#=> iteration 3
+#=> iteration 4
+#=> iteration 5
+
+# Each-metodin lisäksi Rubyssa on useita muita iterointimetodeja kuten
+# "map" ja "reduce". Näistä "map" kutsuttuna taulukolla ottaa argumentikseen
+# lohkon, suorittaa sen kerran jokaiselle rakenteen jäsenelle, ja lopuksi
+# palauttaa uuden taulukon, jonka jäsenet ovat lohkon suorituksen tuloksia.
+
+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]
+
+# Case-rakenne siirtää ohjelman kulun yhdelle monista määritellyistä poluista:
+
+grade = 'B'
+
+case grade
+when 'A'
+ puts 'Way to go kiddo'
+when 'B'
+ puts 'Better luck next time'
+when 'C'
+ puts 'You can do better'
+when 'D'
+ puts 'Scraping through'
+when 'F'
+ puts 'You failed!'
+else
+ puts 'Alternative grading system, eh?'
+end
+#=> "Better luck next time"
+
+# Case-rakenteessa voidaan hyödyntää lukuvälejä:
+grade = 82
+case grade
+when 90..100
+ puts 'Hooray!'
+when 80...90
+ puts 'OK job'
+else
+ puts 'You failed!'
+end
+#=> "OK job"
+
+# Virheidenkäsittely:
+begin
+ # Seuraava koodinpätkä aiheuttaa NoMemoryError-poikkeuksen
+ 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
+
+# Ylimmän näkyvyysalueen metodi näyttää itsenäiseltä funktiolta:
+def double(x)
+ x * 2
+end
+
+# Funktiot (ja lohkot) palauttavat implisiittisesti
+# viimeiseksi ajamansa lausekkeen arvon:
+double(2) #=> 4
+
+# Metodikutsun argumentteja ympäröivät kaarisulkeet voi jättää pois,
+# kunhan koodi ei muutu monitulkintaiseksi:
+
+double 3 #=> 6
+
+double double 3 #=> 12
+
+def sum(x, y)
+ x + y
+end
+
+# Argumentit erotetaan pilkuilla:
+
+sum 3, 4 #=> 7
+
+sum sum(3, 4), 5 #=> 12
+
+# Kaikilla metodeilla on implisiittinen lohkoparametri,
+# joka voidaan suorittaa yield-avainsanalla:
+
+def surround
+ puts '{'
+ yield
+ puts '}'
+end
+
+surround { puts 'hello world' }
+
+# {
+# hello world
+# }
+
+# Metodille annetun lohkon voi nimetä parametrilistassa &-merkin avulla,
+# minkä jälkeen se suoritetaan call-metodilla:
+def guests(&block)
+ block.call 'some_argument'
+end
+
+# Metodille voi antaa vaihtelevan määrän muuttujia. Ne siirretään taulukkoon,
+# jolle annetaan parametrilistassa nimi \*-merkin avulla
+def guests(*array)
+ array.each { |guest| puts guest }
+end
+
+# Luokan määritys aloitetaan class-avainsanalla:
+
+class Human
+
+ # Tässä luokkamuuttuja, joka on yhteinen kaikille luokan olioille:
+ @@species = 'H. sapiens'
+
+ # Alustusmetodin määrittely:
+ def initialize(name, age = 0)
+ # name-oliomuuttujan arvon asetus metodille annetun name-muuttujan mukaan:
+ @name = name
+
+ # Jos tätä metodia kutsuessa jätetään toinen argumentti (age) antamatta,
+ # saa se parametriluettelossa määritetyn arvon 0:
+ @age = age
+ end
+
+ # Tyypillinen oliomuuttujan arvon asettava metodi:
+ def name=(name)
+ @name = name
+ end
+
+ # Tyypillinen oliomuuttujan arvon palauttava metodi:
+ def name
+ @name
+ end
+
+ # Edelliset kaksi metodia voi ilmaista idiomaattisemmin myös näin:
+ attr_accessor :name
+
+ # Lisäksi arvon palauttavan ja asettavan metodin voi määritellä erikseen:
+ attr_reader :name
+ attr_writer :name
+
+ # Luokkametodeissa käytetään avainsanaa self erotuksena oliometodeista.
+ # Luokkametodia voi kutsua vain luokalla itsellään, ei olioilla:
+ def self.say(msg)
+ puts msg
+ end
+
+ def species
+ @@species
+ end
+end
+
+# Olion luonti:
+
+jim = Human.new('Jim Halpert')
+
+dwight = Human.new('Dwight K. Schrute')
+
+# Olion metodien kutsuja:
+jim.species #=> "H. sapiens"
+jim.name #=> "Jim Halpert"
+jim.name = "Jim Halpert II" #=> "Jim Halpert II"
+jim.name #=> "Jim Halpert II"
+dwight.species #=> "H. sapiens"
+dwight.name #=> "Dwight K. Schrute"
+
+# Luokkametodin kutsu:
+Human.say('Hi') #=> "Hi"
+
+# Muuttujan näkyvyysalueen voi määritellä etuliitteellä.
+
+# $-alkuiset muuttujat ovat globaaleja:
+$var = "I'm a global var"
+defined? $var #=> "global-variable"
+
+# @-alkuiset muuttujat kuuluvat oliolle,
+# jonka näkyvyysalueella määrittely tehdään:
+@var = "I'm an instance var"
+defined? @var #=> "instance-variable"
+
+# @@-alkuiset muuttujat kuuluvat vastaavasti näkyvyysalueensa luokalle:
+@@var = "I'm a class var"
+defined? @@var #=> "class variable"
+
+# Isolla alkukirjaimella nimetyt muuttujat ovatkin vakioita:
+Var = "I'm a constant"
+defined? Var #=> "constant"
+
+# Kuten odottaa saattaa, myös luokat itsessään ovat olioita.
+# Siksi niille voi määritellä muuttujia, jotka ovat yhteisiä kaikille
+# luokan ilmentymille ja perillisille.
+
+# Tavallisen luokan määrittely:
+
+class Human
+ @@foo = 0
+
+ def self.foo
+ @@foo
+ end
+
+ def self.foo=(value)
+ @@foo = value
+ end
+end
+
+# Perillisluokan määrittely:
+
+class Worker < Human
+end
+
+Human.foo # 0
+Worker.foo # 0
+
+Human.foo = 2 # 2
+Worker.foo # 2
+
+# Oliomuuttuja on kuitenkin olion oma eikä periydy:
+
+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
+
+# Moduulien lisääminen luokkaan "include"-avainsanalla siirtää moduulin metodit
+# luokan ilmentymille, kun taas "extend" avainsana siirtää metodit
+# luokalle itselleen:
+
+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'
+
+# Callback-tyyppiset metodit suoritetaan moduulia sisällyttäessä:
+
+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'
+```
+
+## Lisämateriaalia englanniksi
+
+- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - Selaimessa tehtäviä harjoituksia tämän dokumentin hengessä
+- [An Interactive Tutorial for Ruby](https://rubymonk.com/)
+- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) - Virallinen dokumentaatio
+- [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/) - Vanhempi, mutta [ilmainen painos](http://ruby-doc.com/docs/ProgrammingRuby/) on luettavissa netissä
+- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Yhteisön luoma Ruby-tyyliopas
+- [Try Ruby](http://tryruby.org) - Rubyn perusteet interaktiivisesti
diff --git a/forth.html.markdown b/forth.html.markdown
index b4a5581b..55d755b2 100644
--- a/forth.html.markdown
+++ b/forth.html.markdown
@@ -54,7 +54,7 @@ Forth, but most of what is written here should work elsewhere.
3 dup - \ duplicate the top item (1st now equals 2nd): 3 - 3
2 5 swap / \ swap the top with the second element: 5 / 2
6 4 5 rot .s \ rotate the top 3 elements: 4 5 6
-4 0 drop 2 / \ remove the top item (dont print to screen): 4 / 2
+4 0 drop 2 / \ remove the top item (don't print to screen): 4 / 2
1 2 3 nip .s \ remove the second item (similar to drop): 1 3
\ ---------------------- More Advanced Stack Manipulation ----------------------
diff --git a/fr-fr/HTML-fr.html.markdown b/fr-fr/HTML-fr.html.markdown
index fdde9107..4d2da921 100644
--- a/fr-fr/HTML-fr.html.markdown
+++ b/fr-fr/HTML-fr.html.markdown
@@ -5,6 +5,7 @@ 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).
@@ -17,7 +18,7 @@ Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parl
Cet article porte principalement sur la syntaxe et quelques astuces.
-```HTML
+```html
<!-- Les commentaires sont entouré comme cette ligne! -->
<!-- #################### Les balises #################### -->
diff --git a/fr-fr/brainfuck-fr.html.markdown b/fr-fr/bf-fr.html.markdown
index 545e407e..0fae6032 100644
--- a/fr-fr/brainfuck-fr.html.markdown
+++ b/fr-fr/bf-fr.html.markdown
@@ -1,5 +1,5 @@
---
-language: brainfuck
+language: bf
filename: learnbrainfuck-fr.bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown
index d9bd9b48..bfb9f2ce 100644
--- a/fr-fr/d.html.markdown
+++ b/fr-fr/d.html.markdown
@@ -8,7 +8,7 @@ translators:
lang: fr-fr
---
-```d
+```c
// Commençons par un classique
module hello;
@@ -30,7 +30,7 @@ D est activement développé par de nombreuses personnes très intelligents, gui
[Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu).
Après cette petite introduction, jetons un coup d'oeil à quelques exemples.
-```d
+```c
import std.stdio;
void main() {
@@ -75,7 +75,7 @@ On peut définir de nouveaux types avec les mots-clés `struct`, `class`,
`union` et `enum`. Ces types sont passés au fonction par valeur (ils sont copiés)
De plus, on peut utiliser les templates pour rendre toutes ces abstractions génériques.
-```d
+```c
// Ici, 'T' est un paramètre de type. Il est similaire au <T> de C++/C#/Java.
struct LinkedList(T) {
T data = null;
@@ -140,7 +140,7 @@ une méthode qui peut se comporter comme une lvalue. On peut donc utiliser
la syntaxe des structures classiques (`struct.x = 7`) comme si il
s'agissait de méthodes getter ou setter.
-```d
+```c
// Considérons une classe paramétrée avec les types 'T' et 'U'
class MyClass(T, U) {
T _data;
@@ -212,7 +212,7 @@ de premier ordre, les fonctions `pure` et les données immuables.
De plus, tout vos algorithmes fonctionelles favoris (map, reduce, filter)
sont disponibles dans le module `std.algorithm`.
-```d
+```c
import std.algorithm : map, filter, reduce;
import std.range : iota; // construit un intervalle excluant la dernière valeur.
@@ -242,7 +242,7 @@ est de type A, comme si c'était une méthode de A.
J'aime le parallélisme. Vous aimez les parallélisme ? Bien sur que vous aimez ça
Voyons comment on le fait en D !
-```d
+```c
import std.stdio;
import std.parallelism : parallel;
import std.math : sqrt;
diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown
index 16558e7e..9d8bef70 100644
--- a/fr-fr/go-fr.html.markdown
+++ b/fr-fr/go-fr.html.markdown
@@ -3,7 +3,7 @@ name: Go
category: language
language: Go
lang: fr-fr
-filename: learngo.go
+filename: learngo-fr.go
contributors:
- ["Sonia Keys", "https://github.com/soniakeys"]
- ["Christopher Bess", "https://github.com/cbess"]
diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown
new file mode 100644
index 00000000..48d24549
--- /dev/null
+++ b/fr-fr/make-fr.html.markdown
@@ -0,0 +1,268 @@
+---
+language: make
+contributors:
+ - ["Robert Steed", "https://github.com/robochat"]
+translators:
+ - ["altaris", "https://github.com/altaris"]
+filename: Makefile-fr
+lang: fr-fr
+---
+
+Un makefile est un fichier qui définit un ensemble de règles liées entre elles
+pour créer une ou plusieurs cibles. L'idée est d'effectuer le moins de travail
+possible afin de mettre à jour la ou les cibles en fonction des dépendances.
+
+Écrit en un week-end par Stuart Feldman en 1976, le make et les
+makefiles sont encore très utilisés (principalement dans les systèmes Unix),
+malgré la concurrence et les critiques faites à son égard.
+
+Le programme make a plusieurs variantes. Dans ce tutoriel, nous utiliserons
+l'implémentation standard : GNU make.
+
+```make
+
+# Ceci est un commentaire.
+
+# Un makefile devrait être nommé "Makefile" (avec ou sans la
+# majuscule). Il peut alors être exécuté par `make <cible>`.
+# Ce nommage n'est toutefois pas obligatoire : utiliser
+# `make -f "fichier" <cible>`.
+
+# ATTENTION : l'indentation est quant à elle obligatoire, et se fait avec des
+# tabulations, pas avec des espaces !
+
+#-----------------------------------------------------------------------
+# Les basiques
+#-----------------------------------------------------------------------
+
+# Une règle. Elle ne sera exécutée que si fichier0.txt n'existe pas.
+fichier0.txt:
+ echo "truc" > fichier0.txt
+ # Même les commentaires sont transférés dans le terminal.
+
+# Cette règle ne sera exécutée que si fichier0.txt est plus récent que
+# fichier1.txt.
+fichier1.txt: fichier0.txt
+ cat fichier0.txt > fichier1.txt
+ # Utiliser la même syntaxe que dans un terminal.
+ @cat fichier0.txt >> fichier1.txt
+ # @ empêche l'affichage de la sortie texte d'une commande.
+ -@echo 'hello'
+ # - signifie que la règle devrait continuer à s'exécuter si cette commande
+ # échoue.
+
+# Une règle peut avoir plusieurs cibles et plusieurs dépendances.
+fichier2.txt fichier3.txt: fichier0.txt fichier1.txt
+ touch fichier2.txt
+ touch fichier3.txt
+
+# Make affichera un avertissement si le makefile comporte plusieurs règles pour
+# une même cible. Cependant les règles vides ne comptent pas, et peuvent être
+# utilisées pour ajouter des dépendances plus facilement.
+
+#-----------------------------------------------------------------------
+# Fausses règles
+#-----------------------------------------------------------------------
+
+# Une fausse règle est une règle qui ne correspond pas à un fichier.
+# Par définition, elle ne peut pas être à jour, et donc make l’exécutera à
+# chaque demande.
+all: maker process
+
+# La déclaration des règles peut être faite dans n'importe quel ordre.
+maker:
+ touch ex0.txt ex1.txt
+
+# On peut transformer une règle en fausse règle grâce à la cible spéciale
+# suivante :
+.PHONY: all maker process
+
+# Une règle dépendante d'une fausse règle sera toujours exécutée.
+ex0.txt ex1.txt: maker
+
+# Voici quelques exemples fréquents de fausses règles : all, make, clean,
+# install...
+
+#-----------------------------------------------------------------------
+# Variables automatiques et wildcards
+#-----------------------------------------------------------------------
+
+# Utilise un wildcard pour des noms de fichier
+process: fichier*.txt
+ @echo $^ # $^ est une variable contenant la liste des dépendances de la
+ # cible actuelle.
+ @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles
+ # multiples, $@ est le nom de la cible ayant causé l'exécution
+ # de cette règle.
+ @echo $< # $< contient la première dépendance.
+ @echo $? # $? contient la liste des dépendances qui ne sont pas à jour.
+ @echo $+ # $+ contient la liste des dépendances avec d'éventuels
+ # duplicatas, contrairement à $^.
+ @echo $| # $| contient la liste des cibles ayant préséance sur la cible
+ # actuelle.
+
+# Même si la définition de la règle est scindée en plusieurs morceaux, $^
+# listera toutes les dépendances indiquées.
+process: ex1.txt fichier0.txt
+# Ici, fichier0.txt est un duplicata dans $+.
+
+#-----------------------------------------------------------------------
+# Pattern matching
+#-----------------------------------------------------------------------
+
+# En utilisant le pattern matching, on peut par exemple créer des règles pour
+# convertir les fichiers d'un certain format dans un autre.
+%.png: %.svg
+ inkscape --export-png $^
+
+# Make exécute une règle même si le fichier correspondant est situé dans un sous
+# dossier. En cas de conflit, la règle avec la meilleure correspondance est
+# choisie.
+small/%.png: %.svg
+ inkscape --export-png --export-dpi 30 $^
+
+# Dans ce type de conflit (même cible, même dépendances), make exécutera la
+# dernière règle déclarée...
+%.png: %.svg
+ @echo cette règle est choisie
+
+# Dans ce type de conflit (même cible mais pas les mêmes dépendances), make
+# exécutera la première règle pouvant être exécutée.
+%.png: %.ps
+ @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents
+
+# Make a des règles pré établies. Par exemple, il sait comment créer la cible
+# *.o à partir de *.c.
+
+# Les makefiles plus vieux utilisent un matching par extension de fichier.
+.png.ps:
+ @echo cette règle est similaire à une règle par pattern matching
+
+# Utiliser cette règle spéciale pour déclarer une règle comme ayant un
+# matching par extension de fichier.
+.SUFFIXES: .png
+
+#-----------------------------------------------------------------------
+# Variables, ou macros
+#-----------------------------------------------------------------------
+
+# Les variables sont des chaînes de caractères.
+
+variable = Ted
+variable2="Sarah"
+
+echo:
+ @echo $(variable)
+ @echo ${variable2}
+ @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) !
+ @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide).
+
+# Les variables sont déclarées de 4 manières, de la plus grande priorité à la
+# plus faible :
+# 1 : dans la ligne de commande qui invoque make,
+# 2 : dans le makefile,
+# 3 : dans les variables d’environnement du terminal qui invoque make,
+# 4 : les variables prédéfinies.
+
+# Assigne la variable si une variable d’environnement du même nom n'existe pas
+# déjà.
+variable4 ?= Jean
+
+# Empêche cette variable d'être modifiée par la ligne de commande.
+override variable5 = David
+
+# Concatène à une variable (avec un espace avant).
+variable4 +=gris
+
+# Assignations de variable pour les règles correspondant à un pattern
+# (spécifique à GNU make).
+*.png: variable2 = Sara # Pour toutes les règles correspondant à *.png, et tous
+ # leurs descendants, la variable variable2 vaudra
+ # "Sara".
+# Si le jeux des dépendances et descendances devient vraiment trop compliqué,
+# des incohérences peuvent survenir.
+
+# Certaines variables sont prédéfinies par make :
+affiche_predefinies:
+ echo $(CC)
+ echo ${CXX}
+ echo $(FC)
+ echo ${CFLAGS}
+ echo $(CPPFLAGS)
+ echo ${CXXFLAGS}
+ echo $(LDFLAGS)
+ echo ${LDLIBS}
+
+#-----------------------------------------------------------------------
+# Variables : le retour
+#-----------------------------------------------------------------------
+
+# Les variables sont évaluées à chaque instance, ce qui peut être coûteux en
+# calculs. Pour parer à ce problème, il existe dans GNU make une seconde
+# manière d'assigner des variables pour qu'elles ne soient évaluées qu'une seule
+# fois seulement.
+
+var := A B C
+var2 ::= $(var) D E F # := et ::= sont équivalents.
+
+# Ces variables sont évaluées procéduralement (i.e. dans leur ordre
+# d'apparition), contrairement aux règles par exemple !
+
+# Ceci ne fonctionne pas.
+var3 ::= $(var4) et fais de beaux rêves
+var4 ::= bonne nuit
+
+#-----------------------------------------------------------------------
+# Fonctions
+#-----------------------------------------------------------------------
+
+# Make a une multitude de fonctions. La syntaxe générale est
+# $(fonction arg0,arg1,arg2...).
+
+# Quelques exemples :
+
+fichiers_source = $(wildcard *.c */*.c)
+fichiers_objet = $(patsubst %.c,%.o,$(fichiers_source))
+
+ls: * src/*
+ @echo $(filter %.txt, $^)
+ @echo $(notdir $^)
+ @echo $(join $(dir $^),$(notdir $^))
+
+#-----------------------------------------------------------------------
+# Directives
+#-----------------------------------------------------------------------
+
+# Inclut d'autres makefiles.
+include meuh.mk
+
+# Branchements conditionnels.
+sport = tennis
+report:
+ifeq ($(sport),tennis) # Il y a aussi ifneq.
+ @echo 'jeu, set et match'
+else
+ @echo "C'est pas ici Wimbledon ?"
+endif
+
+truc = true
+ifdef $(truc) # Il y a aussi ifndef.
+ machin = 'salut'
+endif
+```
+
+## Quelques références
+
+### En français
+
++ [Introduction à Makefile (developpez.com)]
+(http://gl.developpez.com/tutoriel/outil/makefile/),
++ [Compilez sous GNU/Linux ! (openclassrooms)]
+(https://openclassrooms.com/courses/compilez-sous-gnu-linux).
+
+### En anglais
+
++ [Documentation de GNU make](https://www.gnu.org/software/make/manual/),
++ [Software carpentry tutorial](http://swcarpentry.github.io/make-novice/),
++ Learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html)
+[ex28](http://c.learncodethehardway.org/book/ex28.html).
diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown
index 66f0efbe..2e4e8461 100644
--- a/fr-fr/markdown.html.markdown
+++ b/fr-fr/markdown.html.markdown
@@ -62,8 +62,8 @@ __Celui-là aussi.__
**_Pareil ici_**
*__Et là!__*
-<!-- Dans le "Github Flavored Markdown", utilisé pour interpréter le Markdown
-sur Github, on a également le strikethrough ( texte barré ) : -->
+<!-- Dans le "GitHub Flavored Markdown", utilisé pour interpréter le Markdown
+sur GitHub, on a également le strikethrough ( texte barré ) : -->
~~Ce texte est barré avec strikethrough.~~
@@ -172,7 +172,7 @@ fonctionne aussi à l'intérieur du bloc de code -->
La fonction `run()` ne vous oblige pas à aller courir!
-<!-- Via Github Flavored Markdown, vous pouvez utiliser
+<!-- Via GitHub Flavored Markdown, vous pouvez utiliser
des syntaxes spécifiques -->
\`\`\`ruby
@@ -183,7 +183,7 @@ puts "Hello world!"
end
\`\`\` <!-- pareil, pas de backslashes, juste ``` en guise de fin -->
-<-- Pas besoin d'indentation pour le code juste au dessus, de plus, Github
+<-- Pas besoin d'indentation pour le code juste au dessus, de plus, GitHub
va utiliser une coloration syntaxique pour le langage indiqué après les ``` -->
<!-- Ligne Horizontale (<hr />) -->
@@ -264,7 +264,7 @@ Pour taper *ce texte* entouré d'astérisques mais pas en italique :
Tapez \*ce texte\*.
<!-- Tableaux -->
-<!-- les Tableaux ne sont disponibles que dans le Github Flavored Markdown
+<!-- les Tableaux ne sont disponibles que dans le GitHub Flavored Markdown
et c'est ce n'est pas super agréable d'utilisation.
Mais si vous en avez besoin :
-->
diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown
index 4e31c4bf..fbe1741e 100644
--- a/fr-fr/objective-c-fr.html.markdown
+++ b/fr-fr/objective-c-fr.html.markdown
@@ -1,5 +1,4 @@
---
-
language: Objective-C
contributors:
- ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
@@ -9,7 +8,6 @@ translators:
- ["Yannick Loriot", "https://github.com/YannickL"]
filename: LearnObjectiveC-fr.m
lang: fr-fr
-
---
L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch.
@@ -519,6 +517,7 @@ __unsafe_unretained NSArray *unsafeArray; // Comme __weak, mais la variable n'es
// l'objet est supprimé
```
+
## Lectures Complémentaires
[La Page Wikipedia de l'Objective-C](http://fr.wikipedia.org/wiki/Objective-C)
diff --git a/fr-fr/typescript-fr.html.markdown b/fr-fr/typescript-fr.html.markdown
index b8807104..52d34650 100644
--- a/fr-fr/typescript-fr.html.markdown
+++ b/fr-fr/typescript-fr.html.markdown
@@ -87,22 +87,22 @@ mySearch = function(src: string, sub: string) {
// Les membres des classes sont publiques par défaut.
class Point {
- // Propriétés
- x: number;
-
- // Constructeur - Les mots clés "public" et "private" dans ce contexte
- // génèrent le code de la propriété et son initialisation dans le
- // constructeur. Ici, "y" sera défini de la même façon que "x",
- // mais avec moins de code. Les valeurs par défaut sont supportées.
- constructor(x: number, public y: number = 0) {
- this.x = x;
- }
+ // Propriétés
+ x: number;
+
+ // Constructeur - Les mots clés "public" et "private" dans ce contexte
+ // génèrent le code de la propriété et son initialisation dans le
+ // constructeur. Ici, "y" sera défini de la même façon que "x",
+ // mais avec moins de code. Les valeurs par défaut sont supportées.
+ constructor(x: number, public y: number = 0) {
+ this.x = x;
+ }
- // Fonctions
- dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
+ // Fonctions
+ dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
- // Membres statiques
- static origin = new Point(0, 0);
+ // Membres statiques
+ static origin = new Point(0, 0);
}
var p1 = new Point(10 ,20);
@@ -110,17 +110,17 @@ var p2 = new Point(25); // y sera 0
// Héritage
class Point3D extends Point {
- constructor(x: number, y: number, public z: number = 0) {
- // Un appel explicite au constructeur de la super classe
- // est obligatoire.
- super(x, y);
- }
+ constructor(x: number, y: number, public z: number = 0) {
+ // Un appel explicite au constructeur de la super classe
+ // est obligatoire.
+ super(x, y);
+ }
- // Redéfinition
- dist() {
- var d = super.dist();
- return Math.sqrt(d * d + this.z * this.z);
- }
+ // Redéfinition
+ dist() {
+ var d = super.dist();
+ return Math.sqrt(d * d + this.z * this.z);
+ }
}
// Modules, "." peut être utilisé comme un séparateur de sous modules.
@@ -144,19 +144,19 @@ var s2 = new G.Square(10);
// Génériques
// Classes
class Tuple<T1, T2> {
- constructor(public item1: T1, public item2: T2) {
- }
+ constructor(public item1: T1, public item2: T2) {
+ }
}
// Interfaces
interface Pair<T> {
- item1: T;
- item2: T;
+ item1: T;
+ item2: T;
}
// Et fonctions
var pairToTuple = function<T>(p: Pair<T>) {
- return new Tuple(p.item1, p.item2);
+ return new Tuple(p.item1, p.item2);
};
var tuple = pairToTuple({ item1:"hello", item2:"world"});
diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown
new file mode 100644
index 00000000..7b446259
--- /dev/null
+++ b/fr-fr/wolfram-fr.html.markdown
@@ -0,0 +1,167 @@
+---
+language: wolfram
+contributors:
+ - ["hyphz", "http://github.com/hyphz/"]
+translators:
+ - ["altaris", "http://github.com/altaris/"]
+filename: learnwolfram-fr.nb
+lang: fr-fr
+---
+
+Le langage Wolfram est utilisé dans les programmes suivants :
+* La ligne de commandes interactive noyau du Raspberry Pi, mais elle ne peut pas
+gérer des éléments graphiques.
+* _Mathematica_, un éditeur de texte riche spécialisé pour les mathématiques :
+appuyer sur `Shift + Entrée` dans une cellule de code crée un nouvelle cellule
+contenant le résultat.
+* _Wolfram Wokbench_, une variante d'Eclipse spécialisée pour le langage
+Wolfram.
+
+Ce code d'exemple peut être utilisé et modifié dans ces logiciels. Cependant, le
+copier-coller directement dans Mathematica peut causer des problèmes de
+formatage, car il ne contient aucune information de mise en page.
+
+```
+(* Ceci est un commentaire *)
+
+(* Dans Mathematica, au lieu d'utiliser ces commentaires, vous pouvez créer des
+ cellules de texte et insérer de jolies images *)
+
+(* Saisissez une opération et appuyez sur Shift + Entrée pour obtenir le
+ résultat *)
+2*2 (* 4 *)
+5+8 (* 13 *)
+
+(* Appels de fonction *)
+Sin[Pi/2] (* 1 *)
+(* Syntaxe alternative pour les appels de fonction à 1 paramètre *)
+Sin@(Pi/2) (* 1 *)
+(Pi/2) // Sin (* 1 *)
+
+(* Attention : le langage est sensible à la casse ! *)
+
+(* Toutes les expressions sont en réalité des appels de fonction *)
+Times[2, 2] (* 4 *)
+Plus[5, 8] (* 13 *)
+
+(* Utiliser une variable pour la première fois la déclare globalement *)
+x = 5 (* 5 *)
+x == 5 (* True, l'assignation et le test d'égalité est écrit comme
+ en C *)
+x (* 5 *)
+x = x + 5 (* 10 *)
+x (* 10 *)
+Set[x, 20] (* TOUT est un appel de fonction, TOUUUUUUUUT *)
+x (* 20 *)
+
+(* Le langage Wolfram effectue des manipulations symboliques, donc utiliser des
+ variables non déclarées est légal *)
+truc + 5 (* 5 + truc, comme truc n'est pas déclarée, l'évaluation
+ s'arrête là *)
+truc + 5 + 10 (* 15 + truc, on évalue ce qu'on peut... *)
+% (* 15 + truc, % représente le dernier résultat *)
+% - truc (* 15, les variables non déclarées peuvent quand même
+ s'annuler *)
+chose = truc + 5 (* Attention : chose est ici une expression et non un nombre *)
+
+(* Déclaration d'une fonction *)
+Double[x_] := x * 2 (* Le symbole := empêche l'évaluation immédiate du terme
+ à droite *)
+Double[10] (* 20 *)
+Double[Sin[Pi/2]] (* 2 *)
+Double @ Sin @ (Pi/2) (* 2, Utiliser @ évite les paquets de crochets
+ fermants si moches *)
+(Pi/2) // Sin // Double (* 2, Utiliser // permet d'écrire les fonctions dans
+ l'ordre d'appel *)
+
+(* En programmation impérative, utiliser ; pour séparer les expressions *)
+Salut[] := (Print@"Hello"; Print@"World") (* Les parenthèses sont nécessaires
+ car ; est prioritaire sur := *)
+Salut[] (* Hello World *)
+
+(* Boucles For à la C *)
+Compter[x_] := For[y=0, y<x, y++, (Print[y])] (* L'évaluation des boucles For
+ se fait comme en C *)
+Compter[5] (* 0 1 2 3 4 *)
+
+(* Boucles While *)
+x = 0; While[x < 2, (Print@x; x++)] (* De nouveau, comme en C *)
+
+(* Expressions conditionnelles et If *)
+x = 8; If[x==8, Print@"Huit", Print@"Pas huit"] (* If [condition, si vrai,
+ si faux] *)
+Switch[x, 2, Print@"Deux", 8, Print@"Huit"] (* Switch par valeur *)
+Which[x==2, Print@"Deux", x==8, Print@"Huit"] (* Switch du type if, else if,
+ else if, ..., else *)
+
+(* Les variables autres que les paramètres de fonctions sont par défaut
+ globales, même à l'intérieur des fonctions *)
+y = 10 (* 10, y est une variable globale *)
+Compter[5] (* 0 1 2 3 4 *)
+y (* 5, y a été modifiée par Compter *)
+x = 20 (* 20, x est une variable globale *)
+Compter[5] (* 0 1 2 3 4 *)
+x (* 20, dans Compter, le paramètre x masque la variable
+ globale x *)
+
+(* La fonction Module permet d'utiliser des variables locales *)
+MieuxCompter[x_] := Module[{y}, (For[y=0, y<x, y++, (Print@y)])]
+y = 20 (* y est une variable globale *)
+MieuxCompter[5] (* 0 1 2 3 4 *)
+y (* 20, y n'a pas été modifiée car le y du Module masque le
+ y global. C'est bien mieux comme ça ! *)
+
+(* Module permet de faire des déclarations globales aussi *)
+Module[{compte}, compte=0; (* compte est une variable locale *)
+ (Incrementer[] := ++compte); (* Ce module déclare des fonctions, mais elles
+ ne sont globales. Elles ont cependant accès
+ aux variables locales au module. *)
+ (Decrementer[] := --compte)]
+compte (* compte, car il n'y a pas de variable globale nommée
+ compte *)
+Incrementer[] (* 1, la fonction utilise la variable compte du module *)
+Incrementer[] (* 2, le précédent appel de Incrementer a modifié compte *)
+Decrementer[] (* 1 *)
+compte (* compte, car il n'existe toujours pas de variable globale
+ nommé compte *)
+
+(* Listes *)
+liste = {1, 2, 3, 4} (* {1, 2, 3, 4} *)
+liste[[1]] (* 1, les indexes commencent à 1 et non 0 !!! *)
+Map[Double, liste] (* {2, 4, 6, 8}, appliquer une fonction à une liste de
+ manière fonctionnelle *)
+Double /@ liste (* {2, 4, 6, 8}, syntaxe abrégée de la ligne
+ précédente *)
+Scan[Print, liste] (* 1 2 3 4, boucle impérative sur une liste *)
+Fold[Plus, 0, liste] (* 10 (0+1+2+3+4) *)
+FoldList[Plus, 0, liste] (* {0, 1, 3, 6, 10}, variante de la fonction
+ précédente qui donne aussi les résultats
+ intermédiaires *)
+Append[liste, 5] (* {1, 2, 3, 4, 5}, liste n'est pas modifiée... *)
+Prepend[liste, 5] (* {5, 1, 2, 3, 4}, ... mais elle peut l'être en
+ écrivant "liste = " *)
+Join[liste, {3, 4}] (* {1, 2, 3, 4, 3, 4} *)
+liste[[2]] = 5 (* {1, 5, 3, 4}, ceci modifie bien la liste *)
+
+(* Tables associatives, ou dictionnaires *)
+table = <|"Vert" -> 2, "Rouge" -> 1|> (* Crée une table associative *)
+table[["Vert"]] (* 2, l'utilise *)
+table[["Vert"]] := 5 (* 5, la modifie *)
+table[["Bleu"]] := 3.5 (* 3.5, l'étend *)
+KeyDropFrom[table, "Vert"] (* Supprime la clé "Vert" *)
+Keys[table] (* {Rouge, Bleu} *)
+Values[table] (* {1, 3.5} *)
+
+(* Pour finir, toute bonne démonstration du langage Wolfram contient un
+ Manipulate ! *)
+Manipulate[y^2, {y, 0, 20}] (* Crée une interface graphique interactive qui
+ affiche y^2, permettant à l'utilisateur de
+ modifier la valeur de y grâce à un contrôle
+ allant de 0 à 20. Ne fonctionne que si le
+ logiciel utilisé gère les éléments graphiques. *)
+```
+
+## Envie d'aller plus loin ?
+
+* [Documentation du langage Wolfram (en anglais)]
+(http://reference.wolfram.com/language/)
diff --git a/fsharp.html.markdown b/fsharp.html.markdown
index 809a1da2..e345201d 100644
--- a/fsharp.html.markdown
+++ b/fsharp.html.markdown
@@ -346,7 +346,7 @@ module DataTypeExamples =
let trySendEmail email =
match email with // use pattern matching
| ValidEmailAddress address -> () // send
- | InvalidEmailAddress address -> () // dont send
+ | InvalidEmailAddress address -> () // don't send
// The combination of union types and record types together
// provide a great foundation for domain driven design.
@@ -426,7 +426,7 @@ module ActivePatternExamples =
// -----------------------------------
// You can create partial matching patterns as well
- // Just use underscore in the defintion, and return Some if matched.
+ // Just use underscore in the definition, and return Some if matched.
let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None
let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None
@@ -627,7 +627,3 @@ module NetCompatibilityExamples =
For more demonstrations of F#, go to the [Try F#](http://www.tryfsharp.org/Learn) site, or my [why use F#](http://fsharpforfunandprofit.com/why-use-fsharp/) series.
Read more about F# at [fsharp.org](http://fsharp.org/).
-
-
-
-
diff --git a/git.html.markdown b/git.html.markdown
index e7ca07d6..6472c462 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -24,9 +24,12 @@ Version control is a system that records changes to a file(s), over time.
### Centralized Versioning VS Distributed Versioning
-* Centralized version control focuses on synchronizing, tracking, and backing up files.
-* Distributed version control focuses on sharing changes. Every change has a unique id.
-* Distributed systems have no defined structure. You could easily have a SVN style, centralized system, with git.
+* Centralized version control focuses on synchronizing, tracking, and backing
+up files.
+* Distributed version control focuses on sharing changes. Every change has a
+unique id.
+* Distributed systems have no defined structure. You could easily have a SVN
+style, centralized system, with git.
[Additional Information](http://git-scm.com/book/en/Getting-Started-About-Version-Control)
@@ -35,13 +38,13 @@ Version control is a system that records changes to a file(s), over time.
* Can work offline.
* Collaborating with others is easy!
* Branching is easy!
+* Branching is fast!
* Merging is easy!
* Git is fast.
* Git is flexible.
## Git Architecture
-
### Repository
A set of files, directories, historical records, commits, and heads. Imagine it
@@ -52,7 +55,8 @@ A git repository is comprised of the .git directory & working tree.
### .git Directory (component of repository)
-The .git directory contains all the configurations, logs, branches, HEAD, and more.
+The .git directory contains all the configurations, logs, branches, HEAD, and
+more.
[Detailed List.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html)
### Working Tree (component of repository)
@@ -62,16 +66,16 @@ referred to as your working directory.
### Index (component of .git dir)
-The Index is the staging area in git. It's basically a layer that separates your working tree
-from the Git repository. This gives developers more power over what gets sent
-to the Git repository.
+The Index is the staging area in git. It's basically a layer that separates
+your working tree from the Git repository. This gives developers more power
+over what gets sent to the Git repository.
### Commit
-A git commit is a snapshot of a set of changes, or manipulations to your Working
-Tree. For example, if you added 5 files, and removed 2 others, these changes
-will be contained in a commit (or snapshot). This commit can then be pushed to
-other repositories, or not!
+A git commit is a snapshot of a set of changes, or manipulations to your
+Working Tree. For example, if you added 5 files, and removed 2 others, these
+changes will be contained in a commit (or snapshot). This commit can then be
+pushed to other repositories, or not!
### Branch
@@ -85,11 +89,14 @@ functionality to mark release points (v1.0, and so on)
### HEAD and head (component of .git dir)
-HEAD is a pointer that points to the current branch. A repository only has 1 *active* HEAD.
-head is a pointer that points to any commit. A repository can have any number of heads.
+HEAD is a pointer that points to the current branch. A repository only has 1
+*active* HEAD.
+head is a pointer that points to any commit. A repository can have any number
+of heads.
### Stages of Git
-* Modified - Changes have been made to a file but file has not been committed to Git Database yet
+* Modified - Changes have been made to a file but file has not been committed
+to Git Database yet
* Staged - Marks a modified file to go into your next commit snapshot
* Committed - Files have been committed to the Git Database
@@ -98,14 +105,12 @@ head is a pointer that points to any commit. A repository can have any number of
* [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/)
* [Git For Designers](http://hoth.entp.com/output/git_for_designers.html)
-
## Commands
-
### init
-Create an empty Git repository. The Git repository's settings, stored information,
-and more is stored in a directory (a folder) named ".git".
+Create an empty Git repository. The Git repository's settings, stored
+information, and more is stored in a directory (a folder) named ".git".
```bash
$ git init
@@ -116,7 +121,6 @@ $ git init
To configure settings. Whether it be for the repository, the system itself,
or global configurations ( global config file is `~/.gitconfig` ).
-
```bash
# Print & Set Some Basic Config Variables (Global)
$ git config --global user.email "MyEmail@Zoho.com"
@@ -157,13 +161,11 @@ $ echo "temp/" >> .gitignore
$ echo "private_key" >> .gitignore
```
-
### status
To show differences between the index file (basically your working copy/repo)
and the current HEAD commit.
-
```bash
# Will display the branch, untracked files, changes and other differences
$ git status
@@ -174,8 +176,8 @@ $ git help status
### add
-To add files to the staging area/index. If you do not `git add` new files to the
-staging area/index, they will not be included in commits!
+To add files to the staging area/index. If you do not `git add` new files to
+the staging area/index, they will not be included in commits!
```bash
# add a file in your current working directory
@@ -193,7 +195,8 @@ working directory/repo.
### branch
-Manage your branches. You can view, edit, create, delete branches using this command.
+Manage your branches. You can view, edit, create, delete branches using this
+command.
```bash
# list existing branches & remotes
@@ -220,54 +223,64 @@ Manage your tags
```bash
# List tags
$ git tag
+
# Create a annotated tag
# The -m specifies a tagging message,which is stored with the tag.
# If you don’t specify a message for an annotated tag,
# Git launches your editor so you can type it in.
$ git tag -a v2.0 -m 'my version 2.0'
+
# Show info about tag
# That shows the tagger information, the date the commit was tagged,
# and the annotation message before showing the commit information.
$ git show v2.0
+
# Push a single tag to remote
$ git push origin v2.0
+
# Push a lot of tags to remote
$ git push origin --tags
```
### checkout
-Updates all files in the working tree to match the version in the index, or specified tree.
+Updates all files in the working tree to match the version in the index, or
+specified tree.
```bash
# Checkout a repo - defaults to master branch
$ git checkout
+
# Checkout a specified branch
$ git checkout branchName
+
# Create a new branch & switch to it
# equivalent to "git branch <name>; git checkout <name>"
+
$ git checkout -b newBranch
```
### clone
Clones, or copies, an existing repository into a new directory. It also adds
-remote-tracking branches for each branch in the cloned repo, which allows you to push
-to a remote branch.
+remote-tracking branches for each branch in the cloned repo, which allows you
+to push to a remote branch.
```bash
# Clone learnxinyminutes-docs
$ git clone https://github.com/adambard/learnxinyminutes-docs.git
+
# shallow clone - faster cloning that pulls only latest snapshot
$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git
+
# clone only a specific branch
$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch
```
### commit
-Stores the current contents of the index in a new "commit." This commit contains
-the changes made and a message created by the user.
+Stores the current contents of the index in a new "commit." This commit
+contains the changes made and a message created by the user.
```bash
# commit with a message
@@ -382,7 +395,8 @@ $ git pull origin master
$ git pull
# Merge in changes from remote branch and rebase
-# branch commits onto your local repo, like: "git pull <remote> <branch>, git rebase <branch>"
+# branch commits onto your local repo, like: "git pull <remote> <branch>, git
+# rebase <branch>"
$ git pull origin master --rebase
```
@@ -408,8 +422,8 @@ $ git push
### stash
-Stashing takes the dirty state of your working directory and saves it on a stack
-of unfinished changes that you can reapply at any time.
+Stashing takes the dirty state of your working directory and saves it on a
+stack of unfinished changes that you can reapply at any time.
Let's say you've been doing some work in your git repo, but you want to pull
from the remote. Since you have dirty (uncommited) changes to some files, you
@@ -440,7 +454,8 @@ nothing to commit, working directory clean
```
You can see what "hunks" you've stashed so far using `git stash list`.
-Since the "hunks" are stored in a Last-In-First-Out stack, our most recent change will be at top.
+Since the "hunks" are stored in a Last-In-First-Out stack, our most recent
+change will be at top.
```bash
$ git stash list
@@ -470,7 +485,8 @@ Now you're ready to get back to work on your stuff!
### rebase (caution)
-Take all changes that were committed on one branch, and replay them onto another branch.
+Take all changes that were committed on one branch, and replay them onto
+another branch.
*Do not rebase commits that you have pushed to a public repo*.
```bash
@@ -484,8 +500,8 @@ $ git rebase master experimentBranch
### reset (caution)
Reset the current HEAD to the specified state. This allows you to undo merges,
-pulls, commits, adds, and more. It's a great command but also dangerous if you don't
-know what you are doing.
+pulls, commits, adds, and more. It's a great command but also dangerous if you
+don't know what you are doing.
```bash
# Reset the staging area, to match the latest commit (leaves dir unchanged)
@@ -503,11 +519,12 @@ $ git reset 31f2bb1
# after the specified commit).
$ git reset --hard 31f2bb1
```
+
### revert
-Revert can be used to undo a commit. It should not be confused with reset which restores
-the state of a project to a previous point. Revert will add a new commit which is the
-inverse of the specified commit, thus reverting it.
+Revert can be used to undo a commit. It should not be confused with reset which
+restores the state of a project to a previous point. Revert will add a new
+commit which is the inverse of the specified commit, thus reverting it.
```bash
# Revert a specified commit
@@ -540,7 +557,7 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/)
-* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
+* [SalesForce Cheat Sheet](http://res.cloudinary.com/hy4kyit2a/image/upload/SF_git_cheatsheet.pdf)
* [GitGuys](http://www.gitguys.com/)
@@ -549,4 +566,3 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [Pro Git](http://www.git-scm.com/book/en/v2)
* [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners)
-
diff --git a/groovy.html.markdown b/groovy.html.markdown
index 492c1ba2..94678c39 100644
--- a/groovy.html.markdown
+++ b/groovy.html.markdown
@@ -13,8 +13,8 @@ Groovy - A dynamic language for the Java platform [Read more here.](http://www.g
/*
Set yourself up:
- 1) Install GVM - http://gvmtool.net/
- 2) Install Groovy: gvm install groovy
+ 1) Install SDKMAN - http://sdkman.io/
+ 2) Install Groovy: sdk install groovy
3) Start the groovy console by typing: groovyConsole
*/
@@ -280,7 +280,7 @@ def clos = { print it }
clos( "hi" )
/*
- Groovy can memorize closure results [1][2][3]
+ Groovy can memoize closure results [1][2][3]
*/
def cl = {a, b ->
sleep(3000) // simulate some time consuming processing
diff --git a/haskell.html.markdown b/haskell.html.markdown
index 936744a0..4ce1a839 100644
--- a/haskell.html.markdown
+++ b/haskell.html.markdown
@@ -189,16 +189,16 @@ foo = add 10 -- foo is now a function that takes a number and adds 10 to it
foo 5 -- 15
-- Another way to write the same thing
-foo = (+10)
+foo = (10+)
foo 5 -- 15
-- function composition
--- the (.) function chains functions together.
+-- the operator `.` chains functions together.
-- For example, here foo is a function that takes a value. It adds 10 to it,
-- multiplies the result of that by 4, and then returns the final value.
-foo = (*4) . (+10)
+foo = (4*) . (10+)
--- (5 + 10) * 4 = 60
+-- 4*(10 + 5) = 60
foo 5 -- 60
-- fixing precedence
@@ -222,7 +222,7 @@ even . fib $ 7 -- false
-- 5. Type signatures
----------------------------------------------------
--- Haskell has a very strong type system, and everything has a type signature.
+-- Haskell has a very strong type system, and every valid expression has a type.
-- Some basic types:
5 :: Integer
@@ -259,7 +259,7 @@ case args of
_ -> putStrLn "bad args"
-- Haskell doesn't have loops; it uses recursion instead.
--- map applies a function over every element in an array
+-- map applies a function over every element in a list
map (*2) [1..5] -- [2, 4, 6, 8, 10]
@@ -279,7 +279,7 @@ foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43
-- This is the same as
(2 * (2 * (2 * 4 + 1) + 2) + 3)
--- foldl is left-handed, foldr is right-
+-- foldl is left-handed, foldr is right-handed
foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16
-- This is now the same as
@@ -318,7 +318,7 @@ Nothing -- of type `Maybe a` for any `a`
-- it is not hard to explain enough to get going.
-- When a Haskell program is executed, `main` is
--- called. It must return a value of type `IO ()`. For example:
+-- called. It must return a value of type `IO a` for some type `a`. For example:
main :: IO ()
main = putStrLn $ "Hello, sky! " ++ (say Blue)
@@ -361,7 +361,7 @@ sayHello = do
-- You can think of a value of type `IO a` as representing a
-- computer program that will generate a value of type `a`
-- when executed (in addition to anything else it does). We can
--- store and reuse this value using `<-`. We can also
+-- name and reuse this value using `<-`. We can also
-- make our own action of type `IO String`:
action :: IO String
@@ -401,11 +401,26 @@ main'' = do
let foo = 5
--- You can see the type of any value with `:t`:
+-- You can see the type of any value or expression with `:t`:
->:t foo
+> :t foo
foo :: Integer
+-- Operators, such as `+`, `:` and `$`, are functions.
+-- Their type can be inspected by putting the operator in parentheses:
+
+> :t (:)
+(:) :: a -> [a] -> [a]
+
+-- You can get additional information on any `name` using `:i`:
+
+> :i (+)
+class Num a where
+ (+) :: a -> a -> a
+ ...
+ -- Defined in ‘GHC.Num’
+infixl 6 +
+
-- You can also run any action of type `IO ()`
> sayHello
@@ -417,7 +432,7 @@ Hello, Friend!
There's a lot more to Haskell, including typeclasses and monads. These are the
big ideas that make Haskell such fun to code in. I'll leave you with one final
-Haskell example: an implementation of quicksort in Haskell:
+Haskell example: an implementation of a quicksort variant in Haskell:
```haskell
qsort [] = []
@@ -426,7 +441,7 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater
greater = filter (>= p) xs
```
-Haskell is easy to install. Get it [here](http://www.haskell.org/platform/).
+There are two popular ways to install Haskell: The traditional [Cabal-based installation](http://www.haskell.org/platform/), and the newer [Stack-based process](https://www.stackage.org/install).
You can find a much gentler introduction from the excellent
[Learn you a Haskell](http://learnyouahaskell.com/) or
diff --git a/hu-hu/ruby-hu.html.markdown b/hu-hu/ruby-hu.html.markdown
index 169f2b8e..f2fe4e5d 100644
--- a/hu-hu/ruby-hu.html.markdown
+++ b/hu-hu/ruby-hu.html.markdown
@@ -1,7 +1,7 @@
---
language: ruby
lang: hu-hu
-filenev: learnruby.rb
+filename: learnruby-hu.rb
contributors:
- ["David Underwood", "http://theflyingdeveloper.com"]
- ["Joel Walden", "http://joelwalden.net"]
@@ -13,7 +13,7 @@ contributors:
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
- ["Levi Bostian", "https://github.com/levibostian"]
- ["Rahil Momin", "https://github.com/iamrahil"]
- translators:
+translators:
- ["Zsolt Prontvai", "https://github.com/prozsolt"]
---
diff --git a/hu-hu/yaml-hu.html.markdown b/hu-hu/yaml-hu.html.markdown
new file mode 100644
index 00000000..37ce4cb2
--- /dev/null
+++ b/hu-hu/yaml-hu.html.markdown
@@ -0,0 +1,147 @@
+---
+language: yaml
+filename: learnyaml-hu.yaml
+contributors:
+ - ["Adam Brenecki", "https://github.com/adambrenecki"]
+translators:
+ - ["Tamás Diószegi", "https://github.com/ditam"]
+lang: hu-hu
+---
+
+A YAML egy adat sorosító nyelv, amit úgy terveztek, hogy közvetlenül is
+olvasható és írható legyen emberi szemmel.
+
+A JSON formátum egy szigorú befoglaló halmazát alkotja, kiegészítve azt
+szintaktikai jelentéssel bíró sortörésekkel és indentációval,
+a Pythonhoz hasonlóan. A Pythonnal ellentétben azonban a YAML nem engedélyezi
+a közvetlen tab karakterek jelenlétét.
+
+Megjegyzés: UTF-8 ékezetes betűk használhatóak, ha a fájl kódlása megfelelő,
+a kódolást a tartalomban explicit nem kell (és nem is lehet) feltüntetni.
+
+```yaml
+# A kommentek YAML-ban így néznek ki.
+
+##################
+# Skalár típusok #
+##################
+
+# A gyökér objektumunk (az egész dokumentumra értve) egy map,
+# ami a más nyelvekből ismert dictionary, hash vagy object típusokkal egyenértékű.
+kulcs: érték
+masik_kulcs: Másik érték jön ide.
+egy_szam: 100
+tudomanyos_jelolessel: 1e+12
+boolean: true
+null_value: null
+kulcs benne szóközökkel: érték
+# Látható, hogy a sztringeket nem szükséges idézőjelek közé zárni, bár szabad.
+Továbbá: "Idézőjelekkel megadott sztring."
+"A kulcs is lehet idézőjeles.": "Hasznos lehet, ha ':'-ot akarsz a kulcsban."
+
+# Többsoros sztringek írhatóak 'literal block'-ként ('|' jelet használva)
+# vagy 'folded block'-ként is ('>' jelet használva).
+literal_block: |
+ Ez az egész szöveg-blokk lesz az értéke a literal_block kulcsnak,
+ a sortöréseket megtartva.
+
+ Az ilyen sztringet az indentáció visszahúzása zárja le, a behúzás pedig
+ eltávolításra kerül.
+
+ A 'még jobban' behúzott részek megtartják a behúzásukat -
+ ezeknek a soroknak 4 szóköz behúzása lesz.
+folded_style: >
+ Az az egész szöveg-blokk lesz az értéke a 'folded_style' kulcsnak, de
+ ezúttal minden sortörés egy szóközre lesz cserélve.
+
+ Az üres sorok, mint a fenti, új sor karakterre cserélődnek.
+
+ A 'még jobban' behúzott sorok megtartják a sortöréseiket, -
+ ez a szöveg két sorban jelenik meg.
+
+######################
+# Gyűjtemény típusok #
+######################
+
+# Egymásba ágyazás a behúzás változtatásával érhető el.
+beagyazott_map:
+ key: value
+ another_key: Another Value
+ masik_beagyazott_map:
+ hello: hello
+
+# A mapeknek nem csak sztring kulcsaik lehetnek.
+0.25: lebegőpontos kulcs
+
+# A kulcsok lehetnek többsoros objektumok is, ? jellel jelezve a kulcs kezdetét
+? |
+ Ez itt egy
+ többsoros kulcs
+: és ez az értéke
+
+# Szintén engedélyezett a kollekció típusok használata kulcsként, de egyéb
+# nyelvekben ez gyakran problémákat fog okozni.
+
+# Szekvenciák (listákkal vagy tömbökkel egyenértékűek) így néznek ki:
+egy_szekvencia:
+ - Item 1
+ - Item 2
+ - 0.5 # Többféle típust is tartalmazhat
+ - Item 4
+ - key: value
+ another_key: another_value
+ -
+ - Ez egy szekvencia
+ - egy másik szekvenciába ágyazva
+
+# Mivel a YAML a JSON befoglaló halmazát alkotja, JSON szintaxisú
+# mapek és szekvenciák is használhatóak:
+json_map: {"key": "value"}
+json_seq: [3, 2, 1, "takeoff"]
+
+#########################
+# EXTRA YAML KÉPESSÉGEK #
+#########################
+
+# A YAML-ben ún. 'anchor'-ök segítségével könnyen lehet duplikálni
+# tartalmakat a dokumentumon belül. A következő kulcsok azonos értékkel bírnak:
+anchored_tartalom: &anchor_neve Ez a sztring két kulcs értéke is lesz.
+másik_anchor: *anchor_neve
+
+# Vannak a YAML-ben tagek is, amivel explicit lehet típusokat jelölni.
+explicit_string: !!str 0.5
+# Bizonyos implementációk nyelv-specifikus tageket tartalmaznak, mint
+# például ez a Python komplex szám típusának jelölésére:
+python_complex_number: !!python/complex 1+2j
+
+######################
+# EXTRA YAML TÍPUSOK #
+######################
+
+# Nem a sztringek és a számok az egyedüli skalár típusok YAML-ben.
+# ISO-formátumú dátumok és dátumot jelölő literal kifejezések is értelmezettek.
+datetime: 2001-12-15T02:59:43.1Z
+datetime_with_spaces: 2001-12-14 21:59:43.10 -5
+date: 2002-12-14
+
+# A !!binary tag jelöli, hogy egy sztring valójában base64-kódolású
+# reprezentációja egy bináris blob-nak
+gif_file: !!binary |
+ R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
+ OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+ +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
+ AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
+
+# Létezik a YAML-ban egy halmaz típus (set) is, ami így néz ki:
+set:
+ ? elem1
+ ? elem2
+ ? elem3
+
+# Mint Pythonban, a halmazok null értékekkel feltöltött mapek, vagyis a fenti
+# halmaz egyenértékű a következővel:
+set2:
+ elem1: null
+ elem2: null
+ elem3: null
+``` \ No newline at end of file
diff --git a/hy.html.markdown b/hy.html.markdown
index 9beaff0c..79c16c23 100644
--- a/hy.html.markdown
+++ b/hy.html.markdown
@@ -3,13 +3,14 @@ language: hy
filename: learnhy.hy
contributors:
- ["Abhishek L", "http://twitter.com/abhishekl"]
+ - ["Zirak", "http://zirak.me"]
---
Hy is a lisp dialect built on top of python. This is achieved by
converting hy code to python's abstract syntax tree (ast). This allows
hy to call native python code or python to call native hy code as well
-This tutorial works for hy ≥ 0.9.12
+This tutorial works for hy ≥ 0.9.12, with some corrections for hy 0.11.
```clojure
;; this gives an gentle introduction to hy for a quick trial head to
@@ -89,6 +90,17 @@ True ; => True
(foolists 3) ;=> [3 2]
(foolists 10 3) ;=> [10 3]
+; you can use rest arguments and kwargs too:
+(defn something-fancy [wow &rest descriptions &kwargs props]
+ (print "Look at" wow)
+ (print "It's" descriptions)
+ (print "And it also has:" props))
+
+(something-fancy "My horse" "amazing" :mane "spectacular")
+
+; you use apply instead of the splat operators:
+(apply something-fancy ["My horse" "amazing"] { "mane" "spectacular" })
+
; anonymous functions are created using `fn' or `lambda' constructs
; which are similiar to `defn'
(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16]
@@ -102,6 +114,8 @@ True ; => True
; slice lists using slice
(slice mylist 1 3) ;=> [2 3]
+; or, in hy 0.11, use cut instead:
+(cut mylist 1 3) ;=> [2 3]
; get elements from a list or dict using `get'
(get mylist 1) ;=> 2
@@ -122,6 +136,22 @@ True ; => True
; a.foo(arg) is called as (.foo a arg)
(.split (.strip "hello world ")) ;=> ["hello" "world"]
+; there is a shortcut for executing multiple functions on a value called the
+; "threading macro", denoted by an arrow:
+(-> "hello world " (.strip) (.split)) ;=> ["hello" "world]
+; the arrow passes the value along the calls as the first argument, for instance:
+(-> 4 (* 3) (+ 2))
+; is the same as:
+(+ (* 4 3) 2)
+
+; there is also a "threading tail macro", which instead passes the value as the
+; second argument. compare:
+(-> 4 (- 2) (+ 1)) ;=> 3
+(+ (- 4 2) 1) ;=> 3
+; to:
+(->> 4 (- 2) (+ 1)) ;=> -1
+(+ 1 (- 2 4)) ;=> -1
+
;; Conditionals
; (if condition (body-if-true) (body-if-false)
(if (= passcode "moria")
@@ -160,6 +190,14 @@ True ; => True
[get-spell (fn [self]
self.spell)]])
+; or, in hy 0.11:
+(defclass Wizard [object]
+ (defn --init-- [self spell]
+ (setv self.spell spell))
+
+ (defn get-spell [self]
+ self.spell))
+
;; do checkout hylang.org
```
@@ -169,6 +207,6 @@ This tutorial is just a very basic introduction to hy/lisp/python.
Hy docs are here: [http://hy.readthedocs.org](http://hy.readthedocs.org)
-Hy's Github repo: [http://github.com/hylang/hy](http://github.com/hylang/hy)
+Hy's GitHub repo: [http://github.com/hylang/hy](http://github.com/hylang/hy)
On freenode irc #hy, twitter hashtag #hylang
diff --git a/id-id/json-id.html.markdown b/id-id/json-id.html.markdown
index 52e61449..ca346f6c 100644
--- a/id-id/json-id.html.markdown
+++ b/id-id/json-id.html.markdown
@@ -1,11 +1,12 @@
---
language: json
-filename: learnjson.json
+filename: learnjson-id.json
contributors:
- ["Anna Harren", "https://github.com/iirelu"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
-translators
+translators:
- ["Rizky Luthfianto", "https://github.com/rilut"]
+lang: id-id
---
JSON adalah format pertukaran data yang sangat simpel, kemungkinan besar,
diff --git a/id-id/php-id.html.markdown b/id-id/php-id.html.markdown
new file mode 100644
index 00000000..34d6e5f5
--- /dev/null
+++ b/id-id/php-id.html.markdown
@@ -0,0 +1,848 @@
+---
+language: PHP
+contributors:
+ - ["Malcolm Fell", "http://emarref.net/"]
+ - ["Trismegiste", "https://github.com/Trismegiste"]
+filename: learnphp-id.php
+translators:
+ - ["Ahmad Zafrullah", "https://github.com/23Pstars"]
+lang: id-id
+---
+
+Dokumen ini menjelaskan tentang PHP5 keatas.
+
+```php
+<?php // Skrip PHP harus diawali dengan tag <?php
+
+// Jika dokumen PHP hanya mengandung kode PHP, sebaiknya tidak menggunakan
+// tag penutup PHP untuk menghindari ketidaksengajaan tampilnya sesuatu.
+
+// Dua garis miring diawal digunakan untuk komentar satu baris.
+
+/*
+ Membatasi teks dalam garis miring-bintang dan bintang-garis miring
+ membuat komentar untuk banyak-baris sekaligus.
+*/
+
+// Gunakan "echo" or "print" untuk menampilkan sesuatu
+print('Halo '); // Menampilkan "Halo " tanpa baris baru
+
+// () boleh tidak digunakan dalam menggunakan "print" dan "echo"
+echo "Dunia\n"; // Menampilkan "Dunia" dengan baris baru
+// (semua perintah harus diakhiri dengan titik koma)
+
+// Apapun yang berada diluar tag <?php akan ditampilkan secara otomatis
+?>
+Halo Dunia, lagi!
+<?php
+
+
+/************************************
+ * Tipe Data & Variabel
+ */
+
+// Variabel diawali dengan simnbol $.
+// Nama variabel yang benar diawali dengan huruf atau garis-bawah,
+// diikuti dengan beberapa huruf, angka, dan garis-bawah lainnya.
+
+// Nilai Boolean adalah case-insensitive
+$boolean = true; // atau TRUE atau True
+$boolean = false; // atau FALSE atau False
+
+// Nilai Integer
+$int1 = 12; // => 12
+$int2 = -12; // => -12
+$int3 = 012; // => 10 (awalan 0 menandakan bilangan Oktal)
+$int4 = 0x0F; // => 15 (awalan 0x menandakan bilangan Heksadesimal)
+// Bilangan Biner Integer tersedia mulai dari PHP 5.4.0.
+$int5 = 0b11111111; // 255 (awalan 0b menandakan bilangan Biner)
+
+// Nilai Floats (dikenal juga sebagai Doubles)
+$float = 1.234;
+$float = 1.2e3;
+$float = 7E-10;
+
+// Menghapus variable
+unset($int1);
+
+// Aritmatika
+$jumlah = 1 + 1; // 2
+$selisih = 2 - 1; // 1
+$perkalian = 2 * 2; // 4
+$pembagian = 2 / 1; // 2
+
+// Aritmatika singkat
+$angka = 0;
+$angka += 1; // Menjumlahkan $angka dengan 1
+echo $angka++; // Menampilkan 1 (dijumlahkan dengan 1 setelah ditampilkan)
+echo ++$angka; // Menampilkan 3 (dijumlahkan dengan 1 sebelum ditampilkan)
+$angka /= $float; // Membagi dan menyimpan hasil pembagian pada $angka;
+
+// String biasanya diawali dan ditutup dengan petik satu.
+$sgl_quotes = '$String'; // => '$String'
+
+// Hindari menggunakan petik dua kecuali menyertakan variabel lain
+$dbl_quotes = "Ini adalah $sgl_quotes."; // => 'Ini adalah $String.'
+
+// Karakter khusus hanya berlaku pada petik dua
+$berfungsi = "Ini mengandung \t karakter tab.";
+$tidak_berfungsi = 'Ini hanya mengandung garis miring dan huruf t: \t';
+
+// Batasi variabel dengan kurung kurawal jika diperlukan
+$uang = "Saya memiliki $${angka} di Bank.";
+
+// Sejak PHP 5.3, nowdocs dapat digunakan untuk tak-terinterpolasi banyak-baris
+$nowdoc = <<<'END'
+Banyak baris
+string
+END;
+
+// Heredocs akan melakukan interpolasi
+$heredoc = <<<END
+Banyak baris
+$sgl_quotes
+END;
+
+// Menyambung string dapat dilakukan menggunakan .
+echo 'String ini ' . 'tersambung';
+
+// String dapat dijadikan parameter pada "echo"
+echo 'Banyak', 'Parameter', 'String'; // Menampilkan 'BanyakParameterString'
+
+
+/********************************
+ * Konstan
+ */
+
+// Sebuah konstan didifinisikan menggunakan fungsi define()
+// dan tidak bisa diganti/rubah selama program berjalan!
+
+// Nama konstan yang benar diawali dengan huruf dan garis-bawah,
+// diikuti dengan beberapa huruf, angka, atau garis-bawah.
+define("FOO", "sesuatu");
+
+// Mengakses konstan memungkinkan untuk dapat dipanggil tanpa menggunakan simbol $
+echo FOO; // Menampilkan 'sesuatu'
+echo 'Keluaran ini adalah ' . FOO; // Menampilkan 'Keluaran ini adalah sesuatu'
+
+
+
+/********************************
+ * Larik (Array)
+ */
+
+// Semua larik dalam PHP bersifat asosiatif (saling berhubungan).
+
+// Berfungsi pada semua versi PHP
+$asosiatif = array('Satu' => 1, 'Dua' => 2, 'Tiga' => 3);
+
+// Pada PHP 5.4 diperkenalkan cara penulisan (sintaks) baru
+$asosiatif = ['Satu' => 1, 'Dua' => 2, 'Tiga' => 3];
+
+echo $asosiatif['Satu']; // menampilkan 1
+
+// Daftar literal secara tidak langsung ditentukan oleh kunci integer
+$larik = ['Satu', 'Dua', 'Tiga'];
+echo $larik[0]; // => "Satu"
+
+// Menambahkan sebuah elemen pada akhir larik
+$larik[] = 'Empat';
+// atau
+array_push($larik, 'Lima');
+
+// Menghapus elemen dari larik
+unset($larik[3]);
+
+/********************************
+ * Keluaran
+ */
+
+echo('Halo Dunia!');
+// Menampilkan Halo Dunia! ke "stdout".
+// "stdout" adalah sebuah halaman web ketika dijalankan dalam peramban (browser).
+
+print('Halo Dunia!'); // Sama seperti "echo"
+
+// "echo" dan "print" merupakan bahasa konstruksi, jadi tanda kurung dapat dihilangkan
+echo 'Halo Dunia!';
+print 'Halo Dunia!';
+
+$paragraf = 'paragraf';
+
+echo 100; // Menampilkan variabel skalar secara langsung
+echo $paragraf; // atau sebuat variabel
+
+// Jika PHP tag-singkat telah dikonfigurasi, atau versi PHP yang digunakan
+// adalah 5.4.0 keatas, dapat digunakan sintaks "echo" singkat
+
+?>
+<p><?= $paragraf ?></p>
+<?php
+
+$x = 1;
+$y = 2;
+$x = $y; // $x sekarang berisi nilai yang sama dengan $y
+$z = &$y;
+// $z sekarang berisi referensi ke $y. Mengubah nilai dari $z
+// akan mengubah nilai dari $y juga, begitupun sebaliknya.
+// $x tetap tidak berubah sebagaimana nilai asli dari $y
+
+echo $x; // => 2
+echo $z; // => 2
+$y = 0;
+echo $x; // => 2
+echo $z; // => 0
+
+// Menampilkan tipe dan nilai dari variabel ke "stdout"
+var_dump($z); // prints int(0)
+
+// Menampilkan variabel ke "stdout" dalam format yang mudah dibaca
+print_r($larik); // menampilkan: Array ( [0] => Satu [1] => Dua [2] => Tiga )
+
+/********************************
+ * Logika
+ */
+$a = 0;
+$b = '0';
+$c = '1';
+$d = '1';
+
+// menegaskan lemparan sebuah peringatan jika pernyataan tidak benar
+
+// Perbandingan berikut akan selalu benar, meskipun memiliki tipe yang berbeda.
+assert($a == $b); // kesamaan
+assert($c != $a); // ketidak-samaan
+assert($c <> $a); // versi lain dari ketidak-samaan
+assert($a < $c);
+assert($c > $b);
+assert($a <= $b);
+assert($c >= $d);
+
+// Dibawah ini hanya akan bernilai benar jika nilainya memiliki tipe yang sama.
+assert($c === $d);
+assert($a !== $d);
+assert(1 === '1');
+assert(1 !== '1');
+
+// Operator 'Spaceship' (sejak PHP 7)
+// Mengembalikan 0 jika nilai pada kedua sisi adalah sama
+// Mengembalikan 1 jika nilai pada sisi kiri lebih besar
+// Mengembalikan -1 jika nilai pada sisi kanan lebih besar
+
+$a = 100;
+$b = 1000;
+
+echo $a <=> $a; // 0 karena keduanya sama
+echo $a <=> $b; // -1 karena $a < $b
+echo $b <=> $a; // 1 karena $b > $a
+
+// Variabel dapat dikonversi menjadi tipe lain, sesuai penggunaannya.
+
+$integer = 1;
+echo $integer + $integer; // => 2
+
+$string = '1';
+echo $string + $string; // => 2 (string dipaksa menjadi integer)
+
+$string = 'satu';
+echo $string + $string; // => 0
+// Menghasilkan 0 karena operator (+) tidak dapat memaksa string 'satu' menjadi sebuah integer
+
+// Perubahan tipe dapat dimanfaatkan untuk diperlakukan sebagai tipe lainnya
+
+$boolean = (boolean) 1; // => true
+
+$nol = 0;
+$boolean = (boolean) $nol; // => false
+
+// Terdapat juga fungsi khusus untuk melakukan perubahan terhadap beberapa tipe
+$integer = 5;
+$string = strval($integer);
+
+$var = null; // Nilai Null
+
+
+/********************************
+ * Struktur Kontrol
+ */
+
+if (true) {
+ print 'Saya tampil';
+}
+
+if (false) {
+ print 'Saya tidak tampil';
+} else {
+ print 'Saya tampil';
+}
+
+if (false) {
+ print 'Tidak tampil';
+} elseif(true) {
+ print 'Tampil';
+}
+
+// operator ternary
+print (false ? 'Tidak tampil' : 'Tampil');
+
+// cara pintas operator ternary mulai dirilis sejak PHP 5.3
+// persamaan dari "$x ? $x : 'Kerjakan'"
+$x = false;
+print($x ?: 'Kerjakan');
+
+// operator null coalesce sejak PHP 7
+$a = null;
+$b = 'Ditampilkan';
+echo $a ?? 'a belum di-set'; // menampilkan 'a belum di-set'
+echo $b ?? 'b belum di-set'; // menampilkan 'Ditampilkan'
+
+
+$x = 0;
+if ($x === '0') {
+ print 'Tidak ditampilkan';
+} elseif($x == '1') {
+ print 'Tidak ditampilkan';
+} else {
+ print 'Tampil';
+}
+
+
+// Alternatif sintaks untuk kebutuhan templat:
+?>
+
+<?php if ($x): ?>
+Ini ditampilkan jika pengujian benar.
+<?php else: ?>
+Selain tersebut ini yang akan ditampilkan.
+<?php endif; ?>
+
+<?php
+
+// Gunakan "switch" untuk menghemat logika.
+switch ($x) {
+ case '0':
+ print 'Switch mendukung tipe paksaan';
+ break; // Kata kunci "break" harus disertakan, jika tidak
+ // maka logika tersebut akan berlanjut ke bagian "dua" dan "tiga"
+ case 'dua':
+ case 'tiga':
+ // Lakukan sesuatu jika $x bernilai "dua" atau "tiga"
+ break;
+ default:
+ // Aksi cadangan
+}
+
+// "while", "do...while" dan perulangan "for"
+$i = 0;
+while ($i < 5) {
+ echo $i++;
+}; // Menampilkan "01234"
+
+echo "\n";
+
+$i = 0;
+do {
+ echo $i++;
+} while ($i < 5); // Menampilkan "01234"
+
+echo "\n";
+
+for ($x = 0; $x < 10; $x++) {
+ echo $x;
+} // Menampilkan "0123456789"
+
+echo "\n";
+
+$roda = ['sepeda' => 2, 'mobil' => 4];
+
+// Perulangan "foreach" dapat melakukan iterasi pada larik (array)
+foreach ($roda as $jumlah_roda) {
+ echo $jumlah_roda;
+} // Menampilkan "24"
+
+echo "\n";
+
+// Iterasi dapat dilakukan terhadap "key" (kunci) dan "value" (nilai)
+foreach ($roda as $mesin => $jumlah_roda) {
+ echo "$mesin memiliki $jumlah_roda buah roda";
+}
+
+echo "\n";
+
+$i = 0;
+while ($i < 5) {
+ if ($i === 3) {
+ break; // Menghentikan proses perulangan
+ }
+ echo $i++;
+} // Menampilkan "012"
+
+for ($i = 0; $i < 5; $i++) {
+ if ($i === 3) {
+ continue; // Melewati tahapan iterasi saat ini
+ }
+ echo $i;
+} // Menampilkan "0124"
+
+
+/********************************
+ * Fungsi
+ */
+
+// Fungsi didefinisikan dengan "function":
+function fungsi_saya () {
+ return 'Halo';
+}
+
+echo fungsi_saya(); // => "Halo"
+
+// Nama fungsi yang baik dan benar diawali dengan sebuah huruf atau garis-bawah, diikuti oleh
+// beberapa huruf, angka, atau garis-bawah.
+
+function jumlah ($x, $y = 1) { // $y merupakan opsional, jika tidak ditentukan akan bernilai 1
+ $hasil = $x + $y;
+ return $hasil;
+}
+
+echo jumlah(4); // => 5
+echo jumlah(4, 2); // => 6
+
+// $hasil tidak dapat diakses dari luar fungsi
+// print $hasil; // Akan menghasilkan sebuah "warning".
+
+// Sejak PHP 5.3 fungsi dapat dideklarasikan menjadi tanpa-nama (anonymous);
+$inc = function ($x) {
+ return $x + 1;
+};
+
+echo $inc(2); // => 3
+
+function foo ($x, $y, $z) {
+ echo "$x - $y - $z";
+}
+
+// Fungsi dapat mengembalikan fungsi juga
+function bar ($x, $y) {
+ // Gunakan "use" untuk mengakses variabel diluar fungsi
+ return function ($z) use ($x, $y) {
+ foo($x, $y, $z);
+ };
+}
+
+$bar = bar('A', 'B');
+$bar('C'); // Menampilkan "A - B - C"
+
+// Fungsi uang memiliki nama dapat dipanggil berdasarkan string
+$nama_fungsi = 'jumlah';
+echo $nama_fungsi(1, 2); // => 3
+// Bermanfaat untuk menentukan fungsi mana yang akan dipanggil secara dinamis.
+// Atau, dapat juga menggunakan fungsi call_user_func(callable $callback [, $parameter [, ... ]]);
+
+// Akses semua parameter yang dikirim ke sebuah fungsi
+function parameter() {
+ $jumlah_param = func_num_args();
+ if( $jumlah_param > 0 ) {
+ echo func_get_arg(0) . ' | ';
+ }
+ $daftar_param = func_get_args();
+ foreach( $daftar_param as $kunci => $param ) {
+ echo $kunci . ' - ' . $param . ' | ';
+ }
+}
+
+parameter('Halo', 'Dunia'); // Halo | 0 - Halo | 1 - Dunia |
+
+// Sejak PHP 5.6, mendapatkan jumlah variabel yang ada pada parameter
+function variabel($kata, ...$daftar) {
+ echo $kata . " || ";
+ foreach ($daftar as $item) {
+ echo $item . ' | ';
+ }
+}
+
+variable("Pemisah", "Halo", "Dunia") // Pemisah || Halo | Dunia |
+
+/********************************
+ * Penyertaan ("include")
+ */
+
+<?php
+// Skrip PHP yang berada dalam dokumen "include" juga harus dibuka dengan tag PHP.
+
+include 'dokumen-saya.php';
+// Kode yang ada dalam dokumen-saya.php sekarang dapat diakses dari cakupan saat ini.
+// Jika dokumen tidak dapat disertakan (include, seperti dokumen tidak ditemukan), maka pesan peringatan akan muncul.
+
+include_once 'dokumen-saya.php';
+// Jika dokumen-saya telah disertakan (include) oleh perintah sebelumnya, maka
+// dokumen tersebut tidak akan disertakan lagi. Ini bertujuan untuk menghindari kesalahan
+// yang diakibatkan oleh deklarasi ganda.
+
+require 'dokumen-saya.php';
+require_once 'dokumen-saya.php';
+// Memiliki fungsi yang sama dengan "include", namun jika dokumen tidak ditemukan
+// atau tidak dapat disertakan maka akan menghasilkan pesan kesalahan fatal.
+
+// Isi dari dokumen-saya.php:
+<?php
+
+return 'Apapun yang kamu suka.';
+// akhir dari dokumen
+
+// "include" dan "require" dapat mengembalikan sebuah nilai.
+$nilai = include 'dokumen-saya.php';
+
+// Dokumen akan disertakan berdasarkan lokasi direktori dokumen (file path) yang diberikan, jika tidak didefinisikan
+// maka akan digunakan konfigurasi dari "include_path". Jika dokumen tidak ditemukan dalam "include_path",
+// fungsi include akan melakukan pengecekan pada direktori yang sama dengan dokumen yang menggunakan fungsi include tersebut,
+// jika tidak ditemukan juga maka pesan gagal akan dimunculkan.
+/* */
+
+/********************************
+ * Kelas (class)
+ */
+
+// Kelas didefinisikan dengan kata "class"
+
+class KelasSaya
+{
+ const NILAI_KONSTAN = 'nilai'; // Sebuah konstan
+
+ static $nilaiStatis = 'statis';
+
+ // Variabel statis dan hak jenis aksesnya
+ public static $variabelStatisPublik = 'nilaiStatisPublik';
+ // Hanya dapat diakses dalam kelas
+ private static $variabelStatisPrivat = 'nilaiStatisPrivat';
+ // Dapat diakses dalam kelas dan kelas turunan
+ protected static $variabelStatisTerlindungi = 'nilaiStatisTerlindungi';
+
+ // Properti harus mendeklarasikan hak aksesnya
+ public $properti = 'publik';
+ public $PropertiInstansi;
+ protected $variabel = 'terlindungi'; // Dapat diakses dari kelas itu sendiri dan kelas turunannya
+ private $variabel = 'tersembunyi'; // Hanya dapat diakses dari kelas itu sendiri
+
+ // Membuat konstruktor dengan perintah __construct
+ public function __construct($PropertiInstansi) {
+ // Akses variabel instansi menggunakan perintah $this
+ $this->PropertiInstansi = $PropertiInstansi;
+ }
+
+ // Method dideklarasikan sebagai fungsi didalam kelas
+ public function methodSaya()
+ {
+ print 'KelasSaya';
+ }
+
+ // Perintah "final" membuat sebuah fungsi tidak dapat di-override oleh kelas turunannya
+ final function tidakDapatDiOverride()
+ {
+ }
+
+/*
+ * Deklarasi properti atau method pada kelas sebagai statis membuat properti atau method tersebut
+ * dapat diakses tanpa melakukan instansiasi kelas. Properti statis tidak dapat diakses melalui
+ * objek kelas yang hasil instansiasi, sedangkan method statis bisa.
+ */
+
+ public static function methodStatisSaya()
+ {
+ print 'Saya adalah statis';
+ }
+}
+
+// Konstan pada kelas dapat diakses secara statis
+echo KelasSaya::NILAI_KONSTAN; // Menampilkan 'nilai'
+
+echo KelasSaya::$nilaiStatis; // Menampilkan 'statis'
+KelasSaya::methodStatisSaya(); // Menampilkan 'Saya adalah statis'
+
+// Instansi kelas menggunakan perintah "new"
+$kelas_saya = new KelasSaya('Sebuah properti instansiasi');
+// Tanda kurung adalah opsional jika tidak ingin menggunakan argumen.
+
+// Akses anggota kelas menggunakan ->
+echo $kelas_saya->properti; // => "publik"
+echo $kelas_saya->propertiInstansi; // => "Sebuah properti instansi"
+$kelas_saya->methodSaya(); // => "KelasSaya"
+
+// Menurunkan kelas menggunakan kata kunci "extends"
+class KelasSayaLainnya extends KelasSaya
+{
+ function tampilkanPropertiTerlindungi()
+ {
+ echo $this->properti;
+ }
+
+ // "override" terhadap sebuah method
+ function methodSaya()
+ {
+ parent::methodSaya();
+ print ' > KelasSayaLainnya';
+ }
+}
+
+$kelas_saya_lainnya = new KelasSayaLainnya('Instansiasi properti');
+$kelas_saya_lainnya->tampilkanPropertiTerlindung(); // => Menampilkan "terlindungi"
+$kelas_saya_lainnya->methodSaya(); // Menampilkan "KelasSaya > KelasSayaLainnya"
+
+final class SayaTidakBisaDiturunkan
+{
+}
+
+// Gunakan method ajaib (magic method) untuk membuat fungsi "getters" dan "setters"
+class PetaKelasSaya
+{
+ private $properti;
+
+ public function __get($key)
+ {
+ return $this->$key;
+ }
+
+ public function __set($key, $value)
+ {
+ $this->$key = $value;
+ }
+}
+
+$x = new PetaKelasSaya();
+echo $x->properti; // akan memanggil method __get()
+$x->properti = 'Sesuatu'; // akan memanggil method __set();
+
+// Kelas dapat dijadikan abstrak (menggunakan kata kunci "abstract"), atau
+// meng-implementasikan interfaces (menggunakan kata kunci "implements").
+// Sebuah interface dideklarasikan dengan perintah "interface".
+
+interface InterfaceSatu
+{
+ public function kerjakanSesuatu();
+}
+
+interface InterfaceDua
+{
+ public function kerjakanYangLain();
+}
+
+// interface dapat diturunkan
+interface InterfaceTiga extends InterfaceDua
+{
+ public function kerjakanYangBerbeda();
+}
+
+abstract class KelasAbstrakSaya implements InterfaceSatu
+{
+ public $x = 'kerjakanSesuatu';
+}
+
+class KelasKongkritSaya extends KelasAbstrakSaya implements InterfaceTwo
+{
+ public function kerjakanSesuatu()
+ {
+ echo $x;
+ }
+
+ public function kerjakanYangLain()
+ {
+ echo 'kerjakanYangLain';
+ }
+}
+
+// Kelas dapat diimplementasikan pada banyak interface
+class KelasLainnya implements InterfaceSatu, InterfaceDua
+{
+ public function kerjakanSesuatu()
+ {
+ echo 'kerjakanSesuatu';
+ }
+
+ public function kerjakanYangLain()
+ {
+ echo 'kerjakanYangLain';
+ }
+}
+
+
+/********************************
+ * Sifat (Traits)
+ */
+
+// Traits mulai tersedia sejak PHP 5.4.0 dan dideklarasikan menggunakan kata kunci "trait"
+
+trait TraitSaya
+{
+ public function methodTraitSaya()
+ {
+ print 'Saya menggunakan Trait';
+ }
+}
+
+class KelasTraitSaya
+{
+ use TraitSaya;
+}
+
+$kls = new KelasTraitSaya();
+$kls->methodTraitSaya(); // menampilkan "Saya menggunakan Trait"
+
+
+/********************************
+ * Namespaces
+ */
+
+// Bagian ini telah dibatasi, karena deklarasi "namespace"
+// karena harus ditempatkan diawal dokumen.
+
+<?php
+
+// Secara default, kelas tersedia sebagai namespace umum, dan dapat
+// secara khusus dipanggil dengan garis-miring terbalik (backslash).
+
+$kls = new \KelasSaya();
+
+
+// Menentukan namespace untuk sebuah dokumen
+namespace Saya\Namespace;
+
+class KelasSaya
+{
+}
+
+// (dari dokumen lainnya)
+$kls = new Saya\Namespace\KelasSaya;
+
+// Atau dari dalam namespace lainnya.
+namespace Saya\Lainnya\Namespace;
+
+use Saya\Namespace\KelasSaya;
+
+$kls = new KelasSaya();
+
+// Namespace dapat menggunakan alias
+
+namespace Saya\Lainnya\Namespace;
+
+use Saya\Namespace as SuatuKelasLainnya;
+
+$kls = new SuatuKelasLainnya\KelasSaya();
+
+
+/**********************
+* Late Static Binding
+*
+*/
+
+class KelasInduk {
+ public static function siapa() {
+ echo "Ini adalah " . __CLASS__ . "\n";
+ }
+ public static function coba() {
+ // kata kunci "self" merujuk pada method yang berada dalam satu kelas
+ self::who();
+ // kata kunci "static" merujuk pada method yang berada di kelas dimana method itu dijalankan
+ static::who();
+ }
+}
+
+KelasInduk::coba();
+/*
+Ini adalah KelasInduk
+Ini adalah KelasInduk
+*/
+
+class KelasAnak extends KelasInduk {
+ public static function siapa() {
+ echo "Tapi ini adalah " . __CLASS__ . "\n";
+ }
+}
+
+KelasAnak::tes();
+/*
+Ini adalah KelasInduk
+Tapi ini adalah KelasAnak
+*/
+
+/**********************
+* Magic constants
+*
+*/
+
+// Mendapatkan nama dari suatu kelas. Harus dideklarasikan didalam kelas tersebut.
+echo "Nama kelas ini adalah " . __CLASS__;
+
+// Mendapatkan alamat lengkap direktori
+echo "Alamat direktori ini adalah " . __DIR__;
+
+ // Beberapa yang banyak digunakan
+ require __DIR__ . '/vendor/autoload.php';
+
+// Mendapatkan alamat lengkap dokumen
+echo "Alamat dokumen ini adalah " . __FILE__;
+
+// Mendapatkan nama fungsi
+echo "Nama fungsi ini adalah " . __FUNCTION__;
+
+// Mendapatkan nomor baris perintah
+echo "Nomor baris perintah ini adalah " . __LINE__;
+
+// Mendapatkan nama method. Hanya mengembalikan sebuah nilai jika berada didalam trait atau deklarasi objek.
+echo "Nama method ini adalah " . __METHOD__;
+
+// Mendapatkan nama namespace
+echo "Namespace saat ini adalah " . __NAMESPACE__;
+
+// Mendapatkan nama dari trait. Hanya mengembalikan sebuah nilai jika berada didalam trait atau deklarasi objek.
+echo "Namespace saat ini adalah " . __TRAIT__;
+
+/**********************
+* Penanganan Kesalahan (Error)
+*
+*/
+
+// Penanganan error sederhana menggunakan "try...catch"
+
+try {
+ // Kerjakan sesuatu
+} catch (Exception $e) {
+ // Penanganan exception
+}
+
+// Menggunakan "try...catch" blok pada namespace
+
+try {
+ // Kerjakan sesuatu
+} catch (\Exception $e) {
+ // Penanganan exception
+}
+
+// Exception khusus
+
+class ExceptionSaya extends Exception {}
+
+try {
+
+ $kondisi = true;
+
+ if ($kondisi) {
+ throw new ExceptionSaya('Terjadi sesuatu');
+ }
+
+} catch (ExceptionSaya $e) {
+ // Penanganan untuk exception khusus
+}
+
+```
+
+## Informasi lainnya
+
+Kunjungi [Dokumentasi resmi PHP](http://www.php.net/manual/) untuk referensi dan masukan komunitas.
+
+Jika anda tertarik untuk belajar lebih dalam, kunjungi
+[PHP The Right Way](http://www.phptherightway.com/).
+
+Jika anda terbiasa dengan manajemen paket, kunjungi
+[Composer](http://getcomposer.org/).
+
+Untuk standar umum, kunjungi PHP Framework Interoperability Group's
+[PSR standards](https://github.com/php-fig/fig-standards).
diff --git a/id-id/ruby-id.html.markdown b/id-id/ruby-id.html.markdown
new file mode 100644
index 00000000..28135da1
--- /dev/null
+++ b/id-id/ruby-id.html.markdown
@@ -0,0 +1,622 @@
+---
+language: ruby
+filename: learnruby-id.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"]
+ - ["Gabriel Halley", "https://github.com/ghalley"]
+ - ["Persa Zula", "http://persazula.com"]
+ - ["Jake Faris", "https://github.com/farisj"]
+translators:
+ - ["Ukaza Perdana", "https://github.com/ukazap"]
+lang: id-id
+---
+
+```ruby
+# Ini adalah sebuah komentar
+
+=begin
+Ini adalah komentar multibaris
+Tak seorang pun menggunakannya
+Kamu juga tidak perlu
+=end
+
+# Pertama-tama dan yang terpenting: Semuanya adalah objek.
+
+# Angka adalah objek
+
+3.class #=> Fixnum
+
+3.to_s #=> "3"
+
+
+# Beberapa aritmetika dasar
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+2**5 #=> 32
+5 % 3 #=> 2
+
+# Operator-operator bitwise
+3 & 5 #=> 1
+3 | 5 #=> 7
+3 ^ 5 #=> 6
+
+# Aritmetika tidak lain adalah pemanis sintaks (syntactic sugar)
+# untuk memanggil sebuah metode pada suatu objek
+1.+(3) #=> 4
+10.* 5 #=> 50
+
+# Nilai-nilai khusus adalah objek
+nil # setara dengan "null" di bahasa-bahasa lain
+true # kebenaran
+false # ketidakbenaran
+
+nil.class #=> NilClass
+true.class #=> TrueClass
+false.class #=> FalseClass
+
+# Kesamaan
+1 == 1 #=> true
+2 == 1 #=> false
+
+# Ketidaksamaan
+1 != 1 #=> false
+2 != 1 #=> true
+
+# selain false itu sendiri, nil adalah nilai lain yang "salah"
+!nil #=> true
+!false #=> true
+!0 #=> false
+
+# Perbandingan lain
+1 < 10 #=> true
+1 > 10 #=> false
+2 <= 2 #=> true
+2 >= 2 #=> true
+
+# Operator pembanding yang dikombinasikan ("spaceship operator")
+1 <=> 10 #=> -1
+10 <=> 1 #=> 1
+1 <=> 1 #=> 0
+
+# Operator-operator logika
+true && false #=> false
+true || false #=> true
+!true #=> false
+
+# Terdapat versi-versi operator logika yang berbeda dengan lebih sedikit awalan.
+# Mereka digunakan sebagai kendali alur untuk merangkai beberapa pernyataan
+# hingga salah satunya mengembalikan (return) nilai true atau false.
+
+# `lakukan_suatu_lainnya` hanya dipanggil jika `lakukan_sesuatu` berhasil.
+lakukan_sesuatu() and lakukan_suatu_lainnya()
+# `catat_error` hanya dipanggil jika `lakukan_sesuatu` gagal.
+lakukan_sesuatu() or catat_error()
+
+
+# String adalah objek
+
+'Aku adalah string'.class #=> String
+"Aku juga adalah string".class #=> String
+
+wadah = 'menggunakan string interpolation'
+"Aku bisa #{wadah} ketika memakai tanda kutip ganda"
+#=> "Aku bisa menggunakan string interpolation ketika memakai tanda kutip ganda"
+
+# Gunakan tanda kutip tunggal daripada tanda kutip ganda jika memungkinkan
+# String bertanda kutip ganda melakukan kalkulasi tambahan di dalam
+
+# Kombinasikan string, tapi tidak dengan angka
+'halo ' + 'dunia' #=> "halo dunia"
+'halo ' + 3 #=> TypeError: can't convert Fixnum into String
+'halo ' + 3.to_s #=> "halo 3"
+
+# Kombinasikan string dengan operator
+'halo ' * 3 #=> "halo halo halo "
+
+# Membubuhkan ke string
+'halo' << ' dunia' #=> "halo dunia"
+
+# cetak ke output dan buat baris baru (newline) di akhir
+puts "Aku mencetak!"
+#=> Aku mencetak!
+#=> nil
+
+# cetak ke output tanpa baris baru
+print "Aku mencetak!"
+#=> Aku mencetak! => nil
+
+# Variabel
+x = 25 #=> 25
+x #=> 25
+
+# Catat bahwa pemberian nilai mengembalikan nilai yang diberikan
+# Artinya kamu bisa melakukan pemberian nilai secara jamak:
+
+x = y = 10 #=> 10
+x #=> 10
+y #=> 10
+
+# Berdasarkan adat, gunakan gaya snake_case untuk menulis nama variabel
+snake_case = true
+
+# Gunakan nama variabel yang deskriptif
+path_to_project_root = '/good/name/'
+path = '/bad/name/'
+
+# Simbol (adalah objek)
+# Simbol adalah konstanta yang dapat didaur ulang yang tidak dapat diubah
+# (immutable), secara internal diwakili oleh nilai integer. Seringkali
+# digunakan sebagai pengganti string untuk menyampaikan nilai yang mengandung
+# makna spesifik secara efisien.
+
+:menunggu.class #=> Symbol
+
+status = :menunggu
+
+status == :menunggu #=> true
+
+status == 'menunggu' #=> false
+
+status == :diterima #=> false
+
+# Array
+
+# Ini adalah sebuah array
+array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+
+# Array bisa menampung item dengan beragam tipe
+
+[1, 'halo', false] #=> [1, "halo", false]
+
+# Array bisa di-indeks-kan
+# Dari depan
+array[0] #=> 1
+array.first #=> 1
+array[12] #=> nil
+
+# Sama dengan aritmetika, pengaksesan [var]
+# hanyalah pemanis sintaks
+# untuk memanggil metode [] pada suatu objek
+array.[] 0 #=> 1
+array.[] 12 #=> nil
+
+# Dari belakang
+array[-1] #=> 5
+array.last #=> 5
+
+# Dengan indeks awal dan panjang (jumlah item)
+array[2, 3] #=> [3, 4, 5]
+
+# Membalik sebuah Array
+a=[1,2,3]
+a.reverse! #=> [3,2,1]
+
+# Atau menggunakan jangkauan (range)
+array[1..3] #=> [2, 3, 4]
+
+# Tambahkan ke array seperti ini
+array << 6 #=> [1, 2, 3, 4, 5, 6]
+# Atau seperti ini
+array.push(6) #=> [1, 2, 3, 4, 5, 6]
+
+# Periksa apakah suatu item ada dalam sebuah array
+array.include?(1) #=> true
+
+# Hash adalah kamus utama Ruby berupa pasangan kunci/nilai (key/value pair).
+# Hash ditandai dengan kurung kurawal:
+hash = { 'warna' => 'hijau', 'angka' => 5 }
+
+hash.keys #=> ['warna', 'angka']
+
+# Nilai dalam Hash bisa diperoleh menggunakan kunci:
+hash['warna'] #=> 'hijau'
+hash['angka'] #=> 5
+
+# Meminta hash untuk kunci yang tidak ada akan mengembalikan nil:
+hash['tidak ada di sini'] #=> nil
+
+# Sejak Ruby 1.9, ada sintaks khusus ketika menggunakan simbol sebagai kunci:
+
+hash_baru = { defcon: 3, action: true }
+
+hash_baru.keys #=> [:defcon, :action]
+
+# Periksa ada/atau tidaknya kunci dan nilai dalam hash
+hash_baru.key?(:defcon) #=> true
+hash_baru.value?(3) #=> true
+
+# Tip: Baik array maupun hash adalah Enumerable
+# Mereka berbagi banyak metode yang berguna diantaranya each, map, count, dll.
+
+# Struktur-struktur kendali
+
+if true
+ 'pernyataan if'
+elsif false
+ 'else if, opsional'
+else
+ 'else, opsional juga'
+end
+
+for penghitung in 1..5
+ puts "iterasi #{penghitung}"
+end
+#=> iterasi 1
+#=> iterasi 2
+#=> iterasi 3
+#=> iterasi 4
+#=> iterasi 5
+
+# NAMUN, tidak ada orang yang menggunakan pengulangan for.
+# Sebagai ganti, gunakan metode "each" dan memberinya sebuah blok (block).
+# Blok adalah serangkaian kode yang bisa dimasukkan ke metode seperti "each".
+# Ia serupa dengan lambda, fungsi anonim atau closure di bahasa lainnya.
+#
+# Metode "each" dari range menjalankan blok untuk setiap elemen dari range.
+# Bloknya diberikan penghitung sebagai parameter.
+# Memanggil metode "each" dengan blok terlihat seperti ini:
+
+(1..5).each do |penghitung|
+ puts "iterasi #{penghitung}"
+end
+#=> iterasi 1
+#=> iterasi 2
+#=> iterasi 3
+#=> iterasi 4
+#=> iterasi 5
+
+# Kamu juga bisa mengurung blok dalam kurung kurawal:
+(1..5).each { |penghitung| puts "iterasi #{penghitung}" }
+
+# Isi dari struktur-struktur data juga bisa di-iterasi menggunakan each.
+array.each do |elemen|
+ puts "#{elemen} adalah bagian dari array"
+end
+hash.each do |kunci, nilai|
+ puts "#{kunci} adalah #{nilai}"
+end
+
+# Jika kamu masih membutuhkan indeks, bisa menggunakan "each_with_index"
+# dan definisikan variabel indeks
+array.each_with_index do |elemen, indeks|
+ puts "#{elemen} adalah nomor #{indeks} dalam array"
+end
+
+penghitung = 1
+while penghitung <= 5 do
+ puts "iterasi #{penghitung}"
+ penghitung += 1
+end
+#=> iterasi 1
+#=> iterasi 2
+#=> iterasi 3
+#=> iterasi 4
+#=> iterasi 5
+
+# Ada kumpulan fungsi pengulangan lainnya yang berguna di Ruby,
+# contohnya "map", "reduce", "inject", daftarnya sangat panjang. Map,
+# misalnya, mengambil array yang di-iterasi-nya, melakukan sesuatu pada
+# setiap elemen sesuai definisi pada blok, dan mengembalikan array baru.
+array = [1,2,3,4,5]
+berganda = array.map do |elemen|
+ elemen * 2
+end
+puts berganda
+#=> [2,4,6,8,10]
+puts array
+#=> [1,2,3,4,5]
+
+nilai = 'B'
+
+case nilai
+when 'A'
+ puts 'Pertahankan, nak'
+when 'B'
+ puts 'Semoga lebih beruntung di lain waktu'
+when 'C'
+ puts 'Kamu bisa lebih baik'
+when 'D'
+ puts 'Susah payah'
+when 'F'
+ puts 'Kamu gagal!'
+else
+ puts 'Sistem penilaian lainnya, heh?'
+end
+#=> "Semoga lebih beruntung di lain waktu"
+
+# case juga bisa menggunakan range
+nilai = 82
+case nilai
+when 90..100
+ puts 'Hore!'
+when 80...90
+ puts 'Cukup bagus'
+else
+ puts 'Kamu gagal!'
+end
+#=> "Cukup bagus"
+
+# penanganan kesalahan (exception handling):
+begin
+ # kode di sini yang mungkin membangkitkan exception
+ raise NoMemoryError, 'Kamu kehabisan memori.'
+rescue NoMemoryError => variabel_exception
+ puts 'NoMemoryError dibangkitkan', variabel_exception
+rescue RuntimeError => variabel_exception_lainnya
+ puts 'RuntimeError dibangkitkan sekarang'
+else
+ puts 'Ini dijalankan bila tidak ada exceptions sama sekali'
+ensure
+ puts 'Kode ini akan berjalan bagaimanapun juga'
+end
+
+# Fungsi (atau metode)
+
+def gandakan(x)
+ x * 2
+end
+
+# Fungsi dan semua blok secara tersirat mengembalikan nilai pernyataan terakhir
+gandakan(2) #=> 4
+
+# Tanda kurung bersifat optional, boleh ditiadakan jika tidak ambigu
+gandakan 3 #=> 6
+
+gandakan gandakan 3 #=> 12
+
+def jumlah(x, y)
+ x + y
+end
+
+# Argumen-argumen dari metode dipisahkan dengan koma
+sum 3, 4 #=> 7
+
+sum sum(3, 4), 5 #=> 12
+
+# yield
+# Semua metode secara tersirat mempunyai parameter blok opsional
+# yang bisa dipanggil dengan kata kunci 'yield'
+
+def kurung
+ puts '{'
+ yield
+ puts '}'
+end
+
+kurung { puts 'halo dunia' }
+
+# {
+# halo dunia
+# }
+
+
+# Kamu bisa memasukkan blok ke sebuah fungsi
+# "&" adalah penanda blok yang masuk
+def tamu_tamu(&blok)
+ blok.call 'beberapa_argumen'
+end
+
+# Kamu bisa memasukkan daftar argumen yang akan dikonversi menjadi array
+# Itulah gunanya operator splat ("*")
+def tamu_tamu(*array)
+ array.each { |tamu| puts tamu }
+end
+
+# Bila metode mengembalikan array, bisa memberi nilai dengan destrukturisasi
+# (destructuring assignment):
+def makanan
+ ['tempe penyet', 'sayur asam', 'nasi goreng']
+end
+sarapan, makan_siang, makan_malam = makanan
+sarapan #=> 'tempe penyet'
+makan_malam #=> 'nasi goreng'
+
+# Menurut adat, nama metode yang mengembalikan boolean diakhiri tanda tanya
+5.even? # false
+5.odd? # true
+
+# Dan jika suatu metode berakhiran tanda seru, ia melakukan sesuatu yang merusak
+# seperti mengubah penerimanya. Banyak metode mempunyai versi ! untuk melakukan
+# perubahan dan versi non-! untuk sekedar mengembalikan perubahannya
+nama_perusahaan = "Putra Sejahtera"
+nama_perusahaan.upcase #=> "PUTRA SEJAHTERA"
+nama_perusahaan #=> "Putra Sejahtera"
+nama_perusahaan.upcase! # kali ini kita benar-benar mengubah nama_perusahaan!
+nama_perusahaan #=> "PUTRA SEJAHTERA"
+
+
+# Definisikan kelas menggunakan kata kunci class
+class Manusia
+
+ # Variabel kelas. Ini dibagi oleh semua instans (instance) dari kelas ini.
+ @@spesies = 'H. sapiens'
+
+ # Inisialisasi dasar
+ def initialize(nama, usia = 0)
+ # Berikan argumen ke variabel instans "nama" dalam instans ini
+ @nama = nama
+ # Jika tidak diberi usia, nilai default dalam daftar argumen digunakan.
+ @usia = usia
+ end
+
+ # Metode setter dasar
+ def nama=(nama)
+ @nama = nama
+ end
+
+ # Metode getter dasar
+ def nama
+ @nama
+ end
+
+ # Fungsi di atas bisa disingkat dengan metode attr_accessor sebagai berikut
+ attr_accessor :nama
+
+ # Metode getter/setter juga bisa dibuat secara terpisah seperti ini
+ attr_reader :nama
+ attr_writer :nama
+
+ # Metode kelas menggunakan self untuk membedakannya dari metode instans.
+ # Ia hanya bisa dipanggil pada kelas, bukan pada instans-nya.
+ def self.katakan(pesan)
+ puts pesan
+ end
+
+ def spesies
+ @@spesies
+ end
+end
+
+
+# Membuat instans kelas
+jim = Manusia.new('Jim Halpert')
+
+dwight = Manusia.new('Dwight K. Schrute')
+
+# Mari panggil beberapa metode
+jim.spesies #=> "H. sapiens"
+jim.nama #=> "Jim Halpert"
+jim.nama = "Jim Halpert II" #=> "Jim Halpert II"
+jim.nama #=> "Jim Halpert II"
+dwight.spesies #=> "H. sapiens"
+dwight.nama #=> "Dwight K. Schrute"
+
+# Panggil metode kelas
+Manusia.katakan('Hai') #=> "Hai"
+
+# Lingkup variabel didefinisikan berdasarkan bagaimana kita memberikannya nama
+# Variabel yang berawalan $ memiliki lingkup global
+$var = "Aku adalah variabel global"
+defined? $var #=> "global-variable"
+
+# Variabel yang berawalan @ memiliki lingkup instans
+@var = "Aku adalah variabel instans"
+defined? @var #=> "instance-variable"
+
+# Variabel yang berawalan @@ memiliki lingkup kelas
+@@var = "Aku adalah variabel kelas"
+defined? @@var #=> "class variable"
+
+# Variabel yang berawalan huruf kapital adalah konstanta
+Var = "Aku adalah konstanta"
+defined? Var #=> "constant"
+
+# Kelas juga adalah objek sehingga kelas bisa memiliki variabel instans.
+# Variabel kelas dibagi diantara kelas dan semua pewarisnya.
+
+# kelas dasar
+class Manusia
+ @@foo = 0
+
+ def self.foo
+ @@foo
+ end
+
+ def self.foo=(nilai)
+ @@foo = nilai
+ end
+end
+
+# kelas turunan
+class Buruh < Manusia
+end
+
+Manusia.foo # 0
+Buruh.foo # 0
+
+Manusia.foo = 2 # 2
+Buruh.foo # 2
+
+# Variabel instans milik kelas tidak dibagikan dengan pewaris kelas tersebut.
+
+class Manusia
+ @bar = 0
+
+ def self.bar
+ @bar
+ end
+
+ def self.bar=(nilai)
+ @bar = nilai
+ end
+end
+
+class Dokter < Manusia
+end
+
+Manusia.bar # 0
+Dokter.bar # nil
+
+module ContohModul
+ def foo
+ 'foo'
+ end
+end
+
+# Include modul mengikat metode-metodenya pada instans-instans kelas
+# Extend modul mengikat metode-metodenya pada kelas
+
+class Orang
+ include ContohModul
+end
+
+class Buku
+ extend ContohModul
+end
+
+Orang.foo # => NoMethodError: undefined method `foo' for Orang:Class
+Orang.new.foo # => 'foo'
+Buku.foo # => 'foo'
+Buku.new.foo # => NoMethodError: undefined method `foo'
+
+# Callbacks dijalankan ketika meng-include dan meng-extend sebuah modul
+
+module ContohUrusan
+ def self.included(base)
+ base.extend(MetodeKelas)
+ base.send(:include, MetodeInstans)
+ end
+
+ module MetodeKelas
+ def bar
+ 'bar'
+ end
+ end
+
+ module MetodeInstans
+ def qux
+ 'qux'
+ end
+ end
+end
+
+class Sesuatu
+ include ContohUrusan
+end
+
+Sesuatu.bar # => 'bar'
+Sesuatu.qux # => NoMethodError: undefined method `qux'
+Sesuatu.new.bar # => NoMethodError: undefined method `bar'
+Sesuatu.new.qux # => 'qux'
+```
+
+## Sumber tambahan
+
+- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - Varian dari referensi ini dengan tantangan dalam browser.
+- [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Belajar Ruby melalui serangkaian tutorial interaktif.
+- [Dokumentasi resmi](http://www.ruby-doc.org/core-2.1.1/)
+- [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/) - Edisi lama yang [gratis](http://ruby-doc.com/docs/ProgrammingRuby/) tersedia online.
+- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Panduan penulisan kode Ruby oleh komunitas.
+- [Try Ruby](http://tryruby.org) - Pelajari dasar bahasa pemrograman Ruby, secara interaktif di browser.
diff --git a/id-id/xml-id.html.markdown b/id-id/xml-id.html.markdown
index 8b8d72ae..fedba711 100644
--- a/id-id/xml-id.html.markdown
+++ b/id-id/xml-id.html.markdown
@@ -5,19 +5,76 @@ contributors:
- ["João Farias", "https://github.com/JoaoGFarias"]
translators:
- ["Rizky Luthfianto", "https://github.com/rilut"]
+ - ["Ahmad Zafrullah", "https://github.com/23Pstars"]
lang: id-id
---
-XML adalah bahasa markup yang dirancang untuk menyimpan dan mengirim data.
+XML adalah bahasa markup yang dirancang untuk menyimpan dan mengirim data. XML mudah dibaca oleh manusia dan mesin.
Tidak seperti HTML, XML tidak menentukan bagaimana menampilkan atau format data, hanya membawanya.
-* Sintaks XML
+Terdapat perbedaan antara **konten** dan **markup**. Singkatnya, konten dapat berupa apapun dan markup adalah sebagai penentu.
+
+## Definisi dan Pendahuluan
+
+Dokumen XML pada dasarnya disusun oleh *elemen* yang dapat memiliki *atribut* untuk menjelaskan elemen tersebut dan dapat memiliki beberapa konten tekstual atau beberapa elemen sebagai anak-nya. Setiap dokumen XML hendaknya memiliki satu elemen akar, yang menjadi induk dari semua elemen dalam dokumen XML.
+
+Pengurai XML dirancang menjadi sangat ketat, dan akan berhenti melakukan penguraian terhadap dokumen yang cacat. Oleh karena itu semua dokumen XML harus mengikuti [Aturan Sintaks XML](http://www.w3schools.com/xml/xml_syntax.asp).
```xml
-<!-- Komentar di XML seperti ini -->
+<!-- Ini adalah komentar. Komentar harus memiliki dua tanda penghubung secara berurutan (-). -->
+<!-- Komentar dapat renggang
+ menjadi banyak baris -->
+
+<!-- Elemen -->
+<!-- Elemen merupakan komponen dasar dari XML. Ada dua tipe dari elemen, kosong: -->
+<elemen1 atribut="nilai" /> <!-- Elemen kosong tidak memiliki konten apapun -->
+<!-- dan tidak-kosong: -->
+<elemen2 atribut="nilai">Konten</elemen2>
+<!-- Nama elemen hanya dapat berupa huruf dan angka saja. -->
+
+<kosong /> <!-- Elemen yang terdiri dari tag elemen kosong… -->
+<!-- …tidak memiliki content apapun dan murni markup. -->
+
+<tidakkosong> <!-- Atau, elemen ini memiliki tag pembuka… -->
+ <!-- …suatu konten… -->
+</tidakkosong> <!-- dan sebuah tag penutup. -->
+
+<!-- Nama elemen merupakan *case sensitive*. -->
+<elemen />
+<!-- …tidak sama dengan elemen sebelumnya -->
+<eLEMEN />
+
+<!-- Atribut -->
+<!-- Sebuah atribut merupakan hubungan kunci-nilai yang terdapat pada elemen. -->
+<elemen atribut="nilai" lainnya="nilaiLainnya" banyakNilai="daftar nilai ber-spasi" />
+<!-- Sebuah atribut digunakan hanya sekali dalam sebuah elemen. Dan hanya memiliki satu nilai.
+ Salah satu solusi untuk mengatasi permasalahan tersebut adalah dengan menggunakan daftar nilai ber-spasi. -->
+
+<!-- Elemen bersarang -->
+<!-- Konten dari sebuah elemen dapat berupa elemen lainnya:: -->
+<ayah>
+ <anak>Teks</anak>
+ <oranglain />
+</ayah>
+<!-- Mengikuti standar tatanan pohon. Setiap elemen disebut *node*.
+ Induk yang berada satu tingkat diatasnya disebut *parent*, keturunan yang berada satu tingkat dibawahnya disebut *children*.
+ Elemen yang berada pada *parent* yang sama disebut Saudara (*siblings*). -->
+
+<!-- XML mempertahankan spasi. -->
+<anak>
+ Teks
+</anak>
+<!-- …tidak sama dengan -->
+<anak>Teks</anak>
+```
+
+
+## Dokumen XML
+```xml
<?xml version="1.0" encoding="UTF-8"?>
+<!-- XML prolog, boleh tidak digunakan namun direkomendasikan untuk digunakan. -->
<tokobuku>
<buku category="MEMASAK">
<judul lang="en">Everyday Italian</judul>
@@ -65,7 +122,7 @@ Tidak seperti HTML, XML tidak menentukan bagaimana menampilkan atau format data,
```
-* Dokumen yang well-formated & Validasi
+## Dokumen yang well-formated & Validasi
Sebuah dokumen XML disebut well-formated jika sintaksisnya benar.
Namun, juga mungkin untuk mendefinisikan lebih banyak batasan dalam dokumen,
@@ -128,3 +185,17 @@ Dengan alat ini, Anda dapat memeriksa data XML di luar logika aplikasi.
</buku>
</tokobuku>
```
+## Kompatibilitas DTD dan Definisi Skema XML
+
+Dukungan untuk DTD dapat ditemukan dimana-mana karena sudah sangat lama. Namun sayangnya, fitur XML terkini seperti *namespaces* tidak didukung oleh DTD. XML Xchema Definitions (XSDs) bertujuan untuk mengganti DTD dalam mendefinisikan tatabahasa dokumen XML.
+
+## Sumber
+
+* [Validasi dokumen XML](http://www.xmlvalidation.com)
+
+## Bacaan lainnya
+
+* [XML Schema Definitions Tutorial](http://www.w3schools.com/schema/)
+* [DTD Tutorial](http://www.w3schools.com/xml/xml_dtd_intro.asp)
+* [XML Tutorial](http://www.w3schools.com/xml/default.asp)
+* [Using XPath queries to parse XML](http://www.w3schools.com/xml/xml_xpath.asp)
diff --git a/inform7.html.markdown b/inform7.html.markdown
new file mode 100644
index 00000000..7f1da0e0
--- /dev/null
+++ b/inform7.html.markdown
@@ -0,0 +1,195 @@
+---
+language: Inform7
+contributors:
+ - ["Hyphz", "http://github.com/hyphz/"]
+filename: LearnInform.Inform
+---
+Inform 7 is a natural language based language created by Graham Nelson and Emily Short for writing text adventures, but also potentially usable for other text based applications, especially data backed ones.
+
+```
+"LearnInform" by Hyphz
+
+[This is a comment.]
+
+[Inform 7 is a language designed for building text adventures.
+It can be used for other purposes too, although the default
+library builds a text adventure. Inform 7 is object oriented.]
+
+[This creates a class by subclassing. "Value" is the universal subclass,
+but "object" is the most basic that behaves like an OO object.]
+A datablock is a kind of object.
+
+[Classes can have properties.]
+A datablock can be broken. [This creates a boolean property.]
+A datablock is usually not broken. [This sets its default value.]
+A datablock can be big or small. [This creates an enumerated property.]
+A datablock is usually small. [This sets its default value.]
+A datablock has a number called the sequence number. [This creates a typed property.]
+A datablock has some text called the name. ["Some text" means a string.]
+A datablock has a datablock called the chain. [Declared classes become types.]
+
+[This creates a global named instance.]
+Block1 is a datablock.
+The sequence number of Block1 is 1.
+The name of Block1 is "Block One."
+
+[Functions and procedures are defined as "phrases".]
+To do the thing everyone does with their first program:
+ say "Hello World.". [Full stop indicates the end, indent indicates the scope.]
+
+To dump (the block - a datablock): [That's how we create a parameter.]
+ say the sequence number of the block;
+ say the name of the block;
+ if the block is broken, say "(Broken)".
+
+To toggle (the block - a datablock):
+ if the block is broken: [Conditional.]
+ now the block is not broken; [Updating a property.]
+ else:
+ now the block is broken.
+
+[Multiple parameters.]
+To fix (the broken block - a datablock) using (the repair block - a datablock):
+ if the broken block is not broken, stop; [Comma for a non indented single command.]
+ if the repair block is broken, stop;
+ now the sequence number of the broken block is the sequence number of the repair block;
+ now the broken block is not broken.
+
+[Because of its text adventure origins, Inform 7 doesn't generally allow objects
+to be created dynamically, although there's a language extension that enables it.]
+Block2 is a datablock.
+Block2 is broken.
+The sequence number of Block2 is 2.
+The name of Block2 is "Block two."
+
+To demonstrate calling a phrase with two parameters:
+ Let the second block be block2; [Local pointer variable.]
+ fix the second block using Block1;
+ say the sequence number of the second block. [1.]
+
+[Lists.]
+To show how to use list types:
+ let the list be a list of datablocks;
+ add Block1 to the list;
+ add Block2 to the list;
+ say the list; ["Block1 and Block2"]
+ [Membership.]
+ if Block1 is listed in the list:
+ say "Block1 is there.";
+ [Loop.]
+ repeat with the block running through the list:
+ dump the block; [1 Block One. 1 Block Two.]
+ [Remember block two's sequence number was changed above.]
+ let X be entry 2 of the list; [Counting starts at 1.]
+ dump X; ["1 Block two."]
+ remove X from the list;
+ say the list. [Block1]
+
+[Here's how we define a function and do arithmetic.]
+
+To decide which number is the sum of all numbers up to (X - a number) (this is summing up):
+ let the total so far be a number;
+ repeat with the current number running from 1 to X:
+ now the total so far is the total so far + the current number;
+ decide on the total so far. [This is the return statement.]
+
+[ We have higher order functions too. ]
+
+To demonstrate a higher order function:
+ say summing up applied to {1, 2, 3, 4}.
+
+To decide which number is the result of applying (phrase - phrase A -> A) twice to (B - a value of kind A):
+ let b1 be phrase applied to B;
+ let b2 be phrase applied to b1;
+ decide on b2.
+
+To demonstrate defining a higher order function:
+ let X be 5;
+ say the result of applying summing up twice to X.
+
+[ Rulebooks allow a number of functions which apply to the same type under different conditions to be stacked. ]
+
+Datablock validation rules is a datablock based rulebook.
+
+A datablock validation rule for a broken datablock: rule fails.
+A datablock validation rule for a datablock (called the block):
+ dump the block;
+ rule succeeds.
+
+To demonstrate invoking a rulebook:
+ follow datablock validation rules for Block1;
+ follow datablock validation rules for Block2.
+
+[ Objects can also have relations, which resemble those in a relational database. ]
+A dog is a kind of thing.
+Rover is a dog.
+The kennel is a container. [This is a built in base class.]
+Rover is in the kennel. [This creates an inbuilt relation called "containment".]
+
+[We can create relations by declaring their type.]
+
+Guide dog ownership relates one dog to one person. [One-to-one.]
+Property ownership relates various things to one person. [Many-to-one.]
+Friendship relates various people to various people. [Many-to-many.]
+
+[To actually use them we must assign verbs or prepositions to them.]
+
+The verb to own means the property ownership relation.
+The verb to be the guide dog of means the guide dog ownership relation.
+The verb to be guided by means the reversed guide dog ownership relation.
+The verb to be friends with means the friendship relation.
+
+Edward is a person. A person can be blind. Edward is blind.
+Edward is guided by Rover.
+Benny is a person. Edward is friends with Benny.
+
+To demonstrate looking something up with a relation:
+ repeat with the dog running through things that are the guide dog of Edward:
+ say the dog;
+ repeat with the friend running through things that are friends with Edward:
+ say the friend.
+
+[We can also define relations that exist procedurally.]
+
+Helpfulness relates a person (called the helper) to a person (called the helpee) when the helpee is blind and the helper is not blind.
+The verb to be helpful to means the helpfulness relation.
+To demonstrate using a procedural relation:
+ repeat with the helper running through people that are helpful to Edward:
+ say the helper.
+
+
+[ Interface to the text adventure harness to allow the above code to be run. ]
+Tutorial room is a room.
+"A rather strange room full of buttons. Push them to run the exercises, or turn on the robot to run them all."
+A button is a kind of thing. A button is fixed in place.
+
+The red button is a button in tutorial room.
+Instead of pushing the red button, do the thing everyone does with their first program.
+The green button is a button in tutorial room.
+Instead of pushing the green button, demonstrate calling a phrase with two parameters.
+The blue button is a button in tutorial room.
+Instead of pushing the blue button, show how to use list types.
+The cyan button is a button in tutorial room.
+Instead of pushing the cyan button, say the sum of all numbers up to 5.
+The purple button is a button in tutorial room.
+Instead of pushing the purple button, demonstrate a higher order function.
+The black button is a button in tutorial room.
+Instead of pushing the black button, demonstrate defining a higher order function.
+The white button is a button in tutorial room.
+Instead of pushing the white button, demonstrate invoking a rulebook.
+The puce button is a button in tutorial room.
+Instead of pushing the puce button, demonstrate looking something up with a relation.
+The orange button is a button in tutorial room.
+Instead of pushing the orange button, demonstrate using a procedural relation.
+
+The robot is an object in tutorial room.
+Instead of switching on the robot:
+ say "The robot begins to frantically flail its arms about.";
+ repeat with button running through buttons in the tutorial room:
+ say "The robot randomly hits [the button].";
+ try pushing button.
+```
+
+##Ready For More?
+
+* [Inform 7](http://www.inform7.com/)
diff --git a/it-it/bash-it.html.markdown b/it-it/bash-it.html.markdown
index af8823c4..d535babc 100644
--- a/it-it/bash-it.html.markdown
+++ b/it-it/bash-it.html.markdown
@@ -10,7 +10,7 @@ contributors:
- ["Anton Strömkvist", "http://lutic.org/"]
- ["Rahil Momin", "https://github.com/iamrahil"]
- ["Gregrory Kielian", "https://github.com/gskielian"]
-filename: LearnBash.sh
+filename: LearnBash-it.sh
translators:
- ["Robert Margelli", "http://github.com/sinkswim/"]
- ["Tommaso Pifferi", "http://github.com/neslinesli93/"]
diff --git a/it-it/brainfuck-it.html.markdown b/it-it/bf-it.html.markdown
index 08d2ede9..a79710d0 100644
--- a/it-it/brainfuck-it.html.markdown
+++ b/it-it/bf-it.html.markdown
@@ -1,5 +1,5 @@
---
-language: brainfuck
+language: bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]
diff --git a/it-it/coffeescript-it.html.markdown b/it-it/coffeescript-it.html.markdown
index 31973369..d30ba819 100644
--- a/it-it/coffeescript-it.html.markdown
+++ b/it-it/coffeescript-it.html.markdown
@@ -4,8 +4,6 @@ contributors:
- ["Luca 'Kino' Maroni", "http://github.com/kino90"]
- ["Tenor Biel", "http://github.com/L8D"]
- ["Xavier Yao", "http://github.com/xavieryao"]
-translators:
- - ["Tommaso Pifferi","http://github.com/neslinesli93"]
filename: coffeescript-it.coffee
lang: it-it
---
diff --git a/it-it/git-it.html.markdown b/it-it/git-it.html.markdown
new file mode 100644
index 00000000..521538a1
--- /dev/null
+++ b/it-it/git-it.html.markdown
@@ -0,0 +1,498 @@
+---
+category: tool
+tool: git
+contributors:
+ - ["Jake Prather", "http://github.com/JakeHP"]
+ - ["Leo Rudberg" , "http://github.com/LOZORD"]
+ - ["Betsy Lorton" , "http://github.com/schbetsy"]
+ - ["Bruno Volcov", "http://github.com/volcov"]
+translators:
+ - ["Christian Grasso", "http://chris54721.net"]
+filename: LearnGit-it.txt
+lang: it-it
+---
+
+Git è un sistema di
+[controllo versione distribuito](https://it.wikipedia.org/wiki/Controllo_versione_distribuito)
+e di gestione del codice sorgente.
+
+Git esegue una serie di _snapshot_ per salvare lo stato di un progetto, così
+facendo può fornirti la possibilità di gestire il tuo codice e di salvarne lo
+stato assegnando delle versioni.
+
+## Basi del controllo versione
+
+### Cos'è il controllo versione?
+
+Il controllo versione (_Version Control_ o _Versioning_) è un sistema che
+registra le modifiche apportate a uno o più file nel tempo.
+
+### Controllo versione centralizzato e distribuito
+
+* Il controllo versione centralizzato si concentra sulla sincronizzazione, il
+ monitoraggio e il backup dei file.
+* Il controllo versione distribuito si concentra sulla condivisione delle
+ modifiche. Ogni modifica ha un identificatore univoco.
+* I sistemi distribuiti non hanno una struttura definita. Si potrebbe creare
+ ad esempio un sistema centralizzato simile a SVN utilizzando Git.
+
+[Ulteriori informazioni](http://git-scm.com/book/it/v1/Per-Iniziare-Il-Controllo-di-Versione)
+
+### Perchè usare Git?
+
+* Consente di lavorare offline.
+* Collaborare con altre persone è semplice!
+* Utilizzare i branch (rami di sviluppo) è semplice!
+* Git è veloce.
+* Git è flessibile.
+
+## Architettura di Git
+
+### Repository
+
+Un insieme di file, cartelle, registrazioni della cronologia e versioni.
+Immaginalo come una struttura dati del codice, con la caratteristica che ogni
+"elemento" del codice ti fornisce accesso alla sua cronologia delle revisioni,
+insieme ad altre cose.
+
+Un repository comprende la cartella .git e il working tree.
+
+### Cartella .git (componente del repository)
+
+La cartella .git contiene tutte le configurazioni, i log, i rami e altro.
+[Lista dettagliata](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html)
+
+### Working Tree (componente del repository)
+
+Si tratta semplicemente delle cartelle e dei file presenti nel repository.
+Spesso viene indicato come "directory di lavoro" ("working directory").
+
+### Index (componente della cartella .git)
+
+L'Index è l'area di staging di Git. Si tratta di un livello che separa il
+working tree dal repository. Ciò fornisce agli sviluppatori più controllo su
+cosa viene inviato al repository.
+
+### Commit
+
+Un commit è uno snapshot di una serie di modifiche apportate al working tree.
+Ad esempio, se hai aggiunto 5 file e ne hai rimossi 2, ciò sarà registrato in
+un commit. Il commit può essere pushato (inviato) o meno ad altri repository.
+
+### Branch (ramo)
+
+Un branch (ramo) è essenzialmente un puntatore all'ultimo commit che hai
+effettuato. Effettuando altri commit, il puntatore verrà automaticamente
+aggiornato per puntare all'ultimo commit.
+
+### Tag
+
+Un tag è un contrassegno applicato a un punto specifico nella cronologia dei
+commit. Di solito i tag vengono utilizzati per contrassegnare le versioni
+rilasciate (v1.0, v1.1, etc.).
+
+### HEAD e head (componenti della cartella .git)
+
+HEAD (in maiuscolo) è un puntatore che punta al branch corrente. Un repository
+può avere solo 1 puntatore HEAD *attivo*.
+
+head (in minuscolo) è un puntatore che può puntare a qualsiasi commit. Un
+repository può avere un numero qualsiasi di puntatori head.
+
+### Stadi di Git
+* _Modified_ - Un file è stato modificato, ma non è ancora stato effettuato
+ un commit per registrare le modifiche nel database di Git
+* _Staged_ - Un file modificato è stato contrassegnato per essere incluso nel
+ prossimo commit
+* _Committed_ - È stato effettuato un commit e le modifiche sono state
+ registrate nel database di Git
+
+## Comandi
+
+### init
+
+Crea un repository Git vuoto. Le impostazioni e le informazioni del repository
+sono salvate nella cartella ".git".
+
+```bash
+$ git init
+```
+
+### config
+
+Utilizzato per configurare le impostazioni, sia specifiche del repository, sia
+a livello globale. Le impostazioni globali sono salvate in `~/.gitconfig`.
+
+```bash
+$ git config --global user.email "email@example.com"
+$ git config --global user.name "Nome utente"
+```
+
+[Ulteriori informazioni su git config](http://git-scm.com/docs/git-config)
+
+### help
+
+Fornisce una documentazione molto dettagliata di ogni comando.
+
+```bash
+# Mostra i comandi più comuni
+$ git help
+
+# Mostra tutti i comandi disponibili
+$ git help -a
+
+# Documentazione di un comando specifico
+# git help <nome_comando>
+$ git help add
+$ git help commit
+$ git help init
+# oppure git <nome_comando> --help
+$ git add --help
+$ git commit --help
+$ git init --help
+```
+
+### Ignorare file
+
+Per impedire intenzionalmente che file privati o temporanei vengano inviati
+al repository Git.
+
+```bash
+$ echo "temp/" >> .gitignore
+$ echo "privato.txt" >> .gitignore
+```
+
+
+### status
+
+Mostra le differenza tra lo stato attuale del working tree e l'attuale commit
+HEAD.
+
+```bash
+$ git status
+```
+
+### add
+
+Aggiunge file alla staging area, ovvero li contrassegna per essere inclusi nel
+prossimo commit. Ricorda di aggiungere i nuovi file, altrimenti non saranno
+inclusi nei commit!
+
+```bash
+# Aggiunge un file nella directory attuale
+$ git add HelloWorld.java
+
+# Aggiunge un file in una sottocartella
+$ git add /path/to/file/HelloWorld.c
+
+# Il comando supporta le espressioni regolari
+$ git add ./*.java
+
+# Aggiunge tutti i file non ancora contrassegnati
+$ git add --all
+```
+
+Questo comando contrassegna soltanto i file, senza effettuare un commit.
+
+### branch
+
+Utilizzato per gestire i branch (rami). Puoi visualizzare, modificare, creare o
+eliminare branch utilizzando questo comando.
+
+```bash
+# Visualizza i branch e i remote
+$ git branch -a
+
+# Crea un nuovo branch
+$ git branch nuovoBranch
+
+# Elimina un branch
+$ git branch -d nomeBranch
+
+# Rinomina un branch
+$ git branch -m nomeBranch nuovoNomeBranch
+
+# Permette di modificare la descrizione di un branch
+$ git branch nomeBranch --edit-description
+```
+
+### tag
+
+Utilizzato per gestire i tag.
+
+```bash
+# Visualizza i tag esistenti
+$ git tag
+# Crea un nuovo tag
+# L'opzione -m consente di specificare una descrizione per il tag.
+# Se l'opzione -m non viene aggiunta, Git aprirà un editor per consentire
+# l'inserimento del messaggio.
+$ git tag -a v2.0 -m 'Versione 2.0'
+# Mostra informazioni relative a un tag
+# Include informazioni sul creatore del tag, la data di creazione, e il
+# messaggio assegnato al tag oltre alle informazioni sul commit.
+$ git show v2.0
+```
+
+### checkout
+
+Consente di cambiare branch o ripristinare i file a una revisione specifica.
+Tutti i file nel working tree vengono aggiornati per corrispondere alla versione
+presente nel branch o nel commit specificato.
+
+```bash
+# Effettua il checkout di un repository - il branch predefinito è 'master'
+$ git checkout
+# Effettua il checkout di un branch specifico
+$ git checkout nomeBranch
+# Crea un nuovo branch e ne effettua il checkout
+# Equivalente a "git branch <nomeBranch>; git checkout <nomeBranch>"
+$ git checkout -b nuovoBranch
+```
+
+### clone
+
+Clona, o copia, un repository esistente in una nuova directory. Inoltre,
+aggiunge dei branch _remote-tracking_, utilizzati per monitorare i branch
+remoti corrispondenti a quelli locali, e consentendo così di inviare le
+modifiche al repository remoto.
+
+```bash
+# Clona learnxinyminutes-docs
+$ git clone https://github.com/adambard/learnxinyminutes-docs.git
+# Clona solo l'ultima revisione di un repository
+$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git
+# Clona solo un branch specifico
+$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch
+```
+
+### commit
+
+Effettua uno _snapshot_ dello stato attuale del working tree e registra le
+modifiche in un nuovo commit. Il commit contiene, oltre alle modifiche apportate,
+anche l'autore e una descrizione.
+
+```bash
+# Crea un nuovo commit con un messaggio
+$ git commit -m "Aggiunta la funzione multiplyNumbers() in HelloWorld.c"
+
+# Aggiunge (git add) automaticamente i file modificati o eliminati (ESCLUSI
+# i nuovi file) e quindi effettua il commit
+$ git commit -a -m "Modificato foo.php e rimosso bar.php"
+
+# Modifica l'ultimo commit (il comando elimina il commit precedente e lo
+# sostituisce con uno nuovo)
+$ git commit --amend -m "Messaggio corretto"
+```
+
+### diff
+
+Mostra la differenza tra un file nel working tree e la sua versione nell'index,
+in un branch o ad un commit specifico.
+
+```bash
+# Mostra la differenza tra il working tree e l'index
+$ git diff
+
+# Mostra la differenza tra l'index e il commit più recente
+$ git diff --cached
+
+# Mostra la differenza tra il working tree e un commit specifico
+$ git diff <commit>
+
+# Mostra la differenza tra due commit
+$ git diff <commit1> <commit2>
+```
+
+### grep
+
+Consente di effettuare una ricerca veloce nel repository.
+
+```bash
+# Cerca "variableName" nei file Java
+$ git grep 'variableName' -- '*.java'
+
+# Cerca una riga contenente "arrayListName" E "add" oppure "remove"
+$ git grep -e 'arrayListName' --and \( -e add -e remove \)
+```
+
+Impostazioni relative a `git grep`:
+
+```bash
+# Mostra il numero delle righe
+$ git config --global grep.lineNumber true
+
+# Rende i risultati più leggibili
+$ git config --global alias.g "grep --break --heading --line-number"
+```
+
+### log
+
+Mostra la cronologia dei commit inviati al repository.
+
+```bash
+# Mostra tutti i commit
+$ git log
+
+# Mostra ogni commit su una sola riga
+$ git log --oneline
+
+# Mostra solo i commit legati ai merge
+$ git log --merges
+```
+
+### merge
+
+Effettua un "merge", ovvero unisce le modifiche di un branch in quello attuale.
+
+```bash
+# Unisce il branch specificato a quello attuale
+$ git merge nomeBranch
+
+# Genera un commit in ogni caso dopo aver eseguito il merge
+$ git merge --no-ff nomeBranch
+```
+
+### mv
+
+Rinomina o sposta un file.
+
+```bash
+# Rinomina un file
+$ git mv HelloWorld.c HelloNewWorld.c
+
+# Sposta un file
+$ git mv HelloWorld.c ./new/path/HelloWorld.c
+
+# Forza l'esecuzione del comando
+# Se un file "nuovoNomeFile" esiste già nella directory, verrà sovrascritto
+$ git mv -f nomeFile nuovoNomeFile
+```
+
+### pull
+
+Aggiorna il repository effettuando il merge delle nuove modifiche.
+
+```bash
+# Aggiorna il branch attuale dal remote "origin"
+$ git pull
+
+# Di default, git pull aggiorna il branch attuale effettuando il merge
+# delle nuove modifiche presenti nel branch remote-tracking corrispondente
+$ git pull
+
+# Aggiorna le modifiche dal branch remoto, quindi effettua il rebase dei commit
+# nel branch locale
+# Equivalente a: "git pull <remote> <branch>; git rebase <branch>"
+$ git pull origin master --rebase
+```
+
+### push
+
+Invia ed effettua il merge delle modifiche da un branch locale ad uno remoto.
+
+```bash
+# Invia ed effettua il merge delle modifiche dal branch "master"
+# al remote "origin".
+# git push <remote> <branch>
+$ git push origin master
+
+# Di default, git push invia ed effettua il merge delle modifiche
+# dal branch attuale al branch remote-tracking corrispondente
+$ git push
+
+# Per collegare il branch attuale ad uno remoto, basta aggiungere l'opzione -u
+$ git push -u origin master
+```
+
+### stash
+
+Salva lo stato attuale del working tree in una lista di modifiche non ancora
+inviate al repository con un commit che possono essere applicate nuovamente
+in seguito.
+
+Questo comando può essere utile se, ad esempio, mentre stai effettuando delle
+modifiche non ancora completate, hai bisogno di aggiornare il repository locale
+con `git pull`. Poichè non hai ancora effettuato il commit di tutte le modifiche,
+non sarà possibile effettuare il pull. Tuttavia, puoi utilizzare `git stash` per
+salvare temporaneamente le modifiche e applicarle in seguito.
+
+```bash
+$ git stash
+```
+
+Ora puoi effettuare il pull:
+
+```bash
+$ git pull
+```
+
+A questo punto, come già suggerito dall'output del comando `git stash`, puoi
+applicare le modifiche:
+
+```bash
+$ git stash apply
+```
+
+Infine puoi controllare che tutto sia andato bene:
+
+```bash
+$ git status
+```
+
+Puoi visualizzare gli accantonamenti che hai effettuato finora utilizzando:
+
+```bash
+$ git stash list
+```
+
+### rebase (attenzione)
+
+Applica le modifiche effettuate su un branch su un altro branch.
+*Non effettuare il rebase di commit che hai già inviato a un repository pubblico!*
+
+```bash
+# Effettua il rebase di experimentBranch in master
+$ git rebase master experimentBranch
+```
+
+[Ulteriori informazioni](https://git-scm.com/book/it/v1/Diramazioni-in-Git-Rifondazione)
+
+### reset (attenzione)
+
+Effettua il reset del commit HEAD attuale ad uno stato specifico.
+Questo comando consente di annullare `merge`, `pull`, `commit`, `add` e altro.
+Tuttavia, può essere pericoloso se non si sa cosa si sta facendo.
+
+```bash
+# Effettua il reset della staging area (annullando le aggiunte e le rimozioni
+# di file dal repository, senza modificare il working tree)
+$ git reset
+
+# Effettua il reset completo della staging area, ovvero annulla qualsiasi
+# modifica al repository eliminando definitivamente anche tutte le modifiche
+# ai file non inviate e ripristinando il working tree
+$ git reset --hard
+
+# Effettua il reset del branch attuale al commit specificato (lasciando il
+# working tree intatto)
+$ git reset 31f2bb1
+
+# Effettua il reset completo del branch attuale al commit specificato,
+# eliminando qualsiasi modifica non inviata
+$ git reset --hard 31f2bb1
+```
+
+### rm
+
+Consente di rimuovere un file dal working tree e dal repository.
+Per eliminare un file solo dal working tree ma non dal repository, è invece
+necessario utilizzare `/bin/rm`.
+
+```bash
+# Elimina un file nella directory attuale
+$ git rm HelloWorld.c
+
+# Elimina un file da una sottocartella
+$ git rm /pather/to/the/file/HelloWorld.c
+```
diff --git a/it-it/python-it.html.markdown b/it-it/python-it.html.markdown
new file mode 100644
index 00000000..3a4099e7
--- /dev/null
+++ b/it-it/python-it.html.markdown
@@ -0,0 +1,647 @@
+---
+language: python
+contributors:
+ - ["Louie Dinh", "http://ldinh.ca"]
+ - ["Amin Bandali", "http://aminbandali.com"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+filename: learnpython.py
+translators:
+ - ["Ale46", "http://github.com/Ale46/"]
+lang: it-it
+---
+Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari
+linguaggi esistenti. Mi sono innamorato di Python per la sua chiarezza sintattica. E' sostanzialmente
+pseudocodice eseguibile.
+
+Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service]
+
+Nota: Questo articolo è valido solamente per Python 2.7, ma dovrebbe andar bene anche per
+Python 2.x. Per Python 3.x, dai un'occhiata a [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
+
+```python
+
+# I commenti su una sola linea iniziano con un cancelletto
+
+""" Più stringhe possono essere scritte
+ usando tre ", e sono spesso usate
+ come commenti
+"""
+
+####################################################
+## 1. Tipi di dati primitivi ed Operatori
+####################################################
+
+# Hai i numeri
+3 # => 3
+
+# La matematica è quello che vi aspettereste
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+35 / 5 # => 7
+
+# La divisione è un po' complicata. E' una divisione fra interi in cui viene
+# restituito in automatico il risultato intero.
+5 / 2 # => 2
+
+# Per le divisioni con la virgola abbiamo bisogno di parlare delle variabili floats.
+2.0 # Questo è un float
+11.0 / 4.0 # => 2.75 ahhh...molto meglio
+
+# Il risultato di una divisione fra interi troncati positivi e negativi
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # funziona anche per i floats
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
+
+# Operazione Modulo
+7 % 3 # => 1
+
+# Elevamento a potenza (x alla y-esima potenza)
+2**4 # => 16
+
+# Forzare le precedenze con le parentesi
+(1 + 3) * 2 # => 8
+
+# Operatori Booleani
+# Nota "and" e "or" sono case-sensitive
+True and False #=> False
+False or True #=> True
+
+# Note sull'uso di operatori Bool con interi
+0 and 2 #=> 0
+-5 or 0 #=> -5
+0 == False #=> True
+2 == True #=> False
+1 == True #=> True
+
+# nega con not
+not True # => False
+not False # => True
+
+# Uguaglianza è ==
+1 == 1 # => True
+2 == 1 # => False
+
+# Disuguaglianza è !=
+1 != 1 # => False
+2 != 1 # => True
+
+# Altri confronti
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
+
+# I confronti possono essere concatenati!
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
+
+# Le stringhe sono create con " o '
+"Questa è una stringa."
+'Anche questa è una stringa.'
+
+# Anche le stringhe possono essere sommate!
+"Ciao " + "mondo!" # => Ciao mondo!"
+# Le stringhe possono essere sommate anche senza '+'
+"Ciao " "mondo!" # => Ciao mondo!"
+
+# ... oppure moltiplicate
+"Hello" * 3 # => "HelloHelloHello"
+
+# Una stringa può essere considerata come una lista di caratteri
+"Questa è una stringa"[0] # => 'Q'
+
+# % può essere usato per formattare le stringhe, in questo modo:
+"%s possono essere %s" % ("le stringhe", "interpolate")
+
+# Un nuovo modo per fomattare le stringhe è il metodo format.
+# Questo metodo è quello consigliato
+"{0} possono essere {1}".format("le stringhe", "formattate")
+# Puoi usare delle parole chiave se non vuoi contare
+"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="lasagna")
+
+# None è un oggetto
+None # => None
+
+# Non usare il simbolo di uguaglianza "==" per comparare oggetti a None
+# Usa "is" invece
+"etc" is None # => False
+None is None # => True
+
+# L'operatore 'is' testa l'identità di un oggetto. Questo non è
+# molto utile quando non hai a che fare con valori primitivi, ma lo è
+# quando hai a che fare con oggetti.
+
+# None, 0, e stringhe/liste vuote sono tutte considerate a False.
+# Tutti gli altri valori sono True
+bool(0) # => False
+bool("") # => False
+
+
+####################################################
+## 2. Variabili e Collections
+####################################################
+
+# Python ha una funzione di stampa
+print "Sono Python. Piacere di conoscerti!"
+
+# Non c'è bisogno di dichiarare una variabile per assegnarle un valore
+una_variabile = 5 # Convenzionalmente si usa caratteri_minuscoli_con_underscores
+una_variabile # => 5
+
+# Accedendo ad una variabile non precedentemente assegnata genera un'eccezione.
+# Dai un'occhiata al Control Flow per imparare di più su come gestire le eccezioni.
+un_altra_variabile # Genera un errore di nome
+
+# if può essere usato come un'espressione
+"yahoo!" if 3 > 2 else 2 # => "yahoo!"
+
+# Liste immagazzinano sequenze
+li = []
+# Puoi partire con una lista pre-riempita
+altra_li = [4, 5, 6]
+
+# Aggiungi cose alla fine di una lista con append
+li.append(1) # li ora è [1]
+li.append(2) # li ora è [1, 2]
+li.append(4) # li ora è [1, 2, 4]
+li.append(3) # li ora è [1, 2, 4, 3]
+# Rimuovi dalla fine della lista con pop
+li.pop() # => 3 e li ora è [1, 2, 4]
+# Rimettiamolo a posto
+li.append(3) # li ora è [1, 2, 4, 3] di nuovo.
+
+# Accedi ad una lista come faresti con un array
+li[0] # => 1
+# Assegna nuovo valore agli indici che sono già stati inizializzati con =
+li[0] = 42
+li[0] # => 42
+li[0] = 1 # Nota: è resettato al valore iniziale
+# Guarda l'ultimo elemento
+li[-1] # => 3
+
+# Guardare al di fuori dei limiti è un IndexError
+li[4] # Genera IndexError
+
+# Puoi guardare gli intervalli con la sintassi slice (a fetta).
+# (E' un intervallo chiuso/aperto per voi tipi matematici.)
+li[1:3] # => [2, 4]
+# Ometti l'inizio
+li[2:] # => [4, 3]
+# Ometti la fine
+li[:3] # => [1, 2, 4]
+# Seleziona ogni seconda voce
+li[::2] # =>[1, 4]
+# Copia al contrario della lista
+li[::-1] # => [3, 4, 2, 1]
+# Usa combinazioni per fare slices avanzate
+# li[inizio:fine:passo]
+
+# Rimuovi arbitrariamente elementi da una lista con "del"
+del li[2] # li è ora [1, 2, 3]
+# Puoi sommare le liste
+li + altra_li # => [1, 2, 3, 4, 5, 6]
+# Nota: i valori per li ed altra_li non sono modificati.
+
+# Concatena liste con "extend()"
+li.extend(altra_li) # Ora li è [1, 2, 3, 4, 5, 6]
+
+# Controlla l'esistenza di un valore in una lista con "in"
+1 in li # => True
+
+# Esamina la lunghezza con "len()"
+len(li) # => 6
+
+
+# Tuple sono come le liste ma immutabili.
+tup = (1, 2, 3)
+tup[0] # => 1
+tup[0] = 3 # Genera un TypeError
+
+# Puoi fare tutte queste cose da lista anche sulle tuple
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# Puoi scompattare le tuple (o liste) in variabili
+a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 and c è ora 3
+# Le tuple sono create di default se non usi le parentesi
+d, e, f = 4, 5, 6
+# Guarda come è facile scambiare due valori
+e, d = d, e # d è ora 5 ed e è ora 4
+
+
+# Dizionari immagazzinano mappature
+empty_dict = {}
+# Questo è un dizionario pre-riempito
+filled_dict = {"uno": 1, "due": 2, "tre": 3}
+
+# Accedi ai valori con []
+filled_dict["uno"] # => 1
+
+# Ottieni tutte le chiavi come una lista con "keys()"
+filled_dict.keys() # => ["tre", "due", "uno"]
+# Nota - Nei dizionari l'ordine delle chiavi non è garantito.
+# Il tuo risultato potrebbe non essere uguale a questo.
+
+# Ottieni tutt i valori come una lista con "values()"
+filled_dict.values() # => [3, 2, 1]
+# Nota - Come sopra riguardo l'ordinamento delle chiavi.
+
+# Controlla l'esistenza delle chiavi in un dizionario con "in"
+"uno" in filled_dict # => True
+1 in filled_dict # => False
+
+# Cercando una chiave non esistente è un KeyError
+filled_dict["quattro"] # KeyError
+
+# Usa il metodo "get()" per evitare KeyError
+filled_dict.get("uno") # => 1
+filled_dict.get("quattro") # => None
+# Il metodo get supporta un argomento di default quando il valore è mancante
+filled_dict.get("uno", 4) # => 1
+filled_dict.get("quattro", 4) # => 4
+# nota che filled_dict.get("quattro") è ancora => None
+# (get non imposta il valore nel dizionario)
+
+# imposta il valore di una chiave con una sintassi simile alle liste
+filled_dict["quattro"] = 4 # ora, filled_dict["quattro"] => 4
+
+# "setdefault()" aggiunge al dizionario solo se la chiave data non è presente
+filled_dict.setdefault("five", 5) # filled_dict["five"] è impostato a 5
+filled_dict.setdefault("five", 6) # filled_dict["five"] è ancora 5
+
+
+# Sets immagazzina ... sets (che sono come le liste, ma non possono contenere doppioni)
+empty_set = set()
+# Inizializza un "set()" con un po' di valori
+some_set = set([1, 2, 2, 3, 4]) # some_set è ora set([1, 2, 3, 4])
+
+# l'ordine non è garantito, anche se a volta può sembrare ordinato
+another_set = set([4, 3, 2, 2, 1]) # another_set è ora set([1, 2, 3, 4])
+
+# Da Python 2.7, {} può essere usato per dichiarare un set
+filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
+
+# Aggiungere elementi ad un set
+filled_set.add(5) # filled_set è ora {1, 2, 3, 4, 5}
+
+# Fai intersezioni su un set con &
+other_set = {3, 4, 5, 6}
+filled_set & other_set # => {3, 4, 5}
+
+# Fai unioni su set con |
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+
+# Fai differenze su set con -
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+
+# Controlla l'esistenza in un set con in
+2 in filled_set # => True
+10 in filled_set # => False
+
+
+####################################################
+## 3. Control Flow
+####################################################
+
+# Dichiariamo una variabile
+some_var = 5
+
+# Questo è un controllo if. L'indentazione è molto importante in python!
+# stampa "some_var è più piccola di 10"
+if some_var > 10:
+ print "some_var è decisamente più grande di 10."
+elif some_var < 10: # Questa clausola elif è opzionale.
+ print "some_var è più piccola di 10."
+else: # Anche questo è opzionale.
+ print "some_var è precisamente 10."
+
+
+"""
+I cicli for iterano sulle liste
+stampa:
+ cane è un mammifero
+ gatto è un mammifero
+ topo è un mammifero
+"""
+for animale in ["cane", "gatto", "topo"]:
+ # Puoi usare {0} per interpolare le stringhe formattate. (Vedi di seguito.)
+ print "{0} è un mammifero".format(animale)
+
+"""
+"range(numero)" restituisce una lista di numeri
+da zero al numero dato
+stampa:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print i
+
+"""
+"range(lower, upper)" restituisce una lista di numeri
+dal più piccolo (lower) al più grande (upper)
+stampa:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print i
+
+"""
+I cicli while vengono eseguiti finchè una condizione viene a mancare
+stampa:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print x
+ x += 1 # Forma compatta per x = x + 1
+
+# Gestisci le eccezioni con un blocco try/except
+
+# Funziona da Python 2.6 in su:
+try:
+ # Usa "raise" per generare un errore
+ raise IndexError("Questo è un errore di indice")
+except IndexError as e:
+ pass # Pass è solo una non-operazione. Solitamente vorrai fare un recupero.
+except (TypeError, NameError):
+ pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario.
+else: # Clausola opzionale al blocco try/except. Deve seguire tutti i blocchi except
+ print "Tutto ok!" # Viene eseguita solo se il codice dentro try non genera eccezioni
+finally: # Eseguito sempre
+ print "Possiamo liberare risorse qui"
+
+# Invece di try/finally per liberare risorse puoi usare il metodo with
+with open("myfile.txt") as f:
+ for line in f:
+ print line
+
+####################################################
+## 4. Funzioni
+####################################################
+
+# Usa "def" per creare nuove funzioni
+def aggiungi(x, y):
+ print "x è {0} e y è {1}".format(x, y)
+ return x + y # Restituisce valori con il metodo return
+
+# Chiamare funzioni con parametri
+aggiungi(5, 6) # => stampa "x è 5 e y è 6" e restituisce 11
+
+# Un altro modo per chiamare funzioni è con parole chiave come argomenti
+aggiungi(y=6, x=5) # Le parole chiave come argomenti possono arrivare in ogni ordine.
+
+
+# Puoi definire funzioni che accettano un numero variabile di argomenti posizionali
+# che verranno interpretati come tuple se non usi il *
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) # => (1, 2, 3)
+
+
+# Puoi definire funzioni che accettano un numero variabile di parole chiave
+# come argomento, che saranno interpretati come un dizionario se non usi **
+def keyword_args(**kwargs):
+ return kwargs
+
+# Chiamiamola per vedere cosa succede
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+
+
+# Puoi farle entrambi in una volta, se ti va
+def all_the_args(*args, **kwargs):
+ print args
+ print kwargs
+"""
+all_the_args(1, 2, a=3, b=4) stampa:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# Quando chiami funzioni, puoi fare l'opposto di args/kwargs!
+# Usa * per sviluppare gli argomenti posizionale ed usa ** per espandere gli argomenti parola chiave
+args = (1, 2, 3, 4)
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # equivalente a foo(1, 2, 3, 4)
+all_the_args(**kwargs) # equivalente a foo(a=3, b=4)
+all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4)
+
+# puoi passare args e kwargs insieme alle altre funzioni che accettano args/kwargs
+# sviluppandoli, rispettivamente, con * e **
+def pass_all_the_args(*args, **kwargs):
+ all_the_args(*args, **kwargs)
+ print varargs(*args)
+ print keyword_args(**kwargs)
+
+# Funzioni Scope
+x = 5
+
+def setX(num):
+ # La variabile locale x non è uguale alla variabile globale x
+ x = num # => 43
+ print x # => 43
+
+def setGlobalX(num):
+ global x
+ print x # => 5
+ x = num # la variabile globable x è ora 6
+ print x # => 6
+
+setX(43)
+setGlobalX(6)
+
+# Python ha funzioni di prima classe
+def create_adder(x):
+ def adder(y):
+ return x + y
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) # => 13
+
+# Ci sono anche funzioni anonime
+(lambda x: x > 2)(3) # => True
+
+# Esse sono incluse in funzioni di alto livello
+map(add_10, [1, 2, 3]) # => [11, 12, 13]
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+
+# Possiamo usare la comprensione delle liste per mappe e filtri
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
+
+
+####################################################
+## 5. Classi
+####################################################
+
+# Usiamo una sottoclasse da un oggetto per avere una classe.
+class Human(object):
+
+ # Un attributo della classe. E' condiviso da tutte le istanze delle classe
+ species = "H. sapiens"
+
+ # Costruttore base, richiamato quando la classe viene inizializzata.
+ # Si noti che il doppio leading e gli underscore finali denotano oggetti
+ # o attributi che sono usati da python ma che vivono nello spazio dei nome controllato
+ # dall'utente. Non dovresti usare nomi di questo genere.
+ def __init__(self, name):
+ # Assegna l'argomento all'attributo name dell'istanza
+ self.name = name
+
+ # Un metodo dell'istanza. Tutti i metodi prendo "self" come primo argomento
+ def say(self, msg):
+ return "{0}: {1}".format(self.name, msg)
+
+ # Un metodo della classe è condiviso fra tutte le istanze
+ # Sono chiamate con la classe chiamante come primo argomento
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # Un metodo statico è chiamato senza una classe od una istanza di riferimento
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+
+# Instanziare una classe
+i = Human(name="Ian")
+print i.say("hi") # stampa "Ian: hi"
+
+j = Human("Joel")
+print j.say("hello") # stampa "Joel: hello"
+
+# Chiamare metodi della classe
+i.get_species() # => "H. sapiens"
+
+# Cambiare l'attributo condiviso
+Human.species = "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
+
+# Chiamare il metodo condiviso
+Human.grunt() # => "*grunt*"
+
+
+####################################################
+## 6. Moduli
+####################################################
+
+# Puoi importare moduli
+import math
+print math.sqrt(16) # => 4
+
+# Puoi ottenere specifiche funzione da un modulo
+from math import ceil, floor
+print ceil(3.7) # => 4.0
+print floor(3.7) # => 3.0
+
+# Puoi importare tutte le funzioni da un modulo
+# Attenzione: questo non è raccomandato
+from math import *
+
+# Puoi abbreviare i nomi dei moduli
+import math as m
+math.sqrt(16) == m.sqrt(16) # => True
+# puoi anche verificare che le funzioni sono equivalenti
+from math import sqrt
+math.sqrt == m.sqrt == sqrt # => True
+
+# I moduli di Python sono normali file python. Ne puoi
+# scrivere di tuoi ed importarli. Il nome del modulo
+# è lo stesso del nome del file.
+
+# Potete scoprire quali funzioni e attributi
+# definiscono un modulo
+import math
+dir(math)
+
+
+####################################################
+## 7. Avanzate
+####################################################
+
+# I generatori ti aiutano a fare codice pigro
+def double_numbers(iterable):
+ for i in iterable:
+ yield i + i
+
+# Un generatore crea valori al volo.
+# Invece di generare e ritornare tutti i valori in una volta ne crea uno in ciascuna
+# iterazione. Ciò significa che i valori più grandi di 15 non saranno considerati in
+# double_numbers.
+# Nota xrange è un generatore che fa la stessa cosa di range.
+# Creare una lista 1-900000000 occuperebbe molto tempo e spazio.
+# xrange crea un oggetto generatore xrange invece di creare l'intera lista
+# come fa range.
+# Usiamo un underscore finale nel nome delle variabile quando vogliamo usare un nome
+# che normalmente colliderebbe con una parola chiave di python
+xrange_ = xrange(1, 900000000)
+
+# raddoppierà tutti i numeri fino a che result >=30 non sarà trovato
+for i in double_numbers(xrange_):
+ print i
+ if i >= 30:
+ break
+
+
+# Decoratori
+# in questo esempio beg include say
+# Beg chiamerà say. Se say_please è True allora cambierà il messaggio
+# ritornato
+from functools import wraps
+
+
+def beg(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, "Per favore! Sono povero :(")
+ return msg
+
+ return wrapper
+
+
+@beg
+def say(say_please=False):
+ msg = "Puoi comprarmi una birra?"
+ return msg, say_please
+
+
+print say() # Puoi comprarmi una birra?
+print say(say_please=True) # Puoi comprarmi una birra? Per favore! Sono povero :(
+```
+
+## Pronto per qualcosa di più?
+
+### Gratis 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/)
+* [The Official Docs](http://docs.python.org/2.6/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/2/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+
+### Libri cartacei
+
+* [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)
diff --git a/it-it/ruby-ecosystem-it.html.markdown b/it-it/ruby-ecosystem-it.html.markdown
new file mode 100644
index 00000000..d745399b
--- /dev/null
+++ b/it-it/ruby-ecosystem-it.html.markdown
@@ -0,0 +1,145 @@
+---
+category: tool
+tool: ruby ecosystem
+contributors:
+ - ["Jon Smock", "http://github.com/jonsmock"]
+ - ["Rafal Chmiel", "http://github.com/rafalchmiel"]
+translators:
+ - ["Cristian Achille", "http://github.com/blackdev1l/"]
+lang: it-it
+---
+
+Generalmente chi usa ruby ha l'esigenza di avere differenti versioni di Ruby
+installate, gestire le proprie gemme, e le loro dipendenze.
+
+## Manager Ruby
+
+Alcune piattaforme hanno Ruby pre-installato o disponibile come pacchetto.
+Molti sviluppatori Ruby non usano questi pacchetti, o se lo fanno, li usano solo
+per installare dei manager Ruby, i quali permettono di installare e gestire più
+versioni di Ruby in base al progetto su cui si lavora.
+
+Di seguito i più famosi manager Ruby:
+
+* [RVM](https://rvm.io/) - Installa e permette di utilizzare diverse versioni di
+ Ruby. RVM Ha anche il concetto di gemsets i quali isolano completamente l'ambiente di sviluppo del progetto.
+* [ruby-build](https://github.com/sstephenson/ruby-build) - Installa solamente
+ multiple versioni di ruby. Usa questo se vuoi maggior controllo sull'installazione di Ruby.
+* [rbenv](https://github.com/sstephenson/rbenv) -
+ Permette solo la scelta di quale versione Ruby utilizzare. Usato insieme a ruby-build.
+ Utilizza questo per un maggior controllo su quale versione di Ruby utilizzare.
+* [chruby](https://github.com/postmodern/chruby) -
+ Permette solo la scelta di quale Ruby utilizzare, simile a rbenv.
+
+## Ruby Versions
+
+Ruby fu creato da Yukihiro "Matz" Matsumoto, il [BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life),
+(acronimo inglese che sta per "Benevolo dittatore a vita") , seppur
+ultimamente non è più del tutto vera; l'implementazione di Ruby
+è detta MRI (Matz' Reference Implementation), e dunque quando si legge di una
+versione Ruby, essa si riferisce sempre al rilascio di una MRI
+
+Le tre maggiori versioni di Ruby in uso sono:
+
+* 2.0.0 - Rilasciata nel febbraio 2013. La maggior parte delle librerie e
+ framework supportano la 2.0.0
+* 1.9.3 - Rilasciata nel ottobre 2011. QUesta è la versione che molti
+ svluppatori usano, il supporto è
+ [concluso](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/)
+* 1.8.7 - Il supporto per Ruby 1.8.7 è
+ [concluso](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/).
+
+I cambiamenti tra la 1.8.7 a la 1.9.x sono maggiori di quelli tra la 1.9.3 a la
+2.0.0. Per esempio, nella 1.9 vengono introdotti encodings e bytecode VM.
+Esistono ancora dei progetti basati sulla 1.8.7, ma stanno diventando una
+minoranza man mano che la community si trasferisce alle versioni 1.92 e
+1.9.3
+
+## Ruby Implementations
+
+L'ecosistema Ruby gode di molte implementazioni differenti di Ruby, ognuna con
+particolari punti di forza, da chiarire che ogni implementazione è scritta con
+un linguaggio diverso, ma esse *sono tutte Ruby*. Ogni implementazione ha
+feature extra ma tutte esse possono eseguire file ruby. Per esempio, JRuby è
+scritto in Java, ma non devi conoscere java per usarlo.
+
+Implementazioni mature e compatibili:
+
+* [MRI](https://github.com/ruby/ruby) - Scritto in C, Questa è l'implementazione
+ standard di Ruby, per definizione è 100% compatibile (con se stessa). Tutte le
+ altre implemetazioni mantengono la compatibilità con MRI
+ (vedere [RubySpec](#rubyspec) sotto).
+* [JRuby](http://jruby.org/) - Scritto in Java e Ruby, Questa implementazione è
+ molto veloce e robusta, la forza di JRuby consiste nell'interoperabilità
+ tra JVM/Java, permettendo l'utilizzo di struemnti Java già esistenti, progetti
+ e linguaggi
+* [Rubinius](http://rubini.us/) - Scritto principalmente in Ruby con un
+ c++ bytecode VM, molto matura e veloce, permette alcune feature riguardo VM.
+
+Mediamente mature e compatibili:
+
+* [Maglev](http://maglev.github.io/) - Sviluppata sui Gemstone, è una Smalltalk
+VM, Smalltalk è degli strumenti molto utili, e questo progetto cerca di portare
+questi strumenti nello sviluppo Ruby.
+* [RubyMotion](http://www.rubymotion.com/) - Porta ruby nello sviluppo iOS.
+
+Poco mature e compatibili:
+
+* [Topaz](http://topazruby.com/) - Scritto in RPython (usando PyPy come
+ toolchain) Topaz è un progetto ancora giovane e non compatibile, ha le
+ possibilità di diventare una implementazione Ruby molto performante
+* [IronRuby](http://ironruby.net/) - Scritto in C# e prendendo di mira la
+ piattaforma .NET, lo sviluppo sembra fermo da quando Microsoft ha rimosso il
+ suo supporto.
+
+Le implementazioni Ruby possono avere una propria versione, ma hanno sempre come
+target una specifica versione di MRI. Molte implementazioni hanno l'abilità di
+selezionare una versione specifica di MRI.
+
+##RubySpec
+
+La maggior parte delle implementazioni Ruby dipendono pesantemente su
+[RubySpec](http://rubyspec.org/). Ruby non ha una specifica ufficiale, quindi la
+community ha scritto una specifica eseguibile in Ruby per testare la compatibilità
+con MRI.
+
+## RubyGems
+
+[RubyGems](http://rubygems.org/) è un package manager gestito dalla communtiy
+per Ruby. Rubygems viene installato con Ruby, quindi non c'è bisogno di
+scaricarlo separatamente.
+
+I pacchetti Ruby sono chiamate "gemme", e possono essere hostate dalla community
+su RubyGems.org . Ogni gemma contiene il codice sorgente e del metadata, tra cui
+la versione, le dipendenze, autor* e licenz*.
+
+## Bundler
+
+[Bundler](http://bundler.io/) è un risolvitore di dipendenze, Esso usa il Gemfile
+di un progetto per cercare le dipendenze, dopo di che ottiene le dipendenze delle
+dipendenze ricorsivamente, Questo procedimento viene eseguito finchè tutte le
+dipendenze sono state risolte e scaricate, o si fermerà se un conflitto verrà
+trovato.
+
+Bundler genererà un error se troverà dipendenze in conflitto, Per esempio,
+se la gemma A richiede la versione 3 o maggiore della gemma Z, ma la gemma B
+richiede la versione 2, Bundler ti notificherà del conflitto. Questo diventa
+di aiuto nel momento in cui si hanno molte gemme nel progetto, il che porta a
+un grande grafo di dipendenza da risolvere.
+
+# Testing
+
+Il testing è un pezzo fondamentale della cultura Ruby, Ruby viene installato con
+il proprio testing framework chiamato minitest (O TestUnit per ruby 1.8.x).
+Esistono molte librerie con obiettivi differenti
+
+* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - Testing frameowrk rilasciato insieme a Ruby 1.8.x
+* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - Testing frameowrk rilasciato insieme a Ruby 1.9/2.0
+* [RSpec](http://rspec.info/) - Un testing framework che si concentra nella chiarezza
+* [Cucumber](http://cukes.info/) - Un BDD testing framework che estrapola testo formattato in Gherkin
+
+## Sii cordiale
+
+La community Ruby è orgogliosa di essere una communtiy aperta, accogliente e
+variegata. Matz stesso è estremamente amichevole, e la generosità degli sviluppatori
+Ruby è fantastica.
diff --git a/ja-jp/bash-jp.html.markdown b/ja-jp/bash-jp.html.markdown
index 88e5ff1c..ea8fa49f 100644
--- a/ja-jp/bash-jp.html.markdown
+++ b/ja-jp/bash-jp.html.markdown
@@ -66,7 +66,7 @@ echo "Last program return value: $?"
echo "Script's PID: $$"
echo "Number of arguments: $#"
echo "Scripts arguments: $@"
-echo "Scripts arguments seperated in different variables: $1 $2..."
+echo "Scripts arguments separated in different variables: $1 $2..."
# 入力値の読み込み
echo "What's your name?"
@@ -117,7 +117,7 @@ echo "There are $(ls | wc -l) items here."
echo "There are `ls | wc -l` items here."
# BashはJavaやC++のように、case文による分岐ができます
-case "$VARIABLE" in
+case "$VARIABLE" in
#分岐条件として使いたいパターンを並べてください
0) echo "There is a zero.";;
1) echo "There is a one.";;
diff --git a/ja-jp/php-jp.html.markdown b/ja-jp/php-jp.html.markdown
new file mode 100644
index 00000000..112916f4
--- /dev/null
+++ b/ja-jp/php-jp.html.markdown
@@ -0,0 +1,777 @@
+---
+language: PHP
+contributors:
+ - ["Malcolm Fell", "http://emarref.net/"]
+ - ["Trismegiste", "https://github.com/Trismegiste"]
+translators:
+ - ["Kazushige Tominaga", "https://github.com/kazu9su"]
+filename: learnphp-jp.php
+lang: ja-jp
+---
+
+このドキュメントでは、 PHP 5+ について説明します。
+
+```php
+<?php // PHPのコードは、<?php タグで囲む必要があります。
+
+// もしあなたのphpファイルがPHPのみで構成される場合、
+// 意図しない出力を防ぐために、phpの閉じタグは省略するのがベストプラクティスです。
+// 一行のコメントを書く場合、2つのスラッシュで始めます。
+# ハッシュ(ポンド記号として知られる)を使いたいでしょうが、//のほうが一般的です
+/*
+ スラッシュとアスタリスク、アスタリスクとスラッシュで囲むと、
+ 複数行のコメントを書けます。
+*/
+
+// 出力をプリントしたい場合は、"echo" か "print" を使います。
+print('Hello '); // これは "Hello " という改行なしの文字列をプリントします。
+
+// カッコ()はprintとecho関数に置いては省略できます。
+echo "World\n"; // これは改行ありの"World"という文字列をプリントします。
+// (全ての命令文では、セミコロンを最後に付けることが必須です。)
+
+// <?php タグの外側にあるものは、自動的にプリントされます。
+?>
+Hello World Again!
+<?php
+
+
+/************************************
+ * 型と変数について
+ */
+
+// 変数は"$"マークで始まります
+// 有効な変数名にするには、文字またはアンダースコア(_)で始めて,
+// その後はどんな数字でも、文字でも、アンダースコアで続けても構いません
+
+//ブーリアン値は大文字、小文字問いません
+$boolean = true; // or TRUE or True
+$boolean = false; // or FALSE or False
+
+// 数値
+$int1 = 12; // => 12
+$int2 = -12; // => -12
+$int3 = 012; // => 10 (先頭の0は8進法を示す)
+$int4 = 0x0F; // => 15 (先頭の0xは16進法を示す)
+
+// floats(浮動小数) (別名double)
+$float = 1.234;
+$float = 1.2e3;
+$float = 7E-10;
+
+// 変数の削除
+unset($int1);
+
+// 計算式
+$sum = 1 + 1; // 2
+$difference = 2 - 1; // 1
+$product = 2 * 2; // 4
+$quotient = 2 / 1; // 2
+
+// 式の省略
+$number = 0;
+$number += 1; // $numberに1加算Increment $number by 1
+echo $number++; // 1 がプリントされる(式の評価の後に加算される)
+echo ++$number; // 3 がプリントされる(式の評価の前に加算される)
+$number /= $float; // 割り算した結果の商を$numberに割り当てる
+
+// 文字列はシングルクォートで囲むのが望ましいです
+$sgl_quotes = '$String'; // => '$String'
+
+// 文字列中に、他の変数を埋め込みたい場合以外は、ダブルクォートを使用するのはやめましょう
+$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.'
+
+// Special characters are only escaped in double quotes
+// 特殊文字はダブルクォートによってのみ、エスケープされます
+$escaped = "This contains a \t tab character.";
+$unescaped = 'This just contains a slash and a t: \t';
+
+// 必要があれば、変数を波括弧で囲みます
+$money = "I have $${number} in the bank.";
+
+// PHP 5.3から、nowdocs形式が変数の挿入をしない複数行の文字列の定義に使用できます
+$nowdoc = <<<'END'
+Multi line
+string
+END;
+
+// ヒアドキュメント形式なら、文字列中に変数の挿入を行えます。
+$heredoc = <<<END
+Multi line
+$sgl_quotes
+END;
+
+// 文字列の連結は . で行います
+echo 'This string ' . 'is concatenated';
+
+// 別々のパラメータとしてechoに渡すこともできます
+echo 'Multiple', 'Parameters', 'Valid';
+
+/********************************
+ * 定数
+ */
+
+// 定数は define() を使って定義します
+// また、実行中は変更することができないので注意が必要です!
+
+// 有効は定数は文字かアンダースコアで始めます
+// それ移行のは、どんな数値でも文字列でもアンダースコアでも構いません
+define("FOO", "something");
+
+// 定義した名前をそのまま($はつけずに)使用することで、定数にアクセスできます
+// access to a constant is possible by direct using the choosen name
+echo 'This outputs '.FOO;
+
+
+/********************************
+ * 配列
+ */
+
+// PHPの配列はすべて連想配列です
+
+// 連想配列は、他の言語ではハッシュ(ハッシュマップ)として知られています
+
+// すべてのバージョンのPHPで動作します
+$associative = array('One' => 1, 'Two' => 2, 'Three' => 3);
+
+// PHP 5.4 から、新しいシンタックスが導入されました
+$associative = ['One' => 1, 'Two' => 2, 'Three' => 3];
+
+echo $associative['One']; // 1とプリントされます
+
+// キーを指定しないシンプルな配列にも、自動的に数値キーが振られます
+$array = ['One', 'Two', 'Three'];
+echo $array[0]; // => "One"
+
+// 配列の最後に要素を追加する
+$array[] = 'Four';
+// または、次のようにも書けます
+array_push($array, 'Five');
+
+// 配列から要素を削除
+unset($array[3]);
+
+/********************************
+ * 出力
+ */
+
+echo('Hello World!');
+// 標準出力にHello World! とプリントします
+// 標準出力はブラウザーで実行していればWebページに出力されます
+// Stdout is the web page if running in a browser.
+
+print('Hello World!'); // echoの結果と同じです
+
+// echo は言語自体の構成要素であり、括弧なしで呼び出せます
+// echo is actually a language construct, so you can drop the parentheses.
+echo 'Hello World!';
+print 'Hello World!'; // printも同様です
+
+$paragraph = 'paragraph';
+
+echo 100; // スカラー数値を直接出力します
+echo $paragraph; // 変数も使用できます
+
+// PHPタグの短縮型が設定されているか、使用しているPHPのバージョンが
+// 5.4.0 以上であれば、短縮echoシンタックスを使用できます
+?>
+<p><?= $paragraph ?></p>
+<?php
+
+$x = 1;
+$y = 2;
+$x = $y; // $xに$yの値を代入します
+$z = &$y;
+// $zは$yへの参照です。
+// $zの値を変更すると$yの値も変更されるでしょう。逆も同様です。
+// $xは$yの最初の値を変わらず保持しています
+
+echo $x; // => 2
+echo $z; // => 2
+$y = 0;
+echo $x; // => 2
+echo $z; // => 0
+
+// 変数の型と値を標準出力へダンプします
+var_dump($z); // int(0) と出力されます
+
+// 人間が読めるフォーマットで変数を標準出力にプリントします
+print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three )
+
+/********************************
+ * ロジック
+ */
+$a = 0;
+$b = '0';
+$c = '1';
+$d = '1';
+
+// assertは引数がfalseの場合、Exceptionを投げます
+
+//これらの比較は型が違ったとしても、常に真です。
+assert($a == $b); // equality
+assert($c != $a); // inequality
+assert($c <> $a); // alternative inequality
+assert($a < $c);
+assert($c > $b);
+assert($a <= $b);
+assert($c >= $d);
+
+// 次の比較は値が等しく、かつ同じ型である場合のみ真です
+assert($c === $d);
+assert($a !== $d);
+assert(1 === '1');
+assert(1 !== '1');
+
+// spaceship演算子はPHP7から使用可能です
+$a = 100;
+$b = 1000;
+
+echo $a <=> $a; // 等しいので0になります
+echo $a <=> $b; // $a < $b なので -1 です
+echo $b <=> $a; // $b > $a なので 1 です
+
+// 変数は使用するコンテキストによって、変換されます
+
+$integer = 1;
+echo $integer + $integer; // => 2
+
+$string = '1';
+echo $string + $string; // => 2 (文字列は強制的に数値として処理されます)
+
+$string = 'one';
+echo $string + $string; // => 0
+// '+'演算子は文字列'one'を数値にキャストできないので、0と出力されます
+
+// 型のキャスティングによって、変数を指定したもう一つの型として扱うことができます
+// Type casting can be used to treat a variable as another type
+
+$boolean = (boolean) 1; // => true
+
+$zero = 0;
+$boolean = (boolean) $zero; // => false
+
+// 型をキャストするため専用の関数も存在します
+$integer = 5;
+$string = strval($integer);
+
+$var = null; // Null値
+
+
+/********************************
+ * 制御構造
+ */
+
+if (true) {
+ print 'I get printed';
+}
+
+if (false) {
+ print 'I don\'t';
+} else {
+ print 'I get printed';
+}
+
+if (false) {
+ print 'Does not get printed';
+} elseif(true) {
+ print 'Does';
+}
+
+// 三項演算子
+print (false ? 'Does not get printed' : 'Does');
+
+// PHP 5.3から、三項演算子の短縮形が使用できます
+// $x ? $x : 'Does'と同義です
+$x = false;
+print($x ?: 'Does');
+
+// null合体演算子はPHP 7から使用できます
+$a = null;
+$b = 'Does print';
+echo $a ?? 'a is not set'; // prints 'a is not set'
+echo $b ?? 'b is not set'; // prints 'Does print'
+
+
+$x = 0;
+if ($x === '0') {
+ print 'Does not print';
+} elseif($x == '1') {
+ print 'Does not print';
+} else {
+ print 'Does print';
+}
+
+
+
+// :を用いる別の構文はテンプレートで有用です
+?>
+
+<?php if ($x): ?>
+この部分はifが真のとき表示されます
+<?php else: ?>
+それ以外の場合は、この部分が表示されます
+<?php endif; ?>
+
+<?php
+
+// いくつかのロジックを保存するにはswitchを使用します
+switch ($x) {
+ case '0':
+ print 'Switch does type coercion';
+ break; // breakを書く必要があります。
+ // でなければ、次の'two', 'three'のcase文を続けて実行することになります。
+ case 'two':
+ case 'three':
+ // 変数が'two'または'three'の場合、何かを実行します
+ break;
+ default:
+ //デフォルトで何かを実行します
+}
+
+// while, do, forの構文は、おそらく他の言語とも共通なものです
+$i = 0;
+while ($i < 5) {
+ echo $i++;
+}; // Prints "01234"
+
+echo "\n";
+
+$i = 0;
+do {
+ echo $i++;
+} while ($i < 5); // Prints "01234"
+
+echo "\n";
+
+for ($x = 0; $x < 10; $x++) {
+ echo $x;
+} // Prints "0123456789"
+
+echo "\n";
+
+$wheels = ['bicycle' => 2, 'car' => 4];
+
+//Foreachループによって、 配列を反復処理できます
+foreach ($wheels as $wheel_count) {
+ echo $wheel_count;
+} // Prints "24"
+
+echo "\n";
+
+// 値と同じ様に、keyも反復処理できます
+foreach ($wheels as $vehicle => $wheel_count) {
+ echo "A $vehicle has $wheel_count wheels";
+}
+
+echo "\n";
+
+$i = 0;
+while ($i < 5) {
+ if ($i === 3) {
+ break; // Exit out of the while loop
+ }
+ echo $i++;
+} // Prints "012"
+
+for ($i = 0; $i < 5; $i++) {
+ if ($i === 3) {
+ continue; // Skip this iteration of the loop
+ }
+ echo $i;
+} // Prints "0124"
+
+
+/********************************
+ * 関数
+ */
+
+// 関数を"function"で定義します
+function my_function () {
+ return 'Hello';
+}
+
+echo my_function(); // => "Hello"
+
+// 有効な関数名は、文字またはアンダースコアで始めます。それ以降は
+// どれだけ長い文字、数値、アンダースコアを続けても構いません
+
+function add ($x, $y = 1) { // $yはオプショナルな値であり、デフォルトで 1 です
+ $result = $x + $y;
+ return $result;
+}
+
+echo add(4); // => 5
+echo add(4, 2); // => 6
+
+// $result には、関数の外からアクセス出来ません
+// print $result; // エラーになります
+
+// PHP 5.3 から、無名関数が使えます
+$inc = function ($x) {
+ return $x + 1;
+};
+
+echo $inc(2); // => 3
+
+function foo ($x, $y, $z) {
+ echo "$x - $y - $z";
+}
+
+// 関数は、関数を返すことができます
+function bar ($x, $y) {
+ // 関数外の変数を利用したいときは、'use'を使います
+ return function ($z) use ($x, $y) {
+ foo($x, $y, $z);
+ };
+}
+
+$bar = bar('A', 'B');
+$bar('C'); // Prints "A - B - C"
+
+// 文字列を使って、定義済みの関数を呼び出すことができます
+$function_name = 'add';
+echo $function_name(1, 2); // => 3
+
+// プログラミング中に、動的に動かす関数を決める場合に便利です。
+// もしくは、call_user_func(callable $callback [, $parameter [, ... ]]) を使っても同じことができます
+
+
+// 特に指定しなくても、渡された引数を受け取ることもできます
+function parameters() {
+ $numargs = func_num_args();
+ if ($numargs > 0) {
+ echo func_get_arg(0) . ' | ';
+ }
+ $args_array = func_get_args();
+ foreach ($args_array as $key => $arg) {
+ echo $key . ' - ' . $arg . ' | ';
+ }
+}
+
+parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World |
+
+/********************************
+ * ファイルの読み込み
+ */
+
+<?php
+// 読み込まれたファイル中のPHPは、同じくPHPのオープンタグで始める必要があります
+
+include 'my-file.php';
+// my-file.php中のコードは、現在のスコープの中で使用可能です
+// もしファイルを読み込めなければ (例:file not found)、警告が発せられます
+
+include_once 'my-file.php';
+// my-file.phpのコードが既にどこかで読み込まれていれば、
+// ファイルを読み込みません。これは、クラスの多重定義のエラーを防ぎます
+
+require 'my-file.php';
+require_once 'my-file.php';
+// include()と同じように、require()はもしファイルを読み込むことができなければ、
+// 致命的エラーの原因となります
+
+// my-include.phpの内容
+<?php
+
+return 'Anything you like.';
+// End file
+
+// include()とrequire()は一つの値を返します
+$value = include 'my-include.php';
+
+// ファイルは与えられたファイルパスを基に読み込まれます。
+// ファイルパスを指定しない場合は、include_path の設定を利用します。
+// もしファイルがinclude_path中に見つからない場合は、
+// 呼び出し元スクリプトのディレクトリと作業ディレクトリの中も探します。
+// それでも見つからない場合、失敗します。
+/* */
+
+/********************************
+ * クラス
+ */
+
+// クラスはclassキーワードで定義します
+
+class MyClass
+{
+ const MY_CONST = 'value'; // クラス定数です
+
+ static $staticVar = 'static';
+
+ // スタティック変数とアクセス制限
+ public static $publicStaticVar = 'publicStatic';
+ // クラス内でのみアクセス可能
+ private static $privateStaticVar = 'privateStatic';
+ // そのクラスと子クラスで参照可能
+ protected static $protectedStaticVar = 'protectedStatic';
+
+ // プロパティはアクセス制限を宣言する必要があります
+ public $property = 'public';
+ public $instanceProp;
+ protected $prot = 'protected'; // そのクラスと子クラスで参照可能
+ private $priv = 'private'; // クラス内でのみアクセス可能
+
+ // __constructでコンストラクターを生成します
+ public function __construct($instanceProp) {
+ // $thisでインスタンス変数にアクセスします
+ $this->instanceProp = $instanceProp;
+ }
+
+ // メソッドはクラス内で関数として定義されます
+ public function myMethod()
+ {
+ print 'MyClass';
+ }
+
+ // finalキーワードは関数の上書きを禁止します
+ final function youCannotOverrideMe()
+ {
+ }
+
+/*
+ * クラスプロパティまたはメソッドをstaticとして作成すれば、
+ * クラスをインスタンス化(newすること)しなくてもアクセスできます。
+ * プロパティをstaticとして定義すると、
+ * インスタンス化されたクラスオブジェクトを通してのアクセスはできなくなります。
+ */
+
+ public static function myStaticMethod()
+ {
+ print 'I am static';
+ }
+}
+
+// クラス定数は、いつでも静的にアクセスできます。
+echo MyClass::MY_CONST; // Outputs 'value';
+
+echo MyClass::$staticVar; // Outputs 'static';
+MyClass::myStaticMethod(); // Outputs 'I am static';
+
+// クラスをインスタンス化するには、newを使います。
+$my_class = new MyClass('An instance property');
+// 括弧はもし引数を渡す必要がなければ省略可能です。
+
+// ->を使ってクラスのメンバにアクセスします。
+echo $my_class->property; // => "public"
+echo $my_class->instanceProp; // => "An instance property"
+$my_class->myMethod(); // => "MyClass"
+
+
+// extendsを使用してクラスを継承します。
+class MyOtherClass extends MyClass
+{
+ function printProtectedProperty()
+ {
+ echo $this->prot;
+ }
+
+ // メソッドを上書きします。
+ function myMethod()
+ {
+ parent::myMethod();
+ print ' > MyOtherClass';
+ }
+}
+
+$my_other_class = new MyOtherClass('Instance prop');
+$my_other_class->printProtectedProperty(); // => Prints "protected"
+$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass"
+
+final class YouCannotExtendMe
+{
+}
+
+// 「マジックメソッド」を使ってゲッターとセッターを生成できます。
+class MyMapClass
+{
+ private $property;
+
+ public function __get($key)
+ {
+ return $this->$key;
+ }
+
+ public function __set($key, $value)
+ {
+ $this->$key = $value;
+ }
+}
+
+$x = new MyMapClass();
+echo $x->property; // __get() メソッドを使用します
+$x->property = 'Something'; // __set() メソッドを使用します
+
+// クラスは抽象クラスにもできます(abstractキーワードを使用します)し、
+// インターフェースを実装することもできます(implementsキーワードを使用します)。
+// インターフェースはinterfaceキーワードで定義します。
+
+interface InterfaceOne
+{
+ public function doSomething();
+}
+
+interface InterfaceTwo
+{
+ public function doSomethingElse();
+}
+
+// インターフェースは継承することができます
+interface InterfaceThree extends InterfaceTwo
+{
+ public function doAnotherContract();
+}
+
+abstract class MyAbstractClass implements InterfaceOne
+{
+ public $x = 'doSomething';
+}
+
+class MyConcreteClass extends MyAbstractClass implements InterfaceTwo
+{
+ public function doSomething()
+ {
+ echo $x;
+ }
+
+ public function doSomethingElse()
+ {
+ echo 'doSomethingElse';
+ }
+}
+
+
+// クラスは1つ以上のインターフェースを実装できます。
+class SomeOtherClass implements InterfaceOne, InterfaceTwo
+{
+ public function doSomething()
+ {
+ echo 'doSomething';
+ }
+
+ public function doSomethingElse()
+ {
+ echo 'doSomethingElse';
+ }
+}
+
+
+/********************************
+ * トレイト
+ */
+
+// トレイトはPHP 5.4.0 以上で使用可能で、traitキーワードで定義します。
+
+trait MyTrait
+{
+ public function myTraitMethod()
+ {
+ print 'I have MyTrait';
+ }
+}
+
+class MyTraitfulClass
+{
+ use MyTrait;
+}
+
+$cls = new MyTraitfulClass();
+$cls->myTraitMethod(); // Prints "I have MyTrait"
+
+
+/********************************
+ * 名前空間
+ */
+
+// このセクションは名前空間の定義はファイルの先頭で宣言される必要があるため、
+// 独立しています。
+// そのケースには当てはまらないふりをして続けましょう。
+
+<?php
+
+// デフォルトでは、クラスはグローバルな名前空間に存在し、
+// バックスラッシュによって明確にコールできます。
+
+$cls = new \MyClass();
+
+
+
+// ファイルに名前空間をセットします
+namespace My\Namespace;
+
+class MyClass
+{
+}
+
+// (別のファイルからの呼び出し)
+$cls = new My\Namespace\MyClass;
+
+// 異なる名前空間からの呼び出し
+namespace My\Other\Namespace;
+
+use My\Namespace\MyClass;
+
+$cls = new MyClass();
+
+// 名前空間に別名をつけることもできます
+
+namespace My\Other\Namespace;
+
+use My\Namespace as SomeOtherNamespace;
+
+$cls = new SomeOtherNamespace\MyClass();
+
+/**********************
+* エラーハンドリング
+*
+*/
+
+// シンプルなエラーハンドリングは、try catchを使えば行えます
+
+try {
+ // 処理を実行します
+} catch ( Exception $e) {
+ // 例外を処理します
+}
+
+// try catchを名前空間を持った環境で使用するときは、次のようにします。
+
+try {
+ // Do something
+ // 処理を実行します
+} catch (\Exception $e) {
+ // 例外を処理します
+}
+
+// 例外のカスタマイズ
+
+class MyException extends Exception {}
+
+try {
+
+ $condition = true;
+
+ if ($condition) {
+ throw new MyException('Something just happend');
+ }
+
+} catch (MyException $e) {
+ // Handle my exception
+}
+
+```
+
+## より詳しい情報
+
+リファレンスを見るため、またコミュニティへの情報提供のために、 [PHP公式ドキュメント](http://www.php.net/manual/) を訪れてみてください。
+
+もし最新のベストプラクティスに興味があるなら、
+[PHP The Right Way](http://www.phptherightway.com/)を訪れてみてください。
+
+
+もしあなたがよいパッケージマネジメント・システムを持つ言語で開発経験があるのなら、
+[Composer](http://getcomposer.org/)も確かめてみてください。
+
+
+共通基準を知るためには、PHP Framework Interoperability Groupの
+[PSR standards](https://github.com/php-fig/fig-standards)にも訪れてみてください。
diff --git a/java.html.markdown b/java.html.markdown
index 84978ecc..48e6ec75 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -17,9 +17,11 @@ programming language.
```java
// Single-line comments start with //
+
/*
Multi-line comments look like this.
*/
+
/**
JavaDoc comments look like this. Used to describe the Class or various
attributes of a Class.
@@ -30,11 +32,12 @@ import java.util.ArrayList;
// Import all classes inside of java.security package
import java.security.*;
-// Each .java file contains one outer-level public class, with the same name as
-// the file.
+// Each .java file contains one outer-level public class, with the same name
+// as the file.
public class LearnJava {
- // In order to run a java program, it must have a main method as an entry point.
+ // In order to run a java program, it must have a main method as an entry
+ // point.
public static void main (String[] args) {
// Use System.out.println() to print lines.
@@ -60,7 +63,8 @@ public class LearnJava {
*/
// Declare a variable using <type> <name>
int fooInt;
- // Declare multiple variables of the same type <type> <name1>, <name2>, <name3>
+ // Declare multiple variables of the same
+ // type <type> <name1>, <name2>, <name3>
int fooInt1, fooInt2, fooInt3;
/*
@@ -69,7 +73,8 @@ public class LearnJava {
// Initialize a variable using <type> <name> = <val>
int fooInt = 1;
- // Initialize multiple variables of same type with same value <type> <name1>, <name2>, <name3> = <val>
+ // Initialize multiple variables of same type with same
+ // value <type> <name1>, <name2>, <name3> = <val>
int fooInt1, fooInt2, fooInt3;
fooInt1 = fooInt2 = fooInt3 = 1;
@@ -119,18 +124,15 @@ public class LearnJava {
final double E;
E = 2.71828;
-
// BigInteger - Immutable arbitrary-precision integers
//
// BigInteger is a data type that allows programmers to manipulate
// integers longer than 64-bits. Integers are stored as an array of
// of bytes and are manipulated using functions built into BigInteger
//
- // BigInteger can be initialized using an array of bytes or a string.
-
+ // BigInteger can be initialized using an array of bytes or a string.
BigInteger fooBigInteger = new BigInteger(fooByteArray);
-
// BigDecimal - Immutable, arbitrary-precision signed decimal number
//
// A BigDecimal takes two parts: an arbitrary precision integer
@@ -142,16 +144,13 @@ public class LearnJava {
//
// BigDecimal can be initialized with an int, long, double or String
// or by initializing the unscaled value (BigInteger) and scale (int).
-
BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt);
// Be wary of the constructor that takes a float or double as
// the inaccuracy of the float/double will be copied in BigDecimal.
// Prefer the String constructor when you need an exact value.
-
BigDecimal tenCents = new BigDecimal("0.1");
-
// Strings
String fooString = "My String Is Here!";
@@ -175,7 +174,7 @@ public class LearnJava {
// Another way to declare & initialize an array
int[] y = {9000, 1000, 1337};
String names[] = {"Bob", "John", "Fred", "Juan Pedro"};
- boolean bools[] = new boolean[] {true, false, false};
+ boolean bools[] = {true, false, false};
// Indexing an array - Accessing an element
System.out.println("intArray @ 0: " + intArray[0]);
@@ -184,7 +183,7 @@ public class LearnJava {
intArray[1] = 1;
System.out.println("intArray @ 1: " + intArray[1]); // => 1
- // Others to check out
+ // Other data types worth checking out
// ArrayLists - Like arrays except more functionality is offered, and
// the size is mutable.
// LinkedLists - Implementation of doubly-linked list. All of the
@@ -212,7 +211,7 @@ public class LearnJava {
System.out.println("1+2 = " + (i1 + i2)); // => 3
System.out.println("2-1 = " + (i2 - i1)); // => 1
System.out.println("2*1 = " + (i2 * i1)); // => 2
- System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns an int)
+ System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns int)
System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5
// Modulo
@@ -242,7 +241,7 @@ public class LearnJava {
| Bitwise inclusive OR
*/
- // Incrementations
+ // Increment operators
int i = 0;
System.out.println("\n->Inc/Dec-rementation");
// The ++ and -- operators increment and decrement by 1 respectively.
@@ -314,7 +313,6 @@ public class LearnJava {
// for each loop structure => for (<object> : <iterable>)
// reads as: for each element in the iterable
// note: the object type must match the element type of the iterable.
-
for (int bar : fooList) {
System.out.println(bar);
//Iterates 9 times and prints 1-9 on new lines
@@ -364,7 +362,6 @@ public class LearnJava {
String bar = (foo < 10) ? "A" : "B";
System.out.println(bar); // Prints A, because the statement is true
-
////////////////////////////////////////
// Converting Data Types And Typecasting
////////////////////////////////////////
@@ -387,7 +384,6 @@ public class LearnJava {
// with some more intermediate concepts. Feel free to check it out here:
// http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
-
///////////////////////////////////////
// Classes And Functions
///////////////////////////////////////
@@ -409,7 +405,6 @@ public class LearnJava {
// Double Brace Initialization
// The Java Language has no syntax for how to create static Collections
// in an easy way. Usually you end up in the following way:
-
private static final Set<String> COUNTRIES = new HashSet<String>();
static {
validCodes.add("DENMARK");
@@ -420,7 +415,6 @@ public class LearnJava {
// But there's a nifty way to achieve the same thing in an
// easier way, by using something that is called Double Brace
// Initialization.
-
private static final Set<String> COUNTRIES = new HashSet<String>() {{
add("DENMARK");
add("SWEDEN");
@@ -436,10 +430,8 @@ public class LearnJava {
} // End main method
} // End LearnJava class
-
// You can include other, non-public outer-level classes in a .java file,
-// but it is good practice. Instead split classes into separate files.
-
+// but it is not good practice. Instead split classes into separate files.
// Class Declaration Syntax:
// <public/private/protected> class <class name> {
@@ -454,7 +446,6 @@ class Bicycle {
private int speed; // Private: Only accessible from within the class
protected int gear; // Protected: Accessible from the class and subclasses
String name; // default: Only accessible from within this package
-
static String className; // Static class variable
// Static block
@@ -476,7 +467,6 @@ class Bicycle {
speed = 5;
name = "Bontrager";
}
-
// This is a constructor that takes arguments
public Bicycle(int startCadence, int startSpeed, int startGear,
String name) {
@@ -501,23 +491,18 @@ class Bicycle {
public void setCadence(int newValue) {
cadence = newValue;
}
-
public void setGear(int newValue) {
gear = newValue;
}
-
public void speedUp(int increment) {
speed += increment;
}
-
public void slowDown(int decrement) {
speed -= decrement;
}
-
public void setName(String newName) {
name = newName;
}
-
public String getName() {
return name;
}
@@ -535,7 +520,7 @@ class PennyFarthing extends Bicycle {
// (Penny Farthings are those bicycles with the big front wheel.
// They have no gears.)
- public PennyFarthing(int startCadence, int startSpeed){
+ public PennyFarthing(int startCadence, int startSpeed) {
// Call the parent constructor with super
super(startCadence, startSpeed, 0, "PennyFarthing");
}
@@ -566,10 +551,8 @@ public interface Digestible {
public void digest();
}
-
// We can now create a class that implements both of these interfaces.
-public class Fruit implements Edible, Digestible {
-
+public class Fruit implements Edible, Digestible {
@Override
public void eat() {
// ...
@@ -585,7 +568,6 @@ public class Fruit implements Edible, Digestible {
// interfaces. For example:
public class ExampleClass extends ExampleClassParent implements InterfaceOne,
InterfaceTwo {
-
@Override
public void InterfaceOneMethod() {
}
@@ -604,14 +586,13 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
// // Method declarations
// }
-// Marking a class as abstract means that it contains abstract methods that must
-// be defined in a child class. Similar to interfaces, abstract classes cannot
-// be instantiated, but instead must be extended and the abstract methods
-// defined. Different from interfaces, abstract classes can contain a mixture of
+// Marking a class as abstract means that it contains abstract methods that
+// must be defined in a child class. Similar to interfaces, abstract classes
+// cannot be instantiated, but instead must be extended and the abstract
+// methods defined. Different from interfaces, abstract classes can contain a
// concrete and abstract methods. Methods in an interface cannot have a body,
-// unless the method is static, and variables are final by default, unlike an
-// abstract class. Also abstract classes CAN have the "main" method.
-
+// mixture of unless the method is static, and variables are final by default,
+// unlike an abstract class. Also abstract classes CAN have the "main" method.
public abstract class Animal
{
public abstract void makeSound();
@@ -656,7 +637,7 @@ class Dog extends Animal
// @Override annotation here, since java doesn't allow
// overriding of static methods.
// What is happening here is called METHOD HIDING.
- // Check out this awesome SO post: http://stackoverflow.com/questions/16313649/
+ // Check out this SO post: http://stackoverflow.com/questions/16313649/
public static void main(String[] args)
{
Dog pluto = new Dog();
@@ -695,33 +676,29 @@ public abstract class Mammal()
// Final Method Syntax:
// <access modifier> final <return type> <function name>(<args>)
- // Final methods, like, final classes cannot be overridden by a child class,
- // and are therefore the final implementation of the method.
+ // Final methods, like, final classes cannot be overridden by a child
+ // class, and are therefore the final implementation of the method.
public final boolean isWarmBlooded()
{
return true;
}
}
-
// Enum Type
//
// An enum type is a special data type that enables for a variable to be a set
-// of predefined constants. The variable must be equal to one of the values that
-// have been predefined for it. Because they are constants, the names of an enum
-// type's fields are in uppercase letters. In the Java programming language, you
-// define an enum type by using the enum keyword. For example, you would specify
-// a days-of-the-week enum type as:
-
+// of predefined constants. The variable must be equal to one of the values
+// that have been predefined for it. Because they are constants, the names of
+// an enum type's fields are in uppercase letters. In the Java programming
+// language, you define an enum type by using the enum keyword. For example,
+// you would specify a days-of-the-week enum type as:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
// We can use our enum Day like that:
-
public class EnumTest {
-
// Variable Enum
Day day;
@@ -734,16 +711,13 @@ public class EnumTest {
case MONDAY:
System.out.println("Mondays are bad.");
break;
-
case FRIDAY:
System.out.println("Fridays are better.");
- break;
-
+ break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
- break;
-
+ break;
default:
System.out.println("Midweek days are so-so.");
break;
@@ -793,7 +767,6 @@ The links provided here below are just to get an understanding of the topic, fee
* [Codingbat.com](http://codingbat.com/java)
-
**Books**:
* [Head First Java](http://www.headfirstlabs.com/books/hfjava/)
@@ -802,4 +775,4 @@ The links provided here below are just to get an understanding of the topic, fee
* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660)
-* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300)
+* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) \ No newline at end of file
diff --git a/julia.html.markdown b/julia.html.markdown
index ef3ea244..23d834f4 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -9,7 +9,7 @@ filename: learnjulia.jl
Julia is a new homoiconic functional language focused on technical computing.
While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python.
-This is based on Julia 0.3.
+This is based on Julia 0.4.
```ruby
@@ -23,7 +23,7 @@ This is based on Julia 0.3.
## 1. Primitive Datatypes and Operators
####################################################
-# Everything in Julia is a expression.
+# Everything in Julia is an expression.
# There are several basic types of numbers.
3 # => 3 (Int64)
@@ -151,12 +151,16 @@ a = Int64[] # => 0-element Int64 Array
# 1-dimensional array literals can be written with comma-separated values.
b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6]
+b = [4; 5; 6] # => 3-element Int64 Array: [4, 5, 6]
b[1] # => 4
b[end] # => 6
-# 2-dimentional arrays use space-separated values and semicolon-separated rows.
+# 2-dimensional arrays use space-separated values and semicolon-separated rows.
matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4]
+# Arrays of a particular Type
+b = Int8[4, 5, 6] # => 3-element Int8 Array: [4, 5, 6]
+
# Add stuff to the end of a list with push! and append!
push!(a,1) # => [1]
push!(a,2) # => [1,2]
@@ -268,8 +272,8 @@ values(filled_dict)
# Note - Same as above regarding key ordering.
# Check for existence of keys in a dictionary with in, haskey
-in(("one", 1), filled_dict) # => true
-in(("two", 3), filled_dict) # => false
+in(("one" => 1), filled_dict) # => true
+in(("two" => 3), filled_dict) # => false
haskey(filled_dict, "one") # => true
haskey(filled_dict, 1) # => false
@@ -288,7 +292,7 @@ get(filled_dict,"four",4) # => 4
# Use Sets to represent collections of unordered, unique values
empty_set = Set() # => Set{Any}()
# Initialize a set with values
-filled_set = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4)
+filled_set = Set([1,2,2,3,4]) # => Set{Int64}(1,2,3,4)
# Add more values to a set
push!(filled_set,5) # => Set{Int64}(5,4,2,3,1)
@@ -298,7 +302,7 @@ in(2, filled_set) # => true
in(10, filled_set) # => false
# There are functions for set intersection, union, and difference.
-other_set = Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3)
+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)
@@ -416,14 +420,12 @@ varargs(1,2,3) # => (1,2,3)
# The ... is called a splat.
# We just used it in a function definition.
-# It can also be used in a fuction call,
+# It can also be used in a function call,
# where it will splat an Array or Tuple's contents into the argument list.
-Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # produces a Set of Arrays
-Set([1,2,3]...) # => Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3)
+add([5,6]...) # this is equivalent to add(5,6)
-x = (1,2,3) # => (1,2,3)
-Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # a Set of Tuples
-Set(x...) # => Set{Int64}(2,3,1)
+x = (5,6) # => (5,6)
+add(x...) # this is equivalent to add(5,6)
# You can define functions with optional positional arguments
@@ -545,12 +547,8 @@ abstract Cat # just a name and point in the type hierarchy
# Abstract types cannot be instantiated, but can have subtypes.
# For example, Number is an abstract type
-subtypes(Number) # => 6-element Array{Any,1}:
- # Complex{Float16}
- # Complex{Float32}
- # Complex{Float64}
+subtypes(Number) # => 2-element Array{Any,1}:
# Complex{T<:Real}
- # ImaginaryUnit
# Real
subtypes(Cat) # => 0-element Array{Any,1}
@@ -568,10 +566,11 @@ subtypes(AbstractString) # 8-element Array{Any,1}:
# Every type has a super type; use the `super` function to get it.
typeof(5) # => Int64
super(Int64) # => Signed
-super(Signed) # => Real
+super(Signed) # => Integer
+super(Integer) # => Real
super(Real) # => Number
super(Number) # => Any
-super(super(Signed)) # => Number
+super(super(Signed)) # => Real
super(Any) # => Any
# All of these type, except for Int64, are abstract.
typeof("fire") # => ASCIIString
diff --git a/ko-kr/brainfuck-kr.html.markdown b/ko-kr/bf-kr.html.markdown
index c2e4341f..3d366d7c 100644
--- a/ko-kr/brainfuck-kr.html.markdown
+++ b/ko-kr/bf-kr.html.markdown
@@ -1,5 +1,5 @@
---
-language: brainfuck
+language: bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]
diff --git a/ko-kr/erlang-kr.html.markdown b/ko-kr/erlang-kr.html.markdown
new file mode 100644
index 00000000..b0b1dd2a
--- /dev/null
+++ b/ko-kr/erlang-kr.html.markdown
@@ -0,0 +1,333 @@
+---
+language: erlang
+contributors:
+ - ["Giovanni Cappellotto", "http://www.focustheweb.com/"]
+filename: learnerlang-kr.erl
+translators:
+ - ["Taesung Jung", "https://github.com/tsj"]
+lang: ko-kr
+---
+
+```erlang
+% 퍼센트 기호는 한 줄 주석을 시작한다.
+
+%% 두 개의 퍼센트 문자는 함수의 주석에 사용된다.
+
+%%% 세 개의 퍼센트 문자는 모듈의 주석에 사용된다.
+
+% Erlang에선 3가지 유형의 문장 부호를 사용한다.
+% 쉼표(`,`)는 함수 호출에서 인수, 데이터 생성자(constructors), 패턴을 구분한다.
+% 마침표(`.`)(다음에 오는 공백)는 셸에서 함수 전체와 식을 구분한다.
+% 세미콜론(`;`)은 절을 구분한다. 몇 가지 문맥(contexts)에서 절이 발견된다:
+% 함수 정의와 `case`, `if`, `try..catch`, 그리고 `receive` 식
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% 1. 변수와 패턴 매칭
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Erlang에서 새로운 변수는 `=` 문장에 의해 바인딩 된다.
+Num = 42. % 모든 변수 이름은 반드시 대문자로 시작해야 한다.
+
+% Erlang은 단일 할당 변수(single-assignment variables)를 가진다;
+% 만약 다른 값을 `Num` 변수에 할당하려고 시도하면 오류가 발생한다.
+Num = 43. % ** 예외 오류: 우변의 값 43과 매칭되지 않음
+
+% 대부분 언어에서 `=`는 할당문을 나타낸다. 그러나 Erlang에서
+% `=`는 패턴 매칭 연산자를 나타낸다. 비어 있는 변수가 `=` 연산자의 좌변에
+% 사용되면 바인드(할당) 된다, 그러나 바인드 변수가 좌변에 사용된 경우에
+% 다음 행동은 그 바인드 변수가 관측된다.
+% `Lhs = Rhs`의 진짜 의미: 우변(`Rhs`)을 평가하고, 그리고
+% 그 결과를 좌변(`Lhs`)의 패턴과 매치시켜라.
+Num = 7 * 6.
+
+% 부동 소수점 수.
+Pi = 3.14159.
+
+% Atom은 숫자가 아닌 서로 다른 상숫값을 표현하는 데 사용한다. Atom은
+% 소문자로 시작하고, 연속적인 영숫자(alphanumeric) 문자나 밑줄(`_`) 또는
+% 골뱅이(`@`) 기호가 따라온다.
+Hello = hello.
+OtherNode = example@node.
+
+% 영숫자 값이 아닌 Atom은 작은따옴표로 묶여서 작성될 수 있다.
+AtomWithSpace = 'some atom with space'.
+
+% Tuple은 C의 struct와 비슷하다.
+Point = {point, 10, 45}.
+
+% Tuple에서 어떤 값을 추출하려면, 패턴 매칭 연산자 `=`를 사용한다.
+{point, X, Y} = Point. % X = 10, Y = 45
+
+% 관심 없는 변수를 위해 자리 표시자(placeholder) `_`를 사용할 수 있다.
+% 기호 `_`는 익명 변수(anonymous variable)라 부른다. 일반적인 변수들과
+% 다르게 같은 패턴에서 여러 번 나오더라도 동일한 값으로 바인드되지 않아도 된다.
+Person = {person, {name, {first, joe}, {last, armstrong}}, {footsize, 42}}.
+{_, {_, {_, Who}, _}, _} = Person. % Who = joe
+
+% List를 만들기 위해서 List의 원소는 대괄호([])로 둘러싸고 쉼표(,)로 구분한다.
+% List의 각각의 원소는 어떤 타입도 가능하다.
+% List의 첫 번째 원소는 List의 HEAD이다. 만약 List의 HEAD를 제거하면,
+% 남은 부분은 List의 TAIL이라 부른다.
+ThingsToBuy = [{apples, 10}, {pears, 6}, {milk, 3}].
+
+% 만약 `T`가 List이면, `[H|T]`도 HEAD가 `H`이고 TAIL이 `T`인 List이다.
+% 세로 막대(`|`)는 List의 HEAD와 TAIL을 분리한다. `[]`는 빈 List다.
+% List의 원소들은 패턴 매칭 연산으로 추출할 수 있다.
+% 만약 비어있지 않은 List `L`이 있을 때, `[X|Y] = L` 식의 `X`와 `Y`가
+% 바인드되지 않은 변수이면, List의 HEAD는 X에 그리고 TAIL은 Y로 추출된다.
+[FirstThing|OtherThingsToBuy] = ThingsToBuy.
+% FirstThing = {apples, 10}
+% OtherThingsToBuy = [{pears, 6}, {milk, 3}]
+
+% Erlang에는 문자열(String)이 없다. 문자열은 사실 정수의 List일 뿐이다.
+% 문자열은 큰따옴표(`"`)로 묶인다.
+Name = "Hello".
+[72, 101, 108, 108, 111] = "Hello".
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% 2. 순차 프로그래밍
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Erlang에서 Module은 코드의 기본 단위이다. 우리가 작성한 모든 함수는
+% Module에 담긴다. Module은 확장자가 `.erl`인 파일에 저장된다.
+% 코드가 실행되기 전에 Module은 컴파일되어야 한다. 컴파일된 Module은
+% `.beam` 확장자를 가진다.
+-module(geometry).
+-export([area/1]). % Module로부터 내보내진(exported) 함수의 List
+
+% 함수 `area`는 두 개의 절로 구성된다. 절은 세미콜론(`;`)으로 구분되며,
+% 마지막 절은 마침표-공백(dot-whitespace)으로 끝난다.
+% 각 절은 서문(head)과 본문(body)을 가진다. 서문은 함수의 이름에 이어서
+% 패턴이(괄호 속에) 따라온다. 본문은 연속적인 식으로 구성되고,
+% 연속적인 식은 서문의 패턴과 호출한 인수가 성공적으로 매치되면 평가된다.
+% 패턴은 함수 정의가 나타나는 순서대로 매치된다.
+area({rectangle, Width, Ht}) -> Width * Ht;
+area({circle, R}) -> 3.14159 * R * R.
+
+% geometry.erl 파일의 코드 컴파일
+c(geometry). % {ok,geometry}
+
+% 호출하려는 함수를 정확히 알아내기 위해 함수 이름을 Module 이름과 함께
+% 명시하는 것이 필요하다.
+geometry:area({rectangle, 10, 5}). % 50
+geometry:area({circle, 1.4}). % 6.15752
+
+% Erlang에서, 같은 Module에 이름이 같고 Arity(인수의 갯수)가 다른
+% 두 함수는 전혀 다른 함수를 나타낸다.
+-module(lib_misc).
+-export([sum/1]). % Arity가 1인 내보내진(export) 함수 `sum`
+ % 하나의 인수만 받음: 정수의 List
+sum(L) -> sum(L, 0).
+sum([], N) -> N;
+sum([H|T], N) -> sum(T, H+N).
+
+% Fun은 "익명(anonymous)" 함수다. 이름이 없어서 이렇게 부른다.
+% 그러나, 변수에 할당될 수 있다.
+Double = fun(X) -> 2 * X end. % `Double`은 익명 함수를 가리킨다:
+ % #Fun<erl_eval.6.17052888>
+Double(2). % 4
+
+% 함수는 인수로 Fun을 받거나, Fun을 반환할 수 있다.
+Mult = fun(Times) -> ( fun(X) -> X * Times end ) end.
+Triple = Mult(3).
+Triple(5). % 15
+
+% List 해석(List comprehensions)은 Fun, Map, Filter 없이 List를 만드는 식이다.
+% 표기법 `[F(X) || X <- L]`은 `F(X)`의 List라는 의미이다.
+% 이때 `X`는 List `L`로부터 가져온다.
+L = [1,2,3,4,5].
+[2 * X || X <- L]. % [2,4,6,8,10]
+% List 해석은 Generator와 생성된 값들의 부분 집합을 선택하는 Filter를 가질 수 있다.
+EvenNumbers = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4]
+
+% Guard는 패턴 매칭의 능력을 향상시키는데 사용할 수 있는 구조다.
+% Guard를 사용하면, 패턴에 있는 변수에 대해 간단한 검사와 비교를 수행할 수 있다.
+% 함수 정의의 서문(head)에 `when` 키워드로 시작되는 Guard를 사용할 수도 있고,
+% 또는 식이 허용되는 언어의 어떤 곳에도 사용될 수 있다.
+max(X, Y) when X > Y -> X;
+max(X, Y) -> Y.
+
+% Guard는 쉼표(`,`)로 구분된 연속된 Guard 식이다.
+% 모든 Guard 식 `GuardExpr1`, `GuardExpr2`, ..., `GuardExprN`이
+% `true`로 평가된다면, Guard `GuardExpr1`, `GuardExpr2`, ..., `GuardExprN`는
+% 참이다.
+is_cat(A) when is_atom(A), A =:= cat -> true;
+is_cat(A) -> false.
+is_dog(A) when is_atom(A), A =:= dog -> true;
+is_dog(A) -> false.
+
+% `=:=` 연산자는 여기서 자세히 다루지 않을 것이다; 두 개의 Erlang 식의 값이 같고
+% *그리고* 같은 타입인지 검사하는 데 사용된다고만 알면 된다.
+% `==` 연산자의 작동과 대조할 것:
+1 + 2 =:= 3. % true
+1 + 2 =:= 3.0. % false
+1 + 2 == 3.0. % true
+
+% 연속적인 Guard는 단일 Guard 또는 세미콜론(`;`)으로 구분된 연속된 Guard다.
+% Guard `G1; G2; ...; Gn` 중에 적어도 하나의 Guard가 `true`로 평가된다면,
+% 연속적인 Guard `G1; G2; ...; Gn`는 참이다.
+is_pet(A) when is_atom(A), (A =:= dog);(A =:= cat) -> true;
+is_pet(A) -> false.
+
+% 주의: 모든 유효한 Erlang 식이 Guard 식으로 사용될 수 있는 것은 아니다;
+% 특히, 함수 `is_cat`과 `is_dog`는 `is_pet`의 정의 안에 있는
+% 연속적인 Guard 사이에 사용될 수 없다.
+% 연속적인 Guard에 허용되는 식의 자세한 설명은 Erlang 레퍼런스 메뉴얼
+% [section](http://erlang.org/doc/reference_manual/expressions.html#id81912)
+% 을 참조하라.
+
+% Record는 Tuple 안에 이름과 특정 요소를 연결하는 방법을 제공한다.
+% Record 정의는 Erlang 소스 코드 파일에 포함되거나 Erlang 소스 코드 파일에
+% 포함될 수 있는 확장자가 `.hrl`인 파일에 집어넣을 수 있다.
+-record(todo, {
+ status = reminder, % 기본 값
+ who = joe,
+ text
+}).
+
+% Record를 사용할 수 있기 전에 Record 정의를 반드시 셸로 읽어 들여야 한다.
+% 셸로 읽어 들이기 위해 셸 함수 `rr`(read records의 약자)을 사용한다.
+rr("records.hrl"). % [todo]
+
+% Record 생성과 수정
+X = #todo{}.
+% #todo{status = reminder, who = joe, text = undefined}
+X1 = #todo{status = urgent, text = "Fix errata in book"}.
+% #todo{status = urgent, who = joe, text = "Fix errata in book"}
+X2 = X1#todo{status = done}.
+% #todo{status = done, who = joe, text = "Fix errata in book"}
+
+% `case` 식
+% `filter`는 List `L`의 원소 `X` 중에서 `P(X)`가 참인 모든 `X`의 List를 반환한다.
+filter(P, [H|T]) ->
+ case P(H) of
+ true -> [H|filter(P, T)];
+ false -> filter(P, T)
+ end;
+filter(P, []) -> [].
+filter(fun(X) -> X rem 2 == 0 end, [1, 2, 3, 4]). % [2, 4]
+
+% `if` 식.
+max(X, Y) ->
+ if
+ X > Y -> X;
+ X < Y -> Y;
+ true -> nil
+ end.
+
+% 주의: 적어도 if 식의 Guard 중의 하나는 반드시 `true`로 평가되어야 한다.
+% 그렇지 않으면 예외가 발생한다.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% 3. 예외
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% 예외는 내부에 에러가 생겼거나 명시적으로 `throw(Exception)`,
+% `exit(Exception)` 또는 `erlang:error(Exception)`를 호출하면
+% 시스템에 의해 발생한다.
+generate_exception(1) -> a;
+generate_exception(2) -> throw(a);
+generate_exception(3) -> exit(a);
+generate_exception(4) -> {'EXIT', a};
+generate_exception(5) -> erlang:error(a).
+
+% Erlang은 예외를 잡는 두 가지 방법을 가지고 있다. 한 가지는
+% 예외를 발생시키는 함수의 호출 부분을 `try...catch` 식으로 감싸는 것이다.
+catcher(N) ->
+ try generate_exception(N) of
+ Val -> {N, normal, Val}
+ catch
+ throw:X -> {N, caught, thrown, X};
+ exit:X -> {N, caught, exited, X};
+ error:X -> {N, caught, error, X}
+ end.
+
+% 다른 방법은 그 호출 부분을 `catch` 식으로 감싸는 것이다.
+% 예외를 잡았을 때, 그 예외는 오류를 설명하는 Tuple로 변환된다.
+catcher(N) -> catch generate_exception(N).
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% 4. 병행성
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Erlang은 병행성을 위해 Actor 모델을 사용한다. Erlang에서 병행 프로그램을
+% 작성하는 데 필요한 모든 것은 3가지 기본 형식(primitivies)이다:
+% 프로세스 생성, 메시지 보내기, 메시지 받기
+
+% 새로운 프로세스를 시작하기 위해, 함수를 인수로 받는 `spawn` 함수를 사용한다.
+
+F = fun() -> 2 + 2 end. % #Fun<erl_eval.20.67289768>
+spawn(F). % <0.44.0>
+
+% `spawn`은 pid(프로세스 식별자)를 반환한다. 이 pid를 프로세스로
+% 메시지를 보내는 데 사용할 수 있다. 메시지 전달을 위해, `!` 연산자를 사용한다.
+% 위의 기능이 유용하려면, 메시지를 받을 수 있어야 한다. 메시지를 받는 것은
+% `receive` 메커니즘을 사용한다.
+
+-module(calculateGeometry).
+-compile(export_all).
+calculateArea() ->
+ receive
+ {rectangle, W, H} ->
+ W * H;
+ {circle, R} ->
+ 3.14 * R * R;
+ _ ->
+ io:format("We can only calculate area of rectangles or circles.")
+ end.
+
+% Module을 컴파일하고 셸에서 `calculateArea`를 평가한 프로세스를 생성한다.
+c(calculateGeometry).
+CalculateArea = spawn(calculateGeometry, calculateArea, []).
+CalculateArea ! {circle, 2}. % 12.56000000000000049738
+
+% 셸도 마찬가지로 프로세스이다. 현재 pid를 얻기 위해서 `self`를 사용할 수 있다.
+self(). % <0.41.0>
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% 5. EUnit과 테스트
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% EUnit의 테스트 생성기(generators)와 assert 매크로를 이용해
+% 단위 테스트를 작성할 수 있다.
+-module(fib).
+-export([fib/1]).
+-include_lib("eunit/include/eunit.hrl").
+
+fib(0) -> 1;
+fib(1) -> 1;
+fib(N) when N > 1 -> fib(N-1) + fib(N-2).
+
+fib_test_() ->
+ [?_assert(fib(0) =:= 1),
+ ?_assert(fib(1) =:= 1),
+ ?_assert(fib(2) =:= 2),
+ ?_assert(fib(3) =:= 3),
+ ?_assert(fib(4) =:= 5),
+ ?_assert(fib(5) =:= 8),
+ ?_assertException(error, function_clause, fib(-1)),
+ ?_assert(fib(31) =:= 2178309)
+ ].
+
+% EUnit은 Erlang 셸에서 테스트를 실행할 수 있게
+% 자동으로 test() 함수를 내보낸다(export).
+fib:test()
+
+% Erlang의 유명한 빌드 툴인 Rebar는 EUnit과 호환된다.
+% ```
+% rebar eunit
+% ```
+
+```
+
+## 참조
+
+* ["Learn You Some Erlang for great good!"](http://learnyousomeerlang.com/)
+* ["Programming Erlang: Software for a Concurrent World" by Joe Armstrong](http://pragprog.com/book/jaerlang/programming-erlang)
+* [조 암스트롱, 김석준 역, "프로그래밍 얼랭: Software for a Concurrent World", 인사이트](http://ebook.insightbook.co.kr/book/23)
+* [Erlang/OTP Reference Documentation](http://www.erlang.org/doc/)
+* [Erlang - Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml)
diff --git a/ko-kr/lua-kr.html.markdown b/ko-kr/lua-kr.html.markdown
index b4a018ef..ce3b71cb 100644
--- a/ko-kr/lua-kr.html.markdown
+++ b/ko-kr/lua-kr.html.markdown
@@ -418,5 +418,5 @@ lua-users.org에 있는 <a href="http://lua-users.org/files/wiki_insecure/users/
learn.lua로 저장한 후 "lua learn.lua"를 실행해 보세요!
이 글은 tylerneylon.com에 처음으로 써본 글이며,
-<a href="https://gist.github.com/tylerneylon/5853042">Github의 Gist</a>에서도 확인할 수 있습니다.
+<a href="https://gist.github.com/tylerneylon/5853042">GitHub의 Gist</a>에서도 확인할 수 있습니다.
루아로 즐거운 시간을 보내세요!
diff --git a/kotlin.html.markdown b/kotlin.html.markdown
new file mode 100644
index 00000000..7b1475a8
--- /dev/null
+++ b/kotlin.html.markdown
@@ -0,0 +1,322 @@
+---
+language: kotlin
+contributors:
+ - ["S Webber", "https://github.com/s-webber"]
+filename: LearnKotlin.kt
+---
+
+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
+// Single-line comments start with //
+/*
+Multi-line comments look like this.
+*/
+
+// The "package" keyword works in the same way as in Java.
+package com.learnxinyminutes.kotlin
+
+/*
+The entry point to a Kotlin program is a function named "main".
+The function is passed an array containing any command line arguments.
+*/
+fun main(args: Array<String>) {
+ /*
+ Declaring values is done using either "var" or "val".
+ "val" declarations cannot be reassigned, whereas "vars" can.
+ */
+ val fooVal = 10 // we cannot later reassign fooVal to something else
+ var fooVar = 10
+ fooVar = 20 // fooVar can be reassigned
+
+ /*
+ In most cases, Kotlin can determine what the type of a variable is,
+ so we don't have to explicitly specify it every time.
+ We can explicitly declare the type of a variable like so:
+ */
+ val foo : Int = 7
+
+ /*
+ 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);
+
+ /*
+ A raw string is delimited by a triple quote (""").
+ Raw strings can contain newlines and any other characters.
+ */
+ val fooRawString = """
+fun helloWorld(val name : String) {
+ println("Hello, world!")
+}
+"""
+ println(fooRawString)
+
+ /*
+ Strings can contain template expressions.
+ A template expression starts with a dollar sign ($).
+ */
+ val fooTemplateString = "$fooString has ${fooString.length} characters"
+ println(fooTemplateString)
+
+ /*
+ For a variable to hold null it must be explicitly specified as nullable.
+ A variable can be specified as nullable by appending a ? to its type.
+ We can access a nullable variable by using the ?. operator.
+ We can use the ?: operator to specify an alternative value to use
+ if a variable is null
+ */
+ var fooNullable: String? = "abc"
+ println(fooNullable?.length) // => 3
+ println(fooNullable?.length ?: -1) // => 3
+ fooNullable = null
+ println(fooNullable?.length) // => null
+ println(fooNullable?.length ?: -1) // => -1
+
+ /*
+ Functions can be declared using the "fun" keyword.
+ Function arguments are specified in brackets after the function name.
+ 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 {
+ return "Hello, $name!"
+ }
+ println(hello("foo")) // => Hello, foo!
+ println(hello(name = "bar")) // => Hello, bar!
+ println(hello()) // => Hello, world!
+
+ /*
+ A function parameter may be marked with the "vararg" keyword
+ to allow a variable number of arguments to be passed to the function.
+ */
+ fun varargExample(vararg names: Int) {
+ println("Argument has ${names.size} elements")
+ }
+ varargExample() // => Argument has 0 elements
+ varargExample(1) // => Argument has 1 elements
+ varargExample(1, 2, 3) // => Argument has 3 elements
+
+ /*
+ When a function consists of a single expression then the curly brackets can
+ be omitted. The body is specified after a = symbol.
+ */
+ fun odd(x: Int): Boolean = x % 2 == 1
+ println(odd(6)) // => false
+ println(odd(7)) // => true
+
+ // If the return type can be inferred then we don't need to specify it.
+ fun even(x: Int) = x % 2 == 0
+ println(even(6)) // => true
+ println(even(7)) // => false
+
+ // Functions can take functions as arguments and return functions.
+ 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.
+ val notZero = not {n -> n == 0}
+ /*
+ If an anonymous function has only one parameter
+ then its declaration can be omitted (along with the ->).
+ The name of the single parameter will be "it".
+ */
+ val notPositive = not {it > 0}
+ for (i in 0..4) {
+ println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}")
+ }
+
+ //The "class" keyword is used to declare classes.
+ class ExampleClass(val x: Int) {
+ fun memberFunction(y: Int) : Int {
+ return x + y
+ }
+
+ infix fun infixMemberFunction(y: Int) : Int {
+ return x * y
+ }
+ }
+ /*
+ To create a new instance we call the constructor.
+ Note that Kotlin does not have a "new" keyword.
+ */
+ val fooExampleClass = ExampleClass(7)
+ // Member functions can be called using dot notation.
+ println(fooExampleClass.memberFunction(4)) // => 11
+ /*
+ If a function has been marked with the "infix" keyword then it can be
+ called using infix notation.
+ */
+ println(fooExampleClass infixMemberFunction 4) // => 28
+
+ /*
+ Data classes are a concise way to create classes that just hold data.
+ The "hashCode"/"equals" and "toString" methods are automatically generated.
+ */
+ 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)
+
+ // Data classes have a "copy" function.
+ val fooCopy = fooData.copy(y = 100)
+ println(fooCopy) // => DataClassExample(x=1, y=100, z=4)
+
+ // Objects can be destructured into multiple variables.
+ val (a, b, c) = fooCopy
+ println("$a $b $c") // => 1 100 4
+
+ // The "with" function is similar to the JavaScript "with" statement.
+ 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)
+
+ /*
+ We can create a list using the "listOf" function.
+ The list will be immutable - elements cannot be added or removed.
+ */
+ val fooList = listOf("a", "b", "c")
+ println(fooList.size) // => 3
+ println(fooList.first()) // => a
+ println(fooList.last()) // => c
+ // elements can be accessed by index
+ println(fooList[1]) // => b
+
+ // A mutable list can be created using the "mutableListOf" function.
+ val fooMutableList = mutableListOf("a", "b", "c")
+ fooMutableList.add("d")
+ println(fooMutableList.last()) // => d
+ println(fooMutableList.size) // => 4
+
+ // We can create a set using the "setOf" function.
+ val fooSet = setOf("a", "b", "c")
+ println(fooSet.contains("a")) // => true
+ println(fooSet.contains("z")) // => false
+
+ // We can create a map using the "mapOf" function.
+ val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9)
+ // Map values can be accessed by their key.
+ println(fooMap["a"]) // => 8
+
+ // Kotlin provides higher-order functions for working with collections.
+ val x = (1..9).map {it * 3}
+ .filter {it < 20}
+ .groupBy {it % 2 == 0}
+ .mapKeys {if (it.key) "even" else "odd"}
+ println(x) // => {odd=[3, 9, 15], even=[6, 12, 18]}
+
+ // A "for" loop can be used with anything that provides an iterator.
+ for (c in "hello") {
+ println(c)
+ }
+
+ // "while" loops work in the same way as other languages.
+ var ctr = 0
+ while (ctr < 5) {
+ println(ctr)
+ ctr++
+ }
+ do {
+ println(ctr)
+ ctr++
+ } while (ctr < 10)
+
+ // "when" can be used as an alternative to "if-else if" chains.
+ val i = 10
+ when {
+ i < 7 -> println("first block")
+ fooString.startsWith("hello") -> println("second block")
+ else -> println("else block")
+ }
+
+ // "when" can be used with an argument.
+ 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" can be used as a function that returns a value.
+ 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)
+
+ /*
+ We can check if an object is a particular type by using the "is" operator.
+ If an object passes a type check then it can be used as that type without
+ explicitly casting it.
+ */
+ fun smartCastExample(x: Any) : Boolean {
+ if (x is Boolean) {
+ // x is automatically cast to Boolean
+ return x
+ } else if (x is Int) {
+ // x is automatically cast to Int
+ return x > 0
+ } else if (x is String) {
+ // x is automatically cast to String
+ return x.isNotEmpty()
+ } else {
+ return false
+ }
+ }
+ println(smartCastExample("Hello, world!")) // => true
+ println(smartCastExample("")) // => false
+ println(smartCastExample(5)) // => true
+ println(smartCastExample(0)) // => false
+ println(smartCastExample(true)) // => true
+
+ /*
+ Extensions are a way to add new functionality to a class.
+ This is similar to C# extension methods.
+ */
+ fun String.remove(c: Char): String {
+ return this.filter {it != c}
+ }
+ println("Hello, world!".remove('l')) // => Heo, word!
+
+ println(EnumExample.A) // => A
+ println(ObjectExample.hello()) // => hello
+}
+
+// Enum classes are similar to Java enum types.
+enum class EnumExample {
+ A, B, C
+}
+
+/*
+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.
+This is similar to Scala singleton objects.
+*/
+object ObjectExample {
+ fun hello() : String {
+ return "hello"
+ }
+}
+
+```
+
+### Further Reading
+
+* [Kotlin tutorials](https://kotlinlang.org/docs/tutorials/)
+* [Try Kotlin in your browser](http://try.kotlinlang.org/)
+* [A list of Kotlin resources](http://kotlin.link/)
diff --git a/latex.html.markdown b/latex.html.markdown
index 2492f226..81c0d24c 100644
--- a/latex.html.markdown
+++ b/latex.html.markdown
@@ -178,7 +178,7 @@ We can also insert Tables in the same way as figures.
% the {} arguments below describe how each row of the table is drawn.
% Again, I have to look these up. Each. And. Every. Time.
\begin{tabular}{c|cc}
- Number & Last Name & First Name \\ % Column rows are separated by $
+ Number & Last Name & First Name \\ % Column rows are separated by &
\hline % a horizontal line
1 & Biggus & Dickus \\
2 & Monty & Python
@@ -205,14 +205,14 @@ environment.
By now you're probably wondering how to compile this fabulous document
and look at the glorious glory that is a LaTeX pdf.
-(yes, this document actually does compiles). \\
+(yes, this document actually does compile). \\
Getting to the final document using LaTeX consists of the following steps:
\begin{enumerate}
\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): \\
\begin{verbatim}
- $pdflatex learn-latex.tex learn-latex.pdf
+ > pdflatex learn-latex.tex learn-latex.pdf
\end{verbatim}
\end{enumerate}
diff --git a/less.html.markdown b/less.html.markdown
index 41d66a54..a1018ca3 100644
--- a/less.html.markdown
+++ b/less.html.markdown
@@ -8,7 +8,7 @@ contributors:
Less is a CSS pre-processor, that adds features such as variables, nesting, mixins and more.
Less (and other preprocessors, such as [Sass](http://sass-lang.com/) help developers to write maintainable and DRY (Don't Repeat Yourself) code.
-```less
+```css
//Single line comments are removed when Less is compiled to CSS.
@@ -89,7 +89,7 @@ div {
background-color: #A3A4FF;
}
-/* You can omit the mixin code from being compiled by adding paranthesis
+/* You can omit the mixin code from being compiled by adding parenthesis
after the selector */
.center() {
diff --git a/lt-lt/json-lt.html.markdown b/lt-lt/json-lt.html.markdown
index 8c97e598..50e52a7a 100644
--- a/lt-lt/json-lt.html.markdown
+++ b/lt-lt/json-lt.html.markdown
@@ -1,6 +1,6 @@
---
language: json
-filename: learnjson.json
+filename: learnjson-lt.json
lang: lt-lt
contributors:
- ["Zygimantus", "https://github.com/zygimantus"]
diff --git a/make.html.markdown b/make.html.markdown
index e8cfd2b5..ab128475 100644
--- a/make.html.markdown
+++ b/make.html.markdown
@@ -9,16 +9,16 @@ A Makefile defines a graph of rules for creating a target (or targets).
Its purpose is to do the minimum amount of work needed to update a
target to the most recent version of the source. Famously written over a
weekend by Stuart Feldman in 1976, it is still widely used (particularly
-on Unix) despite many competitors and criticisms.
+on Unix and Linux) despite many competitors and criticisms.
-There are many varieties of make in existance, this article assumes that
-we are using GNU make which is the standard on Linux.
+There are many varieties of make in existence, however this article
+assumes that we are using GNU make which is the standard on Linux.
```make
# Comments can be written like this.
-# Files should be named Makefile and then be can run as `make <target>`.
+# File should be named Makefile and then can be run as `make <target>`.
# Otherwise we use `make -f "filename" <target>`.
# Warning - only use TABS to indent in Makefiles, never spaces!
@@ -27,13 +27,16 @@ we are using GNU make which is the standard on Linux.
# Basics
#-----------------------------------------------------------------------
+# Rules are of the format
+# target: <prerequisite>
+# where prerequisites are optional.
+
# A rule - this rule will only run if file0.txt doesn't exist.
file0.txt:
echo "foo" > file0.txt
# Even comments in these 'recipe' sections get passed to the shell.
# Try `make file0.txt` or simply `make` - first rule is the default.
-
# This rule will only run if file0.txt is newer than file1.txt.
file1.txt: file0.txt
cat file0.txt > file1.txt
@@ -99,8 +102,8 @@ process: ex1.txt file0.txt
%.png: %.svg
inkscape --export-png $^
-# Pattern rules will only do anything if make decides to create the \
-target.
+# Pattern rules will only do anything if make decides to create the
+# target.
# Directory paths are normally ignored when matching pattern rules. But
# make will try to use the most appropriate rule available.
@@ -145,11 +148,11 @@ echo:
# In order of priority from highest to lowest:
# 1: commandline arguments
# 2: Makefile
-# 3: shell enviroment variables - make imports these automatically.
+# 3: shell environment variables - make imports these automatically.
# 4: make has some predefined variables
name4 ?= Jean
-# Only set the variable if enviroment variable is not already defined.
+# Only set the variable if environment variable is not already defined.
override name5 = David
# Stops commandline arguments from changing this variable.
@@ -185,7 +188,7 @@ var := hello
var2 ::= $(var) hello
#:= and ::= are equivalent.
-# These variables are evaluated procedurely (in the order that they
+# These variables are evaluated procedurally (in the order that they
# appear), thus breaking with the rest of the language !
# This doesn't work
diff --git a/markdown.html.markdown b/markdown.html.markdown
index 8961c995..bdf42368 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -7,7 +7,9 @@ filename: markdown.md
---
-Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well).
+Markdown was created by John Gruber in 2004. It's meant to be an easy to read
+and write syntax which converts easily to HTML (and now many other formats as
+well).
Markdown also varies in implementation from one parser to a next. This
guide will attempt to clarify when features are universal or when they are
@@ -26,10 +28,12 @@ specific to a certain parser.
## HTML Elements
Markdown is a superset of HTML, so any HTML file is valid Markdown.
+
```markdown
-<!--This means we can use HTML elements in Markdown, such as the comment element,
-and they won't be affected by a markdown parser. However, if you create an HTML element
-in your markdown file, you cannot use markdown syntax within that element's contents.-->
+<!--This means we can use HTML elements in Markdown, such as the comment
+element, and they won't be affected by a markdown parser. However, if you
+create an HTML element in your markdown file, you cannot use markdown syntax
+within that element's contents.-->
```
## Headings
@@ -54,6 +58,7 @@ This is an h1
This is an h2
-------------
```
+
## Simple text styles
Text can be easily styled as italic or bold using markdown.
@@ -70,8 +75,8 @@ __And so is this text.__
*__And this!__*
```
-In Github Flavored Markdown, which is used to render markdown files on
-Github, we also have strikethrough:
+In GitHub Flavored Markdown, which is used to render markdown files on
+GitHub, we also have strikethrough:
```markdown
~~This text is rendered with strikethrough.~~
@@ -133,6 +138,7 @@ or
- Item
- One last item
```
+
Ordered lists are done with a number followed by a period.
```markdown
@@ -152,6 +158,7 @@ render the numbers in order, but this may not be a good idea.
(This renders the same as the above example)
You can also use sublists
+
```markdown
1. Item one
2. Item two
@@ -196,22 +203,23 @@ Inline code can be created using the backtick character `
John didn't even know what the `go_to()` function did!
```
-In Github Flavored Markdown, you can use a special syntax for code
-```markdown
-\`\`\`ruby <!-- except remove those backslashes when you do this, just ```ruby ! -->
+In GitHub Flavored Markdown, you can use a special syntax for code
+
+<pre>
+<code class="highlight">&#x60;&#x60;&#x60;ruby
def foobar
puts "Hello world!"
end
-\`\`\` <!-- here too, no backslashes, just ``` -->
-```
+&#x60;&#x60;&#x60;</code></pre>
-The above text doesn't require indenting, plus Github will use syntax
+The above text doesn't require indenting, plus GitHub will use syntax
highlighting of the language you specify after the \`\`\`
## Horizontal rule
-Horizontal rules (`<hr/>`) are easily added with three or more asterisks or hyphens,
-with or without spaces.
+Horizontal rules (`<hr/>`) are easily added with three or more asterisks or
+hyphens, with or without spaces.
+
```markdown
***
---
@@ -228,58 +236,64 @@ the text to display in hard brackets [] followed by the url in parentheses ()
[Click me!](http://test.com/)
```
You can also add a link title using quotes inside the parentheses.
+
```markdown
[Click me!](http://test.com/ "Link to Test.com")
```
Relative paths work too.
+
```markdown
[Go to music](/music/).
```
+
Markdown also supports reference style links.
-```markdown
-[Click this link][link1] for more info about it!
-[Also check out this link][foobar] if you want to.
-[link1]: http://test.com/ "Cool!"
-[foobar]: http://foobar.biz/ "Alright!"
-```
+<pre><code class="highlight">&#x5b;<span class="nv">Click this link</span>][<span class="ss">link1</span>] for more info about it!
+&#x5b;<span class="nv">Also check out this link</span>][<span class="ss">foobar</span>] if you want to.
+
+&#x5b;<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Cool!"</span>
+&#x5b;<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Alright!"</span></code></pre>
+
The title can also be in single quotes or in parentheses, or omitted
entirely. The references can be anywhere in your document and the reference IDs
can be anything so long as they are unique.
There is also "implicit naming" which lets you use the link text as the id.
-```markdown
-[This][] is a link.
-[this]: http://thisisalink.com/
-```
+<pre><code class="highlight">&#x5b;<span class="nv">This</span>][] is a link.
+
+&#x5b;<span class="nv">this</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
+
But it's not that commonly used.
## Images
Images are done the same way as links but with an exclamation point in front!
+
```markdown
![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title")
```
+
And reference style works as expected.
-```markdown
-![This is the alt-attribute.][myimage]
-[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here"
-```
+<pre><code class="highlight">!&#x5b;<span class="nv">This is the alt-attribute.</span>][<span class="ss">myimage</span>]
+&#x5b;<span class="nv">myimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"if you need a title, it's here"</span></code></pre>
## Miscellany
### Auto-links
+
```markdown
<http://testwebsite.com/> is equivalent to
[http://testwebsite.com/](http://testwebsite.com/)
```
### Auto-links for emails
+
```markdown
<foo@bar.com>
```
### Escaping characters
+
```markdown
I want to type *this text surrounded by asterisks* but I don't want it to be
in italics, so I do this: \*this text surrounded by asterisks\*.
@@ -287,15 +301,18 @@ in italics, so I do this: \*this text surrounded by asterisks\*.
### Keyboard keys
-In Github Flavored Markdown, you can use a `<kbd>` tag to represent keyboard keys.
+In GitHub Flavored Markdown, you can use a `<kbd>` tag to represent keyboard
+keys.
+
```markdown
Your computer crashed? Try sending a
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
```
### Tables
-Tables are only available in Github Flavored Markdown and are slightly
+Tables are only available in GitHub Flavored Markdown and are slightly
cumbersome, but if you really want it:
+
```markdown
| Col1 | Col2 | Col3 |
| :----------- | :------: | ------------: |
@@ -309,5 +326,6 @@ Col 1 | Col2 | Col3
:-- | :-: | --:
Ugh this is so ugly | make it | stop
```
+
---
For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
diff --git a/ms-my/bash-my.html.markdown b/ms-my/bash-my.html.markdown
new file mode 100644
index 00000000..e4e55b2c
--- /dev/null
+++ b/ms-my/bash-my.html.markdown
@@ -0,0 +1,284 @@
+---
+category: tool
+tool: bash
+contributors:
+ - ["Max Yankov", "https://github.com/golergka"]
+ - ["Darren Lin", "https://github.com/CogBear"]
+ - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"]
+ - ["Denis Arh", "https://github.com/darh"]
+ - ["akirahirose", "https://twitter.com/akirahirose"]
+ - ["Anton Strömkvist", "http://lutic.org/"]
+ - ["Rahil Momin", "https://github.com/iamrahil"]
+ - ["Gregrory Kielian", "https://github.com/gskielian"]
+ - ["Etan Reisner", "https://github.com/deryni"]
+filename: LearnBash-ms.sh
+translators:
+ - ["hack1m", "https://github.com/hack1m"]
+lang: ms-my
+---
+
+Bash adalah nama daripada unix shell, yang mana telah diagihkan sebagai shell untuk sistem operasi GNU dan sebagai shell lalai pada Linux dan Mac OS X. Hampir semua contoh di bawah boleh menjadi sebahagian daripada skrip shell atau dijalankan terus dalam shell.
+
+[Baca lebih lanjut di sini.](http://www.gnu.org/software/bash/manual/bashref.html)
+
+```bash
+#!/bin/bash
+# Baris pertama daripada skrip ialah shebang yang mana memberitahu sistem bagaimana untuk melaksana
+# skrip: http://en.wikipedia.org/wiki/Shebang_(Unix)
+# Seperti yang anda sudah gambarkan, komen bermula dengan #. Shebang juga ialah komen.
+
+# Contoh mudah hello world:
+echo Hello world!
+
+# Setiap arahan bermula pada baris baru, atau selepas semikolon:
+echo 'This is the first line'; echo 'This is the second line'
+
+# Mengisytihar pembolehubah kelihatan seperti ini:
+Variable="Some string"
+
+# Tetapi bukan seperti ini:
+Variable = "Some string"
+# Bash akan memutuskan yang pembolehubah adalah arahan ia mesti laksanakan dan memberi ralat
+# kerana ia tidak boleh dijumpai.
+
+# Atau seperti ini:
+Variable= 'Some string'
+# Bash akan memutuskan yang ‘Beberapa rentetan’ adalah arahan ia mesti laksanakan dan memberi
+# ralat kerana ia tidak dijumpai. (Dalam kes ini ‘Variable=' sebahagian dilihat
+# sebagai penetapan pembolehubah sah hanya untuk skop ‘Beberapa rentetan’
+# arahan.)
+
+# Menggunakan pembolehubah:
+echo $Variable
+echo "$Variable"
+echo '$Variable'
+# Apabila anda guna pembolehubah itu sendiri - menetapkan, mengeksport, atau lain-lain - anda menulis
+# nama ia tanpa $. Atau anda ingin menggunakan nilai pembolehubah, anda mesti guna $.
+# Perlu diingatkan ‘(Petikan tunggal) tidak akan memperluaskan pembolehubah!
+
+# Penggantian rentetan dalam pembolehubah
+echo ${Variable/Some/A}
+# Ini akan menukarkan sebutan pertama bagi "Some" dengan "A"
+
+# Subrentetan daripada pembolehubah
+Length=7
+echo ${Variable:0:Length}
+# Ini akan kembalikan hanya 7 aksara pertama pada nilai
+
+# Nilai lalai untuk pembolehubah
+echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"}
+# Ini berfungsi untuk null (Foo=) dan rentetan kosong (Foo=“”); sifar (Foo=0) kembali 0.
+# Perlu diingatkan ia hanya kembalikan nilai lalai dan tidak mengubah nilai pembolehubah.
+
+# Pembolehubah terbina:
+# Terdapat beberapa pembolehubah terbina berguna, seperti
+echo "Last program's return value: $?"
+echo "Script's PID: $$"
+echo "Number of arguments passed to script: $#"
+echo "All arguments passed to script: $@"
+echo "Script's arguments separated into different variables: $1 $2..."
+
+# Membaca nilai dari input:
+echo "What's your name?"
+read Name # Perlu diingatkan kita tidak perlu isytihar pembolehubah baru
+echo Hello, $Name!
+
+# Kita ada yang biasa jika struktur:
+# guna 'man test' untuk maklumat lanjut tentang bersyarat
+if [ $Name -ne $USER ]
+then
+ echo "Your name isn't your username"
+else
+ echo "Your name is your username"
+fi
+
+# Terdapat juga pelaksanaan bersyarat
+echo "Always executed" || echo "Only executed if first command fails"
+echo "Always executed" && echo "Only executed if first command does NOT fail"
+
+# Untuk guna && dan || bersama kenyataan ‘if’, anda perlu beberapa pasang daripada tanda kurung siku:
+if [ $Name == "Steve" ] && [ $Age -eq 15 ]
+then
+ echo "This will run if $Name is Steve AND $Age is 15."
+fi
+
+if [ $Name == "Daniya" ] || [ $Name == "Zach" ]
+then
+ echo "This will run if $Name is Daniya OR Zach."
+fi
+
+# Eskspresi ia ditandai dengan format berikut:
+echo $(( 10 + 5 ))
+
+# Tidak seperti bahasa pengaturcaraan lain, bash adalah shell jadi ia berfungsi dalam konteks
+# daripada direktori semasa. Anda boleh menyenaraikan fail dan direktori dalam direktori
+# semasa dengan arahan ini:
+ls
+
+# Arahan ini mempunyai opsyen yang mengawal perlaksanaannya:
+ls -l # Senarai setiap fail dan direktori pada baris yang berbeza
+
+# Keputusan arahan sebelum boleh diberikan kepada arahan selepas sebagai input.
+# arahan grep menapis input dengan memberi paten. Ini bagaimana kita boleh senaraikan
+# fail .txt di dalam direktori semasa:
+ls -l | grep "\.txt"
+
+# Anda boleh mengubah hala arahan input dan output (stdin, stdout, dan stderr).
+# Baca dari stdin sampai ^EOF$ dan menulis ganti hello.py dengan baris
+# antara “EOF":
+cat > hello.py << EOF
+#!/usr/bin/env python
+from __future__ import print_function
+import sys
+print("#stdout", file=sys.stdout)
+print("#stderr", file=sys.stderr)
+for line in sys.stdin:
+ print(line, file=sys.stdout)
+EOF
+
+# Jalankan hello.py dengan pelbagai penghantaran semula stdin, stdout, dan stderr:
+python hello.py < "input.in"
+python hello.py > "output.out"
+python hello.py 2> "error.err"
+python hello.py > "output-and-error.log" 2>&1
+python hello.py > /dev/null 2>&1
+# Output ralat akan menulis ganti fail jika ia wujud,
+# jika anda ingin menambah sebaliknya, guna ‘>>”:
+python hello.py >> "output.out" 2>> "error.err"
+
+# Menulis ganti output.out, menambah ke error.err, dan mengira baris:
+info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err
+wc -l output.out error.err
+
+# Jalankan arahan dan cetak fail Deskriptor (e.g. /dev/fd/123)
+# lihat: man fd
+echo <(echo "#helloworld")
+
+# Menulis ganti output.out dengan “#helloworld":
+cat > output.out <(echo "#helloworld")
+echo "#helloworld" > output.out
+echo "#helloworld" | cat > output.out
+echo "#helloworld" | tee output.out >/dev/null
+
+# Membersihkan fail semantara keseluruhan (tambah ‘-i’ untuk interaktif)
+rm -v output.out error.err output-and-error.log
+
+# Arahan boleh digantikan dalam arahan lain menggunakan $():
+# Arahan berikut memaparkan jumlah fail dan direktori dalam
+# direktori semasa.
+echo "There are $(ls | wc -l) items here."
+
+# Perkara yang sama boleh dilakukan dengan menggunakan backticks `` tetapi ia tidak boleh bersarang - cara yang terbaik
+# ialah menggunakan $( ).
+echo "There are `ls | wc -l` items here."
+
+# Bash menggunakan penyataan case yang berfungsi sama seperti ‘switch’ pada Java dan C++:
+case "$Variable" in
+ # Senarai paten untuk syarat yang ada ingin ketemui
+ 0) echo "There is a zero.";;
+ 1) echo "There is a one.";;
+ *) echo "It is not null.";;
+esac
+
+# ‘for loops iterate' untuk sebanyak mana argumen yang ditetapkan:
+# Kandungan dari $Variable dicetakan sebanyak tiga kali.
+for Variable in {1..3}
+do
+ echo "$Variable"
+done
+
+# Atau tulis ia cara "traditional for loop":
+for ((a=1; a <= 3; a++))
+do
+ echo $a
+done
+
+# Ia juga boleh digunakan untuk bertindak ke atas fail..
+# Ini akan menjalankan arahan 'cat' pada file1 dan file2
+for Variable in file1 file2
+do
+ cat "$Variable"
+done
+
+# ..atau output daripada arahan
+# Ini akan 'cat' output dari ls.
+for Output in $(ls)
+do
+ cat "$Output"
+done
+
+# while loop:
+while [ true ]
+do
+ echo "loop body here..."
+ break
+done
+
+# Anda juga boleh mendefinasikan fungsi
+# Definasi:
+function foo ()
+{
+ echo "Arguments work just like script arguments: $@"
+ echo "And: $1 $2..."
+ echo "This is a function"
+ return 0
+}
+
+# atau lebih mudah
+bar ()
+{
+ echo "Another way to declare functions!"
+ return 0
+}
+
+# Memanggil fungsi
+foo "My name is" $Name
+
+# Terdapat banyak arahan yang berguna yang perlu anda belajar:
+# cetak 10 baris terakhir dalam file.txt
+tail -n 10 file.txt
+# cetak 10 baris pertama dalam file.txt
+head -n 10 file.txt
+# menyusun baris fail.txt
+sort file.txt
+# laporan atau meninggalkan garisan berulang, dengan -d ia melaporkan
+uniq -d file.txt
+# cetak hanya kolum pertama sebelum aksara ','
+cut -d ',' -f 1 file.txt
+# menggantikan setiap kewujudan 'okay' dengan 'great' dalam file.txt, (serasi regex)
+sed -i 's/okay/great/g' file.txt
+# cetak ke stdoout semua baris dalam file.txt yang mana sepadan beberapa regex
+# contoh cetak baris yang mana bermula dengan “foo” dan berakhir dengan “bar”
+grep "^foo.*bar$" file.txt
+# beri opsyen “-c” untuk sebaliknya mencetak jumlah baris sepadan regex
+grep -c "^foo.*bar$" file.txt
+# jika anda secara literal mahu untuk mencari rentetan,
+# dan bukannya regex, guna fgrep (atau grep -F)
+fgrep "^foo.*bar$" file.txt
+
+
+# Baca dokumentasi Bash shell terbina dengan 'help' terbina:
+help
+help help
+help for
+help return
+help source
+help .
+
+# Baca dokumentasi Bash manpage dengan man
+apropos bash
+man 1 bash
+man bash
+
+# Baca dokumentasi info dengan info (? for help)
+apropos info | grep '^info.*('
+man info
+info info
+info 5 info
+
+# Baca dokumentasi bash info:
+info bash
+info bash 'Bash Features'
+info bash 6
+info --apropos bash
+```
diff --git a/ms-my/json-my.html.markdown b/ms-my/json-my.html.markdown
new file mode 100644
index 00000000..2d2da519
--- /dev/null
+++ b/ms-my/json-my.html.markdown
@@ -0,0 +1,102 @@
+---
+language: json
+filename: learnjson-ms.json
+contributors:
+ - ["Anna Harren", "https://github.com/iirelu"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["himanshu", "https://github.com/himanshu81494"]
+ - ["Michael Neth", "https://github.com/infernocloud"]
+translators:
+ - ["abdalim", "https://github.com/abdalim"]
+lang: ms-my
+---
+
+Disebabkan JSON adalah format pertukaran-data yang sangat ringkas, panduan ini
+kemungkinan besar adalah Learn X in Y Minutes yang paling mudah.
+
+JSON dalam bentuk paling aslinya sebenarnya tidak mempunyai sebarang komentar,
+tetapi kebanyakan pembaca menerima komen dalam bentuk C (`\\`,`/* */`). Beberapa
+pembaca juga bertoleransi terhadap koma terakhir (iaitu koma selepas elemen
+terakhir di dalam array atau selepas ciri terakhir sesuatu objek), tetapi semua
+ini harus dielakkan dan dijauhkan untuk keserasian yang lebih baik.
+
+Untuk tujuan ini bagaimanapun, semua di dalam panduan ini adalah 100% JSON yang
+sah. Luckily, it kind of speaks for itself.
+
+Sebuah nilai JSON harus terdiri dari salah satu, iaitu, nombor, string, array,
+objek atau salah satu dari nama literal berikut: true, false, null.
+
+Pelayar web yang menyokong adalah: Firefox 3.5+, Internet Explorer 8.0+, Chrome
+1.0+, Opera 10.0+, dan Safari 4.0+.
+
+Sambungan fail untuk fail - fail JSON adalah ".json" dan jenis MIME untuk teks
+JSON adalah "application/json".
+
+Banyak bahasa aturcara mempunyai fungsi untuk menyirikan (mengekod) dan
+menyah-sirikan (men-dekod) data JSON kepada struktur data asal. Javascript
+mempunyai sokongon tersirat untuk memanipulasi teks JSON sebagai data.
+
+Maklumat lebih lanjut boleh dijumpai di http://www.json.org/
+
+JSON dibina pada dua struktur:
+* Sebuah koleksi pasangan nama/nilai. Di dalam pelbagai bahasa aturcara, ini
+direalisasikan sebagai objek, rekod, "struct", "dictionary", "hash table",
+senarai berkunci, atau "associative array".
+* Sebuah senarai nilai yang tersusun. Dalam kebanyakan bahasa aturcara, ini
+direalisasikan sebagai array, vektor, senarai atau urutan.
+
+Sebuah objek dengan pelbagai pasangan nama/nilai.
+
+```json
+{
+ "kunci": "nilai",
+
+ "kekunci": "harus sentiasa dibalut dengan 'double quotes'",
+ "nombor": 0,
+ "strings": "Hellø, wørld. Semua unicode dibenarkan, bersama \"escaping\".",
+ "ada bools?": true,
+ "tiada apa - apa": null,
+
+ "nombor besar": 1.2e+100,
+
+ "objek": {
+ "komen": "Sebahagian besar struktur akan terdiri daripada objek.",
+
+ "array": [0, 1, 2, 3, "Array boleh mempunyai sebarang jenis data di dalamnya.", 5],
+
+ "objek lain": {
+ "komen": "Objek boleh dibina dengan pelbagai lapisan, sangat berguna."
+ }
+ },
+
+ "kebendulan": [
+ {
+ "punca potassium": ["pisang"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "neo"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "stail alternatif": {
+ "komen": "cuba lihat ini!"
+ , "posisi koma": "tidak mengapa - selagi ia adalah sebelum nama atau kunci seterusnya, maka ia sah"
+ , "komen lain": "sungguh bagus"
+ }
+}
+```
+
+Sebuah array sahaja yang mengandungi nilai - nilai juga adalah JSON yang sah.
+
+```json
+[1, 2, 3, "text", true]
+```
+
+Objek - objek boleh menjadi sebahagian dari array juga.
+
+```json
+[{"nama": "Abe", "umur": 25}, {"nama": "Jemah", "umur": 29}, {"name": "Yob", "umur": 31}]
+```
diff --git a/ms-my/sass-my.html.markdown b/ms-my/sass-my.html.markdown
new file mode 100644
index 00000000..68ce4ab3
--- /dev/null
+++ b/ms-my/sass-my.html.markdown
@@ -0,0 +1,232 @@
+---
+language: sass
+filename: learnsass-ms.scss
+contributors:
+ - ["Laura Kyle", "https://github.com/LauraNK"]
+translators:
+ - ["hack1m", "https://github.com/hack1m"]
+lang: ms-my
+---
+
+Sass ialah bahasa sambungan CSS yang menambah ciri-ciri seperti pembolehubah, bersarang, mixins dan banyak lagi.
+Sass (dan prapemproses lain, seperti [Less](http://lesscss.org/)) membantu pembangun untuk menulis kod mampu diselenggara dan DRY (Don't Repeat Yourself).
+
+Sass mempunyai dua perbezaan pilihan sintaks untuk dipilih. SCSS, yang mana mempunyai sintaks yang sama seperti CSS tetapi dengan ditambah ciri-ciri Sass. Atau Sass (sintaks asal), yang menggunakan indentasi bukannya tanda kurung dakap dan semikolon.
+Tutorial ini ditulis menggunakan SCSS.
+
+```scss
+
+//Komen baris tunggal dikeluarkan apabila Sass dikompil ke CSS.
+
+/*Komen multi dikekalkan. */
+
+
+
+/*Pembolehubah
+==============================*/
+
+
+
+/* Anda boleh menyimpan nilai CSS (seperti warna) dalam pembolehubah.
+Guna simbol '$' untuk membuat pembolehubah. */
+
+$primary-color: #A3A4FF;
+$secondary-color: #51527F;
+$body-font: 'Roboto', sans-serif;
+
+/* Anda boleh mengguna pembolehubah diseluruh lembaran gaya anda.
+Kini jika anda ingin mengubah warna, anda hanya perlu membuat perubahan sekali.*/
+
+body {
+ background-color: $primary-color;
+ color: $secondary-color;
+ font-family: $body-font;
+}
+
+/* Ia akan dikompil kepada: */
+body {
+ background-color: #A3A4FF;
+ color: #51527F;
+ font-family: 'Roboto', sans-serif;
+}
+
+
+/* Ini jauh lebih mampu diselenggara daripada perlu menukar warna
+setiap yang ada diseluruh lembaran gaya anda. */
+
+
+
+/*Mixins
+==============================*/
+
+
+
+/* Jika anda jumpa yang anda menulis kod yang sama pada lebih dari satu
+elemen, anda mungkin ingin menyimpan kod itu di dalam mixin.
+
+Guna arahan '@mixin', tambah dengan nama untuk mixin anda.*/
+
+@mixin center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+/* Anda boleh guna mixin bersama '@include' dan nama mixin. */
+
+div {
+ @include center;
+ background-color: $primary-color;
+}
+
+/*Ia akan dikompil kepada: */
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #A3A4FF;
+}
+
+
+/* Anda boleh guna mixins untuk membuat singkatan property. */
+
+@mixin size($width, $height) {
+ width: $width;
+ height: $height;
+}
+
+/*Yang mana anda boleh seru dengan memberi argumen lebar dan tinggi. */
+
+.rectangle {
+ @include size(100px, 60px);
+}
+
+.square {
+ @include size(40px, 40px);
+}
+
+/* Ia dikompil kepada: */
+.rectangle {
+ width: 100px;
+ height: 60px;
+}
+
+.square {
+ width: 40px;
+ height: 40px;
+}
+
+
+
+
+/*Extend (Inheritance)
+==============================*/
+
+
+
+/*Extend ialah jalan untuk berkongsi sifat dengan satu pemilih dengan yang lain. */
+
+.display {
+ @include size(5em, 5em);
+ border: 5px solid $secondary-color;
+}
+
+.display-success {
+ @extend .display;
+ border-color: #22df56;
+}
+
+/* Dikompil kepada: */
+.display, .display-success {
+ width: 5em;
+ height: 5em;
+ border: 5px solid #51527F;
+}
+
+.display-success {
+ border-color: #22df56;
+}
+
+
+
+
+/*Bersarang
+==============================*/
+
+
+
+/*Sass membenarkan anda untuk sarangkan pemilih dengan pemilih */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: #FF0000;
+ }
+}
+
+/* '&' akan digantikan dengan pemilih induk. */
+/* Anda juga boleh sarangkan kelas-pseudo. */
+/* Perlu diingat terlebih bersarang akan membuat kod anda kurang mampu diselenggara.
+Sebagai contoh: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: red;
+
+ &:hover {
+ background-color: blue;
+ }
+
+ a {
+ color: white;
+ }
+ }
+}
+
+/* Dikompil kepada: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+}
+
+ul li {
+ background-color: red;
+}
+
+ul li:hover {
+ background-color: blue;
+}
+
+ul li a {
+ color: white;
+}
+
+
+
+
+```
+
+
+
+## SASS atau Sass?
+Adakah anda tertanya-tanya sama ada Sass adalah akronim atau tidak? Anda mungkin tidak perlu, tetapi saya akan memberitahu. Nama bahasa ini adalah perkataan, "Sass", dan tidak akronim.
+Kerana orang sentiasa menulis ia sebagai "Sass", pencipta bahasa bergurau memanggilnya "Syntactically Awesome StyleSheets".
+
+## Berlatih Sass
+Jika anda ingin bermain dengan Sass di pelayar anda, lihat [SassMeister](http://sassmeister.com/).
+Anda boleh guna salah satu sintaks, hanya pergi ke tetapan dan pilih sama ada Sass atau SCSS.
+
+
+## Bacaan lanjut
+* [Dokumentasi Rasmi](http://sass-lang.com/documentation/file.SASS_REFERENCE.html)
+* [The Sass Way](http://thesassway.com/) menyediakan tutorial (asas-lanjutan) dan artikel.
diff --git a/ms-my/xml-my.html.markdown b/ms-my/xml-my.html.markdown
new file mode 100644
index 00000000..a9d7509b
--- /dev/null
+++ b/ms-my/xml-my.html.markdown
@@ -0,0 +1,130 @@
+---
+language: xml
+filename: learnxml-ms.xml
+contributors:
+ - ["João Farias", "https://github.com/JoaoGFarias"]
+translators:
+ - ["hack1m", "https://github.com/hack1m"]
+lang: ms-my
+---
+
+XML adalah bahasa markup direka untuk menyimpan dan mengangkutan data.
+
+Tidak seperti HTML, XML tidak menyatakan bagaimana paparan atau mengformat data, hanya membawanya.
+
+* Sintaks XML
+
+```xml
+<!-- Komen di XML seperti ini -->
+
+<?xml version="1.0" encoding="UTF-8"?>
+<bookstore>
+ <book category="COOKING">
+ <title lang="en">Everyday Italian</title>
+ <author>Giada De Laurentiis</author>
+ <year>2005</year>
+ <price>30.00</price>
+ </book>
+ <book category="CHILDREN">
+ <title lang="en">Harry Potter</title>
+ <author>J K. Rowling</author>
+ <year>2005</year>
+ <price>29.99</price>
+ </book>
+ <book category="WEB">
+ <title lang="en">Learning XML</title>
+ <author>Erik T. Ray</author>
+ <year>2003</year>
+ <price>39.95</price>
+ </book>
+</bookstore>
+
+<!-- Di atas adalah fail XML biasa.
+ Ia bermula dengan perisytiharan, memaklumkan beberapa metadata (pilihan).
+
+ XML menggunakan struktur pokok, Di atas, nod akar ialah ‘bookstore’, yang mana mempunyai tiga nod anak, semua ‘books’. Nod itu mempunyai lebih nod anak (atau anak-anak), dan seterusnya…
+
+ Nod dibuat menggunakan tag pembuka/penutup, dan anak-anak hanya nod antara
+ pembuka dan penutup tag.-->
+
+
+ <!-- XML membawa dua jenis data:
+ 1 - Atribut -> Iaitu metadata mengenai nod.
+ Biasanya, penghurai XML menggunakan informasi untuk menyimpan data dengan betul.
+ Ia mempunyai ciri-ciri yang dipaparkan bersama format name=“value” dalam tag
+ pembuka.
+
+ 2 - Elemen -> Iaitu data tulen.
+ Iaitu apa penghurai akan menerima daripada fail XML.
+ Elemen memaparkan diantara pembuka dan penutup tag. —>
+
+
+<!-- Di bawah, elemen dengan dua atribut -->
+<file type="gif" id="4293">computer.gif</file>
+
+
+```
+
+* Dokumen Format sempurna x Pengesahan
+
+Satu dokumen XML adalah format sempurna jika ia adalah sintaksis yang betul.
+Walau bagaimanapun, ia mungkin menyuntik lebih banyak kekangan dalam dokumen itu,
+menggunakan definasi dokumen, seperti DTD dan Skema XML.
+
+Satu dokumen XML yang mana mengikut definasi dokumen dipanggil sah,
+mengenai dokumen itu.
+
+Dengan alat ini, anda boleh menyemak data XML di luar logik aplikasi.
+
+```xml
+
+<!-- Dibawah, anda boleh melihat versi ringkas daripada dokumen bookstore,
+ dengan tambahan definisi DTD. -->
+
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE note SYSTEM "Bookstore.dtd">
+<bookstore>
+ <book category="COOKING">
+ <title >Everyday Italian</title>
+ <price>30.00</price>
+ </book>
+</bookstore>
+
+<!-- DTD boleh menjadi sesuatu seperti ini: -->
+
+<!DOCTYPE note
+[
+<!ELEMENT bookstore (book+)>
+<!ELEMENT book (title,price)>
+<!ATTLIST book category CDATA "Literature">
+<!ELEMENT title (#PCDATA)>
+<!ELEMENT price (#PCDATA)>
+]>
+
+
+<!-- DTD bermula dengan pengisytiharan.
+ Berikut, nod akar diisytihar, memerlukan 1 atau lebih nod anak ‘book’.
+ Setiap ‘book’ harus mengandungi betul-betul satu ‘title’ dan ‘price’ dan atribut
+ dipanggil ‘category’, bersama “Literature" sebagai nilai lalai ia.
+ Nod ‘title’ dan ‘price’ mengandungi aksara data terhurai.-—>
+
+<!-- DTD boleh diisytiharkan di dalam fail XML itu sendiri. -->
+
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!DOCTYPE note
+[
+<!ELEMENT bookstore (book+)>
+<!ELEMENT book (title,price)>
+<!ATTLIST book category CDATA "Literature">
+<!ELEMENT title (#PCDATA)>
+<!ELEMENT price (#PCDATA)>
+]>
+
+<bookstore>
+ <book category="COOKING">
+ <title >Everyday Italian</title>
+ <price>30.00</price>
+ </book>
+</bookstore>
+```
diff --git a/nim.html.markdown b/nim.html.markdown
index 79271732..5d00304d 100644
--- a/nim.html.markdown
+++ b/nim.html.markdown
@@ -11,7 +11,7 @@ that gives the programmer power without compromises on runtime efficiency.
Nim is efficient, expressive, and elegant.
-```nimrod
+```nim
var # Declare (and assign) variables,
letter: char = 'n' # with or without type annotations
lang = "N" & "im"
diff --git a/nl-nl/amd-nl.html.markdown b/nl-nl/amd-nl.html.markdown
deleted file mode 100644
index d5e0022a..00000000
--- a/nl-nl/amd-nl.html.markdown
+++ /dev/null
@@ -1,235 +0,0 @@
----
-category: tool
-tool: amd
-contributors:
- - ["Frederik Ring", "https://github.com/m90"]
-translators:
- - ["Reinoud Kruithof", "https://github.com/reinoudk"]
-filename: learnamd-nl.js
-lang: nl-nl
----
-
-## Aan de slag met AMD
-
-De **Asynchronous Module Definition** API specificeert een mechanisme om JavaScript
- modules the definiren zodat de module en dependencies (afhankelijkheden) asynchroon
- geladen kunnen worden. Dit is vooral erg geschikt voor de browseromgeving, waar het
- synchroon laden van modules zorgt voor problemen qua prestatie, gebruiksvriendelijkheid,
- debugging en cross-domain toegangsproblemen.
-
-### Basis concept
-```javascript
-// De basis AMD API bestaat uit niks meer dan twee methodes: `define` en `require`
-// and gaat vooral over de definitie en gebruik van modules:
-// `define(id?, dependencies?, factory)` definieert een module
-// `require(dependencies, callback)` importeert een set van dependencies en
-// gebruikt ze in de gegeven callback
-
-// Laten we starten met het gebruiken van define om een nieuwe module (met naam)
-// te creeren, welke geen dependencies heeft. Dit doen we door een naam
-// en een zogeheten factory functie door te geven aan define:
-define('awesomeAMD', function(){
- var isAMDAwesome = function(){
- return true;
- };
- // De return waarde van een module's factory functie is
- // wat andere modules of require calls ontvangen wanneer
- // ze onze `awesomeAMD` module requiren.
- // De gexporteerde waarde kan van alles zijn: (constructor) functies,
- // objecten, primitives, zelfs undefined (hoewel dat niet veel nut heeft).
- return isAMDAwesome;
-});
-
-
-// We gaan nu een andere module defineren die afhankelijk is van onze
-// `awesomeAMD` module. Merk hierbij op dat er nu een extra functieargument
-// is die de dependencies van onze module defineert:
-define('schreewlelijk', ['awesomeAMD'], function(awesomeAMD){
- // dependencies worden naar de factory's functieargumenten
- // gestuurd in de volgorde waarin ze gespecificeert zijn
- var vertelIedereen = function(){
- if (awesomeAMD()){
- alert('Dit is zOoOo cool!');
- } else {
- alert('Vrij saai, niet?');
- }
- };
- return vertelIedereen;
-});
-
-// Nu we weten hoe we define moeten gebruiken, kunnen we require gebruiken
-// om ons programma mee te starten. De vorm van `require` is
-// `(arrayVanDependencies, callback)`.
-require(['schreeuwlelijk'], function(schreewlelijk){
- schreeuwlelijk();
-});
-
-// Om deze tutorial code uit te laten voeren, gaan we hier een vrij basic
-// (niet-asynchrone) versie van AMD implementeren:
-function define(naam, deps, factory){
- // merk op hoe modules zonder dependencies worden afgehandeld
- define[naam] = require(factory ? deps : [], factory || deps);
-}
-
-function require(deps, callback){
- var args = [];
- // we halen eerst alle dependecies op die nodig zijn
- // om require aan te roepen
- for (var i = 0; i < deps.length; i++){
- args[i] = define[deps[i]];
- }
- // voldoe aan alle dependencies van de callback
- return callback.apply(null, args);
-}
-// je kan deze code hier in actie zien (Engels): http://jsfiddle.net/qap949pd/
-```
-
-### require.js in de echte wereld
-
-In contrast met het voorbeeld uit de introductie, implementeert `require.js`
- (de meest populaire AMD library) de **A** in **AMD**. Dit maakt het mogelijk
- om je modules en hun dependencies asynchroon in the laden via XHR:
-
-```javascript
-/* file: app/main.js */
-require(['modules/someClass'], function(SomeClass){
- // de callback word uitgesteld tot de dependency geladen is
- var things = new SomeClass();
-});
-console.log('Dus, hier wachten we!'); // dit wordt als eerste uitgevoerd
-```
-
-De afspraak is dat je over het algemeen n module in n bestand opslaat.
-`require.js` kan module-namen achterhalen gebaseerd op de bestandslocatie,
-dus je hoeft je module geen naam te geven. Je kan simpelweg aan ze referen
- door hun locatie te gebruiken.
-In het voorbeeld nemen we aan dat `someClass` aanwezig is in de `modules` map,
- relatief ten opzichte van de `baseUrl` uit je configuratie.
-
-* app/
- * main.js
- * modules/
- * someClass.js
- * someHelpers.js
- * ...
- * daos/
- * things.js
- * ...
-
-Dit betekent dat we `someClass` kunnen defineren zonder een module-id te specificeren:
-
-```javascript
-/* file: app/modules/someClass.js */
-define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){
- // definitie van de module gebeurt, natuurlijk, ook asynchroon
- function SomeClass(){
- this.method = function(){/**/};
- // ...
- }
- return SomeClass;
-});
-```
-Gebruik `requirejs.config(configObj)` om het gedrag van de standaard mapping
- aan te passen in je `main.js`:
-
-```javascript
-/* file: main.js */
-requirejs.config({
- baseUrl : 'app',
- paths : {
- // je kan ook modules uit andere locatie inladen
- jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min',
- coolLibUitBower : '../bower_components/cool-lib/coollib'
- }
-});
-require(['jquery', 'coolLibUitBower', 'modules/someHelpers'], function($, coolLib, helpers){
- // een `main` bestand moet require minstens eenmaal aanroepen,
- // anders zal er geen code uitgevoerd worden
- coolLib.doFancyDingenMet(helpers.transform($('#foo')));
-});
-```
-Op `require.js` gebaseerde apps hebben vaak een enkel beginpunt (`main.js`)
- welke toegevoegd wordt aan de `require.js` script tag als een data-attribuut.
-Deze zal automisch geladen en uitgevoerd worden als de pagina laadt:
-
-```html
-<!DOCTYPE html>
-<html>
-<head>
- <title>Honder script tags? Nooi meer!</title>
-</head>
-<body>
- <script src="require.js" data-main="app/main"></script>
-</body>
-</html>
-```
-
-### Een heel project optimaliseren met r.js
-
-Veel mensen geven er de voorkeur aan om AMD te gebruiken tijdens de
- ontwikkelfase om code op een gezonde manier te organiseren maar
- willen nog steeds een enkel scriptbestand gebruiken in productie in
- plaats van honderderen XHR verzoeken uit te voeren als de pagina laadt.
-
-`require.js` wordt geleverd met een script genaamd `r.js` (die je waarschijnlijk
-uitvoert in node.js, hoewel Rhino ook ondersteund wordt) welke de
-dependency book van je project analyseert en een enkel bestand bouwt met daarin
-al je module (juist genaamd), geminificeerd en klaar voor productie.
-
-Instaleren met `npm`:
-```shell
-$ npm install requirejs -g
-```
-
-Nu kun je het een configuratiebestand voeden:
-```shell
-$ r.js -o app.build.js
-```
-
-Voor ons bovenstaande voorbeeld zou de configuratie er zo uit kunnen zien:
-```javascript
-/* file : app.build.js */
-({
- name : 'main', // naam van het beginpunt
- out : 'main-built.js', // naam van het bestand waar de output naar geschreven wordt
- baseUrl : 'app',
- paths : {
- // `empty:` verteld r.js dat dee nog steeds geladen moet worden van de CDN,
- // gebruik makend van de locatie gespecificeert in `main.js`
- jquery : 'empty:',
- coolLibUitBower : '../bower_components/cool-lib/coollib'
- }
-})
-```
-Verwissel simpelweg `data-main` om het gebouwde bestand te gebruiken in productie:
-```html
-<script src="require.js" data-main="app/main-built"></script>
-```
-
-Een erg gedetaileerd [overzicht van bouwopties](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is
-beschikbar in de GitHub repo (Engels).
-
-Hieronder vind je nog meer informatie over AMD (Engels).
-
-### Onderwerpen die niet aan bod zijn gekomen
-* [Loader plugins / transforms](http://requirejs.org/docs/plugins.html)
-* [CommonJS style loading and exporting](http://requirejs.org/docs/commonjs.html)
-* [Advanced configuration](http://requirejs.org/docs/api.html#config)
-* [Shim configuration (loading non-AMD modules)](http://requirejs.org/docs/api.html#config-shim)
-* [CSS loading and optimizing with require.js](http://requirejs.org/docs/optimization.html#onecss)
-* [Using almond.js for builds](https://github.com/jrburke/almond)
-
-### Verder lezen:
-
-* [Official Spec](https://github.com/amdjs/amdjs-api/wiki/AMD)
-* [Why AMD?](http://requirejs.org/docs/whyamd.html)
-* [Universal Module Definition](https://github.com/umdjs/umd)
-
-### Implementaties:
-
-* [require.js](http://requirejs.org)
-* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/)
-* [cujo.js](http://cujojs.com/)
-* [curl.js](https://github.com/cujojs/curl)
-* [lsjs](https://github.com/zazl/lsjs)
-* [mmd](https://github.com/alexlawrence/mmd)
diff --git a/nl-nl/brainfuck-nl.html.markdown b/nl-nl/bf.html.markdown
index 6062b24c..016e2ba2 100644
--- a/nl-nl/brainfuck-nl.html.markdown
+++ b/nl-nl/bf.html.markdown
@@ -1,5 +1,5 @@
---
-language: brainfuck
+language: bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]
diff --git a/nl-nl/coffeescript-nl.html.markdown b/nl-nl/coffeescript-nl.html.markdown
index dc0b1e19..390e6572 100644
--- a/nl-nl/coffeescript-nl.html.markdown
+++ b/nl-nl/coffeescript-nl.html.markdown
@@ -6,6 +6,7 @@ contributors:
translators:
- ["Jelle Besseling", "https://github.com/Jell-E"]
- ["D.A.W. de Waal", "http://github.com/diodewaal"]
+ - ["Sam van Kampen", "http://tehsvk.net"]
filename: coffeescript-nl.coffee
lang: nl-nl
---
@@ -13,10 +14,10 @@ lang: nl-nl
CoffeeScript is een kleine programmeertaal die direct compileert naar
JavaScript en er is geen interpretatie tijdens het uitvoeren.
CoffeeScript probeert om leesbare, goed geformatteerde en goed draaiende
-JavaScript code te genereren, die in elke JavaScript runtime werkt, als een
+JavaScript code te genereren, die in elke JavaScript-runtime werkt, als een
opvolger van JavaScript.
-Op [de CoffeeScript website](http://coffeescript.org/), staat een
+Op [de CoffeeScript-website](http://coffeescript.org/), staat een
volledigere tutorial voor CoffeeScript.
``` coffeescript
@@ -26,7 +27,7 @@ volledigere tutorial voor CoffeeScript.
###
Blokken commentaar maak je zo, ze vertalen naar JavaScripts */ en /*
-in de uitvoer van de CoffeeScript compiler.
+in de uitvoer van de CoffeeScript-compiler.
Het is belangrijk dat je ongeveer snapt hoe JavaScript
werkt voordat je verder gaat.
@@ -43,7 +44,7 @@ getal = -42 if tegengestelde #=> if(tegengestelde) { getal = -42; }
kwadraat = (x) -> x * x #=> var kwadraat = function(x) { return x * x; }
vul = (houder, vloeistof = "koffie") ->
- "Nu de #{houder} met #{koffie} aan het vullen..."
+ "Nu de #{houder} met #{vloeistof} aan het vullen..."
#=>var vul;
#
#vul = function(houder, vloeistof) {
@@ -80,7 +81,7 @@ wedstrijd = (winnaar, lopers...) ->
alert "Ik wist het!" if elvis?
#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
-# Lijst abstractie:
+# Lijstabstracties:
derdemachten = (wiskunde.derdemacht num for num in lijst)
#=>derdemachten = (function() {
# var _i, _len, _results;
diff --git a/nl-nl/json-nl.html.markdown b/nl-nl/json-nl.html.markdown
new file mode 100644
index 00000000..906112ff
--- /dev/null
+++ b/nl-nl/json-nl.html.markdown
@@ -0,0 +1,71 @@
+---
+language: json
+filename: learnjson-nl.json
+contributors:
+ - ["Anna Harren", "https://github.com/iirelu"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["himanshu", "https://github.com/himanshu81494"]
+translators:
+ - ["Niels van Velzen", "https://nielsvanvelzen.me"]
+lang: nl-nl
+---
+
+Gezien JSON een zeer eenvouding formaat heeft zal dit een van de simpelste
+Learn X in Y Minutes ooit zijn.
+
+JSON heeft volgens de specificaties geen commentaar, ondanks dat hebben de
+meeste parsers support voor C-stijl (`//`, `/* */`) commentaar.
+Sommige parsers staan zelfs trailing komma's toe.
+(Een komma na het laatste element in een array of ahter de laatste eigenshap van een object).
+Het is wel beter om dit soort dingen te vermijden omdat het niet overal zal werken.
+
+In het voorbeeld zal alleen 100% geldige JSON gebruikt worden.
+
+Data types gesupport door JSON zijn: nummers, strings, booleans, arrays, objecten en null.
+Gesupporte browsers zijn: Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4.
+De extensie voor JSON bestanden is ".json". De MIME type is "application/json"
+Enkele nadelen van JSON zijn het gebrek een type definities en een manier van DTD.
+
+```json
+{
+ "sleutel": "waarde",
+
+ "sleutels": "zijn altijd in quotes geplaatst",
+ "nummers": 0,
+ "strings": "Hallø, wereld. Alle unicode karakters zijn toegestaan, samen met \"escaping\".",
+ "boolean": true,
+ "niks": null,
+
+ "groot nummer": 1.2e+100,
+
+ "objecten": {
+ "commentaar": "In JSON gebruik je vooral objecten voor je strutuur",
+
+ "array": [0, 1, 2, 3, "Arrays kunnen alles in zich hebben.", 5],
+
+ "nog een object": {
+ "commentaar": "Objecten kunnen genest worden, erg handig."
+ }
+ },
+
+ "dwaasheid": [
+ {
+ "bronnen van kalium": ["bananen"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "neo"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "alternatieve stijl": {
+ "commentaar": "Kijk dit!"
+ , "De komma positie": "maakt niet uit zolang het er maar is"
+ , "nog meer commentaar": "wat leuk"
+ },
+
+ "dat was kort": "En nu ben je klaar, dit was alles wat je moet weten over JSON."
+}
+```
diff --git a/nl-nl/json.html.markdown b/nl-nl/json.html.markdown
new file mode 100644
index 00000000..bedfb70a
--- /dev/null
+++ b/nl-nl/json.html.markdown
@@ -0,0 +1,61 @@
+---
+language: json
+filename: learnjson-nl.json
+contributors:
+ - ["Anna Harren", "https://github.com/iirelu"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+translators:
+ - ["Mathieu De Coster", "https://github.com/m-decoster"]
+lang: nl-nl
+---
+
+Aangezien JSON een extreem eenvoudig datauitwisselingsformaat is, zal dit waarschijnlijk
+de meest eenvoudige Learn X in Y Minutes ooit zijn.
+
+Puur JSON heeft geen commentaar, maar de meeste parsers zullen commentaar in de stijl
+van C (`//`, `/* */`) aanvaarden. In dit voorbeeld zal alles 100% correcte JSON zijn.
+Gelukkig spreekt het meeste voor zichzelf.
+
+```json
+{
+ "key": "value",
+
+ "keys": "moeten altijd tussen dubbele aanhalingstekens staan",
+ "getallen": 0,
+ "strings": "Hellø, world. Alle Unicode-karakters zijn toegelaten, zo ook \"escaping\".",
+ "heeft json booleans?": true,
+ "niets": null,
+
+ "groot getal": 1.2e+100,
+
+ "objecten": {
+ "commentaar": "De meeste structuur wordt gemaakt met objecten.",
+
+ "array": [0, 1, 2, 3, "Arrays kunnen eender wat bevatten.", 5],
+
+ "nog een object": {
+ "commentaar": "Hoe handig, we kunnen objecten nesten."
+ }
+ },
+
+ "dwaasheid": [
+ {
+ "bronnen van kalium": ["bananen"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "neo"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "alternatieve stijl": {
+ "commentaar": "kijk hier eens naar!"
+ , "komma locatie": "maakt niet uit - zo lang het voor de value komt, is alles in orde"
+ , "nog commentaar": "hoe leuk"
+ },
+
+ "dat was kort": "Je bent klaar. Je kent nu alles dat JSON kan aanbieden."
+}
+```
diff --git a/nl-nl/typescript-nl.html.markdown b/nl-nl/typescript-nl.html.markdown
new file mode 100644
index 00000000..dcea2a4d
--- /dev/null
+++ b/nl-nl/typescript-nl.html.markdown
@@ -0,0 +1,174 @@
+---
+language: TypeScript
+contributors:
+ - ["Philippe Vlérick", "https://github.com/pvlerick"]
+filename: learntypescript-nl.ts
+translators:
+ - ["Niels van Velzen", "https://nielsvanvelzen.me"]
+lang: nl-nl
+---
+
+TypeScript is een taal gericht op het versoepelen van de ontwikkeling van
+grote applicaties gemaakt in JavaScript.
+TypeScript voegt veelgebruikte technieken zoals klassen, modules, interfaces,
+generieken en statische typen toe aan JavaScript.
+TypeScript is een superset van JavaScript: alle JavaScript code is geldige
+TypeScript code waardoor de overgang van JavaScript naar TypeScript wordt versoepeld.
+
+Dit artikel focust zich alleen op de extra's van TypeScript tegenover [JavaScript] (../javascript-nl/).
+
+Om de compiler van TypeScript te kunnen proberen kun je naar de [Playground] (http://www.typescriptlang.org/Playground) gaan.
+Hier kun je automatisch aangevulde code typen in TypeScript en de JavaScript variant bekijken.
+
+```js
+// Er zijn 3 basis typen in TypeScript
+var isKlaar: boolean = false;
+var lijnen: number = 42;
+var naam: string = "Peter";
+
+// Wanneer het type onbekend is gebruik je "Any"
+var nietZeker: any = 4;
+nietZeker = "misschien een string";
+nietZeker = false; // Toch een boolean
+
+// Voor collecties zijn er "typed arrays"
+var lijst: number[] = [1, 2, 3];
+// of generieke arrays
+var lijst: Array<number> = [1, 2, 3];
+
+// Voor enumeraties:
+enum Kleur {Rood, Groen, Blauw};
+var c: Kleur = Kleur.Groen;
+
+// Als laatst, "void" wordt gebruikt voor als een functie geen resultaat geeft
+function groteVerschrikkelijkeMelding(): void {
+ alert("Ik ben een vervelende melding!");
+}
+
+// Functies zijn eersteklas ?, supporten de lambda "fat arrow" syntax en
+// gebruiken gebruiken "type inference"
+
+// Het volgende is allemaal hetzelfde
+var f1 = function(i: number): number { return i * i; }
+var f2 = function(i: number) { return i * i; }
+var f3 = (i: number): number => { return i * i; }
+var f4 = (i: number) => { return i * i; }
+// Omdat we maar 1 lijn gebruiken hoeft het return keyword niet gebruikt te worden
+var f5 = (i: number) => i * i;
+
+// Interfaces zijn structureel, elk object wat de eigenschappen heeft
+// is een gebruiker van de interface
+interface Persoon {
+ naam: string;
+ // Optionele eigenschappen worden gemarkeerd met "?"
+ leeftijd?: number;
+ // En natuurlijk functies
+ verplaats(): void;
+}
+
+// Object die gebruikt maakt van de "Persoon" interface
+// Kan gezien worden als persoon sinds het de naam en verplaats eigenschappen bevat
+var p: Persoon = { naam: "Bobby", verplaats: () => {} };
+// Object met de optionele leeftijd eigenschap
+var geldigPersoon: Persoon = { naam: "Bobby", leeftijd: 42, verplaats: () => {} };
+// Ongeldig persoon vanwege de leeftijds type
+var ongeldigPersoon: Persoon = { naam: "Bobby", leeftijd: true };
+
+// Interfaces kunnen ook een functie ype beschrijven
+interface ZoekFunc {
+ (bron: string, subString: string): boolean;
+}
+// Alleen de parameters types zijn belangrijk, namen maken niet uit.
+var mySearch: ZoekFunc;
+mySearch = function(src: string, sub: string) {
+ return src.search(sub) != -1;
+}
+
+// Classes - leden zijn standaard publiek
+class Punt {
+ // Eigenschappen
+ x: number;
+
+ // Constructor - de publieke / prive trefwoorden in deze context zullen
+ // eigenschappen in de klasse kunnen aanmaken zonder ze te defineren.
+ // In dit voorbeeld zal "y" net als "x" gedefineerd worden met minder code.
+ // Standaard waardes zijn ook gesupport
+
+ constructor(x: number, public y: number = 0) {
+ this.x = x;
+ }
+
+ // Functies
+ dist(): number { return Math.sqrt(this.x * this.x + this.y * this.y); }
+
+ // Statische leden
+ static origin = new Punt(0, 0);
+}
+
+var p1 = new Punt(10 ,20);
+var p2 = new Punt(25); // y zal de waarde 0 krijgen
+
+// Overnemen
+class Punt3D extends Punt {
+ constructor(x: number, y: number, public z: number = 0) {
+ super(x, y); // Constructor van ouder aanroepen (Punt)
+ }
+
+ // Overschrijven
+ dist(): number {
+ var d = super.dist();
+ return Math.sqrt(d * d + this.z * this.z);
+ }
+}
+
+// Modules werken ongeveer hetzelfde als namespaces
+// met "." kan je submodules defineren
+module Geometrie {
+ export class Vierkant {
+ constructor(public zijLengte: number = 0) {
+ }
+
+ oppervlakte() {
+ return Math.pow(this.zijLengte, 2);
+ }
+ }
+}
+
+var s1 = new Geometrie.Vierkant(5);
+
+// Local alias for referencing a module
+import G = Geometrie;
+
+var s2 = new G.Vierkant(10);
+
+// Generieken
+// Classes
+class Tupel<T1, T2> {
+ constructor(public item1: T1, public item2: T2) {
+ }
+}
+
+// Interfaces
+interface Paar<T> {
+ item1: T;
+ item2: T;
+}
+
+// En functies
+var paarNaarTupel = function<T>(p: Paar<T>) {
+ return new Tupel(p.item1, p.item2);
+};
+
+var tupel = paarNaarTupel({ item1: "hallo", item2: "wereld" });
+
+// Refferentie naar een definitie bestand:
+/// <reference path="jquery.d.ts" />
+
+```
+
+## Verder lezen (engels)
+ * [TypeScript Official website] (http://www.typescriptlang.org/)
+ * [TypeScript language specifications (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238)
+ * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript)
+ * [Source Code on GitHub] (https://github.com/Microsoft/TypeScript)
+ * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/)
diff --git a/nl-nl/xml-nl.html.markdown b/nl-nl/xml-nl.html.markdown
new file mode 100644
index 00000000..930f7cf4
--- /dev/null
+++ b/nl-nl/xml-nl.html.markdown
@@ -0,0 +1,134 @@
+---
+language: xml
+filename: learnxml-nl.xml
+contributors:
+ - ["Joo Farias", "https://github.com/JoaoGFarias"]
+translators:
+ - ["Frank van Gemeren", "https://github.com/frvge"]
+lang: nl-nl
+---
+
+XML is een markuptaal die ontwikkeld is om data in te bewaren en data mee te
+verzenden.
+
+Anders dan HTML specificeert XML niet hoe data getoond of geformatteerd moet worden.
+Het bevat de data slechts.
+
+* XML Syntax
+
+```xml
+<!-- Dit is commentaar in XML -->
+
+<?xml version="1.0" encoding="UTF-8"?>
+<boekenwinkel>
+ <boek categorie="KOKEN">
+ <title taal="nl">Alledaags Italiaans</titel>
+ <auteur>Giada De Laurentiis</auteur>
+ <jaar>2005</jaar>
+ <prijs>30.00</prijs>
+ </boek>
+ <boek categorie="KINDEREN">
+ <titel taal="nl">Harry Potter</titel>
+ <auteur>J K. Rowling</auteur>
+ <jaar>2005</jaar>
+ <prijs>29.99</prijs>
+ </boek>
+ <boek categorie="WEB">
+ <titel taal="en">Learning XML</titel>
+ <auteur>Erik T. Ray</auteur>
+ <jaar>2003</jaar>
+ <prijs>39.95</prijs>
+ </boek>
+</boekenwinkel>
+
+<!-- Hierboven staat een standaard XML bestand.
+ Het begint met een declaratie die optionele metadata bevat.
+
+ XML werkt met een boomstructuur. De stamknoop hierboven is 'boekenwinkel'.
+ Deze heeft drie kinderen die allemaal 'boek' zijn. Deze knopen hebben op
+ hun beurt weer kinderen, enzovoort...
+
+ Knopen hebben open- en sluittags. Kinderen zijn knopen die zich tussen de
+ open- en sluittags van hun ouders bevinden. -->
+
+<!-- XML bevat two soorten data:
+ 1 - Attributen -> Dit is metadata van een knoop.
+ Deze informatie wordt meestal door de XML parser gebruikt om de data op
+ de juiste manier op te slaan. Je herkent het door de syntax in de vorm
+ van naam="waarde" in de open tag.
+ 2 - Elementen -> Dit is de pure data
+ Deze gegevens worden door de parser uit het XML bestand gehaald.
+ Elementen staan tussen de open- en sluittags. -->
+
+
+<!-- Hieronder staat een element met twee attributen -->
+<bestand type="gif" id="4293">computer.gif</bestand>
+
+
+```
+
+* Grammaticaal correcte documenten x Validatie
+
+Een XML document is "grammaticaal correct" of "well-formatted" als de
+syntax correct is. Het is ook mogelijk om meer structuur in het document
+aan te brengen met document definities zoals DTD en XML Schema.
+
+Een XML document dat aan een document definitie voldoet wordt "valide" volgens
+die document definitie genoemd.
+
+Met deze gereedschappen kan je de XML data buiten je applicatie logica
+controleren.
+
+```xml
+
+<!-- Hieronder staat een versimpelde versie voor een boekenwinkel document,
+ met een toevoeging van een DTD definitie. -->
+
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE note SYSTEM "boekenwinkel.dtd">
+<boekenwinkel>
+ <boek categorie="KOKEN">
+ <titel>Alledaags Italiaans</titel>
+ <prijs>30.00</prijs>
+ </boek>
+</boekenwinkel>
+
+<!-- De DTD kan er als volgt uitzien:-->
+
+<!DOCTYPE note
+[
+<!ELEMENT boekenwinkel (boek+)>
+<!ELEMENT boek (titel,prijs)>
+<!ATTLIST boek categorie CDATA "Literatuur">
+<!ELEMENT titel (#PCDATA)>
+<!ELEMENT prijs (#PCDATA)>
+]>
+
+
+<!-- De DTD begint met een declaratie.
+ Hierna volgt de declaratie van de stamknoop, die 1 of meer 'boek' kinderen
+ moet bevatten.
+ Elk 'boek' moet precies 1 'titel' en 'prijs' element bevatten en een attribuut
+ 'categorie' hebben waarvan 'Literatuur' de standaard waarde is.
+ De 'titel' en 'prijs' knopen bevatten parsed character data.-->
+
+<!-- De DTD kan ook in het XML bestand zelf gedeclareerd worden.-->
+
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!DOCTYPE note
+[
+<!ELEMENT boekenwinkel (boek+)>
+<!ELEMENT boek (titel,prijs)>
+<!ATTLIST boek categorie CDATA "Literatuur">
+<!ELEMENT titel (#PCDATA)>
+<!ELEMENT prijs (#PCDATA)>
+]>
+
+<boekenwinkel>
+ <boek categorie="KOKEN">
+ <titel>Alledaags Italiaans</titel>
+ <prijs>30.00</prijs>
+ </boek>
+</boekenwinkel>
+``` \ No newline at end of file
diff --git a/ocaml.html.markdown b/ocaml.html.markdown
index 8faab297..59ead9ec 100644
--- a/ocaml.html.markdown
+++ b/ocaml.html.markdown
@@ -104,7 +104,7 @@ let fact_4 = factorial (5-1) ;;
let sqr2 = sqr (-2) ;;
(* Every function must have at least one argument.
- Since some funcions naturally don't take any arguments, there's
+ Since some functions naturally don't take any arguments, there's
"unit" type for it that has the only one value written as "()" *)
let print_hello () = print_endline "hello world" ;;
@@ -216,7 +216,7 @@ List.nth my_list 1 ;;
(* There are higher-order functions for lists such as map and filter. *)
List.map (fun x -> x * 2) [1; 2; 3] ;;
-List.filter (fun x -> if x mod 2 = 0 then true else false) [1; 2; 3; 4] ;;
+List.filter (fun x -> x mod 2 = 0) [1; 2; 3; 4] ;;
(* You can add an item to the beginning of a list with the "::" constructor
often referred to as "cons". *)
diff --git a/paren.html.markdown b/paren.html.markdown
index cde14853..701cadfd 100644
--- a/paren.html.markdown
+++ b/paren.html.markdown
@@ -4,6 +4,7 @@ language: Paren
filename: learnparen.paren
contributors:
- ["KIM Taegyoon", "https://github.com/kimtg"]
+ - ["Claudson Martins", "https://github.com/claudsonm"]
---
[Paren](https://bitbucket.org/ktg/paren) is a dialect of Lisp. It is designed to be an embedded language.
@@ -77,7 +78,7 @@ some-var ; => 5
;; Accessing a previously unassigned variable is an exception
; x ; => Unknown variable: x : nil
-;; Local binding: Use lambda calculus! `a' and `b' are bound to `1' and `2' only within the (fn ...)
+;; Local binding: Use lambda calculus! 'a' and 'b' are bound to '1' and '2' only within the (fn ...)
((fn (a b) (+ a b)) 1 2) ; => 3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@@ -88,12 +89,12 @@ some-var ; => 5
;; Lists are vector-like data structures. (Random access is O(1).)
(cons 1 (cons 2 (cons 3 (list)))) ; => (1 2 3)
-;; `list' is a convenience variadic constructor for lists
+;; 'list' is a convenience variadic constructor for lists
(list 1 2 3) ; => (1 2 3)
;; and a quote can also be used for a literal list value
(quote (+ 1 2)) ; => (+ 1 2)
-;; Can still use `cons' to add an item to the beginning of a list
+;; Can still use 'cons' to add an item to the beginning of a list
(cons 0 (list 1 2 3)) ; => (0 1 2 3)
;; Lists are a very basic type, so there is a *lot* of functionality for
@@ -106,7 +107,7 @@ some-var ; => 5
;; 3. Functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;; Use `fn' to create functions.
+;; Use 'fn' to create functions.
;; A function always returns the value of its last expression
(fn () "Hello World") ; => (fn () Hello World) : fn
@@ -117,7 +118,7 @@ some-var ; => 5
(set hello-world (fn () "Hello World"))
(hello-world) ; => "Hello World"
-;; You can shorten this using the function definition syntatcic sugae:
+;; You can shorten this using the function definition syntactic sugar:
(defn hello-world2 () "Hello World")
;; The () in the above is the list of arguments for the function
@@ -134,7 +135,7 @@ some-var ; => 5
;; 4. Equality
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;; for numbers use `=='
+;; for numbers use '=='
(== 3 3.0) ; => true
(== 2 1) ; => false
@@ -166,7 +167,7 @@ some-var ; => 5
;; 6. Mutation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;; Use `set' to assign a new value to a variable or a place
+;; Use 'set' to assign a new value to a variable or a place
(set n 5) ; => 5
(set n (inc n)) ; => 6
n ; => 6
diff --git a/perl.html.markdown b/perl.html.markdown
index 1b86f410..61e8cd0e 100644
--- a/perl.html.markdown
+++ b/perl.html.markdown
@@ -5,6 +5,7 @@ language: perl
filename: learnperl.pl
contributors:
- ["Korjavin Ivan", "http://github.com/korjavin"]
+ - ["Dan Book", "http://github.com/Grinnz"]
---
Perl 5 is a highly capable, feature-rich programming language with over 25 years of development.
@@ -14,6 +15,15 @@ Perl 5 runs on over 100 platforms from portables to mainframes and is suitable f
```perl
# Single line comments start with a number sign.
+#### Strict and warnings
+
+use strict;
+use warnings;
+
+# All perl scripts and modules should include these lines. Strict causes
+# compilation to fail in cases like misspelled variable names, and warnings
+# will print warning messages in case of common pitfalls like concatenating
+# to an undefined value.
#### Perl variable types
@@ -37,7 +47,9 @@ my @animals = ("camel", "llama", "owl");
my @numbers = (23, 42, 69);
my @mixed = ("camel", 42, 1.23);
-
+# Array elements are accessed using square brackets, with a $ to indicate
+# one value will be returned.
+my $second = $animals[1];
## Hashes
# A hash represents a set of key/value pairs:
@@ -50,11 +62,39 @@ my %fruit_color = (
apple => "red",
banana => "yellow",
);
+
+# Hash elements are accessed using curly braces, again with the $ sigil.
+my $color = $fruit_color{apple};
+
# Scalars, arrays and hashes are documented more fully in perldata.
# (perldoc perldata).
-# More complex data types can be constructed using references, which allow you
-# to build lists and hashes within lists and hashes.
+#### References
+
+# More complex data types can be constructed using references, which allow
+# you to build arrays and hashes within arrays and hashes.
+
+my $array_ref = \@array;
+my $hash_ref = \%hash;
+my @array_of_arrays = (\@array1, \@array2, \@array3);
+
+# You can also create anonymous arrays or hashes, returning a reference:
+
+my $fruits = ["apple", "banana"];
+my $colors = {apple => "red", banana => "yellow"};
+
+# References can be dereferenced by prefixing the appropriate sigil.
+
+my @fruits_array = @$fruits;
+my %colors_hash = %$colors;
+
+# As a shortcut, the arrow operator can be used to dereference and access a
+# single value.
+
+my $first = $array_ref->[0];
+my $value = $hash_ref->{banana};
+
+# See perlreftut and perlref for more in-depth documentation on references.
#### Conditional and looping constructs
@@ -105,6 +145,9 @@ for (@elements) {
# the Perlish post-condition way again
print for @elements;
+# iterating through the keys and values of a referenced hash
+print $hash_ref->{$_} for keys %$hash_ref;
+
#### Regular expressions
# Perl's regular expression support is both broad and deep, and is the subject
@@ -151,11 +194,101 @@ sub logger {
# Now we can use the subroutine just as any other built-in function:
logger("We have a logger subroutine!");
-```
-#### Using Perl modules
+#### Modules
+
+# A module is a set of Perl code, usually subroutines, which can be used in
+# other Perl code. It is usually stored in a file with the extension .pm so
+# that Perl can find it.
+
+package MyModule;
+use strict;
+use warnings;
+
+sub trim {
+ my $string = shift;
+ $string =~ s/^\s+//;
+ $string =~ s/\s+$//;
+ return $string;
+}
+
+1;
+
+# From elsewhere:
+
+use MyModule;
+MyModule::trim($string);
+
+# The Exporter module can help with making subroutines exportable, so they
+# can be used like this:
+
+use MyModule 'trim';
+trim($string);
+
+# Many Perl modules can be downloaded from CPAN (http://www.cpan.org/) and
+# provide a range of features to help you avoid reinventing the wheel. A
+# number of popular modules like Exporter are included with the Perl
+# distribution itself. See perlmod for more details on modules in Perl.
+
+#### Objects
+
+# Objects in Perl are just references that know which class (package) they
+# belong to, so that methods (subroutines) called on it can be found there.
+# The bless function is used in constructors (usually new) to set this up.
+# However, you never need to call it yourself if you use a module like Moose
+# or Moo (see below).
+
+package MyCounter;
+use strict;
+use warnings;
+
+sub new {
+ my $class = shift;
+ my $self = {count => 0};
+ return bless $self, $class;
+}
+
+sub count {
+ my $self = shift;
+ return $self->{count};
+}
+
+sub increment {
+ my $self = shift;
+ $self->{count}++;
+}
+
+1;
+
+# Methods can be called on a class or object instance with the arrow operator.
+
+use MyCounter;
+my $counter = MyCounter->new;
+print $counter->count, "\n"; # 0
+$counter->increment;
+print $counter->count, "\n"; # 1
+
+# The modules Moose and Moo from CPAN can help you set up your object classes.
+# They provide a constructor and simple syntax for declaring attributes. This
+# class can be used equivalently to the one above.
+
+package MyCounter;
+use Moo; # imports strict and warnings
+
+has 'count' => (is => 'rwp', default => 0, init_arg => undef);
+
+sub increment {
+ my $self = shift;
+ $self->_set_count($self->count + 1);
+}
+
+1;
+
+# Object-oriented programming is covered more thoroughly in perlootut, and its
+# low-level implementation in Perl is covered in perlobj.
+```
-Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN (http://www.cpan.org/). A number of popular modules are included with the Perl distribution itself.
+#### FAQ
perlfaq contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use.
diff --git a/perl6.html.markdown b/perl6.html.markdown
index 1829f964..b5a25a41 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -103,7 +103,7 @@ sub say-hello-to(Str $name) { # You can provide the type of an argument
## It can also have optional arguments:
sub with-optional($arg?) { # the "?" marks the argument optional
- say "I might return `(Any)` (Perl's "null"-like value) if I don't have
+ say "I might return `(Any)` (Perl's 'null'-like value) if I don't have
an argument passed, or I'll return my argument";
$arg;
}
@@ -803,9 +803,8 @@ module Foo::Bar {
my sub unavailable { # `my sub` is the default
say "Can't access me from outside, I'm my !";
}
+ say ++$n; # increment the package variable and output its value
}
-
- say ++$n; # lexically-scoped variables are still available
}
say $Foo::Bar::n; #=> 1
Foo::Bar::inc; #=> 2
@@ -825,7 +824,7 @@ say why-not[^5]; #=> 5 15 25 35 45
# (they exist in other langages such as C as `static`)
sub fixed-rand {
state $val = rand;
- say $rand;
+ say $val;
}
fixed-rand for ^10; # will print the same number 10 times
@@ -1330,7 +1329,7 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ...
-### Extra: the MAIN subroutime
+### Extra: the MAIN subroutine
# The `MAIN` subroutine is called when you run a Perl 6 file directly.
# It's very powerful, because Perl 6 actually parses the arguments
# and pass them as such to the sub. It also handles named argument (`--foo`)
diff --git a/php.html.markdown b/php.html.markdown
index 0504ced2..6c2b38c8 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -53,6 +53,8 @@ $int1 = 12; // => 12
$int2 = -12; // => -12
$int3 = 012; // => 10 (a leading 0 denotes an octal number)
$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal)
+// Binary integer literals are available since PHP 5.4.0.
+$int5 = 0b11111111; // 255 (a leading 0b denotes a binary number)
// Floats (aka doubles)
$float = 1.234;
@@ -116,11 +118,11 @@ echo 'Multiple', 'Parameters', 'Valid'; // Returns 'MultipleParametersValid'
// a valid constant name starts with a letter or underscore,
// followed by any number of letters, numbers, or underscores.
-define("FOO", "something");
+define("FOO", "something");
// access to a constant is possible by calling the choosen name without a $
echo FOO; // Returns 'something'
-echo 'This outputs '.FOO; // Returns 'This ouputs something'
+echo 'This outputs ' . FOO; // Returns 'This ouputs something'
@@ -140,6 +142,9 @@ $associative = ['One' => 1, 'Two' => 2, 'Three' => 3];
echo $associative['One']; // prints 1
+// Add an element to an associative array
+$associative['Four'] = 4;
+
// List literals implicitly assign integer keys
$array = ['One', 'Two', 'Three'];
echo $array[0]; // => "One"
@@ -534,10 +539,23 @@ class MyClass
print 'MyClass';
}
- //final keyword would make a function unoverridable
+ // final keyword would make a function unoverridable
final function youCannotOverrideMe()
{
}
+
+ // Magic Methods
+
+ // what to do if Object is treated as a String
+ public function __toString() {
+ return $property;
+ }
+
+ // opposite to __construct()
+ // called when object is no longer referenced
+ public function __destruct() {
+ print "Destroying";
+ }
/*
* Declaring class properties or methods as static makes them accessible without
@@ -765,6 +783,37 @@ I'm a ParentClass
But I'm ChildClass
*/
+/**********************
+* Magic constants
+*
+*/
+
+// Get current class name. Must be used inside a class declaration.
+echo "Current class name is " . __CLASS__;
+
+// Get full path directory of a file
+echo "Current directory is " . __DIR__;
+
+ // Typical usage
+ require __DIR__ . '/vendor/autoload.php';
+
+// Get full path of a file
+echo "Current file path is " . __FILE__;
+
+// Get current function name
+echo "Current function name is " . __FUNCTION__;
+
+// Get current line number
+echo "Current line number is " . __LINE__;
+
+// Get the name of the current method. Only returns a value when used inside a trait or object declaration.
+echo "Current method is " . __METHOD__;
+
+// Get the name of the current namespace
+echo "Current namespace is " . __NAMESPACE__;
+
+// Get the name of the current trait. Only returns a value when used inside a trait or object declaration.
+echo "Current namespace is " . __TRAIT__;
/**********************
* Error Handling
diff --git a/pl-pl/brainfuck-pl.html.markdown b/pl-pl/bf-pl.html.markdown
index 69d814c4..801f1a9a 100644
--- a/pl-pl/brainfuck-pl.html.markdown
+++ b/pl-pl/bf-pl.html.markdown
@@ -1,5 +1,5 @@
---
-language: brainfuck
+language: bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]
diff --git a/pl-pl/perl-pl.html.markdown b/pl-pl/perl-pl.html.markdown
index 9e8ade5b..029ca006 100644
--- a/pl-pl/perl-pl.html.markdown
+++ b/pl-pl/perl-pl.html.markdown
@@ -163,7 +163,7 @@ z repozytorium CPAN do zrealizowania konkretnego zadania.
#### Do doczytania
- - [perl-tutorial](http://perl-tutorial.org/)
- - [Naucz się Perla na www.perl.com](http://www.perl.org/learn.html)
- - [perldoc](http://perldoc.perl.org/)
- - wbudowane w Perla: `perldoc perlintro` \ No newline at end of file
+ - [perl-tutorial](http://perl-tutorial.org/)
+ - [Naucz się Perla na www.perl.com](http://www.perl.org/learn.html)
+ - [perldoc](http://perldoc.perl.org/)
+ - wbudowane w Perla: `perldoc perlintro`
diff --git a/pl-pl/xml-pl.html.markdown b/pl-pl/xml-pl.html.markdown
new file mode 100644
index 00000000..7cce138f
--- /dev/null
+++ b/pl-pl/xml-pl.html.markdown
@@ -0,0 +1,137 @@
+---
+language: xml
+filename: learnxml-pl.xml
+contributors:
+ - ["João Farias", "https://github.com/JoaoGFarias"]
+translators:
+ - ["Tomasz Janiszewski", "https://github.com/janisz"]
+lang: pl-pl
+---
+
+XML (_Extensible Markup Language_) to rozszerzalny język znaczników, stworzony
+do przechowywania i transportu danych.
+
+W przeciwieństwie do HTML, XML nie specyfikuje w jaki sposób wyświetlić dane, a
+tylko je przechowuje.
+
+* Składnia XML
+
+```xml
+<!-- Komentarze w XML wyglądają jak ten -->
+
+<?xml version="1.0" encoding="UTF-8"?>
+<ksiegarnia>
+ <ksiazka kategoria="GOTOWANIE">
+ <tytul lang="pl">Codzienny Włoski</tytul>
+ <autor>Giada De Laurentiis</autor>
+ <rok>2005</rok>
+ <cena>30.00</cena>
+ </ksiazka>
+ <ksiazka kategoria="DZIECI">
+ <tytul lang="pl">Harry Potter</tytul>
+ <autor>J K. Rowling</autor>
+ <rok>2005</rok>
+ <cena>29.99</cena>
+ </ksiazka>
+ <ksiazka kategoria="WEB">
+ <tytul lang="pl">Nauka XML</tytul>
+ <autor>Erik T. Ray</autor>
+ <rok>2003</rok>
+ <cena>39.95</cena>
+ </ksiazka>
+</ksiegarnia>
+
+<!-- Powyżej jest typowy plik XML.
+ Zaczyna się od deklaracji zawierającej metadane (opcjonalne).
+
+ XML używa drzewiastej struktury. Powyżej, głównym wierzchołkiem jest
+ 'ksiegarnia' , która zawiera trzy (3) węzły potomne, wszystkie 'ksiazki',
+ które zawierają swoje węzły potomne, i tak dalej...
+
+ Węzły są tworzone używające otwierających/zamykających znaczników.
+ Węzły potomne znajdują się pomiędzy otwierającym i zamykającym znacznikiem.
+-->
+
+<!-- XML przechowuje dwa typy danych
+ 1 - Atrybuty -> metadane o węźle
+ Zazwyczaj parser XML używa tych informacji do przechowywania danych we
+ właściwy sposób. Atrybuty nadawane są poprzez wpisanie ich w otwierajacym
+ znaczniku.
+ 2 - Elementy -> to są czyste dane.
+ Dane, które parser otrzymuje z pliku XML.
+ Elementy są deklarowane pomiędzy otwierajacym i zamykającym znacznikiem,
+ bez nawiasów. -->
+
+<!-- Poniższy element ma dwa atrybuty -->
+<plik type="gif" id="4293">komputer.gif</plik>
+
+
+```
+
+* Dobrze sformatowany dokument i walidacja
+
+Dokument XML jest dobrze sformatowany gdy jest syntaktycznie poprawny.
+Jednakże możliwe jest wstrzykiwanie większej liczby ograniczeń w dokumencie,
+używając definicji takich jak DTD i XML Schema.
+
+Dokument XML, który jest zgodny ze swoją definicją jest poprawny.
+
+
+Korzystając z tych narzędzi możesz sprawdzić dane zawarte w dokumencie poza
+logiką aplikacji.
+
+```xml
+
+
+<!-- Poniżej jest uproszczona wersja dokumentu księgarni,
+ z dodatkową definicją DTD.-->
+
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE notatka SYSTEM "Ksiegarnia.dtd">
+<ksiegarnia>
+ <ksiazka kategoria="GOTOWANIE">
+ <tytul >Everyday Italian</tytul>
+ <cena>30.00</cena>
+ </ksiazka>
+</ksiegarnia>
+
+<!-- DTD może wyglądać następująco:-->
+
+<!DOCTYPE notatka
+[
+<!ELEMENT ksiegarnia (ksiazka+)>
+<!ELEMENT ksiazka (tytul,cena)>
+<!ATTLIST ksiazka kategoria CDATA "Literatura">
+<!ELEMENT tytul (#PCDATA)>
+<!ELEMENT cena (#PCDATA)>
+]>
+
+
+<!-- DTD zaczyna się od deklaracji
+ Zaczynając od góry, główny węzeł jest zadeklarowany jako wymagający jednego
+ lub więcej węzłów potomnych typu 'ksiżka'.
+ Każda 'ksiażka' powinna zawierać dokładnie jeden 'tytuł' i 'cene' oraz atrybut
+ 'kategoria' z 'literaturą' jako wartość domyślna.
+ 'tytuł' i 'cena' to pola typu parsowalnych zmiennyc znakowych, co oznacza że
+ użyte znaczniki zostaną zinterpretowane &lt; zamienione <. -->
+
+<!-- DTD moze być deklarowane wewnątrz pliku XML. -->
+
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!DOCTYPE notatka
+[
+<!ELEMENT ksiegarnia (ksiazka+)>
+<!ELEMENT ksiazka (tytul,cena)>
+<!ATTLIST ksiazka kategoria CDATA "Literatura">
+<!ELEMENT tytul (#PCDATA)>
+<!ELEMENT cena (#PCDATA)>
+]>
+
+<ksiegarnia>
+ <ksiazka kategoria="GOTOWANIE">
+ <tytul >Everyday Italian</tytul>
+ <cena>30.00</cena>
+ </ksiazka>
+</ksiegarnia>
+```
diff --git a/powershell.html.markdown b/powershell.html.markdown
index 4bc1ab39..fc944b85 100644
--- a/powershell.html.markdown
+++ b/powershell.html.markdown
@@ -18,6 +18,7 @@ rather than plain text.
[Read more here.](https://technet.microsoft.com/en-us/library/bb978526.aspx)
If you are uncertain about your environment:
+
```
Get-ExecutionPolicy -List
Set-ExecutionPolicy AllSigned
@@ -33,6 +34,7 @@ $PSVersionTable
```
Getting help:
+
```
# Find commands
Get-Command about_* # alias: gcm
@@ -49,6 +51,7 @@ Update-Help # Run as admin
```
The tutorial starts here:
+
```
# As you already figured, comments start with #
@@ -244,10 +247,12 @@ function New-Website() {
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
# Note that .NET functions MUST be called with parentheses
-# while PS functions CANNOT be called with parentheses
+# while PS functions CANNOT be called with parentheses.
+# If you do call a cmdlet/PS function with parentheses,
+# it is the same as passing a single parameter list
$writer = New-Object System.IO.StreamWriter($path, $true)
$writer.Write([Environment]::NewLine)
-$write.Dispose()
+$writer.Dispose()
### IO
# Reading a value from input:
@@ -265,12 +270,14 @@ Get-Command ConvertTo-*,ConvertFrom-*
# Refresh your PATH
$env:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") +
";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
+
# Find Python in path
$env:PATH.Split(";") | Where-Object { $_ -like "*python*"}
# Change working directory without having to remember previous path
Push-Location c:\temp # change working directory to c:\temp
Pop-Location # change back to previous working directory
+# Aliases are: pushd and popd
# Unblock a directory after download
Get-ChildItem -Recurse | Unblock-File
@@ -292,6 +299,7 @@ $Shortcut.Save()
Configuring your shell
+
```
# $Profile is the full path for your `Microsoft.PowerShell_profile.ps1`
# All code there will be executed when the PS session starts
@@ -304,6 +312,7 @@ if (-not (Test-Path $Profile)) {
```
Interesting Projects
+
* [Channel9](https://channel9.msdn.com/Search?term=powershell%20pipeline#ch9Search&lang-en=en) PowerShell tutorials
* [PSGet](https://github.com/psget/psget) NuGet for PowerShell
* [PSReadLine](https://github.com/lzybkr/PSReadLine/) A bash inspired readline implementation for PowerShell (So good that it now ships with Windows10 by default!)
@@ -314,6 +323,7 @@ Interesting Projects
* [PowerShell Community Extensions](http://pscx.codeplex.com/) (Dead)
Not covered
+
* WMI: Windows Management Intrumentation (Get-CimInstance)
* Multitasking: Start-Job -scriptBlock {...},
* Code Signing
diff --git a/pt-br/amd.html.markdown b/pt-br/amd.html.markdown
new file mode 100644
index 00000000..690fc8da
--- /dev/null
+++ b/pt-br/amd.html.markdown
@@ -0,0 +1,218 @@
+---
+category: tool
+tool: amd
+contributors:
+ - ["Frederik Ring", "https://github.com/m90"]
+translators:
+ - ["Felipe Tarijon", "http://nanoincub.com/"]
+lang: ptr-br
+filename: learnamd-pt.js
+---
+
+## Começando com AMD
+
+A API de Definição de Módulos Assíncrona **Asynchronous Module Definition**
+especifica um mecanismo para definição de módulos em JavaScript para os quais o
+módulo e suas dependências podem ser carregados de forma assíncrona. Isso é
+particularmente bem adequado para o ambiente do browser onde o carregamento de
+módulos de forma síncrona fica sujeito a problemas de performance, usabilidade,
+debugging e problemas de acesso em requisições cross-domain.
+
+### Conceito básico
+```javascript
+// O básico da API de AMD consiste de nada mais que dois métodos: `define` e `require`
+// e isso é tudo sobre a definição de módulo e consumo:
+// `define(id?, dependências?, factory)` define um módulo
+// `require(dependências, callback)` importa uma série de dependências e
+// consome elas no callback passado como parâmetro.
+
+// Vamos começar usando o define para definir um novo módulo
+// que não tem dependências. Nós vamos fazer isso passando um nome
+// e uma função factory para definir:
+define('awesomeAMD', function(){
+ var isAMDAwesome = function(){
+ return true;
+ };
+ // O valor retornado da função de factory do módulo é
+ // o que os outros módulos ou chamadas de require irão
+ // receber quando requisitarem nosso módulo `awesomeAMD`.
+ // O valor exportado pode ser qualquer coisa, (construtor) funções,
+ // objetos, primitives, até mesmo undefined (apesar de que não irão ajudar muito).
+ return isAMDAwesome;
+});
+
+// Agora, vamos definir outro módulo que depende do nosso módulo `awesomeAMD`.
+// Perceba que existe um argumento adicional definindo nossas dependências do
+// módulo agora:
+define('loudmouth', ['awesomeAMD'], function(awesomeAMD){
+ // dependências serão passadas como argumentos da factory
+ // na ordem que elas forem especificadas
+ var tellEveryone = function(){
+ if (awesomeAMD()){
+ alert('Isso é tãaaao loko!');
+ } else {
+ alert('Bem estúpido, né não?');
+ }
+ };
+ return tellEveryone;
+});
+
+// Agora que nós sabemos como usar o define, vamos usar o `require` para
+// começar nosso programa. A assinatura do `require` é `(arrayDedependências, callback)`.
+require(['loudmouth'], function(loudmouth){
+ loudmouth();
+});
+
+// Para fazer esse tutorial executável, vamos implementar uma versão muito básica
+// (não-assíncrona) de AMD bem aqui nesse lugar:
+function define(nome, deps, factory){
+ // perceba como os módulos sem dependências são manipulados
+ define[nome] = require(factory ? deps : [], factory || deps);
+}
+
+function require(deps, callback){
+ var args = [];
+ // primeiro vamos recuperar todas as dependências necessárias
+ // pela chamada requerida
+ for (var i = 0; i < deps.length; i++){
+ args[i] = define[deps[i]];
+ }
+ // corresponder todas as dependências da função de callback
+ return callback.apply(null, args);
+}
+// você pode ver esse código em ação aqui: http://jsfiddle.net/qap949pd/
+```
+
+### Uso na vida real com require.js
+
+Em contraste com o exemplo introdutório, `require.js` (a biblioteca mais popular de AMD) na verdade implementa o **A** do **AMD**, permitindo que você carregue os módulos e suas
+dependências via XHR:
+
+```javascript
+/* file: app/main.js */
+require(['modules/algumaClasse'], function(AlgumaClasse){
+ // o callback é deferido até que a dependencia seja carregada
+ var coisa = new AlgumaClasse();
+});
+console.log('Então aqui estamos nós, esperando!'); // isso vai rodar primeiro
+```
+
+Por convenção, você geralmente guarda um módulo em um arquivo. `require.js` pode resolver nome de módulos baseado no caminho das pastas, então você não precisa nomear os seus módulos, mas sim simplesmente referenciar eles usando sua origem. No exemplo `algumaClasse` é adotado a pasta `modules`, relativa a configuração da sua `baseUrl`:
+
+* app/
+ * main.js
+ * modules/
+ * algumaClasse.js
+ * algunsHelpers.js
+ * ...
+ * daos/
+ * coisas.js
+ * ...
+
+Isso significa que nós podemos definir `algumaClasse` sem especificar o id de um módulo:
+
+```javascript
+/* arquivo: app/modules/algumaClasse.js */
+define(['daos/coisas', 'modules/algunsHelpers'], function(coisasDao, helpers){
+ // definição de módulo, claro, irá acontecer também de forma assíncrona
+ function AlgumaClasse(){
+ this.metodo = function(){/**/};
+ // ...
+ }
+ return AlgumaClasse;
+});
+```
+Para alterar o comportamento padrão de mapeamento de caminho de pastas utilize
+`requirejs.config(configObj)` em seu `main.js`:
+
+```javascript
+/* arquivo: main.js */
+requirejs.config({
+ baseUrl : 'app',
+ paths : {
+ // você pode também carregar módulos de outros locais
+ jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min',
+ coolLibFromBower : '../bower_components/cool-lib/coollib'
+ }
+});
+require(['jquery', 'coolLibFromBower', 'modules/algunsHelpers'], function($, coolLib, helpers){
+ // um arquivo `main` precisa chamar o require pelo menos uma vez,
+ // caso contrário, o código jamais rodará
+ coolLib.facaAlgoDoidoCom(helpers.transform($('#foo')));
+});
+```
+Apps baseados em `require.js` geralmente terão u´m único ponto de acesso (`main.js`) que é passado à tag script do `require.js` como um data-attribute. Ele vai ser automaticamente carregado e executado com o carregamento da página:
+
+```html
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Umas 100 tags de script? Nunca mais!</title>
+</head>
+<body>
+ <script src="require.js" data-main="app/main"></script>
+</body>
+</html>
+```
+
+### Otimizando um projeto inteiro utilizando r.js
+
+Muitas pessoas preferem usar AMD para sanar a organização do código durante o desenvolvimento, mas continuam querendo colocar um único arquivo de script em produção ao invés de realizarem centenas de requisições XHRs no carregamento da página.
+
+`require.js` vem com um script chamado `r.js` (que você vai provavelmente rodar em node.js, embora Rhino suporte também) que você pode analisar o gráfico de dependências de seu projeto, e fazer em um único arquivo contendo todos os seus módulos (corretamente nomeados), minificados e prontos para serem consumidos.
+
+Instale-o utilizando `npm`:
+```shell
+$ npm install requirejs -g
+```
+
+Agora você pode alimentá-lo com um arquivo de configuração:
+```shell
+$ r.js -o app.build.js
+```
+
+Para o nosso exemplo acima a configuração pode ser essa:
+```javascript
+/* file : app.build.js */
+({
+ name : 'main', // nome do ponto de acesso
+ out : 'main-built.js', // nome o arquivo para gravar a saída
+ baseUrl : 'app',
+ paths : {
+ // `empty:` fala para o r.js que isso ainda deve ser baixado da CDN, usando
+ // o local especificado no `main.js`
+ jquery : 'empty:',
+ coolLibFromBower : '../bower_components/cool-lib/coollib'
+ }
+})
+```
+
+Para usar o arquivo gerado, em produção, simplesmente troque o `data-main`:
+```html
+<script src="require.js" data-main="app/main-built"></script>
+```
+
+Uma incrível e detalhada visão geral [de build options](https://github.com/jrburke/r.js/blob/master/build/example.build.js) está disponível no repositório do GitHub.
+
+### Tópicos não abordados nesse tutorial
+* [Plugins de carregamento / transforms](http://requirejs.org/docs/plugins.html)
+* [CommonJS style carregamento e exportação](http://requirejs.org/docs/commonjs.html)
+* [Configuração avançada](http://requirejs.org/docs/api.html#config)
+* [Shim configuration (carregando módulos sem AMD)](http://requirejs.org/docs/api.html#config-shim)
+* [Carregando e otimizando CSS com require.js](http://requirejs.org/docs/optimization.html#onecss)
+* [Usando almond.js para builds](https://github.com/jrburke/almond)
+
+### Outras leituras:
+
+* [Especificação oficial](https://github.com/amdjs/amdjs-api/wiki/AMD)
+* [Por quê AMD?](http://requirejs.org/docs/whyamd.html)
+* [Universal Module Definition](https://github.com/umdjs/umd)
+
+### Implementações:
+
+* [require.js](http://requirejs.org)
+* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/)
+* [cujo.js](http://cujojs.com/)
+* [curl.js](https://github.com/cujojs/curl)
+* [lsjs](https://github.com/zazl/lsjs)
+* [mmd](https://github.com/alexlawrence/mmd)
diff --git a/pt-br/asymptotic-notation-pt.html.markdown b/pt-br/asymptotic-notation-pt.html.markdown
new file mode 100644
index 00000000..2e299d09
--- /dev/null
+++ b/pt-br/asymptotic-notation-pt.html.markdown
@@ -0,0 +1,159 @@
+---
+category: Algorithms & Data Structures
+name: Asymptotic Notation
+contributors:
+ - ["Jake Prather", "http://github.com/JakeHP"]
+translators:
+ - ["João Farias", "https://github.com/JoaoGFarias"]
+lang: pt-br
+---
+
+# Notação Assintótica
+
+## O que é?
+
+Notação Assintótica é uma linguagem que nos permite analisar o tempo de execução
+ de um algoritmo através da indentificação de seu comportamento com o
+ crescimento da entrada oferecida. Isso também é conhecido como taxa de
+ crescimento do algoritmo. O algoritmo de repente torna-se lento quando o
+ tamanho da entrada cresce? O algoritmo mantém, em geral, seu tempo de execução
+ rápido mesmo com aumento da entrada? Notação Assintótica nos dá a habilidade de
+ responder estas questões.
+
+## Quais são as alternativas para responder a estas questões?
+
+Um modo seria contar o número de operações primitivas com diferentes tamanhos de
+ entrada. Apesar desta ser uma solução válida, o trabalho que ela requer, mesmo para algoritmos simples, não a justifica.
+
+ Outro modo é fisicamente medir a quantidade de tempo que um algoritmo requer
+ para terminar com diferentes tamanhos de entrada. Entretanto, a precisão e
+ relatividade (tempo obtido seria relativo apenas à máquina onde ocorreu a
+ execução) deste método está limitado a variáveis de ambiente, como hardware,
+ poder de processamento, etc.
+
+## Tipos de Notação Assintótica
+
+Na primeira seção desse documento, descrevemos como Notação Assintótica identifica o comportamento de um algoritmo
+ a medida que o tamanho da entrada cresce. Imaginemos um algoritmo como uma função
+ *f*, *n* como o tamanho da entrada e *f(n)* sendo o tempo de execução. Então,
+ para dado algoritmo *f*, com entrada de tamanho *n*, você terá tempo de execução
+ *f(n)*. Isto resulta em um gráfico onde a coordernada Y é o tempo de execução
+, a coordernada X representa o tamanho da entrada e os pontos representao o tempo
+de execução para dado tamanho de entrada.
+
+Você pode representar a função, ou o algoritmo, com Notação Assintótica de várias
+maneiras. Você pode representar um algoritmo nas formas de Melhor Caso, Pior Caso
+ou Caso Médio.
+A maneira mais comum de analisar um algoritmo é pelo Pior Caso. Você tipicamente
+não avalia o melhor caso, porque essas condições não são atingidas com frequência.
+Um bom exemplo disto seria em algoritmos de ordenação; especificamente, na adição
+de elementos à árvores. O melhor caso na maioria de algoritmos pode ser de apenas
+uma operação. Entretanto, na maioria dos casos, o elemento a ser adicionado terá
+que percorrer a árvore de forma apropriada, o que pode causar a analise de um
+ramo inteiro.
+Este é o pior caso, e isto é o que você está se preparando.
+
+### Tipos de funções, limites e simplificação
+
+```
+Função Logarítmica - log n
+Função Linear - an + b
+Função Quadrática - an^2 + bn + c
+Função Polinomial - an^z + . . . + an^2 + a*n^1 + a*n^0, onde *z* é uma constante
+Função Exponencial - a^n, onde a é alguma constante
+```
+Estas são as funções básicas de crescimento usadas em várias notações. A lista
+ começa com a de crescimento mais lento (logarítima, a de execução mais rápida)
+e segue para a de crescimento mais rápido (exponencial, de execução mais lenta).
+Repare que enquando *n*, a entrada, cresce, cada uma dessas funções cresce mais
+rápido que quadrático, polinimial e exponencial, comparadas com logaritma e linear.
+
+Uma nota extremamente importante para notações é tentar usar os termos mais simples.
+Isto significa descartar constantes e termos de ordem mais baixa, pois quando o
+tamanho da entrada cresce para o infinito (limites matemáticos), os termos de ordem
+mais baixa e constantes tornam-se irrelevantes. Por exemplo, se você tiver uma
+constante muito grande, 2^9001, a simplificação não afeterá sua notação.
+
+Já que queremos as formas mais simples, mudemos nossa tabela um pouco...
+
+```
+Função Logarítmica - log n
+Função Linear - n
+Função Quadrática - n^2
+Função Polinomial - n^z, onde *z* é uma constante
+Função Exponencial - a^n, onde *a* é uma constante
+```
+
+### Big-O
+
+Big-O, também escrita como O, é uma Notação Assintótica para o pior caso. Digamos
+*f(n)* seja o tempo de exeução de um algoritmo e *g(n)) um tempo de complexidade
+arbritário que você quer relacionar com seu algoritmo. *f(n)* é O(g(n)), se, para
+quando constante real c (c > 0), *f(n)* <= *c g(n)* para todo tamanho de entrada
+n (n > 0).
+
+
+*Exemplo 1*
+
+```
+f(n) = 3log n + 100
+g(n) = log n
+```
+
+`f(n)` é O(g(n))?
+
+`3 log n + 100` é O(log n)?
+
+Vejamos a definição de Big-O:
+
+```
+3log n + 100 <= c * log n
+```
+
+Há alguma constante c que satisfaça a definição para todo n?
+
+```
+3log n + 100 <= 150 * log n, n > 2 (Indefinido em n = 1)
+```
+
+Sim! A definição de Big-I for atentida, portante `f(n)` é `O(g(n))`.
+
+*Exemplo 2*
+
+```
+f(n) = 3*n^2
+g(n) = n
+```
+
+`f(n)` é O(g(n))?
+
+`3 * n^2` é O(n)?
+Vejamos a definição de Big-O:
+
+```
+3 * n^2 <= c * n
+```
+
+Há alguma constante c que satisfaça a definição para todo n?
+
+Não, não há. `f(n)` não é O(g(n)).
+
+### Big-Omega
+Big-Omega, também escrita como Ω, é uma Notação Assintótica para o melhor caso.
+
+`f(n)`é Ω(g(n)), se para qualquer constante real c (c > 0), `f(n)` é >= `c g(n)` para todo tamanho de entrada n (n > 0).
+
+Sinta-se livre para adicionar mais exemplos. Big-O é a notação primária usada para medir complexidade de algoritmos.
+
+### Notas Finais
+É difícil manter esse tipo de tópico curto e você deveria ler os livros e artigos listados abaixo. Eles cobrem muito mais profundamente definições e exemplos. Mais x='Algoritms & Data Structures' virá; teremos um documento sobre analisar código em breve.
+
+## Livros
+
+* [Algorithms](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X)
+* [Algorithm Design](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651)
+
+## Artigos Online
+
+* [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)
diff --git a/pt-br/bash-pt.html.markdown b/pt-br/bash-pt.html.markdown
new file mode 100644
index 00000000..a604e7b8
--- /dev/null
+++ b/pt-br/bash-pt.html.markdown
@@ -0,0 +1,282 @@
+---
+category: tool
+tool: bash
+contributors:
+ - ["Max Yankov", "https://github.com/golergka"]
+ - ["Darren Lin", "https://github.com/CogBear"]
+ - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"]
+ - ["Denis Arh", "https://github.com/darh"]
+ - ["akirahirose", "https://twitter.com/akirahirose"]
+ - ["Anton Strömkvist", "http://lutic.org/"]
+translators:
+ - ["Davidson Mizael", "https://github.com/davidsonmizael"]
+filename: LearnBash-pt_br.sh
+lang: pt-br
+---
+
+Tutorial de shell em português
+
+Bash é o nome do shell do Unix, que também é distribuido como shell do sistema
+operacional GNU e como shell padrão para Linux e Mac OS X. Praticamente todos
+os exemplos abaixo podem fazer parte de um shell script e pode ser executados
+diretamente no shell.
+
+[Leia mais sobre](http://www.gnu.org/software/bash/manual/bashref.html)
+
+```bash
+#!/bin/bash
+# A primeira linha do script é o shebang, que conta para o sistema como executar
+# o script: http://en.wikipedia.org/wiki/Shebang_(Unix)
+# Como você já deve ter percebido, comentários começam com #.
+# Shebang também é um comentário.
+
+# Exemplo simples de hello world:
+echo Hello World!
+
+# Cada comando começa com uma nova linha, ou após um ponto virgula:
+echo 'Essa é a primeira linha'; echo 'Essa é a segunda linha'
+
+# A declaração de variáveis é mais ou menos assim
+Variavel="Alguma string"
+
+# Mas não assim:
+Variavel = "Alguma string"
+# Bash interpretará Variavel como um comando e tentará executar e lhe retornar
+# um erro porque o comando não pode ser encontrado.
+
+# Ou assim:
+Variavel= 'Alguma string'
+# Bash interpretará 'Alguma string' como um comando e tentará executar e lhe retornar
+# um erro porque o comando não pode ser encontrado. (Nesse caso a a parte 'Variavel='
+# é vista com uma declaração de variável valida apenas para o escopo do comando 'Uma string').
+
+# Usando a variável:
+echo $Variavel
+echo "$Variavel"
+echo '$Variavel'
+# Quando você usa a variável em si — declarando valor, exportando, etc — você escreve
+# seu nome sem o $. Se você quer usar o valor da variável você deve usar o $.
+# Note que ' (aspas simples) não expandirão as variáveis!
+
+# Substituição de strings em variáveis
+echo ${Variavel/Alguma/Uma}
+# Isso substituirá a primeira ocorrência de "Alguma" por "Uma"
+
+# Substring de uma variável
+Tamanho=7
+echo ${Variavel:0:Tamanho}
+# Isso retornará apenas os 7 primeiros caractéres da variável
+
+# Valor padrão de uma variável
+echo ${Foo:-"ValorPadraoSeFooNaoExistirOuEstiverVazia"}
+# Isso funciona para nulo (Foo=) e (Foo=""); zero (Foo=0) retorna 0.
+# Note que isso apenas retornar o valor padrão e não mudar o valor da variável.
+
+# Variáveis internas
+# Tem algumas variáveis internas bem uteis, como
+echo "O ultimo retorno do programa: $?"
+echo "PID do script: $$"
+echo "Numero de argumentos passados para o script $#"
+echo "Todos os argumentos passados para o script $@"
+echo "Os argumentos do script em variáveis diferentes: $1, $2..."
+
+# Lendo o valor do input:
+echo "Qual o seu nome?"
+read Nome # Note que nós não precisamos declarar a variável
+echo Ola, $Nome
+
+# Nós temos a estrutura if normal:
+# use 'man test' para mais infomações para as condicionais
+if [ $Nome -ne $USER ]
+then
+ echo "Seu nome não é o seu username"
+else
+ echo "Seu nome é seu username"
+fi
+
+# Tem também execução condicional
+echo "Sempre executado" || echo "Somente executado se o primeiro falhar"
+echo "Sempre executado" && "Só executado se o primeiro NÃO falhar"
+
+# Para usar && e || com o if, você precisa multiplicar os pares de colchetes
+if [ $Nome == "Estevao"] && [ $Idade -eq 15]
+then
+ echo "Isso vai rodar se $Nome é igual Estevao E $Idade é 15."
+fi
+
+fi [ $Nome == "Daniela" ] || [ $Nome = "Jose" ]
+then
+ echo "Isso vai rodar se $Nome é Daniela ou Jose."
+fi
+
+# Expressões são denotadas com o seguinte formato
+echo $(( 10 + 5))
+
+# Diferentemente das outras linguagens de programação, bash é um shell, então ele
+# funciona no diretório atual. Você pode listar os arquivos e diretórios no diretório
+# atual com o comando ls:
+ls
+
+#Esse comando tem opções que controlam sua execução
+ls -l # Lista todo arquivo e diretorio em linhas separadas
+
+# Os resultados do comando anterior pode ser passado para outro comando como input.
+# O comando grep filtra o input com o padrão passado. É assim que listamos apenas
+# os arquivos .txt no diretório atual:
+ls -l | grep "\.txt"
+
+# Você pode redirecionar o comando de input e output (stdin, stdout e stderr).
+# Lê o stdin até ^EOF$ e sobrescreve hello.py com as linhas entre "EOF":
+cat > hello.py << EOF
+#!/usr/bin/env python
+from __future__ imprt print_function
+import sys
+print("#stdout", file=sys.stdout)
+print("stderr", file=sys.stderr)
+for line in sys.stdin:
+ print(line, file=sys.stdout)
+EOF
+
+# Rode hello.py com várias instruções stdin, stdout e stderr:
+python hello.py < "input.in"
+python hello.py > "ouput.out"
+python hello.py 2> "error.err"
+python hello.py > "output-and-error.log" 2>&1
+python hello.py > /dev/null 2>&1
+# O erro no output sobrescreverá o arquivo se existir,
+# se ao invés disso você quiser complementar, use ">>":
+python hello.py >> "output.out" 2>> "error.err"
+
+# Sobrescreve output.out, complemente para error.err e conta as linhas
+info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err
+wc -l output.out error.err
+
+#Roda um comando e imprime o desencriptador (e.g. /dev/fd/123)
+# veja: man fd
+echo <(echo "#helloworld")
+
+# Sobrescreve ouput.out com "#helloworld":
+cat > output.out <(echo "#helloworld")
+echo "#helloworld" > output.out
+echo "#helloworld" | cat > output.out
+echo "#helloworld" | tee output.out > /dev/null
+
+# Limpa os arquivos temporarios detalhando quais foram deletados (use '-i' para confirmar exlusão)
+rm -v output.out error.err output-and-error.log
+
+# Comando podem ser substituidos por outros comandos usando $( ):
+# O comand oa seguir mostra o número de arquivos e diretórios no diretorio atual
+echo "Existem $(ls | wc -l) itens aqui."
+
+# O mesmo pode ser feito usando crase `` mas elas não podem ser aninhadas - dá se
+# preferência ao uso do $( )
+echo "Existem `ls | wc -l` itens aqui."
+
+# Bash usa o comando case que funciona de uma maneira similar ao switch de Java e C++:
+case "$Variavel" in
+ # Lista de parametros para condições que você quer encontrar
+ 0) echo "Isso é um Zero.";;
+ 1) echo "Isso é um Um.";;
+ *) echo "Isso não é null.";;
+esac
+
+# loops for iteragem para quantos argumentos passados:
+# O conteudo de $Variavel é exibido três vezes.
+for Variavel in {1..3}
+do
+ echo "$Variavel"
+done
+
+# Ou use o loop da "maneira tradicional":
+for ((a=1; a <= 3; a++))
+do
+ echo $a
+done
+
+# Eles também podem ser usados em arquivos...
+# Isso irá rodar o comando 'cat' em arquivo1 e arquivo2
+for Variavel in arquivo1 arquivo2
+do
+ cat "$Variavel"
+done
+
+# ...ou o output de um comando
+# Isso irá usar cat no output do ls.
+for Output in $(ls)
+do
+ cat "$Output"
+done
+
+# loop while:
+while [ true ]
+do
+ echo "corpo do loop aqui..."
+ break
+done
+
+# Você também pode usar funções
+# Definição:
+function foo() {
+ echo "Argumentos funcionam bem assim como os dos scripts: $@"
+ echo "E: $1 $2..."
+ echo "Isso é uma função"
+ return 0
+}
+
+# ou simplesmente
+bar () {
+ echo "Outro jeito de declarar funções!"
+ return 0
+}
+
+# Chamando sua função
+foo "Meu nome é" $Nome
+
+# Existe um monte de comandos úteis que você deveria aprender:
+# exibe as 10 ultimas linhas de arquivo.txt
+tail -n 10 arquivo.txt
+# exibe as primeiras 10 linhas de arquivo.txt
+head -n 10 arquivo.txt
+# ordena as linhas de arquivo.txt
+sort arquivo.txt
+# reporta ou omite as linhas repetidas, com -d você as reporta
+uniq -d arquivo.txt
+# exibe apenas a primeira coluna após o caráctere ','
+cut -d ',' -f 1 arquivo.txt
+# substitui todas as ocorrencias de 'okay' por 'legal' em arquivo.txt (é compativel com regex)
+sed -i 's/okay/legal/g' file.txt
+# exibe para o stdout todas as linhas do arquivo.txt que encaixam com o regex
+# O exemplo exibe linhas que começam com "foo" e terminam com "bar"
+grep "^foo.*bar$" arquivo.txt
+# passe a opção "-c" para ao invês de imprimir o numero da linha que bate com o regex
+grep -c "^foo.*bar$" arquivo.txt
+# se você quer literalmente procurar por uma string,
+# e não pelo regex, use fgrep (ou grep -F)
+fgrep "^foo.*bar$" arquivo.txt
+
+
+# Leia a documentação interna do shell Bash com o comando interno 'help':
+help
+help help
+help for
+help return
+help source
+help .
+
+# Leia a página principal da documentação com man
+apropos bash
+man 1 bash
+man bash
+
+# Leia a documentação de informação com info (? para ajuda)
+apropos info | grep '^info.*('
+man info
+info info
+info 5 info
+
+#Leia a documentação informativa do Bash:
+info bash
+info bash 'Bash Features'
+info bash 6
+info --apropos bash
+```
diff --git a/pt-br/brainfuck-pt.html.markdown b/pt-br/bf.html.markdown
index 9e4b458d..d6d7c6e9 100644
--- a/pt-br/brainfuck-pt.html.markdown
+++ b/pt-br/bf.html.markdown
@@ -1,5 +1,5 @@
---
-language: brainfuck
+language: bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]
diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown
new file mode 100644
index 00000000..547f4817
--- /dev/null
+++ b/pt-br/csharp.html.markdown
@@ -0,0 +1,896 @@
+---
+language: c#
+filename: csharp-pt.cs
+contributors:
+ - ["Robson Alves", "http://robsonalves.net/"]
+lang: pt-br
+---
+
+C# é uma linguagem elegante e altamente tipado orientada a objetos que permite aos desenvolvedores criarem uma variedade de aplicações seguras e robustas que são executadas no .NET Framework.
+
+[Read more here.](http://msdn.microsoft.com/pt-br/library/vstudio/z1zx9t92.aspx)
+
+```c#
+// Comentário de linha única começa com //
+/*
+Múltipas linhas é desta forma
+*/
+/// <summary>
+/// Esta é uma documentação comentário XML que pode ser usado para gerar externo
+/// documentação ou fornecer ajuda de contexto dentro de um IDE
+/// </summary>
+//public void MethodOrClassOrOtherWithParsableHelp() {}
+
+// Especificar qual namespace seu código irá usar
+// Os namespaces a seguir são padrões do .NET Framework Class Library
+using System;
+using System.Collections.Generic;
+using System.Dynamic;
+using System.Linq;
+using System.Net;
+using System.Threading.Tasks;
+using System.IO;
+
+// Mas este aqui não é :
+using System.Data.Entity;
+// Para que consiga utiliza-lo, você precisa adicionar novas referências
+// Isso pode ser feito com o gerenciador de pacotes NuGet : `Install-Package EntityFramework`
+
+// Namespaces são escopos definidos para organizar o códgo em "pacotes" or "módulos"
+// Usando este código a partir de outra arquivo de origem: using Learning.CSharp;
+namespace Learning.CSharp
+{
+ // Cada .cs deve conter uma classe com o mesmo nome do arquivo
+ // você está autorizado a contrariar isto, mas evite por sua sanidade.
+ public class AprenderCsharp
+ {
+ // Sintaxe Básica - Pule para as CARACTERÍSTICAS INTERESSANTES se você ja usou Java ou C++ antes.
+ public static void Syntax()
+ {
+ // Use Console.WriteLine para apresentar uma linha
+ Console.WriteLine("Hello World");
+ Console.WriteLine(
+ "Integer: " + 10 +
+ " Double: " + 3.14 +
+ " Boolean: " + true);
+
+ // Para apresentar sem incluir uma nova linha, use Console.Write
+ Console.Write("Hello ");
+ Console.Write("World");
+
+ ///////////////////////////////////////////////////
+ // Tpos e Variáveis
+ //
+ // Declare uma variável usando <tipo> <nome>
+ ///////////////////////////////////////////////////
+
+ // Sbyte - Signed 8-bit integer
+ // (-128 <= sbyte <= 127)
+ sbyte fooSbyte = 100;
+
+ // Byte - Unsigned 8-bit integer
+ // (0 <= byte <= 255)
+ byte fooByte = 100;
+
+ // Short - 16-bit integer
+ // Signed - (-32,768 <= short <= 32,767)
+ // Unsigned - (0 <= ushort <= 65,535)
+ short fooShort = 10000;
+ ushort fooUshort = 10000;
+
+ // Integer - 32-bit integer
+ int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647)
+ uint fooUint = 1; // (0 <= uint <= 4,294,967,295)
+
+ // Long - 64-bit integer
+ long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
+ ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615)
+ // Numbers default to being int or uint depending on size.
+ // L is used to denote that this variable value is of type long or ulong
+
+ // Double - Double-precision 64-bit IEEE 754 Floating Point
+ double fooDouble = 123.4; // Precision: 15-16 digits
+
+ // Float - Single-precision 32-bit IEEE 754 Floating Point
+ float fooFloat = 234.5f; // Precision: 7 digits
+ // f is used to denote that this variable value is of type float
+
+ // Decimal - a 128-bits data type, with more precision than other floating-point types,
+ // suited for financial and monetary calculations
+ decimal fooDecimal = 150.3m;
+
+ // Boolean - true & false
+ bool fooBoolean = true; // or false
+
+ // Char - A single 16-bit Unicode character
+ char fooChar = 'A';
+
+ // Strings - ao contrário dos anteriores tipos base, que são todos os tipos de valor,
+            // Uma string é um tipo de referência. Ou seja, você pode configurá-lo como nulo
+ string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)";
+ Console.WriteLine(fooString);
+
+ // Você pode acessar todos os caracteres de string com um indexador:
+ char charFromString = fooString[1]; // => 'e'
+ // Strings são imutáveis: você não pode fazer fooString[1] = 'X';
+
+ // Compare strings com sua atual cultura, ignorando maiúsculas e minúsculas
+ string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase);
+
+ // Formatando, baseado no sprintf
+ string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2);
+
+ // Datas e formatações
+ DateTime fooDate = DateTime.Now;
+ Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy"));
+
+ // Você pode juntar um string em mais de duas linhas com o símbolo @. Para escapar do " use ""
+ string bazString = @"Here's some stuff
+on a new line! ""Wow!"", the masses cried";
+
+ // Use const ou read-only para fazer uma variável imutável
+ // os valores da const são calculados durante o tempo de compilação
+ const int HoursWorkPerWeek = 9001;
+
+ ///////////////////////////////////////////////////
+ // Estrutura de Dados
+ ///////////////////////////////////////////////////
+
+ // Matrizes - zero indexado
+ // O tamanho do array pode ser decidido ainda na declaração
+ // O formato para declarar uma matriz é o seguinte:
+ // <tipodado>[] <var nome> = new <tipodado>[<array tamanho>];
+ int[] intArray = new int[10];
+
+ // Outra forma de declarar & inicializar uma matriz
+ int[] y = { 9000, 1000, 1337 };
+
+ // Indexando uma matriz - Acessando um elemento
+ Console.WriteLine("intArray @ 0: " + intArray[0]);
+ // Matriz são alteráveis
+ intArray[1] = 1;
+
+ // Listas
+ // Listas são usadas frequentemente tanto quanto matriz por serem mais flexiveis
+ // O formato de declarar uma lista é o seguinte:
+ // List<tipodado> <var nome> = new List<tipodado>();
+ List<int> intList = new List<int>();
+ List<string> stringList = new List<string>();
+ List<int> z = new List<int> { 9000, 1000, 1337 }; // inicializar
+ // O <> são para genéricos - Confira está interessante seção do material
+
+ // Lista não possuem valores padrão.
+ // Um valor deve ser adicionado antes e depois acessado pelo indexador
+ intList.Add(1);
+ Console.WriteLine("intList @ 0: " + intList[0]);
+
+ // Outras estruturas de dados para conferir:
+ // Pilha/Fila
+ // Dicionário (uma implementação de map de hash)
+ // HashSet
+ // Read-only Coleção
+ // Tuple (.Net 4+)
+
+ ///////////////////////////////////////
+ // Operadores
+ ///////////////////////////////////////
+ Console.WriteLine("\n->Operators");
+
+ int i1 = 1, i2 = 2; // Forma curta para declarar diversas variáveis
+
+ // Aritmética é clara
+ Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3
+
+ // Modulo
+ Console.WriteLine("11%3 = " + (11 % 3)); // => 2
+
+ // Comparações de operadores
+ Console.WriteLine("3 == 2? " + (3 == 2)); // => falso
+ Console.WriteLine("3 != 2? " + (3 != 2)); // => verdadeiro
+ Console.WriteLine("3 > 2? " + (3 > 2)); // => verdadeiro
+ Console.WriteLine("3 < 2? " + (3 < 2)); // => falso
+ Console.WriteLine("2 <= 2? " + (2 <= 2)); // => verdadeiro
+ Console.WriteLine("2 >= 2? " + (2 >= 2)); // => verdadeiro
+
+ // Operadores bit a bit (bitwise)
+ /*
+ ~ Unário bitwise complemento
+ << Signed left shift
+ >> Signed right shift
+ & Bitwise AND
+ ^ Bitwise exclusivo OR
+ | Bitwise inclusivo OR
+ */
+
+ // Incrementações
+ int i = 0;
+ Console.WriteLine("\n->Inc/Dec-rementation");
+ Console.WriteLine(i++); //i = 1. Post-Incrementation
+ Console.WriteLine(++i); //i = 2. Pre-Incrementation
+ Console.WriteLine(i--); //i = 1. Post-Decrementation
+ Console.WriteLine(--i); //i = 0. Pre-Decrementation
+
+ ///////////////////////////////////////
+ // Estrutura de Controle
+ ///////////////////////////////////////
+ Console.WriteLine("\n->Control Structures");
+
+ // Declaração if é como a linguagem C
+ int j = 10;
+ if (j == 10)
+ {
+ Console.WriteLine("I get printed");
+ }
+ else if (j > 10)
+ {
+ Console.WriteLine("I don't");
+ }
+ else
+ {
+ Console.WriteLine("I also don't");
+ }
+
+ // Operador Ternário
+ // Um simples if/else pode ser escrito da seguinte forma
+ // <condição> ? <verdadeiro> : <falso>
+ int toCompare = 17;
+ string isTrue = toCompare == 17 ? "True" : "False";
+
+ // While loop
+ int fooWhile = 0;
+ while (fooWhile < 100)
+ {
+ //Iterated 100 times, fooWhile 0->99
+ fooWhile++;
+ }
+
+ // Do While Loop
+ int fooDoWhile = 0;
+ do
+ {
+ // Inicia a interação 100 vezes, fooDoWhile 0->99
+ if (false)
+ continue; // pule a intereção atual para apróxima
+
+ fooDoWhile++;
+
+ if (fooDoWhile == 50)
+ break; // Interrompe o laço inteiro
+
+ } while (fooDoWhile < 100);
+
+ //estrutura de loop for => for(<declaração para começar>; <condicional>; <passos>)
+ for (int fooFor = 0; fooFor < 10; fooFor++)
+ {
+ //Iterado 10 vezes, fooFor 0->9
+ }
+
+ // For Each Loop
+ // Estrutura do foreach => foreach(<Tipo Iterador> <Nome do Iterador> in <enumerable>)
+ // O laço foreach percorre sobre qualquer objeto que implementa IEnumerable ou IEnumerable<T>
+ // Toda a coleção de tipos (Array, List, Dictionary...) no .Net framework
+ // implementa uma ou mais destas interfaces.
+ // (O ToCharArray() pode ser removido, por que uma string também implementa IEnumerable)
+ foreach (char character in "Hello World".ToCharArray())
+ {
+ //Iterated over all the characters in the string
+ }
+
+ // Switch Case
+ // Um switch funciona com os tipos de dados byte, short, char, e int.
+ // Isto também funcional com tipos enumeradors (discutidos em Tipos Enum),
+ // A classe String, and a few special classes that wrap
+ // tipos primitívos: Character, Byte, Short, and Integer.
+ int month = 3;
+ string monthString;
+ switch (month)
+ {
+ case 1:
+ monthString = "January";
+ break;
+ case 2:
+ monthString = "February";
+ break;
+ case 3:
+ monthString = "March";
+ break;
+ // You can assign more than one case to an action
+ // But you can't add an action without a break before another case
+ // (if you want to do this, you would have to explicitly add a goto case x
+ case 6:
+ case 7:
+ case 8:
+ monthString = "Summer time!!";
+ break;
+ default:
+ monthString = "Some other month";
+ break;
+ }
+
+ ///////////////////////////////////////
+ // Converting Data Types And Typecasting
+ ///////////////////////////////////////
+
+ // Converting data
+
+ // Convert String To Integer
+ // this will throw a FormatException on failure
+ int.Parse("123");//returns an integer version of "123"
+
+ // try parse will default to type default on failure
+ // in this case: 0
+ int tryInt;
+ if (int.TryParse("123", out tryInt)) // Function is boolean
+ Console.WriteLine(tryInt); // 123
+
+ // Convert Integer To String
+ // Convert class has a number of methods to facilitate conversions
+ Convert.ToString(123);
+ // or
+ tryInt.ToString();
+
+ // Casting
+ // Cast decimal 15 to a int
+ // and then implicitly cast to long
+ long x = (int) 15M;
+ }
+
+ ///////////////////////////////////////
+ // CLASSES - see definitions at end of file
+ ///////////////////////////////////////
+ public static void Classes()
+ {
+ // See Declaration of objects at end of file
+
+ // Use new to instantiate a class
+ Bicycle trek = new Bicycle();
+
+ // Call object methods
+ trek.SpeedUp(3); // You should always use setter and getter methods
+ trek.Cadence = 100;
+
+ // ToString is a convention to display the value of this Object.
+ Console.WriteLine("trek info: " + trek.Info());
+
+ // Instantiate a new Penny Farthing
+ PennyFarthing funbike = new PennyFarthing(1, 10);
+ Console.WriteLine("funbike info: " + funbike.Info());
+
+ Console.Read();
+ } // End main method
+
+ // CONSOLE ENTRY A console application must have a main method as an entry point
+ public static void Main(string[] args)
+ {
+ OtherInterestingFeatures();
+ }
+
+ //
+ // INTERESTING FEATURES
+ //
+
+ // DEFAULT METHOD SIGNATURES
+
+ public // Visibility
+ static // Allows for direct call on class without object
+ int // Return Type,
+ MethodSignatures(
+ int maxCount, // First variable, expects an int
+ int count = 0, // will default the value to 0 if not passed in
+ int another = 3,
+ params string[] otherParams // captures all other parameters passed to method
+ )
+ {
+ return -1;
+ }
+
+ // Methods can have the same name, as long as the signature is unique
+ // A method that differs only in return type is not unique
+ public static void MethodSignatures(
+ ref int maxCount, // Pass by reference
+ out int count)
+ {
+ count = 15; // out param must be assigned before control leaves the method
+ }
+
+ // GENERICS
+ // The classes for TKey and TValue is specified by the user calling this function.
+ // This method emulates the SetDefault of Python
+ public static TValue SetDefault<TKey, TValue>(
+ IDictionary<TKey, TValue> dictionary,
+ TKey key,
+ TValue defaultItem)
+ {
+ TValue result;
+ if (!dictionary.TryGetValue(key, out result))
+ return dictionary[key] = defaultItem;
+ return result;
+ }
+
+ // You can narrow down the objects that are passed in
+ public static void IterateAndPrint<T>(T toPrint) where T: IEnumerable<int>
+ {
+ // We can iterate, since T is a IEnumerable
+ foreach (var item in toPrint)
+ // Item is an int
+ Console.WriteLine(item.ToString());
+ }
+
+ public static void OtherInterestingFeatures()
+ {
+ // OPTIONAL PARAMETERS
+ MethodSignatures(3, 1, 3, "Some", "Extra", "Strings");
+ MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones
+
+ // BY REF AND OUT PARAMETERS
+ int maxCount = 0, count; // ref params must have value
+ MethodSignatures(ref maxCount, out count);
+
+ // EXTENSION METHODS
+ int i = 3;
+ i.Print(); // Defined below
+
+ // NULLABLE TYPES - great for database interaction / return values
+ // any value type (i.e. not a class) can be made nullable by suffixing a ?
+ // <type>? <var name> = <value>
+ int? nullable = null; // short hand for Nullable<int>
+ Console.WriteLine("Nullable variable: " + nullable);
+ bool hasValue = nullable.HasValue; // true if not null
+
+ // ?? is syntactic sugar for specifying default value (coalesce)
+ // in case variable is null
+ int notNullable = nullable ?? 0; // 0
+
+ // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is:
+ var magic = "magic is a string, at compile time, so you still get type safety";
+ // magic = 9; will not work as magic is a string, not an int
+
+ // GENERICS
+ //
+ var phonebook = new Dictionary<string, string>() {
+ {"Sarah", "212 555 5555"} // Add some entries to the phone book
+ };
+
+ // Calling SETDEFAULT defined as a generic above
+ Console.WriteLine(SetDefault<string,string>(phonebook, "Shaun", "No Phone")); // No Phone
+ // nb, you don't need to specify the TKey and TValue since they can be
+ // derived implicitly
+ Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555
+
+ // LAMBDA EXPRESSIONS - allow you to write code in line
+ Func<int, int> square = (x) => x * x; // Last T item is the return value
+ Console.WriteLine(square(3)); // 9
+
+ // ERROR HANDLING - coping with an uncertain world
+ try
+ {
+ var funBike = PennyFarthing.CreateWithGears(6);
+
+ // will no longer execute because CreateWithGears throws an exception
+ string some = "";
+ if (true) some = null;
+ some.ToLower(); // throws a NullReferenceException
+ }
+ catch (NotSupportedException)
+ {
+ Console.WriteLine("Not so much fun now!");
+ }
+ catch (Exception ex) // catch all other exceptions
+ {
+ throw new ApplicationException("It hit the fan", ex);
+ // throw; // A rethrow that preserves the callstack
+ }
+ // catch { } // catch-all without capturing the Exception
+ finally
+ {
+ // executes after try or catch
+ }
+
+ // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily.
+ // Most of objects that access unmanaged resources (file handle, device contexts, etc.)
+ // implement the IDisposable interface. The using statement takes care of
+ // cleaning those IDisposable objects for you.
+ using (StreamWriter writer = new StreamWriter("log.txt"))
+ {
+ writer.WriteLine("Nothing suspicious here");
+ // At the end of scope, resources will be released.
+ // Even if an exception is thrown.
+ }
+
+ // 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())
+ {
+ responses[website] = r.ContentType;
+ }
+ });
+
+ // This won't happen till after all requests have been completed
+ foreach (var key in responses.Keys)
+ Console.WriteLine("{0}:{1}", key, responses[key]);
+
+ // DYNAMIC OBJECTS (great for working with other languages)
+ dynamic student = new ExpandoObject();
+ student.FirstName = "First Name"; // No need to define class first!
+
+ // You can even add methods (returns a string, and takes in a string)
+ student.Introduce = new Func<string, string>(
+ (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo));
+ Console.WriteLine(student.Introduce("Beth"));
+
+ // IQUERYABLE<T> - almost all collections implement this, which gives you a lot of
+ // very useful Map / Filter / Reduce style methods
+ var bikes = new List<Bicycle>();
+ bikes.Sort(); // Sorts the array
+ bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Sorts based on wheels
+ var result = bikes
+ .Where(b => b.Wheels > 3) // Filters - chainable (returns IQueryable of previous type)
+ .Where(b => b.IsBroken && b.HasTassles)
+ .Select(b => b.ToString()); // Map - we only this selects, so result is a IQueryable<string>
+
+ var sum = bikes.Sum(b => b.Wheels); // Reduce - sums all the wheels in the collection
+
+ // Create a list of IMPLICIT objects based on some parameters of the bike
+ var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles });
+ // Hard to show here, but you get type ahead completion since the compiler can implicitly work
+ // out the types above!
+ foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome))
+ Console.WriteLine(bikeSummary.Name);
+
+ // ASPARALLEL
+ // And this is where things get wicked - combines linq and parallel operations
+ var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name);
+ // this will happen in parallel! Threads will automagically be spun up and the
+ // results divvied amongst them! Amazing for large datasets when you have lots of
+ // cores
+
+ // LINQ - maps a store to IQueryable<T> objects, with delayed execution
+ // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document
+ var db = new BikeRepository();
+
+ // execution is delayed, which is great when querying a database
+ var filter = db.Bikes.Where(b => b.HasTassles); // no query run
+ if (42 > 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality
+ filter = filter.Where(b => b.IsBroken); // no query run
+
+ var query = filter
+ .OrderBy(b => b.Wheels)
+ .ThenBy(b => b.Name)
+ .Select(b => b.Name); // still no query run
+
+ // Now the query runs, but opens a reader, so only populates are you iterate through
+ foreach (string bike in query)
+ Console.WriteLine(result);
+
+
+
+ }
+
+ } // End LearnCSharp class
+
+ // You can include other classes in a .cs file
+
+ public static class Extensions
+ {
+ // EXTENSION FUNCTIONS
+ public static void Print(this object obj)
+ {
+ Console.WriteLine(obj.ToString());
+ }
+ }
+
+ // Class Declaration Syntax:
+ // <public/private/protected/internal> class <class name>{
+ // //data fields, constructors, functions all inside.
+ // //functions are called as methods in Java.
+ // }
+
+ public class Bicycle
+ {
+ // Bicycle's Fields/Variables
+ public int Cadence // Public: Can be accessed from anywhere
+ {
+ get // get - define a method to retrieve the property
+ {
+ return _cadence;
+ }
+ set // set - define a method to set a proprety
+ {
+ _cadence = value; // Value is the value passed in to the setter
+ }
+ }
+ private int _cadence;
+
+ protected virtual int Gear // Protected: Accessible from the class and subclasses
+ {
+ get; // creates an auto property so you don't need a member field
+ set;
+ }
+
+ internal int Wheels // Internal: Accessible from within the assembly
+ {
+ get;
+ private set; // You can set modifiers on the get/set methods
+ }
+
+ int _speed; // Everything is private by default: Only accessible from within this class.
+ // can also use keyword private
+ public string Name { get; set; }
+
+ // 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).
+ // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
+ // An enum can't contain the same value twice.
+ public enum BikeBrand
+ {
+ AIST,
+ BMC,
+ Electra = 42, //you can explicitly set a value to a name
+ Gitane // 43
+ }
+ // We defined this type inside a Bicycle class, so it is a nested type
+ // Code outside of this class should reference this type as Bicycle.Brand
+
+ public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type
+
+ // Decorate an enum with the FlagsAttribute to indicate that multiple values can be switched on
+ [Flags] // Any class derived from Attribute can be used to decorate types, methods, parameters etc
+ public enum BikeAccessories
+ {
+ None = 0,
+ Bell = 1,
+ MudGuards = 2, // need to set the values manually!
+ Racks = 4,
+ Lights = 8,
+ FullPackage = Bell | MudGuards | Racks | Lights
+ }
+
+ // Usage: aBike.Accessories.HasFlag(Bicycle.BikeAccessories.Bell)
+ // Before .NET 4: (aBike.Accessories & Bicycle.BikeAccessories.Bell) == Bicycle.BikeAccessories.Bell
+ public BikeAccessories Accessories { get; set; }
+
+ // Static members belong to the type itself rather then specific object.
+ // You can access them without a reference to any object:
+ // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated);
+ public static int BicyclesCreated { get; set; }
+
+ // readonly values are set at run time
+ // they can only be assigned upon declaration or in a constructor
+ readonly bool _hasCardsInSpokes = false; // read-only private
+
+ // Constructors are a way of creating classes
+ // This is a default constructor
+ public Bicycle()
+ {
+ this.Gear = 1; // you can access members of the object with the keyword this
+ Cadence = 50; // but you don't always need it
+ _speed = 5;
+ Name = "Bontrager";
+ Brand = BikeBrand.AIST;
+ BicyclesCreated++;
+ }
+
+ // This is a specified constructor (it contains arguments)
+ public Bicycle(int startCadence, int startSpeed, int startGear,
+ string name, bool hasCardsInSpokes, BikeBrand brand)
+ : base() // calls base first
+ {
+ Gear = startGear;
+ Cadence = startCadence;
+ _speed = startSpeed;
+ Name = name;
+ _hasCardsInSpokes = hasCardsInSpokes;
+ Brand = brand;
+ }
+
+ // Constructors can be chained
+ public Bicycle(int startCadence, int startSpeed, BikeBrand brand) :
+ this(startCadence, startSpeed, 0, "big wheels", true, brand)
+ {
+ }
+
+ // Function Syntax:
+ // <public/private/protected> <return type> <function name>(<args>)
+
+ // classes can implement getters and setters for their fields
+ // or they can implement properties (this is the preferred way in C#)
+
+ // Method parameters can have default values.
+ // In this case, methods can be called with these parameters omitted
+ public void SpeedUp(int increment = 1)
+ {
+ _speed += increment;
+ }
+
+ public void SlowDown(int decrement = 1)
+ {
+ _speed -= decrement;
+ }
+
+ // properties get/set values
+ // when only data needs to be accessed, consider using properties.
+ // properties may have either get or set, or both
+ private bool _hasTassles; // private variable
+ public bool HasTassles // public accessor
+ {
+ get { return _hasTassles; }
+ set { _hasTassles = value; }
+ }
+
+ // You can also define an automatic property in one line
+ // this syntax will create a backing field automatically.
+ // You can set an access modifier on either the getter or the setter (or both)
+ // to restrict its access:
+ public bool IsBroken { get; private set; }
+
+ // Properties can be auto-implemented
+ public int FrameSize
+ {
+ get;
+ // you are able to specify access modifiers for either get or set
+ // this means only Bicycle class can call set on Framesize
+ private set;
+ }
+
+ // It's also possible to define custom Indexers on objects.
+ // All though this is not entirely useful in this example, you
+ // could do bicycle[0] which yields "chris" to get the first passenger or
+ // bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle)
+ private string[] passengers = { "chris", "phil", "darren", "regina" };
+
+ public string this[int i]
+ {
+ get {
+ return passengers[i];
+ }
+
+ set {
+ return passengers[i] = value;
+ }
+ }
+
+ //Method to display the attribute values of this Object.
+ public virtual string Info()
+ {
+ return "Gear: " + Gear +
+ " Cadence: " + Cadence +
+ " Speed: " + _speed +
+ " Name: " + Name +
+ " Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") +
+ "\n------------------------------\n"
+ ;
+ }
+
+ // Methods can also be static. It can be useful for helper methods
+ public static bool DidWeCreateEnoughBycles()
+ {
+ // Within a static method, we only can reference static class members
+ return BicyclesCreated > 9000;
+ } // If your class only needs static members, consider marking the class itself as static.
+
+
+ } // end class Bicycle
+
+ // PennyFarthing is a subclass of Bicycle
+ class PennyFarthing : Bicycle
+ {
+ // (Penny Farthings are those bicycles with the big front wheel.
+ // They have no gears.)
+
+ // calling parent constructor
+ public PennyFarthing(int startCadence, int startSpeed) :
+ base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra)
+ {
+ }
+
+ protected override int Gear
+ {
+ get
+ {
+ return 0;
+ }
+ set
+ {
+ throw new InvalidOperationException("You can't change gears on a PennyFarthing");
+ }
+ }
+
+ public static PennyFarthing CreateWithGears(int gears)
+ {
+ var penny = new PennyFarthing(1, 1);
+ penny.Gear = gears; // Oops, can't do this!
+ return penny;
+ }
+
+ public override string Info()
+ {
+ string result = "PennyFarthing bicycle ";
+ result += base.ToString(); // Calling the base version of the method
+ return result;
+ }
+ }
+
+ // Interfaces only contain signatures of the members, without the implementation.
+ interface IJumpable
+ {
+ void Jump(int meters); // all interface members are implicitly public
+ }
+
+ interface IBreakable
+ {
+ bool Broken { get; } // interfaces can contain properties as well as methods & events
+ }
+
+ // Class can inherit only one other class, but can implement any amount of interfaces
+ class MountainBike : Bicycle, IJumpable, IBreakable
+ {
+ int damage = 0;
+
+ public void Jump(int meters)
+ {
+ damage += meters;
+ }
+
+ public bool Broken
+ {
+ get
+ {
+ return damage > 100;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Used to connect to DB for LinqToSql example.
+ /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional)
+ /// http://msdn.microsoft.com/en-us/data/jj193542.aspx
+ /// </summary>
+ public class BikeRepository : DbContext
+ {
+ public BikeRepository()
+ : base()
+ {
+ }
+
+ public DbSet<Bicycle> Bikes { get; set; }
+ }
+} // End Namespace
+```
+
+## Topics Not Covered
+
+ * Attributes
+ * async/await, yield, pragma directives
+ * Web Development
+ * ASP.NET MVC & WebApi (new)
+ * ASP.NET Web Forms (old)
+ * WebMatrix (tool)
+ * Desktop Development
+ * Windows Presentation Foundation (WPF) (new)
+ * Winforms (old)
+
+## Further Reading
+
+ * [DotNetPerls](http://www.dotnetperls.com)
+ * [C# in Depth](http://manning.com/skeet2)
+ * [Programming C#](http://shop.oreilly.com/product/0636920024064.do)
+ * [LINQ](http://shop.oreilly.com/product/9780596519254.do)
+ * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx)
+ * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials)
+ * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials)
+ * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials)
+ * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208)
+ * [C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx)
diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown
index 981da503..ea3570d6 100644
--- a/pt-br/git-pt.html.markdown
+++ b/pt-br/git-pt.html.markdown
@@ -5,8 +5,12 @@ lang: pt-br
filename: LearnGit.txt
contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
+ - ["Leo Rudberg" , "http://github.com/LOZORD"]
+ - ["Betsy Lorton" , "http://github.com/schbetsy"]
+ - ["Bruno Volcov", "http://github.com/volcov"]
translators:
- ["Suzane Sant Ana", "http://github.com/suuuzi"]
+ - ["Bruno Volcov", "http://github.com/volcov"]
---
Git é um sistema distribuido de gestão para código fonte e controle de versões.
@@ -84,6 +88,11 @@ Um *branch* é essencialmente uma referência que aponta para o último *commit*
efetuado. Na medida que são feitos novos commits, esta referência é atualizada
automaticamente e passa a apontar para o commit mais recente.
+### *Tag*
+
+Uma tag é uma marcação em um ponto específico da história. Geralmente as
+pessoas usam esta funcionalidade para marcar pontos de release (v2.0, e por aí vai)
+
### *HEAD* e *head* (componentes do diretório .git)
*HEAD* é a referência que aponta para o *branch* em uso. Um repositório só tem
@@ -196,6 +205,29 @@ $ git branch -m myBranchName myNewBranchName
$ git branch myBranchName --edit-description
```
+### Tag
+
+Gerencia as *tags*
+
+```bash
+# Listar tags
+$ git tag
+# Criar uma tag anotada.
+# O parâmetro -m define uma mensagem, que é armazenada com a tag.
+# Se você não especificar uma mensagem para uma tag anotada,
+# o Git vai rodar seu editor de texto para você digitar alguma coisa.
+$ git tag -a v2.0 -m 'minha versão 2.0'
+# Mostrar informações sobre a tag
+# O comando mostra a informação da pessoa que criou a tag,
+# a data de quando o commit foi taggeado,
+# e a mensagem antes de mostrar a informação do commit.
+$ git show v2.0
+# Enviar uma tag para o repositório remoto
+$ git push origin v2.0
+# Enviar várias tags para o repositório remoto
+$ git push origin --tags
+```
+
### checkout
Atualiza todos os arquivos no diretório do projeto para que fiquem iguais
diff --git a/pt-br/hy-pt.html.markdown b/pt-br/hy-pt.html.markdown
index 4230579d..5fa4df75 100644
--- a/pt-br/hy-pt.html.markdown
+++ b/pt-br/hy-pt.html.markdown
@@ -171,6 +171,6 @@ Este tutorial é apenas uma introdução básica para hy/lisp/python.
Docs Hy: [http://hy.readthedocs.org](http://hy.readthedocs.org)
-Repo Hy no Github: [http://github.com/hylang/hy](http://github.com/hylang/hy)
+Repo Hy no GitHub: [http://github.com/hylang/hy](http://github.com/hylang/hy)
Acesso ao freenode irc com #hy, hashtag no twitter: #hylang
diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown
index 3c9512aa..db087a5f 100644
--- a/pt-br/java-pt.html.markdown
+++ b/pt-br/java-pt.html.markdown
@@ -214,42 +214,42 @@ public class LearnJava {
//Iteração feita 10 vezes, fooFor 0->9
}
System.out.println("Valor do fooFor: " + fooFor);
-
- // O Loop For Each
+
+ // O Loop For Each
// Itera automaticamente por um array ou lista de objetos.
int[] fooList = {1,2,3,4,5,6,7,8,9};
//estrutura do loop for each => for(<objeto> : <array_de_objeto>)
//lê-se: para cada objeto no array
//nota: o tipo do objeto deve ser o mesmo do array.
-
+
for( int bar : fooList ){
//System.out.println(bar);
//Itera 9 vezes e imprime 1-9 em novas linhas
}
-
+
// Switch
// Um switch funciona com os tipos de dados: byte, short, char e int
// Ele também funciona com tipos enumerados (vistos em tipos Enum)
// como também a classe String e algumas outras classes especiais
// tipos primitivos: Character, Byte, Short e Integer
- int mes = 3;
- String mesString;
- switch (mes){
+ int mes = 3;
+ String mesString;
+ switch (mes){
case 1:
- mesString = "Janeiro";
+ mesString = "Janeiro";
break;
case 2:
- mesString = "Fevereiro";
+ mesString = "Fevereiro";
break;
case 3:
- mesString = "Março";
+ mesString = "Março";
break;
default:
- mesString = "Algum outro mês";
+ mesString = "Algum outro mês";
break;
}
System.out.println("Resultado do Switch: " + mesString);
-
+
// Condição de forma abreviada.
// Você pode usar o operador '?' para atribuições rápidas ou decisões lógicas.
// Lê-se "Se (declaração) é verdadeira, use <primeiro valor>
@@ -287,9 +287,9 @@ public class LearnJava {
// Classes e Métodos
///////////////////////////////////////
- System.out.println("\n->Classes e Métodos");
+ System.out.println("\n->Classes e Métodos");
- // (segue a definição da classe Bicicleta)
+ // (segue a definição da classe Bicicleta)
// Use o new para instanciar uma classe
Bicicleta caloi = new Bicicleta(); // Objeto caloi criado.
@@ -318,9 +318,9 @@ class Bicicleta {
// Atributos/Variáveis da classe Bicicleta.
public int ritmo; // Public: Pode ser acessada em qualquer lugar.
- private int velocidade; // Private: Apenas acessível a classe.
+ private int velocidade; // Private: Apenas acessível a classe.
protected int catraca; // Protected: Acessível a classe e suas subclasses.
- String nome; // default: Apenas acessível ao pacote.
+ String nome; // default: Apenas acessível ao pacote.
// Construtores são uma forma de criação de classes
// Este é o construtor padrão.
@@ -388,7 +388,7 @@ class Bicicleta {
// Velocipede é uma subclasse de bicicleta.
class Velocipede extends Bicicleta {
// (Velocípedes são bicicletas com rodas dianteiras grandes
- // Elas não possuem catraca.)
+ // Elas não possuem catraca.)
public Velocipede(int ritmoInicial, int velocidadeInicial){
// Chame o construtor do pai (construtor de Bicicleta) com o comando super.
@@ -626,11 +626,11 @@ Os links fornecidos aqui abaixo são apenas para ter uma compreensão do tema, u
Outros tópicos para pesquisar:
-* [Tutorial Java para Sun Trail / Oracle](http://docs.oracle.com/javase/tutorial/index.html)
+* [Tutorial Java para Sun Trail / Oracle](http://docs.oracle.com/javase/tutorial/index.html)
* [Modificadores de acesso do Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
-* [Coceitos de Programação Orientada à Objetos](http://docs.oracle.com/javase/tutorial/java/concepts/index.html):
+* [Coceitos de Programação Orientada à Objetos](http://docs.oracle.com/javase/tutorial/java/concepts/index.html):
* [Herança](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)
* [Polimorfismo](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html)
* [Abstração](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
@@ -646,3 +646,9 @@ Outros tópicos para pesquisar:
Livros:
* [Use a cabeça, Java] (http://www.headfirstlabs.com/books/hfjava/)
+
+Apostila:
+
+* [Java e Orientação a Objetos] (http://www.caelum.com.br/apostila-java-orientacao-objetos/)
+
+* [Java para Desenvolvimento Web] (https://www.caelum.com.br/apostila-java-web/)
diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown
index 6424214e..59c6890e 100644
--- a/pt-br/javascript-pt.html.markdown
+++ b/pt-br/javascript-pt.html.markdown
@@ -519,13 +519,13 @@ if (Object.create === undefined){ // Não o sobrescreve se já existir
## Leitura Adicional
O [Mozilla Developer
-Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) dispõe de uma
+Network](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript) dispõe de uma
excelente documentação sobre Javascript e seu uso nos browsers. E mais,
é uma wiki, portanto conforme você vai aprendendo, mais você pode ir ajudando
os outros compartilhando do seu conhecimento.
[Uma re-introdução do JavaScript pela MDN]
-(https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
+(https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
cobre muito dos conceitos abordados aqui em mais detalhes. Este guia fala
somente sobre a linguagem JavaScript em si; se você quiser aprender mais
sobre e como usar o JavaScript em páginas na web, comece aprendendo sobre
@@ -542,5 +542,5 @@ profundo de todas as partes do JavaScript.
/ livro de referência.
Parte desse artigo foi adaptado do tutorial de Python do Louie Dinh que está
-nesse site e do [Tutorial de JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
+nesse site e do [Tutorial de JS](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
da Mozilla Developer Network.
diff --git a/pt-br/markdown-pt.html.markdown b/pt-br/markdown-pt.html.markdown
index 4030ce3c..f22093f9 100644
--- a/pt-br/markdown-pt.html.markdown
+++ b/pt-br/markdown-pt.html.markdown
@@ -56,7 +56,7 @@ __E este também está._
*--Danouse! Este também__*
<!-- Em GitHub Flavored Markdown, que é usado para processar arquivos Markdown
-Github, nós também temos: -->
+GitHub, nós também temos: -->
~~Este texto é processado com tachado.~~
@@ -148,7 +148,7 @@ dentro do seu código -->
John não sabia nem o que o função 'goto()' fazia!
-<!-- Em Github Flavored Markdown, você pode usar uma sintaxe especial para o código -->
+<!-- Em GitHub Flavored Markdown, você pode usar uma sintaxe especial para o código -->
\`\`\`ruby <!-- exceto remover essas barras invertidas quando você faz isso, apenas ```
ruby! -->
@@ -157,7 +157,7 @@ def foobar
end
\`\`\` <!-- Aqui também, não barras invertidas, apenas ``` -->
-<-- O texto acima não requer recuo, mas o Github vai usar a sintaxe
+<-- O texto acima não requer recuo, mas o GitHub vai usar a sintaxe
destacando do idioma que você especificar após a ``` -->
<!-- Regra Horizontal (<hr />) -->
@@ -230,7 +230,7 @@ Quero digitar * Este texto entre asteriscos *, mas eu não quero que ele seja
em itálico, então eu faço o seguinte: \*Este texto entre asteriscos \*.
<!-- Tabelas -->
-<!-- Tabelas estão disponíveis apenas no Github Flavored Markdown e são ligeiramente
+<!-- Tabelas estão disponíveis apenas no GitHub Flavored Markdown e são ligeiramente
complicadas, mas se você realmente quer: -->
| Col1 | Col2 | Col3 |
diff --git a/pt-br/paren-pt.html.markdown b/pt-br/paren-pt.html.markdown
new file mode 100644
index 00000000..464a69d2
--- /dev/null
+++ b/pt-br/paren-pt.html.markdown
@@ -0,0 +1,196 @@
+---
+language: Paren
+filename: learnparen-pt.paren
+contributors:
+ - ["KIM Taegyoon", "https://github.com/kimtg"]
+translators:
+ - ["Claudson Martins", "https://github.com/claudsonm"]
+lang: pt-br
+---
+
+[Paren](https://bitbucket.org/ktg/paren) é um dialeto do Lisp. É projetado para ser uma linguagem embutida.
+
+Alguns exemplos foram retirados de <http://learnxinyminutes.com/docs/racket/>.
+
+```scheme
+;;; Comentários
+# Comentários
+
+;; Comentários de única linha começam com um ponto e vírgula ou cerquilha
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 1. Tipos de Dados Primitivos e Operadores
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;;; Números
+123 ; inteiro
+3.14 ; double
+6.02e+23 ; double
+(int 3.14) ; => 3 : inteiro
+(double 123) ; => 123 : double
+
+;; O uso de funções é feito da seguinte maneira (f x y z ...)
+;; onde f é uma função e x, y, z, ... são os operandos
+;; Se você quiser criar uma lista literal de dados, use (quote) para impedir
+;; que sejam interpretados
+(quote (+ 1 2)) ; => (+ 1 2)
+;; Agora, algumas operações aritméticas
+(+ 1 1) ; => 2
+(- 8 1) ; => 7
+(* 10 2) ; => 20
+(^ 2 3) ; => 8
+(/ 5 2) ; => 2
+(% 5 2) ; => 1
+(/ 5.0 2) ; => 2.5
+
+;;; Booleanos
+true ; para verdadeiro
+false ; para falso
+(! true) ; => falso
+(&& true false (prn "não chega aqui")) ; => falso
+(|| false true (prn "não chega aqui")) ; => verdadeiro
+
+;;; Caracteres são inteiros.
+(char-at "A" 0) ; => 65
+(chr 65) ; => "A"
+
+;;; Strings são arrays de caracteres de tamanho fixo.
+"Olá, mundo!"
+"Sebastião \"Tim\" Maia" ; Contra-barra é um caractere de escape
+"Foo\tbar\r\n" ; Inclui os escapes da linguagem C: \t \r \n
+
+;; Strings podem ser concatenadas também!
+(strcat "Olá " "mundo!") ; => "Olá mundo!"
+
+;; Uma string pode ser tratada como uma lista de caracteres
+(char-at "Abacaxi" 0) ; => 65
+
+;; A impressão é muito fácil
+(pr "Isso é" "Paren. ") (prn "Prazer em conhecê-lo!")
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 2. Variáveis
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; Você pode criar ou definir uma variável usando (set)
+;; o nome de uma variável pode conter qualquer caracter, exceto: ();#"
+(set alguma-variavel 5) ; => 5
+alguma-variavel ; => 5
+
+;; Acessar uma variável ainda não atribuída gera uma exceção
+; x ; => Unknown variable: x : nil
+
+;; Ligações locais: Utiliza cálculo lambda!
+;; 'a' e 'b' estão ligados a '1' e '2' apenas dentro de (fn ...)
+((fn (a b) (+ a b)) 1 2) ; => 3
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 3. Coleções
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;;; Listas
+
+;; Listas são estruturas de dados semelhantes a vetores. (A classe de comportamento é O(1).)
+(cons 1 (cons 2 (cons 3 (list)))) ; => (1 2 3)
+;; 'list' é uma variação conveniente para construir listas
+(list 1 2 3) ; => (1 2 3)
+;; Um quote também pode ser usado para uma lista de valores literais
+(quote (+ 1 2)) ; => (+ 1 2)
+
+;; Você ainda pode utilizar 'cons' para adicionar um item ao início da lista
+(cons 0 (list 1 2 3)) ; => (0 1 2 3)
+
+;; Listas são um tipo muito básico, portanto existe *enorme* funcionalidade
+;; para elas, veja alguns exemplos:
+(map inc (list 1 2 3)) ; => (2 3 4)
+(filter (fn (x) (== 0 (% x 2))) (list 1 2 3 4)) ; => (2 4)
+(length (list 1 2 3 4)) ; => 4
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 3. Funções
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Use 'fn' para criar funções.
+;; Uma função sempre retorna o valor de sua última expressão
+(fn () "Olá Mundo") ; => (fn () Olá Mundo) : fn
+
+;; Use parênteses para chamar todas as funções, incluindo uma expressão lambda
+((fn () "Olá Mundo")) ; => "Olá Mundo"
+
+;; Atribuir uma função a uma variável
+(set ola-mundo (fn () "Olá Mundo"))
+(ola-mundo) ; => "Olá Mundo"
+
+;; Você pode encurtar isso utilizando a definição de função açúcar sintático:
+(defn ola-mundo2 () "Olá Mundo")
+
+;; Os () acima é a lista de argumentos para a função
+(set ola
+ (fn (nome)
+ (strcat "Olá " nome)))
+(ola "Steve") ; => "Olá Steve"
+
+;; ... ou equivalente, usando a definição açucarada:
+(defn ola2 (nome)
+ (strcat "Olá " name))
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 4. Igualdade
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Para números utilize '=='
+(== 3 3.0) ; => verdadeiro
+(== 2 1) ; => falso
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 5. Controle de Fluxo
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;;; Condicionais
+
+(if true ; Testa a expressão
+ "isso é verdade" ; Então expressão
+ "isso é falso") ; Senão expressão
+; => "isso é verdade"
+
+;;; Laços de Repetição
+
+;; O laço for é para número
+;; (for SÍMBOLO INÍCIO FIM SALTO EXPRESSÃO ..)
+(for i 0 10 2 (pr i "")) ; => Imprime 0 2 4 6 8 10
+(for i 0.0 10 2.5 (pr i "")) ; => Imprime 0 2.5 5 7.5 10
+
+;; Laço while
+((fn (i)
+ (while (< i 10)
+ (pr i)
+ (++ i))) 0) ; => Imprime 0123456789
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 6. Mutação
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Use 'set' para atribuir um novo valor a uma variável ou local
+(set n 5) ; => 5
+(set n (inc n)) ; => 6
+n ; => 6
+(set a (list 1 2)) ; => (1 2)
+(set (nth 0 a) 3) ; => 3
+a ; => (3 2)
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; 7. Macros
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; Macros lhe permitem estender a sintaxe da linguagem.
+;; Os macros no Paren são fáceis.
+;; Na verdade, (defn) é um macro.
+(defmacro setfn (nome ...) (set nome (fn ...)))
+(defmacro defn (nome ...) (def nome (fn ...)))
+
+;; Vamos adicionar uma notação infixa
+(defmacro infix (a op ...) (op a ...))
+(infix 1 + 2 (infix 3 * 4)) ; => 15
+
+;; Macros não são higiênicos, você pode sobrescrever as variáveis já existentes!
+;; Eles são transformações de códigos.
+```
diff --git a/pt-br/ruby-ecosystem-pt.html.markdown b/pt-br/ruby-ecosystem-pt.html.markdown
new file mode 100644
index 00000000..da4f6f37
--- /dev/null
+++ b/pt-br/ruby-ecosystem-pt.html.markdown
@@ -0,0 +1,147 @@
+---
+category: tool
+tool: ruby ecosystem
+contributors:
+ - ["Jon Smock", "http://github.com/jonsmock"]
+ - ["Rafal Chmiel", "http://github.com/rafalchmiel"]
+translators:
+ - ["Claudson Martins", "http://github.com/claudsonm"]
+lang: pt-br
+
+---
+
+Pessoas utilizando Ruby geralmente têm uma forma de instalar diferentes versões
+do Ruby, gerenciar seus pacotes (ou gemas) e as dependências das gemas.
+
+## Gerenciadores Ruby
+
+Algumas plataformas possuem o Ruby pré-instalado ou disponível como um pacote.
+A maioria dos "rubistas" não os usam, e se usam, é apenas para inicializar outro
+instalador ou implementação do Ruby. Ao invés disso, rubistas tendêm a instalar
+um gerenciador para instalar e alternar entre diversas versões do Ruby e seus
+ambientes de projeto.
+
+Abaixo estão os gerenciadores Ruby mais populares:
+
+* [RVM](https://rvm.io/) - Instala e alterna entre os rubies. RVM também possui
+ o conceito de gemsets para isolar os ambientes dos projetos completamente.
+* [ruby-build](https://github.com/sstephenson/ruby-build) - Apenas instala os
+ rubies. Use este para um melhor controle sobre a instalação de seus rubies.
+* [rbenv](https://github.com/sstephenson/rbenv) - Apenas alterna entre os rubies.
+ Usado com o ruby-build. Use este para um controle mais preciso sobre a forma
+ como os rubies são carregados.
+* [chruby](https://github.com/postmodern/chruby) - Apenas alterna entre os rubies.
+ A concepção é bastante similar ao rbenv. Sem grandes opções sobre como os
+ rubies são instalados.
+
+## Versões do Ruby
+
+O Ruby foi criado por Yukihiro "Matz" Matsumoto, que continua a ser uma espécie
+de [BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), embora
+isso esteja mudando recentemente. Como resultado, a implementação de referência
+do Ruby é chamada de MRI (Matz' Reference Implementation), e quando você ver uma
+versão do Ruby, ela está se referindo a versão de lançamento do MRI.
+
+As três principais versões do Ruby em uso são:
+
+* 2.0.0 - Lançada em Fevereiro de 2013. Maioria das principais bibliotecas e
+ suporte a frameworks 2.0.0.
+* 1.9.3 - Lançada em Outubro de 2011. Está é a versão mais utilizada pelos rubistas
+ atualmente. Também [aposentada](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/).
+* 1.8.7 - O Ruby 1.8.7 foi
+ [aposentado](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/).
+
+A diferença entre a versão 1.8.7 para 1.9.x é muito maior do que a da 1.9.3 para
+a 2.0.0. Por exemplo, a série 1.9 introduziu encodes e uma VM bytecode. Ainda
+existem projetos na versão 1.8.7, mas eles estão tornando-se uma pequena minoria
+pois a maioria da comunidade migrou para a versão, pelo menos, 1.9.2 ou 1.9.3.
+
+## Implementações Ruby
+
+O ecossistema Ruby conta com várias diferentes implementações do Ruby, cada uma
+com pontos fortes e estados de compatibilidade. Para ser claro, as diferentes
+implementações são escritas em diferentes linguagens, mas *todas elas são Ruby*.
+Cada implementação possui hooks especiais e recursos extra, mas todas elas
+executam arquivos normais do Ruby tranquilamente. Por exemplo, JRuby é escrita
+em Java, mas você não precisa saber Java para utilizá-la.
+
+Muito maduras/compatíveis:
+
+* [MRI](https://github.com/ruby/ruby) - Escrita em C, esta é a implementação de
+ referência do Ruby. Por definição, é 100% compatível (consigo mesma). Todos os
+ outros rubies mantêm compatibilidade com a MRI (veja [RubySpec](#rubyspec) abaixo).
+* [JRuby](http://jruby.org/) - Escrita em Java e Ruby, esta implementação
+ robusta é um tanto rápida. Mais importante ainda, o ponto forte do JRuby é a
+ interoperabilidade com JVM/Java, aproveitando ferramentas JVM, projetos, e
+ linguagens existentes.
+* [Rubinius](http://rubini.us/) - Escrita principalmente no próprio Ruby, com
+ uma VM bytecode em C++. Também madura e rápida. Por causa de sua implementação
+ em Ruby, ela expõe muitos recursos da VM na rubyland.
+
+Medianamente maduras/compatíveis:
+
+* [Maglev](http://maglev.github.io/) - Construída em cima da Gemstone, uma
+ máquina virtual Smalltalk. O Smalltalk possui algumas ferramentas impressionantes,
+ e este projeto tenta trazer isso para o desenvolvimento Ruby.
+* [RubyMotion](http://www.rubymotion.com/) - Traz o Ruby para o desenvolvimento iOS.
+
+Pouco maduras/compatíveis:
+
+* [Topaz](http://topazruby.com/) - Escrita em RPython (usando o conjunto de
+ ferramentas PyPy), Topaz é bastante jovem e ainda não compatível. Parece ser
+ promissora como uma implementação Ruby de alta performance.
+* [IronRuby](http://ironruby.net/) - Escrita em C# visando a plataforma .NET,
+ o trabalho no IronRuby parece ter parado desde que a Microsoft retirou seu apoio.
+
+Implementações Ruby podem ter seus próprios números de lançamento, mas elas
+sempre focam em uma versão específica da MRI para compatibilidade. Diversas
+implementações têm a capacidade de entrar em diferentes modos (1.8 ou 1.9, por
+exemplo) para especificar qual versão da MRI focar.
+
+## RubySpec
+
+A maioria das implementações Ruby dependem fortemente da [RubySpec](http://rubyspec.org/).
+Ruby não tem uma especificação oficial, então a comunidade tem escrito
+especificações executáveis em Ruby para testar a compatibilidade de suas
+implementações com a MRI.
+
+## RubyGems
+
+[RubyGems](http://rubygems.org/) é um gerenciador de pacotes para Ruby mantido
+pela comunidade. RubyGems vem com o Ruby, portanto não é preciso baixar separadamente.
+
+Os pacotes do Ruby são chamados de "gemas", e elas podem ser hospedadas pela
+comunidade em RubyGems.org. Cada gema contém seu código-fonte e alguns metadados,
+incluindo coisas como versão, dependências, autor(es) e licença(s).
+
+## Bundler
+
+[Bundler](http://bundler.io/) é um gerenciador de dependências para as gemas.
+Ele usa a Gemfile de um projeto para encontrar dependências, e então busca as
+dependências dessas dependências de forma recursiva. Ele faz isso até que todas
+as dependências sejam resolvidas e baixadas, ou para se encontrar um conflito.
+
+O Bundler gerará um erro se encontrar um conflito entre dependências. Por exemplo,
+se a gema A requer versão 3 ou maior que a gema Z, mas a gema B requer a versão
+2, o Bundler irá notificá-lo que há um conflito. Isso se torna extremamente útil
+quando diversas gemas começam a referenciar outras gemas (que referem-se a outras
+gemas), o que pode formar uma grande cascata de dependências a serem resolvidas.
+
+# Testes
+
+Testes são uma grande parte da cultura do Ruby. O Ruby vem com o seu próprio
+framework de teste de unidade chamado minitest (ou TestUnit para Ruby versão 1.8.x).
+Existem diversas bibliotecas de teste com diferentes objetivos.
+
+* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) -
+ Framework de testes "Unit-style" para o Ruby 1.8 (built-in)
+* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) -
+ Framework de testes para o Ruby 1.9/2.0 (built-in)
+* [RSpec](http://rspec.info/) - Um framework de testes que foca na expressividade
+* [Cucumber](http://cukes.info/) - Um framework de testes BDD que analisa testes Gherkin formatados
+
+## Seja Legal
+
+A comunidade Ruby orgulha-se de ser uma comunidade aberta, diversa, e receptiva.
+O próprio Matz é extremamente amigável, e a generosidade dos rubistas em geral
+é incrível.
diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown
index 89a051d4..668cd25f 100644
--- a/pt-br/ruby-pt.html.markdown
+++ b/pt-br/ruby-pt.html.markdown
@@ -4,6 +4,7 @@ lang: pt-br
filename: learnruby-pt.rb
contributors:
- ["Bruno Henrique - Garu", "http://garulab.com"]
+ - ["Jean Matheus Souto", "http://jeanmatheussouto.github.io"]
translators:
- ["Katyanna Moura", "https://twitter.com/amelie_kn"]
---
@@ -161,9 +162,6 @@ hash['numero'] #=> 5
hash['nada aqui'] #=> nil
# Interar sobre hashes com o método #each:
-hash.each do |k, v|
- puts "#{k} is #{v}"
-end
hash.each do |k, v|
puts "#{k} é #{v}"
@@ -385,3 +383,11 @@ Humano.bar # 0
Doutor.bar # nil
```
+
+## Mais sobre Ruby
+
+- [Documentação oficial](http://www.ruby-doc.org/core-2.1.1/)
+- [Aprenda Ruby com desafios](http://www.learneroo.com/modules/61/nodes/338) - Uma coleção de desafios para testar a linguagem.
+- [Ruby a partir de outras linguagens](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/)- Um mais antigo [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) e tambem uma versão online disponível.
+- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Uma versão colaborativa de um *style-guide*
diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown
new file mode 100644
index 00000000..341ae675
--- /dev/null
+++ b/pt-br/yaml-pt.html.markdown
@@ -0,0 +1,142 @@
+---
+language: yaml
+contributors:
+ - ["Adam Brenecki", "https://github.com/adambrenecki"]
+translators:
+ - ["Rodrigo Russo", "https://github.com/rodrigozrusso"]
+filename: learnyaml-pt.yaml
+lang: pt-br
+---
+
+YAML é uma linguagem de serialização de dados projetado para ser diretamente gravável e
+legível por seres humanos.
+
+É um estrito subconjunto de JSON, com a adição de sintaticamente
+novas linhas e recuo significativos, como Python. Ao contrário de Python, no entanto,
+YAML não permite caracteres de tabulação literais em tudo.
+
+```yaml
+# Commentários em YAML são como este.
+
+###################
+# TIPOS ESCALARES #
+###################
+
+# Nosso objeto raiz (que continua por todo o documento) será um mapa,
+# o que equivale a um dicionário, hash ou objeto em outras linguagens.
+chave: valor
+outra_chave: Outro valor vai aqui.
+u_valor_numerico: 100
+notacao_cientifica: 1e+12
+boleano: true
+valor_nulo: null
+chave com espaco: valor
+# Observe que strings não precisam de aspas. Porém, elas podem ter.
+porem: "Uma string, entre aspas."
+"Chaves podem estar entre aspas tambem.": "É útil se você quiser colocar um ':' na sua chave."
+
+# Seqüências de várias linhas podem ser escritos como um 'bloco literal' (utilizando |),
+# ou em um 'bloco compacto' (utilizando '>').
+bloco_literal: |
+ Todo esse bloco de texto será o valor da chave 'bloco_literal',
+ preservando a quebra de com linhas.
+
+ O literal continua até de-dented, e a primeira identação é
+ removida.
+
+ Quaisquer linhas que são 'mais identadas' mantém o resto de suas identações -
+ estas linhas serão identadas com 4 espaços.
+estilo_compacto: >
+ Todo esse bloco de texto será o valor de 'estilo_compacto', mas esta
+ vez, todas as novas linhas serão substituídas com espaço simples.
+
+ Linhas em branco, como acima, são convertidas em um carater de nova linha.
+
+ Linhas 'mais-indentadas' mantém suas novas linhas também -
+ este texto irá aparecer em duas linhas.
+
+####################
+# TIPOS DE COLEÇÃO #
+####################
+
+# Texto aninhado é conseguido através de identação.
+um_mapa_aninhado:
+ chave: valor
+ outra_chave: Outro valor
+ outro_mapa_aninhado:
+ ola: ola
+
+# Mapas não tem que ter chaves com string.
+0.25: uma chave com valor flutuante
+
+# As chaves podem ser também objetos multi linhas, utilizando ? para indicar o começo de uma chave.
+? |
+ Esta é uma chave
+ que tem várias linhas
+: e este é o seu valor
+
+# também permite tipos de coleção de chaves, mas muitas linguagens de programação
+# vão reclamar.
+
+# Sequências (equivalente a listas ou arrays) semelhante à isso:
+uma_sequencia:
+ - Item 1
+ - Item 2
+ - 0.5 # sequencias podem conter tipos diferentes.
+ - Item 4
+ - chave: valor
+ outra_chave: outro_valor
+ -
+ - Esta é uma sequencia
+ - dentro de outra sequencia
+
+# Como YAML é um super conjunto de JSON, você também pode escrever mapas JSON de estilo e
+# sequencias:
+mapa_json: {"chave": "valor"}
+json_seq: [3, 2, 1, "decolar"]
+
+##########################
+# RECURSOS EXTRA DO YAML #
+##########################
+
+# YAML também tem um recurso útil chamado "âncoras", que permitem que você facilmente duplique
+# conteúdo em seu documento. Ambas estas chaves terão o mesmo valor:
+conteudo_ancora: & nome_ancora Essa string irá aparecer como o valor de duas chaves.
+outra_ancora: * nome_ancora
+
+# YAML também tem tags, que você pode usar para declarar explicitamente os tipos.
+string_explicita: !! str 0,5
+# Alguns analisadores implementam tags específicas de linguagem, como este para Python de
+# Tipo de número complexo.
+numero_complexo_em_python: !! python / complex 1 + 2j
+
+####################
+# YAML TIPOS EXTRA #
+####################
+
+# Strings e números não são os únicos que escalares YAML pode entender.
+# Data e 'data e hora' literais no formato ISO também são analisados.
+datetime: 2001-12-15T02: 59: 43.1Z
+datetime_com_espacos 2001/12/14: 21: 59: 43.10 -5
+Data: 2002/12/14
+
+# A tag !!binary indica que a string é na verdade um base64-encoded (condificado)
+# representação de um blob binário.
+gif_file: !!binary |
+ R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
+ OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+ +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
+ AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
+
+# YAML também tem um tipo de conjunto, o que se parece com isso:
+set:
+ ? item1
+ ? item2
+ ? item3
+
+# Como Python, são apenas conjuntos de mapas com valors nulos; o acima é equivalente a:
+set2:
+ item1: nulo
+ item2: nulo
+ item3: nulo
+```
diff --git a/pt-pt/brainfuck-pt.html.markdown b/pt-pt/bf.html.markdown
index da4c787f..da4c787f 100644
--- a/pt-pt/brainfuck-pt.html.markdown
+++ b/pt-pt/bf.html.markdown
diff --git a/purescript.html.markdown b/purescript.html.markdown
index 6d8cfbb9..b413a9e3 100644
--- a/purescript.html.markdown
+++ b/purescript.html.markdown
@@ -48,7 +48,7 @@ not true -- false
23 == 23 -- true
1 /= 4 -- true
1 >= 4 -- false
--- Comparisions < <= > >=
+-- Comparisons < <= > >=
-- are defined in terms of compare
compare 1 2 -- LT
compare 2 2 -- EQ
@@ -62,7 +62,7 @@ true && (9 >= 19 || 1 < 2) -- true
"Hellow\
\orld" -- "Helloworld"
-- Multiline string with newlines
-"""Hello
+"""Hello
world""" -- "Hello\nworld"
-- Concatenate
"such " ++ "amaze" -- "such amaze"
@@ -197,7 +197,7 @@ let even x = x `mod` 2 == 0
filter even (1..10) -- [2,4,6,8,10]
map (\x -> x + 11) (1..5) -- [12,13,14,15,16]
--- Requires purescript-foldable-traversabe (Data.Foldable)
+-- Requires purescript-foldable-traversable (Data.Foldable)
foldr (+) 0 (1..10) -- 55
sum (1..10) -- 55
@@ -208,4 +208,3 @@ any even [1,2,3] -- true
all even [1,2,3] -- false
```
-
diff --git a/python.html.markdown b/python.html.markdown
index f8f712d3..28b0a7ae 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -8,20 +8,22 @@ contributors:
filename: learnpython.py
---
-Python was created by Guido Van Rossum in the early 90s. It is now one of the most popular
-languages in existence. I fell in love with Python for its syntactic clarity. It's basically
-executable pseudocode.
+Python was created by Guido Van Rossum in the early 90s. It is now one of the
+most popular languages in existence. I fell in love with Python for its
+syntactic clarity. It's basically executable pseudocode.
-Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service]
+Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh)
+or louiedinh [at] [google's email service]
-Note: This article applies to Python 2.7 specifically, but should be applicable
-to Python 2.x. Python 2.7 is reaching end of life and will stop being maintained in 2020,
-it is though recommended to start learning Python with Python 3.
-For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
+Note: This article applies to Python 2.7 specifically, but should be applicable
+to Python 2.x. Python 2.7 is reaching end of life and will stop being
+maintained in 2020, it is though recommended to start learning Python with
+Python 3. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
-It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same time,
-using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports
-allow you to write Python 3 code that will run on Python 2, so check out the Python 3 tutorial.
+It is also possible to write Python code which is compatible with Python 2.7
+and 3.x at the same time, using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports
+allow you to write Python 3 code that will run on Python 2, so check out the
+Python 3 tutorial.
```python
@@ -32,6 +34,7 @@ allow you to write Python 3 code that will run on Python 2, so check out the Pyt
as comments
"""
+
####################################################
## 1. Primitive Datatypes and Operators
####################################################
@@ -124,7 +127,7 @@ not False # => True
"This is a string"[0] # => 'T'
#String formatting with %
-#Even though the % string operator will be deprecated on Python 3.1 and removed
+#Even though the % string operator will be deprecated on Python 3.1 and removed
#later at some time, it may still be good to know how it works.
x = 'apple'
y = 'lemon'
@@ -188,6 +191,7 @@ some_other_var # Raises a name error
# Equivalent of C's '?:' ternary operator
"yahoo!" if 3 > 2 else 2 # => "yahoo!"
+
# Lists store sequences
li = []
# You can start with a prefilled list
@@ -441,6 +445,7 @@ with open("myfile.txt") as f:
for line in f:
print line
+
####################################################
## 4. Functions
####################################################
@@ -464,7 +469,6 @@ def varargs(*args):
varargs(1, 2, 3) # => (1, 2, 3)
-
# You can define functions that take a variable number of
# keyword args, as well, which will be interpreted as a dict by using **
def keyword_args(**kwargs):
@@ -657,6 +661,12 @@ math.sqrt == m.sqrt == sqrt # => True
import math
dir(math)
+# If you have a Python script named math.py in the same
+# folder as your current script, the file math.py will
+# be loaded instead of the built-in Python module.
+# This happens because the local folder has priority
+# over Python's built-in libraries.
+
####################################################
## 7. Advanced
@@ -692,7 +702,6 @@ for i in double_numbers(xrange_):
# message
from functools import wraps
-
def beg(target_function):
@wraps(target_function)
def wrapper(*args, **kwargs):
@@ -703,13 +712,11 @@ def beg(target_function):
return wrapper
-
@beg
def say(say_please=False):
msg = "Can you buy me a beer?"
return msg, say_please
-
print say() # Can you buy me a beer?
print say(say_please=True) # Can you buy me a beer? Please! I am poor :(
```
@@ -726,6 +733,8 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :(
* [Python Module of the Week](http://pymotw.com/2/)
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+* [LearnPython](http://www.learnpython.org/)
+* [Fullstack Python](https://www.fullstackpython.com/)
### Dead Tree
diff --git a/python3.html.markdown b/python3.html.markdown
index 8cc03320..2e37fccb 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -97,13 +97,13 @@ False or True # => True
1 < 2 < 3 # => True
2 < 3 < 2 # => False
-# (is vs. ==) is checks if two variable refer to the same object, but == checks
+# (is vs. ==) is checks if two variables refer to the same object, but == checks
# if the objects pointed to have the same values.
a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
b = a # Point b at what a is pointing to
b is a # => True, a and b refer to the same object
b == a # => True, a's and b's objects are equal
-b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
+b = [1, 2, 3, 4] # Point b at a new list, [1, 2, 3, 4]
b is a # => False, a and b do not refer to the same object
b == a # => True, a's and b's objects are equal
@@ -174,6 +174,10 @@ some_var # => 5
# See Control Flow to learn more about exception handling.
some_unknown_var # Raises a NameError
+# if can be used as an expression
+# Equivalent of C's '?:' ternary operator
+"yahoo!" if 3 > 2 else 2 # => "yahoo!"
+
# Lists store sequences
li = []
# You can start with a prefilled list
@@ -583,12 +587,11 @@ add_10(3) # => 13
(lambda x: x > 2)(3) # => True
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
-# TODO - Fix for iterables
# There are built-in higher order functions
-map(add_10, [1, 2, 3]) # => [11, 12, 13]
-map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
+list(map(add_10, [1, 2, 3])) # => [11, 12, 13]
+list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3]
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7]
# We can use list comprehensions for nice maps and filters
# List comprehension stores the output as a list which can itself be a nested list
@@ -712,6 +715,11 @@ math.sqrt(16) == m.sqrt(16) # => True
import math
dir(math)
+# If you have a Python script named math.py in the same
+# folder as your current script, the file math.py will
+# be loaded instead of the built-in Python module.
+# This happens because the local folder has priority
+# over Python's built-in libraries.
####################################################
## 7. Advanced
@@ -780,6 +788,7 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
* [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
diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown
index 78b62e33..8ee3aa64 100644
--- a/pythonstatcomp.html.markdown
+++ b/pythonstatcomp.html.markdown
@@ -1,14 +1,16 @@
---
-language: Statistical computing with Python
+category: tool
+tool: Statistical Computing with Python
contributors:
- ["e99n09", "https://github.com/e99n09"]
-filename: pythonstatcomp.py
---
This is a tutorial on how to do some typical statistical programming tasks using Python. It's intended for people basically familiar with Python and experienced at statistical programming in a language like R, Stata, SAS, SPSS, or MATLAB.
```python
+
+
# 0. Getting set up ====
""" Get set up with IPython and pip install the following: numpy, scipy, pandas,
@@ -25,17 +27,17 @@ This is a tutorial on how to do some typical statistical programming tasks using
already using Python, there's a benefit to sticking with one language.
"""
-import requests # for HTTP requests (web scraping, APIs)
+import requests # for HTTP requests (web scraping, APIs)
import os
# web scraping
r = requests.get("https://github.com/adambard/learnxinyminutes-docs")
-r.status_code # if 200, request was successful
-r.text # raw page source
-print(r.text) # prettily formatted
+r.status_code # if 200, request was successful
+r.text # raw page source
+print(r.text) # prettily formatted
# save the page source in a file:
-os.getcwd() # check what's the working directory
-f = open("learnxinyminutes.html","wb")
+os.getcwd() # check what's the working directory
+f = open("learnxinyminutes.html", "wb")
f.write(r.text.encode("UTF-8"))
f.close()
@@ -44,7 +46,7 @@ fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/"
fn = "pets.csv"
r = requests.get(fp + fn)
print(r.text)
-f = open(fn,"wb")
+f = open(fn, "wb")
f.write(r.text.encode("UTF-8"))
f.close()
@@ -58,7 +60,9 @@ f.close()
you've used R, you will be familiar with the idea of the "data.frame" already.
"""
-import pandas as pd, numpy as np, scipy as sp
+import pandas as pd
+import numpy as np
+import scipy as sp
pets = pd.read_csv(fn)
pets
# name age weight species
@@ -74,20 +78,20 @@ pets
pets.age
pets["age"]
-pets.head(2) # prints first 2 rows
-pets.tail(1) # prints last row
+pets.head(2) # prints first 2 rows
+pets.tail(1) # prints last row
-pets.name[1] # 'vesuvius'
-pets.species[0] # 'cat'
-pets["weight"][2] # 34
+pets.name[1] # 'vesuvius'
+pets.species[0] # 'cat'
+pets["weight"][2] # 34
# in R, you would expect to get 3 rows doing this, but here you get 2:
pets.age[0:2]
# 0 3
# 1 6
-sum(pets.age)*2 # 28
-max(pets.weight) - min(pets.weight) # 20
+sum(pets.age) * 2 # 28
+max(pets.weight) - min(pets.weight) # 20
""" If you are doing some serious linear algebra and number-crunching, you may
just want arrays, not DataFrames. DataFrames are ideal for combining columns
@@ -96,7 +100,8 @@ max(pets.weight) - min(pets.weight) # 20
# 3. Charts ====
-import matplotlib as mpl, matplotlib.pyplot as plt
+import matplotlib as mpl
+import matplotlib.pyplot as plt
%matplotlib inline
# To do data vizualization in Python, use matplotlib
@@ -105,13 +110,17 @@ plt.hist(pets.age);
plt.boxplot(pets.weight);
-plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight");
+plt.scatter(pets.age, pets.weight)
+plt.xlabel("age")
+plt.ylabel("weight");
# seaborn sits atop matplotlib and makes plots prettier
import seaborn as sns
-plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight");
+plt.scatter(pets.age, pets.weight)
+plt.xlabel("age")
+plt.ylabel("weight");
# there are also some seaborn-specific plotting functions
# notice how seaborn automatically labels the x-axis on this barplot
@@ -141,41 +150,40 @@ ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets")
url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv"
r = requests.get(url)
fp = "hre.csv"
-f = open(fp,"wb")
-f.write(r.text.encode("UTF-8"))
-f.close()
+with open(fp, "wb") as f:
+ f.write(r.text.encode("UTF-8"))
hre = pd.read_csv(fp)
hre.head()
"""
- Ix Dynasty Name Birth Death Election 1
-0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN
-1 NaN Carolingian Louis I 778 20 June 840 NaN
-2 NaN Carolingian Lothair I 795 29 September 855 NaN
-3 NaN Carolingian Louis II 825 12 August 875 NaN
-4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN
-
- Election 2 Coronation 1 Coronation 2 Ceased to be Emperor
-0 NaN 25 December 800 NaN 28 January 814
-1 NaN 11 September 813 5 October 816 20 June 840
-2 NaN 5 April 823 NaN 29 September 855
-3 NaN Easter 850 18 May 872 12 August 875
-4 NaN 29 December 875 NaN 6 October 877
-
- Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2
-0 NaN NaN NaN NaN
-1 Charles I son NaN NaN
-2 Louis I son NaN NaN
-3 Lothair I son NaN NaN
-4 Louis I son NaN NaN
+ Ix Dynasty Name Birth Death Election 1
+0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN
+1 NaN Carolingian Louis I 778 20 June 840 NaN
+2 NaN Carolingian Lothair I 795 29 September 855 NaN
+3 NaN Carolingian Louis II 825 12 August 875 NaN
+4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN
+
+ Election 2 Coronation 1 Coronation 2 Ceased to be Emperor
+0 NaN 25 December 800 NaN 28 January 814
+1 NaN 11 September 813 5 October 816 20 June 840
+2 NaN 5 April 823 NaN 29 September 855
+3 NaN Easter 850 18 May 872 12 August 875
+4 NaN 29 December 875 NaN 6 October 877
+
+ Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2
+0 NaN NaN NaN NaN
+1 Charles I son NaN NaN
+2 Louis I son NaN NaN
+3 Lothair I son NaN NaN
+4 Louis I son NaN NaN
"""
# clean the Birth and Death columns
-import re # module for regular expressions
+import re # module for regular expressions
-rx = re.compile(r'\d+$') # match trailing digits
+rx = re.compile(r'\d+$') # match trailing digits
""" This function applies the regular expression to an input column (here Birth,
Death), flattens the resulting list, converts it to a Series object, and
@@ -185,8 +193,9 @@ rx = re.compile(r'\d+$') # match trailing digits
- http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list
- http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html
"""
+
def extractYear(v):
- return(pd.Series(reduce(lambda x,y: x+y,map(rx.findall,v),[])).astype(int))
+ return(pd.Series(reduce(lambda x, y: x + y, map(rx.findall, v), [])).astype(int))
hre["BirthY"] = extractYear(hre.Birth)
hre["DeathY"] = extractYear(hre.Death)
@@ -199,17 +208,17 @@ sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False);
# use scipy to run a linear regression
from scipy import stats
-(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge)
+(slope, intercept, rval, pval, stderr) = stats.linregress(hre.BirthY, hre.EstAge)
# code source: http://wiki.scipy.org/Cookbook/LinearRegression
# check the slope
-slope # 0.0057672618839073328
+slope # 0.0057672618839073328
# check the R^2 value:
-rval**2 # 0.020363950027333586
+rval**2 # 0.020363950027333586
# check the p-value
-pval # 0.34971812581498452
+pval # 0.34971812581498452
# use seaborn to make a scatterplot and plot the linear regression trend line
sns.lmplot("BirthY", "EstAge", data=hre);
@@ -223,6 +232,7 @@ sns.lmplot("BirthY", "EstAge", data=hre);
To see a version of the Holy Roman Emperors analysis using R, see
- http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R
"""
+
```
If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial.
diff --git a/ro-ro/bash-ro.html.markdown b/ro-ro/bash-ro.html.markdown
index debeb67a..32a878b2 100644
--- a/ro-ro/bash-ro.html.markdown
+++ b/ro-ro/bash-ro.html.markdown
@@ -12,166 +12,171 @@ lang: ro-ro
filename: LearnBash-ro.sh
---
-Bash este numele shell-ului unix, care a fost de asemenea distribuit drept shell pentru sistemul de operare GNU si ca shell implicit pentru Linux si Mac OS X.
+Bash este numele shell-ului UNIX, care a fost de asemenea distribuit drept shell pentru sistemul de operare GNU și ca shell implicit pentru Linux si Mac OS X.
Aproape toate exemplele de mai jos pot fi parte dintr-un script sau pot fi executate direct in linia de comanda.
-[Citeste mai multe:](http://www.gnu.org/software/bash/manual/bashref.html)
+[Citește mai multe:](http://www.gnu.org/software/bash/manual/bashref.html)
```bash
#!/bin/bash
# Prima linie din script se numeste "shebang"
-# care spune systemului cum sa execute scriptul
+# care spune sistemului cum să execute scriptul
# http://en.wikipedia.org/wiki/Shebang_(Unix)
-# Dupa cum te-ai prins deja, comentariile incep cu #.
+# După cum te-ai prins deja, comentariile încep cu #.
# Shebang este de asemenea un comentariu.
# Exemplu simplu de hello world:
echo Hello world!
-# Fiecare comanda incepe pe o linie noua, sau dupa punct si virgula ;
+# Fiecare comandă începe pe o linie nouă, sau după punct și virgula ;
echo 'Prima linie'; echo 'A doua linie'
# Declararea unei variabile se face astfel:
-VARIABLE="Niste text"
+VARIABLE="Niște text"
-# DAR nu asa:
+# DAR nu așa:
VARIABLE = "Niste text"
-# Bash va crede ca VARIABLE este o comanda care trebuie executata si va
-# returna o eroare pentru ca nu va putea fi gasita.
+# Bash va crede că VARIABLE este o comandă care trebuie executată și va
+# returna o eroare pentru că nu va putea fi găsita.
# Folosind variabila:
echo $VARIABLE
echo "$VARIABLE"
echo '$VARIABLE'
-# Atunci cand folosesti variabila, o atribui, o exporti sau altfel,
-# numele ei se scrie fara $.
-# Daca vrei sa folosesti valoarea variabilei, atunci trebuie sa folosesti $.
-# Atentie la faptul ca ' (apostrof) nu va inlocui variabla cu valoarea ei.
+# Atunci când folosesti variabila, o atribui, o exporți sau altfel,
+# numele ei se scrie fără $.
+# Daca vrei sa folosesti valoarea variabilei, atunci trebuie să folosești $.
+# Atentie la faptul că ' (apostrof) nu va inlocui variabla cu valoarea ei.
-# Inlocuirea de caractere in variabile
-echo ${VARIABLE/Some/A}
-# Asta va inlocui prima aparitie a "Some" cu "A" in variabila de mai sus.
+# Inlocuirea de caractere în variabile
+echo ${VARIABLE/Niște/Un}
+# Asta va înlocui prima apariție a "Niște" cu "Un" în variabila de mai sus.
-# Substring dintr-o variabila
+# Substring dintr-o variabilă
echo ${VARIABLE:0:7}
# Asta va returna numai primele 7 caractere din variabila.
# Valoarea implicita a unei variabile:
-echo ${FOO:-"ValoareaImplicitaDacaFOOLipsesteSauEGoala"}
-# Asta functioneaza pentru null (FOO=),
-# sir de caractere gol (FOO=""), zero (FOO=0) returneaza 0
+echo ${FOO:-"ValoareaImplicitaDacaFOOLipseșteSauEGoală"}
+# Asta functionează pentru null (FOO=),
+# sir de caractere gol (FOO=""), zero (FOO=0) returnează 0
# Variabile pre-existente
-echo "Ulima valoare returnata de ultimul program rulat: $?"
-echo "ID-ul procesului (PID) care ruleaza scriptul: $$"
-echo "Numarul de argumente: $#"
+echo "Ulima valoare returnată de ultimul program rulat: $?"
+echo "ID-ul procesului (PID) care rulează scriptul: $$"
+echo "Numărul de argumente: $#"
echo "Argumentele scriptului: $@"
-echo "Argumentele scriptului separate in variabile: $1 $2..."
+echo "Argumentele scriptului separate în variabile: $1 $2..."
-# Citind o valoare din consola
-echo "Care e numele tau?"
-read NAME # Observa faptul ca nu a trebuit sa declaram o variabila noua
+# Citind o valoare din consolă
+echo "Care e numele tău?"
+read NAME # Observă faptul că nu a trebuit să declarăm o variabilă nouă
echo Salut, $NAME!
# Avem obisnuita instructiune "if"
-# Foloseste "man test" pentru mai multe informatii
-# despre instructinea conditionala
+# Folosește "man test" pentru mai multe informații
+# despre instrucținea conditionala
if [ $NAME -ne $USER ]
then
- echo "Numele tau este username-ul tau"
+ echo "Numele tău este username-ul tău"
else
- echo "Numele tau nu este username-ul tau"
+ echo "Numele tău nu este username-ul tău"
fi
-# Este de asemenea si executarea conditionala de comenzi
-echo "Intotdeauna executat" || echo "Executat daca prima instructiune esueaza"
-echo "Intotdeauna executat" && echo "Executat daca prima instructiune NU esueaza"
+# Există, de asemenea, și executarea conditională de comenzi
+echo "Întotdeauna executat" || echo "Executat dacă prima instrucțiune eșuează"
+echo "Întotdeauna executat" && echo "Executat dacă prima instrucțiune NU esuează"
-# Expresiile apar in urmatorul format
+# Expresiile apar în urmatorul format
echo $(( 10 + 5 ))
-# Spre deosebire de alte limbaje de programare bash este un shell - asa ca
-# functioneaza in contextul directorului curent. Poti vedea fisiere si directoare
+# Spre deosebire de alte limbaje de programare, bash este un shell - așa că
+# funcționează in contextul directorului curent. Poți vedea fișiere și directoare
# din directorul curent folosind comanda "ls":
ls
-# Aceste comenzi au optiuni care la controleaza executia
-ls -l # Listeaza fiecare fisier si director pe o linie separata
+# Aceste comenzi au optiuni care le controlează execuțiă
+ls -l # Listează fiecare fișier și director pe o linie separată
# Rezultatele comenzii anterioare pot fi
-# trimise urmatoarei comenzi drept argument
-# Comanda grep filtreaza argumentele trimise cu sabloane.
+# trimise următoarei comenzi drept argument
+# Comanda grep filtrează argumentele trimise cu sabloane.
# Astfel putem vedea fiserele .txt din directorul curent.
ls -l | grep "\.txt"
-# De asemenea poti redirectiona o comanda, input si error output
-python2 hello.py < "input.in"
-python2 hello.py > "output.out"
-python2 hello.py 2> "error.err"
-# Output-ul va suprascrie fisierul daca acesta exista.
-# Daca vrei sa fie concatenate poti folosi ">>"
-
-# Comenzile pot fi inlocuite in interiorul altor comenzi folosind $( ):
-# Urmatoarea comanda afiseaza numarul de fisiere
-# si directoare din directorul curent
-echo "Sunt $(ls | wc -l) fisiere aici."
-
-# Acelasi lucru se poate obtine folosind apostrf-ul inversat ``,
-# dar nu pot fi folosite unele in interiorul celorlalte asa ca modalitatea
-# preferata este de a folosi $( )
-echo "Sunt `ls | wc -l` fisiere aici."
-
-# Bash foloseste o instructiune 'case' care functioneaza
-# in mod similar cu instructiunea switch din Java si C++
+# De asemenea, poți redirecționa date de intrare spre sau erori/date de ieșire
+# dinspre o comandă
+python2 hello.py < "intrare.in"
+python2 hello.py > "ieșire.out"
+python2 hello.py 2> "erori.err"
+# Output-ul va suprascrie fișierul dacă acesta există.
+# Daca vrei să fie concatenate datele poți folosi ">>" în loc de ">"
+
+# Comenzile pot fi înlocuite în interiorul altor comenzi folosind $( ):
+# Urmatoarea comandă afișează numărul de fișiere
+# și directoare din directorul curent
+echo "Sunt $(ls | wc -l) fișiere aici."
+
+# Același lucru se poate obține folosind apostroful inversat ``,
+# dar nu pot fi folosite limbricate, așa ca modalitatea
+# preferată este de a folosi $( )
+echo "Sunt `ls | wc -l` fișiere aici."
+
+# Bash folosește o instrucțiune 'case' care funcționeaza
+# în mod similar cu instructiunea switch din Java si C++
case "$VARIABLE" in
0) echo "Este un zero.";;
1) echo "Este un unu.";;
*) echo "Nu este null";;
esac
-# Instructiunea for parcurge toate elementele trimise:
-# Continutul variabilei $VARIABLE este printat de 3 ori
+# Instrucțiunea 'for' parcurge toate elementele trimise:
+# Conținutul variabilei $VARIABLE este printat de 3 ori
for VARIABLE in {1..3}
do
echo "$VARIABLE"
done
-# while loop:
+# Buclă while:
while [true]
do
- echo "in interiorul iteratiei aici..."
+ echo "în interiorul iterației aici..."
break
done
-# De asemenea poti defini functii
-# Definitie:
+# De asemenea poți defini funcții
+# Definiție:
function foo ()
{
- echo "Argumentele functioneaza ca si argumentele scriptului: $@"
+ echo "Argumentele funcționeaza ca și argumentele scriptului: $@"
echo "Si: $1 $2..."
- echo "Asta este o functie"
+ echo "Asta este o funcție"
return 0
}
-# sau mai simplu
+# sau mai simplu:
bar ()
{
- echo "Alta metoda de a declara o functie"
+ echo "Altă metodă de a declara o funcție"
return 0
}
-# Invocarea unei functii
+# Invocarea unei funcții:
foo "Numele meu este: " $NAME
-# Sunt o multime de comenzi utile pe care ar trebui sa le inveti:
+# Sunt o multime de comenzi utile pe care ar trebui să le inveți:
tail -n 10 file.txt
-# printeaza ultimele 10 linii din fisierul file.txt
+# afișează ultimele 10 linii din fișierul file.txt
+
head -n 10 file.txt
-# printeaza primele 10 linii din fisierul file.txt
+# afișează primele 10 linii din fișierul file.txt
+
sort file.txt
-# sorteaza liniile din file.txt
+# sortează liniile din file.txt
+
uniq -d file.txt
-# raporteaza sau omite liniile care se repeta, cu -d le raporteaza
+# raporteaza sau omite liniile care se repetă. Cu -d le raporteaza
+
cut -d ',' -f 1 file.txt
-# printeaza doar prima coloana inainte de caracterul ","
+# printează doar prima coloană inainte de caracterul ","
```
diff --git a/ro-ro/bf-ro.html.markdown b/ro-ro/bf-ro.html.markdown
new file mode 100644
index 00000000..61b555ed
--- /dev/null
+++ b/ro-ro/bf-ro.html.markdown
@@ -0,0 +1,90 @@
+---
+language: brainfuck
+contributors:
+ - ["Prajit Ramachandran", "http://prajitr.github.io/"]
+ - ["Mathias Bynens", "http://mathiasbynens.be/"]
+translators:
+ - ["Petru Dimitriu", "http://petru-dimitriu.github.io"]
+lang: ro-ro
+---
+
+Brainfuck (un nume propriu care nu primește majusculă inițială decât la începutul
+propoziției) este un limbaj de programare Turing-comple extrem de minimalist cu
+doar 8 instrucțiuni.
+
+Puteți încerca brainfuck în navigatorul dumneavoastră cu [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/).
+
+```
+Orice caracter in afara de "><+-.,[]" (fara ghilimele) este ignorat.
+
+Brainfuck se reprezinta ca un vector de 30 000 de celule initializate cu zero
+si un pointer de date care trimite spre celula curenta.
+
+Exista opt comenzi:
++ : Incrementeaza valoarea celulei curente cu 1.
+- : Decrementeaza valoarea celulei curente cu 1.
+> : Muta pointerul de date la urmatoarea celula (o celula la dreapta).
+< : Muta pointerul de date la celula precedenta (o celula la stanga).
+. : Afiseaza valoarea caracterului ASCII din celul caurenta (ex. 65 = 'A').
+, : Citeste un singur caracter si plaseaza valoarea lui in celula curenta.
+[ : Daca valoarea in celula curenta este zero, sare la urmatorul caracter ] .
+ Altfel, merge la urmatoarea instructiune.
+] : Daca valoarea in celula curenta este zero, sare la urmatoarea
+ instructiune.
+ Altfel, se intoarce la instructiunea de dupa caracterul [ precedent .
+
+[ and ] formeaza un ciclu. Evident, trebuie ca parantezarea sa fie corecta.
+
+Sa privim cateva programe brainfuck simple.
+
+++++++ [ > ++++++++++ < - ] > +++++ .
+
+Acest program afiseaza litera 'A'. Mai intai, incrementeaza celula #1 pana
+la valoarea 6. Celula #1 va fi folosita pentru ciclare. Apoi, intra in ciclu
+([) si muta pointerul la celula #2. Incrementeaza celula #2 de 10 ori,
+muta pointerul la celula #1 si decrementeaza celula #1. Acest ciclu parcurge
+6 iteratii (este nevoie de 6 decrementari pentru ca celula #1 sa ajunga la 0),
+iar dupa aceea se trece la caracterul ] corespunzator si se continua executia.
+
+In acest moment, ne aflam in celula #1, care are valoarea 0, in timp ce celula
+#2 are valoarea 60. Ne mutam pe celula #2, incrementam de 5 ori, pentru a
+obtine valoarea 65, si apoi afisam valoarea celulei #2. 65 este codul ASCII
+pentru 'A', deci se afiseaza 'A' in terminal.
+
+, [ > + < - ] > .
+
+Acest program citeste un caracter de la intrarea utilizator si copiaza caracterul
+in celula #1. Apoi incepem un ciclu. Se muta pointerul in celula #2, se
+incremneteaza valoarea de la celula #2, se muta inapoi la celula #1, se
+decrementeaza valoarea de la celula #1. Aceasta continua pana cand celula #1 este
+0 iar celula #2 retine vechea valoare a celulei #1. Deoarece ne aflam in celula
+#1 la sfarsitul ciclului, ne mutam pe celula #2 si afisam simbolul corespunzator
+in ASCII.
+
+Aveti in vedere ca spatiile sunt doar pentru usurinta citirii. La fel de bine
+programul ar fi putut fi scris astfel:
+
+,[>+<-]>.
+
+Incercati sa va dati seama ce face acest program:
+
+,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >>
+
+Acest program citeste doua numere ca intrare si le inmulteste.
+
+Pe scurt, programul citeste doua date de intrare, apoi incepe ciclul
+mare, a carui conditie se afla in celula #1; apoi se muta la celula #2
+si incepe un ciclu imbricat a carui conditie de reluare se afla in
+celula #2, si care incrementeaza celula #3. Totusi aici intervine o
+problema: La sfarsitul ciclului imbricat, celula #2 este zero. In
+acest caz, celula ciclul imbricat nu va mai functiona data viitoare.
+Pentru a rezolva aceasta problema, incrementam celula si #4, si
+recopiem celula #4 in celula #2. In final, celula #3 este rezultatul.
+
+```
+
+Așadar acesta este limbajul brainfuck. Nu e atât de greu, nu? Pentru
+amuzament, puteți să scrieți propriile dumneavoastră limbaje, sau puteți
+scrie un interpretor pentru brainfuck într-un alt limbaj. Interpretorul
+este destul de ușor de implementat, dar dacă sunteți masochist, încercați
+să implementați un interpretor de brainfuck… în brainfuck. \ No newline at end of file
diff --git a/ro-ro/coffeescript-ro.html.markdown b/ro-ro/coffeescript-ro.html.markdown
new file mode 100644
index 00000000..695274d2
--- /dev/null
+++ b/ro-ro/coffeescript-ro.html.markdown
@@ -0,0 +1,102 @@
+---
+language: coffeescript
+contributors:
+ - ["Tenor Biel", "http://github.com/L8D"]
+ - ["Xavier Yao", "http://github.com/xavieryao"]
+translators:
+ - ["Bogdan Lazar", "http://twitter.com/tricinel"]
+filename: coffeescript-ro.coffee
+lang: ro-ro
+---
+
+CoffeeScript este un limbaj de programare care este compilat in Javascript. Nu exista un interpretator la runtime-ul aplicatiei. Fiind unul din successorii Javascript, CoffeeScript incearca sa compileze Javascript usor de citit si performant.
+
+Mai cititi si [website-ul CoffeeScript](http://coffeescript.org/), care contine un tutorial complet Coffeescript.
+
+```coffeescript
+# CoffeeScript este un limbaj de hipster.
+# Se foloseste de trendurile multor limbaje moderne de programare.
+# Comentarii sunt ca in Ruby sau Python.
+
+###
+Comentariile in bloc sunt create cu `###`, iar acestea sunt transformate in `/*` si `*/` pentru Javascript
+
+Ar trebuie sa intelegeti Javascript pentru a continua cu acest ghid.
+###
+
+# Atribuirea valorilor:
+numar = 42 #=> var numar = 42;
+opus = true #=> var opus = true;
+
+# Conditii:
+numar = -42 if opus #=> if(opus) { numar = -42; }
+
+# Functii:
+laPatrat = (x) -> x * x #=> var laPatrat = function(x) { return x * x; }
+
+plin = (recipient, lichid = "cafea") ->
+ "Umplem #{recipient} cu #{cafea}..."
+#=>var plin;
+#
+#plin = function(recipient, lichid) {
+# if (lichid == null) {
+# lichid = "cafea";
+# }
+# return "Umplem " + recipient + " cu " + lichid + "...";
+#};
+
+# Liste:
+lista = [1..5] #=> var lista = [1, 2, 3, 4, 5];
+
+# Obiecte:
+matematica =
+ radacina: Math.sqrt
+ laPatrat: laPatrat
+ cub: (x) -> x * square x
+#=> var matematica = {
+# "radacina": Math.sqrt,
+# "laPatrat": laPatrat,
+# "cub": function(x) { return x * square(x); }
+# };
+
+# Splats:
+cursa = (castigator, alergatori...) ->
+ print castigator, alergatori
+#=>cursa = function() {
+# var alergatori, castigator;
+# castigator = arguments[0], alergatori = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
+# return print(castigator, alergatori);
+# };
+
+# Verificarea existentei:
+alert "Stiam eu!" if elvis?
+#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Stiam eu!"); }
+
+# Operatiuni cu matrice:
+cuburi = (math.cube num for num in list)
+#=>cuburi = (function() {
+# var _i, _len, _results;
+# _results = [];
+# for (_i = 0, _len = list.length; _i < _len; _i++) {
+# num = list[_i];
+# _results.push(math.cube(num));
+# }
+# return _results;
+# })();
+
+alimente = ['broccoli', 'spanac', 'ciocolata']
+mananca aliment for aliment in alimente when aliment isnt 'ciocolata'
+#=>alimente = ['broccoli', 'spanac', 'ciocolata'];
+#
+#for (_k = 0, _len2 = alimente.length; _k < _len2; _k++) {
+# aliment = alimente[_k];
+# if (aliment !== 'ciocolata') {
+# eat(aliment);
+# }
+#}
+```
+
+## Resurse aditionale
+
+- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/)
+- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read)
diff --git a/ro-ro/json-ro.html.markdown b/ro-ro/json-ro.html.markdown
new file mode 100644
index 00000000..e897059c
--- /dev/null
+++ b/ro-ro/json-ro.html.markdown
@@ -0,0 +1,61 @@
+---
+language: json
+filename: learnjson-ro.json
+contributors:
+ - ["Anna Harren", "https://github.com/iirelu"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+translators:
+ - ["Serban Constantin", "https://github.com/fuzzmz"]
+lang: ro-ro
+---
+
+Deoarece JSON este un fromat foarte simplu de schimb de date acesta va fi
+probabil cel mai simplu Invata X in Y minute.
+
+JSON in forma cea mai pura nu contine comentarii insa majoritatea parserelor
+vor accepta comentarii in stil C (`//`, `/* */`). Pentru acest caz insa totul
+va fi JSON 100% valid. Din fericire codul vorbeste de la sine.
+
+```json
+{
+ "cheie": "valoare",
+
+ "chei": "trebuie mereu inconjurate de ghilimele",
+ "numere": 0,
+ "stringuri": "Bunã. Tot setul unicode este permis, chiar si \"escaping\".",
+ "are booleane?": true,
+ "nimic": null,
+
+ "numere mari": 1.2e+100,
+
+ "obiecte": {
+ "comentariu": "Majoritatea structurii va veni din obiecte.",
+
+ "vectori": [0, 1, 2, 3, "Vectorii pot avea orice in ei.", 5],
+
+ "alt obiect": {
+ "comentariu": "Lucrurile pot fi subordonate. Foarte util."
+ }
+ },
+
+ "glumite": [
+ {
+ "surse de potasiu": ["banane"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "neo"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "stil alternativ": {
+ "comentariu": "ia uite la asta!"
+ , "pozitia virgulei": "nu conteaza - daca e inaintea valorii atunci e valida"
+ , "alt comentariu": "ce dragut"
+ },
+
+ "a fost scurt": "Am terminat. Acum stii tot ce are JSON de oferit."
+}
+```
diff --git a/ro-ro/latex.html.markdown b/ro-ro/latex.html.markdown
new file mode 100644
index 00000000..35651e28
--- /dev/null
+++ b/ro-ro/latex.html.markdown
@@ -0,0 +1,258 @@
+---
+language: latex
+contributors:
+ - ["Chaitanya Krishna Ande", "http://icymist.github.io"]
+ - ["Colton Kohnke", "http://github.com/voltnor"]
+ - ["Sricharan Chiruvolu", "http://sricharan.xyz"]
+ - ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"]
+translators:
+ - ["Petru Dimitriu", "http://petru-dimitriu.github.io"]
+filename: brainfuck-ro.clj
+filename: learn-latex-ro.tex
+lang: ro-ro
+---
+
+```tex
+% Toate comentariile încep cu %
+% Nu există comentarii multi-linie
+
+% LaTeX NU este un program software de procesare text de tipul
+% "What You See Is What You Get"
+% precum MS Word, sau OpenOffice Writer
+
+% Toate comenzile LaTeX încep cu backslash. (\)
+
+% Documentele LaTeX încep cu o linie care definește tipul documentului
+% care urmează a fi compilat. Alte tipuri de documente sunt book (carte),
+% presentation (prezentare), etc. Opțiunile pentru document apar
+% între paranteze drepte. În acest caz, specificăm că vrem să folosim
+% un corp de text (font) de 12 puncte.
+\documentclass[12pt]{article}
+
+% Mai apoi definim pachetele pe care documentul le folosește.
+% Dacă vreți să includeți grafice, text colorat sau
+% cod sursă din alt fișier în documentul dumneavoastră,
+% trebuie să îmbogățiți capabilitățile LaTeX. Aceasta se realizează
+% adăugând pachete. Voi include pachetele float și caption pentru
+% imagini.
+\usepackage{caption}
+\usepackage{float}
+% această comandă este necesară atunci când vreți să scrieți codul
+% sursă folosind diacrtice! (cum e cazul aici, unde translatorul
+% a vrut să scrie neapărat folosind diacriticele românești)
+\usepackage[utf8]{inputenc}
+
+% De asemenea, putem defini și alte proprietăți pentru documente.
+% We can define some other document properties too!
+\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu \\ Traducere de Petru Dimitriu}
+\date{\today}
+\title{Învățați LaTeX în Y minute!}
+
+% Suntem gata să începem documentul.
+% Tot ce se află înaintea acestei linii se numește "Preambul"
+\begin{document}
+% dacă am setat autorul, data și titlul, putem cere LaTeX să
+% creeze o pagină de titlu
+\maketitle
+
+% Cele mai multe documente științifice au un abstract; puteți folosi comenzile
+% predefinite pentru acesta. Acesta ar trebui să apară, așa cum ar fi logic,
+% după titlu, dar înainte de secțiunile principale ale corpului.
+% Această comandă este disponibilă în clasele de document article și report.
+\begin{abstract}
+ Documentațue LaTeX scrisă în LaTeX. O idee nicidecum nouă și nicidecum a mea!
+\end{abstract}
+
+% Comenzile pentru secțiuni sunt intuitive.
+% Toate titlurile secțiunilor sunt adăugate automat la tabla de materii (cuprins).
+\section{Introducere}
+Salut, mă numesc Petru. Astăzi vom învăța împreună LaTeX!
+
+\section{Altă secțiune}
+Acesta este textul pentru altă secțiune. Vom face o subsecțiune.
+
+\subsection{Aceasta este o subsecțiune} % Subsecțiunile sunt și ele intuitive.
+Și încă una.
+
+\subsubsection{Pitagora}
+Mult mai bine.
+\label{subsec:pitagora}
+
+% Folosind asteriscul putem suprima numărătoarea automată a LaTeX.
+% Aceasta funcționează și pentru alte comenzi LaTeX.
+\section*{Secțiune fără numerotare}
+Totuși nu toate secțiunile trebuie să fie nenumerotate!
+
+\section{Note despre text}
+În general LaTeX se pricepe să pună textul unde trebuie. Dacă o linie are \\
+nevoie \\ să \\ fie \\ întreruptă, puteți adăuga două caractere backslash
+la codul sursă.
+
+\section{Liste}
+Listele sunt printre cel mai simplu de făcut lucruri în LaTeX! Mâine merg la
+cumpărături așa că fac o listă:
+\begin{enumerate} % Aceasta creează un mediu "enumerate"
+ % \item spune mediului "enumerate" să incrementeze
+ \item salată
+ \item 27 pepeni
+ \item un singur iepuroi
+ % putem suprascrie numărul elementului folosind []
+ \item[câte?] conserve de ton
+
+ Nu este un element din listă, dar încă face parte din "enumerate".
+
+\end{enumerate} % All environments must have an end.
+
+\section{Matematică}
+
+Una dintre principalele întrebuințări ale LaTeX este realizarea
+articolelor academice sau a foilor tehnice, de obicei aflate în
+universul matematicii și științelor exacte. Astfel, trebuie să putem
+adăuga simboluri speciale în documentului nostru! \\
+
+Matematica are multe simboluri, mult mai multe decât se găsesc
+pe o tastatură - printre ele, simboluri pentru mulțimi și relații,
+săgeți, operatori și litere grecești.\\
+
+Mulțimile și relațiile sunt de bază în lucrările științifce matematice.
+Iată cum se scrie: toți y aparținând lui X.\\
+$\forall$ x $\in$ X. \\
+
+% Observați cum am avut nevoie să pun semnul $ înainte și după simboluri.
+% Aceasta pentru că atunci când scriem, suntem în modul text (text-mode).
+% Totuși simbolurile matematice există numai în modul matematic (math-mode).
+% Când ne aflăm în text-mode, putem scrie texte în math-mode punând $ înainte
+% și după simboluri. La fel și viceversa. Și variabilele pot fi redate
+% în math-mode. Putem intra în math-mode și scriind \[\].
+
+\[a^2 + b^2 = c^2 \]
+
+Litera mea grecească este $\xi$. De asemenea îmi plac $\beta$, $\gamma$ și
+$\sigma$. Nu există nicio literă grecească necunoscută pentru LaTeX!
+
+Operatorii sunt exențiali într-un document matematic!
+funcțiile trigonometrice ($\sin$, $\cos$, $\tan$),
+logaritmii și exponențialele ($\log$, $\exp$),
+limitele ($\lim$), etc.
+au comenzi definite în LaTeX pentru fiecare.
+Să vedem cum scriem o ecuație: \\
+
+$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$
+
+Fracțiile (numărător - numitor) pot fi scrise astfel:
+% 10 / 7
+$^{10}/_{7}$ \\
+
+% Fracții relativ complexe pot fi scrie ca
+% \frac{numărător}{numitor}
+$\frac{n!}{k!(n - k)!}$ \\
+
+Putem insera ecuații și într-un "mediu pentru ecuații".
+
+% Afișează text matematic într-un mediu pentru ecuații.
+\begin{equation} % intră în math-mode
+ c^2 = a^2 + b^2.
+ \label{eq:pitagora} % pentru referențiere
+\end{equation}
+% toate instrucțiunile cu \begin trebuie să fie cuplate cu o instrucțiune cu \end
+
+Putem referenția noua nosatră ecuație!
+~\ref{eq:pitagora} este cunoscută și ca Teorema lui Pitagora, despre care vorbim și la Sec.~\ref{subsec:pitagora}. Multe lucruri prot fi etichetate:
+figuri, ecuații, secțiuni, etc.
+
+Sumele discrete și integralele se scriu cu comenzile sum și int.
+
+% Unele compilatoare LaTeX nu acceptă să există linii goala
+% într-un mediu pentru ecuații.
+\begin{equation}
+ \sum_{i=0}^{5} f_{i}
+\end{equation}
+\begin{equation}
+ \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
+\end{equation}
+
+\section{Figuri}
+
+Să inserăm o figură. Așezarea figurilor poate fi ușor dificilă.
+Eu trebuie să mă uit peste opțiunile de așezare de fiecare dată.
+
+\begin{figure}[H] % H denumește opțiunle de așezare
+ \centering % centrează figura pe pagină
+ % Inserează o figură scalată la 0.8 din lățimea paginii.
+ %\includegraphics[width=0.8\linewidth]{right-triangle.png}
+ % Comentat pentru a nu împiedica fișierul să compileze.
+ \caption{Triunghi dreptunghic cu laturile $a$, $b$, $c$}
+ \label{fig:right-triangle}
+\end{figure}
+
+\subsection{Tabel}
+Putem insera tabele la fel cum inserăm figuri.
+
+\begin{table}[H]
+ \caption{Descriere pentru tabel}
+ % argumentele {} controlează cum vor fi afișate coloanele
+ \begin{tabular}{c|cc}
+ Număr & Nume & Prenume \\ % Numele coloanelor sunt separate prin $
+ \hline % a linie orizonală
+ 1 & Popescu & Ion \\
+ 2 & Sima & Felix
+ \end{tabular}
+\end{table}
+
+% \section{Hyperlinkuri} % În curând
+
+\section{Cum facem ca LaTeX să nu compileze ceva (de exemplu cod sursă)}
+Să zicem că vrem să includem niște cod în documentul nostru LaTeX.
+Vom avea nevoie ca LaTeX să nu încerce să interpreteze acel cod,
+ci doar să îl redea în document. Vom face asta cu un mediu verbatim.
+
+% Există și alte pachete (i.e. minty, lstlisting, etc.)
+% dar verbatim este pachetul cel mai simplu.
+\begin{verbatim}
+ print("Salut lume!")
+ a%b; % hei! putem folosi % în verbatim
+ random = 4;
+\end{verbatim}
+
+\section{Compilarea}
+Acum vă întrebați cum se compilează acest document minunat și să vă
+minunați de rezultatul, un PDF LaTeX. (da, documentul acesta chiar
+compilează). \\
+Realizarea documentului cu LaTeX va parcurge următorii pași:
+ \begin{enumerate}
+ \item Se scrie documentul în text simplu. (codul sursă)
+ \item Se compilează documentul pentru a produce un PDF.
+ Compilarea arată cam așa în Linux:\\
+ \begin{verbatim}
+ $pdflatex learn-latex.tex learn-latex.pdf
+ \end{verbatim}
+ \end{enumerate}
+
+Anumiți editor pentru LaTeX combină pașii 1 și 2 în același produs software.
+Așadar, dacă vreți să vedeți realizați pasul 1 dar nu și pasul 2, el se poate
+realiza "în spate".
+
+Scrieți toate informațiile de formatare în pasul 1. Compilarea din pasul 2
+se ocupă de producerea documentului în formatul definit în pasul 1.
+
+\section{Final}
+
+Asta e tot pentru moment!
+
+% De multe ori veți vrea să aveți o secțiune cu bibliografie în document.
+% Cea mai ușoară modalitate este folosind mediul thebibliography.
+\begin{thebibliography}{1}
+ % Similar celorlalte liste, comanda \bibitem e folosită pentru a înșirui
+ % elemente; fiecare element poate fi citat în interiorul textului
+ \bibitem{latexwiki} Uimitoarea carte wiki LaTeX: {\em https://en.wikibooks.org/wiki/LaTeX}
+ \bibitem{latextutorial} Un tutorial propriu-zis: {\em http://www.latex-tutorial.com}
+\end{thebibliography}
+
+% încheie documentul
+\end{document}
+```
+
+## Mai multe despre LaTeX
+
+* Uimitoarea carte wiki LaTeX: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX)
+* Un tutorial propriu-zis: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
diff --git a/ro-ro/python-ro.html.markdown b/ro-ro/python-ro.html.markdown
index 125ba2f4..c96e30dc 100644
--- a/ro-ro/python-ro.html.markdown
+++ b/ro-ro/python-ro.html.markdown
@@ -8,14 +8,16 @@ filename: learnpython-ro.py
lang: ro-ro
---
-Python a fost creat de Guido Van Rossum la începutul anilor '90. Python a devenit astăzi unul din
-cele mai populare limbaje de programare. M-am indrăgostit de Python pentru claritatea sa sintactică.
-Python este aproape pseudocod executabil.
+Python a fost creat de Guido Van Rossum la începutul anilor '90. Python a
+devenit astăzi unul din cele mai populare limbaje de programare.
+M-am indrăgostit de Python pentru claritatea sa sintactică. Python este aproape
+pseudocod executabil.
-Opinia dumneavoastră este binevenită! Puteţi sa imi scrieţi la [@ociule](http://twitter.com/ociule) sau ociule [at] [google's email service]
+Opinia dumneavoastră este binevenită! Puteţi sa imi scrieţi la [@ociule](http://twitter.com/ociule)
+sau ociule [at] [google's email service]
-Notă: Acest articol descrie Python 2.7, dar este util şi pentru Python 2.x. O versiune Python 3 va apărea
-în curând, în limba engleză mai întâi.
+Notă: Acest articol descrie Python 2.7, dar este util şi pentru Python 2.x.
+O versiune Python 3 va apărea în curând, în limba engleză mai întâi.
```python
# Comentariile pe o singură linie încep cu un caracter diez.
@@ -36,7 +38,8 @@ Notă: Acest articol descrie Python 2.7, dar este util şi pentru Python 2.x. O
10 * 2 #=> 20
35 / 5 #=> 7
-# Împărţirea este un pic surprinzătoare. Este de fapt împărţire pe numere întregi şi rotunjeşte
+# Împărţirea este un pic surprinzătoare. Este de fapt împărţire pe numere
+# întregi şi rotunjeşte
# automat spre valoarea mai mică
5 / 2 #=> 2
diff --git a/ro-ro/xml-ro.html.markdown b/ro-ro/xml-ro.html.markdown
new file mode 100644
index 00000000..269010c2
--- /dev/null
+++ b/ro-ro/xml-ro.html.markdown
@@ -0,0 +1,133 @@
+---
+language: xml
+filename: learnxml-ro.xml
+contributors:
+ - ["João Farias", "https://github.com/JoaoGFarias"]
+translators:
+ - ["Serban Constantin", "https://github.com/fuzzmz"]
+lang: ro-ro
+---
+
+XML este un limbaj de markup ce are ca scop stocarea si transportul de date.
+
+Spre deosebire de HTML, XML nu specifica cum sa fie afisata sau formatata
+informatia, ci doar o transporta.
+
+* Sintaxa XML
+
+```xml
+<!-- Comentariile in XML arata asa -->
+
+<?xml version="1.0" encoding="UTF-8"?>
+<librarie>
+ <carte categorie="GATIT">
+ <titlu limba="ro">Mancaruri italiene</titlu>
+ <autor>Giada De Laurentiis</autor>
+ <an>2005</an>
+ <pret>30.00</pret>
+ </carte>
+ <carte categorie="COPII">
+ <titlu limba="ro">Harry Potter</titlu>
+ <autor>J K. Rowling</autor>
+ <an>2005</an>
+ <pret>29.99</pret>
+ </carte>
+ <carte categorie="WEB">
+ <titlu limba="ro">Invata XML</titlu>
+ <autor>Erik T. Ray</autor>
+ <an>2003</an>
+ <pret>39.95</pret>
+ </carte>
+</librarie>
+
+<!-- Deasupra este un fisier XML obisnuit.
+ Incepe cu o declaratie ce adauga niste metadata (optional).
+
+ XML foloseste o structura arborescenta. Deasupra, nodul de baza este
+ 'librarie', care are trei noduri copil, toate 'carti'. Acele noduri au la
+ randul lor noduri copii si asa mai departe...
+
+ Nodurile sunt create folosind taguri deschise/inchise, iar copii sunt doar
+ noduri intre tagurile de deschis si inchis.-->
+
+
+<!-- XML transporta doua tipuri de date:
+ 1 - Atribute -> Metadata despre un nod.
+ In general, parserul XML foloseste aceasta informatie sa stocheze
+ proprietatile datelor.
+ Este caracterizat de aparitia in paranteze in cadrul tagului deschis
+ 2 - Elemente -> Date pure.
+ Asta este ceea ce parserul va extrage din documentul XML.
+ Elementele apar intre tagurile deschis si inchis, fara paranteze. -->
+
+
+<!-- Dedesubt, un element cu doua atribute -->
+<file type="gif" id="4293">computer.gif</file>
+
+
+```
+
+* Document bine formatat x Validare
+
+Un document XML este bine formatat daca este corect sintactic.
+Cu toate astea este posibil sa injectam mai multe constrangeri in document
+folosind definitii precum DTD si XML Schema.
+
+Un document XML ce foloseste o definitie de document este numit valid in
+contextul documentului.
+
+Cu acest tool poti verifica datele XML in afara codului aplicatiei.
+
+```xml
+
+<!-- Dedesubt este o versiune simplificata a documentului librarie,
+ cu aditia definitiei DTD.-->
+
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE note SYSTEM "Librarie.dtd">
+<librarie>
+ <carte categorie="GATIT">
+ <titlu >Everyday Italian</titlu>
+ <pret>30.00</pret>
+ </carte>
+</librarie>
+
+<!-- DTD-ul poate fi ceva similar cu:-->
+
+<!DOCTYPE note
+[
+<!ELEMENT librarie (carte+)>
+<!ELEMENT carte (titlu,pret)>
+<!ATTLIST carte categorie CDATA "Literatura">
+<!ELEMENT titlu (#PCDATA)>
+<!ELEMENT pret (#PCDATA)>
+]>
+
+
+<!-- DTD-ul incepe cu o declaratie.
+ Dupa, nodul de baza este declarat, cerand unul sau mai multe noduri copii
+ de tipul 'carte'.
+ Fiecare 'carte' trebuie sa contina exact un 'titlu' si 'pret' si un atribut
+ numit 'categorie', cu "Literatura" ca valoare implicita.
+ Nodurile 'titlu' si 'pret' contin parsed character data.-->
+
+<!-- DTD-ul poate fi declara si in interiorul fisierului XML.-->
+
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!DOCTYPE note
+[
+<!ELEMENT librarie (carte+)>
+<!ELEMENT carte (titlu,pret)>
+<!ATTLIST carte categorie CDATA "Literatura">
+<!ELEMENT titlu (#PCDATA)>
+<!ELEMENT pret (#PCDATA)>
+]>
+
+<librarie>
+ <carte categorie="GATIT">
+ <titlu >Everyday Italian</titlu>
+ <pret>30.00</pret>
+ </carte>
+</librarie>
+```
diff --git a/ru-ru/brainfuck-ru.html.markdown b/ru-ru/bf.html.markdown
index fcee185f..20f0fa56 100644
--- a/ru-ru/brainfuck-ru.html.markdown
+++ b/ru-ru/bf.html.markdown
@@ -1,5 +1,5 @@
---
-language: brainfuck
+language: bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]
diff --git a/ru-ru/d-ru.html.markdown b/ru-ru/d-ru.html.markdown
new file mode 100644
index 00000000..bfa3f085
--- /dev/null
+++ b/ru-ru/d-ru.html.markdown
@@ -0,0 +1,754 @@
+---
+language: D
+filename: learnd-ru.d
+contributors:
+ - ["Anton Pastukhov", "http://dprogramming.ru/"]
+ - ["Robert Brights-Gray", "http://lhs-blog.info/"]
+ - ["Andre Polykanine", "http://oire.me/"]
+lang: ru-ru
+---
+
+D - современный компилируемый язык общего назначения с Си-подобным синтаксисом,
+который сочетает удобство, продуманный дизайн и высокую производительность.
+D - это С++, сделанный правильно.
+
+```c
+// Welcome to D! Это однострочный комментарий
+
+/* многострочный
+ комментарий */
+
+/+
+ // вложенные комментарии
+
+ /* еще вложенные
+ комментарии */
+
+ /+
+ // мало уровней вложенности? Их может быть сколько угодно.
+ +/
++/
+
+/*
+ Имя модуля. Каждый файл с исходным кодом на D — модуль.
+ Если имя не указано явно, то предполагается, что оно совпадает с именем
+ файла. Например, для файла "test.d" имя модуля будет "test", если явно
+ не указать другое
+ */
+module app;
+
+// импорт модуля. Std — пространство имен стандартной библиотеки (Phobos)
+import std.stdio;
+
+// можно импортировать только нужные части, не обязательно модуль целиком
+import std.exception : enforce;
+
+// точка входа в программу — функция main, аналогично C/C++
+void main()
+{
+ writeln("Hello, world!");
+}
+
+
+
+/*** типы и переменные ***/
+
+int a; // объявление переменной типа int (32 бита)
+float b = 12.34; // тип с плавающей точкой
+double c = 56.78; // тип с плавающей точкой (64 бита)
+
+/*
+ Численные типы в D, за исключением типов с плавающей точкой и типов
+ комплексных чисел, могут быть беззнаковыми.
+ В этом случае название типа начинается с префикса "u"
+*/
+uint d = 10; ulong e = 11;
+bool b = true; // логический тип
+char d = 'd'; // UTF-символ, 8 бит. D поддерживает UTF "из коробки"
+wchar e = 'é'; // символ UTF-16
+dchar f; // и даже UTF-32, если он вам зачем-то понадобится
+
+string s = "для строк есть отдельный тип, это не просто массив char-ов из Си";
+wstring ws = "поскольку у нас есть wchar, должен быть и wstring";
+dstring ds = "...и dstring, конечно";
+
+string кириллица = "Имена переменных должны быть в Unicode, но не обязательно на латинице.";
+
+typeof(a) b = 6; // typeof возвращает тип своего выражения.
+ // В результате, b имеет такой же тип, как и a
+
+// Тип переменной, помеченной ключевым словом auto,
+// присваивается компилятором исходя из значения этой переменной
+auto x = 1; // Например, тип этой переменной будет int.
+auto y = 1.1; // этой — double
+auto z = "Zed is dead!"; // а этой — string
+
+int[3] arr = [1, 2, 3]; // простой одномерный массив с фиксированным размером
+int[] arr2 = [1, 2, 3, 4]; // динамический массив
+int[string] aa = ["key1": 5, "key2": 6]; // ассоциативный массив
+
+/*
+ Строки и массивы в D — встроенные типы. Для их использования не нужно
+ подключать ни внешние, ни даже стандартную библиотеку, хотя в последней
+ есть множество дополнительных инструментов для работы с ними.
+ */
+immutable int ia = 10; // неизменяемый тип,
+ // обозначается ключевым словом immutable
+ia += 1; // — вызовет ошибку на этапе компиляции
+
+// перечислимый (enumerable) тип,
+// более правильный способ работы с константами в D
+enum myConsts = { Const1, Const2, Const3 };
+
+// свойства типов
+writeln("Имя типа : ", int.stringof); // int
+writeln("Размер в байтах : ", int.sizeof); // 4
+writeln("Минимальное значение : ", int.min); // -2147483648
+writeln("Максимальное значение : ", int.max); // 2147483647
+writeln("Начальное значение : ", int.init); // 0. Это значение,
+ // присвоенное по умолчанию
+
+// На самом деле типов в D больше, но все мы здесь описывать не будем,
+// иначе не уложимся в Y минут.
+
+
+
+/*** Приведение типов ***/
+
+// to!(имя типа)(выражение) - для большинства конверсий
+import std.conv : to; // функция "to" - часть стандартной библиотеки, а не языка
+double d = -1.75;
+short s = to!short(d); // s = -1
+
+/*
+ cast - если вы знаете, что делаете. Кроме того, это единственный способ
+ преобразования типов-указателей в "обычные" и наоборот
+*/
+void* v;
+int* p = cast(int*)v;
+
+// Для собственного удобства можно создавать псевдонимы
+// для различных встроенных объектов
+alias int newInt; // теперь можно обращаться к newInt так, как будто бы это int
+newInt a = 5;
+
+alias newInt = int; // так тоже допустимо
+alias uint[2] pair; // дать псевдоним можно даже сложным структурам данных
+
+
+
+/*** Операторы ***/
+
+int x = 10; // присваивание
+x = x + 1; // 11
+x -= 2; // 9
+x++; // 10
+++x; // 11
+x *= 2; // 22
+x /= 2; // 11
+x = x ^^ 2; // 121 (возведение в степень)
+x ^^= 2; // 1331 (то же самое)
+
+string str1 = "Hello";
+string str2 = ", world!";
+string hw = str1 ~ str2; // Конкатенация строк
+
+int[] arr = [1, 2, 3];
+arr ~= 4; // [1, 2, 3, 4] - добавление элемента в конец массива
+
+
+
+/*** Логика и сравнения ***/
+
+int x = 0; int y = 1;
+
+x == y; // false
+x > y; // false
+x < y; // true
+x >= y; // false
+x != y; // true. ! — логическое "не"
+x > 0 || x < 1; // true. || — логическое "или"
+x > 0 && x < 1; // false && — логическое "и"
+x ^ y // true; ^ - xor (исключающее "или")
+
+// Тернарный оператор
+auto y = (x > 10) ? 1 : 0; // если x больше 10, то y равен 1,
+ // в противном случае y равен нулю
+
+
+/*** Управляющие конструкции ***/
+
+// if - абсолютно привычен
+if (a == 1) {
+ // ..
+} else if (a == 2) {
+ // ..
+} else {
+ // ..
+}
+
+// switch
+switch (a) {
+ case 1:
+ // делаем что-нибудь
+ break;
+ case 2:
+ // делаем что-нибудь другое
+ break;
+ case 3:
+ // делаем что-нибудь еще
+ break;
+ default:
+ // default обязателен, без него будет ошибка компиляции
+ break;
+}
+
+// в D есть констукция "final switch". Она не может содержать секцию "defaul"
+// и применяется, когда все перечисляемые в switch варианты должны быть
+// обработаны явным образом
+
+int dieValue = 1;
+final switch (dieValue) {
+ case 1:
+ writeln("You won");
+ break;
+
+ case 2, 3, 4, 5:
+ writeln("It's a draw");
+ break;
+
+ case 6:
+ writeln("I won");
+ break;
+}
+
+// while
+while (a > 10) {
+ // ..
+ if (number == 42) {
+ break;
+ }
+}
+
+while (true) {
+ // бесконечный цикл
+}
+
+// do-while
+do {
+ // ..
+} while (a == 10);
+
+// for
+for (int number = 1; number < 11; ++number) {
+ writeln(number); // все абсолютно стандартно
+}
+
+for ( ; ; ) {
+ // секции могут быть пустыми. Это бесконечный цикл в стиле Си
+}
+
+// foreach - универсальный и самый "правильный" цикл в D
+foreach (element; array) {
+ writeln(element); // для простых массивов
+}
+
+foreach (key, val; aa) {
+ writeln(key, ": ", val); // для ассоциативных массивов
+}
+
+foreach (c; "hello") {
+ writeln(c); // hello. Поскольку строки - это вариант массива,
+ // foreach применим и к ним
+}
+
+foreach (number; 10..15) {
+ writeln(number); // численные интервалы можно указывать явным образом
+ // этот цикл выведет значения с 10 по 14, но не 15,
+ // поскольку диапазон не включает в себя верхнюю границу
+}
+
+// foreach_reverse - в обратную сторону
+auto container = [1, 2, 3];
+foreach_reverse (element; container) {
+ writefln("%s ", element); // 3, 2, 1
+}
+
+// foreach в массивах и им подобных структурах не меняет сами структуры
+int[] a = [1, 2 ,3 ,4 ,5];
+foreach (elem; array) {
+ elem *= 2; // сам массив останется неизменным
+}
+
+writeln(a); // вывод: [1, 2, 3, 4, 5] Т.е изменений нет
+
+// добавление ref приведет к тому, что массив будет изменяться
+foreach (ref elem; array) {
+ elem *= 2;
+}
+
+writeln(a); // [2, 4, 6, 8, 10]
+
+// foreach умеет рассчитывать индексы элементов
+int[] a = [1, 2, 3, 4, 5];
+foreach (ind, elem; array) {
+ writeln(ind, " ", elem); // через ind - доступен индекс элемента,
+ // а через elem - сам элемент
+}
+
+
+
+/*** Функции ***/
+
+test(42); // Что, вот так сразу? Разве мы где-то уже объявили эту функцию?
+
+// Нет, вот она. Это не Си, здесь объявление функции не обязательно должно быть
+// до первого вызова
+int test(int argument) {
+ return argument * 2;
+}
+
+
+// В D используется единый синтаксис вызова функций
+// (UFCS, Uniform Function Call Syntax), поэтому так тоже можно:
+int var = 42.test();
+
+// и даже так, если у функции нет аргументов:
+int var2 = 42.test;
+
+// можно выстраивать цепочки:
+int var3 = 42.test.test;
+
+/*
+ Аргументы в функцию передаются по значению (т.е. функция работает не с
+ оригинальными значениями, переданными ей, а с их локальными копиями.
+ Исключение составляют объекты классов, которые передаются по ссылке.
+ Кроме того, любой параметр можно передать в функцию по ссылке с помощью
+ ключевого слова "ref"
+*/
+int var = 10;
+
+void fn1(int arg) {
+ arg += 1;
+}
+
+void fn2(ref int arg) {
+ arg += 1;
+}
+
+fn1(var); // var все еще = 10
+fn2(var); // теперь var = 11
+
+// Возвращаемое значение тоже может быть auto,
+// если его можно "угадать" из контекста
+auto add(int x, int y) {
+ return x + y;
+}
+
+auto z = add(x, y); // тип int - компилятор вывел его автоматически
+
+// Значения аргументов по умолчанию
+float linearFunction(float k, float x, float b = 1)
+{
+ return k * x + b;
+}
+
+auto linear1 = linearFunction(0.5, 2, 3); // все аргументы используются
+auto linear2 = linearFunction(0.5, 2); // один аргумент пропущен, но в функции
+ // он все равно использован и равен 1
+
+// допускается описание вложенных функций
+float quarter(float x) {
+ float doubled(float y) {
+ return y * y;
+ }
+
+ return doubled(doubled(x));
+}
+
+// функции с переменным числом аргументов
+int sum(int[] a...)
+{
+ int s = 0;
+ foreach (elem; a) {
+ s += elem;
+ }
+ return s;
+}
+
+auto sum1 = sum(1);
+auto sum2 = sum(1,2,3,4);
+
+/*
+ модификатор "in" перед аргументами функций говорит о том, что функция имеет
+ право их только просматривать. При попытке модификации такого аргумента
+ внутри функции - получите ошибку
+*/
+float printFloat(in float a)
+{
+ writeln(a);
+}
+printFloat(a); // использование таких функций - самое обычное
+
+// модификатор "out" позволяет вернуть из функции несколько результатов
+// без посредства глобальных переменных или массивов
+uint remMod(uint a, uint b, out uint modulus)
+{
+ uint remainder = a / b;
+ modulus = a % b;
+ return remainder;
+}
+
+uint modulus; // пока в этой переменной ноль
+uint rem = remMod(5, 2, modulus); // наша "хитрая" функция, и теперь
+ // в modulus - остаток от деления
+writeln(rem, " ", modulus); // вывод: 2 1
+
+
+
+/*** Структуры, классы, базовое ООП ***/
+
+// Объявление структуры. Структуры почти как в Си
+struct MyStruct {
+ int a;
+ float b;
+
+ void multiply() {
+ return a * b;
+ }
+}
+
+MyStruct str1; // Объявление переменной с типом MyStruct
+str1.a = 10; // Обращение к полю
+str1.b = 20;
+auto result = str1.multiply();
+MyStruct str2 = {4, 8} // Объявление + инициализация в стиле Си
+auto str3 = MyStruct(5, 10); // Объявление + инициализация в стиле D
+
+
+// области видимости полей и методов - 3 способа задания
+struct MyStruct2 {
+ public int a;
+
+ private:
+ float b;
+ bool c;
+
+ protected {
+ float multiply() {
+ return a * b;
+ }
+ }
+ /*
+ в дополнение к знакомым public, private и protected, в D есть еще
+ область видимости "package". Поля и методы с этим атрибутом будут
+ доступны изо всех модулей, включенных в "пакет" (package), но не
+ за его пределами. package - это "папка", в которой может храниться
+ несколько модулей. Например, в "import.std.stdio", "std" - это
+ package, в котором есть модуль stdio (и еще множество других)
+ */
+ package:
+ string d;
+
+ /* помимо этого, имеется еще один модификатор - export, который позволяет
+ использовать объявленный с ним идентификатор даже вне самой программы !
+ */
+ export:
+ string description;
+}
+
+// Конструкторы и деструкторы
+struct MyStruct3 {
+ this() { // конструктор. Для структур его не обязательно указывать явно,
+ // в этом случае пустой конструктор добавляется компилятором
+ writeln("Hello, world!");
+ }
+
+
+ // а вот это конструкция - одна из интересных идиом и представляет собой
+ // конструктор копирования, т.е конструктор, возвращающий копию структуры.
+ // Работает только в структурах.
+ this(this)
+ {
+ return this;
+ }
+
+ ~this() { // деструктор, также необязателен
+ writeln("Awww!");
+ }
+}
+
+// Объявление простейшего класса
+class MyClass {
+ int a; // в D по умолчанию данные-члены являются public
+ float b;
+}
+
+auto mc = new MyClass(); // ...и создание его экземпляра
+auto mc2 = new MyClass; // ... тоже сработает
+
+// Конструктор
+class MyClass2 {
+ int a;
+ float b;
+
+ this(int a, float b) {
+ this.a = a; // ключевое слово "this" - ссылка на объект класса
+ this.b = b;
+ }
+}
+
+auto mc2 = new MyClass2(1, 2.3);
+
+// Классы могут быть вложенными
+class Outer
+{
+ int m;
+
+ class Inner
+ {
+ int foo()
+ {
+ return m; // можно обращаться к полям "внешнего" класса
+ }
+ }
+}
+
+// наследование
+class Base {
+ int a = 1;
+ float b = 2.34;
+
+
+ // это статический метод, т.е метод который можно вызывать, обращаясь
+ // к классу напрямую, а не через создание экземпляра объекта
+ static void multiply(int x, int y)
+ {
+ writeln(x * y);
+ }
+}
+
+Base.multiply(2, 5); // используем статический метод. Результат: 10
+
+class Derived : Base {
+ string c = "Поле класса - наследника";
+
+
+ // override означает то, что наследник предоставит свою реализацию метода,
+ // переопределив метод базового класса
+ override static void multiply(int x, int y)
+ {
+ super.multiply(x, y); // super - это ссылка на класс-предок, или базовый класс
+ writeln(x * y * 2);
+ }
+}
+
+auto mc3 = new Derived();
+writeln(mc3.a); // 1
+writeln(mc3.b); // 2.34
+writeln(mc3.c); // Поле класса - наследника
+
+// Финальный класс, наследовать от него нельзя
+// кроме того, модификатор final работает не только для классов, но и для методов
+// и даже для модулей !
+final class FC {
+ int a;
+}
+
+class Derived : FC { // это вызовет ошибку
+ float b;
+}
+
+// Абстрактный класс не может быть истанциирован, но может иметь наследников
+abstract class AC {
+ int a;
+}
+
+auto ac = new AC(); // это вызовет ошибку
+
+class Implementation : AC {
+ float b;
+
+ // final перед методом нефинального класса означает запрет возможности
+ // переопределения метода
+ final void test()
+ {
+ writeln("test passed !");
+ }
+}
+
+auto impl = new Implementation(); // ОК
+
+
+
+/*** Примеси (mixins) ***/
+
+// В D можно вставлять код как строку, если эта строка известна на этапе
+// компиляции. Например:
+void main() {
+ mixin(`writeln("Hello World!");`);
+}
+
+// еще пример
+string print(string s) {
+ return `writeln("` ~ s ~ `");`;
+}
+
+void main() {
+ mixin (print("str1"));
+ mixin (print("str2"));
+}
+
+
+
+/*** Шаблоны ***/
+
+/*
+ Шаблон функции. Эта функция принимает аргументы разных типов, которые
+ подставляются вместо T на этапе компиляции. "T" - это не специальный
+ символ, а просто буква. Вместо "T" может быть любое слово, кроме ключевого.
+ */
+void print(T)(T value) {
+ writefln("%s", value);
+}
+
+void main() {
+ print(42); // В одну и ту же функцию передается: целое
+ print(1.2); // ...число с плавающей точкой,
+ print("test"); // ...строка
+}
+
+// "Шаблонных" параметров может быть сколько угодно
+void print(T1, T2)(T1 value1, T2 value2) {
+ writefln(" %s %s", value1, value2);
+}
+
+void main() {
+ print(42, "Test");
+ print(1.2, 33);
+}
+
+// Шаблон класса
+class Stack(T)
+{
+ private:
+ T[] elements;
+
+ public:
+ void push(T element) {
+ elements ~= element;
+ }
+
+ void pop() {
+ --elements.length;
+ }
+
+ T top() const @property {
+ return elements[$ - 1];
+ }
+
+ size_t length() const @property {
+ return elements.length;
+ }
+}
+
+void main() {
+ /*
+ восклицательный знак - признак шаблона. В данном случае мы создаем
+ класс и указываем, что "шаблонное" поле будет иметь тип string
+ */
+ auto stack = new Stack!string;
+
+ stack.push("Test1");
+ stack.push("Test2");
+
+ writeln(stack.top);
+ writeln(stack.length);
+
+ stack.pop;
+ writeln(stack.top);
+ writeln(stack.length);
+}
+
+
+
+/*** Диапазоны (ranges) ***/
+
+/*
+ Диапазоны - это абстракция, которая позволяет легко использовать разные
+ алгоритмы с разными структурами данных. Вместо того, чтобы определять свои
+ уникальные алгоритмы для каждой структуры, мы можем просто указать для нее
+ несколько единообразных функций, определяющих, _как_ мы получаем доступ
+ к элементам контейнера, вместо того, чтобы описывать внутреннее устройство
+ этого контейнера. Сложно? На самом деле не очень.
+
+ Простейший вид диапазона - Input Range. Для того, чтобы превратить любой
+ контейнер в Input Range, достаточно реализовать для него 3 метода:
+ - empty - проверяет, пуст ли контейнер
+ - front - дает доступ к первому элементу контейнера
+ - popFront - удаляет из контейнера первый элемент
+*/
+struct Student
+{
+ string name;
+ int number;
+ string toString() {
+ return format("%s(%s)", name, number);
+ }
+}
+
+struct School
+{
+ Student[] students;
+}
+
+struct StudentRange
+{
+ Student[] students;
+
+ this(School school) {
+ this.students = school.students;
+ }
+
+ bool empty() {
+ return students.length == 0;
+ }
+
+ Student front() {
+ return students[0];
+ }
+
+ void popFront() {
+ students = students[1 .. $];
+ }
+}
+
+void main(){
+ auto school = School([
+ Student("Mike", 1),
+ Student("John", 2) ,
+ Student("Dan", 3)
+ ]);
+ auto range = StudentRange(school);
+ writeln(range); // [Mike(1), John(2), Dan(3)]
+ writeln(school.students.length); // 3
+ writeln(range.front()); // Mike(1)
+ range.popFront();
+ writeln(range.empty()); // false
+ writeln(range); // [John(2), Dan(3)]
+}
+/*
+ Смысл в том, что нам не так уж важно внутреннее устройство контейнера, если
+ у нас есть унифицированные методы доступа к его элементам.
+ Кроме Input Range в D есть и другие типы диапазонов, которые требуют
+ реализации большего числа методов, зато дают больше контроля. Это большая
+ тема и мы не будем в подробностях освещать ее здесь.
+
+ Диапазоны - это важная часть D, они используются в нем повсеместно.
+*/
+```
+## Что дальше?
+
+- [Официальный сайт](http://dlang.org/)
+- [Онлайн-книга](http://ddili.org/ders/d.en/)
+- [Официальная вики](http://wiki.dlang.org/)
diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown
index b24ad555..a1a5cdfc 100644
--- a/ru-ru/java-ru.html.markdown
+++ b/ru-ru/java-ru.html.markdown
@@ -9,7 +9,7 @@ filename: LearnJavaRu.java
lang: ru-ru
---
-Java - это объектно ориентированный язык программирования общего назначения,
+Java - это объектно-ориентированный язык программирования общего назначения,
основанный на классах и поддерживающий параллельное программирование.
[Подробнее читайте здесь.](http://docs.oracle.com/javase/tutorial/java/index.html)
@@ -43,17 +43,41 @@ public class LearnJavaRu {
" Double: " + 3.14 +
" Boolean: " + true);
- // Чтобы напечатать что-либо не заканчивая переводом строки
- // используется System.out.print.
+ // Чтобы печатать что-либо, не заканчивая переводом строки,
+ // используйте System.out.print.
System.out.print("Hello ");
System.out.print("World");
+ // Используйте System.out.printf() для печати с форматированием
+ System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159
///////////////////////////////////////
- // Типы и Переменные
+ // Переменные
///////////////////////////////////////
+ /*
+ * Объявление переменных
+ */
// Переменные объявляются с использованием <тип> <имя>
+ int fooInt;
+ // Одновременное объявление нескольких переменных одного типа
+ // <type> <name1>, <name2>, <name3>
+ int fooInt1, fooInt2, fooInt3;
+
+ /*
+ * Инициализация переменных
+ */
+
+ // объявление и инициализация переменной <type> <name> = <val>
+ int fooInt = 1;
+ int fooInt1, fooInt2, fooInt3;
+ // инициализация нескольких переменных одного типа
+ // <type> <name1>, <name2>, <name3> = <val>
+ fooInt1 = fooInt2 = fooInt3 = 1;
+
+ /*
+ * Типы переменных
+ */
// Byte - 8-битное целое число.
// (-128 <= byte <= 127)
byte fooByte = 100;
@@ -247,7 +271,7 @@ public class LearnJavaRu {
// Switch Case
// switch работает с типами byte, short, char и int.
// Также он работает с перечислениями,
- // классом String и с некоторыми классами-обертками над
+ // классом String (с Java 7) и с некоторыми классами-обертками над
// примитивными типами: Character, Byte, Short и Integer.
int month = 3;
String monthString;
@@ -319,7 +343,7 @@ public class LearnJavaRu {
System.out.println("trek info: " + trek.toString());
} // Конец метода main.
-} // Конец класса LearnJava.
+} // Конец класса LearnJavaRu.
// Вы можете включать другие, не публичные классы в .java файл.
@@ -362,7 +386,7 @@ class Bicycle {
// Классы в Java часто реализуют сеттеры и геттеры для своих полей.
// Синтаксис определения метода:
- // <модификатор> <тип возвращаемого значения> <имя>(<аргументы>)
+ // <модификатор доступа> <тип возвращаемого значения> <имя метода>(<аргументы>)
public int getCadence() {
return cadence;
}
@@ -424,10 +448,10 @@ class PennyFarthing extends Bicycle {
// Интерфейсы
// Синтаксис определения интерфейса:
-// <модификатор доступа> interface <имя> extends <базовый интерфейс> {
-// // Константы
-// // Определение методов.
-//}
+// <модификатор доступа> interface <имя интерфейса> extends <базовый интерфейс> {
+// // Константы
+// // Определение методов
+// }
// Пример - Еда:
public interface Edible {
diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown
index eb8e4881..f71435ea 100644
--- a/ru-ru/markdown-ru.html.markdown
+++ b/ru-ru/markdown-ru.html.markdown
@@ -2,55 +2,77 @@
language: markdown
contributors:
- ["Dan Turkel", "http://danturkel.com/"]
+ - ["Jacob Ward", "http://github.com/JacobCWard/"]
+translators:
- ["Pirogov Alexey", "http://twitter.com/alex_pir"]
+ - ["Andre Polykanine", https://github.com/Oire"]
filename: markdown-ru.md
lang: ru-ru
---
Язык разметки Markdown создан Джоном Грубером (англ. John Gruber)
-и Аароном Шварцем (англ. Aaron H. Swartz) в 2004 году.
+в 2004 году.
Авторы задавались целью создать максимально удобочитаемый
и удобный в публикации облегчённый язык разметки,
пригодный для последующего преобразования в HTML
(а также и в другие форматы).
+Также реализации Markdown варьируют в зависимости от парсера.
+В этом руководстве будет указано, какие функции универсальны для языка,
+а какие зависят от конкретного парсера.
+
+- [HTML-элементы](#html-elements)
+- [Заголовки](#headings)
+- [Простейшая стилизация текста](#simple-text-styles)
+- [Абзацы](#paragraphs)
+- [Списки](#lists)
+- [Блоки кода](#code-blocks)
+- [Горизонтальный разделитель](#horizontal-rule)
+- [Ссылки](#links)
+- [Изображения](#images)
+- [Разное](#miscellany)
+
+## HTML-элементы
+Markdown является надмножеством HTML, поэтому любой HTML-файл является
+корректным документом Markdown.
+
```markdown
-<!-- Markdown является надмножеством HTML, поэтому любой HTML-файл является
-валидным документом Markdown, что позволяет использовать напрямую
+<!-- Это позволяет использовать напрямую
любые элементы HTML-разметки, такие, например, как этот комментарий.
Встроенные в документ HTML-элементы не затрагиваются парсером Markdown
-и попадают в итоговый HTML без изменений. Однако, следует понимать,
+и попадают в итоговый HTML без изменений. Однако следует понимать,
что эта же особенность не позволяет использовать разметку Markdown внутри
HTML-элементов -->
-<!-- Ещё одна особенность формата Markdown состоит в том, что поддерживаемые
-возможности разметки зависят от конкретной реализации парсера. В данном
-руководстве возможности, поддерживаемые лишь определёнными парсерами,
-сопровождаются соответствующими примечаниями. -->
-
-<!-- Заголовки -->
+## Заголовки
-<!-- HTML-элементы от <h1> до <h6> размечаются очень просто:
+HTML-элементы от <h1> до <h6> размечаются очень просто:
текст, который должен стать заголовком, предваряется
-соответствующим количеством символов "#": -->
+соответствующим количеством символов "#":
+
+```markdown
# Это заголовок h1
## Это заголовок h2
### Это заголовок h3
#### Это заголовок h4
##### Это заголовок h5
###### Это заголовок h6
+```
+Markdown позволяет размечать заголовки <h1> и <h2> ещё одним способом:
-<!-- Markdown позволяет размечать заголовки <h1> и <h2> ещё одним способом: -->
+```markdown
Это заголовок h1
================
А это заголовок h2
------------------
+```
-<!-- Простейшая стилизация текста -->
+## Простейшая стилизация текста
-<!-- Текст легко сделать полужирным и/или курсивным: -->
+Текст легко сделать полужирным и/или курсивным:
+```markdown
*Этот текст будет выведен курсивом.*
_Так же, как этот._
@@ -60,44 +82,58 @@ __И этот тоже.__
***Полужирный курсив.***
**_И тут!_**
*__И даже здесь!__*
+```
-<!-- В Github Flavored Markdown (версии Markdown, использующейся в Github,
-для рендеринга Markdown-документов) текст можно сделать зачёркнутым: -->
+В Github Flavored Markdown, стандарте, который используется в Github,
+текст также можно сделать зачёркнутым:
+```markdown
~~Зачёркнутый текст.~~
+```
+
+## Абзацы
+
+Абзацами являются любые строки, следующие друг за другом.
+Разделяются же абзацы одной или несколькими пустыми строками:
-<!-- Абзацами являются любые строки, следующие друг за другом.
-Разделяются же абзацы одной или несколькими пустыми строками: -->
+```markdown
+Это абзац. Я печатаю в абзаце, разве это не прикольно?
-Это абзац. Всё предельно просто.
+А тут уже абзац №2.
+Эта строка всё ещё относится к абзацу №2!
-А тут уже параграф №2.
-Эта строка всё ещё относится к параграфу №2!
+О, а вот это уже абзац №3!
+```
-О, а вот это уже параграф №3!
+Для вставки принудительных переносов можно завершить абзац двумя дополнительными пробелами:
-<!-- Для вставки принудительных переносов можно использовать HTML-тэг <br/>: -->
+```markdown
+Эта строка завершается двумя пробелами (выделите, чтобы увидеть!).
-Принудительный <br/> перенос!
+Над этой строкой есть <br />!
+```
-<!-- Цитаты размечаются с помощью символа ">": -->
+Цитаты размечаются с помощью символа «>»:
+```markdown
> Это цитата. В цитатах можно
-> принудительно переносить строки, вставляя ">" в начало каждой следующей строки. А можно просто оставлять достаточно длинными, и такие длинные строки будут перенесены автоматически.
+> принудительно переносить строки, вставляя «>» в начало каждой следующей строки. А можно просто оставлять их достаточно длинными, и такие длинные строки будут перенесены автоматически.
> Разницы между этими двумя подходами к переносу строк нет, коль скоро
-> каждая строка начинается с символа ">"
+> каждая строка начинается с символа «>»
> А ещё цитаты могут быть многоуровневыми:
>> как здесь
>>> и здесь :)
> Неплохо?
+```
-<!-- Списки -->
-<!-- Маркированные списки размечаются вставкой в начало каждого элемента
-одного из символов "*", "+" или "-":
-(символ должен быть одним и тем же для всех элементов) -->
+## Списки
+Маркированные списки размечаются вставкой в начало каждого элемента
+одного из символов «*», «+» или «-»:
+(символ должен быть одним и тем же для всех элементов)
+```markdown
* Список,
* Размеченный
* Звёздочками
@@ -113,167 +149,207 @@ __И этот тоже.__
- Список,
- Размеченный
- Дефисами
+```
-<!-- В нумерованных списках каждая строка начинается
-с числа и точки вслед за ним: -->
+В нумерованных списках каждая строка начинается
+с числа и точки вслед за ним:
+```markdown
1. Первый элемент
2. Второй элемент
3. Третий элемент
+```
-<!-- Заметьте, нумеровать элементы корректно необязательно. Достаточно указать
-любое число в начале каждого элемента и рендер пронумерует элементы сам!
-Правда, злоупотреблять этим не стоит :) -->
+Заметьте, нумеровать элементы корректно необязательно. Достаточно указать
+любое число в начале каждого элемента, и парсер пронумерует элементы сам!
+Правда, злоупотреблять этим не стоит :)
+```markdown
1. Первый элемент
1. Второй элемент
1. Третий элемент
-<!-- (Этот список будет отрендерен так же, как и предыдущий!) -->
+```
+(Этот список будет отображён так же, как и предыдущий!)
-<!-- Списки могут быть вложенными: -->
+Списки могут быть вложенными:
+```markdown
1. Введение
2. Начало работы
3. Примеры использования
* Простые
* Сложные
4. Заключение
+```
+
+Можно даже делать списки задач. Блок ниже создаёт HTML-флажки.
-<!-- Блоки с исходным кодом -->
-<!-- Фрагменты исходного кода выделяются очень просто - каждая строка блока должна иметь отступ в четыре пробела либо в один символ табуляции -->
+```markdown
+Для отметки флажка используйте «x»
+- [ ] Первая задача
+- [ ] Вторая задача
+Этот флажок ниже будет отмечен
+- [x] Задача была завершена
+```
+## Блоки кода
+
+Фрагменты исходного кода (обычно отмечаемые тегом `<code>`) выделяются просто:
+каждая строка блока должна иметь отступ в четыре пробела либо в один символ табуляции.
+
+```markdown
Это код,
- причём - многострочный
+ причём многострочный
+```
-<!-- Дополнительные отступы в коде следует делать с помощью четырёх пробелов: -->
+Вы также можете делать дополнительные отступы, добавляя символы табуляции
+или по четыре пробела:
+```markdown
my_array.each do |item|
puts item
end
+```
-<!-- Иногда бывает нужно вставить фрагмент кода прямо в строку текста,
+Иногда бывает нужно вставить фрагмент кода прямо в строку текста,
не выделяя код в блок. Для этого фрагменты кода нужно обрамлять
-символами "`": -->
+символами «`»:
-Например, можно выделить имя функции `go_to()` прямо посреди текста.
+```markdown
+Ваня даже не знал, что делает функция `go_to()`!
+```
-<!-- Github Flavored Markdown позволяет указать для блока кода синтаксис оного.
-В этом случае синтаксис внутри блока будет подсвечен. Пример: -->
+В Github Flavored Markdown для блоков кода можно использовать
+специальный синтаксис:
-\`\`\`ruby <!-- Только нужно будет убрать символы "\", оставив лишь "```ruby" -->
+<pre>
+<code class="highlight">&#x60;&#x60;&#x60;ruby
def foobar
- puts "Hello world!"
+ puts "Привет, мир!"
end
-\`\`\` <!-- И здесь тоже backslashes нужно убрать, т.е. оставить "```" -->
+&#x60;&#x60;&#x60;</code></pre>
-<-- Обратите внимание: фрагмент, указанный выше, не предваряется отступами,
-поскольку Github сам в состоянии определить границы блока - по строкам "```" -->
+Во фрагменте, приведённом выше, отступ не требуется.
+Кроме того, Github подсветит синтаксис языка, указанного после \`\`\`
-<!-- Горизонтальный разделитель (<hr />) -->
-<!-- Разделители добавляются вставкой строки из трёх и более
-(одинаковых) символов "*" или "-": -->
+## Горизонтальный разделитель
+Разделители (`<hr>`) добавляются вставкой строки из трёх и более
+(одинаковых) символов «*» или «-», с пробелами или без них:
+
+```markdown
***
---
-- - - <!-- между символами допустимы пробелы -->
+- - -
****************
+```
+
+## Ссылки
-<!-- Ссылки -->
-<!-- Одной из сильных сторон Markdown можно смело считать то,
+Одной из сильных сторон Markdown можно смело считать то,
как просто размечаются гиперссылки. Для создания ссылки укажите
текст ссылки, заключив его в квадратные скобки,
-и сразу после - url, заключенный в "круглые" -->
+и сразу после — URL-адрес, заключенный в круглые
+```markdown
[Ссылка!](http://test.com/)
+```
+Также для ссылки можно указать всплывающую подсказку (`title`), используя
+кавычки внутри круглых скобок:
-<!-- Также для ссылки можно указать всплывающую подсказку: -->
-
+```markdown
[Ссылка!](http://test.com/ "Ссылка на Test.com")
+```
+Относительные пути тоже возможны:
-<!-- В url можно использовать относительные пути: -->
-
+```markdown
[Перейти к музыке](/music/).
+```
-<!-- Markdown позволяет размечать ссылку в виде сноски: -->
+Markdown также позволяет размечать ссылку в виде сноски:
-[Здесь][link1] высможете узнать больше!
-А можно кликнуть [сюда][foobar], если очень хочется.
+<pre><code class="highlight">&#x5b;<span class="nv">Щёлкните эту ссылку</span>][<span class="ss">link1</span>] для подробной информации!
+&#x5b;<span class="nv">Также посмотрите эту ссылку,</span>][<span class="ss">foobar</span>] если хотите.
-<!-- где-нибудь внизу -->
-[link1]: http://test.com/ "Круто!"
-[foobar]: http://foobar.biz/ "Тоже хорошо!"
+&#x5b;<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Круто!"</span>
+&#x5b;<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Нормально!"</span></code></pre>
-<!-- Примечания:
-- Подсказка может быть заключена в одинарные кавычки вместо двойных,
- а также в круглые скобки.
-- Сноска может находиться в любом месте документа и может иметь
-идентификатор (далее ID) произвольной длины,
-лишь бы это ID был уникальным. -->
+`Title` также может быть в одинарных кавычках или круглых скобках, а также
+отсутствовать вовсе. Ссылки на сноски могут быть в любом месте документа,
+а идентификаторы могут быть какими угодно, лишь бы они были уникальными.
-<!-- Также при разметке ссылок-сносок можно опустить ID,
-если текст ссылки уникален в пределах документа: -->
+Существует также неявное именование, когда ссылка является идентификатором.
-Ссылка на [Google][].
+<pre><code class="highlight">&#x5b;<span class="nv">Это</span>][] ссылка.
-[google]: http://google.com/
+&#x5b;<span class="nv">это</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
-<!-- Правда, эта возможность не очень распространена. -->
+Правда, эта возможность не очень распространена.
-<!-- Изображения -->
-<!-- Разметка изображений очень похожа на разметку ссылок.
-Нужно всего лишь добавить "!" перед ссылкой! -->
+## Изображения
+Разметка изображений очень похожа на разметку ссылок.
+Нужно всего лишь добавить перед ссылкой восклицательный знак!
+```markdown
![Альтернативный текст для изображения](http://imgur.com/myimage.jpg "Подсказка")
+```
+Изображения тоже могут быть оформлены, как сноски.
-<!-- Изображения тоже могут быть оформлены, как сноски: -->
-
-![Альтернативный текст][myimage]
-
-![То же изображение ещё раз][myimage]
-
-[myimage]: relative/urls/cool/image.jpg "подсказка"
+<pre><code class="highlight">!&#x5b;<span class="nv">Это альтернативный текст.</span>][<span class="ss">myimage</span>]
-<!-- Ещё немного ссылок: -->
-<!-- Автоссылки -->
+&#x5b;<span class="nv">myimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"Если нужна подсказка, её можно добавить"</span></code></pre>
+## Разное
+### Автоссылки
+```markdown
Ссылка вида <http://testwebsite.com/> эквивалентна
[http://testwebsite.com/](http://testwebsite.com/)
+```
-<!-- Автоссылки для адресов электронной почты -->
+### Автоссылки для адресов электронной почты
+```markdown
<foo@bar.com>
+```
+
+### Экранирование символов
-<!-- Экранирование символов -->
+```markdown
+Я хочу напечатать *текст, заключённый в звёздочки*, но я не хочу,
+чтобы он был курсивным. Тогда я делаю так:
+\*Текст, заключённый в звёздочки\*
+```
-<!-- Может потребоваться вставить спецсимвол в текст "как есть",
-т.е. защитить его от обработки парсером.
-Такой символ должен быть "экранирован" с помощью обратной косой черты
-(символа "\"): -->
+### Клавиши на клавиатуре
+В Github Flavored Markdown для представления клавиш на клавиатуре
+вы можете использовать тег `<kbd>`.
-\*текст, заключённый в звёздочки!\*
+```markdown
+Ваш компьютер завис? Попробуйте нажать
+<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
+```
-<!-- Таблицы -->
-<!-- Таблицы официально поддерживаются только в Github Flavored Markdown,
+### Таблицы
+Таблицы официально поддерживаются только в GitHub Flavored Markdown,
да и синтаксис имеют не слишком удобный.
-Но если очень нужно, размечайте таблицы так: -->
+Но если очень нужно, размечайте таблицы так:
+```markdown
| Столбец 1 | Столбец 2 | Столбец 3 |
| :----------- | :----------: | -----------: |
| Выравнивание | Выравнивание | Выравнивание |
| влево | по центру | вправо |
+```
+Или более компактно
-<!-- Или более компактно -->
-
-Колонка 1|Колонка 2|Колонка 3
+```markdown
+Столбец 1|Столбец 2|Столбец 3
:--|:-:|--:
Выглядит|это|страшновато...
-
-<!-- Ну вот и всё! -->
-
```
-За более подробной информацией обращайтесь к [статье](http://daringfireball.net/projects/markdown/syntax) Джона Грубера о синтаксисе Markdown.
+Ну вот и всё!
-Также часто бывает полезной отличная ["шпаргалка"](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) по Markdown от Adam Pritchard.
+За более подробной информацией обращайтесь к [статье](http://daringfireball.net/projects/markdown/syntax) Джона Грубера о синтаксисе Markdown.
-Если вдруг встретите ошибки в переводе или же захотите его дополнить, делайте pull requests - авторы всегда рады обратной связи!
+Также часто бывает полезной отличная ["шпаргалка"](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) по Markdown от Адама Притчарда.
diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown
index 8eac4ddb..d60db1d8 100644
--- a/ru-ru/objective-c-ru.html.markdown
+++ b/ru-ru/objective-c-ru.html.markdown
@@ -381,20 +381,21 @@ if ([myClass respondsToSelector:selectorVar]) { // Проверяет содер
NSLog(@"MyClass не содержит метод: %@", NSStringFromSelector(selectedVar));
}
-// Имплементируйте методы в файле МойКласс.m:
+// Имплементируйте методы в файле MyClass.m:
@implementation MyClass {
long distance; // Переменная экземпляра с закрытым (private) доступом
NSNumber height;
}
-// To access a public variable from the interface file, use '_' followed by variable name:
-_count = 5; // References "int count" from MyClass interface
-// Access variables defined in implementation file:
-distance = 18; // References "long distance" from MyClass implementation
-// To use @property variable in implementation, use @synthesize to create accessor variable:
-@synthesize roString = _roString; // _roString available now in @implementation
+// Для доступа к public переменной, объявленной в интерфейсе, используйте '_' перед названием переменной:
+_count = 5; // Ссылается на "int count" из интерфейса MyClass
+// Получение доступа к переменной, объявленной в реализации происходит следующим образом:
+distance = 18; // Ссылается на "long distance" из реализации MyClass
+// Для использования в иплементации переменной, объявленной в интерфейсе с помощью @property,
+// следует использовать @synthesize для создания переменной аксессора:
+@synthesize roString = _roString; // Теперь _roString доступна в @implementation (реализации интерфейса)
-// Called before calling any class methods or instantiating any objects
+// Вызывается в первую очередь, перед вызовом других медотов класса или инициализации других объектов
+ (void)initialize
{
if (self == [MyClass class]) {
@@ -505,10 +506,10 @@ distance = 18; // References "long distance" from MyClass implementation
@end
-// Теперь, если мы хотели создать грузовой объект, мы должны вместо создания подкласса класса Car, как это будет
-// изменять функциональность Car чтобы вести себя подобно грузовику. Но давайте посмотрим, если мы хотим только добавить
-// функциональность в существующий Car. Хороший пример должен быть чистить автомобиль. Итак мы создадим
-// категорию для добавления его очистительных методов:
+// Теперь, если мы хотим создать объект Truck - грузовик, мы должны создать подкласс класса Car, что
+// изменит функционал Car и позволит вести себя подобно грузовику. Но что, если мы хотим только добавить
+// определенный функционал в уже существующий класс Car? Например - чистка автомобиля. Мы просто создадим
+// категорию, которая добавит несколько методов для чистки автомобиля в класс Car:
// @interface ИмяФайла: Car+Clean.h (ИмяБазовогоКласса+ИмяКатегории.h)
#import "Car.h" // Убедитесь в том, что базовый класс импортирован для расширения.
@@ -794,7 +795,7 @@ MyClass *arcMyClass = [[MyClass alloc] init];
// weakVar-свойство автоматически примет значение nil,
// во избежание падения приложения
@property (strong) MyClass *strongVar; // 'strong' принимает право на владение
-// объектом. Гарантирует, что объект останится в памяти для использования
+// объектом. Гарантирует, что объект останется в памяти для использования
// Для обычных переменных (не объявленных с помощью @property), используйте
// следующий способ:
diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown
index 37b6a86e..42c4d360 100644
--- a/ru-ru/php-ru.html.markdown
+++ b/ru-ru/php-ru.html.markdown
@@ -32,7 +32,7 @@ print('Hello '); // Напечатать "Hello " без перевода стр
// () необязательно применять для print и echo
echo "World\n"; // Напечатать "World" и перейти на новую строку.
-// (все утверждения должны заканчиваться ;)
+// (все утверждения должны заканчиваться точкой с запятой)
// Любые символы за пределами закрывающего тега выводятся автоматически:
?>
@@ -45,8 +45,8 @@ Hello World Again!
*/
// Переменные начинаются с символа $.
-// Правильное имя переменной начинается с буквы или знака подчеркивания,
-// и может содержать любые цифры, буквы, или знаки подчеркивания.
+// Правильное имя переменной начинается с буквы или символа подчеркивания,
+// за которым следует любое количество букв, цифр или символов подчеркивания.
// Не рекомендуется использовать кириллические символы в именах (прим. пер.)
// Логические значения нечувствительны к регистру
@@ -55,7 +55,7 @@ $boolean = false; // или FALSE или False
// Целые числа
$int1 = 12; // => 12
-$int2 = -12; // => -12-
+$int2 = -12; // => -12
$int3 = 012; // => 10 (ведущий 0 обозначает восьмеричное число)
$int4 = 0x0F; // => 15 (ведущие символы 0x означают шестнадцатеричное число)
@@ -87,7 +87,7 @@ $dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.'
$escaped = "This contains a \t tab character.";
$unescaped = 'This just contains a slash and a t: \t';
-// Заключайте переменные в фигурные скобки если это необходимо
+// Заключайте переменные в фигурные скобки, если это необходимо
$money = "I have $${number} in the bank.";
// Начиная с PHP 5.3, синтаксис nowdocs может использоваться для
@@ -106,6 +106,9 @@ END;
// Строки соединяются при помощи .
echo 'This string ' . 'is concatenated';
+// echo можно передавать строки как параметры
+echo 'Multiple', 'Parameters', 'Valid'; // печатает 'MultipleParametersValid'
+
/********************************
* Константы
@@ -114,18 +117,19 @@ echo 'This string ' . 'is concatenated';
// Константа определяется при помощи define()
// и никогда не может быть изменена во время выполнения программы!
-// Правильное имя константы начинается с буквы или символа подчеркивания,
-// и содержит любое колличество букв, цифр и знаков подчеркивания.
+// Правильное имя константы начинается с буквы или символа подчеркивания
+// и содержит любое колличество букв, цифр или символов подчеркивания.
define("FOO", "something");
-// Доступ к константе возможен через прямое указание её имени
-echo 'This outputs '.FOO;
+// Доступ к константе возможен через прямое указание её имени без знака $
+echo FOO; // печатает 'something'
+echo 'This outputs ' . FOO; // печатает 'This ouputs something'
/********************************
* Массивы
*/
-// Все массивы в PHP - это ассоциативные массивы или хеши,
+// Все массивы в PHP - это ассоциативные массивы
// Ассоциативные массивы, известные в других языках как HashMap.
@@ -189,7 +193,7 @@ $b = '0';
$c = '1';
$d = '1';
-// Утверждение (assert) выдает предупреждение если аргумент не true
+// Утверждение (assert) выдает предупреждение, если его аргумент не true
// Эти сравнения всегда будут истинными, даже если типы будут различаться
assert($a == $b); // "равно"
@@ -284,35 +288,35 @@ This is displayed otherwise.
// Использование switch.
switch ($x) {
case '0':
- print 'Switch does type coercion';
- break; // You must include a break, or you will fall through
- // to cases 'two' and 'three'
+ print 'Switch использует неточное сравнение';
+ break; // вы должны использовать break, иначе PHP будет продолжать
+ // исполнять команды следующих секций case 'two' и 'three'
case 'two':
case 'three':
- // Do something if $variable is either 'two' or 'three'
+ // делаем что-то, если $x == 'two' или $x == 'three'
break;
default:
- // Do something by default
+ // делаем что-то по умолчанию
}
// Циклы: while, do...while и for
$i = 0;
while ($i < 5) {
echo $i++;
-}; // Prints "01234"
+}; // печатает "01234"
echo "\n";
$i = 0;
do {
echo $i++;
-} while ($i < 5); // Prints "01234"
+} while ($i < 5); // печатает "01234"
echo "\n";
for ($x = 0; $x < 10; $x++) {
echo $x;
-} // Напечатает "0123456789"
+} // печатает "0123456789"
echo "\n";
@@ -335,17 +339,17 @@ echo "\n";
$i = 0;
while ($i < 5) {
if ($i === 3) {
- break; // Exit out of the while loop
+ break; // выйти из цикла while
}
echo $i++;
} // Напечатает "012"
for ($i = 0; $i < 5; $i++) {
if ($i === 3) {
- continue; // Skip this iteration of the loop
+ continue; // пропустить текущую итерацию цикла
}
echo $i;
-} // Напечатает "0124"
+} // печатает "0124"
/********************************
@@ -360,7 +364,7 @@ function my_function () {
echo my_function(); // => "Hello"
// Правильное имя функции начинается с буквы или символа подчеркивания
-// и состоит из букв, цифр или знаков подчеркивания.
+// и состоит из букв, цифр или символов подчеркивания.
function add ($x, $y = 1) { // $y по умолчанию равно 1
$result = $x + $y;
@@ -447,7 +451,7 @@ $value = include 'my-include.php';
class MyClass
{
- const MY_CONST = 'value'; // A constant
+ const MY_CONST = 'value'; // Константа
static $staticVar = 'static';
@@ -656,7 +660,10 @@ $cls = new SomeOtherNamespace\MyClass();
```
## Смотрите также:
-Посетите страницу [официальной документации PHP](http://www.php.net/manual/) для справки.
+Посетите страницу [официальной документации PHP](http://www.php.net/manual/) для справки.
+
Если вас интересуют полезные приемы использования PHP посетите [PHP The Right Way](http://www.phptherightway.com/).
+
Если вы раньше пользовались языком с хорошей организацией пакетов, посмотрите [Composer](http://getcomposer.org/).
+
Для изучения стандартов использования языка посетите PHP Framework Interoperability Group's [PSR standards](https://github.com/php-fig/fig-standards).
diff --git a/ru-ru/tmux-ru.html.markdown b/ru-ru/tmux-ru.html.markdown
new file mode 100644
index 00000000..aa7545cc
--- /dev/null
+++ b/ru-ru/tmux-ru.html.markdown
@@ -0,0 +1,252 @@
+---
+category: tool
+tool: tmux
+contributors:
+ - ["mdln", "https://github.com/mdln"]
+translators:
+ - ["Davydov Anton", "https://github.com/davydovanton"]
+filename: LearnTmux-ru.txt
+lang: ru-ru
+---
+
+[tmux](http://tmux.sourceforge.net) - терминальный мультиплексор.
+Он позволяет создавать, получать доступ и контролировать любое
+количество терминалов из единого окна.
+Сессия tmux также может быть свернута в фоновый режим, и она
+будет работать в фоне, а после к ней можно будет подключиться.
+
+
+```
+
+ tmux [command] # Запуск команды 'tmux'
+ # без какой-либо команды создаст новую сессию
+
+ new # Создать новую сессию
+ -s "Session" # Создать именованную сессию
+ -n "Window" # Создать именованное окно
+ -c "/dir" # Запустить сессию в конкретной директории
+
+ attach # Подключиться к последней/существующей сессии
+ -t "№" # Подключиться к определенной сессии
+ -d # Завершить определенную сессию
+
+ ls # Список открытых сессий
+ -a # Список всех открытых сессий
+
+ lsw # Список окон
+ -a # Список всех окон
+ -s # Список всех окон в сессии
+
+ lsp # Список панелей
+ -a # Список всех панелей
+ -s # Список всех панелей в сессии
+ -t # Список всех панелей для конкретного объекта
+
+ kill-window # Закрыть текущее окно
+ -t "#" # Закрыть конкретное окно
+ -a # Закрыть все окна
+ -a -t "#" # Закрыть все окна, кроме конкретного
+
+ kill-session # Завершить текущую сессию
+ -t "#" # Завершить конкретную сессию
+ -a # Завершить все сессии
+ -a -t "#" # Завершить все сессии, кроме конкретной
+
+```
+
+
+### "Горячие" клавиши
+
+Способ, с помощью которого контролируется любая tmux
+сессия, - комбинация клавиш, называемая 'Префиксом'.
+
+```
+----------------------------------------------------------------------
+ (C-b) = Ctrl + b # 'Префикс' необходим для
+ # использования горячих клавиш
+
+ (M-1) = Meta + 1 -или- Alt + 1
+----------------------------------------------------------------------
+
+ ? # Список всех горячих клавиш
+ : # Начать ввод в командной строке tmux
+ r # Принудительная перерисовка текущего клиента
+ c # Создать новое окно
+
+ ! # Переместить текущую панель в отдельное окно
+ % # Разделить текущую панель на две: левую и правую
+ " # Разделить текущую панель на две: верхнюю и нижнюю
+
+ n # Переместиться на следующее окно
+ p # Переместиться на предыдущее окно
+ { # Заменить текущую панель на предыдущую
+ } # Заменить текущую панель на следующую
+
+ s # Интерактивный выбор запущенных сессий
+ w # Интерактивный выбор текущего окна
+ от 0 до 9 # Выбрать окно номер 0..9
+
+ d # Отключить текущий клиент
+ D # Выбрать клиент, который будет отключен
+
+ & # Закрыть текущее окно
+ x # Закрыть текущую панель
+
+ Стрелки вверх, вниз # Переместиться на панель выше, ниже, левее
+ влево, вправо # или правее
+
+ M-1 to M-5 # Расставить панели:
+ # 1) выровнять по горизонтали
+ # 2) выровнять по вертикали
+ # 3) основное горизонтально
+ # 4) основное вертикально
+ # 5) мозаикой
+
+ C-Up, C-Down # Изменение размера текущей панели с шагом в одну
+ C-Left, C-Right # колонку
+
+ M-Up, M-Down # Изменение размера текущей панели с шагом в пять
+ M-Left, M-Right # колонок
+
+```
+
+
+### Настройка ~/.tmux.conf
+
+Файл tmux.conf может быть использован для автоматической установки
+опций при старте, как, например, .vimrc или init.el.
+
+```
+# Пример файла tmux.conf
+# 2014.10
+
+
+### Общее
+###########################################################################
+
+# Включить поддержку UTF-8
+setw -g utf8 on
+set-option -g status-utf8 on
+
+# Установить лимит истории
+set -g history-limit 2048
+
+# Порядковый номер первой панели
+set -g base-index 1
+
+# Включить поддержку мыши
+set-option -g mouse-select-pane on
+
+# Принудительная перезагрузка конфигурационного файла
+unbind r
+bind r source-file ~/.tmux.conf
+
+
+### Горячие клавиши
+###########################################################################
+
+# Отменить комбинацию C-b как стандартный префикс
+unbind C-b
+
+# Установить новую комбинацию как префикс
+set-option -g prefix `
+
+# Вернуть предыдущее окно, если префикс был нажат два раза
+bind C-a last-window
+bind ` last-window
+
+# Разрешить замену C-a и ` на F11/F12
+bind F11 set-option -g prefix C-a
+bind F12 set-option -g prefix `
+
+# Настройки клавиш
+setw -g mode-keys vi
+set-option -g status-keys vi
+
+# Перемещение между панелями, как в vim
+bind h select-pane -L
+bind j select-pane -D
+bind k select-pane -U
+bind l select-pane -R
+
+# Переключить/Заменить окно
+bind e previous-window
+bind f next-window
+bind E swap-window -t -1
+bind F swap-window -t +1
+
+# Комманды, упрощающие разделением панелей
+bind = split-window -h
+bind - split-window -v
+unbind '"'
+unbind %
+
+# Активировать центральную сессию (когда вложенный tmux) для отправки команд
+bind a send-prefix
+
+
+### Цветовая схема
+###########################################################################
+
+# Цветовая палитра строки состояния
+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
+
+# Цветовая палитра окантовки панели
+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
+
+# Цветовая палитра сообщений
+set-option -g message-fg black
+set-option -g message-bg green
+
+# Цветовая палитра статус окна
+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
+
+
+### Интерфейс
+###########################################################################
+
+# Уведомления
+setw -g monitor-activity on
+set -g visual-activity on
+set-option -g bell-action any
+set-option -g visual-bell off
+
+# Автоматическая установка заголовка окна
+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)
+
+# Настройки строки состояния
+set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]"
+
+# Показывать системные характеристики в статусбаре
+# Требует 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]"
+
+```
+
+### Ссылки
+
+[Tmux | Домашняя страница](http://tmux.sourceforge.net)
+
+[Страница мануала Tmux](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)
+
+[Отображение CPU/MEM % в статусбаре](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux)
diff --git a/ru-ru/typescript-ru.html.markdown b/ru-ru/typescript-ru.html.markdown
new file mode 100644
index 00000000..67b58a38
--- /dev/null
+++ b/ru-ru/typescript-ru.html.markdown
@@ -0,0 +1,173 @@
+---
+language: TypeScript
+lang: ru-ru
+contributors:
+ - ["Philippe Vlérick", "https://github.com/pvlerick"]
+translators:
+ - ["Fadil Mamedov", "https://github.com/fadilmamedov"]
+ - "Andre Polykanine", "https://github.com/Oire"]
+filename: learntypescript-ru.ts
+---
+
+TypeScript — это язык программирования, целью которого является лёгкая разработка широкомасштабируемых JavaScript-приложений.
+TypeScript добавляет в Javascript общие концепции, такие, как классы, модули, интерфейсы, обобщённое программирование и (опционально) статическую типизацию.
+Это надмножество языка JavaScript: весь JavaScript-код является валидным TypeScript-кодом, следовательно, может быть добавлен бесшовно в любой проект.
+Компилятор TypeScript генерирует JavaScript-код.
+
+Эта статья концентрируется только на синтаксисе TypeScript, в противовес статье о [JavaScript](javascript-ru/).
+
+Для тестирования компилятора TypeScript пройдите по ссылке в [песочницу](http://www.typescriptlang.org/Playground).
+Там вы можете написать код (с поддержкой автодополнения) и сразу же увидеть сгенерированный JavaScript код.
+
+```js
+// В TypeScript есть 3 базовых типа
+var isDone: boolean = false;
+var lines: number = 42;
+var name: string = "Андерс";
+
+// Тип «any» для случаев, когда заранее неизвестен тип переменной
+var notSure: any = 4;
+notSure = "а может быть, строка";
+notSure = false; // а теперь логический тип
+
+// Для коллекций есть типизированные массивы и обобщённые массивы
+var list: number[] = [1, 2, 3];
+// Как альтернатива, использование обобщённого массива
+var list: Array<number> = [1, 2, 3];
+
+// Перечисления:
+enum Color {Red, Green, Blue};
+var c: Color = Color.Green;
+
+// Наконец, «void» используется для обозначения того, что функция ничего не возвращает
+function bigHorribleAlert(): void {
+ alert("Я маленькое надоедливое окошко!");
+}
+
+// Функции — это объекты первого класса. Они поддерживают лямбда-синтаксис (=>)
+// и используют вывод типов (type inference)
+
+// Следующие строки кода являются эквивалентными, компилятором предполагается
+// одинаковая сигнатура, на выходе генерируется одинаковый JavaScript-код
+var f1 = function(i: number): number { return i * i; }
+// Предполагается возвращаемый тип
+var f2 = function(i: number) { return i * i; }
+var f3 = (i: number): number => { return i * i; }
+// Предполагается возвращаемый тип
+var f4 = (i: number) => { return i * i; }
+// Предполагается возвращаемый тип, в однострочной функции ключевое слово «return» не нужно
+var f5 = (i: number) => i * i;
+
+// Интерфейсы являются структурными; всё, что имеет свойства, совместимо с интерфейсом
+interface Person {
+ name: string;
+ // Опциональные свойства, помеченные символом «?»
+ age?: number;
+ // И, конечно, функции
+ move(): void;
+}
+
+// Объект, который реализует интерфейс «Person»
+// К нему можно обращаться, как к «Person», так как он имеет свойства «name» и «move»
+var p: Person = { name: "Бобби", move: () => {} };
+// Объекты, которые могут иметь опциональные свойства:
+var validPerson: Person = { name: "Бобби", age: 42, move: () => {} };
+// Это не «Person», поскольку «age» не является числовым значением
+var invalidPerson: Person = { name: "Бобби", age: true };
+
+// Интерфейсы могут также описывать функциональный тип
+interface SearchFunc {
+ (source: string, subString: string): boolean;
+}
+// Важны только типы параметров, имена — нет.
+var mySearch: SearchFunc;
+mySearch = function(src: string, sub: string) {
+ return src.search(sub) != -1;
+}
+
+// Классы. Члены класса по умолчанию являются публичными
+class Point {
+ // Свойства
+ x: number;
+
+ // Конструктор — ключевые слова public/private в данном контексте сгенерируют
+ // шаблонный код для свойства и для инициализации в конструкторе
+ // В данном примере «y» будет определён так же, как и «x», но меньшим количеством кода
+ // Значения по умолчанию также поддерживаются
+
+ constructor(x: number, public y: number = 0) {
+ this.x = x;
+ }
+
+ // Функции
+ dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
+
+ // Статические члены
+ static origin = new Point(0, 0);
+}
+
+var p1 = new Point(10 ,20);
+var p2 = new Point(25); //y будет равен 0
+
+// Наследование
+class Point3D extends Point {
+ constructor(x: number, y: number, public z: number = 0) {
+ super(x, y); // Явный вызов конструктора базового класса обязателен
+ }
+
+ // Перегрузка
+ dist() {
+ var d = super.dist();
+ return Math.sqrt(d * d + this.z * this.z);
+ }
+}
+
+// Модули, знак «.» может быть использован как разделитель для обозначения подмодулей
+module Geometry {
+ export class Square {
+ constructor(public sideLength: number = 0) {
+ }
+ area() {
+ return Math.pow(this.sideLength, 2);
+ }
+ }
+}
+
+var s1 = new Geometry.Square(5);
+
+// Локальный псевдоним для ссылки на модуль
+import G = Geometry;
+
+var s2 = new G.Square(10);
+
+// Обобщённое программирование
+// Классы
+class Tuple<T1, T2> {
+ constructor(public item1: T1, public item2: T2) {
+ }
+}
+
+// Интерфейсы
+interface Pair<T> {
+ item1: T;
+ item2: T;
+}
+
+// И функции
+var pairToTuple = function<T>(p: Pair<T>) {
+ return new Tuple(p.item1, p.item2);
+};
+
+var tuple = pairToTuple({ item1:"hello", item2:"world"});
+
+// Включение ссылки на файл определения:
+/// <reference path="jquery.d.ts" />
+
+```
+
+## Для дальнейшего чтения
+ * [Официальный веб-сайт TypeScript](http://www.typescriptlang.org/)
+ * [Спецификация языка TypeScript (pdf)](http://go.microsoft.com/fwlink/?LinkId=267238)
+ * [Anders Hejlsberg — Introducing TypeScript на Channel 9](http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript)
+ * [Исходный код на GitHub](https://github.com/Microsoft/TypeScript)
+ * [Definitely Typed — репозиторий определений типов](http://definitelytyped.org/)
diff --git a/ruby.html.markdown b/ruby.html.markdown
index b7f8b4a1..adf5ce81 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -285,7 +285,7 @@ hash.each do |key, value|
puts "#{key} is #{value}"
end
-# If you still need and index you can use "each_with_index" and define an index
+# If you still need an index you can use "each_with_index" and define an index
# variable
array.each_with_index do |element, index|
puts "#{element} is number #{index} in the array"
@@ -411,6 +411,28 @@ def guests(*array)
array.each { |guest| puts guest }
end
+# If a method returns an array, you can use destructuring assignment
+def foods
+ ['pancake', 'sandwich', 'quesadilla']
+end
+breakfast, lunch, dinner = foods
+breakfast #=> 'pancake'
+dinner #=> 'quesadilla'
+
+# By convention, all methods that return booleans end with a question mark
+5.even? # false
+5.odd? # true
+
+# And if a method ends with an exclamation mark, it does something destructive
+# like mutate the receiver. Many methods have a ! version to make a change, and
+# a non-! version to just return a new changed version
+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"
+
+
# Define a class with the class keyword
class Human
@@ -594,3 +616,4 @@ Something.new.qux # => 'qux'
- [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/scala.html.markdown b/scala.html.markdown
index bc8cd422..745605ed 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -48,7 +48,7 @@ println(10)
// Printing, without forcing a new line on next print
print("Hello world")
print(10)
-// Hello world!10
+// Hello world10
// Declaring values is done using either var or val.
// val declarations are immutable, whereas vars are mutable. Immutability is
@@ -237,7 +237,7 @@ r foreach println
(5 to 1 by -1) foreach (println)
-// A while loops
+// A while loop
var i = 0
while (i < 10) { println("i " + i); i += 1 }
@@ -245,17 +245,18 @@ while (i < 10) { println("i " + i); i += 1 } // Yes, again. What happened? Why
i // Show the value of i. Note that while is a loop in the classical sense -
// it executes sequentially while changing the loop variable. while is very
- // fast, faster that Java loops, but using the combinators and
- // comprehensions above is easier to understand and parallelize
+ // fast, but using the combinators and comprehensions above is easier
+ // to understand and parallelize
-// A do while loop
+// A do-while loop
i = 0
do {
println("i is still less than 10")
i += 1
} while (i < 10)
-// Tail recursion is an idiomatic way of doing recurring things in Scala.
+// Recursion is the idiomatic way of repeating an action in Scala (as in most
+// other functional languages).
// Recursive functions need an explicit return type, the compiler can't infer it.
// Here it's Unit.
def showNumbersInRange(a: Int, b: Int): Unit = {
@@ -273,7 +274,7 @@ val x = 10
if (x == 1) println("yeah")
if (x == 10) println("yeah")
if (x == 11) println("yeah")
-if (x == 11) println ("yeah") else println("nay")
+if (x == 11) println("yeah") else println("nay")
println(if (x == 10) "yeah" else "nope")
val text = if (x == 10) "yeah" else "nope"
@@ -327,9 +328,15 @@ divideInts(10, 3) // (Int, Int) = (3,1)
val d = divideInts(10, 3) // (Int, Int) = (3,1)
d._1 // Int = 3
-
d._2 // Int = 1
+// Alternatively you can do multiple-variable assignment to tuple, which is more
+// convenient and readable in many cases
+val (div, mod) = divideInts(10, 3)
+
+div // Int = 3
+mod // Int = 1
+
/////////////////////////////////////////////////
// 5. Object Oriented Programming
@@ -460,6 +467,9 @@ def matchEverything(obj: Any): String = obj match {
// You can nest patterns:
case List(List((1, 2, "YAY"))) => "Got a list of list of tuple"
+
+ // Match any case (default) if all previous haven't matched
+ case _ => "Got unknown object"
}
// In fact, you can pattern match any object with an "unapply" method. This
@@ -612,6 +622,9 @@ import scala.collection.immutable.{List => ImmutableList}
// Import all classes, except some. The following excludes Map and Set:
import scala.collection.immutable.{Map => _, Set => _, _}
+// Java classes can also be imported. Scala syntax can be used
+import java.swing.{JFrame, JWindow}
+
// Your programs entry point is defined in an scala file using an object, with a
// single method, main:
object Application {
diff --git a/self.html.markdown b/self.html.markdown
index 9290a0c9..fc7f69db 100644
--- a/self.html.markdown
+++ b/self.html.markdown
@@ -60,7 +60,7 @@ also sending the message 'true' to the lobby."
# Sending messages to objects
-Messages can either be unary, binary or keyword. Precedence is in that order. Unlike Smalltalk, the precedence of binary messages must be specified, and all keywords after the first must start with a capital letter. Messages are separeated from their destination by whitespace.
+Messages can either be unary, binary or keyword. Precedence is in that order. Unlike Smalltalk, the precedence of binary messages must be specified, and all keywords after the first must start with a capital letter. Messages are separated from their destination by whitespace.
```
"unary message, sends 'printLine' to the object '23'
diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown
index 3b388505..2c17b753 100644
--- a/smalltalk.html.markdown
+++ b/smalltalk.html.markdown
@@ -37,7 +37,7 @@ Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/j
`"Comments are enclosed in quotes"`
-`"Period (.) is the statement seperator"`
+`"Period (.) is the statement separator"`
## Transcript:
```
@@ -305,7 +305,7 @@ result := (switch at: $B) value.
x := 4. y := 1.
[x > 0] whileTrue: [x := x - 1. y := y * 2]. "while true loop"
[x >= 4] whileFalse: [x := x + 1. y := y * 2]. "while false loop"
-x timesRepeat: [y := y * 2]. "times repear loop (i := 1 to x)"
+x timesRepeat: [y := y * 2]. "times repeat loop (i := 1 to x)"
1 to: x do: [:a | y := y * 2]. "for loop"
1 to: x by: 2 do: [:a | y := y / 2]. "for loop with specified increment"
#(5 4 3) do: [:a | x := x + a]. "iterate over array elements"
@@ -320,7 +320,7 @@ y := x isUppercase. "test if upper case"
y := x isLetter. "test if letter"
y := x isDigit. "test if digit"
y := x isAlphaNumeric. "test if alphanumeric"
-y := x isSeparator. "test if seperator char"
+y := x isSeparator. "test if separator char"
y := x isVowel. "test if vowel"
y := x digitValue. "convert to numeric digit value"
y := x asLowercase. "convert to lower case"
diff --git a/solidity.html.markdown b/solidity.html.markdown
new file mode 100644
index 00000000..a511bbb3
--- /dev/null
+++ b/solidity.html.markdown
@@ -0,0 +1,795 @@
+---
+language: Solidity
+filename: learnSolidity.sol
+contributors:
+ - ["Nemil Dalal", "https://www.nemil.com"]
+ - ["Joseph Chow", ""]
+---
+
+Solidity lets you program on [Ethereum](https://www.ethereum.org/), a
+blockchain-based virtual machine that allows the creation and
+execution of smart contracts, without needing centralized or trusted parties.
+
+Solidity is a statically typed, contract programming language that has
+similarities to Javascript and C. Like objects in OOP, each contract contains
+state variables, functions, and common data types. Contract-specific features
+include modifier (guard) clauses, event notifiers for listeners, and custom
+global variables.
+
+Some Ethereum contract examples include crowdfunding, voting, and blind auctions.
+
+As Solidity and Ethereum are under active development, experimental or beta
+features are explicitly marked, and subject to change. Pull requests welcome.
+
+```javascript
+// First, a simple Bank contract
+// Allows deposits, withdrawals, and balance checks
+
+// simple_bank.sol (note .sol extension)
+/* **** START EXAMPLE **** */
+
+// Start with Natspec comment (the three slashes)
+// used for documentation - and as descriptive data for UI elements/actions
+
+/// @title SimpleBank
+/// @author nemild
+
+/* 'contract' has similarities to 'class' in other languages (class variables,
+inheritance, etc.) */
+contract SimpleBank { // CamelCase
+ // Declare state variables outside function, persist through life of contract
+
+ // dictionary that maps addresses to balances
+ mapping (address => uint) private balances;
+
+ // "private" means that other contracts can't directly query balances
+ // but data is still viewable to other parties on blockchain
+
+ address public owner;
+ // 'public' makes externally readable (not writeable) by users or contracts
+
+ // Events - publicize actions to external listeners
+ event DepositMade(address accountAddress, uint amount);
+
+ // Constructor, can receive one or many variables here; only one allowed
+ function AcmeBank() {
+ // msg provides details about the message that's sent to the contract
+ // msg.sender is contract caller (address of contract creator)
+ owner = msg.sender;
+ }
+
+ /// @notice Deposit ether into bank
+ /// @return The balance of the user after the deposit is made
+ function deposit() public returns (uint) {
+ balances[msg.sender] += msg.value;
+ // no "this." or "self." required with state variable
+ // all values set to data type's initial value by default
+
+ DepositMade(msg.sender, msg.value); // fire event
+
+ return balances[msg.sender];
+ }
+
+ /// @notice Withdraw ether from bank
+ /// @dev This does not return any excess ether sent to it
+ /// @param withdrawAmount amount you want to withdraw
+ /// @return The balance remaining for the user
+ function withdraw(uint withdrawAmount) public returns (uint remainingBal) {
+ if(balances[msg.sender] >= withdrawAmount) {
+ balances[msg.sender] -= withdrawAmount;
+
+ if (!msg.sender.send(withdrawAmount)) {
+ // to be safe, may be sending to contract that
+ // has overridden 'send' which may then fail
+ balances[msg.sender] += withdrawAmount;
+ }
+ }
+
+ return balances[msg.sender];
+ }
+
+ /// @notice Get balance
+ /// @return The balance of the user
+ // 'constant' prevents function from editing state variables;
+ // allows function to run locally/off blockchain
+ function balance() constant returns (uint) {
+ return balances[msg.sender];
+ }
+
+ // Fallback function - Called if other functions don't match call or
+ // sent ether without data
+ // Typically, called when invalid data is sent
+ // Added so ether sent to this contract is reverted if the contract fails
+ // otherwise, the sender's money is transferred to contract
+ function () {
+ throw; // throw reverts state to before call
+ }
+}
+// ** END EXAMPLE **
+
+
+// Now, the basics of Solidity
+
+// 1. DATA TYPES AND ASSOCIATED METHODS
+// uint used for currency amount (there are no doubles
+// or floats) and for dates (in unix time)
+uint x;
+
+// int of 256 bits, cannot be changed after instantiation
+int constant a = 8;
+int256 constant a = 8; // same effect as line above, here the 256 is explicit
+uint constant VERSION_ID = 0x123A1; // A hex constant
+// with 'constant', compiler replaces each occurrence with actual value
+
+
+// For int and uint, can explicitly set space in steps of 8 up to 256
+// e.g., int8, int16, int24
+uint8 b;
+int64 c;
+uint248 e;
+
+// Be careful that you don't overflow, and protect against attacks that do
+
+// No random functions built in, use other contracts for randomness
+
+// Type casting
+int x = int(b);
+
+bool b = true; // or do 'var b = true;' for inferred typing
+
+// Addresses - holds 20 byte/160 bit Ethereum addresses
+// No arithmetic allowed
+address public owner;
+
+// Types of accounts:
+// Contract account: address set on create (func of creator address, num transactions sent)
+// External Account: (person/external entity): address created from public key
+
+// Add 'public' field to indicate publicly/externally accessible
+// a getter is automatically created, but NOT a setter
+
+// All addresses can be sent ether
+owner.send(SOME_BALANCE); // returns false on failure
+if (owner.send) {} // typically wrap in 'if', as contract addresses have
+// functions have executed on send and can fail
+
+// can override send by defining your own
+
+// Can check balance
+owner.balance; // the balance of the owner (user or contract)
+
+
+// Bytes available from 1 to 32
+byte a; // byte is same as bytes1
+bytes2 b;
+bytes32 c;
+
+// Dynamically sized bytes
+bytes m; // A special array, same as byte[] array (but packed tightly)
+// More expensive than byte1-byte32, so use those when possible
+
+// same as bytes, but does not allow length or index access (for now)
+string n = "hello"; // stored in UTF8, note double quotes, not single
+// string utility functions to be added in future
+// prefer bytes32/bytes, as UTF8 uses more storage
+
+// Type inferrence
+// var does inferred typing based on first assignment,
+// can't be used in functions parameters
+var a = true;
+// use carefully, inference may provide wrong type
+// e.g., an int8, when a counter needs to be int16
+
+// var can be used to assign function to variable
+function a(uint x) returns (uint) {
+ return x * 2;
+}
+var f = a;
+f(22); // call
+
+// by default, all values are set to 0 on instantiation
+
+// Delete can be called on most types
+// (does NOT destroy value, but sets value to 0, the initial value)
+uint x = 5;
+
+
+// Destructuring/Tuples
+(x, y) = (2, 7); // assign/swap multiple value
+
+
+// 2. DATA STRUCTURES
+// Arrays
+bytes32[5] nicknames; // static array
+bytes32[] names; // dynamic array
+uint newLength = names.push("John"); // adding returns new length of the array
+// Length
+names.length; // get length
+names.length = 1; // lengths can be set (for dynamic arrays in storage only)
+
+// multidimensional array
+uint x[][5]; // arr with 5 dynamic array elements (opp order of most languages)
+
+// Dictionaries (any type to any other type)
+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
+// 'public' created a getter (but not setter) like the following:
+function balances(address _account) returns (uint balance) {
+ return balances[_account];
+}
+
+// Nested mappings
+mapping (address => mapping (address => uint)) public custodians;
+
+// To delete
+delete balances["John"];
+delete balances; // sets all elements to 0
+
+// Unlike other languages, CANNOT iterate through all elements in
+// mapping, without knowing source keys - can build data structure
+// on top to do this
+
+// Structs and enums
+struct Bank {
+ address owner;
+ uint balance;
+}
+Bank b = Bank({
+ owner: msg.sender,
+ balance: 5
+});
+// or
+Bank c = Bank(msg.sender, 5);
+
+c.amount = 5; // set to new value
+delete b;
+// sets to initial value, set all variables in struct to 0, except mappings
+
+// Enums
+enum State { Created, Locked, Inactive }; // often used for state machine
+State public state; // Declare variable from enum
+state = State.Created;
+// enums can be explicitly converted to ints
+uint createdState = uint(State.Created); // 0
+
+// Data locations: Memory vs. storage vs. stack - all complex types (arrays,
+// structs) have a data location
+// 'memory' does not persist, 'storage' does
+// Default is 'storage' for local and state variables; 'memory' for func params
+// stack holds small local variables
+
+// for most types, can explicitly set which data location to use
+
+
+// 3. Simple operators
+// Comparisons, bit operators and arithmetic operators are provided
+// exponentiation: **
+// exclusive or: ^
+// bitwise negation: ~
+
+
+// 4. Global Variables of note
+// ** this **
+this; // address of contract
+// often used at end of contract life to send remaining balance to party
+this.balance;
+this.someFunction(); // calls func externally via call, not via internal jump
+
+// ** msg - Current message received by the contract ** **
+msg.sender; // address of sender
+msg.value; // amount of ether provided to this contract in wei
+msg.data; // bytes, complete call data
+msg.gas; // remaining gas
+
+// ** tx - This transaction **
+tx.origin; // address of sender of the transaction
+tx.gasprice; // gas price of the transaction
+
+// ** block - Information about current block **
+now; // current time (approximately), alias for block.timestamp (uses Unix time)
+block.number; // current block number
+block.difficulty; // current block difficulty
+block.blockhash(1); // returns bytes32, only works for most recent 256 blocks
+block.gasLimit();
+
+// ** storage - Persistent storage hash **
+storage['abc'] = 'def'; // maps 256 bit words to 256 bit words
+
+
+// 4. FUNCTIONS AND MORE
+// A. Functions
+// Simple function
+function increment(uint x) returns (uint) {
+ x += 1;
+ return x;
+}
+
+// Functions can return many arguments, and by specifying returned arguments
+// name don't need to explicitly return
+function increment(uint x, uint y) returns (uint x, uint y) {
+ x += 1;
+ y += 1;
+}
+// Call previous functon
+uint (a,b) = increment(1,1);
+
+// 'constant' indicates that function does not/cannot change persistent vars
+// Constant function execute locally, not on blockchain
+uint y;
+
+function increment(uint x) constant returns (uint x) {
+ x += 1;
+ y += 1; // this line would fail
+ // y is a state variable, and can't be changed in a constant function
+}
+
+// 'Function Visibility specifiers'
+// These can be placed where 'constant' is, including:
+// public - visible externally and internally (default)
+// external
+// private - only visible in the current contract
+// internal - only visible in current contract, and those deriving from it
+
+// Functions hoisted - and can assign a function to a variable
+function a() {
+ var z = b;
+ b();
+}
+
+function b() {
+
+}
+
+
+// Prefer loops to recursion (max call stack depth is 1024)
+
+// B. Events
+// Events are notify external parties; easy to search and
+// access events from outside blockchain (with lightweight clients)
+// typically declare after contract parameters
+
+// Declare
+event Sent(address from, address to, uint amount); // note capital first letter
+
+// Call
+Sent(from, to, amount);
+
+// For an external party (a contract or external entity), to watch:
+Coin.Sent().watch({}, '', function(error, result) {
+ if (!error) {
+ console.log("Coin transfer: " + result.args.amount +
+ " coins were sent from " + result.args.from +
+ " to " + result.args.to + ".");
+ console.log("Balances now:\n" +
+ "Sender: " + Coin.balances.call(result.args.from) +
+ "Receiver: " + Coin.balances.call(result.args.to));
+ }
+}
+// Common paradigm for one contract to depend on another (e.g., a
+// contract that depends on current exchange rate provided by another)
+
+// C. Modifiers
+// Modifiers validate inputs to functions such as minimal balance or user auth;
+// similar to guard clause in other languages
+
+// '_' (underscore) often included as last line in body, and indicates
+// function being called should be placed there
+modifier onlyAfter(uint _time) { if (now <= _time) throw; _ }
+modifier onlyOwner { if (msg.sender == owner) _ }
+// commonly used with state machines
+modifier onlyIfState (State currState) { if (currState != State.A) _ }
+
+// Append right after function declaration
+function changeOwner(newOwner)
+onlyAfter(someTime)
+onlyOwner()
+onlyIfState(State.A)
+{
+ owner = newOwner;
+}
+
+// underscore can be included before end of body,
+// but explicitly returning will skip, so use carefully
+modifier checkValue(uint amount) {
+ _
+ if (msg.value > amount) {
+ msg.sender.send(amount - msg.value);
+ }
+}
+
+
+// 6. BRANCHING AND LOOPS
+
+// All basic logic blocks work - including if/else, for, while, break, continue
+// return - but no switch
+
+// Syntax same as javascript, but no type conversion from non-boolean
+// to boolean (comparison operators must be used to get the boolean val)
+
+
+// 7. OBJECTS/CONTRACTS
+
+// A. Calling external contract
+contract infoFeed {
+ function info() returns (uint ret) { return 42; }
+}
+
+contract Consumer {
+ InfoFeed feed; // points to contract on blockchain
+
+ // Set feed to existing contract instance
+ function setFeed(address addr) {
+ // automatically cast, be careful; constructor is not called
+ feed = InfoFeed(addr);
+ }
+
+ // Set feed to new instance of contract
+ function createNewFeed() {
+ feed = new InfoFeed(); // new instance created; constructor called
+ }
+
+ function callFeed() {
+ // final parentheses call contract, can optionally add
+ // custom ether value or gas
+ feed.info.value(10).gas(800)();
+ }
+}
+
+// B. Inheritance
+
+// Order matters, last inherited contract (i.e., 'def') can override parts of
+// previously inherited contracts
+contract MyContract is abc, def("a custom argument to def") {
+
+// Override function
+ function z() {
+ if (msg.sender == owner) {
+ def.z(); // call overridden function from def
+ super.z(); // call immediate parent overriden function
+ }
+ }
+}
+
+// abstract function
+function someAbstractFunction(uint x);
+// cannot be compiled, so used in base/abstract contracts
+// that are then implemented
+
+// C. Import
+
+import "filename";
+import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol";
+
+// Importing under active development
+// Cannot currently be done at command line
+
+
+// 8. OTHER KEYWORDS
+
+// A. Throwing
+// Throwing
+throw; // reverts unused money to sender, state is reverted
+// Can't currently catch
+
+// Common design pattern is:
+if (!addr.send(123)) {
+ throw;
+}
+
+// B. Selfdestruct
+// selfdestruct current contract, sending funds to address (often creator)
+selfdestruct(SOME_ADDRESS);
+
+// removes storage/code from current/future blocks
+// helps thin clients, but previous data persists in blockchain
+
+// Common pattern, lets owner end the contract and receive remaining funds
+function remove() {
+ if(msg.sender == creator) { // Only let the contract creator do this
+ selfdestruct(creator); // Makes contract inactive, returns funds
+ }
+}
+
+// May want to deactivate contract manually, rather than selfdestruct
+// (ether sent to selfdestructed contract is lost)
+
+
+// 9. CONTRACT DESIGN NOTES
+
+// A. Obfuscation
+// All variables are publicly viewable on blockchain, so anything
+// that is private needs to be obfuscated (e.g., hashed w/secret)
+
+// Steps: 1. Commit to something, 2. Reveal commitment
+sha3("some_bid_amount", "some secret"); // commit
+
+// call contract's reveal function in the future
+// showing bid plus secret that hashes to SHA3
+reveal(100, "mySecret");
+
+// B. Storage optimization
+// Writing to blockchain can be expensive, as data stored forever; encourages
+// smart ways to use memory (eventually, compilation will be better, but for now
+// benefits to planning data structures - and storing min amount in blockchain)
+
+// Cost can often be high for items like multidimensional arrays
+// (cost is for storing data - not declaring unfilled variables)
+
+// C. Data access in blockchain
+// Cannot restrict human or computer from reading contents of
+// transaction or transaction's state
+
+// While 'private' prevents other *contracts* from reading data
+// directly - any other party can still read data in blockchain
+
+// All data to start of time is stored in blockchain, so
+// anyone can observe all previous data and changes
+
+// D. Cron Job
+// Contracts must be manually called to handle time-based scheduling; can create external
+// code to regularly ping, or provide incentives (ether) for others to
+
+// E. Observer Pattern
+// An Observer Pattern lets you register as a subscriber and
+// register a function which is called by the oracle (note, the oracle pays
+// for this action to be run)
+// Some similarities to subscription in Pub/sub
+
+// This is an abstract contract, both client and server classes import
+// the client should implement
+contract SomeOracleCallback {
+ function oracleCallback(int _value, uint _time, bytes32 info) external;
+}
+
+contract SomeOracle {
+ SomeOracleCallback[] callbacks; // array of all subscribers
+
+ // Register subscriber
+ function addSubscriber(SomeOracleCallback a) {
+ callbacks.push(a);
+ }
+
+ function notify(value, time, info) private {
+ for(uint i = 0;i < callbacks.length; i++) {
+ // all called subscribers must implement the oracleCallback
+ callbacks[i].oracleCallback(value, time, info);
+ }
+ }
+
+ function doSomething() public {
+ // Code to do something
+
+ // Notify all subscribers
+ notify(_value, _time, _info);
+ }
+}
+
+// Now, your client contract can addSubscriber by importing SomeOracleCallback
+// and registering with Some Oracle
+
+// F. State machines
+// see example below for State enum and inState modifier
+
+
+// *** EXAMPLE: A crowdfunding example (broadly similar to Kickstarter) ***
+// ** START EXAMPLE **
+
+// CrowdFunder.sol
+
+/// @title CrowdFunder
+/// @author nemild
+contract CrowdFunder {
+ // Variables set on create by creator
+ address public creator;
+ address public fundRecipient; // creator may be different than recipient
+ uint public minimumToRaise; // required to tip, else everyone gets refund
+ string campaignUrl;
+
+ // Data structures
+ enum State {
+ Fundraising,
+ ExpiredRefundPending,
+ Successful,
+ ExpiredRefundComplete
+ }
+ struct Contribution {
+ uint amount;
+ address contributor;
+ }
+
+ // State variables
+ State public state = State.Fundraising; // initialize on create
+ uint public totalRaised;
+ uint public raiseBy;
+ Contribution[] contributions;
+
+ event fundingReceived(address addr, uint amount, uint currentTotal);
+ event allRefundsSent();
+ event winnerPaid(address winnerAddress);
+
+ modifier inState(State _state) {
+ if (state != _state) throw;
+ _
+ }
+
+ modifier isCreator() {
+ if (msg.sender != creator) throw;
+ _
+ }
+
+ modifier atEndOfLifecycle() {
+ if(state != State.ExpiredRefundComplete && state != State.Successful) {
+ throw;
+ }
+ }
+
+ function CrowdFunder(
+ uint timeInHoursForFundraising,
+ string _campaignUrl,
+ address _fundRecipient,
+ uint _minimumToRaise)
+ {
+ creator = msg.sender;
+ fundRecipient = _fundRecipient;
+ campaignUrl = _campaignUrl;
+ minimumToRaise = _minimumToRaise;
+ raiseBy = now + (timeInHoursForFundraising * 1 hours);
+ }
+
+ function contribute()
+ public
+ inState(State.Fundraising)
+ {
+ contributions.push(
+ Contribution({
+ amount: msg.value,
+ contributor: msg.sender
+ }) // use array, so can iterate
+ );
+ totalRaised += msg.value;
+
+ fundingReceived(msg.sender, msg.value, totalRaised);
+
+ checkIfFundingCompleteOrExpired();
+ }
+
+ function checkIfFundingCompleteOrExpired() {
+ if (totalRaised > minimumToRaise) {
+ state = State.Successful;
+ payOut();
+
+ // could incentivize sender who initiated state change here
+ } else if ( now > raiseBy ) {
+ state = State.ExpiredRefundPending;
+ refundAll();
+ }
+ }
+
+ function payOut()
+ public
+ inState(State.Successful)
+ {
+ if(!fundRecipient.send(this.balance)) {
+ throw;
+ }
+
+ winnerPaid(fundRecipient);
+ }
+
+ function refundAll()
+ public
+ inState(State.ExpiredRefundPending)
+ {
+ uint length = contributions.length;
+ for (uint i = 0; i < length; i++) {
+ if(!contributions[i].contributor.send(contributions[i].amount)) {
+ throw;
+ }
+ }
+
+ allRefundsSent();
+ state = State.ExpiredRefundComplete;
+ }
+
+ function removeContract()
+ public
+ isCreator()
+ atEndOfLifecycle()
+ {
+ selfdestruct(msg.sender);
+ }
+
+ function () { throw; }
+}
+// ** END EXAMPLE **
+
+
+// 10. OTHER NATIVE FUNCTIONS
+
+// Currency units
+// Currency is defined using wei, smallest unit of Ether
+uint minAmount = 1 wei;
+uint a = 1 finney; // 1 ether == 1000 finney
+// Other units, see: http://ether.fund/tool/converter
+
+// Time units
+1 == 1 second
+1 minutes == 60 seconds
+
+// Can multiply a variable times unit, as units are not stored in a variable
+uint x = 5;
+(x * 1 days); // 5 days
+
+// Careful about leap seconds/years with equality statements for time
+// (instead, prefer greater than/less than)
+
+// Cryptography
+// All strings passed are concatenated before hash action
+sha3("ab", "cd");
+ripemd160("abc");
+sha256("def");
+
+
+// 11. LOW LEVEL FUNCTIONS
+// call - low level, not often used, does not provide type safety
+successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2');
+
+// callcode - Code at target address executed in *context* of calling contract
+// provides library functionality
+someContractAddress.callcode('function_name');
+
+
+// 12. STYLE NOTES
+// Based on Python's PEP8 style guide
+
+// Quick summary:
+// 4 spaces for indentation
+// Two lines separate contract declarations (and other top level declarations)
+// Avoid extraneous spaces in parentheses
+// Can omit curly braces for one line statement (if, for, etc)
+// else should be placed on own line
+
+
+// 13. NATSPEC COMENTS
+// used for documentation, commenting, and external UIs
+
+// Contract natspec - always above contract definition
+/// @title Contract title
+/// @author Author name
+
+// Function natspec
+/// @notice information about what function does; shown when function to execute
+/// @dev Function documentation for developer
+
+// Function parameter/return value natspec
+/// @param someParam Some description of what the param does
+/// @return Description of the return value
+```
+
+## Additional resources
+- [Solidity Docs](https://solidity.readthedocs.org/en/latest/)
+- [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide.
+- [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/)
+- [Gitter Chat room](https://gitter.im/ethereum/solidity)
+- [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/)
+- Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc))
+
+## Sample contracts
+- [Dapp Bin](https://github.com/ethereum/dapp-bin)
+- [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts)
+- [ConsenSys Contracts](https://github.com/ConsenSys/dapp-store-contracts)
+- [State of Dapps](http://dapps.ethercasts.com/)
+
+## Information purposefully excluded
+- Libraries
+
+## Style
+- Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy
+
+## Future To Dos
+- New keywords: protected, inheritable
+
+Feel free to send a pull request with any edits - or email nemild -/at-/ gmail
diff --git a/sv-se/json-sv.html.markdown b/sv-se/json-sv.html.markdown
new file mode 100644
index 00000000..c2ee36dd
--- /dev/null
+++ b/sv-se/json-sv.html.markdown
@@ -0,0 +1,62 @@
+---
+language: json
+filename: learnjson-sv.json
+contributors:
+ - ["Anna Harren", "https://github.com/iirelu"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+translators:
+ - ["Lari Kovanen", "https://github.com/larkov"]
+lang: sv-se
+---
+
+Eftersom JSON är ett extremt lätt data-utbytes format så kommer detta
+förmodligen att vara den lättaste "Learn X in Y Minutes" någonsin.
+
+JSON i dess renaste form har inga kommentarer, men de flesta tolkarna accepterar
+C-stils (`//`, `/* */`) kommentarer. Detta dokument kommer dock att tillämpa
+100% giltigt JSON. Lyckligtvis så är resten av dokumentet självförklarande.
+
+
+```json
+{
+ "nyckel": "värde",
+
+ "nycklar": "måste alltid omslutas med dubbla citationstecken",
+ "nummer": 0,
+ "strängar": "Alla unicode-tecken (inklusive \"escaping\") är tillåtna.",
+ "boolska värden?": true,
+ "nullvärden": null,
+
+ "stora tal": 1.2e+100,
+
+ "objekt": {
+ "kommentar": "De flesta datastukturerna i JSON kommer i form av objekt.",
+
+ "matris": [0, 1, 2, 3, "Matriser kan innehålla vad som helst.", 5],
+
+ "ytterligare objekt": {
+ "kommentar": "Objekten kan vara nästlade."
+ }
+ },
+
+ "trams": [
+ {
+ "kaliumkällor": ["bananer"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "neo"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "alternativ formatering": {
+ "kommentar": "kolla på detta!"
+ , "kommats position": "spelar ingen roll - så länge det kommer innan värdet"
+ , "en kommentar till": "vad fint"
+ },
+
+ "det var kort": "Nu är du klar och kan allt vad JSON har att erbjuda."
+}
+```
diff --git a/swift.html.markdown b/swift.html.markdown
index e6bf1621..e921e7ea 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -94,6 +94,8 @@ 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 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
if !someOptionalStringConstant.hasPrefix("ok") {
@@ -213,7 +215,7 @@ default: // required (in order to cover all possible input)
// Functions are a first-class type, meaning they can be nested
// in functions and can be passed around
-// Function with Swift header docs (format as reStructedText)
+// Function with Swift header docs (format as Swift-modified Markdown syntax)
/**
A greet operation
@@ -221,9 +223,9 @@ A greet operation
- A bullet in docs
- Another bullet in the docs
-:param: name A name
-:param: day A day
-:returns: A string containing the name and day value.
+- Parameter name : A name
+- Parameter day : A day
+- Returns : A string containing the name and day value.
*/
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
@@ -392,7 +394,7 @@ testTryStuff()
public class Shape {
public func getArea() -> Int {
- return 0;
+ return 0
}
}
diff --git a/ta_in/css-ta.html.markdown b/ta_in/css-ta.html.markdown
index 56f94ed0..cbe88f1e 100644
--- a/ta_in/css-ta.html.markdown
+++ b/ta_in/css-ta.html.markdown
@@ -7,9 +7,9 @@ contributors:
- ["Connor Shea", "https://github.com/connorshea"]
- ["Deepanshu Utkarsh", "https://github.com/duci9y"]
translators:
- - ["Rasendran Kirushan", "https://github.com/kirushanr"]
-filename: learncss.css
-lang:in-ta
+ - ["Rasendran Kirushan", "https://github.com/kirushanr"]
+filename: learncss-ta.css
+lang: in-ta
---
diff --git a/ta_in/javascript-ta.html.markdown b/ta_in/javascript-ta.html.markdown
index f0b0a36a..d3fe5a85 100644
--- a/ta_in/javascript-ta.html.markdown
+++ b/ta_in/javascript-ta.html.markdown
@@ -5,8 +5,8 @@ contributors:
- ['Ariel Krakowski', 'http://www.learneroo.com']
translators:
- ["Rasendran Kirushan", "https://github.com/kirushanr"]
-filename: javascript.js
-lang:in-ta
+filename: javascript-ta.js
+lang: in-ta
---
javascript 1995 ஆம் ஆண்டு Netscape இல் பணிபுரிந்த Brendan Eich
diff --git a/ta_in/xml-ta.html.markdown b/ta_in/xml-ta.html.markdown
index a9bfa9cd..d782399d 100644
--- a/ta_in/xml-ta.html.markdown
+++ b/ta_in/xml-ta.html.markdown
@@ -1,11 +1,11 @@
---
language: xml
-filename: learnxml.xml
+filename: learnxml-ta.xml
contributors:
- ["João Farias", "https://github.com/JoaoGFarias"]
translators:
- ["Rasendran Kirushan", "https://github.com/kirushanr"]
-lang:in-ta
+lang: in-ta
---
diff --git a/tmux.html.markdown b/tmux.html.markdown
index 868302a8..c9e3db6b 100644
--- a/tmux.html.markdown
+++ b/tmux.html.markdown
@@ -7,7 +7,7 @@ filename: LearnTmux.txt
---
-[tmux](http://tmux.sourceforge.net)
+[tmux](http://tmux.github.io)
is a terminal multiplexer: it enables a number of terminals
to be created, accessed, and controlled from a single screen. tmux
may be detached from a screen and continue running in the background
@@ -240,7 +240,7 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] |
### References
-[Tmux | Home](http://tmux.sourceforge.net)
+[Tmux | Home](http://tmux.github.io)
[Tmux Manual page](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux)
diff --git a/tr-tr/brainfuck-tr.html.markdown b/tr-tr/bf-tr.html.markdown
index bd842b17..e7015cd0 100644
--- a/tr-tr/brainfuck-tr.html.markdown
+++ b/tr-tr/bf-tr.html.markdown
@@ -1,5 +1,5 @@
---
-language: brainfuck
+language: bf
filename: brainfuck-tr
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io"]
diff --git a/tr-tr/markdown-tr.html.markdown b/tr-tr/markdown-tr.html.markdown
index bac8f6fc..b8f11e39 100644
--- a/tr-tr/markdown-tr.html.markdown
+++ b/tr-tr/markdown-tr.html.markdown
@@ -52,7 +52,7 @@ __Bu yazı da kalın.__
**_Bu da öyle!_**
*__Hatta bu bile!__*
-<!-- Github Flavored Markdown'da ayrıca üstü çizgili karakter de desteklenir: -->
+<!-- GitHub Flavored Markdown'da ayrıca üstü çizgili karakter de desteklenir: -->
~~Bu yazı üstü çizili olarak gözükecek.~~
<!-- Paragraflar bir veya daha fazla boş satırla ayrılır. -->
@@ -151,7 +151,7 @@ kullanabilirsiniz -->
Ahmet `go_to()` fonksiyonun ne yaptığını bilmiyor!
-<!-- Github Flavored Markdown'da, kod içerisinde aydınlatma kullanabilirsiniz -->
+<!-- GitHub Flavored Markdown'da, kod içerisinde aydınlatma kullanabilirsiniz -->
\`\`\`ruby <!-- buradaki ters slaş (\) işaretlerini kullanmayın, sadece ```ruby ! -->
def foobar
@@ -159,7 +159,7 @@ def foobar
end
\`\`\` <!-- burada da (\) işaretlerini kullanmayın, sadece ``` -->
-<!-- Yukarıdaki örnekte girinti kullanmanıza gerek yok, Github da
+<!-- Yukarıdaki örnekte girinti kullanmanıza gerek yok, GitHub da
``` işaretinden sonra belirttiğiniz yazılım diline göre gerekli
syntax aydınlatmaları uygulanacaktır -->
@@ -230,7 +230,7 @@ Bu yazının *yıldızlar arasında gözükmesini* istiyorum fakat italik olmama
bunun için, şu şekilde: \*bu yazı italik değil, yıldızlar arasında\*.
<!-- Tablolar -->
-<!-- Tablolar sadece Github Flavored Markdown'da destekleniyor ve açıkçası
+<!-- Tablolar sadece GitHub Flavored Markdown'da destekleniyor ve açıkçası
performansı çok yoruyorlar, fakat illa ki kullanmak isterseniz: -->
| Sütun1 | Sütun 2 | Sütün 3 |
diff --git a/tr-tr/swift-tr.html.markdown b/tr-tr/swift-tr.html.markdown
index c13f5ecf..15056bb8 100644
--- a/tr-tr/swift-tr.html.markdown
+++ b/tr-tr/swift-tr.html.markdown
@@ -25,14 +25,14 @@ import UIKit
//XCode işaretlemelerle kodunuzu bölümlere ayırmanızı ve sağ üstteki metot
- listesinde gruplama yapmanıza olanak sağlıyor
+//listesinde gruplama yapmanıza olanak sağlıyor
// MARK: Bölüm işareti
// TODO: Daha sonra yapılacak
// FIXME: Bu kodu düzelt
-//Swift 2 de, println ve print metotları print komutunda birleştirildi. Print
- otomatik olarak yeni satır ekliyor.
+//Swift 2 de, println ve print metotları print komutunda birleştirildi.
+//Print otomatik olarak yeni satır ekliyor.
print("Merhaba dünya") // println print olarak kullanılıyor.
print("Merhaba dünya", appendNewLine: false) // yeni bir satır eklemeden yazar.
@@ -75,7 +75,7 @@ print("Build degiskeni: \(buildDegiskeni)") // Build degeri: 7
*/
var baziOptionalString: String? = "optional" // nil olabilir.
// yukarıdakiyle aynı ama ? bir postfix (sona eklenir) operatördür. (kolay
-okunabilir)
+//okunabilir)
var someOptionalString2: Optional<String> = "optional"
@@ -104,7 +104,8 @@ if let baziOpsiyonelSabitString = baziOptionalString {
// Swift değişkenlerde herhangi bir tip saklanabilir.
// AnyObject == id
// Objective-C deki `id` den farklı olarak, AnyObject tüm değişkenlerle
- çalışabilir (Class, Int, struct, etc)
+//çalışabilir
+(Class, Int, struct, etc)
var herhangiBirObject: AnyObject = 7
herhangiBirObject = "Değer string olarak değişti, iyi bir yöntem değil ama mümkün"
@@ -234,7 +235,7 @@ func fiyatlariGetir() -> (Double, Double, Double) {
let fiyatTuple = fiyatlariGetir()
let fiyat = fiyatTuple.2 // 3.79
// _ (alt çizgi) kullanımı Tuple degerlerini veya diğer değerleri görmezden
-gelir
+//gelir
let (_, fiyat1, _) = fiyatTuple // fiyat1 == 3.69
print(fiyat1 == fiyatTuple.1) // true
print("Benzin fiyatı: \(fiyat)")
diff --git a/typescript.html.markdown b/typescript.html.markdown
index 26f1fcd9..47e41405 100644
--- a/typescript.html.markdown
+++ b/typescript.html.markdown
@@ -159,6 +159,14 @@ var tuple = pairToTuple({ item1:"hello", item2:"world"});
// Including references to a definition file:
/// <reference path="jquery.d.ts" />
+// Template Strings (strings that use backticks)
+// String Interpolation with Template Strings
+var name = 'Tyrone';
+var greeting = `Hi ${name}, how are you?`
+// Multiline Strings with Template Strings
+var multiline = `This is an example
+of a multiline string`;
+
```
## Further Reading
diff --git a/ua-ua/bash-ua.html.markdown b/ua-ua/bash-ua.html.markdown
deleted file mode 100644
index 2c930ad1..00000000
--- a/ua-ua/bash-ua.html.markdown
+++ /dev/null
@@ -1,296 +0,0 @@
----
-category: tool
-tool: bash
-contributors:
- - ["Max Yankov", "https://github.com/golergka"]
- - ["Darren Lin", "https://github.com/CogBear"]
- - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"]
- - ["Denis Arh", "https://github.com/darh"]
- - ["akirahirose", "https://twitter.com/akirahirose"]
- - ["Anton Strömkvist", "http://lutic.org/"]
- - ["Rahil Momin", "https://github.com/iamrahil"]
- - ["Gregrory Kielian", "https://github.com/gskielian"]
- - ["Etan Reisner", "https://github.com/deryni"]
-translators:
- - ["Ehreshi Ivan", "https://github.com/IvanEh"]
-lang: ua-ua
----
-
-Bash - командна оболонка unix (unix shell), що також розповсюджувалась як оболонка для
-операційної системи GNU і зараз використовується як командна оболонка за замовчуванням
-для Linux i Max OS X.
-Почти все нижеприведенные примеры могут быть частью shell-скриптов или исполнены напрямую в shell.
-Майже всі приклади, що наведені нижче можуть бути частиною shell-скриптів або
-виконані в оболонці
-
-[Більш детально тут.](http://www.gnu.org/software/bash/manual/bashref.html)
-
-```bash
-#!/bin/bash
-# Перший рядок скрипта - це shebang, який вказує системі, як потрібно виконувати
-# скрипт. Як ви вже зрозуміли, коментарі починаються з #. Shebang - тоже коментар
-
-# Простий приклад hello world:
-echo Hello world!
-
-# Окремі команди починаються з нового рядка або розділяються крапкою з комкою:
-echo 'Перший рядок'; echo 'Другий рядок'
-
-# Оголошення змінної
-VARIABLE="Просто рядок"
-
-# Але не так!
-VARIABLE = "Просто рядок"
-# Bash вирішить, що VARIABLE - це команда, яку він може виконати,
-# і видасть помилку, тому що не зможе знайти її
-
-# І так також не можна писати:
-VARIABLE= 'Просто рядок'
-# Bash сприйме рядок 'Просто рядок' як команду. Але такої команди не має, тому
-# видасть помилку.
-# (тут 'VARIABLE=' інтерпретується як присвоєння тільки в контексті
-# виконання команди 'Просто рядок')
-
-# Використання змінних:
-echo $VARIABLE
-echo "$VARIABLE"
-echo '$VARIABLE'
-# Коли ви використовуєте змінну - присвоюєте значення, експортуєте і т.д. -
-# пишіть її імя без $. А для отримання значення змінної використовуйте $.
-# Одинарні лапки ' не розкривають значення змінних
-
-# Підстановка рядків в змінні
-echo ${VARIABLE/Просто/A}
-# Цей вираз замінить перше входження підрядка "Просто" на "А"
-
-# Отримання підрядка із рядка
-LENGTH=7
-echo ${VARIABLE:0:LENGTH}
-# Цей вираз поверне тільки перші 7 символів змінної VARIABLE
-
-# Значення за замовчуванням
-echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"}
-# Це спрацює при відсутності значення (FOO=) і при пустому рядку (FOO="")
-# Нуль (FOO=0) поверне 0.
-# Зауважте, що у всіх випадках значення самої змінної FOO не зміниться
-
-# Вбудовані змінні:
-# В bash є корисні вбудовані змінні, наприклад
-echo "Значення, яке було повернуте в останній раз: $?"
-echo "PID скрипта: $$"
-echo "Кількість аргументів: $#"
-echo "Аргументи скрипта: $@"
-echo "Аргументи скрипта, розподілені по різним змінним: $1 $2..."
-
-# Зчитування змінних з пристроїв введення
-echo "Як вас звати?"
-read NAME # Зверніть увагу, що вам не потрібно оголошувати нову змінну
-echo Привіт, $NAME!
-
-# В bash є звичайна умовна конструкція if:
-# наберіть 'man test', щоб переглянути детальну інформацію про формати умов
-if [ $NAME -ne $USER ]
-then
- echo "Ім’я користувача не збігається з введеним"
-else
- echo "Ім’я збігаєтьяс з іменем користувача"
-fi
-
-# Зауважте! якщо $Name пуста, bash інтерпретує код вище як:
-if [ -ne $USER ]
-# що є неправильним синтаксисом
-# тому безпечний спосіб використання потенційно пустих змінних має вигляд:
-if [ "$Name" -ne $USER ] ...
-# коли $Name пуста, інтерпретується наступним чином:
-if [ "" -ne $USER ] ...
-# що працює як і очікувалося
-
-# Умовне виконання (conditional execution)
-echo "Виконується завжди" || echo "Виконається, якщо перша команда завершиться з помилкою"
-echo "Виконується завжди" && echo "Виконається, якщо перша команда завершиться успішно"
-
-# Щоб використати && і || у конструкції if, потрібно декілька пар дужок:
-if [ $NAME == "Steve" ] && [ $AGE -eq 15 ]
-then
- echo "Виконається, якщо $NAME="Steve" i AGE=15."
-fi
-
-if [ $NAME == "Daniya" ] || [ $NAME == "Zach" ]
-then
- echo "Виконається, якщо NAME="Steve" або NAME="Zach"."
-fi
-
-# Вирази позначаються наступним форматом:
-echo $(( 10 + 5 ))
-
-# На відмінно від інших мов програмування, Bash - це командна оболонка, а
-# отже, працює в контексті поточної директорії
-ls
-
-# Ця команда може використовуватися з опціями
-ls -l # Показати кожен файл і директорію на окремому рядку
-
-# Результат попередньої команди можна перенаправити на вхід наступної.
-# Команда grep фільтрує вхід по шаблону.
-# Таким чином ми можемо переглянути тільки *.txt файли в поточній директорії:
-ls -l | grep "\.txt"
-
-# Ви можете перенаправ вхід і вихід команди (stdin, stdout, stderr).
-# Наступна команда означає: читати із stdin, поки не зустрінеться ^EOF$, і
-# перезаписати hello.py наступними рядками (до рядка "EOF"):
-cat > hello.py << EOF
-#!/usr/bin/env python
-from __future__ import print_function
-import sys
-print("#stdout", file=sys.stdout)
-print("#stderr", file=sys.stderr)
-for line in sys.stdin:
- print(line, file=sys.stdout)
-EOF
-
-# Запуск hello.py з різними варіантами перенаправлення stdin,
-# stdout, stderr (стандартні потоки введення, виведення і помилок):
-python hello.py < "input.in"
-python hello.py > "output.out"
-python hello.py 2> "error.err"
-python hello.py > "output-and-error.log" 2>&1
-python hello.py > /dev/null 2>&1
-# Поток помилок перезапише фпйл, якщо цей файл існує
-# тому, якщо ви хочете дописувати до файлу, використовуйте ">>":
-python hello.py >> "output.out" 2>> "error.err"
-
-# Перезаписати output.txt, дописати error.err і порахувати кількість рядків:
-info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err
-wc -l output.out error.err
-
-# Запустити команду і вивести її файловий дескриптор (див.: man fd; наприклад /dev/fd/123)
-echo <(echo "#helloworld")
-
-# Перезаписати output.txt рядком "#helloworld":
-cat > output.out <(echo "#helloworld")
-echo "#helloworld" > output.out
-echo "#helloworld" | cat > output.out
-echo "#helloworld" | tee output.out >/dev/null
-
-# Подчистить временные файлы с подробным выводом ('-i' - интерактивый режим)
-# Очистити тимчасові файли з детальним виводом (додайте '-i'
-# для інтерактивного режиму)
-rm -v output.out error.err output-and-error.log
-
-# Команди можуть бути підставлені в інші команди використовуючи $():
-# наступна команда виводить кількість файлів і директорій в поточній директорії
-echo "Тут $(ls | wc -l) елементів."
-
-# Те саме можна зробити використовуючи зворотні лапки
-# Але вони не можуть бути вкладеними, тому перший варіант бажаніший
-echo "Тут `ls | wc -l` елементів."
-
-# В Bash є структура case, яка схожа на switch в Java и C++:
-case "$VARIABLE" in
- # перерахуйте шаблони, які будуть використовуватися в якості умов
- 0) echo "Тут нуль.";;
- 1) echo "Тут один.";;
- *) echo "Не пусте значення.";;
-esac
-
-# Цикл for перебирає елементи передані в аргумент:
-# Значення $VARIABLE буде напечатано тричі.
-for VARIABLE in {1..3}
-do
- echo "$VARIABLE"
-done
-
-# Aбо можна використати звичний синтаксис for:
-for ((a=1; a <= 3; a++))
-do
- echo $a
-done
-
-# Цикл for можно використати, щоб виконувати дії над файлами.
-# Цей код запустить команду 'cat' для файлів file1 и file2
-for VARIABLE in file1 file2
-do
- cat "$VARIABLE"
-done
-
-# ... або дії над виводом команд
-# Запустимо cat для виведення із ls.
-for OUTPUT in $(ls)
-do
- cat "$OUTPUT"
-done
-
-# Цикл while:
-while [ true ]
-do
- echo "Тіло циклу..."
- break
-done
-
-# Ви також можете оголосити функцію
-# Оголошення:
-function foo ()
-{
- echo "Аргументи функції доступні так само, як і аргументи скрипта: $@"
- echo "$1 $2..."
- echo "Це функція"
- return 0
-}
-
-# Або просто
-bar ()
-{
- echo "Інший спосіб оголошення функцій!"
- return 0
-}
-
-# Виклик функцій
-foo "Мое имя" $NAME
-
-# Є багато корисних команд:
-# вивести останні 10 рядків файла file.txt
-tail -n 10 file.txt
-# вивести перші 10 рядків файла file.txt
-head -n 10 file.txt
-# відсортувати рядки file.txt
-sort file.txt
-# відібрати або пропустити рядки, що дублюються (з опцією -d відбирає)
-uniq -d file.txt
-# вивести тільки першу колонку перед символом ','
-cut -d ',' -f 1 file.txt
-# замінити кожне 'okay' на 'great' у файлі file.txt (підтримується regex)
-sed -i 's/okay/great/g' file.txt
-# вивести в stdout все рядки з file.txt, що задовольняють шаблону regex;
-# цей приклад виводить рядки, що починаються на foo і закінчуються на bar:
-grep "^foo.*bar$" file.txt
-# використайте опцію -c, щоб вивести кількість входжень
-grep -c "^foo.*bar$" file.txt
-# чтобы искать по строке, а не шаблону regex, используйте fgrep (или grep -F)
-# щоб здійснити пошук по рядку, а не по шаблону regex, використовуйте fgrea (або grep -F)
-fgrep "^foo.*bar$" file.txt
-
-# Читайте вбудовану документацію Bash командою 'help':
-help
-help help
-help for
-help return
-help source
-help .
-
-# Читайте Bash man-документацію
-apropos bash
-man 1 bash
-man bash
-
-# Читайте документацію info (? для допомоги)
-apropos info | grep '^info.*('
-man info
-info info
-info 5 info
-
-# Читайте bash info документацію:
-info bash
-info bash 'Bash Features'
-info bash 6
-info --apropos bash
-```
diff --git a/ua-ua/json-ua.html.markdown b/ua-ua/json-ua.html.markdown
deleted file mode 100644
index 6281ea56..00000000
--- a/ua-ua/json-ua.html.markdown
+++ /dev/null
@@ -1,67 +0,0 @@
----
-language: json
-filename: learnjson-ru.json
-contributors:
- - ["Anna Harren", "https://github.com/iirelu"]
- - ["Marco Scannadinari", "https://github.com/marcoms"]
-translators:
- - ["Ehreshi Ivan", "https://github.com/IvanEh"]
-lang: ua-ua
----
-
-JSON - це надзвичайно простий формат обміну даними. Це мабуть буде найлегшим курсом
-"Learn X in Y Minutes".
-
-В загальному випадку в JSON немає коментарів, але більшість парсерів дозволяють
-використовувати коментарі в С-стилі(//, /\* \*/). Можна залишити кому після останнього
-поля, але все-таки краще такого уникати для кращої сумісності
-
-```json
-{
- "ключ": "значеннь",
-
- "ключі": "завжди мають бути обгорнуті в подвійні лапки",
- "числа": 0,
- "рядки": "Пρивет, світ. Допускаються всі unicode-символи разом з \"екрануванням\".",
- "логічний тип": true,
- "нічого": null,
-
- "велике число": 1.2e+100,
-
- "об’єкти": {
- "коментар": "Більшість ваших структур будуть складатися з об’єктів",
-
- "масив": [0, 1, 2, 3, "масиви можуть містити будь-які типи", 5],
-
- "інший об’єкт": {
- "коментра": "Об’єкти можуть містити інші об’єкти. Це дуже корисно."
- }
- },
-
- "безглуздя": [
- {
- "джерело калія": ["банани"]
- },
- [
- [1, 0, 0, 0],
- [0, 1, 0, 0],
- [0, 0, 1, "нео"],
- [0, 0, 0, 1]
- ]
- ],
-
- "альтернативнтй стиль": {
- "коментар": "Гляньте!"
- , "позиція коми": "неважлива, поки вона знаходиться до наступного поля"
- , "інший коментар": "класно"
- },
-
- "Це було не довго": "І ви справилист. Тепер ви знаєте все про JSON."
-}
-
-Одиничний масив значень теж є правильним JSON
-
-[1, 2, 3, "text", true]
-
-
-```
diff --git a/uk-ua/java-ua.html.markdown b/uk-ua/java-ua.html.markdown
new file mode 100644
index 00000000..1ea30f3d
--- /dev/null
+++ b/uk-ua/java-ua.html.markdown
@@ -0,0 +1,783 @@
+---
+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"]
+ - ["Rachel Stiyer", "https://github.com/rstiyer"]
+translators:
+ - ["Oleksandr Tatarchuk", "https://github.com/tatarchuk"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+filename: LearnJavaUa.java
+lang: uk-ua
+---
+
+Java є об’єктно-орієнтованою мовою програмування загального призначення з підтримкою паралельного програмування, яка базується на класах.
+[Детальніше читайте тут, англ.](http://docs.oracle.com/javase/tutorial/java/)
+
+```java
+// Однорядковий коментар починається з //
+/*
+Багаторядковий коментар виглядає так.
+*/
+/**
+JavaDoc-коментар виглядає так. Використовується для опису класу та членів класу.
+*/
+
+// Імпорт класу ArrayList з пакета java.util
+import java.util.ArrayList;
+// Імпорт усіх класів з пакета java.security
+import java.security.*;
+
+// Кожний .java файл містить один зовнішній публічний клас, ім’я якого співпадає
+// з іменем файлу.
+public class LearnJava {
+
+ // Для запуску програма, написана на java, повинна мати точку входу у вигляді методу main.
+ public static void main (String[] args) {
+
+ // Використання System.out.println() для виводу на друк рядків.
+ System.out.println("Привіт, світе!");
+ System.out.println(
+ " Ціле число: " + 10 +
+ " Число з рухомою комою подвійної точности: " + 3.14 +
+ " Булеве значення: " + true);
+
+ // Для друку без переходу на новий рядок використовується System.out.print().
+ System.out.print("Привіт, ");
+ System.out.print("світе");
+
+ // Використання System.out.printf() для простого форматованого виводу на друк.
+ System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159
+
+ ///////////////////////////////////////
+ // Змінні
+ ///////////////////////////////////////
+
+ /*
+ * Оголошення змінних
+ */
+ // Для оголошення змінних використовується формат <тип> <змінна>
+ int fooInt;
+ // Оголошення декількох змінних одного типу <тип> <ім’я1>, <ім’я2>, <ім’я3>
+ int fooInt1, fooInt2, fooInt3;
+
+ /*
+ * Ініціалізація змінних
+ */
+
+ // Ініціалізація змінної з використанням формату <тип> <ім’я> = <значення>
+ int fooInt = 1;
+ // Ініціалізація декількох змінних одного типу з одним значенням <тип> <ім’я1>, <ім’я2>, <ім’я3> = <значення>
+ int fooInt1, fooInt2, fooInt3;
+ fooInt1 = fooInt2 = fooInt3 = 1;
+
+ /*
+ * Типи змінних
+ */
+ // Байт — 8-бітне ціле число зі знаком
+ // (-128 <= byte <= 127)
+ byte fooByte = 100;
+
+ // Short — 16-бітне ціле число зі знаком
+ // (-32 768 <= short <= 32 767)
+ short fooShort = 10000;
+
+ // Integer — 32-бітне ціле число зі знаком
+ // (-2 147 483 648 <= int <= 2 147 483 647)
+ int fooInt = 1;
+
+ // Long — 64-бітне ціле число зі знаком
+ // (-9 223 372 036 854 775 808 <= long <= 9 223 372 036 854 775 807)
+ long fooLong = 100000L;
+ // L використовується для позначення того, що число має тип Long;
+ // інакше число буде трактуватись як integer.
+
+ // Примітка: Java не має беззнакових типів.
+
+ // Float — 32-бітне число з рухомою комою одиничної точності за стандартом IEEE 754
+ // 2^-149 <= float <= (2-2^-23) * 2^127
+ float fooFloat = 234.5f;
+ // f або F використовується для позначення того, що змінна має тип float;
+ // інакше трактується як double.
+
+ // Double — 64-бітне число з рухомою комою подвійної точності за стандартом IEEE 754
+ // 2^-1074 <= x <= (2-2^-52) * 2^1023
+ double fooDouble = 123.4;
+
+ // Boolean — true & false (істина чи хиба)
+ boolean fooBoolean = true;
+ boolean barBoolean = false;
+
+ // Char — 16-бітний символ Unicode
+ char fooChar = 'A';
+
+ // final - посилання на такі змінні не можуть бути присвоєні іншим об’єктам,
+ final int HOURS_I_WORK_PER_WEEK = 9001;
+ // але вони можуть мати відкладену ініціалізацію.
+ final double E;
+ E = 2.71828;
+
+
+ // BigInteger -Незмінні знакові цілі числа довільної точності
+ //
+ // BigInteger є типом даних, який дає можливість розробнику виконувати операції
+ // з цілими числами, розрядність яких більша за 64 біти. Числа зберігаються у масиві
+ // байтів, операції над ними виконуються функціями, які мають клас BigInteger
+ //
+ // BigInteger можна ініціалізувати, використовуючи масив байтів чи рядок.
+
+ BigInteger fooBigInteger = new BigInteger(fooByteArray);
+
+
+ // BigDecimal — Незмінні знакові дробові числа довільної точності
+ //
+ // BigDecimal складається з двох частин: цілого числа довільної точності
+ // з немасштабованим значенням та 32-бітного масштабованого цілого числа
+ //
+ // BigDecimal дозволяє розробникам контролювати десяткове округлення.
+ // Рекомендовано використовувати BigDecimal зі значеннями валют
+ // і там, де необхідна точність дробових обчислень.
+ //
+ // BigDecimal може бути ініціалізований типами даних int, long, double або String
+ // чи немасштабованим значенням (BigInteger) і масштабованим значенням (int).
+
+ BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt);
+
+ // Для дотримання заданої точності рекомендується використовувати
+ // конструктор, який приймає String
+
+ BigDecimal tenCents = new BigDecimal("0.1");
+
+
+ // Рядки
+ String fooString = "Це мій рядок!";
+
+ // \n є символом переходу на новий рядок
+ String barString = "Друк з нового рядка?\nНема питань!";
+ // \t — це символ табуляції
+ String bazString = "Хочете додати табуляцію?\tТримайте!";
+ System.out.println(fooString);
+ System.out.println(barString);
+ System.out.println(bazString);
+
+ // Масиви
+ // Розмір масиву має бути визначений перед ініціалізацією
+ // Наведений формат ілюструє ініціалізацію масивів
+ // <тип даних>[] <ім’я змінної> = new <тип даних>[<розмір масиву>];
+ // <тип даних> <ім’я змінної>[] = new <тип даних>[<розмір масиву>];
+ int[] intArray = new int[10];
+ String[] stringArray = new String[1];
+ boolean boolArray[] = new boolean[100];
+
+ // Інший шлях оголошення та ініціалізації масиву
+ int[] y = {9000, 1000, 1337};
+ String names[] = {"Bob", "John", "Fred", "Juan Pedro"};
+ boolean bools[] = new boolean[] {true, false, false};
+
+ // Індексація масиву — доступ за елементами
+ System.out.println("intArray @ 0: " + intArray[0]);
+
+ // Масиви є змінними та мають нульовий елемент.
+ intArray[1] = 1;
+ System.out.println("intArray @ 1: " + intArray[1]); // => 1
+
+ // Додатково
+ // ArrayLists — Схожі на масив, але мають більший функціонал та змінний розмір.
+ // LinkedLists — Реалізація двозв’язного списку. Всі операції
+ // виконуються так, як очікується від
+ // двозв’язного списку.
+ // Maps — Множина об’єктів, які пов’язують ключ зі значенням. Map є
+ // інтерфейсом, тому не може бути успадкований.
+ // Типи ключів і значень, які зберігаються в Map, мають
+ // вказуватись у класі, який його реалізує.
+ // Ключ не може повторюватись і пов’язаний лише з одним значенням
+ // HashMaps — Цей клас використовує хеш-таблицю для реалізації інтерфейсу Map.
+ // Це дозволяє виконувати певні операції,
+ // такі, як отримання та вставка елемента,
+ // залишаючись постійними навіть для великої кількості елементів.
+
+ ///////////////////////////////////////
+ // Оператори
+ ///////////////////////////////////////
+ System.out.println("\n->Оператори");
+
+ int i1 = 1, i2 = 2; // Коротка форма присвоєння
+
+ // Арифметичні операції виконуються очевидним способом
+ System.out.println("1+2 = " + (i1 + i2)); // => 3
+ System.out.println("2-1 = " + (i2 - i1)); // => 1
+ System.out.println("2*1 = " + (i2 * i1)); // => 2
+ System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int повертається як int)
+ System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5
+
+ // Ділення з остачею
+ System.out.println("11%3 = "+(11 % 3)); // => 2
+
+ // Оператори порівняння
+ System.out.println("3 == 2? " + (3 == 2)); // => false
+ System.out.println("3 != 2? " + (3 != 2)); // => true
+ System.out.println("3 > 2? " + (3 > 2)); // => true
+ System.out.println("3 < 2? " + (3 < 2)); // => false
+ System.out.println("2 <= 2? " + (2 <= 2)); // => true
+ System.out.println("2 >= 2? " + (2 >= 2)); // => true
+
+ // Логічні оператори
+ System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false
+ System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true
+ System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true
+
+ // Бітові оператори!
+ /*
+ ~ Унарне бітове доповнення
+ << Знаковий зсув уліво
+ >> Знаковий/Арифметичний зсув управо
+ >>> Беззнаковий/Логічний зсув управо
+ & Бітове І
+ ^ Бітови виключне АБО
+ | Бітове АБО
+ */
+
+ // Інкремент
+ int i = 0;
+ System.out.println("\n->Інкремент/Декремент");
+ // Оператори ++ і -- здійснюють інкремент та декремент ретроспективно.
+ // Якщо вони розташовані перед змінною, операція виконається перед поверненням;
+ // якщо після неї — повернеться інкремент або декремент.
+ System.out.println(i++); // i = 1, друкує 0 (постінкремент)
+ System.out.println(++i); // i = 2, друкує 2 (преінкремент)
+ System.out.println(i--); // i = 1, друкує 2 (постдекремент)
+ System.out.println(--i); // i = 0, друкує 0 (предекремент)
+
+ ///////////////////////////////////////
+ // Керуючі конструкції
+ ///////////////////////////////////////
+ System.out.println("\n->Керуючі конструкції");
+
+ // Оператор if використовується так само, як у мові C
+ int j = 10;
+ if (j == 10) {
+ System.out.println("Це надрукується");
+ } else if (j > 10) {
+ System.out.println("А це — ні");
+ } else {
+ System.out.println("Це — також ні");
+ }
+
+ // Цикл з передумовою While
+ int fooWhile = 0;
+ while(fooWhile < 100) {
+ System.out.println(fooWhile);
+ // Інкремент лічильника
+ // Виконається 100 разів, fooWhile 0,1,2...99
+ fooWhile++;
+ }
+ System.out.println("fooWhile Value: " + fooWhile);
+
+ // Цикл з післяумовою Do While
+ int fooDoWhile = 0;
+ do {
+ System.out.println(fooDoWhile);
+ // Інкремент лічильника
+ // Виконається 99 разів, fooDoWhile 0->99
+ fooDoWhile++;
+ } while(fooDoWhile < 100);
+ System.out.println("Значення fooDoWhile: " + fooDoWhile);
+
+ // Цикл з параметром For
+ // структура циклу => for(<початковий стан>; <умова завершення>; <крок>)
+ for (int fooFor = 0; fooFor < 10; fooFor++) {
+ System.out.println(fooFor);
+ // Виконається 10 разів, fooFor 0->9
+ }
+ System.out.println("Значення fooFor: " + fooFor);
+
+ // Вихід із вкладеного циклу через мітку
+ outer:
+ for (int i = 0; i < 10; i++) {
+ for (int j = 0; j < 10; j++) {
+ if (i == 5 && j ==5) {
+ break outer;
+ // вихід із зовнішнього циклу, а не лише внутрішнього
+ }
+ }
+ }
+
+ // Цикл For Each
+ // Призначений для перебору масивів та колекцій
+ int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9};
+
+ for (int bar : fooList) {
+ System.out.println(bar);
+ // Повторюється 9 разів та друкує числа від 1 до 9 на нових рядках
+ }
+
+ // Оператор вибору Switch Case
+ // Оператор вибору працює з типами даних byte, short, char, int.
+ // Також працює з переліками Enum,
+ // класом String та класами-обгортками примітивних типів:
+ // Character, Byte, Short та Integer.
+ int month = 3;
+ String monthString;
+ switch (month) {
+ case 1: monthString = "Січень";
+ break;
+ case 2: monthString = "Лютий";
+ break;
+ case 3: monthString = "Березень";
+ break;
+ default: monthString = "Інший місяць";
+ break;
+ }
+ System.out.println("Результат Switch Case: " + monthString);
+
+ // Починаючи з Java 7 і далі, вибір рядкових змінних здійснюється так:
+ String myAnswer = "можливо";
+ switch(myAnswer) {
+ case "так":
+ System.out.println("Ви відповіли «Так».");
+ break;
+ case "ні":
+ System.out.println("Ви відповіли «ні».");
+ break;
+ case "можливо":
+ System.out.println("Ви відповіли «Можливо».");
+ break;
+ default:
+ System.out.println("Ви відповіли «" + myAnswer + "»");
+ break;
+ }
+
+ // Тернарний оператор вибору
+ // Можна використовувати оператор «?» (знак питання) для визначення умови.
+ // Читається так: «Якщо (умова) вірна, то <перше значення>, інакше
+ // <друге значення>»
+ int foo = 5;
+ String bar = (foo < 10) ? "A" : "B";
+ System.out.println(bar); // Надрукується А, бо умова вірна
+
+
+ ////////////////////////////////////////
+ // Перетворення типів
+ ////////////////////////////////////////
+
+ // Перетворення String на Integer
+ Integer.parseInt("123");//поверне числову версію рядка "123"
+
+ // Перетворення Integer на String
+ Integer.toString(123);//повертає рядкову версію 123
+
+ // Для інших перетворень є наступні класи:
+ // Double
+ // Long
+ // String
+
+ // Приведення типів
+ // Тут можна прочитати про приведення об’єктів (англ.):
+ // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
+
+
+ ///////////////////////////////////////
+ // Класи та функції
+ ///////////////////////////////////////
+
+ System.out.println("\n->Класи та функції");
+
+ // (Клас Bicycle наведений нижче)
+
+ // Новий об’єкт класу
+ Bicycle trek = new Bicycle();
+
+ // Виклик методу об’єкта
+ trek.speedUp(3); // Постійно використовуються методи з назвами set і get
+ trek.setCadence(100);
+
+ // toString повертає рядкове представлення об’єкту.
+ System.out.println("Інформація про об’єкт trek: " + trek.toString());
+
+ // У Java немає синтаксису для явного створення статичних колекцій.
+ // Це можна зробити так:
+
+ private static final Set<String> COUNTRIES = new HashSet<String>();
+ static {
+ validCodes.add("DENMARK");
+ validCodes.add("SWEDEN");
+ validCodes.add("FINLAND");
+ }
+
+ // Але є інший спосіб — ініціалізація з подвійними фігурними дужками.
+
+ private static final Set<String> COUNTRIES = new HashSet<String>() {{
+ add("DENMARK");
+ add("SWEDEN");
+ add("FINLAND");
+ }}
+
+ // Використовується анонімний внутрішній клас
+
+ } // Кінець методу main
+} // Кінець класу LearnJava
+
+
+// У .java-файл можна додавати інші, не public класи зовнішнього рівня,
+// але це не є хорошою практикою. Розміщуйте класи в окремих файлах.
+
+
+// Синтаксис оголошення класу:
+// <public/private/protected> class <ім’я класу> {
+// // поля, конструктори, функції та ін.
+// // у Java функції називаються методами.
+// }
+
+class Bicycle {
+
+ // Поля (змінні) класу Bicycle
+ public int cadence; // Public: доступно звідусіль
+ private int speed; // Private: доступно лише у межах класу
+ protected int gear; // Protected: доступно лише класові та його нащадкам
+ String name; // за замовчанням: доступно у даному пакеті
+
+ static String className; // статична змінна класу
+
+ // статичний блок
+ // Java не має статичних конструкторів, але
+ // має статичний блок ініціалізації змінних класу
+ // Цей блок виконується при завантаженні класу.
+ static {
+ className = "Bicycle";
+ }
+
+ // Конструктори є способом створення класу
+ // Оце — конструктор
+ public Bicycle() {
+ // Можна викликати інший конструктор:
+ // this(1, 50, 5, "Bontrager");
+ gear = 1;
+ cadence = 50;
+ speed = 5;
+ name = "Bontrager";
+ }
+
+ // Цей конструктор приймає аргументи
+ public Bicycle(int startCadence, int startSpeed, int startGear,
+ String name) {
+ this.gear = startGear;
+ this.cadence = startCadence;
+ this.speed = startSpeed;
+ this.name = name;
+ }
+
+ // Синтаксис методу:
+ // <public/private/protected> <тип повернутого значення> <ім’я методу>(<аргументи>)
+
+ // Java-класи часто мають методи для отримання та встановлення змінних
+
+ // Синтаксис оголошення методу:
+ // <модифікатор доступу> <тип повернутого значення> <ім’я методу>(<аргументи>)
+ public int getCadence() {
+ return cadence;
+ }
+
+ // void-методи не повертають значень
+ public void setCadence(int newValue) {
+ cadence = newValue;
+ }
+
+ public void setGear(int newValue) {
+ gear = newValue;
+ }
+
+ public void speedUp(int increment) {
+ speed += increment;
+ }
+
+ public void slowDown(int decrement) {
+ speed -= decrement;
+ }
+
+ public void setName(String newName) {
+ name = newName;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ //Метод показує значення змінних об’єкту.
+ @Override // Успадковано від класу Object.
+ public String toString() {
+ return "gear: " + gear + " cadence: " + cadence + " speed: " + speed +
+ " name: " + name;
+ }
+} // кінець класу Bicycle
+
+// PennyFarthing є розширенням (нащадком) класу Bicycle
+class PennyFarthing extends Bicycle {
+ // (Penny Farthings мають велике переднє колесо.
+ // Вони не мають передач.)
+
+ public PennyFarthing(int startCadence, int startSpeed){
+ // Виклик батьківського конструктора через super
+ super(startCadence, startSpeed, 0, "PennyFarthing");
+ }
+
+ // Перевизначений метод має бути відмічений аннотацією, яка починається зі знака @.
+ // Для ознайомлення з аннотаціями перейдіть за посиланням
+ // http://docs.oracle.com/javase/tutorial/java/annotations/
+ @Override
+ public void setGear(int gear) {
+ gear = 0;
+ }
+}
+
+// Інтерфейси
+// Синтаксис оголошення інтерфейсів
+// <рівень доступу> interface <ім’я інтерфейсу> extends <батьківський інтерфейс> {
+// // Константи
+// // Оголошення методів
+// }
+
+//Приклад — їжа (Food):
+public interface Edible {
+ public void eat(); // Будь-які класи, що реалізують цей інтерфейс,
+ // повинні реалізувати цей метод.
+}
+
+public interface Digestible {
+ public void digest();
+}
+
+
+// Можна створити клас, що реалізує обидва інтерфейси.
+public class Fruit implements Edible, Digestible {
+
+ @Override
+ public void eat() {
+ // ...
+ }
+
+ @Override
+ public void digest() {
+ // ...
+ }
+}
+
+// В Java можна успадковувати лише один клас, але реалізовувати багато
+// інтерфейсів. Наприклад:
+public class ExampleClass extends ExampleClassParent implements InterfaceOne,
+ InterfaceTwo {
+
+ @Override
+ public void InterfaceOneMethod() {
+ }
+
+ @Override
+ public void InterfaceTwoMethod() {
+ }
+
+}
+
+// Абстрактні класи
+
+// Синтаксис оголошення абстрактних класів:
+// <рівень доступу> abstract <ім’я класу> extends <батьківський абстрактний клас> {
+// // Константи і змінні
+// // Оголошення методів
+// }
+
+// Позначення класу як абстрактного означає, що оголошені у ньому методи мають
+// бути реалізовані у дочірніх класах. Подібно до інтерфейсів, не можна створити екземпляри
+// абстракних класів, але їх можна успадковувати. Нащадок зобов’язаний реалізувати всі абстрактні
+// методи. на відміну від інтерфейсів, абстрактні класи можуть мати як визначені,
+// так і абстрактні методи. Методи в інтерфейсах не мають тіла,
+// за винятком статичних методів, а змінні неявно мають модифікатор final, на відміну від
+// абстрактного класу. Абстрактні класи МОЖУТЬ мати метод «main».
+
+public abstract class Animal
+{
+ public abstract void makeSound();
+
+ // Метод може мати тіло
+ public void eat()
+ {
+ System.out.println("Я тварина, і я їм.");
+ // Зауваження: є доступ до приватних змінних.
+ age = 30;
+ }
+
+ // Ініціалізація не потрібна
+ protected int age;
+
+ public void printAge()
+ {
+ System.out.println(age);
+ }
+
+ // Абстрактні класи МОЖУТЬ мати метод «main».
+ public static void main(String[] args)
+ {
+ System.out.println("Я абстрактний");
+ }
+}
+
+class Dog extends Animal
+{
+ // Слід помічати перевизначення абстрактних методів
+ @Override
+ public void makeSound()
+ {
+ System.out.println("Гав!");
+ // age = 30; ==> ПОМИЛКА! age є private для Animal
+ }
+
+ // Зауваження: Буде помилка, якщо використати аннотацію
+ // @Override тут, так як у java не можна
+ // перевизначати статичні методи.
+ // Те, що тут відбувається, називається приховування методів.
+ // Більш детально: http://stackoverflow.com/questions/16313649/
+ public static void main(String[] args)
+ {
+ Dog pluto = new Dog();
+ pluto.makeSound();
+ pluto.eat();
+ pluto.printAge();
+ }
+}
+
+// Фінальні класи
+
+// Синтаксис оголошення фінальних класів
+// <рівень доступу> final <ім’я класу> {
+// // Константи і змінні
+// // Оголошення методів
+// }
+
+// Фінальні класи не можуть мати нащадків, також самі вони є останніми нащадками.
+// Фінальні класи є протилежністю абстрактних у цьому плані.
+
+public final class SaberToothedCat extends Animal
+{
+ // Перевизначення методу
+ @Override
+ public void makeSound()
+ {
+ System.out.println("Гррр!");
+ }
+}
+
+// Фінальні методи
+public abstract class Mammal()
+{
+ // Синтаксис фінальних методів:
+ // <модифікатор доступу> final <тип повернутого значення> <ім’я функції>(<аргументи>)
+
+ // Фінальні методи не можуть бути перевизначені класом-нащадком,
+ // вони є остаточною реалізацією методу.
+ public final boolean isWarmBlooded()
+ {
+ return true;
+ }
+}
+
+
+// Тип Enum (перелік)
+//
+// Enum є спеціальним типом даних, який дозволяє змінним бути певною множиною
+// визначених констант. Змінна має відповідати одному зі значень, що
+// заздалегідь визначені для неї. Оскільки це константи, імена типів полів у enum
+// задаються у верхньому регістрі. Тип «перелік» у Java задається за допомогою
+// ключового слова enum. Наприклад, перелік днів тижня можна задати так:
+
+public enum Day {
+ SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
+ THURSDAY, FRIDAY, SATURDAY
+}
+
+// Перелік Day можна використовувати так:
+
+public class EnumTest {
+
+ // Змінна того же типу, що й перелік
+ Day day;
+
+ public EnumTest(Day day) {
+ this.day = day;
+ }
+
+ public void tellItLikeItIs() {
+ switch (day) {
+ case MONDAY:
+ System.out.println("Понеділкі важкі.");
+ break;
+
+ case FRIDAY:
+ System.out.println("П’ятниці краще.");
+ break;
+
+ case SATURDAY:
+ case SUNDAY:
+ System.out.println("Вихідні найліпші.");
+ break;
+
+ default:
+ System.out.println("Середина тижня так собі.");
+ break;
+ }
+ }
+
+ public static void main(String[] args) {
+ EnumTest firstDay = new EnumTest(Day.MONDAY);
+ firstDay.tellItLikeItIs(); // => Понеділки важкі.
+ EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
+ thirdDay.tellItLikeItIs(); // => Середина тижня так собі.
+ }
+}
+
+// Переліки набагато потужніші, ніж тут показано.
+// Тіло переліків може містити методи та інші змінні.
+// Дивіться більше тут: https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
+
+```
+
+## Додатково для читання
+
+Посилання, наведені нижче, дозволяють тільки зрозуміти тему. Щоб знайти конкретні приклади, використовуйте Ґуґл.
+
+**Офіційні посібники Oracle**:
+
+* [Посібник Java від Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html)
+
+* [Java — модифікатори доступу](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
+
+* [ООП-концепції](http://docs.oracle.com/javase/tutorial/java/concepts/index.html):
+ * [Наслідування](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)
+ * [Поліморфізм](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html)
+ * [Абстракція](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
+
+* [Виключення](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html)
+
+* [Інтерфейси](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)
+
+* [параметризація](http://docs.oracle.com/javase/tutorial/java/generics/index.html)
+
+* [Стиль коду у Java](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html)
+
+**Online-практика та посібники**
+
+* [Learneroo.com — Вивчаємо Java](http://www.learneroo.com)
+
+* [Codingbat.com](http://codingbat.com/java)
+
+
+**Книжки**:
+
+* [Head First Java](http://www.headfirstlabs.com/books/hfjava/)
+
+* [Thinking in Java](http://www.mindview.net/Books/TIJ/)
+
+* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660)
+
+* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300)
diff --git a/uk-ua/json-ua.html.markdown b/uk-ua/json-ua.html.markdown
index 8ee12a93..a860e9a7 100644
--- a/uk-ua/json-ua.html.markdown
+++ b/uk-ua/json-ua.html.markdown
@@ -22,7 +22,7 @@ JSON - це надзвичайно простий формат обміну да
"ключі": "завжди мають бути обгорнуті в подвійні лапки",
"числа": 0,
- "рядки": "Пρивет, світ. Допускаються всі unicode-символи разом з \"екрануванням\".",
+ "рядки": "Пρивіт, світe. Допускаються всі unicode-символи разом із \"екрануванням\".",
"логічний тип": true,
"нічого": null,
@@ -34,13 +34,13 @@ JSON - це надзвичайно простий формат обміну да
"масив": [0, 1, 2, 3, "масиви можуть містити будь-які типи", 5],
"інший об’єкт": {
- "коментра": "Об’єкти можуть містити інші об’єкти. Це дуже корисно."
+ "коментар": "Об’єкти можуть містити інші об’єкти. Це дуже корисно."
}
},
"безглуздя": [
{
- "джерело калія": ["банани"]
+ "джерело калію": ["банани"]
},
[
[1, 0, 0, 0],
@@ -56,7 +56,7 @@ JSON - це надзвичайно простий формат обміну да
, "інший коментар": "класно"
},
- "Це було не довго": "І ви справилист. Тепер ви знаєте все про JSON."
+ "Це було не довго": "І ви впорались! Тепер ви знаєте все про JSON."
}
Одиничний масив значень теж є правильним JSON
diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown
index 38e418e9..8bc334ab 100644
--- a/vi-vn/objective-c-vi.html.markdown
+++ b/vi-vn/objective-c-vi.html.markdown
@@ -1,12 +1,10 @@
---
-
language: Objective-C
contributors:
- ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
- ["Yannick Loriot", "https://github.com/YannickL"]
lang: vi-vn
filename: LearnObjectiveC-vi.m
-
---
Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch.
diff --git a/vi-vn/ruby-ecosystem-vi.html.markdown b/vi-vn/ruby-ecosystem-vi.html.markdown
new file mode 100644
index 00000000..518cf072
--- /dev/null
+++ b/vi-vn/ruby-ecosystem-vi.html.markdown
@@ -0,0 +1,148 @@
+---
+category: tool
+tool: ruby ecosystem
+contributors:
+ - ["Jon Smock", "http://github.com/jonsmock"]
+ - ["Rafal Chmiel", "http://github.com/rafalchmiel"]
+ - ["Vinh Nguyen", "http://rubydaily.net"]
+lang: vi-vn
+---
+
+Nhìn chung các lập trình viên Ruby luôn có cách để cài đặt các phiên bản
+Ruby khác nhau, quản lý các gói (hoặc gems), và quản lý các thư viện.
+
+## Trình quản lý Ruby
+
+Một vài nền tảng phải có Ruby đã được cài đặt trước hoặc có sẵn như một gói.
+Số đông lập trình viên Ruby không sử dụng cái này, hoặc nếu có, họ chỉ sử
+dụng chúng để bootstrap cài đặt Ruby. Thay vào đó, các lập trình viên Ruby
+có xu hướng cài đặt trình quản lý Ruby để cài đặt và chuyển đổi các phiên
+bản của Ruby và môi trường Ruby cho dự án của họ.
+
+Dưới đây là các trình quản lý môi trường Ruby nổi tiếng:
+
+* [RVM](https://rvm.io/) - Cài đặt và chuyển đổi các phiên bản Ruby. RVM cũng
+ có các khái niệm về tập các gems để quản lý môi trường dự án một
+ cách tốt nhất.
+* [ruby-build](https://github.com/sstephenson/ruby-build) - Chỉ cài đặt các
+ phiên bản Ruby. Sử dụng cái này giúp cho việc cài đặt Ruby tốt hơn.
+* [rbenv](https://github.com/sstephenson/rbenv) - Chỉ dùng để chuyển đổi các
+ phiên bản Ruby. Được sử dụng đi kèm với ruby-build. Tiện ích này sẽ giúp
+ cho việc dùng Ruby tốt hơn.
+* [chruby](https://github.com/postmodern/chruby) - Chỉ dùng để chuyển đổi các
+ phiên bản Ruby. Tương tự như rbenv. Không quan tâm làm thế nào Ruby được
+ cài đặt.
+
+## Các phiên bản Ruby
+
+Ruby được tạo ra bởi Yukihiro "Matz" Matsumoto, người được xem như là một
+[BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), mặc dầu gần
+đây luôn thay đổi. Kết quả là, tham chiếu của Ruby được gọi là MRI(Matz'
+Reference Implementation), và khi bạn biết về một phiên bản Ruby, nó đang
+được tham chiếu để phát hành một phiên bản của MRI.
+
+Có ba phiên bản Ruby chính thức được dùng là:
+
+* 2.0.0 - Được phát hành vào tháng 2 năm 2013. Hầu hết các thư viện lớn, và
+nền tảng đều hỗ trợ 2.0.0.
+* 1.9.3 - Được phát hành vào tháng 10 năm 2011. Đây là phiên bản hầu hết các
+lập trình viên Ruby đang dùng. [Nhưng đã không còn hỗ trợ](
+ 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 đã không còn được sử dụng](
+ http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/).
+
+Sự thay đổi giữa phiên bản 1.8.7 đến 1.9.x lớn hơn nhiều so với thay đổi từ
+1.9.3 đến 2.0.0. Ví dụ, các phiên bản 1.9 giới thiệu các bảng mã và một
+byecote VM. Có các dự án vẫn đang ở 1.8.7, nhưng chúng chiếm một số lượng ít
+, phần lớn cộng đồng đã chuyển sang ít nhất là 1.9.2 hoặc 1.9.3
+
+## Các ứng dụng Ruby
+
+Hệ sinh thái Ruby có rất nhiều ứng dụng, với mỗi thế mạnh độc đáo và khả
+năng tương thích. Để rõ ràng hơn, sự khác nhau giữa các ứng dụng được viết
+bằng các ngôn ngữ khác nhau, nhưng *chúng vẫn là Ruby*.
+Mỗi ứng dụng có các hook đặc trưng và những tính năng đặc biệt, nhưng tất cả
+đều chạy Ruby rất tốt. Ví dụ, JRuby được viết bằng Java, nhưng bạn không
+cần biết Java để sử dụng.
+
+Một số ứng dụng nổi tiếng/tương thích cao:
+
+* [MRI](https://github.com/ruby/ruby) - Được viết bằng C, đây là ứng dụng
+ tham chiếu của Ruby. Nó tương thích 100%. Tất cả các phiên bản Ruby có khả
+ năng duy trì với MRI(xem [RubySpec](#rubyspec) bên dưới).
+* [JRuby](http://jruby.org/) - Được viết bằng Java và Ruby, ứng dụng này khá
+ nhanh. Điểm mạnh quan trọng nhất của JRuby là JVM/Java interop, tận dụng
+ các công cụ, dự án và ngôn ngữ hiện có của JVM.
+* [Rubinius](http://rubini.us/) - Được viết bằng ngôn ngữ chính là Ruby với
+ một C++ bytecode VM. Rất nhanh. Bởi vì nó được phát triển bằng chính Ruby.
+
+Một số ứng dụng khá nổi tiếng/tương thích:
+
+* [Maglev](http://maglev.github.io/) - Đứng đầu Gemstone, một Smalltalk VM.
+ SmallTalk có một vài tiện ích hấp dẫn, và trong dự án này đã mang nó vào
+ môi trường Ruby.
+* [RubyMotion](http://www.rubymotion.com/) - Mang Ruby đến việc phát triển iOS.
+
+Một số ứng dụng tốt/tương thích:
+
+* [Topaz](http://topazruby.com/) - Được biết bằng RPython (sử dụng Pypy),
+ Topaz vẫn còn rất trẻ và chưa hoàn toàn tương thích. Nó hứa hẹn khả năng
+ trở thành một ứng dụng Ruby tương thích cao.
+* [IronRuby](http://ironruby.net/) - Được viết bằng C# hướng đến nền tảng .NET
+ , IronRuby dường như đã dừng hoạt động kể từ khi Microsoft rút hỗ trợ.
+
+Các ứng dụng Ruby có các phiên bản riêng của mình, nhưng chúng luôn luôn
+hướng đến sự một phiên bản đặc biệt của MRI cho sự tương thích. Nhiều ứng
+dụng có khả năng đến các chế độ khác nhau (ví dụ, 1.8 hoặc 1.9) để hướng đến
+phiên bản MRI.
+
+## RubySpec
+
+Hầu hết các ứng dụng Ruby dựa vào [RubySpec](http://rubyspec.org/). Ruby không
+có thông báo chính thức, nhưng cộng đồng đã viết những specs thực thi trong
+Ruby để kiểm tra sự tương thích với MRI.
+
+## RubyGems
+
+[RubyGems](http://rubygems.org/) là một cộng đồng quản lý các gói cho Ruby.
+RubyGems đi kèm với Ruby, bởi vậy không cần cài đặt riêng lẻ.
+
+Các gói Ruby được gọi là "gems", và chúng được host bởi cộng đồng tại
+RubyGems.org. Một gem chứa mã nguồn của nó và một vài mô tả, bao gồm những
+thứ như phiên bản, các thư viện độc lập, các tác giả và các loại giấy phép.
+
+## Bundler
+
+[Bundler](http://bundler.io/) là một gem giải quyết độc lập. Nó sử dụng một
+Gemfile để tìm kiếm các thư viện độc lập trong dự án, và sau đó sẽ lấy về
+các thư viện của các thư viện độc lập này. Nó thực hiện cho đến khi việc
+tải các thư viện hoàn tất, hoặc nó sẽ dừng nếu xuất hiện bất kỳ xung đột nào.
+
+Bundler sẽ hiển thị lỗi nếu tìm thấy bất kỳ xung đột giữa các thư viện. Ví
+dụ, nếu như gem A yêu cầu gem Z có phiên bản 3 hoặc cao hơn, nhưng gem B lại
+yêu cầu gem Z phiên bản 2. Bundler sẽ thông báo cho bạn sự xung đột này.
+Điều này đã rất hữu ích khi nhiều gem tham chiếu các các gem khác (trong
+gem này lại tham chiếu đến các gem khác nữa), có thể hình thành một đồ thị
+lớn để nói.
+
+# Kiểm thử
+
+Kiểm thử là một phần lớn của Ruby. Ruby mang đến một nền tảng kiểm thử theo
+kiểu Unit được gọi là minitest (hoặc TestUnit for phiên bản Ruby 1.8.x).
+Có nhiều thư viện kiểm thử với các mục đích khác nhau.
+
+* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/
+ Unit.html) - Nền tảng kiểm thử theo kiểu Unit của Ruby 1.8.
+* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest
+ /rdoc/MiniTest.html) -Nền tảng kiểm thử được xây dựng cho Ruby 1.9/2.0
+* [RSpec](http://rspec.info/) - Một nền tảng kiểm thử tập trung vào sự
+ hoạt động.
+* [Cucumber](http://cukes.info/) - Một nền tảng kiểm thử theo kiểu BDD dưới
+ định dạng Gherkin.
+
+## Be Nice
+
+Cộng đồng Ruby tự hào là một cộng đồng mở, đa dạng và chào đón tất cả mọi
+người. Bản thân Matz là một người cực kỳ thân thiện, và các lập trình viên
+Ruby rất tuyệt vời.
diff --git a/wolfram.html.markdown b/wolfram.html.markdown
new file mode 100644
index 00000000..4514006d
--- /dev/null
+++ b/wolfram.html.markdown
@@ -0,0 +1,137 @@
+---
+language: wolfram
+contributors:
+ - ["hyphz", "http://github.com/hyphz/"]
+filename: learnwolfram.nb
+---
+
+The Wolfram Language is the underlying language originally used in Mathematica, but now available for use in multiple contexts.
+
+Wolfram Language has several interfaces:
+* The command line kernel interface on Raspberry Pi (just called _The Wolfram Language_) which runs interactively and can't produce graphical input.
+* _Mathematica_ which is a rich text/maths editor with interactive Wolfram built in: pressing shift+Return on a "code cell" creates an output cell with the result, which is not dynamic
+* _Wolfram Workbench_ which is Eclipse interfaced to the Wolfram Language backend
+
+The code in this example can be typed in to any interface and edited with Wolfram Workbench. Loading directly into Mathematica may be awkward because the file contains no cell formatting information (which would make the file a huge mess to read as text) - it can be viewed/edited but may require some setting up.
+
+```
+(* This is a comment *)
+
+(* In Mathematica instead of using these comments you can create a text cell
+ and annotate your code with nicely typeset text and images *)
+
+(* Typing an expression returns the result *)
+2*2 (* 4 *)
+5+8 (* 13 *)
+
+(* Function Call *)
+(* Note, function names (and everything else) are case sensitive *)
+Sin[Pi/2] (* 1 *)
+
+(* Alternate Syntaxes for Function Call with one parameter *)
+Sin@(Pi/2) (* 1 *)
+(Pi/2) // Sin (* 1 *)
+
+(* Every syntax in WL has some equivalent as a function call *)
+Times[2, 2] (* 4 *)
+Plus[5, 8] (* 13 *)
+
+(* Using a variable for the first time defines it and makes it global *)
+x = 5 (* 5 *)
+x == 5 (* True, C-style assignment and equality testing *)
+x (* 5 *)
+x = x + 5 (* 10 *)
+x (* 10 *)
+Set[x, 20] (* I wasn't kidding when I said EVERYTHING has a function equivalent *)
+x (* 20 *)
+
+(* Because WL is based on a computer algebra system, *)
+(* using undefined variables is fine, they just obstruct evaluation *)
+cow + 5 (* 5 + cow, cow is undefined so can't evaluate further *)
+cow + 5 + 10 (* 15 + cow, it'll evaluate what it can *)
+% (* 15 + cow, % fetches the last return *)
+% - cow (* 15, undefined variable cow cancelled out *)
+moo = cow + 5 (* Beware, moo now holds an expression, not a number! *)
+
+(* Defining a function *)
+Double[x_] := x * 2 (* Note := to prevent immediate evaluation of the RHS
+ And _ after x to indicate no pattern matching constraints *)
+Double[10] (* 20 *)
+Double[Sin[Pi/2]] (* 2 *)
+Double @ Sin @ (Pi/2) (* 2, @-syntax avoids queues of close brackets *)
+(Pi/2) // Sin // Double(* 2, //-syntax lists functions in execution order *)
+
+(* For imperative-style programming use ; to separate statements *)
+(* Discards any output from LHS and runs RHS *)
+MyFirst[] := (Print@"Hello"; Print@"World") (* Note outer parens are critical
+ ;'s precedence is lower than := *)
+MyFirst[] (* Hello World *)
+
+(* C-Style For Loop *)
+PrintTo[x_] := For[y=0, y<x, y++, (Print[y])] (* Start, test, incr, body *)
+PrintTo[5] (* 0 1 2 3 4 *)
+
+(* While Loop *)
+x = 0; While[x < 2, (Print@x; x++)] (* While loop with test and body *)
+
+(* If and conditionals *)
+x = 8; If[x==8, Print@"Yes", Print@"No"] (* Condition, true case, else case *)
+Switch[x, 2, Print@"Two", 8, Print@"Yes"] (* Value match style switch *)
+Which[x==2, Print@"No", x==8, Print@"Yes"] (* Elif style switch *)
+
+(* Variables other than parameters are global by default, even inside functions *)
+y = 10 (* 10, global variable y *)
+PrintTo[5] (* 0 1 2 3 4 *)
+y (* 5, global y clobbered by loop counter inside PrintTo *)
+x = 20 (* 20, global variable x *)
+PrintTo[5] (* 0 1 2 3 4 *)
+x (* 20, x in PrintTo is a parameter and automatically local *)
+
+(* Local variables are declared using the Module metafunction *)
+(* Version with local variable *)
+BetterPrintTo[x_] := Module[{y}, (For[y=0, y<x, y++, (Print@y)])]
+y = 20 (* Global variable y *)
+BetterPrintTo[5] (* 0 1 2 3 4 *)
+y (* 20, that's better *)
+
+(* Module actually lets us declare any scope we like *)
+Module[{count}, count=0; (* Declare scope of this variable count *)
+ (IncCount[] := ++count); (* These functions are inside that scope *)
+ (DecCount[] := --count)]
+count (* count - global variable count is not defined *)
+IncCount[] (* 1, using the count variable inside the scope *)
+IncCount[] (* 2, incCount updates it *)
+DecCount[] (* 1, so does decCount *)
+count (* count - still no global variable by that name *)
+
+(* Lists *)
+myList = {1, 2, 3, 4} (* {1, 2, 3, 4} *)
+myList[[1]] (* 1 - note list indexes start at 1, not 0 *)
+Map[Double, myList] (* {2, 4, 6, 8} - functional style list map function *)
+Double /@ myList (* {2, 4, 6, 8} - Abbreviated syntax for above *)
+Scan[Print, myList] (* 1 2 3 4 - imperative style loop over list *)
+Fold[Plus, 0, myList] (* 10 (0+1+2+3+4) *)
+FoldList[Plus, 0, myList] (* {0, 1, 3, 6, 10} - fold storing intermediate results *)
+Append[myList, 5] (* {1, 2, 3, 4, 5} - note myList is not updated *)
+Prepend[myList, 5] (* {5, 1, 2, 3, 4} - add "myList = " if you want it to be *)
+Join[myList, {3, 4}] (* {1, 2, 3, 4, 3, 4} *)
+myList[[2]] = 5 (* {1, 5, 3, 4} - this does update myList *)
+
+(* Associations, aka Dictionaries/Hashes *)
+myHash = <|"Green" -> 2, "Red" -> 1|> (* Create an association *)
+myHash[["Green"]] (* 2, use it *)
+myHash[["Green"]] := 5 (* 5, update it *)
+myHash[["Puce"]] := 3.5 (* 3.5, extend it *)
+KeyDropFrom[myHash, "Green"] (* Wipes out key Green *)
+Keys[myHash] (* {Red} *)
+Values[myHash] (* {1} *)
+
+(* And you can't do any demo of Wolfram without showing this off *)
+Manipulate[y^2, {y, 0, 20}] (* Return a reactive user interface that displays y^2
+ and allows y to be adjusted between 0-20 with a slider.
+ Only works on graphical frontends *)
+```
+
+##Ready For More?
+
+* [Wolfram Language Documentation Center](http://reference.wolfram.com/language/)
diff --git a/zfs.html.markdown b/zfs.html.markdown
index 74487e35..3fe05896 100644
--- a/zfs.html.markdown
+++ b/zfs.html.markdown
@@ -9,7 +9,7 @@ filename: LearnZfs.txt
[ZFS](http://open-zfs.org/wiki/Main_Page)
is a rethinking of the storage stack, combining traditional file systems as well as volume
-managers into one cohesive tool. ZFS has some specific teminology that sets it appart from
+managers into one cohesive tool. ZFS has some specific terminology that sets it apart from
more traditional storage systems, however it has a great set of features with a focus on
usability for systems administrators.
@@ -23,7 +23,7 @@ types of VDEV's that offer various advantages, including redundancy and speed.
VDEV's offer better reliability and safety than a RAID card. It is discouraged to use a
RAID setup with ZFS, as ZFS expects to directly manage the underlying disks.
-Types of VDEV's
+Types of VDEV's
* stripe (a single disk, no redundancy)
* mirror (n-way mirrors supported)
* raidz
@@ -39,13 +39,13 @@ increase your IOPS.
### Storage Pools
ZFS uses Storage Pools as an abstraction over the lower level storage provider (VDEV), allow
-you to separate the user visable file system from the physcal layout.
+you to separate the user visible file system from the physical layout.
### ZFS Dataset
-ZFS datasets are analagous to traditional filesystems but with many more features. They
+ZFS datasets are analogous to traditional filesystems but with many more features. They
provide many of ZFS's advantages. Datasets support [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write)
-snapshots, quota's, compression and deduplication.
+snapshots, quota's, compression and de-duplication.
### Limits
@@ -68,7 +68,7 @@ Actions:
List zpools
```bash
-# Create a raidz zpool
+# Create a raidz zpool
$ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2
# List ZPools
@@ -347,7 +347,7 @@ $ zfs promote tank/home/sarlalian_new
### Putting it all together
-This following a script utilizing FreeBSD, jails and ZFS to automate
+This following a script utilizing FreeBSD, jails and ZFS to automate
provisioning a clean copy of a mysql staging database from a live replication
slave.
@@ -384,7 +384,7 @@ mv /jails/staging/etc/rc.conf.staging /jails/staging/etc/rc.conf.local
echo "==== Starting the staging db server ===="
jail -c staging
-echo "==== Make sthe staging database not pull from the master ===="
+echo "==== Makes the staging database not pull from the master ===="
echo "STOP SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging
echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging
```
@@ -393,7 +393,7 @@ echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging
### Additional Reading
* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs)
-* [FreeBSD Handbook on ZFS](https://wiki.freebsd.org/ZF://wiki.freebsd.org/ZFS)
+* [FreeBSD Handbook on ZFS](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/zfs.html)
* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs)
* [Oracle's Tuning Guide](http://www.oracle.com/technetwork/articles/servers-storage-admin/sto-recommended-zfs-settings-1951715.html)
* [OpenZFS Tuning Guide](http://open-zfs.org/wiki/Performance_tuning)
diff --git a/zh-cn/brainfuck-cn.html.markdown b/zh-cn/bf-cn.html.markdown
index a6f3fa09..6cea3012 100644
--- a/zh-cn/brainfuck-cn.html.markdown
+++ b/zh-cn/bf-cn.html.markdown
@@ -1,5 +1,5 @@
---
-language: brainfuck
+language: bf
lang: zh-cn
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
diff --git a/zh-cn/common-lisp-cn.html.markdown b/zh-cn/common-lisp-cn.html.markdown
index b82829a9..c7fe7e2c 100644
--- a/zh-cn/common-lisp-cn.html.markdown
+++ b/zh-cn/common-lisp-cn.html.markdown
@@ -14,6 +14,8 @@ ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范
免费的经典的入门书籍[《实用 Common Lisp 编程》](http://www.gigamonkeys.com/book/)
+许多人都抱怨上面这本书的翻译。[《ANSI Common Lisp》](http://acl.readthedocs.org/en/latest/)也许对中文读者更友好一些。
+
另外还有一本热门的近期出版的
[Land of Lisp](http://landoflisp.com/).
diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown
index a8fd2a4c..1e9c38f6 100644
--- a/zh-cn/java-cn.html.markdown
+++ b/zh-cn/java-cn.html.markdown
@@ -302,7 +302,7 @@ class Bicycle {
// 构造函数是初始化一个对象的方式
// 以下是一个默认构造函数
- public Bi450635425cycle() {
+ public Bicycle() {
gear = 1;
cadence = 50;
speed = 5;
@@ -328,7 +328,7 @@ class Bicycle {
return cadence;
}
- // void返450635425回值函数没有返回值
+ // void返回值函数没有返回值
public void setCadence(int newValue) {
cadence = newValue;
}
diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown
index 098d0ab5..6736dc2a 100644
--- a/zh-cn/lua-cn.html.markdown
+++ b/zh-cn/lua-cn.html.markdown
@@ -91,10 +91,10 @@ until num == 0
-- 2. 函数。
----------------------------------------------------
-function fib(n)
- if n < 2 then return 1 end
- return fib(n - 2) + fib(n - 1)
-end
+function fib(n)
+ if n < 2 then return n end
+ return fib(n - 2) + fib(n - 1)
+end
-- 支持闭包及匿名函数:
function adder(x)
@@ -129,9 +129,11 @@ function f(x) return x * x end
f = function (x) return x * x end
-- 这些也是等价的:
-local function g(x) return math.sin(x) end
-local g; g = function (x) return math.sin(x) end
--- 'local g'使得g可以自引用。
+local function g(x) return math.sin(x) end
+local g; g = function (x) return math.sin(x) end
+-- 以上均因'local g',使得g可以自引用。
+local g = function(x) return math.sin(x) end
+-- 等价于 local function g(x)..., 但函数体中g不可自引用
-- 顺便提下,三角函数以弧度为单位。
@@ -210,7 +212,7 @@ f2 = {a = 2, b = 3}
metafraction = {}
function metafraction.__add(f1, f2)
- sum = {}
+ local sum = {}
sum.b = f1.b * f2.b
sum.a = f1.a * f2.b + f2.a * f1.b
return sum
@@ -273,7 +275,7 @@ eatenBy = myFavs.animal -- 可以工作!感谢元表
Dog = {} -- 1.
function Dog:new() -- 2.
- newObj = {sound = 'woof'} -- 3.
+ local newObj = {sound = 'woof'} -- 3.
self.__index = self -- 4.
return setmetatable(newObj, self) -- 5.
end
@@ -307,7 +309,7 @@ mrDog:makeSound() -- 'I say woof' -- 8.
LoudDog = Dog:new() -- 1.
function LoudDog:makeSound()
- s = self.sound .. ' ' -- 2.
+ local s = self.sound .. ' ' -- 2.
print(s .. s .. s)
end
@@ -328,7 +330,7 @@ seymour:makeSound() -- 'woof woof woof' -- 4.
-- 如果有必要,子类也可以有new(),与基类相似:
function LoudDog:new()
- newObj = {}
+ local newObj = {}
-- 初始化newObj
self.__index = self
return setmetatable(newObj, self)
@@ -340,7 +342,9 @@ end
--[[ 我把这部分给注释了,这样脚本剩下的部分可以运行
+```
+```lua
-- 假设文件mod.lua的内容类似这样:
local M = {}
@@ -411,4 +415,9 @@ lua-users.org上的[Lua简明参考](http://lua-users.org/files/wiki_insecure/us
* <a href="http://lua-users.org/wiki/IoLibraryTutorial">io library</a>
* <a href="http://lua-users.org/wiki/OsLibraryTutorial">os library</a>
+顺便说一下,整个文件是可运行的Lua;
+保存为 learn-cn.lua 用命令 `lua learn-cn.lua` 启动吧!
+
+本文首次撰写于 [tylerneylon.com](http://tylerneylon.com) 同时也有 [github gist](https://gist.github.com/tylerneylon/5853042) 版.
+
使用Lua,欢乐常在!
diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown
index b633714d..87ed46ad 100644
--- a/zh-cn/markdown-cn.html.markdown
+++ b/zh-cn/markdown-cn.html.markdown
@@ -53,7 +53,7 @@ __此文本也是__
**_或者这样。_**
*__这个也是!__*
-<!-- 在 Github 采用的 Markdown 中 -->
+<!-- 在 GitHub 采用的 Markdown 中 -->
~~此文本为删除线效果。~~
@@ -142,7 +142,7 @@ __此文本也是__
John 甚至不知道 `go_to()` 方程是干嘛的!
-<!-- 在Github的 Markdown中,对于代码你可以使用特殊的语法 -->
+<!-- 在GitHub的 Markdown中,对于代码你可以使用特殊的语法 -->
\`\`\`ruby <!-- 插入时记得移除反斜线, 仅留```ruby ! -->
def foobar
@@ -150,7 +150,7 @@ def foobar
end
\`\`\` <!-- 这里也是,移除反斜线,仅留 ``` -->
-<!-- 以上代码不需要缩进,而且 Github 会根据```后表明的语言来进行语法高亮 -->
+<!-- 以上代码不需要缩进,而且 GitHub 会根据```后表明的语言来进行语法高亮 -->
<!-- 水平线 (<hr />) -->
<!-- 水平线可由三个或以上的星号或者减号创建,可带可不带空格。 -->
@@ -220,7 +220,7 @@ end
斜体化, 所以我就: \*这段置文字于星号之间\*。
<!-- 表格 -->
-<!-- 表格只被 Github 的 Markdown 支持,并且有一点笨重,但如果你真的要用的话: -->
+<!-- 表格只被 GitHub 的 Markdown 支持,并且有一点笨重,但如果你真的要用的话: -->
| 第一列 | 第二列 | 第三列 |
| :---------- | :------: | ----------: |
diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown
index 508dd58e..f3327b5b 100644
--- a/zh-cn/scala-cn.html.markdown
+++ b/zh-cn/scala-cn.html.markdown
@@ -369,7 +369,7 @@ object Dog {
// Case 类是有额外内建功能的类。Scala 初学者常遇到的问题之一便是何时用类
// 和何时用 case 类。界线比较模糊,但通常类倾向于封装,多态和行为。类中的值
-// 的作用域一般为 private , 只有方向是暴露的。case 类的主要目的是放置不可变
+// 的作用域一般为 private , 只有方法是暴露的。case 类的主要目的是放置不可变
// 数据。它们通常只有几个方法,且方法几乎没有副作用。
case class Person(name: String, phoneNumber: String)
diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown
index 3efe4941..017a7812 100644
--- a/zh-cn/swift-cn.html.markdown
+++ b/zh-cn/swift-cn.html.markdown
@@ -31,7 +31,7 @@ import UIKit
// Swift2.0 println() 及 print() 已经整合成 print()。
print("Hello, world") // 这是原本的 println(),会自动进入下一行
-print("Hello, world", appendNewLine: false) // 如果不要自动进入下一行,需设定进入下一行为 false
+print("Hello, world", terminator: "") // 如果不要自动进入下一行,需设定结束符为空串
// 变量 (var) 的值设置后可以随意改变
// 常量 (let) 的值设置后不能改变
@@ -171,8 +171,8 @@ while i < 1000 {
i *= 2
}
-// do-while 循环
-do {
+// repeat-while 循环
+repeat {
print("hello")
} while 1 == 2
@@ -212,11 +212,11 @@ default: // 在 Swift 里,switch 语句的 case 必须处理所有可能的情
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
-greet("Bob", "Tuesday")
+greet("Bob", day: "Tuesday")
-// 函数参数前带 `#` 表示外部参数名和内部参数名使用同一个名称。
+// 第一个参数表示外部参数名和内部参数名使用同一个名称。
// 第二个参数表示外部参数名使用 `externalParamName` ,内部参数名使用 `localParamName`
-func greet2(#requiredName: String, externalParamName localParamName: String) -> String {
+func greet2(requiredName requiredName: String, externalParamName localParamName: String) -> String {
return "Hello \(requiredName), the day is \(localParamName)"
}
greet2(requiredName:"John", externalParamName: "Sunday") // 调用时,使用命名参数来指定参数的值
@@ -235,8 +235,8 @@ print("Gas price: \(price)")
// 可变参数
func setup(numbers: Int...) {
// 可变参数是个数组
- let number = numbers[0]
- let argCount = numbers.count
+ let _ = numbers[0]
+ let _ = numbers.count
}
// 函数变量以及函数作为返回值返回
@@ -257,7 +257,7 @@ func swapTwoInts(inout a: Int, inout b: Int) {
}
var someIntA = 7
var someIntB = 3
-swapTwoInts(&someIntA, &someIntB)
+swapTwoInts(&someIntA, b: &someIntB)
print(someIntB) // 7
@@ -286,17 +286,10 @@ numbers = numbers.map({ number in 3 * number })
print(numbers) // [3, 6, 18]
// 简洁的闭包
-numbers = sorted(numbers) { $0 > $1 }
-// 函数的最后一个参数可以放在括号之外,上面的语句是这个语句的简写形式
-// numbers = sorted(numbers, { $0 > $1 })
+numbers = numbers.sort { $0 > $1 }
print(numbers) // [18, 6, 3]
-// 超级简洁的闭包,因为 `<` 是个操作符函数
-numbers = sorted(numbers, < )
-
-print(numbers) // [3, 6, 18]
-
//
// MARK: 结构体
@@ -305,7 +298,7 @@ print(numbers) // [3, 6, 18]
// 结构体和类非常类似,可以有属性和方法
struct NamesTable {
- let names = [String]()
+ let names: [String]
// 自定义下标运算符
subscript(index: Int) -> String {
@@ -516,7 +509,7 @@ protocol ShapeGenerator {
// 一个类实现一个带 optional 方法的协议时,可以实现或不实现这个方法
// optional 方法可以使用 optional 规则来调用
@objc protocol TransformShape {
- optional func reshaped()
+ optional func reshape()
optional func canReshape() -> Bool
}
@@ -528,9 +521,9 @@ class MyShape: Rect {
// 在 optional 属性,方法或下标运算符后面加一个问号,可以优雅地忽略 nil 值,返回 nil。
// 这样就不会引起运行时错误 (runtime error)
- if let allow = self.delegate?.canReshape?() {
+ if let reshape = self.delegate?.canReshape?() where reshape {
// 注意语句中的问号
- self.delegate?.reshaped?()
+ self.delegate?.reshape?()
}
}
}
@@ -542,8 +535,8 @@ class MyShape: Rect {
// 扩展: 给一个已经存在的数据类型添加功能
-// 给 Square 类添加 `Printable` 协议的实现,现在其支持 `Printable` 协议
-extension Square: Printable {
+// 给 Square 类添加 `CustomStringConvertible` 协议的实现,现在其支持 `CustomStringConvertible` 协议
+extension Square: CustomStringConvertible {
var description: String {
return "Area: \(self.getArea()) - ID: \(self.identifier)"
}
@@ -567,8 +560,8 @@ print(14.multiplyBy(3)) // 42
// 泛型: 和 Java 及 C# 的泛型类似,使用 `where` 关键字来限制类型。
// 如果只有一个类型限制,可以省略 `where` 关键字
-func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
- for (index, value) in enumerate(array) {
+func findIndex<T: Equatable>(array: [T], _ valueToFind: T) -> Int? {
+ for (index, value) in array.enumerate() {
if value == valueToFind {
return index
}
diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown
new file mode 100644
index 00000000..cf865dce
--- /dev/null
+++ b/zh-cn/tmux-cn.html.markdown
@@ -0,0 +1,253 @@
+---
+category: tool
+tool: tmux
+filename: LearnTmux-cn.txt
+contributors:
+ - ["mdln", "https://github.com/mdln"]
+translators:
+ - ["Arnie97", "https://github.com/Arnie97"]
+lang: zh-cn
+---
+
+
+[tmux](http://tmux.github.io)是一款终端复用工具。
+在它的帮助下,你可以在同一个控制台上建立、访问并控制多个终端。
+你可以断开与一个 tmux 终端的连接,此时程序将在后台运行,
+当你需要时,可以随时重新连接到这个终端。
+
+```
+
+ tmux [command] # 运行一条命令
+ # 如果单独使用 'tmux' 而不指定某个命令,将会建立一个新的会话
+
+ new # 创建一个新的会话
+ -s "Session" # 创建一个会话,并命名为“Session”
+ -n "Window" # 创建一个窗口,并命名为“Window”
+ -c "/dir" # 在指定的工作目录中启动会话
+
+ attach # 连接到上一次的会话(如果可用)
+ -t "#" # 连接到指定的会话
+ -d # 断开其他客户端的会话
+
+ ls # 列出打开的会话
+ -a # 列出所有打开的会话
+
+ lsw # 列出窗口
+ -a # 列出所有窗口
+ -s # 列出会话中的所有窗口
+
+ lsp # 列出窗格
+ -a # 列出所有窗格
+ -s # 列出会话中的所有窗格
+ -t "#" # 列出指定窗口中的所有窗格
+
+ kill-window # 关闭当前窗口
+ -t "#" # 关闭指定的窗口
+ -a # 关闭所有窗口
+ -a -t "#" # 关闭除指定窗口以外的所有窗口
+
+ kill-session # 关闭当前会话
+ -t "#" # 关闭指定的会话
+ -a # 关闭所有会话
+ -a -t "#" # 关闭除指定会话以外的所有会话
+
+```
+
+
+### 快捷键
+
+通过“前缀”快捷键,可以控制一个已经连入的 tmux 会话。
+
+```
+----------------------------------------------------------------------
+ (C-b) = Ctrl + b # 在使用下列快捷键之前,需要按这个“前缀”快捷键
+
+ (M-1) = Meta + 1 或 Alt + 1
+----------------------------------------------------------------------
+
+ ? # 列出所有快捷键
+ : # 进入 tmux 的命令提示符
+ r # 强制重绘当前客户端
+ c # 创建一个新窗口
+
+ ! # 将当前窗格从窗口中移出,成为为一个新的窗口
+ % # 将当前窗格分为左右两半
+ " # 将当前窗格分为上下两半
+
+ n # 切换到下一个窗口
+ p # 切换到上一个窗口
+ { # 将当前窗格与上一个窗格交换
+ } # 将当前窗格与下一个窗格交换
+
+ s # 在交互式界面中,选择并连接至另一个会话
+ w # 在交互式界面中,选择并激活一个窗口
+ 0 至 9 # 选择 0 到 9 号窗口
+
+ d # 断开当前客户端
+ D # 选择并断开一个客户端
+
+ & # 关闭当前窗口
+ x # 关闭当前窗格
+
+ Up, Down # 将焦点移动至相邻的窗格
+ Left, Right
+
+ M-1 到 M-5 # 排列窗格:
+ # 1) 水平等分
+ # 2) 垂直等分
+ # 3) 将一个窗格作为主要窗格,其他窗格水平等分
+ # 4) 将一个窗格作为主要窗格,其他窗格垂直等分
+ # 5) 平铺
+
+ C-Up, C-Down # 改变当前窗格的大小,每按一次增减一个单位
+ C-Left, C-Right
+
+ M-Up, M-Down # 改变当前窗格的大小,每按一次增减五个单位
+ M-Left, M-Right
+
+```
+
+
+### 配置 ~/.tmux.conf
+
+tmux.conf 可以在 tmux 启动时自动设置选项,类似于 .vimrc 或 init.el 的用法。
+
+```
+# tmux.conf 示例
+# 2014.10
+
+
+### 通用设置
+###########################################################################
+
+# 启用 UTF-8 编码
+setw -g utf8 on
+set-option -g status-utf8 on
+
+# 命令回滚/历史数量限制
+set -g history-limit 2048
+
+# 从 1 开始编号,而不是从 0 开始
+set -g base-index 1
+
+# 启用鼠标
+set-option -g mouse-select-pane on
+
+# 重新加载配置文件
+unbind r
+bind r source-file ~/.tmux.conf
+
+
+### 快捷键设置
+###########################################################################
+
+# 取消默认的前缀键 C-b
+unbind C-b
+
+# 设置新的前缀键 `
+set-option -g prefix `
+
+# 多次按下前缀键时,切换到上一个窗口
+bind C-a last-window
+bind ` last-window
+
+# 按下F11/F12,可以选择不同的前缀键
+bind F11 set-option -g prefix C-a
+bind F12 set-option -g prefix `
+
+# Vim 风格的快捷键绑定
+setw -g mode-keys vi
+set-option -g status-keys vi
+
+# 使用 Vim 风格的按键在窗格间移动
+bind h select-pane -L
+bind j select-pane -D
+bind k select-pane -U
+bind l select-pane -R
+
+# 循环切换不同的窗口
+bind e previous-window
+bind f next-window
+bind E swap-window -t -1
+bind F swap-window -t +1
+
+# 较易于使用的窗格分割快捷键
+bind = split-window -h
+bind - split-window -v
+unbind '"'
+unbind %
+
+# 在嵌套使用 tmux 的情况下,激活最内层的会话,以便向其发送命令
+bind a send-prefix
+
+
+### 外观主题
+###########################################################################
+
+# 状态栏颜色
+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
+
+# 窗格边框颜色
+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
+
+# 消息框颜色
+set-option -g message-fg black
+set-option -g message-bg green
+
+# 窗口状态栏颜色
+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
+
+
+### 用户界面
+###########################################################################
+
+# 通知方式
+setw -g monitor-activity on
+set -g visual-activity on
+set-option -g bell-action any
+set-option -g visual-bell off
+
+# 自动设置窗口标题
+set-option -g set-titles on
+set-option -g set-titles-string '#H:#S.#I.#P #W #T' # 窗口编号,程序名称,是否活动
+
+# 调整状态栏
+set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]"
+
+# 在状态栏中显示性能计数器
+# 需要用到 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]"
+
+```
+
+
+### 参考资料
+
+[Tmux 主页](http://tmux.github.io)
+
+[Tmux 手册](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux)
+
+[FreeBSDChina Wiki](https://wiki.freebsdchina.org/software/t/tmux)
+
+[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux_(简体中文))
+
+[Tmux 快速教程](http://blog.jeswang.org/blog/2013/06/24/tmux-kuai-su-jiao-cheng)
+
+[如何在 tmux 状态栏中显示 CPU / 内存占用的百分比](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux)
+
+[管理复杂 tmux 会话的工具 - tmuxinator](https://github.com/tmuxinator/tmuxinator)
diff --git a/zh-cn/typescript-cn.html.markdown b/zh-cn/typescript-cn.html.markdown
new file mode 100644
index 00000000..2651b1cb
--- /dev/null
+++ b/zh-cn/typescript-cn.html.markdown
@@ -0,0 +1,173 @@
+---
+language: TypeScript
+category: language
+contributors:
+ - ["Philippe Vlérick", "https://github.com/pvlerick"]
+translators:
+ - ["Shawn Zhang", "https://github.com/shawnzhang009"]
+filename: learntypescript-cn.ts
+lang: zh-cn
+---
+
+TypeScript是一门为开发大型JavaScript应用而设计的语言。TypeScript在JavaScript的基础上增加了类、模块、接口、泛型和静态类型(可选)等常见的概念。它是JavaScript的一个超集:所有JavaScript代码都是有效的TypeScript代码,所以任何JavaScript项目都可以无缝引入TypeScript. TypeScript编译器会把TypeScript代码编译成JavaScript代码。
+
+本文只关注TypeScript额外增加的区别于[JavaScript](../javascript-cn/)的语法,.
+
+如需测试TypeScript编译器,你可以在[Playground](http://www.typescriptlang.org/Playground)码代码,它会自动编译成JavaScript代码然后直接显示出来。
+
+```js
+// TypeScript有三种基本类型
+var isDone: boolean = false;
+var lines: number = 42;
+var name: string = "Anders";
+
+// 如果不知道是什么类型,可以使用"any"(任意)类型
+var notSure: any = 4;
+notSure = "maybe a string instead";
+notSure = false; // 亦可,定义为布尔型
+
+// 对于集合的声明, 有类型化数组和泛型数组
+var list: number[] = [1, 2, 3];
+// 另外一种,使用泛型数组
+var list: Array<number> = [1, 2, 3];
+
+// 枚举:
+enum Color {Red, Green, Blue};
+var c: Color = Color.Green;
+
+// 最后,"void"用于函数没有任何返回的特殊情况下
+function bigHorribleAlert(): void {
+ alert("I'm a little annoying box!");
+}
+
+// 函数是"第一等公民"(first class citizens), 支持使用箭头表达式和类型推断
+
+// 以下是相等的,TypeScript编译器会把它们编译成相同的JavaScript代码
+var f1 = function(i: number): number { return i * i; }
+// 返回推断类型的值
+var f2 = function(i: number) { return i * i; }
+var f3 = (i: number): number => { return i * i; }
+// 返回推断类型的值
+var f4 = (i: number) => { return i * i; }
+// 返回推断类型的值, 单行程式可以不需要return关键字和大括号
+var f5 = (i: number) => i * i;
+
+// 接口是结构化的,任何具有这些属性的对象都与该接口兼容
+interface Person {
+ name: string;
+ // 可选属性,使用"?"标识
+ age?: number;
+ // 函数
+ move(): void;
+}
+
+// 实现"Person"接口的对象,当它有了"name"和"move"方法之后可被视为一个"Person"
+var p: Person = { name: "Bobby", move: () => {} };
+// 带了可选参数的对象
+var validPerson: Person = { name: "Bobby", age: 42, move: () => {} };
+// 因为"age"不是"number"类型所以这不是一个"Person"
+var invalidPerson: Person = { name: "Bobby", age: true };
+
+// 接口同样可以描述一个函数的类型
+interface SearchFunc {
+ (source: string, subString: string): boolean;
+}
+// 参数名并不重要,参数类型才是重要的
+var mySearch: SearchFunc;
+mySearch = function(src: string, sub: string) {
+ return src.search(sub) != -1;
+}
+
+// 类 - 成员默认为公共的(public)
+class Point {
+ // 属性
+ x: number;
+
+ // 构造器 - 这里面的public/private关键字会为属性生成样板代码和初始化值
+ // 这个例子中,y会被同x一样定义,不需要额外代码
+ // 同样支持默认值
+
+ constructor(x: number, public y: number = 0) {
+ this.x = x;
+ }
+
+ // 函数
+ dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
+
+ // 静态成员
+ static origin = new Point(0, 0);
+}
+
+var p1 = new Point(10 ,20);
+var p2 = new Point(25); //y为0
+
+// 继承
+class Point3D extends Point {
+ constructor(x: number, y: number, public z: number = 0) {
+ super(x, y); // 必须显式调用父类的构造器
+ }
+
+ // 重写
+ dist() {
+ var d = super.dist();
+ return Math.sqrt(d * d + this.z * this.z);
+ }
+}
+
+// 模块, "."可以作为子模块的分隔符
+module Geometry {
+ export class Square {
+ constructor(public sideLength: number = 0) {
+ }
+ area() {
+ return Math.pow(this.sideLength, 2);
+ }
+ }
+}
+
+var s1 = new Geometry.Square(5);
+
+// 引入模块并定义本地别名
+import G = Geometry;
+
+var s2 = new G.Square(10);
+
+// 泛型
+// 类
+class Tuple<T1, T2> {
+ constructor(public item1: T1, public item2: T2) {
+ }
+}
+
+// 接口
+interface Pair<T> {
+ item1: T;
+ item2: T;
+}
+
+// 以及函数
+var pairToTuple = function<T>(p: Pair<T>) {
+ return new Tuple(p.item1, p.item2);
+};
+
+var tuple = pairToTuple({ item1:"hello", item2:"world"});
+
+// 引用定义文件
+// <reference path="jquery.d.ts" />
+
+// 模板字符串(使用反引号的字符串)
+// 嵌入变量的模板字符串
+var name = 'Tyrone';
+var greeting = `Hi ${name}, how are you?`
+// 有多行内容的模板字符串
+var multiline = `This is an example
+of a multiline string`;
+
+```
+
+## 参考资料
+ * [TypeScript官网](http://www.typescriptlang.org/)
+ * [TypeScript语言规范说明书(pdf)](http://go.microsoft.com/fwlink/?LinkId=267238)
+ * [Anders Hejlsberg - TypeScript介绍](http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript)
+ * [GitHub源码](https://github.com/Microsoft/TypeScript)
+ * [Definitely Typed - 类型定义仓库](http://definitelytyped.org/)
diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown
new file mode 100644
index 00000000..553181d8
--- /dev/null
+++ b/zh-tw/python-tw.html.markdown
@@ -0,0 +1,727 @@
+---
+language: python
+contributors:
+ - ["Louie Dinh", "http://ldinh.ca"]
+ - ["Amin Bandali", "http://aminbandali.com"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+ - ["evuez", "http://github.com/evuez"]
+translators:
+ - ["Michael Yeh", "https://hinet60613.github.io/"]
+filename: learnpython-tw.py
+lang: zh-tw
+---
+
+Python是在1990年代早期由Guido Van Rossum創建的。它是現在最流行的程式語言之一。我愛上Python是因為他極為清晰的語法,甚至可以說它就是可執行的虛擬碼。
+
+非常歡迎各位給我們任何回饋! 你可以在[@louiedinh](http://twitter.com/louiedinh) 或 louiedinh [at] [google's email service]聯絡到我。
+
+註: 本篇文章適用的版本為Python 2.7,但大部分的Python 2.X版本應該都適用。 Python 2.7將會在2020年停止維護,因此建議您可以從Python 3開始學Python。
+Python 3.X可以看這篇[Python 3 教學 (英文)](http://learnxinyminutes.com/docs/python3/).
+
+讓程式碼同時支援Python 2.7和3.X是可以做到的,只要引入
+ [`__future__` imports](https://docs.python.org/2/library/__future__.html) 模組.
+ `__future__` 模組允許你撰寫可以在Python 2上執行的Python 3程式碼,詳細訊息請參考Python 3 教學。
+
+```python
+
+# 單行註解從井字號開始
+
+""" 多行字串可以用三個雙引號
+ 包住,不過通常這種寫法會
+ 被拿來當作多行註解
+"""
+
+####################################################
+## 1. 原始型別與運算元
+####################################################
+
+# 你可以使用數字
+3 # => 3
+
+# 還有四則運算
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+35 / 5 # => 7
+
+# 除法比較麻煩,除以整數時會自動捨去小數位。
+5 / 2 # => 2
+
+# 要做精確的除法,我們需要浮點數
+2.0 # 浮點數
+11.0 / 4.0 # => 2.75 精確多了!
+
+# 整數除法的無條件捨去對正數或負數都適用
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # 浮點數的整數也適用
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
+
+# 我們可以用除法模組(參考第六節:模組),讓
+# 單一斜線代表普通除法,而非無條件捨去
+from __future__ import division
+11/4 # => 2.75 ...普通除法
+11//4 # => 2 ...無條件捨去
+
+# 取餘數
+7 % 3 # => 1
+
+# 指數 (x的y次方)
+2**4 # => 16
+
+# 用括號改變運算順序
+(1 + 3) * 2 # => 8
+
+# 布林運算
+# 注意 "and" 和 "or" 要用小寫
+True and False #=> False
+False or True #=> True
+
+# 用整數與布林值做運算
+0 and 2 #=> 0
+-5 or 0 #=> -5
+0 == False #=> True
+2 == True #=> False
+1 == True #=> True
+
+# 用not取反向
+not True # => False
+not 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
+
+# 比較是可以串接的
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
+
+# 字串用單引號 ' 或雙引號 " 建立
+"This is a string."
+'This is also a string.'
+
+# 字串相加會被串接再一起
+"Hello " + "world!" # => "Hello world!"
+# 不用加號也可以做字串相加
+"Hello " "world!" # => "Hello world!"
+
+# ... 也可以做相乘
+"Hello" * 3 # => "HelloHelloHello"
+
+# 字串可以被視為字元的陣列
+"This is a string"[0] # => 'T'
+
+# 字串的格式化可以用百分之符號 %
+# 儘管在Python 3.1後這個功能被廢棄了,並且在
+# 之後的版本會被移除,但還是可以了解一下
+x = 'apple'
+y = 'lemon'
+z = "The items in the basket are %s and %s" % (x,y)
+
+# 新的格式化方式是使用format函式
+# 這個方式也是較為推薦的
+"{} is a {}".format("This", "placeholder")
+"{0} can be {1}".format("strings", "formatted")
+# 你也可以用關鍵字,如果你不想數你是要用第幾個變數的話
+"{name} wants to eat {food}".format(name="Bob", food="lasagna")
+
+# 無(None) 是一個物件
+None # => None
+
+# 不要用等於符號 "==" 對 無(None)做比較
+# 用 "is"
+"etc" is None # => False
+None is None # => True
+
+# 'is' 運算元是用來識別物件的。對原始型別來說或許沒什麼用,
+# 但對物件來說是很有用的。
+
+# 任何物件都可以被當作布林值使用
+# 以下的值會被視為是False :
+# - 無(None)
+# - 任何型別的零 (例如: 0, 0L, 0.0, 0j)
+# - 空序列 (例如: '', (), [])
+# - 空容器 (例如: {}, set())
+# - 自定義型別的實體,且滿足某些條件
+# 請參考文件: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
+#
+# 其餘的值都會被視為True (用bool()函式讓他們回傳布林值).
+bool(0) # => False
+bool("") # => False
+
+
+####################################################
+## 2. 變數與集合
+####################################################
+
+# Python的輸出很方便
+print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!
+
+# 從命令列獲得值也很方便
+input_string_var = raw_input("Enter some data: ") # 資料會被視為字串存進變數
+input_var = input("Enter some data: ") # 輸入的資料會被當作Python程式碼執行
+# 注意: 請謹慎使用input()函式
+# 註: 在Python 3中,input()已被棄用,raw_input()已被更名為input()
+
+# 使用變數前不需要先宣告
+some_var = 5 # 方便好用
+lower_case_with_underscores
+some_var # => 5
+
+# 對沒有被賦值的變數取值會造成例外
+# 請參考錯誤流程部分做例外處理
+some_other_var # 造成 NameError
+
+# if可以當判斷式使用
+# 相當於C語言中的二元判斷式
+"yahoo!" if 3 > 2 else 2 # => "yahoo!"
+
+# 串列型態可以儲存集合
+li = []
+# 你可以預先填好串列內容
+other_li = [4, 5, 6]
+
+# 用append()在串列後新增東西
+li.append(1) # 此時 li 內容為 [1]
+li.append(2) # 此時 li 內容為 [1, 2]
+li.append(4) # 此時 li 內容為 [1, 2, 4]
+li.append(3) # 此時 li 內容為 [1, 2, 4, 3]
+# 用pop()移除串列尾端的元素
+li.pop() # => 3 ,此時 li 內容為 [1, 2, 4]
+# 然後再塞回去
+li.append(3) # 此時 li 內容再次為 [1, 2, 4, 3]
+
+# 你可以像存取陣列一樣的存取串列
+li[0] # => 1
+# 用等號 = 給串列中特定索引的元素賦值
+li[0] = 42
+li[0] # => 42
+li[0] = 1 # 註: 將其設定回原本的值
+# 用 -1 索引值查看串列最後一個元素
+li[-1] # => 3
+
+# 存取超過範圍會產生IndexError
+li[4] # Raises an IndexError
+
+# 你可以用切片語法來存取特定範圍的值
+# (相當於數學中的左閉右開區間,即包含最左邊界,但不包含右邊界)
+li[1:3] # => [2, 4]
+# 略過開頭元素
+li[2:] # => [4, 3]
+# 略過結尾元素
+li[:3] # => [1, 2, 4]
+# 每隔兩個元素取值
+li[::2] # =>[1, 4]
+# 串列反轉
+li[::-1] # => [3, 4, 2, 1]
+# 你可以任意組合來達到你想要的效果
+# li[開始索引:結束索引:間隔]
+
+# 用 "del" 從串列中移除任意元素
+del li[2] # 現在 li 內容為 [1, 2, 3]
+
+# 你可以做串列相加
+li + other_li # => [1, 2, 3, 4, 5, 6]
+# 註: li 及 other_li 沒有被更動
+
+# 用 "extend()" 做串列串接
+li.extend(other_li) # 現在 li 內容為 [1, 2, 3, 4, 5, 6]
+
+# 移除特定值的第一次出現
+li.remove(2) # 現在 li 內容為 [1, 3, 4, 5, 6]
+li.remove(2) # 2 不在串列中,造成 ValueError
+
+# 在特定位置插入值
+li.insert(1, 2) # 現在 li 內容再次回復為 [1, 2, 3, 4, 5, 6]
+
+# 取得特定值在串列中第一次出現的位置
+li.index(2) # => 1
+li.index(7) # 7 不在串列中,造成 ValueError
+
+# 用 "in" 檢查特定值是否出現在串列中
+1 in li # => True
+
+# 用 "len()" 取得串列長度
+len(li) # => 6
+
+
+# 元組(Tuple,以下仍用原文)類似於串列,但是它是不可改變的
+tup = (1, 2, 3)
+tup[0] # => 1
+tup[0] = 3 # 產生TypeError
+
+# 能對串列做的東西都可以對tuple做
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# 你可以把tuple拆開並分別將值存入不同變數
+a, b, c = (1, 2, 3) # a 現在是 1, b 現在是 2, c 現在是 3
+d, e, f = 4, 5, 6 # 也可以不寫括號
+# 如果不加括號,預設會產生tuple
+g = 4, 5, 6 # => (4, 5, 6)
+# 你看,交換兩個值很簡單吧
+e, d = d, e # 此時 d 的值為 5 且 e 的值為 4
+
+
+# 字典(Dictionary)用來儲存映射關係
+empty_dict = {}
+# 你可以對字典做初始化
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# 用 [] 取值
+filled_dict["one"] # => 1
+
+# 用 "keys()" 將所有的Key輸出到一個List中
+filled_dict.keys() # => ["three", "two", "one"]
+# 註: 字典裡key的排序是不固定的
+# 你的執行結果可能與上面不同
+# 譯註: 只能保證所有的key都有出現,但不保證順序
+
+# 用 "values()" 將所有的Value輸出到一個List中
+filled_dict.values() # => [3, 2, 1]
+# 註: 同上,不保證順序
+
+# 用 "in" 來檢查指定的Key是否在字典中
+"one" in filled_dict # => True
+1 in filled_dict # => False
+
+# 查詢不存在的Key會造成KeyError
+filled_dict["four"] # KeyError
+
+# 用 "get()" 來避免KeyError
+# 若指定的Key不存在的話會得到None
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
+# "get()" 函式支援預設值,當找不到指定的值時,會回傳指定的預設值
+filled_dict.get("one", 4) # => 1
+filled_dict.get("four", 4) # => 4
+# 注意此時 filled_dict.get("four") 仍然為 None
+# (get()此時並沒有產生出任何的值)
+
+# 像操作list一樣,對指定的Key賦值
+filled_dict["four"] = 4 # 此時 filled_dict["four"] => 4
+
+# "setdefault()" 只在指定的Key不存在時才會將值插入dictionary
+filled_dict.setdefault("five", 5) # filled_dict["five"] 被指定為 5
+filled_dict.setdefault("five", 6) # filled_dict["five"] 仍保持 5
+
+
+# 集合(Set)被用來儲存...集合。
+# 跟串列(List)有點像,但集合內不會有重複的元素
+empty_set = set()
+# 初始化 "set()" 並給定一些值
+some_set = set([1, 2, 2, 3, 4]) # 現在 some_set 為 set([1, 2, 3, 4]),注意重複的元素只有一個會被存入
+
+# 一樣,不保證順序,就算真的有照順序排也只是你運氣好
+another_set = set([4, 3, 2, 2, 1]) # another_set 現在為 set([1, 2, 3, 4])
+
+# 從 Python 2.7 開始,可以使用大括號 {} 來宣告Set
+filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
+
+# 加入更多元素進入Set
+filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
+
+# 用 & 來對兩個集合取交集
+other_set = {3, 4, 5, 6}
+filled_set & other_set # => {3, 4, 5}
+
+# 用 | 來對兩個集合取聯集
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+
+# 用 - 來將第二個集合內有的元素移出第一個集合
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+
+# 用 ^ 來對兩個集合取差集
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# 檢查左邊是否為右邊的母集
+{1, 2} >= {1, 2, 3} # => False
+
+# 檢查左邊是否為右邊的子集
+{1, 2} <= {1, 2, 3} # => True
+
+# 用 in 來檢查某元素是否存在於集合內
+2 in filled_set # => True
+10 in filled_set # => False
+
+
+####################################################
+## 3. 控制流程
+####################################################
+
+# 首先,先宣告一個變數
+some_var = 5
+
+# 這邊是 if 判斷式。注意,縮排對Python是很重要的。
+# 下面應該會印出 "some_var is smaller than 10"
+if some_var > 10:
+ print "some_var is totally bigger than 10."
+elif some_var < 10: # elif 可有可無
+ print "some_var is smaller than 10."
+else: # else 也可有可無
+ print "some_var is indeed 10."
+
+
+"""
+For 迴圈會遞迴整的List
+下面的程式碼會輸出:
+ dog is a mammal
+ cat is a mammal
+ mouse is a mammal
+"""
+for animal in ["dog", "cat", "mouse"]:
+ # 你可以用{0}來組合0出格式化字串 (見上面.)
+ print "{0} is a mammal".format(animal)
+
+"""
+"range(number)" 回傳一個包含從0到給定值的數字List,
+下面的程式碼會輸出:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print i
+
+"""
+"range(lower, upper)" 回傳一個包含從給定的下限
+到給定的上限的數字List
+下面的程式碼會輸出:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print i
+
+"""
+While迴圈會執行到條件不成立為止
+下面的程式碼會輸出:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print x
+ x += 1 # x = x + 1 的簡寫
+
+# 用try/except處理例外
+
+# 適用Python 2.6及以上版本
+try:
+ # 用 "raise" 來發起例外
+ raise IndexError("This is an index error")
+except IndexError as e:
+ pass # 毫無反應,就只是個什麼都沒做的pass。通常這邊會讓你做對例外的處理
+except (TypeError, NameError):
+ pass # 有需要的話,多種例外可以一起處理
+else: # else 可有可無,但必須寫在所有的except後
+ print "All good!" # 只有在try的時候沒有產生任何except才會被執行
+finally: # 不管什麼情況下一定會被執行
+ print "We can clean up resources here"
+
+# 除了try/finally以外,你可以用 with 來簡單的處理清理動作
+with open("myfile.txt") as f:
+ for line in f:
+ print line
+
+####################################################
+## 4. 函式
+####################################################
+
+# 用 "def" 來建立新函式
+def add(x, y):
+ print "x is {0} and y is {1}".format(x, y)
+ return x + y # 用 "return" 來回傳值
+
+# 用參數來呼叫函式
+add(5, 6) # => 輸出 "x is 5 and y is 6" 並回傳 11
+
+# 你也可以寫上參數名稱來呼叫函式
+add(y=6, x=5) # 這種狀況下,兩個參數的順序並不影響執行
+
+
+# 你可以定義接受多個變數的函式,用*來表示參數tuple
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) # => (1, 2, 3)
+
+
+# 你可以定義接受多個變數的函式,用**來表示參數dictionary
+def keyword_args(**kwargs):
+ return kwargs
+
+# 呼叫看看會發生什麼事吧
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+
+
+# 如果你想要,你也可以兩個同時用
+def all_the_args(*args, **kwargs):
+ print args
+ print kwargs
+"""
+all_the_args(1, 2, a=3, b=4) prints:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# 呼叫函式時,你可以做反向的操作
+# 用 * 將變數展開為順序排序的變數
+# 用 ** 將變數展開為Keyword排序的變數
+args = (1, 2, 3, 4)
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # 等同於 foo(1, 2, 3, 4)
+all_the_args(**kwargs) # 等同於 foo(a=3, b=4)
+all_the_args(*args, **kwargs) # 等同於 foo(1, 2, 3, 4, a=3, b=4)
+
+# 你可以把args跟kwargs傳到下一個函式內
+# 分別用 * 跟 ** 將它展開就可以了
+def pass_all_the_args(*args, **kwargs):
+ all_the_args(*args, **kwargs)
+ print varargs(*args)
+ print keyword_args(**kwargs)
+
+# 函式範圍
+x = 5
+
+def set_x(num):
+ # 區域變數 x 和全域變數 x 不是同一個東西
+ x = num # => 43
+ print x # => 43
+
+def set_global_x(num):
+ global x
+ print x # => 5
+ x = num # 全域變數 x 在set_global_x(6)被設定為 6
+ print x # => 6
+
+set_x(43)
+set_global_x(6)
+
+# Python有一級函式
+def create_adder(x):
+ def adder(y):
+ return x + y
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) # => 13
+
+# 也有匿名函式
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
+
+# 還有內建的高階函式
+map(add_10, [1, 2, 3]) # => [11, 12, 13]
+map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
+
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+
+# 我們可以用List列表的方式對map和filter等高階函式做更有趣的應用
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
+
+
+####################################################
+## 5. 類別
+####################################################
+
+# 我們可以由object繼承出一個新的類別
+class Human(object):
+
+ # 類別的參數,被所有這個類別的實體所共用
+ species = "H. sapiens"
+
+ # 基礎建構函式,當class被實體化的時候會被呼叫
+ # 注意前後的雙底線
+ # 代表此物件或屬性雖然在使用者控制的命名空間內,但是被python使用
+ def __init__(self, name):
+ # 將函式引入的參數 name 指定給實體的 name 參數
+ self.name = name
+
+ # 初始化屬性
+ self.age = 0
+
+
+ # 一個實體的方法(method)。 所有的method都以self為第一個參數
+ def say(self, msg):
+ return "{0}: {1}".format(self.name, msg)
+
+ # 一個類別方法會被所有的實體所共用
+ # 他們會以類別為第一參數的方式被呼叫
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # 靜態方法
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+ # 屬性就像是用getter取值一樣
+ # 它將方法 age() 轉為同名的、只能讀取的屬性
+ @property
+ def age(self):
+ return self._age
+
+ # 這樣寫的話可以讓屬性被寫入新的值
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # 這樣寫的話允許屬性被刪除
+ @age.deleter
+ def age(self):
+ del self._age
+
+
+# 將類別實體化
+i = Human(name="Ian")
+print i.say("hi") # prints out "Ian: hi"
+
+j = Human("Joel")
+print j.say("hello") # prints out "Joel: hello"
+
+# 呼叫類別方法
+i.get_species() # => "H. sapiens"
+
+# 更改共用的屬性
+Human.species = "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
+
+# 呼叫靜態方法
+Human.grunt() # => "*grunt*"
+
+# 更新屬性
+i.age = 42
+
+# 取得屬性
+i.age # => 42
+
+# 移除屬性
+del i.age
+i.age # => raises an AttributeError
+
+
+####################################################
+## 6. 模組
+####################################################
+
+# 你可以引入模組來做使用
+import math
+print math.sqrt(16) # => 4
+ # math.sqrt()為取根號
+
+# 你可以只從模組取出特定幾個函式
+from math import ceil, floor
+print ceil(3.7) # => 4.0
+print floor(3.7) # => 3.0
+
+# 你可以將所有的函式從模組中引入
+# 注意:不建議這麼做
+from math import *
+
+# 你可以用 as 簡寫模組名稱
+import math as m
+math.sqrt(16) == m.sqrt(16) # => True
+# 你也可以測試函示是否相等
+from math import sqrt
+math.sqrt == m.sqrt == sqrt # => True
+
+# Python的模組就只是一般的Python檔。
+# 你可以自己的模組自己寫、自己的模組自己引入
+# 模組的名稱和檔案名稱一樣
+
+# 你可以用dir()來查看有哪些可用函式和屬性
+import math
+dir(math)
+
+
+####################################################
+## 7. 進階
+####################################################
+
+# 產生器(Generator)可以讓你寫更懶惰的程式碼
+def double_numbers(iterable):
+ for i in iterable:
+ yield i + i
+
+# 產生器可以讓你即時的產生值
+# 不是全部產生完之後再一次回傳,產生器會在每一個遞迴時
+# 產生值。 這也意味著大於15的值不會在double_numbers中產生。
+# 這邊,xrange()做的事情和range()一樣
+# 建立一個 1-900000000 的List會消耗很多時間和記憶體空間
+# xrange() 建立一個產生器物件,而不是如range()建立整個List
+# 我們用底線來避免可能和python的關鍵字重複的名稱
+xrange_ = xrange(1, 900000000)
+
+# 下面的程式碼會把所有的值乘以兩倍,直到出現大於30的值
+for i in double_numbers(xrange_):
+ print i
+ if i >= 30:
+ break
+
+
+# 裝飾子
+# 在這個範例中,beg會綁在say上
+# Beg會呼叫say。 如果say_please為True的話,它會更改回傳的訊息
+from functools import wraps
+
+
+def beg(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, "Please! I am poor :(")
+ return msg
+
+ return wrapper
+
+
+@beg
+def say(say_please=False):
+ msg = "Can you buy me a beer?"
+ return msg, say_please
+
+
+print say() # Can you buy me a beer?
+print say(say_please=True) # Can you buy me a beer? Please! I am poor :(
+```
+
+## 準備好學更多了嗎?
+
+### 線上免費資源
+
+* [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/)
+* [The Official Docs](http://docs.python.org/2/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/2/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+
+### 或買本書?
+
+* [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)