summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-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--bash.html.markdown15
-rw-r--r--bf.html.markdown (renamed from brainfuck.html.markdown)2
-rw-r--r--c++.html.markdown210
-rw-r--r--c.html.markdown166
-rw-r--r--chapel.html.markdown8
-rw-r--r--clojure.html.markdown25
-rw-r--r--coffeescript.html.markdown32
-rw-r--r--coldfusion.html.markdown328
-rw-r--r--common-lisp.html.markdown13
-rw-r--r--cs-cz/markdown.html.markdown260
-rw-r--r--cs-cz/python3.html.markdown8
-rw-r--r--cs-cz/sass.html.markdown439
-rw-r--r--csharp.html.markdown92
-rw-r--r--css.html.markdown269
-rw-r--r--d.html.markdown101
-rw-r--r--dart.html.markdown2
-rw-r--r--de-de/bash-de.html.markdown223
-rw-r--r--de-de/csharp-de.html.markdown2
-rw-r--r--de-de/git-de.html.markdown30
-rw-r--r--de-de/go-de.html.markdown71
-rw-r--r--de-de/haskell-de.html.markdown101
-rw-r--r--de-de/latex-de.html.markdown246
-rw-r--r--de-de/markdown-de.html.markdown10
-rw-r--r--de-de/ruby-de.html.markdown613
-rw-r--r--de-de/ruby-ecosystem-de.html.markdown149
-rw-r--r--de-de/scala-de.html.markdown840
-rw-r--r--de-de/yaml-de.html.markdown4
-rw-r--r--edn.html.markdown108
-rw-r--r--el-gr/css-gr.html.markdown243
-rw-r--r--el-gr/racket-gr.html.markdown72
-rw-r--r--el-gr/scala-gr.html.markdown34
-rw-r--r--elisp.html.markdown3
-rw-r--r--elixir.html.markdown15
-rw-r--r--elm.html.markdown367
-rw-r--r--erlang.html.markdown2
-rw-r--r--es-es/amd-es.html.markdown214
-rw-r--r--es-es/bf-es.html.markdown (renamed from es-es/brainfuck-es.html.markdown)20
-rw-r--r--es-es/git-es.html.markdown14
-rw-r--r--es-es/javascript-es.html.markdown24
-rw-r--r--es-es/json-es.html.markdown16
-rw-r--r--es-es/latex-es.html.markdown213
-rw-r--r--es-es/markdown-es.html.markdown16
-rw-r--r--es-es/php-es.html.markdown825
-rw-r--r--es-es/python3-es.html.markdown8
-rw-r--r--es-es/ruby-es.html.markdown253
-rw-r--r--es-es/swift-es.html.markdown596
-rw-r--r--es-es/tmux-es.html.markdown253
-rw-r--r--es-es/visualbasic-es.html.markdown286
-rw-r--r--fa-ir/bf-fa.html.markdown (renamed from fa-ir/brainfuck.html.markdown)2
-rw-r--r--fa-ir/javascript-fa.html.markdown (renamed from fa-ir/javascript.html.markdown)0
-rw-r--r--factor.html.markdown182
-rw-r--r--fi-fi/go-fi.html.markdown441
-rw-r--r--fi-fi/markdown-fi.html.markdown259
-rw-r--r--fi-fi/ruby-fi.html.markdown608
-rw-r--r--forth.html.markdown4
-rw-r--r--fr-fr/HTML-fr.html.markdown116
-rw-r--r--fr-fr/bf-fr.html.markdown (renamed from fr-fr/brainfuck-fr.html.markdown)2
-rw-r--r--fr-fr/clojure-fr.html.markdown29
-rw-r--r--fr-fr/css-fr.html.markdown8
-rw-r--r--fr-fr/d.html.markdown264
-rw-r--r--fr-fr/go-fr.html.markdown2
-rw-r--r--fr-fr/haml-fr.html.markdown157
-rw-r--r--fr-fr/hy-fr.html.markdown180
-rw-r--r--fr-fr/javascript-fr.html.markdown264
-rw-r--r--fr-fr/livescript-fr.html.markdown2
-rw-r--r--fr-fr/make-fr.html.markdown268
-rw-r--r--fr-fr/markdown.html.markdown12
-rw-r--r--fr-fr/objective-c-fr.html.markdown5
-rw-r--r--fr-fr/perl-fr.html.markdown174
-rw-r--r--fr-fr/python-fr.html.markdown3
-rw-r--r--fr-fr/python3-fr.html.markdown723
-rw-r--r--fr-fr/scala.html.markdown9
-rw-r--r--fr-fr/typescript-fr.html.markdown58
-rw-r--r--fr-fr/wolfram-fr.html.markdown167
-rw-r--r--fr-fr/yaml-fr.html.markdown92
-rw-r--r--fsharp.html.markdown86
-rw-r--r--git.html.markdown59
-rw-r--r--go.html.markdown14
-rw-r--r--groovy.html.markdown6
-rw-r--r--haml.html.markdown25
-rw-r--r--haskell.html.markdown47
-rw-r--r--hu-hu/coffeescript-hu.html.markdown107
-rw-r--r--hu-hu/go-hu.html.markdown (renamed from hu-hu/go.html.markdown)0
-rw-r--r--hu-hu/ruby-hu.html.markdown555
-rw-r--r--hu-hu/yaml-hu.html.markdown147
-rw-r--r--hy.html.markdown2
-rw-r--r--id-id/php-id.html.markdown848
-rw-r--r--id-id/xml-id.html.markdown81
-rw-r--r--inform7.html.markdown195
-rw-r--r--it-it/bash-it.html.markdown72
-rw-r--r--it-it/bf-it.html.markdown92
-rw-r--r--it-it/brainfuck-it.html.markdown101
-rw-r--r--it-it/c++-it.html.markdown211
-rw-r--r--it-it/coffeescript-it.html.markdown32
-rw-r--r--it-it/elixir-it.html.markdown10
-rw-r--r--it-it/java-it.html.markdown170
-rw-r--r--it-it/json-it.html.markdown25
-rw-r--r--it-it/python-it.html.markdown647
-rw-r--r--ja-jp/bash-jp.html.markdown4
-rw-r--r--ja-jp/php-jp.html.markdown777
-rw-r--r--java.html.markdown376
-rw-r--r--javascript.html.markdown130
-rw-r--r--json.html.markdown38
-rw-r--r--julia.html.markdown54
-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--latex.html.markdown247
-rw-r--r--less.html.markdown379
-rw-r--r--lt-lt/json-lt.html.markdown81
-rw-r--r--lua.html.markdown2
-rw-r--r--make.html.markdown8
-rw-r--r--markdown.html.markdown233
-rw-r--r--matlab.html.markdown86
-rw-r--r--ms-my/coffeescript-my.html.markdown105
-rw-r--r--ms-my/javascript-my.html.markdown588
-rw-r--r--ms-my/json-my.html.markdown102
-rw-r--r--nim.html.markdown4
-rw-r--r--nl-nl/bf.html.markdown (renamed from nl-nl/brainfuck-nl.html.markdown)4
-rw-r--r--nl-nl/xml-nl.html.markdown134
-rw-r--r--nl-nl/yaml-nl.html.markdown139
-rw-r--r--objective-c.html.markdown63
-rw-r--r--ocaml.html.markdown8
-rw-r--r--perl.html.markdown147
-rw-r--r--perl6.html.markdown138
-rw-r--r--php.html.markdown178
-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/python-pl.html.markdown161
-rw-r--r--pl-pl/ruby-pl.html.markdown593
-rw-r--r--pl-pl/xml-pl.html.markdown137
-rw-r--r--powershell.html.markdown330
-rw-r--r--pt-br/amd.html.markdown218
-rw-r--r--pt-br/asymptotic-notation-pt.html.markdown159
-rw-r--r--pt-br/bf.html.markdown (renamed from pt-br/brainfuck-pt.html.markdown)2
-rw-r--r--pt-br/c-pt.html.markdown90
-rw-r--r--pt-br/clojure-macros-pt.html.markdown154
-rw-r--r--pt-br/css-pt.html.markdown257
-rw-r--r--pt-br/hy-pt.html.markdown2
-rw-r--r--pt-br/java-pt.html.markdown213
-rw-r--r--pt-br/javascript-pt.html.markdown9
-rw-r--r--pt-br/json-pt.html.markdown17
-rw-r--r--pt-br/markdown-pt.html.markdown8
-rw-r--r--pt-br/matlab-pt.html.markdown540
-rw-r--r--pt-br/ruby-pt.html.markdown12
-rw-r--r--pt-br/sass-pt.html.markdown452
-rw-r--r--pt-br/tmux-pt.html.markdown254
-rw-r--r--pt-pt/bf.html.markdown (renamed from pt-pt/brainfuck-pt.html.markdown)0
-rw-r--r--pt-pt/scala-pt.html.markdown651
-rw-r--r--purescript.html.markdown131
-rw-r--r--python.html.markdown118
-rw-r--r--python3.html.markdown327
-rw-r--r--pythonstatcomp.html.markdown244
-rw-r--r--r.html.markdown107
-rw-r--r--ro-ro/bf-ro.html.markdown90
-rw-r--r--ro-ro/latex.html.markdown258
-rw-r--r--ru-ru/.directory4
-rw-r--r--ru-ru/bash-ru.html.markdown9
-rw-r--r--ru-ru/bf.html.markdown (renamed from ru-ru/brainfuck-ru.html.markdown)2
-rw-r--r--ru-ru/clojure-ru.html.markdown2
-rw-r--r--ru-ru/css-ru.html.markdown250
-rw-r--r--ru-ru/d-ru.html.markdown754
-rw-r--r--ru-ru/erlang-ru.html.markdown2
-rw-r--r--ru-ru/java-ru.html.markdown48
-rw-r--r--ru-ru/javascript-ru.html.markdown2
-rw-r--r--ru-ru/markdown-ru.html.markdown8
-rw-r--r--ru-ru/objective-c-ru.html.markdown29
-rw-r--r--ru-ru/perl-ru.html.markdown195
-rw-r--r--ru-ru/php-ru.html.markdown116
-rw-r--r--ru-ru/python-ru.html.markdown7
-rw-r--r--ru-ru/python3-ru.html.markdown2
-rw-r--r--ru-ru/tmux-ru.html.markdown252
-rw-r--r--ru-ru/typescript-ru.html.markdown173
-rw-r--r--ruby.html.markdown80
-rw-r--r--rust.html.markdown4
-rw-r--r--sass.html.markdown444
-rw-r--r--scala.html.markdown70
-rw-r--r--self.html.markdown2
-rw-r--r--sk-sk/LearnGit-sk.txt208
-rw-r--r--sk-sk/git.html.markdown523
-rw-r--r--sk-sk/latex.html.markdown.tex227
-rw-r--r--sk-sk/learn-latex-sk.tex209
-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.markdown185
-rw-r--r--ta_in/css-ta.html.markdown254
-rw-r--r--ta_in/javascript-ta.html.markdown594
-rw-r--r--ta_in/json-ta.html.markdown86
-rw-r--r--ta_in/xml-ta.html.markdown145
-rw-r--r--tmux.html.markdown10
-rw-r--r--tr-tr/bf-tr.html.markdown (renamed from tr-tr/brainfuck-tr.html.markdown)4
-rw-r--r--tr-tr/c-tr.html.markdown34
-rw-r--r--tr-tr/markdown-tr.html.markdown8
-rw-r--r--tr-tr/objective-c-tr.html.markdown2
-rw-r--r--tr-tr/python3-tr.html.markdown2
-rw-r--r--tr-tr/swift-tr.html.markdown13
-rw-r--r--typescript.html.markdown60
-rw-r--r--uk-ua/bash-ua.html.markdown296
-rw-r--r--uk-ua/java-ua.html.markdown783
-rw-r--r--uk-ua/javascript-ua.html.markdown495
-rw-r--r--uk-ua/json-ua.html.markdown67
-rw-r--r--vi-vn/json-vi.html.markdown76
-rw-r--r--vi-vn/objective-c-vi.html.markdown2
-rw-r--r--vi-vn/ruby-vi.html.markdown549
-rw-r--r--visualbasic.html.markdown123
-rw-r--r--whip.html.markdown17
-rw-r--r--wolfram.html.markdown137
-rw-r--r--xml.html.markdown159
-rw-r--r--yaml.html.markdown33
-rw-r--r--zfs.html.markdown400
-rw-r--r--zh-cn/bf-cn.html.markdown (renamed from zh-cn/brainfuck-cn.html.markdown)2
-rw-r--r--zh-cn/haskell-cn.html.markdown6
-rw-r--r--zh-cn/java-cn.html.markdown6
-rw-r--r--zh-cn/lua-cn.html.markdown31
-rw-r--r--zh-cn/markdown-cn.html.markdown8
-rw-r--r--zh-cn/python3-cn.html.markdown2
-rw-r--r--zh-cn/scala-cn.html.markdown2
-rw-r--r--zh-cn/swift-cn.html.markdown131
-rw-r--r--zh-cn/tmux-cn.html.markdown253
-rw-r--r--zh-tw/python-tw.html.markdown727
225 files changed, 33653 insertions, 2141 deletions
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 774797d5..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 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/bash.html.markdown b/bash.html.markdown
index 191f916a..bd2d5984 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -83,24 +83,33 @@ 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
echo "Your name is your username"
fi
+# NOTE: if $Name is empty, bash sees the above condition as:
+if [ != $USER ]
+# which is invalid syntax
+# so the "safe" way to use potentially empty variables in bash is:
+if [ "$Name" != $USER ] ...
+# which, when $Name is empty, is seen by bash as:
+if [ "" != $USER ] ...
+# which works as expected
+
# There is also conditional execution
echo "Always executed" || echo "Only executed if first command fails"
echo "Always executed" && echo "Only executed if first command does NOT fail"
# To use && and || with if statements, you need multiple pairs of square brackets:
-if [ $Name == "Steve" ] && [ $Age -eq 15 ]
+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" ]
+if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ]
then
echo "This will run if $Name is Daniya OR Zach."
fi
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 6f4d0562..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");
}
}
@@ -310,6 +310,70 @@ basic_string(basic_string&& other);
// constructor that "salvages" parts of that temporary string. You will see this
// concept referred to as "move semantics".
+/////////////////////
+// Enums
+/////////////////////
+
+// Enums are a way to assign a value to a constant most commonly used for
+// easier visualization and reading of code
+enum ECarTypes
+{
+ Sedan,
+ Hatchback,
+ SUV,
+ Wagon
+};
+
+ECarTypes GetPreferredCarType()
+{
+ return ECarTypes::Hatchback;
+}
+
+// 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
+// the desired type and their respective constants
+enum ECarTypes : uint8_t
+{
+ Sedan, // 0
+ Hatchback, // 1
+ SUV = 254, // 254
+ Hybrid // 255
+};
+
+void WriteByteToFile(uint8_t InputValue)
+{
+ // Serialize the InputValue to a file
+}
+
+void WritePreferredCarTypeToFile(ECarTypes InputCarType)
+{
+ // The enum is implicitly converted to a uint8_t due to its declared enum type
+ WriteByteToFile(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
+// won't be implicitly converted
+enum class ECarTypes : uint8_t
+{
+ Sedan, // 0
+ Hatchback, // 1
+ SUV = 254, // 254
+ Hybrid // 255
+};
+
+void WriteByteToFile(uint8_t InputValue)
+{
+ // Serialize the InputValue to a file
+}
+
+void WritePreferredCarTypeToFile(ECarTypes InputCarType)
+{
+ // Won't compile even though ECarTypes is a uint8_t due to the enum
+ // being declared as an "enum class"!
+ WriteByteToFile(InputCarType);
+}
+
//////////////////////////////////////////
// Classes and object-oriented programming
//////////////////////////////////////////
@@ -404,6 +468,8 @@ 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
+// without a public or protected method for doing so
class OwnedDog : public Dog {
void setOwner(const std::string& dogsOwner);
@@ -735,6 +801,94 @@ void doSomethingWithAFile(const std::string& filename)
// all automatically destroy their contents when they fall out of scope.
// - Mutexes using lock_guard and unique_lock
+// containers with object keys of non-primitive values (custom classes) require
+// compare function in the object itself or as a function pointer. Primitives
+// have default comparators, but you can override it.
+class Foo {
+public:
+ int j;
+ Foo(int a) : j(a) {}
+};
+struct compareFunction {
+ bool operator()(const Foo& a, const Foo& b) const {
+ return a.j < b.j;
+ }
+};
+//this isn't allowed (although it can vary depending on compiler)
+//std::map<Foo, int> fooMap;
+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
@@ -786,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 db2ac930..d4ff529d 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -6,7 +6,8 @@ contributors:
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
- ["Jakub Trzebiatowski", "http://cbs.stgn.pl"]
- ["Marco Scannadinari", "https://marcoms.github.io"]
-
+ - ["Zachary Ferguson", "https://github.io/zfergus2"]
+ - ["himanshu", "https://github.com/himanshu81494"]
---
Ah, C. Still **the** language of modern high-performance computing.
@@ -27,6 +28,7 @@ Multi-line comments don't nest /* Be careful */ // comment ends on this line...
*/ // ...not this one!
// Constants: #define <keyword>
+// Constants are written in all-caps out of convention, not requirement
#define DAYS_IN_YEAR 365
// Enumeration constants are also ways to declare constants.
@@ -52,10 +54,21 @@ int function_2(void);
// Must declare a 'function prototype' before main() when functions occur after
// your main() function.
int add_two_ints(int x1, int x2); // function prototype
+// although `int add_two_ints(int, int);` is also valid (no need to name the args),
+// it is recommended to name arguments in the prototype as well for easier inspection
// Your program's entry point is a function called
// main with an integer return type.
int main(void) {
+ // your program
+}
+
+// The command line arguments used to run your program are also passed to main
+// argc being the number of arguments - your program's name counts as 1
+// argv is an array of character arrays - containing the arguments themselves
+// argv[0] = name of your program, argv[1] = first argument, etc.
+int main (int argc, char** argv)
+{
// print output using printf, for "print formatted"
// %d is an integer, \n is a newline
printf("%d\n", 0); // => Prints 0
@@ -64,6 +77,9 @@ int main(void) {
// 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
+
// ints are usually 4 bytes
int x_int = 0;
@@ -132,15 +148,10 @@ int main(void) {
printf("Enter the array size: "); // ask the user for an array size
int size;
fscanf(stdin, "%d", &size);
- char buf[size];
- fgets(buf, sizeof buf, stdin);
-
- // strtoul parses a string to an unsigned integer
- size_t size2 = strtoul(buf, NULL, 10);
- int var_length_array[size2]; // declare the VLA
+ int var_length_array[size]; // declare the VLA
printf("sizeof array = %zu\n", sizeof var_length_array);
- // A possible outcome of this program may be:
+ // Example:
// > Enter the array size: 10
// > sizeof array = 40
@@ -221,14 +232,14 @@ int main(void) {
0 || 1; // => 1 (Logical or)
0 || 0; // => 0
- // Conditional expression ( ? : )
+ // Conditional ternary expression ( ? : )
int e = 5;
int f = 10;
int z;
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;
@@ -291,6 +302,8 @@ int main(void) {
for (i = 0; i <= 5; i++) {
; // use semicolon to act as the body (null statement)
}
+ // Or
+ for (i = 0; i <= 5; i++);
// branching with multiple choices: switch()
switch (a) {
@@ -300,12 +313,40 @@ int main(void) {
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;
}
+ /*
+ using "goto" in C
+ */
+ typedef enum { false, true } bool;
+ // for C don't have bool as data type :(
+ bool disaster = false;
+ int i, j;
+ for(i=0;i<100;++i)
+ for(j=0;j<100;++j)
+ {
+ if((i + j) >= 150)
+ disaster = true;
+ if(disaster)
+ goto error;
+ }
+ error :
+ printf("Error occured at i = %d & j = %d.\n", i, j);
+ /*
+ https://ideone.com/GuPhd6
+ this will print out "Error occured at i = 52 & j = 99."
+ */
+
///////////////////////////////////////
// Typecasting
@@ -406,6 +447,17 @@ int main(void) {
*(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
+ // to keep track of the number of elements (size) of an array. See the
+ // functions section for more info.
+ int size = 10;
+ int *my_arr = malloc(sizeof(int) * size);
+ // Add an element to the array
+ my_arr = realloc(my_arr, ++size);
+ my_arr[10] = 5;
+
// Dereferencing memory that you haven't allocated gives
// "unpredictable results" - the program is said to invoke "undefined behavior"
printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? It may even crash.
@@ -445,7 +497,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.
@@ -472,6 +524,46 @@ char c[] = "This is a test.";
str_reverse(c);
printf("%s\n", c); // => ".tset a si sihT"
*/
+/*
+as we can return only one variable
+to change values of more than one variables we use call by reference
+*/
+void swapTwoNumbers(int *a, int *b)
+{
+ int temp = *a;
+ *a = *b;
+ *b = temp;
+}
+/*
+int first = 10;
+int second = 20;
+printf("first: %d\nsecond: %d\n", first, second);
+swapTwoNumbers(&first, &second);
+printf("first: %d\nsecond: %d\n", first, second);
+// values will be swapped
+*/
+
+/*
+With regards to arrays, they will always be passed to functions
+as pointers. Even if you statically allocate an array like `arr[10]`,
+it still gets passed as a pointer to the first element in any function calls.
+Again, there is no standard way to get the size of a dynamically allocated
+array in C.
+*/
+// Size must be passed!
+// Otherwise, this function has no way of knowing how big the array is.
+void printIntArray(int *arr, int size) {
+ int i;
+ for (i = 0; i < size; i++) {
+ printf("arr[%d] is: %d\n", i, arr[i]);
+ }
+}
+/*
+int my_arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+int size = 10;
+printIntArray(my_arr, size);
+// will print "arr[0] is: 1" etc
+*/
// if referring to external variables outside function, must use extern keyword.
int i = 0;
@@ -628,8 +720,56 @@ typedef void (*my_fnp_type)(char *);
// , | left to right //
//---------------------------------------------------//
-```
+/******************************* 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 separating them into
+separate files.
+
+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.
+*/
+
+/* A safe guard to prevent the header from being defined too many times. This */
+/* happens in the case of circle dependency, the contents of the header is */
+/* already defined. */
+#ifndef EXAMPLE_H /* if EXAMPLE_H is not yet defined. */
+#define EXAMPLE_H /* Define the macro EXAMPLE_H. */
+
+/* Other headers can be included in headers and therefore transitively */
+/* included into files that include this header. */
+#include <string.h>
+
+/* Like c source files macros can be defined in headers and used in files */
+/* that include this header file. */
+#define EXAMPLE_NAME "Dennis Ritchie"
+/* Function macros can also be defined. */
+#define ADD(a, b) (a + b)
+
+/* Structs and typedefs can be used for consistency between files. */
+typedef struct node
+{
+ int val;
+ struct node *next;
+} Node;
+
+/* So can enumerations. */
+enum traffic_light_state {GREEN, YELLOW, RED};
+/* Function prototypes can also be defined here for use in multiple files, */
+/* but it is bad practice to define the function in the header. Definitions */
+/* should instead be put in a c file. */
+Node createLinkedList(int *vals, int len);
+
+/* Beyond the above elements, other definitions should be left to a c source */
+/* 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. */
+
+```
## Further Reading
Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language)
diff --git a/chapel.html.markdown b/chapel.html.markdown
index e20be998..9c1daf40 100644
--- a/chapel.html.markdown
+++ b/chapel.html.markdown
@@ -629,11 +629,11 @@ for (i, j) in zip( toThisArray.domain, -100..#5 ){
}
writeln( toThisArray );
-// This is all very important in undestanding why the statement
+// This is all very important in understanding why the statement
// var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j;
// exhibits a runtime error.
// Even though the domain of the array and the loop-expression are
-// the same size, the body of the expression can be though of as an iterator.
+// the same size, the body of the expression can be thought of as an iterator.
// Because iterators can yield nothing, that iterator yields a different number
// of things than the domain of the array or loop, which is not allowed.
@@ -914,7 +914,7 @@ proc main(){
[ val in myBigArray ] val = 1 / val; // Parallel operation
// Atomic variables, common to many languages, are ones whose operations
- // occur uninterupted. Multiple threads can both modify atomic variables
+ // occur uninterrupted. Multiple threads can both modify atomic variables
// and can know that their values are safe.
// Chapel atomic variables can be of type bool, int, uint, and real.
var uranium: atomic int;
@@ -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/clojure.html.markdown b/clojure.html.markdown
index a125d18f..58e835c9 100644
--- a/clojure.html.markdown
+++ b/clojure.html.markdown
@@ -264,6 +264,31 @@ keymap ; => {:a 1, :b 2, :c 3}
(print "Saying hello to " name)
(str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel")
+
+; Use the threading macros (-> and ->>) to express transformations of
+; data more clearly.
+
+; The "Thread-first" macro (->) inserts into each form the result of
+; the previous, as the first argument (second item)
+(->
+ {:a 1 :b 2}
+ (assoc :c 3) ;=> (assoc {:a 1 :b 2} :c 3)
+ (dissoc :b)) ;=> (dissoc (assoc {:a 1 :b 2} :c 3) :b)
+
+; This expression could be written as:
+; (dissoc (assoc {:a 1 :b 2} :c 3) :b)
+; and evaluates to {:a 1 :c 3}
+
+; The double arrow does the same thing, but inserts the result of
+; each line at the *end* of the form. This is useful for collection
+; operations in particular:
+(->>
+ (range 10)
+ (map inc) ;=> (map inc (range 10)
+ (filter odd?) ;=> (filter odd? (map inc (range 10))
+ (into [])) ;=> (into [] (filter odd? (map inc (range 10)))
+ ; Result: [1 3 5 7 9]
+
; Modules
;;;;;;;;;;;;;;;
diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown
index 85a5f81f..89a29677 100644
--- a/coffeescript.html.markdown
+++ b/coffeescript.html.markdown
@@ -7,7 +7,7 @@ filename: coffeescript.coffee
---
CoffeeScript is a little language that compiles one-to-one into the equivalent JavaScript, and there is no interpretation at runtime.
-As one of the succeeders of JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript codes working well in every JavaScript runtime.
+As one of the successors to JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript code, which works well in every JavaScript runtime.
See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript.
@@ -54,19 +54,19 @@ math =
square: square
cube: (x) -> x * square x
#=> var math = {
-# "root": Math.sqrt,
-# "square": square,
-# "cube": function(x) { return x * square(x); }
-#}
+# "root": Math.sqrt,
+# "square": square,
+# "cube": function(x) { return x * square(x); }
+# };
# Splats:
race = (winner, runners...) ->
print winner, runners
#=>race = function() {
-# var runners, winner;
-# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
-# return print(winner, runners);
-#};
+# var runners, winner;
+# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
+# return print(winner, runners);
+# };
# Existence:
alert "I knew it!" if elvis?
@@ -75,14 +75,14 @@ alert "I knew it!" if elvis?
# Array comprehensions:
cubes = (math.cube num for num in list)
#=>cubes = (function() {
-# var _i, _len, _results;
-# _results = [];
+# var _i, _len, _results;
+# _results = [];
# for (_i = 0, _len = list.length; _i < _len; _i++) {
-# num = list[_i];
-# _results.push(math.cube(num));
-# }
-# return _results;
-# })();
+# num = list[_i];
+# _results.push(math.cube(num));
+# }
+# return _results;
+# })();
foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown
new file mode 100644
index 00000000..482612fe
--- /dev/null
+++ b/coldfusion.html.markdown
@@ -0,0 +1,328 @@
+---
+language: coldfusion
+filename: learncoldfusion.cfm
+contributors:
+ - ["Wayne Boka", "http://wboka.github.io"]
+ - ["Kevin Morris", "https://twitter.com/kevinmorris"]
+---
+
+ColdFusion is a scripting language for web development.
+[Read more here.](http://www.adobe.com/products/coldfusion-family.html)
+
+### CFML
+_**C**old**F**usion **M**arkup **L**anguage_
+ColdFusion started as a tag-based language. Almost all functionality is available using tags.
+
+```html
+<em>HTML tags have been provided for output readability</em>
+
+<!--- Comments start with "<!---" and end with "--->" --->
+<!---
+ Comments can
+ also
+ span
+ multiple lines
+--->
+
+<!--- CFML tags have a similar format to HTML tags. --->
+<h1>Simple Variables</h1>
+<!--- Variable Declaration: Variables are loosely typed, similar to javascript --->
+<p>Set <b>myVariable</b> to "myValue"</p>
+<cfset myVariable = "myValue" />
+<p>Set <b>myNumber</b> to 3.14</p>
+<cfset myNumber = 3.14 />
+
+<!--- Displaying simple data --->
+<!--- Use <cfoutput> for simple values such as strings, numbers, and expressions --->
+<p>Display <b>myVariable</b>: <cfoutput>#myVariable#</cfoutput></p><!--- myValue --->
+<p>Display <b>myNumber</b>: <cfoutput>#myNumber#</cfoutput></p><!--- 3.14 --->
+
+<hr />
+
+<h1>Complex Variables</h1>
+<!--- Declaring complex variables --->
+<!--- Declaring an array of 1 dimension: literal or bracket notation --->
+<p>Set <b>myArray1</b> to an array of 1 dimension using literal or bracket notation</p>
+<cfset myArray1 = [] />
+<!--- Declaring an array of 1 dimension: function notation --->
+<p>Set <b>myArray2</b> to an array of 1 dimension using function notation</p>
+<cfset myArray2 = ArrayNew(1) />
+
+<!--- Outputting complex variables --->
+<p>Contents of <b>myArray1</b></p>
+<cfdump var="#myArray1#" /> <!--- An empty array object --->
+<p>Contents of <b>myArray2</b></p>
+<cfdump var="#myArray2#" /> <!--- An empty array object --->
+
+<!--- Operators --->
+<!--- Arithmetic --->
+<h1>Operators</h1>
+<h2>Arithmetic</h2>
+<p>1 + 1 = <cfoutput>#1 + 1#</cfoutput></p>
+<p>10 - 7 = <cfoutput>#10 - 7#<br /></cfoutput></p>
+<p>15 * 10 = <cfoutput>#15 * 10#<br /></cfoutput></p>
+<p>100 / 5 = <cfoutput>#100 / 5#<br /></cfoutput></p>
+<p>120 % 5 = <cfoutput>#120 % 5#<br /></cfoutput></p>
+<p>120 mod 5 = <cfoutput>#120 mod 5#<br /></cfoutput></p>
+
+<hr />
+
+<!--- Comparison --->
+<h2>Comparison</h2>
+<h3>Standard Notation</h3>
+<p>Is 1 eq 1? <cfoutput>#1 eq 1#</cfoutput></p>
+<p>Is 15 neq 1? <cfoutput>#15 neq 1#</cfoutput></p>
+<p>Is 10 gt 8? <cfoutput>#10 gt 8#</cfoutput></p>
+<p>Is 1 lt 2? <cfoutput>#1 lt 2#</cfoutput></p>
+<p>Is 10 gte 5? <cfoutput>#10 gte 5#</cfoutput></p>
+<p>Is 1 lte 5? <cfoutput>#1 lte 5#</cfoutput></p>
+
+<h3>Alternative Notation</h3>
+<p>Is 1 == 1? <cfoutput>#1 eq 1#</cfoutput></p>
+<p>Is 15 != 1? <cfoutput>#15 neq 1#</cfoutput></p>
+<p>Is 10 > 8? <cfoutput>#10 gt 8#</cfoutput></p>
+<p>Is 1 < 2? <cfoutput>#1 lt 2#</cfoutput></p>
+<p>Is 10 >= 5? <cfoutput>#10 gte 5#</cfoutput></p>
+<p>Is 1 <= 5? <cfoutput>#1 lte 5#</cfoutput></p>
+
+<hr />
+
+<!--- Control Structures --->
+<h1>Control Structures</h1>
+
+<cfset myCondition = "Test" />
+
+<p>Condition to test for: "<cfoutput>#myCondition#</cfoutput>"</p>
+
+<cfif myCondition eq "Test">
+ <cfoutput>#myCondition#. We're testing.</cfoutput>
+<cfelseif myCondition eq "Production">
+ <cfoutput>#myCondition#. Proceed Carefully!!!</cfoutput>
+<cfelse>
+ myCondition is unknown
+</cfif>
+
+<hr />
+
+<!--- Loops --->
+<h1>Loops</h1>
+<h2>For Loop</h2>
+<cfloop from="0" to="10" index="i">
+ <p>Index equals <cfoutput>#i#</cfoutput></p>
+</cfloop>
+
+<h2>For Each Loop (Complex Variables)</h2>
+
+<p>Set <b>myArray3</b> to [5, 15, 99, 45, 100]</p>
+
+<cfset myArray3 = [5, 15, 99, 45, 100] />
+
+<cfloop array="#myArray3#" index="i">
+ <p>Index equals <cfoutput>#i#</cfoutput></p>
+</cfloop>
+
+<p>Set <b>myArray4</b> to ["Alpha", "Bravo", "Charlie", "Delta", "Echo"]</p>
+
+<cfset myArray4 = ["Alpha", "Bravo", "Charlie", "Delta", "Echo"] />
+
+<cfloop array="#myArray4#" index="s">
+ <p>Index equals <cfoutput>#s#</cfoutput></p>
+</cfloop>
+
+<h2>Switch Statement</h2>
+
+<p>Set <b>myArray5</b> to [5, 15, 99, 45, 100]</p>
+
+<cfset myArray5 = [5, 15, 99, 45, 100] />
+
+<cfloop array="#myArray5#" index="i">
+ <cfswitch expression="#i#">
+ <cfcase value="5,15,45" delimiters=",">
+ <p><cfoutput>#i#</cfoutput> is a multiple of 5.</p>
+ </cfcase>
+ <cfcase value="99">
+ <p><cfoutput>#i#</cfoutput> is ninety-nine.</p>
+ </cfcase>
+ <cfdefaultcase>
+ <p><cfoutput>#i#</cfoutput> is not 5, 15, 45, or 99.</p>
+ </cfdefaultcase>
+ </cfswitch>
+</cfloop>
+
+<hr />
+
+<h1>Converting types</h1>
+
+<style>
+ table.table th, table.table td {
+ border: 1px solid #000000;
+ padding: 2px;
+ }
+
+ table.table th {
+ background-color: #CCCCCC;
+ }
+</style>
+
+<table class="table" cellspacing="0">
+ <thead>
+ <tr>
+ <th>Value</th>
+ <th>As Boolean</th>
+ <th>As number</th>
+ <th>As date-time</th>
+ <th>As string</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <th>"Yes"</th>
+ <td>TRUE</td>
+ <td>1</td>
+ <td>Error</td>
+ <td>"Yes"</td>
+ </tr>
+ <tr>
+ <th>"No"</th>
+ <td>FALSE</td>
+ <td>0</td>
+ <td>Error</td>
+ <td>"No"</td>
+ </tr>
+ <tr>
+ <th>TRUE</th>
+ <td>TRUE</td>
+ <td>1</td>
+ <td>Error</td>
+ <td>"Yes"</td>
+ </tr>
+ <tr>
+ <th>FALSE</th>
+ <td>FALSE</td>
+ <td>0</td>
+ <td>Error</td>
+ <td>"No"</td>
+ </tr>
+ <tr>
+ <th>Number</th>
+ <td>True if Number is not 0; False otherwise.</td>
+ <td>Number</td>
+ <td>See &#34;Date-time values&#34; earlier in this chapter.</td>
+ <td>String representation of the number (for example, &#34;8&#34;).</td>
+ </tr>
+ <tr>
+ <th>String</th>
+ <td>If "Yes", True <br>If "No", False <br>If it can be converted to 0, False <br>If it can be converted to any other number, True</td>
+ <td>If it represents a number (for example, &#34;1,000&#34; or &#34;12.36E-12&#34;), it is converted to the corresponding number.</td>
+ <td>If it represents a date-time (see next column), it is converted to the numeric value of the corresponding date-time object. <br>If it is an ODBC date, time, or timestamp (for example &#34;{ts &#39;2001-06-14 11:30:13&#39;}&#34;, or if it is expressed in a standard U.S. date or time format, including the use of full or abbreviated month names, it is converted to the corresponding date-time value. <br>Days of the week or unusual punctuation result in an error. <br>Dashes, forward-slashes, and spaces are generally allowed.</td>
+ <td>String</td>
+ </tr>
+ <tr>
+ <th>Date</th>
+ <td>Error</td>
+ <td>The numeric value of the date-time object.</td>
+ <td>Date</td>
+ <td>An ODBC timestamp.</td>
+ </tr>
+ </tbody>
+</table>
+
+<hr />
+
+<h1>Components</h1>
+
+<em>Code for reference (Functions must return something to support IE)</em>
+
+<cfcomponent>
+ <cfset this.hello = "Hello" />
+ <cfset this.world = "world" />
+
+ <cffunction name="sayHello">
+ <cfreturn this.hello & ", " & this.world & "!" />
+ </cffunction>
+
+ <cffunction name="setHello">
+ <cfargument name="newHello" type="string" required="true" />
+
+ <cfset this.hello = arguments.newHello />
+
+ <cfreturn true />
+ </cffunction>
+
+ <cffunction name="setWorld">
+ <cfargument name="newWorld" type="string" required="true" />
+
+ <cfset this.world = arguments.newWorld />
+
+ <cfreturn true />
+ </cffunction>
+
+ <cffunction name="getHello">
+ <cfreturn this.hello />
+ </cffunction>
+
+ <cffunction name="getWorld">
+ <cfreturn this.world />
+ </cffunction>
+</cfcomponent>
+
+<cfset this.hello = "Hello" />
+<cfset this.world = "world" />
+
+<cffunction name="sayHello">
+ <cfreturn this.hello & ", " & this.world & "!" />
+</cffunction>
+
+<cffunction name="setHello">
+ <cfargument name="newHello" type="string" required="true" />
+
+ <cfset this.hello = arguments.newHello />
+
+ <cfreturn true />
+</cffunction>
+
+<cffunction name="setWorld">
+ <cfargument name="newWorld" type="string" required="true" />
+
+ <cfset this.world = arguments.newWorld />
+
+ <cfreturn true />
+</cffunction>
+
+<cffunction name="getHello">
+ <cfreturn this.hello />
+</cffunction>
+
+<cffunction name="getWorld">
+ <cfreturn this.world />
+</cffunction>
+
+
+<b>sayHello()</b>
+<cfoutput><p>#sayHello()#</p></cfoutput>
+<b>getHello()</b>
+<cfoutput><p>#getHello()#</p></cfoutput>
+<b>getWorld()</b>
+<cfoutput><p>#getWorld()#</p></cfoutput>
+<b>setHello("Hola")</b>
+<cfoutput><p>#setHello("Hola")#</p></cfoutput>
+<b>setWorld("mundo")</b>
+<cfoutput><p>#setWorld("mundo")#</p></cfoutput>
+<b>sayHello()</b>
+<cfoutput><p>#sayHello()#</p></cfoutput>
+<b>getHello()</b>
+<cfoutput><p>#getHello()#</p></cfoutput>
+<b>getWorld()</b>
+<cfoutput><p>#getWorld()#</p></cfoutput>
+```
+
+### CFScript
+_**C**old**F**usion **S**cript_
+In recent years, the ColdFusion language has added script syntax to mirror tag functionality. When using an up-to-date CF server, almost all functionality is available using scrypt syntax.
+
+## Further Reading
+
+The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples.
+
+1. [Coldfusion Reference From Adobe](https://helpx.adobe.com/coldfusion/cfml-reference/topics.html)
+2. [Open Source Documentation](http://cfdocs.org/)
diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown
index 63183c1e..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
@@ -614,9 +614,16 @@ nil ; for false - and the empty list
## Further Reading
-[Keep moving on to the Practical Common Lisp book.](http://www.gigamonkeys.com/book/)
+* [Keep moving on to the Practical Common Lisp book.](http://www.gigamonkeys.com/book/)
+* [A Gentle Introduction to...](https://www.cs.cmu.edu/~dst/LispBook/book.pdf)
+## Extra Info
+
+* [CLiki](http://www.cliki.net/)
+* [common-lisp.net](https://common-lisp.net/)
+* [Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl)
+
## Credits.
Lots of thanks to the Scheme people for rolling up a great starting
diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown
new file mode 100644
index 00000000..568e4343
--- /dev/null
+++ b/cs-cz/markdown.html.markdown
@@ -0,0 +1,260 @@
+---
+language: markdown
+lang: cs-cz
+contributors:
+ - ["Dan Turkel", "http://danturkel.com/"]
+translators:
+ - ["Michal Martinek", "https://github.com/MichalMartinek"]
+filename: markdown-cz.md
+lang: cs-cz
+---
+
+Markdown byl vytvořen Johnem Gruberem v roce 2004. Je zamýšlen jako lehce čitelná
+a psatelná syntaxe, která je jednoduše převeditelná do HTML (a dnes i do mnoha
+dalších formátů)
+
+```markdown
+<!-- Markdown je nadstavba nad HTML, takže jakýkoliv kód HTML je validní
+Markdown, to znamená, že můžeme používat HTML elementy, třeba jako komentář, a
+nebudou ovlivněny parserem Markdownu. Avšak, pokud vytvoříte HTML element v
+Markdownu, tak nemůžete používat syntaxi Markdownu uvnitř tohoto elementu. -->
+
+<!-- Markdown se také mírně liší v jednotlivých interpretacích parseru. Tento
+návod vás bude upozorňovat, které vlastnosti jsou obecné a které specifické pro
+konkrétní parser. -->
+
+<!-- Nadpisy -->
+<!-- Můžete vytvořit HTML elementy <h1> až <h6> jednoduše tak, že text předsadíte
+počtem křížků (#), podle toho jaké úrovně to má být nadpis -->
+# Toto je <h1>
+## Toto je <h2>
+### Toto je <h3>
+#### Toto je <h4>
+##### Toto je <h5>
+###### Toto je <h6>
+
+<!-- Markdown obsahuje taky dvě další cesty, jak udělat h1 a h2 -->
+Toto je h1
+==========
+
+Toto je h2
+----------
+
+<!-- Jednoduché stylování textu -->
+<!-- Pomocí markdownu můžete text jednoduše označit jako kurzívu či tučný -->
+
+*Tento text je kurzívou;*
+_Stejně jako tento._
+
+**Tento text je tučně**
+__Stejně jako tento.__
+
+***Tento text je obojí***
+**_Jako tento!_**
+*__A tento!__*
+
+<!-- Ve verzi Markdownu od GitHubu, máme k dispozici taky prošktrnutí: -->
+
+~~Tento text je prošktrnutý.~~
+
+<!-- Odstavce jsou jedna nebo více řádek textu, oddělených jednou nebo více prázdnými řádky. -->
+
+Toto je odstavec. Píši odstavec, není to zábava?
+
+Teď jsem v odstavci 2.
+Jsem pořád v odstavci 2!
+
+
+Toto je odstavec 3.
+
+<!-- Chtěli jste někdy vložit znak <br /> tag? Můžete napsat na konec odstavce
+dvě nebo více mezer a potom začít nový odstavec. -->
+
+Tento odstavec končí dvěma mezerami.
+
+Nad tímto odstavcem je <br />!
+
+<!-- Blokové citace se dělají jednoduše pomocí znaku >. -->
+
+> Toto je bloková citace. Můžete dokonce
+> manuálně rozdělit řádky, a před každý vložit >, nebo nechat vaše řádky jakkoliv dlouhé, ať se zarovnají sami.
+> Nedělá to rozdíl, dokud začínáte vždy znakem >.
+
+> Můžu použít více než jednu
+>> odsazení?
+> Jak je to úhledné, že?
+
+<!-- Seznamy -->
+<!-- Nečíslovaný seznam můžete jednoduše udělat pomocí hvězdiček, plusů, nebo
+ pomlček -->
+
+* Položka
+* Položka
+* Jinná položka
+
+nebo
+
++ Položka
++ Položka
++ Další položka
+
+nebo
+
+- Položka
+- Položka
+- Další položka
+
+<!-- Číslovaný seznam se dělají pomocí čísla a . -->
+
+1. Položka jedna
+2. Položka dvě
+3. Položka tři
+
+<!-- Nemusíte dokonce psát čísla správně a markdown je zobrazi správně,
+ ale nemusí to být vždy dobrý nápad -->
+
+1. Položka jedna
+1. Položka dvě
+1. Položka tři
+<!-- (Toto zobrazí to samě, jako příklad nadtím.) -->
+
+<!-- Můžete také tvořit podseznamy -->
+
+1. Položka jedna
+2. Položka dvě
+3. Položka tři
+ * Podpoložka
+ * Podpoložka
+4. Položka čtyři
+
+<!-- Existují i zašktávací seznamy. Toto vytvoří HTML checkboxy. -->
+
+Boxy níže bez 'x' jsou nezašktrnuté checkboxy.
+- [ ] První úkol
+- [ ] Druhý úkol
+Tento box bude zašktrnutý
+- [x] Tento úkol byl dokončen
+
+<!-- Bloky ködu -->
+<!-- Můžete označit kód bloku (který používá <code> element) odsazením pomocí 4
+ mezer, nebo tabu -->
+
+ Toto je kód
+ Stejně jako toto
+
+<!-- Můžete dokonce přidat další 4 mezery nebo tab pro další odsazení -->
+
+ moje_pole.each do |i|
+ puts i
+ end
+
+<!-- Kód na řádku může být označen pomocí zpětných apostrofů ` -->
+
+Jan nevědel, jak se dělá `go_to()` funkce!
+
+<!-- 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
+ puts "Ahoj světe!"
+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
+ jazyka. -->
+
+<!-- Horizontální čára (<hr />) -->
+<!-- Horizontální čára se jednoduše přidá pomocí 3 nebo více hvězdiček nebo pomlček
+s nebo bez mezer. -->
+
+***
+---
+- - -
+****************
+
+<!-- Odkazy -->
+<!-- Jedna z nejlepších věcí na Markdownu je, jak jednoduše se dělají odkazy.
+Dejte text, který chcete zobrazit, do [] následovaný url v závorkách () a je to. -->
+
+[Klikni na mě!](http://test.com/)
+
+<!-- Můžete také přidat jméno linku pomocí uvozovek -->
+
+[Klikni na mě!](http://test.com/ "Odkaz na Test.com")
+
+<!-- Relativní cesty fungují taky -->
+
+[Jdi na hudbu](/hudba/).
+
+<!-- Markdown taktéž podporuje reference odkazů. -->
+
+[Klikni na tento odkaz][link1] pro více informací!
+[Taky zkontrolujte tento odkaz][neco], když chcete.
+
+[link1]: http://test.com/ "Cool!"
+[neco]: http://neco.czz/ "Dobře!"
+
+<!-- Titulek může být v apostrofech nebo závorkách, nebo vyjmutý úplně. Reference
+ může být kdekoliv ve vašem dokumentu a identifikátor může být jakýkoliv, dokud
+ je unikátní.-->
+
+<!-- Také existuje "implicitní pojmenování", které použije text jako id -->
+
+[Toto][] je odkaz..
+
+[toto]: http://totojelink.cz/
+
+<!-- Ale toto není zrovna běžné užívané. -->
+
+<!-- Obrázky -->
+<!-- Obrázky se dělají stejně jako odkazy, ale s vykřičníkem na začátku -->
+
+![Toto je atribut alt pro obrázek](http://imgur.com/myimage.jpg "Nepovinný titulek")
+
+<!-- Reference fungují, jak bychom čekali-->
+
+![Toto je atribut alt][mujobrazek]
+
+[mujobrazek]: relativni/cesta/obrazek.jpg "a toto by byl titulek"
+
+<!-- Ostatní -->
+<!-- Automatické odkazy -->
+
+<http://stranka.cz/> je stejná jako
+[http://stranka.cz/](http://stranka.cz/)
+
+<!-- Automatické odkazy pro emaily-->
+
+<jmeno@prijmeni.cz>
+
+<!-- Escapování znaků -->
+
+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áš 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ě,
+ ale když je opravdu chcete: -->
+
+| Sloupec1 | Sloupec2 | Sloupec3 |
+| :----------- | :------: | ------------: |
+| Vlevo zarovn.| Na střed | Vpravo zarovn.|
+| blah | blah | blah |
+
+<!-- nebo, to jde i taky: -->
+
+Sloupec 1 | Sloupec2 | Sloupec3
+:-- | :-: | --:
+Ohh toto je tak ošklivé | radši to | nedělejte
+
+<!-- Konec -->
+
+```
+
+Pro více informací, prozkoumejte oficiální článek o syntaxi od Johna Grubera
+ [zde](http://daringfireball.net/projects/markdown/syntax) a skvělý tahák od Adama Pritcharda [zde](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown
index 11c8a654..b498046a 100644
--- a/cs-cz/python3.html.markdown
+++ b/cs-cz/python3.html.markdown
@@ -48,7 +48,7 @@ Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit sta
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
-# Pokud použiteje desetinné číslo, výsledek je jím také
+# Pokud použijete desetinné číslo, výsledek je jím také
3 * 2.0 # => 6.0
# Modulo
@@ -420,7 +420,7 @@ next(iterator) # Vyhodí StopIteration
## 4. Funkce
####################################################
-# Pro vytvoření nové funkce použijte def
+# Pro vytvoření nové funkce použijte klíčové slovo def
def secist(x, y):
print("x je {} a y je {}".format(x, y))
return x + y # Hodnoty se vrací pomocí return
@@ -520,7 +520,7 @@ class Clovek(object):
# podtržítka na začátku a na konci značí, že se jedná o atribut nebo
# objekt využívaný Pythonem ke speciálním účelům, ale můžete sami
# definovat jeho chování. Metody jako __init__, __str__, __repr__
- # a další se nazývají "magické metody". Nikdy nepoužívejte toto
+ # a další se nazývají "magické metody". Nikdy nepoužívejte toto
# speciální pojmenování pro běžné metody.
def __init__(self, jmeno):
# Přiřazení parametru do atributu instance jmeno
@@ -566,7 +566,7 @@ Clovek.odkaslej_si() # => "*ehm*"
# Lze importovat moduly
import math
-print(math.sqrt(16)) # => 4
+print(math.sqrt(16.0)) # => 4
# Lze také importovat pouze vybrané funkce z modulu
from math import ceil, floor
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 02650038..7d7f4340 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -6,6 +6,8 @@ contributors:
- ["Melvyn Laïly", "http://x2a.yt"]
- ["Shaun McCarthy", "http://www.shaunmccarthy.com"]
- ["Wouter Van Schandevijl", "http://github.com/laoujin"]
+ - ["Jo Pearce", "http://github.com/jdpearce"]
+ - ["Chris Zimmerman", "https://github.com/chriszimmerman"]
filename: LearnCSharp.cs
---
@@ -43,8 +45,8 @@ using System.Data.Entity;
// Using this code from another source file: using Learning.CSharp;
namespace Learning.CSharp
{
- // Each .cs file should at least contain a class with the same name as the file
- // you're allowed to do otherwise, but shouldn't for sanity.
+ // Each .cs file should at least contain a class with the same name as the file.
+ // You're allowed to do otherwise, but shouldn't for sanity.
public class LearnCSharp
{
// BASIC SYNTAX - skip to INTERESTING FEATURES if you have used Java or C++ before
@@ -159,7 +161,7 @@ on a new line! ""Wow!"", the masses cried";
// List<datatype> <var name> = new List<datatype>();
List<int> intList = new List<int>();
List<string> stringList = new List<string>();
- List<int> z = new List<int> { 9000, 1000, 1337 }; // intialize
+ List<int> z = new List<int> { 9000, 1000, 1337 }; // initialize
// The <> are for generics - Check out the cool stuff section
// Lists don't default to a value;
@@ -393,6 +395,7 @@ on a new line! ""Wow!"", the masses cried";
ref int maxCount, // Pass by reference
out int count)
{
+ //the argument passed in as 'count' will hold the value of 15 outside of this function
count = 15; // out param must be assigned before control leaves the method
}
@@ -418,12 +421,48 @@ 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)
+ public static IEnumerable<int> YieldCounter(int limit = 10)
+ {
+ for (var i = 0; i < limit; i++)
+ yield return i;
+ }
+
+ // which you would call like this :
+ public static void PrintYieldCounterToConsole()
+ {
+ foreach (var counter in YieldCounter())
+ Console.WriteLine(counter);
+ }
+
+ // you can use more than one "yield return" in a method
+ public static IEnumerable<int> ManyYieldCounter()
+ {
+ yield return 0;
+ yield return 1;
+ 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)
+ {
+ for (var i = 0; i < limit; i++)
+ {
+ if (i > limit/2) yield break;
+ yield return i;
+ }
+ }
public static void OtherInterestingFeatures()
{
// OPTIONAL PARAMETERS
MethodSignatures(3, 1, 3, "Some", "Extra", "Strings");
- MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones
+ MethodSignatures(3, another: 3); // explicitly set a parameter, skipping optional ones
// BY REF AND OUT PARAMETERS
int maxCount = 0, count; // ref params must have value
@@ -443,6 +482,9 @@ 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
// 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";
@@ -588,7 +630,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());
@@ -610,7 +652,7 @@ on a new line! ""Wow!"", the masses cried";
{
return _cadence;
}
- set // set - define a method to set a proprety
+ set // set - define a method to set a property
{
_cadence = value; // Value is the value passed in to the setter
}
@@ -750,7 +792,7 @@ on a new line! ""Wow!"", the masses cried";
// 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
+ // could do bicycle[0] which returns "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" };
@@ -761,7 +803,7 @@ on a new line! ""Wow!"", the masses cried";
}
set {
- return passengers[i] = value;
+ passengers[i] = value;
}
}
@@ -837,7 +879,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
+ // 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
class MountainBike : Bicycle, IJumpable, IBreakable
{
int damage = 0;
@@ -870,13 +913,42 @@ 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 static void A1()
+ {
+ Console.WriteLine("Method A1 in class A");
+ }
+ }
+
+ // A2.cs
+ public partial class A
+ {
+ public static void A2()
+ {
+ Console.WriteLine("Method A2 in class A");
+ }
+ }
+
+ // Program using the partial class "A"
+ public class Program
+ {
+ static void Main()
+ {
+ A.A1();
+ A.A2();
+ }
+ }
} // End Namespace
```
## Topics Not Covered
* Attributes
- * async/await, yield, pragma directives
+ * async/await, pragma directives
* Web Development
* ASP.NET MVC & WebApi (new)
* ASP.NET Web Forms (old)
diff --git a/css.html.markdown b/css.html.markdown
index 811767e6..8ee4f4b9 100644
--- a/css.html.markdown
+++ b/css.html.markdown
@@ -5,25 +5,21 @@ contributors:
- ["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"]
filename: learncss.css
---
-In the early days of the web there were no visual elements, just pure text. But with the
-further development of browsers, fully visual web pages also became common.
-CSS is the standard language that exists to keep the separation between
-the content (HTML) and the look-and-feel of web pages.
+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**.
-In short, what CSS does is to provide a syntax that enables you to target
-different elements on an HTML page and assign different visual properties to them.
+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.
-Like any other languages, CSS has many versions. Here we focus on CSS2.0,
-which is not the most recent version, but is the most widely supported and compatible version.
+This guide has been written with CSS 2 in mind, which is extended by the new features of CSS 3.
-**NOTE:** Because the outcome of CSS consists of visual effects, in order to
-learn it, you need try everything in a
-CSS playground like [dabblet](http://dabblet.com/).
+**NOTE:** Because CSS produces visual results, in order to learn it, you need to try everything in a CSS playground like [dabblet](http://dabblet.com/).
The main focus of this article is on the syntax and some general tips.
+## Syntax
```css
/* comments appear inside slash-asterisk, just like this line!
@@ -33,219 +29,226 @@ The main focus of this article is on the syntax and some general tips.
## SELECTORS
#################### */
-/* Generally, the primary statement in CSS is very simple */
+/* the selector is used to target an element on a page. */
selector { property: value; /* more properties...*/ }
-/* the selector is used to target an element on page.
-
-You can target all elements on the page using asterisk! */
-* { color:red; }
-
/*
-Given an element like this on the page:
+Here is an example element:
-<div class='some-class class2' id='someId' attr='value' otherAttr='en-us foo bar' />
+<div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' />
*/
-/* you can target it by its name */
-.some-class { }
+/* You can target it using one of its CSS classes */
+.class1 { }
-/* or by both classes! */
-.some-class.class2 { }
+/* or both classes! */
+.class1.class2 { }
-/* or by its element name */
+/* or its name */
div { }
/* or its id */
-#someId { }
+#anID { }
-/* or by the fact that it has an attribute! */
+/* or using the fact that it has an attribute! */
[attr] { font-size:smaller; }
/* or that the attribute has a specific value */
[attr='value'] { font-size:smaller; }
-/* start with a value (CSS3) */
+/* starts with a value (CSS 3) */
[attr^='val'] { font-size:smaller; }
-/* or ends with (CSS3) */
+/* or ends with a value (CSS 3) */
[attr$='ue'] { font-size:smaller; }
-/* or select by one of the values from the whitespace separated list (CSS3) */
-[otherAttr~='foo'] { font-size:smaller; }
+/* or contains a value in a space-separated list */
+[otherAttr~='foo'] { }
+[otherAttr~='bar'] { }
-/* or value can be exactly “value” or can begin with “value” immediately followed by “-” (U+002D) */
+/* or contains a value in a dash-separated list, ie, "-" (U+002D) */
[otherAttr|='en'] { font-size:smaller; }
-/* and more importantly you can combine these together -- there shouldn't be
-any space between different parts because that makes it to have another
-meaning. */
+/* You can combine different selectors to create a more focused selector. Don't
+ put spaces between them. */
div.some-class[attr$='ue'] { }
-/* you can also select an element based on its parent. */
+/* You can select an element which is a child of another element */
+div.some-parent > .class-name { }
+
+/* or a descendant of another element. Children are the direct descendants of
+ their parent element, only one level down the tree. Descendants can be any
+ level down the tree. */
+div.some-parent .class-name { }
+
+/* Warning: the same selector without a space has another meaning.
+ Can you guess what? */
+div.some-parent.class-name { }
-/* an element which is direct child of an element (selected the same way) */
-div.some-parent > .class-name {}
+/* You may also select an element based on its adjacent sibling */
+.i-am-just-before + .this-element { }
-/* or any of its parents in the tree
- the following basically means any element that has class "class-name"
- and is child of a div with class name "some-parent" IN ANY DEPTH */
-div.some-parent .class-name {}
+/* or any sibling preceding it */
+.i-am-any-element-before ~ .this-element { }
-/* warning: the same selector without space has another meaning.
- can you say what? */
-div.some-parent.class-name {}
+/* There are some selectors called pseudo classes that can be used to select an
+ element only when it is in a particular state */
-/* you also might choose to select an element based on its direct
- previous sibling */
-.i-am-before + .this-element { }
+/* for example, when the cursor hovers over an element */
+selector:hover { }
-/* or any sibling before this */
-.i-am-any-before ~ .this-element {}
+/* or a link has been visited */
+selector:visited { }
-/* There are some pseudo classes that allows you to select an element
- based on its page behaviour (rather than page structure) */
+/* or hasn't been visited */
+selected:link { }
-/* for example for when an element is hovered */
-selector:hover {}
+/* or an element is in focus */
+selected:focus { }
-/* or a visited link */
-selected:visited {}
+/* any element that is the first child of its parent */
+selector:first-child {}
-/* or not visited link */
-selected:link {}
+/* any element that is the last child of its parent */
+selector:last-child {}
-/* or an input element which is focused */
-selected:focus {}
+/* 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 {}
+
+/* matches a virtual last child of the selected element */
+selector::after {}
+
+/* At appropriate places, an asterisk may be used as a wildcard to select every
+ element */
+* { } /* all elements */
+.parent * { } /* all descendants */
+.parent > * { } /* all children */
/* ####################
## PROPERTIES
#################### */
selector {
-
- /* Units */
- width: 50%; /* in percent */
- font-size: 2em; /* times current font-size */
- width: 200px; /* in pixels */
- font-size: 20pt; /* in points */
- width: 5cm; /* in centimeters */
- min-width: 50mm; /* in millimeters */
- max-width: 5in; /* in inches. max-(width|height) */
- height: 0.2vh; /* times vertical height of browser viewport (CSS3) */
- width: 0.4vw; /* times horizontal width of browser viewport (CSS3) */
- min-height: 0.1vmin; /* the lesser of vertical, horizontal dimensions of browser viewport (CSS3) */
- max-width: 0.3vmax; /* same as above, except the greater of the dimensions (CSS3) */
-
+
+ /* 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 */
+ font-size: 2rem; /* or the root element's font-size */
+ font-size: 2vw; /* multiples of 1% of the viewport's width (CSS 3) */
+ 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 */
- background-color: #F6E; /* in short hex */
- background-color: #F262E2; /* in long hex format */
- background-color: tomato; /* can be a named color */
- background-color: rgb(255, 255, 255); /* in rgb */
- background-color: rgb(10%, 20%, 50%); /* in rgb percent */
- background-color: rgba(255, 0, 0, 0.3); /* in semi-transparent rgb (CSS3) */
- background-color: transparent; /* see thru */
- background-color: hsl(0, 100%, 50%); /* hsl format (CSS3). */
- background-color: hsla(0, 100%, 50%, 0.3); /* Similar to RGBA, specify opacity at end (CSS3) */
-
-
- /* Images */
- background-image: url(/path-to-image/image.jpg); /* quotes inside url() optional */
-
+ color: #F6E; /* short hex format */
+ color: #FF66EE; /* long hex format */
+ color: tomato; /* a named color */
+ color: rgb(255, 255, 255); /* as rgb values */
+ color: rgb(10%, 20%, 50%); /* as rgb percentages */
+ color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 <= a <= 1 */
+ color: 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;
- font-family: "Courier New"; /* if name has space it appears in single or double quotes */
- font-family: "Courier New", Trebuchet, Arial, sans-serif; /* if first one was not found
- browser uses the second font, and so forth */
+ /* if the font family name has a space, it must be quoted */
+ font-family: "Courier New";
+ /* if the first one is not found, the browser uses the next, and so on */
+ font-family: "Courier New", Trebuchet, Arial, sans-serif;
}
-
```
## Usage
-Save any CSS you want in a file with extension `.css`.
+Save a CSS stylesheet with the extension `.css`.
```xml
-<!-- you need to include the css file in your page's <head>: -->
+<!-- You need to include the css file in your page's <head>. This is the
+ recommended method. Refer to http://stackoverflow.com/questions/8284365 -->
<link rel='stylesheet' type='text/css' href='path/to/style.css' />
-<!-- you can also include some CSS inline in your markup. However it is highly
-recommended to avoid this. -->
+<!-- You can also include some CSS inline in your markup. -->
<style>
a { color: purple; }
</style>
-<!-- or directly set CSS properties on the element.
-This has to be avoided as much as you can. -->
+<!-- Or directly set CSS properties on the element. -->
<div style="border: 1px solid red;">
</div>
-
```
-## Precedence
+## 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.
-As you noticed an element may be targetted by more than one selector.
-and may have a property set on it in more than one.
-In these cases, one of the rules takes precedence over others.
+This process is called cascading, hence the name Cascading Style Sheets.
Given the following CSS:
```css
-/*A*/
+/* A */
p.class1[attr='value']
-/*B*/
-p.class1 {}
+/* B */
+p.class1 { }
-/*C*/
-p.class2 {}
+/* C */
+p.class2 { }
-/*D*/
-p {}
+/* D */
+p { }
-/*E*/
+/* E */
p { property: value !important; }
-
```
and the following markup:
```xml
-<p style='/*F*/ property:value;' class='class1 class2' attr='value'>
-</p>
+<p style='/*F*/ property:value;' class='class1 class2' attr='value' />
```
-The precedence of style is as followed:
-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 to avoid this unless it is strictly necessary to use.
-* `F` is next, because it is inline style.
-* `A` is next, because it is more "specific" than anything else.
- more specific = more specifiers. here 3 specifiers: 1 tagname `p` +
- class name `class1` + 1 attribute `attr='value'`
-* `C` is next. although it has the same specificness as `B`
- but it appears last.
-* Then is `B`
-* and lastly is `D`.
+* `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`.
+* `B` is next.
+* `D` is the last one.
## Compatibility
-Most of the features in CSS2 (and gradually in CSS3) are compatible across
-all browsers and devices. But it's always vital to have in mind the compatibility
-of what you use in CSS with your target browsers.
+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.
-[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this.
+## Resources
-To run a quick compatibility check, [Can I Use...](http://caniuse.com) is a great resource.
+* [CanIUse](http://caniuse.com) (Detailed compatibility info)
+* [Dabblet](http://dabblet.com/) (CSS playground)
+* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) (Tutorials and reference)
+* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) (Reference)
## Further Reading
-* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS)
-* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/)
* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
+* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/)
* [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)
-* [SCSS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing
+* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing
+* [CSS-Tricks](https://css-tricks.com)
diff --git a/d.html.markdown b/d.html.markdown
index ba24b60f..edb3bff5 100644
--- a/d.html.markdown
+++ b/d.html.markdown
@@ -23,8 +23,10 @@ about [D](http://dlang.org/). The D programming language is a modern, general-pu
multi-paradigm language with support for everything from low-level features to
expressive high-level abstractions.
-D is actively developed by Walter Bright and Andrei Alexandrescu, two super smart, really cool
-dudes. With all that out of the way, let's look at some examples!
+D is actively developed by a large group of super-smart people and is spearheaded by
+[Walter Bright](https://en.wikipedia.org/wiki/Walter_Bright) and
+[Andrei Alexandrescu](https://en.wikipedia.org/wiki/Andrei_Alexandrescu).
+With all that out of the way, let's look at some examples!
```c
import std.stdio;
@@ -36,9 +38,10 @@ void main() {
writeln(i);
}
- auto n = 1; // use auto for type inferred variables
+ // 'auto' can be used for inferring types.
+ auto n = 1;
- // Numeric literals can use _ as a digit seperator for clarity
+ // Numeric literals can use '_' as a digit separator for clarity.
while(n < 10_000) {
n += n;
}
@@ -47,16 +50,18 @@ void main() {
n -= (n / 2);
} while(n > 0);
- // For and while are nice, but in D-land we prefer foreach
- // The .. creates a continuous range, excluding the end
- foreach(i; 1..1_000_000) {
+ // For and while are nice, but in D-land we prefer 'foreach' loops.
+ // The '..' creates a continuous range, including the first value
+ // but excluding the last.
+ foreach(n; 1..1_000_000) {
if(n % 2 == 0)
- writeln(i);
+ writeln(n);
}
- foreach_reverse(i; 1..int.max) {
+ // There's also 'foreach_reverse' when you want to loop backwards.
+ foreach_reverse(n; 1..int.max) {
if(n % 2 == 1) {
- writeln(i);
+ writeln(n);
} else {
writeln("No!");
}
@@ -65,20 +70,22 @@ void main() {
```
We can define new types with `struct`, `class`, `union`, and `enum`. Structs and unions
-are passed to functions by value (i.e. copied) and classes are passed by reference. Futhermore,
+are passed to functions by value (i.e. copied) and classes are passed by reference. Furthermore,
we can use templates to parameterize all of these on both types and values!
```c
-// Here, T is a type parameter. Think <T> from C++/C#/Java
+// Here, 'T' is a type parameter. Think '<T>' from C++/C#/Java.
struct LinkedList(T) {
T data = null;
- LinkedList!(T)* next; // The ! is used to instaniate a parameterized type. Again, think <T>
+
+ // Use '!' to instantiate a parameterized type. Again, think '<T>'.
+ LinkedList!(T)* next;
}
class BinTree(T) {
T data = null;
- // If there is only one template parameter, we can omit parens
+ // If there is only one template parameter, we can omit the parentheses.
BinTree!T left;
BinTree!T right;
}
@@ -93,13 +100,11 @@ enum Day {
Saturday,
}
-// Use alias to create abbreviations for types
-
+// Use alias to create abbreviations for types.
alias IntList = LinkedList!int;
alias NumTree = BinTree!double;
// We can create function templates as well!
-
T max(T)(T a, T b) {
if(a < b)
return b;
@@ -107,9 +112,8 @@ T max(T)(T a, T b) {
return a;
}
-// Use the ref keyword to ensure pass by referece.
-// That is, even if a and b are value types, they
-// will always be passed by reference to swap
+// Use the ref keyword to ensure pass by reference. That is, even if 'a' and 'b'
+// are value types, they will always be passed by reference to 'swap()'.
void swap(T)(ref T a, ref T b) {
auto temp = a;
@@ -117,13 +121,13 @@ void swap(T)(ref T a, ref T b) {
b = temp;
}
-// With templates, we can also parameterize on values, not just types
+// With templates, we can also parameterize on values, not just types.
class Matrix(uint m, uint n, T = int) {
T[m] rows;
T[n] columns;
}
-auto mat = new Matrix!(3, 3); // We've defaulted type T to int
+auto mat = new Matrix!(3, 3); // We've defaulted type 'T' to 'int'.
```
@@ -133,21 +137,20 @@ have the syntax of POD structures (`structure.x = 7`) with the semantics of
getter and setter methods (`object.setX(7)`)!
```c
-// Consider a class parameterized on a types T, U
-
+// Consider a class parameterized on types 'T' & 'U'.
class MyClass(T, U) {
T _data;
U _other;
-
}
-// And "getter" and "setter" methods like so
+// And "getter" and "setter" methods like so:
class MyClass(T, U) {
T _data;
U _other;
- // Constructors are always named `this`
+ // Constructors are always named 'this'.
this(T t, U u) {
+ // This will call the setter methods below.
data = t;
other = u;
}
@@ -170,16 +173,24 @@ class MyClass(T, U) {
_other = u;
}
}
-// And we use them in this manner
+// And we use them in this manner:
void main() {
- auto mc = MyClass!(int, string);
+ auto mc = new MyClass!(int, string)(7, "seven");
- mc.data = 7;
- mc.other = "seven";
+ // Import the 'stdio' module from the standard library for writing to
+ // console (imports can be local to a scope).
+ import std.stdio;
- writeln(mc.data);
- writeln(mc.other);
+ // Call the getters to fetch the values.
+ writefln("Earlier: data = %d, str = %s", mc.data, mc.other);
+
+ // Call the setters to assign new values.
+ mc.data = 8;
+ mc.other = "eight";
+
+ // Call the getters again to fetch the new values.
+ writefln("Later: data = %d, str = %s", mc.data, mc.other);
}
```
@@ -188,8 +199,8 @@ our getter and setter methods, and keep the clean syntax of
accessing members directly!
Other object-oriented goodies at our disposal
-include `interface`s, `abstract class`es,
-and `override`ing methods. D does inheritance just like Java:
+include interfaces, abstract classes,
+and overriding methods. D does inheritance just like Java:
Extend one class, implement as many interfaces as you please.
We've seen D's OOP facilities, but let's switch gears. D offers
@@ -207,7 +218,7 @@ void main() {
// from 1 to 100. Easy!
// Just pass lambda expressions as template parameters!
- // You can pass any old function you like, but lambdas are convenient here.
+ // You can pass any function you like, but lambdas are convenient here.
auto num = iota(1, 101).filter!(x => x % 2 == 0)
.map!(y => y ^^ 2)
.reduce!((a, b) => a + b);
@@ -217,7 +228,7 @@ void main() {
```
Notice how we got to build a nice Haskellian pipeline to compute num?
-That's thanks to a D innovation know as Uniform Function Call Syntax.
+That's thanks to a D innovation know as Uniform Function Call Syntax (UFCS).
With UFCS, we can choose whether to write a function call as a method
or free function call! Walter wrote a nice article on this
[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
@@ -227,21 +238,23 @@ is of some type A on any expression of type A as a method.
I like parallelism. Anyone else like parallelism? Sure you do. Let's do some!
```c
+// Let's say we want to populate a large array with the square root of all
+// consecutive integers starting from 1 (up until the size of the array), and we
+// want to do this concurrently taking advantage of as many cores as we have
+// available.
+
import std.stdio;
import std.parallelism : parallel;
import std.math : sqrt;
void main() {
- // We want take the square root every number in our array,
- // and take advantage of as many cores as we have available.
+ // Create your large array
auto arr = new double[1_000_000];
- // Use an index, and an array element by referece,
- // and just call parallel on the array!
+ // 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/dart.html.markdown b/dart.html.markdown
index f7601271..fc7b220e 100644
--- a/dart.html.markdown
+++ b/dart.html.markdown
@@ -498,7 +498,7 @@ main() {
## Further Reading
-Dart has a comprehenshive web-site. It covers API reference, tutorials, articles and more, including a
+Dart has a comprehensive web-site. It covers API reference, tutorials, articles and more, including a
useful Try Dart online.
http://www.dartlang.org/
http://try.dartlang.org/
diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown
index fb9cd9d4..541d28bb 100644
--- a/de-de/bash-de.html.markdown
+++ b/de-de/bash-de.html.markdown
@@ -28,18 +28,50 @@ echo Hello, world!
echo 'Dies ist die erste Zeile'; echo 'Dies die zweite Zeile'
# Variablen deklariert man so:
-VARIABLE="irgendein String"
+Variable="irgendein String"
# Aber nicht so:
-VARIABLE = "irgendein String"
-# Bash wird VARIABLE für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben,
+Variable = "irgendein String"
+# Bash wird 'Variable' für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben,
# weil es den Befehl nicht findet.
+# Und so auch nicht:
+Variable= 'Some string'
+# Bash wird 'Variable' wieder für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben,
+# Hier wird der Teil 'Variable=' als nur für diesen einen Befehl gültige Zuweisung an die Variable gesehen.
+
# Eine Variable wird so benutzt:
-echo $VARIABLE
-echo "$VARIABLE"
-# Wenn du eine Variable selbst benutzt – ihr Werte zuweist, sie exportierst oder irgendetwas anders –,
+echo $Variable
+echo "$Variable"
+echo ${Variable}
+# aber
+echo '$Variable'
+# Wenn du eine Variable selbst benutzt – ihr Werte zuweist, sie exportierst oder irgendetwas anderes –,
# dann über ihren Namen ohne $. Aber wenn du ihren zugewiesenen Wert willst, dann musst du $ voranstellen.
+# Beachte: ' (Hochkomma) verhindert das Interpretieren der Variablen
+
+# Ersetzen von Zeichenketten in Variablen
+echo ${Variable/irgendein/neuer}
+# Ersetzt das erste Vorkommen von "irgendein" durch "neuer"
+
+# Teil einer Zeichenkette
+Laenge=7
+echo ${Variable:0:Laenge}
+# Gibt nur die ersten 7 Zeichen zurück
+
+# Standardwert verwenden
+echo ${Foo:-"ErsatzWennLeerOderUngesetzt"}
+# Das funktioniert mit nicht gesetzten Variablen (Foo=) und leeren Zeichenketten (Foo="")
+# Die Zahl 0 (Foo=0) liefert 0.
+# Beachte: der wert der Variablen wird nicht geändert
+
+# Eingebaute Variable (BUILTINS):
+# Einige nützliche Beispiele
+echo "Rückgabewert des letzten Befehls: $?"
+echo "Die PID des skripts: $$"
+echo "Anzahl der Argumente beim Aufruf: $#"
+echo "Alle Argumente beim Aufruf: $@"
+echo "Die Argumente in einzelnen Variablen: $1 $2..."
# Einen Wert aus der Eingabe lesen:
echo "Wie heisst du?"
@@ -47,14 +79,30 @@ read NAME # Wir mussten nicht mal eine neue Variable deklarieren
echo Hello, $NAME!
# Wir haben die übliche if-Struktur:
-if true
+# 'man test' liefert weitere Informationen zu Bedingungen
+if [ "$NAME" -ne $USER ]
then
- echo "Wie erwartet"
+ echo "Dein Name ist nicht dein Login-Name"
else
- echo "Und dies nicht"
+ echo "Dein Name ist dein Login-Name"
+fi
+
+# Es gibt auch bedingte Ausführung
+echo "immer ausgeführt" || echo "Nur ausgeführt wenn der erste Befehl fehlschlägt"
+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 ]
+then
+ echo "Wird ausgeführt wenn $NAME gleich 'Steve' UND $Alter gleich 15."
+fi
+
+if [ $Name == "Daniya" ] || [ $Name == "Zach" ]
+then
+ echo "Wird ausgeführt wenn $NAME gleich 'Daniya' ODER $NAME gleich 'Zach'."
fi
-# Ausdrücke werden im folgenden Format festgehalten:
+# Ausdrücke haben folgendes Format:
echo $(( 10 + 5 ))
# Anders als andere Programmiersprachen ist Bash eine Shell – es arbeitet also im Kontext von Verzeichnissen.
@@ -69,13 +117,60 @@ ls -l # Liste alle Dateien und Unterverzeichnisse auf einer eigenen Zeile auf
# txt-Dateien im aktuellen Verzeichnis auflisten:
ls -l | grep "\.txt"
-# Befehle können innerhalb anderer Befehle mit $( ) erstetzt werden:
+# Ein- und Ausgabe können umgeleitet werden (stdin, stdout, and stderr).
+# Von stdin lesen bis "EOF" allein in einer Zeile auftaucht
+# und die Datei hello.py mit den Zeilen zwischen den beiden "EOF"
+# überschreiben:
+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
+
+# Führe hello.py mit verschiedenen Umleitungen von
+# stdin, stdout und stderr aus:
+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
+# Die Fehlerausgabe würde die Datei "error.err" überschreiben (falls sie existiert)
+# verwende ">>" um stattdessen anzuhängen:
+python hello.py >> "output.out" 2>> "error.err"
+
+# Überschreibe output.out, hänge an error.err an und zähle die Zeilen beider Dateien:
+info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err
+wc -l output.out error.err
+
+# Führe einen Befehl aus und gib dessen "file descriptor" (zB /dev/fd/123) aus
+# siehe: man fd
+echo <(echo "#helloworld")
+
+# Mehrere Arten, um output.out mit "#helloworld" zu überschreiben:
+cat > output.out <(echo "#helloworld")
+echo "#helloworld" > output.out
+echo "#helloworld" | cat > output.out
+echo "#helloworld" | tee output.out >/dev/null
+
+# Löschen der Hilfsdateien von oberhalb, mit Anzeige der Dateinamen
+# (mit '-i' für "interactive" erfolgt für jede Date eine Rückfrage)
+rm -v output.out error.err output-and-error.log
+
+# Die Ausgabe von Befehlen kann mit Hilfe von $( ) in anderen Befehlen verwendet weden:
# Der folgende Befehl zeigt die Anzahl aller Dateien und Unterverzeichnisse
# im aktuellen Verzeichnis an.
echo "Dieser Ordner beinhaltet $(ls | wc -l) Dateien und Verzeichnisse."
+# Dasselbe kann man mit "backticks" `` erreichen, aber diese können
+# nicht verschachtelt werden. $() ist die empfohlene Methode.
+echo "Dieser Ordner beinhaltet `ls | wc -l` Dateien und Verzeichnisse."
+
# Bash nutzt einen case-Ausdruck, der sich ähnlich wie switch in Java oder C++ verhält.
-case "$VARIABLE"
+case "$Variable"
in
# Liste der Fälle, die unterschieden werden sollen
0) echo "Hier ist eine Null."
@@ -83,10 +178,106 @@ in
*) echo "Das ist nicht Null."
esac
-# loops iterieren über die angegebene Zahl von Argumenten:
-# Der Inhalt von $VARIABLE wird dreimal ausgedruckt.
-for $VARIABLE in x y z
+# 'for' Schleifen iterieren über die angegebene Zahl von Argumenten:
+# Der Inhalt von $Variable wird dreimal ausgedruckt.
+for $Variable in {1..3}
do
- echo "$VARIABLE"
+ echo "$Variable"
done
+
+# Oder verwende die "traditionelle 'for'-Schleife":
+for ((a=1; a <= 3; a++))
+do
+ echo $a
+done
+
+# Schleifen können auch mit Dateien arbeiten:
+# 'cat' zeigt zuerst file1 an und dann file2
+for Variable in file1 file2
+do
+ cat "$Variable"
+done
+
+# .. oder mit der Ausgabe eines Befehls:
+# Ausgabe des Inhalts jeder Datei, die von 'ls' aufgezählt wird
+for Output in $(ls)
+do
+ cat "$Output"
+done
+
+# while Schleife:
+while [ true ]
+do
+ echo "Schleifenkörper..."
+ break
+done
+
+# Funktionen definieren
+# Definition:
+function foo ()
+{
+ echo "Argumente funktionieren wie bei skripts: $@"
+ echo Und: $1 $2..."
+ echo "Dies ist eine Funktion"
+ return 0
+}
+
+# oder einfacher
+bar ()
+{
+ echo "Auch so kann man Funktionen deklarieren!"
+ return 0
+}
+
+# Aufruf der Funktion:
+foo "My name is" $Name
+
+# Was du noch lernen könntest:
+# Ausgabe der letzten 10 Zeilen von file.txt
+tail -n 10 file.txt
+# Ausgabe der ersten 10 Zeilen von file.txt
+head -n 10 file.txt
+# sortierte Ausgabe von file.txt
+sort file.txt
+# Mehrfachzeilen in sortierten Dateien unterdrücken
+# oder (mit -d) nur diese ausgeben
+uniq -d file.txt
+# Ausgabe nur der ersten Spalte (vor dem ersten ',')
+cut -d ',' -f 1 file.txt
+# ersetze in file.txt jedes vorkommende 'gut' durch 'super' (versteht regex)
+sed -i 's/gut/super/g' file.txt
+# Ausgabe nach stdout aller Zeilen von file.txt, die auf eine regex passen
+# Im Beispiel: Zeilen, die mit "foo" beginnen und mit "bar" enden
+grep "^foo.*bar$" file.txt
+# Mit der Option "-c" wird stattdessen die Anzahl der gefundenen Zeilen ausgegeben
+grep -c "^foo.*bar$" file.txt
+# verwende 'fgrep' oder 'grep -F' wenn du buchstäblich nach den Zeichen
+# suchen willst, ohne sie als regex zu interpretieren
+fgrep "^foo.*bar$" file.txt
+
+# Dokumentation über die in bash eingebauten Befehle
+# bekommst du mit dem eingebauten Befehl 'help'
+help
+help help
+help for
+help return
+help source
+help .
+
+# Das bash-Handbuch liest du mit 'man'
+apropos bash
+man 1 bash
+man bash
+
+# Dann gibt es noch das 'info' System (drücke ? um Hilfe angezeigt zu bekommen)
+apropos info | grep '^info.*('
+man info
+info info
+info 5 info
+
+# info Dokumentation über bash:
+info bash
+info bash 'Bash Features'
+info bash 6
+info --apropos bash
```
diff --git a/de-de/csharp-de.html.markdown b/de-de/csharp-de.html.markdown
index 8ad7d71f..78bb0a6b 100644
--- a/de-de/csharp-de.html.markdown
+++ b/de-de/csharp-de.html.markdown
@@ -883,7 +883,7 @@ zur nächsten Zeile, ""Wahnsinn!"", die Massen waren kaum zu bändigen";
* [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 Matrix Tutorials](http://www.asp.net/web-pages/overview/exploring-webmatrix)
* [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)
diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown
index 43939129..dea329d5 100644
--- a/de-de/git-de.html.markdown
+++ b/de-de/git-de.html.markdown
@@ -18,12 +18,12 @@ Anmerkung des Übersetzers: Einige englische Begriffe wie *Repository*, *Commit*
### Was ist Versionsverwaltung?
-Eine Versionskontrolle erfasst die Änderungen einer Datei oder eines Verzeichnisses im Verlauf der Zeit.
+Eine Versionsverwaltung erfasst die Änderungen einer Datei oder eines Verzeichnisses im Verlauf der Zeit.
### Zentrale im Vergleich mit verteilter Versionverwaltung
-* Zentrale Versionskontrolle konzentriert sich auf das Synchronisieren, Verfolgen und Sichern von Dateien.
-* Verteilte Versionskontrolle konzentriert sich auf das Teilen der Änderungen. Jede Änderung hat eine eindeutige ID.
+* Zentrale Versionsverwaltung konzentriert sich auf das Synchronisieren, Verfolgen und Sichern von Dateien.
+* Verteilte Versionsverwaltung konzentriert sich auf das Teilen der Änderungen. Jede Änderung hat eine eindeutige ID.
* Verteilte Systeme haben keine vorbestimmte Struktur. Ein SVN-ähnliches, zentrales System wäre mit Git ebenso umsetzbar.
[Weiterführende Informationen](http://git-scm.com/book/en/Getting-Started-About-Version-Control)
@@ -61,7 +61,7 @@ Der Index ist die die Staging-Area von Git. Es ist im Grunde eine Ebene, die Arb
### Commit
-Ein Commit ist ein Schnappschuss von Uderungen in deinem Arbeitsverzeichnis. Wenn du zum Beispiel 5 Dateien hinzugefügt und 2 andere entfernt hast, werden diese Änderungen im Commit (Schnappschuss) enthalten sein. Dieser Commit kann dann in andere Repositorys gepusht werden. Oder nicht!
+Ein Commit ist ein Schnappschuss von Änderungen in deinem Arbeitsverzeichnis. Wenn du zum Beispiel 5 Dateien hinzugefügt und 2 andere entfernt hast, werden diese Änderungen im Commit (Schnappschuss) enthalten sein. Dieser Commit kann dann in andere Repositories gepusht werden. Oder nicht!
### Branch
@@ -69,7 +69,9 @@ Ein Branch, ein Ast oder Zweig, ist im Kern ein Pointer auf den letzten Commit,
### HEAD und head (Teil des .git-Verzeichnisses)
-HEAD ist ein Pointer auf den aktuellen Branch. Ein Repository hat nur einen *aktiven* HEAD. Ein head ist ein Pointer, der auf ein beliebige Zahl von heads zeigt.
+HEAD ist ein Pointer auf den aktuellen Branch. Ein Repository hat nur einen *aktiven* HEAD.
+
+Ein *head* ist ein Pointer, der auf einen beliebigen Commit zeigt. Ein Repository kann eine beliebige Zahl von *heads* enthalten.
### Konzeptionelle Hintergründe
@@ -127,7 +129,7 @@ Zeigt die Unterschiede zwischen Index (im Grunde dein Arbeitsverzeichnis/-reposi
```bash
-# Zeigt den Branch, nicht-verfolgte Dateien, Uderungen und andere Unterschiede an
+# Zeigt den Branch, nicht-verfolgte Dateien, Änderungen und andere Unterschiede an
$ git status
# Anderes Wissenswertes über git status anzeigen
@@ -151,7 +153,7 @@ $ git add ./*.java
### branch
-Verwalte alle Branches. Du kannst sie mit diesem Befehl ansehen, bearbeiten, neue erschaffen oder löschen.
+Verwalte alle Branches. Du kannst sie mit diesem Befehl ansehen, bearbeiten, neue erzeugen oder löschen.
```bash
# Liste alle bestehenden Branches und Remotes auf
@@ -186,7 +188,7 @@ $ git checkout -b newBranch
### clone
-Ein bestehendes Repository in ein neues Verzeichnis klonen oder kopieren. Es fügt außerdem für hedes geklonte Repo remote-tracking Branches hinzu. Du kannst auf diese Remote-Branches pushen.
+Ein bestehendes Repository in ein neues Verzeichnis klonen oder kopieren. Es fügt außerdem für jedes geklonte Repository remote-tracking Branches hinzu. Du kannst auf diese Remote-Branches pushen.
```bash
# Klone learnxinyminutes-docs
@@ -288,16 +290,16 @@ $ git mv -f myFile existingFile
### pull
-Führe einen Pull, zieht alle Daten, eines Repositorys und f?? einen Merge mit einem anderen Branch durch.
+Führe einen Pull (zieht alle Daten eines Repositories) aus und führt einen Merge mit einem anderen Branch durch.
```bash
-# Update deines lokalen Repos, indem ein Merge der neuen Uderungen
-# von den remote-liegenden "origin"- und "master"-Branches durchgef?? wird.
+# Update deines lokalen Repos, indem ein Merge der neuen Änderungen
+# von den remote-liegenden "origin"- und "master"-Branches durchgeführt wird.
# git pull <remote> <branch>
# git pull => impliziter Verweis auf origin und master
$ git pull origin master
-# F?? einen Merge von Uderungen eines remote-Branch und ein Rebase
+# Führt einen Merge von Änderungen eines remote-Branch und ein Rebase
# des Branch-Commits im lokalen Repo durch. Wie: pull <remote> <branch>, git rebase <branch>"
$ git pull origin master --rebase
```
@@ -337,8 +339,8 @@ $ git reset
# Setze die Staging-Area zurück, um dem letzten Commit zu entsprechen und überschreibe das Arbeitsverzeichnis
$ git reset --hard
-# Bewegt die Spitze des Branches zu dem angegebenen Commit (das Verzeichnis bleibt unber??)
-# Alle Uderungen bleiben im Verzeichnis erhalten
+# Bewegt die Spitze des Branches zu dem angegebenen Commit (das Verzeichnis bleibt unberührt)
+# Alle Änderungen bleiben im Verzeichnis erhalten
$ git reset 31f2bb1
# Bewegt die Spitze des Branches zurück zu dem angegebenen Commit
diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown
index 765372e0..94f48e65 100644
--- a/de-de/go-de.html.markdown
+++ b/de-de/go-de.html.markdown
@@ -3,17 +3,17 @@ language: Go
filename: learngo-de.go
contributors:
- ["Joseph Adams", "https://github.com/jcla1"]
+ - ["Dennis Keller", "https://github.com/denniskeller"]
+ - ["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.
@@ -23,8 +23,8 @@ aktive Community.
/* Mehr-
zeiliger Kommentar */
-// Eine jede Quelldatei beginnt mit einer Paket-Klausel.
-// "main" ist ein besonderer Pkaetname, da er ein ausführbares Programm
+// 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.
package main
@@ -37,9 +37,9 @@ import (
"strconv" // Zeichenkettenmanipulation
)
-// Es folgt die Definition einer Funktions, in diesem Fall von "main". Auch hier
+// 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.
@@ -49,13 +49,13 @@ 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.
// Kurze Deklaration: Benutzen Sie ":=", um die Typisierung automatisch zu
- // folgern, die Variable zu deklarieren und ihr einen Wert zu zuweisen.
+ // folgern, die Variable zu deklarieren und ihr einen Wert zuzuweisen.
y := 4
// Eine Funktion mit mehreren Rückgabewerten.
@@ -98,7 +98,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
@@ -146,7 +146,7 @@ func learnFlowControl() {
if false {
// nicht hier
} else {
- // sonder hier! spielt die Musik
+ // sondern hier! spielt die Musik
}
// Benutzen Sie ein "switch" Statement anstatt eine Anreihung von if-s
@@ -165,7 +165,7 @@ func learnFlowControl() {
// Ab hier gilt wieder: x == 1
// For ist die einzige Schleifenform in Go, sie hat aber mehrere Formen:
- for { // Endloschleife
+ for { // Endlosschleife
break // nur ein Spaß
continue // wird nie ausgeführt
}
@@ -200,7 +200,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.
@@ -254,18 +255,19 @@ 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)
// Auslesen und dann Ausgeben der drei berechneten Werte.
// Man kann nicht im voraus feststellen in welcher Reihenfolge die Werte
// ankommen.
- fmt.Println(<-c, <-c, <-c) // mit dem Kannal rechts ist <- der Empfangs-Operator
+ fmt.Println(<-c, <-c, <-c) // mit dem Kanal rechts ist <- der Empfangs-Operator
- cs := make(chan string) // ein weiterer Kannal, diesmal für strings
- cc := make(chan chan string) // ein Kannal für string Kannäle
+ cs := make(chan string) // ein weiterer Kanal, diesmal für strings
+ cc := make(chan chan string) // ein Kanal für string Kanäle
// Start einer neuen Goroutine, nur um einen Wert zu senden
go func() { c <- 84 }()
@@ -282,7 +284,7 @@ func learnConcurrency() {
fmt.Println("wird nicht passieren.")
}
// Hier wird eine der beiden Goroutines fertig sein, die andere nicht.
- // Sie wird warten bis der Wert den sie sendet von dem Kannal gelesen wird.
+ // Sie wird warten bis der Wert den sie sendet von dem Kanal gelesen wird.
learnWebProgramming() // Go kann es und Sie hoffentlich auch bald.
}
@@ -300,19 +302,18 @@ func learnWebProgramming() {
// Methode implementieren: ServeHTTP
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Senden von Daten mit einer Methode des http.ResponseWriter
- w.Write([]byte("Sie habe Go in Y Minuten gelernt!"))
+ w.Write([]byte("Sie haben Go in Y Minuten gelernt!"))
}
```
## Weitere Resourcen
-Alles zu Go finden Sie auf der [offiziellen Go Webseite](http://golang.org/).
-Dort können sie der 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/haskell-de.html.markdown b/de-de/haskell-de.html.markdown
index 2c548961..d1a0008e 100644
--- a/de-de/haskell-de.html.markdown
+++ b/de-de/haskell-de.html.markdown
@@ -5,6 +5,7 @@ contributors:
- ["Adit Bhargava", "http://adit.io"]
translators:
- ["Henrik Jürges", "https://github.com/santifa"]
+ - ["Nikolai Weh", "http://weh.hamburg"]
filename: haskell-de.hs
---
@@ -58,12 +59,13 @@ not False -- True
-- Strings und Zeichen
"Das ist ein String."
'a' -- Zeichen
-'Einfache Anfuehrungszeichen gehen nicht.' -- error!
+'Einfache Anführungszeichen gehen nicht.' -- error!
-- Strings können konkateniert werden.
"Hello " ++ "world!" -- "Hello world!"
-- Ein String ist eine Liste von Zeichen.
+['H', 'a', 'l', 'l', 'o', '!'] -- "Hallo!"
"Das ist eine String" !! 0 -- 'D'
@@ -76,11 +78,23 @@ not False -- True
[1, 2, 3, 4, 5]
[1..5]
--- Haskell unterstuetzt unendliche Listen!
-[1..] -- Die Liste aller natuerlichen Zahlen
+-- Die zweite Variante nennt sich die "range"-Syntax.
+-- Ranges sind recht flexibel:
+['A'..'F'] -- "ABCDEF"
+
+-- Es ist möglich eine Schrittweite anzugeben:
+[0,2..10] -- [0,2,4,6,8,10]
+[5..1] -- [], da Haskell standardmässig inkrementiert.
+[5,4..1] -- [5,4,3,2,1]
+
+-- Der "!!"-Operator extrahiert das Element an einem bestimmten Index:
+[1..10] !! 3 -- 4
+
+-- Haskell unterstützt unendliche Listen!
+[1..] -- Die Liste aller natürlichen Zahlen
-- Unendliche Listen funktionieren in Haskell, da es "lazy evaluation"
--- unterstuetzt. Haskell evaluiert erst etwas, wenn es benötigt wird.
+-- unterstützt. Haskell evaluiert erst etwas, wenn es benötigt wird.
-- Somit kannst du nach dem 1000. Element fragen und Haskell gibt es dir:
[1..] !! 999 -- 1000
@@ -92,12 +106,9 @@ not False -- True
-- Zwei Listen konkatenieren
[1..5] ++ [6..10]
--- Ein Element als Head hinzufuegen
+-- Ein Element als Head hinzufügen
0:[1..5] -- [0, 1, 2, 3, 4, 5]
--- Gibt den 5. Index zurueck
-[0..] !! 5 -- 5
-
-- Weitere Listenoperationen
head [1..5] -- 1
tail [1..5] -- [2, 3, 4, 5]
@@ -114,7 +125,8 @@ last [1..5] -- 5
-- Ein Tupel:
("haskell", 1)
--- Auf Elemente eines Tupels zugreifen:
+-- Ein Paar (Pair) ist ein Tupel mit 2 Elementen, auf die man wie folgt
+-- zugreifen kann:
fst ("haskell", 1) -- "haskell"
snd ("haskell", 1) -- 1
@@ -140,9 +152,9 @@ add 1 2 -- 3
(//) a b = a `div` b
35 // 4 -- 8
--- Guards sind eine einfache Möglichkeit fuer Fallunterscheidungen.
+-- Guards sind eine einfache Möglichkeit für Fallunterscheidungen.
fib x
- | x < 2 = x
+ | x < 2 = 1
| otherwise = fib (x - 1) + fib (x - 2)
-- Pattern Matching funktioniert ähnlich.
@@ -174,7 +186,7 @@ foldl1 (\acc x -> acc + x) [1..5] -- 15
-- 4. Mehr Funktionen
----------------------------------------------------
--- currying: Wenn man nicht alle Argumente an eine Funktion uebergibt,
+-- currying: Wenn man nicht alle Argumente an eine Funktion übergibt,
-- so wird sie eine neue Funktion gebildet ("curried").
-- Es findet eine partielle Applikation statt und die neue Funktion
-- nimmt die fehlenden Argumente auf.
@@ -190,23 +202,28 @@ foo 5 -- 15
-- Funktionskomposition
-- Die (.) Funktion verkettet Funktionen.
-- Zum Beispiel, die Funktion Foo nimmt ein Argument addiert 10 dazu und
--- multipliziert dieses Ergebnis mit 5.
-foo = (*5) . (+10)
+-- multipliziert dieses Ergebnis mit 4.
+foo = (*4) . (+10)
+
+-- (5 + 10) * 4 = 60
+foo 5 -- 60
--- (5 + 10) * 5 = 75
-foo 5 -- 75
+-- 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,
+-- 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.
--- Haskell hat eine Funktion `$`. Diese ändert den Vorrang,
--- so dass alles links von ihr zuerst berechnet wird und
--- und dann an die rechte Seite weitergegeben wird.
--- Mit `.` und `$` kann man sich viele Klammern ersparen.
+(even (fib 7)) -- false
--- Vorher
-(even (fib 7)) -- true
+-- Äquivalent:
+even $ fib 7 -- false
--- Danach
-even . fib $ 7 -- true
+-- Funktionskomposition:
+even . fib $ 7 -- false
----------------------------------------------------
-- 5. Typensystem
@@ -221,31 +238,31 @@ even . fib $ 7 -- true
True :: Bool
-- Funktionen haben genauso Typen.
--- `not` ist Funktion die ein Bool annimmt und ein Bool zurueckgibt:
+-- `not` ist Funktion die ein Bool annimmt und ein Bool zurückgibt:
-- not :: Bool -> Bool
-- Eine Funktion die zwei Integer Argumente annimmt:
-- add :: Integer -> Integer -> Integer
-- Es ist guter Stil zu jeder Funktionsdefinition eine
--- Typdefinition darueber zu schreiben:
+-- Typdefinition darüber zu schreiben:
double :: Integer -> Integer
double x = x * 2
----------------------------------------------------
--- 6. If-Anweisung und Kontrollstrukturen
+-- 6. If-Ausdrücke und Kontrollstrukturen
----------------------------------------------------
--- If-Anweisung:
+-- If-Ausdruck:
haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome"
--- If-Anweisungen können auch ueber mehrere Zeilen verteilt sein.
--- Das Einruecken ist dabei äußerst wichtig.
+-- If-Ausdrücke können auch über mehrere Zeilen verteilt sein.
+-- Die Einrückung ist dabei wichtig.
haskell = if 1 == 1
then "awesome"
else "awful"
--- Case-Anweisung: Zum Beispiel "commandline" Argumente parsen.
+-- Case-Ausdruck: Am Beispiel vom Parsen von "commandline"-Argumenten.
case args of
"help" -> printHelp
"start" -> startProgram
@@ -276,7 +293,7 @@ foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43
foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16
-- die Abarbeitung sieht so aus:
-(2 * 3 + (2 * 2 + (2 * 1 + 4)))
+(2 * 1 + (2 * 2 + (2 * 3 + 4)))
----------------------------------------------------
-- 7. Datentypen
@@ -300,7 +317,7 @@ data Maybe a = Nothing | Just a
-- Diese sind alle vom Typ Maybe:
Just "hello" -- vom Typ `Maybe String`
Just 1 -- vom Typ `Maybe Int`
-Nothing -- vom Typ `Maybe a` fuer jedes `a`
+Nothing -- vom Typ `Maybe a` für jedes `a`
----------------------------------------------------
-- 8. Haskell IO
@@ -309,8 +326,8 @@ Nothing -- vom Typ `Maybe a` fuer jedes `a`
-- IO kann nicht völlig erklärt werden ohne Monaden zu erklären,
-- aber man kann die grundlegenden Dinge erklären.
--- Wenn eine Haskell Programm ausgefuehrt wird, so wird `main` aufgerufen.
--- Diese muss etwas vom Typ `IO ()` zurueckgeben. Zum Beispiel:
+-- Wenn eine Haskell Programm ausgeführt wird, so wird `main` aufgerufen.
+-- Diese muss etwas vom Typ `IO ()` zurückgeben. Zum Beispiel:
main :: IO ()
main = putStrLn $ "Hello, sky! " ++ (say Blue)
@@ -338,10 +355,10 @@ sayHello = do
-- an die Variable "name" gebunden
putStrLn $ "Hello, " ++ name
--- Uebung: Schreibe deine eigene Version von `interact`,
+-- Übung: Schreibe deine eigene Version von `interact`,
-- die nur eine Zeile einliest.
--- `sayHello` wird niemals ausgefuehrt, nur `main` wird ausgefuehrt.
+-- `sayHello` wird niemals ausgeführt, nur `main` wird ausgeführt.
-- Um `sayHello` laufen zulassen kommentiere die Definition von `main`
-- aus und ersetze sie mit:
-- main = sayHello
@@ -359,7 +376,7 @@ action = do
input1 <- getLine
input2 <- getLine
-- Der Typ von `do` ergibt sich aus der letzten Zeile.
- -- `return` ist eine Funktion und keine Schluesselwort
+ -- `return` ist eine Funktion und keine Schlüsselwort
return (input1 ++ "\n" ++ input2) -- return :: String -> IO String
-- Nun können wir `action` wie `getLine` benutzen:
@@ -370,7 +387,7 @@ main'' = do
putStrLn result
putStrLn "This was all, folks!"
--- Der Typ `IO` ist ein Beispiel fuer eine Monade.
+-- Der Typ `IO` ist ein Beispiel für eine Monade.
-- Haskell benutzt Monaden Seiteneffekte zu kapseln und somit
-- eine rein funktional Sprache zu sein.
-- Jede Funktion die mit der Außenwelt interagiert (z.B. IO)
@@ -387,7 +404,7 @@ main'' = do
-- Starte die REPL mit dem Befehl `ghci`
-- Nun kann man Haskell Code eingeben.
--- Alle neuen Werte muessen mit `let` gebunden werden:
+-- Alle neuen Werte müssen mit `let` gebunden werden:
let foo = 5
@@ -396,7 +413,7 @@ let foo = 5
>:t foo
foo :: Integer
--- Auch jede `IO ()` Funktion kann ausgefuehrt werden.
+-- Auch jede `IO ()` Funktion kann ausgeführt werden.
> sayHello
What is your name?
@@ -420,6 +437,6 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater
Haskell ist sehr einfach zu installieren.
Hohl es dir von [hier](http://www.haskell.org/platform/).
-Eine sehr viele langsamere Einfuehrung findest du unter:
+Eine sehr viele langsamere Einführung findest du unter:
[Learn you a Haskell](http://learnyouahaskell.com/) oder
[Real World Haskell](http://book.realworldhaskell.org/).
diff --git a/de-de/latex-de.html.markdown b/de-de/latex-de.html.markdown
new file mode 100644
index 00000000..ee9c6e3e
--- /dev/null
+++ b/de-de/latex-de.html.markdown
@@ -0,0 +1,246 @@
+---
+language: latex
+contributors:
+ - ["Chaitanya Krishna Ande", "http://icymist.github.io"]
+ - ["Colton Kohnke", "http://github.com/voltnor"]
+ - ["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 mit einem Prozentzeichen %
+
+% 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 (\)
+
+% 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.
+\documentclass[12pt]{article}
+
+% 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.
+% Wir verwenden die Pakete float und caption für Bilder.
+\usepackage{caption}
+\usepackage{float}
+
+% 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!}
+
+% Nun kann's losgehen mit unserem Dokument.
+% Alles vor dieser Zeile wird die Preamble genannt.
+\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
+\maketitle
+
+% 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!
+\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!
+
+\section{Noch eine section}
+Das hier ist der Text für noch eine section. Ich glaube, wir brauchen eine subsection.
+
+\subsection{Das ist eine subsection} % Subsections sind auch ziemlich intuitiv.
+Ich glaube, wir brauchen noch eine.
+
+\subsubsection{Pythagoras}
+So ist's schon viel besser.
+\label{subsec:pythagoras}
+
+% 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{Ein paar Notizen}
+\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,
+also lass uns eine Einkaufsliste schreiben:
+\begin{enumerate} % Dieser Befehl erstellt eine "enumerate" Umgebung.
+ % \item bringt enumerate dazu, eins weiterzuzählen.
+ \item Salat.
+ \item 27 Wassermelonen.
+ \item einen Hasen.
+ % Wir können die Nummer des Eintrags durch [] überschreiben
+ \item[Wie viele?] Mittelgroße Wasserpistolen.
+
+ Kein Listeneintrag, aber immer noch Teil von enumerate.
+
+\end{enumerate} % Alle Umgebungen müssen ein end haben.
+
+\section{Mathe}
+
+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! \\
+
+Mathe kennt sehr viele Symbole, viel mehr als auf einer Tastatur zu finden sind;
+Symbole für Mengen und relationen, Pfeile, Operatoren und Griechische Buchstaben,
+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. \\
+
+% 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!
+
+Operatoren sind ebenfalls wichtige Bestandteile von mathematischen Dokumenten:
+Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$),
+Logarithmus und Exponenten ($\log$, $\exp$),
+Grenzwerte ($\lim$), etc. haben vordefinierte Befehle.
+Lass uns eine Gleichung schreiben: \\
+
+$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$\\
+
+Brüche (Zähler / Nenner) können so geschrieben werden:
+
+% 10 / 7
+$^{10}/_{7}$
+
+% Komplexere Brüche können so geschrieben werden:
+% \frac{Zähler}{Nenner}
+$\frac{n!}{k!(n - k)!}$ \\
+
+Wir können Gleichungen auch in einer equation Umgebung verwenden.
+
+% Dies zeigt Mathe in einer equation Umgebung an
+\begin{equation} % Aktiviert automatisch den Mathe-Modus.
+ c^2 = a^2 + b^2.
+ \label{eq:pythagoras} % Pythagoras referenzieren
+\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
+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}
+ \sum_{i=0}^{5} f_{i}
+\end{equation}
+\begin{equation}
+ \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
+\end{equation}
+
+\section{Grafiken}
+
+Lass uns eine Grafik einfügen. Das Platzieren von Grafiken kann etwas trickreich sein.
+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}
+ % Auskommentiert, damit es nicht im Dokument auftaucht.
+ \caption{Dreieck mit den Seiten $a$, $b$, $c$}
+ \label{fig:right-triangle}
+\end{figure}
+
+\subsection{Tabellen}
+Wir können Tabellen genauso wie Grafiken einfügen.
+
+\begin{table}[H]
+ \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}
+ Nummer & Nachname & Vorname \\ % Spalten werden durch & getrennt
+ \hline % Eine horizontale Linie
+ 1 & Biggus & Dickus \\
+ 2 & Monty & Python
+ \end{tabular}
+\end{table}
+
+% \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,
+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}
+ 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}
+
+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.
+ Das Kompilieren sieht so ähnlich wie das hier aus (Linux): \\
+ \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
+2 wird unsichtbar im Hintergrund ausgeführt.
+
+Alle Formatierungsoptionen werden in Schritt 1 in den Quelltext geschrieben. Schritt 2 verwendet
+dann diese Informationen und kümmert sich drum, dass das Dokument korrekt erstellt wird.
+
+\section{Ende}
+
+Das war's erst mal!
+
+% Dokument beenden
+\end{document}
+```
+## Mehr Informationen über LateX
+
+* Das tolle LaTeX wikibook: [https://de.wikibooks.org/wiki/LaTeX-Kompendium](https://de.wikibooks.org/wiki/LaTeX-Kompendium)
+* Ein Tutorial (englisch): [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
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/ruby-de.html.markdown b/de-de/ruby-de.html.markdown
new file mode 100644
index 00000000..bdeaa30b
--- /dev/null
+++ b/de-de/ruby-de.html.markdown
@@ -0,0 +1,613 @@
+---
+language: ruby
+contributors:
+ - ["David Underwood", "http://theflyingdeveloper.com"]
+ - ["Joel Walden", "http://joelwalden.net"]
+ - ["Luke Holder", "http://twitter.com/lukeholder"]
+ - ["Tristan Hume", "http://thume.ca/"]
+ - ["Nick LaMuro", "https://github.com/NickLaMuro"]
+ - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
+ - ["Dzianis Dashkevich", "https://github.com/dskecse"]
+ - ["Levi Bostian", "https://github.com/levibostian"]
+ - ["Rahil Momin", "https://github.com/iamrahil"]
+translators:
+ - ["Christian Albrecht", "https://github.com/coastalchief"]
+filename: ruby-de.rb
+lang: de-de
+---
+
+# Dies ist ein Kommentar
+
+=begin
+Dies sind multi-line
+Kommentare. Niemand benutzt
+die wirklich.
+=end
+
+# Objekte - Alles ist ein Objekt
+
+## Zahlen sind Objekte
+```
+3.class #=> Fixnum
+3.to_s #=> "3"
+```
+
+### Simple Arithmetik
+```
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+2**5 #=> 32
+```
+
+// Arithmetik ist aber eigentlich nur syntaktischer Zucker
+// um eine Methode eines Objekt aufzurufen
+```
+1.+(3) #=> 4
+10.* 5 #=> 50
+```
+
+## Special values sind Objekte
+```
+nil # Nothing to see here
+true # truth
+false # falsehood
+
+nil.class #=> NilClass
+true.class #=> TrueClass
+false.class #=> FalseClass
+```
+
+## Objektvergleiche
+### Gleicheit
+```
+1 == 1 #=> true
+2 == 1 #=> false
+```
+### Ungleichheit
+```
+1 != 1 #=> false
+2 != 1 #=> true
+```
+### Neben false selbst, nil ist ein anderer 'falsey' Wert
+```
+!nil #=> true
+!false #=> true
+!0 #=> false
+```
+### Weitere Vergleiche
+```
+1 < 10 #=> true
+1 > 10 #=> false
+2 <= 2 #=> true
+2 >= 2 #=> true
+```
+### Logische Operatoren
+```
+true && false #=> false
+true || false #=> true
+!true #=> false
+```
+
+Es gibt alternative Versionen der logischen Operatoren mit niedrigerer
+Wertigkeit. Diese werden meistens bei Flow-Control eingesetzt, um
+verschiedenen Ausdrücke zu verketten bis einer true oder false zurück
+liefert.
+
+#### and
+##### `do_something_else` wird nur ausgewertet wenn `do_something` true ist.
+do_something() and do_something_else()
+
+#### or
+#####`log_error` wird nur ausgewertet wenn `do_something` false ist.
+do_something() or log_error()
+
+## Strings sind Objekte
+```
+'I am a string'.class #=> String
+"I am a string too".class #=> String
+
+
+platzhalter = 'Ruby'
+"Ich kann in #{placeholder} Platzhalter mit doppelten Anführungsstrichen füllen."
+```
+Einfache Anführungszeichen sollten bevorzugt werden.
+Doppelte Anführungszeichen führen interne Berechnungen durch.
+
+### Strings können verbunden werden, aber nicht mit Zahlen
+```
+'hello ' + 'world' #=> "hello world"
+'hello ' + 3 #=> TypeError: can't convert Fixnum into String
+```
+#### Zahl muss in String konvertiert werden
+```
+'hello ' + 3.to_s #=> "hello 3"
+```
+### Text ausgeben
+```
+puts "I'm printing!"
+```
+# Variablen
+## Zuweisungen
+### Diese Zuweisung gibt den zugeordneten Wert zurück
+```
+x = 25 #=> 25
+x #=> 25
+```
+### Damit funktionieren auch mehrfache Zuweisungen
+```
+x = y = 10 #=> 10
+x #=> 10
+y #=> 10
+```
+## Benennung
+### Konvention ist snake_case
+```
+snake_case = true
+```
+### Benutze verständliche Variablennamen
+```
+path_to_project_root = '/good/name/'
+path = '/bad/name/'
+```
+# Symbols (sind auch Objekte)
+Symbols sind unveränderliche, wiederverwendbare Konstanten, welche intern
+als integer repräsentiert werden. Sie werden häufig anstelle von Strings
+verwendet, um sinnvoll Werte zu übermitteln.
+Symbols werden mit dem Doppelpunkt gekennzeichnet.
+
+```
+:pending.class #=> Symbol
+status = :pending
+status == :pending #=> true
+status == 'pending' #=> false
+status == :approved #=> false
+```
+# Arrays
+
+## Ein Array anlegen
+```
+array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+```
+
+## Array können verschiedene Typen beinhalten
+```
+[1, 'hello', false] #=> [1, "hello", false]
+```
+
+## Wie bei arithmetischen Ausdrücken auch wird beim Zugriff auf
+## [0] eigentlich die Methode [] des Array Objekts aufgerufen.
+```
+array.[] 0 #=> 1
+array.[] 12 #=> nil
+```
+
+## Arrays können von vorne indiziert werden
+```
+array[0] #=> 1
+array[12] #=> nil
+```
+
+## Arrays können von hinten indiziert werden
+```
+array[-1] #=> 5
+```
+
+## Arrays können mit Stard Index und Länge indiziert werden
+```
+array[2, 3] #=> [3, 4, 5]
+```
+
+## Arrays können mit einer Range indiziert werden
+```
+array[1..3] #=> [2, 3, 4]
+```
+
+## Einen Wert hinzufügen
+```
+array << 6 #=> [1, 2, 3, 4, 5, 6]
+array.push(6) #=> [1, 2, 3, 4, 5, 6]
+```
+
+## Testen, ob ein Element schon vorhanden ist
+```
+array.include?(1) #=> true
+```
+
+# Hashes
+Hashes sind das Hauptfeature um Key/Values zu speichern
+
+```
+
+## Ein Hash anlegen
+```
+hash = { 'color' => 'green', 'number' => 5 }
+hash.keys #=> ['color', 'number']
+```
+
+## Wert per key herausfinden
+```
+hash['color'] #=> 'green'
+hash['number'] #=> 5
+hash['nothing here'] #=> nil
+// Asking a hash for a key that doesn't exist returns nil:
+```
+
+## Symbols können auch keys sein
+```
+new_hash = { defcon: 3, action: true }
+new_hash.keys #=> [:defcon, :action]
+```
+
+## Testen ob ein Key oder ein Value existiert
+```
+new_hash.has_key?(:defcon) #=> true
+new_hash.has_value?(3) #=> true
+```
+
+### Tip: Arrays und Hashes sind Enumerable
+### Und haben gemeinsame, hilfreiche Methoden wie:
+### each, map, count, and more
+
+# Kontrolstrukturen
+## if
+```
+if true
+ 'if statement'
+elsif false
+ 'else if, optional'
+else
+ 'else, also optional'
+end
+```
+## for - Allerdings werden for Schleifen nicht oft vewendet.
+```
+for counter in 1..5
+ puts "iteration #{counter}"
+end
+```
+## Stattdessen: "each" Methode und einen Bloch übergeben
+Ein Block ist ein Codeteil, den man einer Methode übergeben kann
+Ähnelt stark lambdas, anonymen Funktionen oder Closures in anderen
+Programmiersprachen.
+
+```
+(1..5).each do |counter|
+ puts "iteration #{counter}"
+end
+```
+
+Die each Methode einer Range führt den Block für jedes Element der Range aus.
+
+Dem Block wird ein "counter" parameter übergeben.
+
+### Den Block kann man auch in geschweiften Klammern schreiben
+```
+(1..5).each { |counter| puts "iteration #{counter}" }
+```
+
+### Each kann auch über den Inhalt von Datenstrukturen iterieren
+```
+array.each do |element|
+ puts "#{element} is part of the array"
+end
+hash.each do |key, value|
+ puts "#{key} is #{value}"
+end
+
+counter = 1
+while counter <= 5 do
+ puts "iteration #{counter}"
+ counter += 1
+end
+```
+
+## case
+```
+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 können auch ranges
+```
+grade = 82
+case grade
+when 90..100
+ puts 'Hooray!'
+when 80...90
+ puts 'OK job'
+else
+ puts 'You failed!'
+end
+=> "OK job"
+```
+
+# exception handling:
+```
+begin
+ # code here that might raise an exception
+ 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
+```
+# Funktionen
+```
+def double(x)
+ x * 2
+end
+```
+## Funktionen (und Blocks)
+## geben implizit den Wert des letzten Statements zurück
+```
+double(2) #=> 4
+```
+
+### Klammern sind optional wenn das Ergebnis nicht mehdeutig ist
+```
+double 3 #=> 6
+double double 3 #=> 12
+def sum(x, y)
+ x + y
+end
+```
+
+### Methoden Parameter werden per Komma getrennt
+```
+sum 3, 4 #=> 7
+sum sum(3, 4), 5 #=> 12
+```
+
+## yield
+### Alle Methoden haben einen impliziten, optionalen block Parameter
+### Dieser wird mit dem Schlüsselword "yield" aufgerufen
+```
+def surround
+ puts '{'
+ yield
+ puts '}'
+end
+surround { puts 'hello world' }
+```
+
+## Einen Block kann man auch einer Methoden übergeben
+### "&" kennzeichnet die Referenz zum übergebenen Block
+```
+def guests(&block)
+ block.call 'some_argument'
+end
+```
+
+### Eine Liste von Parametern kann man auch übergeben,
+### Diese wird in ein Array konvertiert
+### "*" kennzeichnet dies.
+```
+def guests(*array)
+ array.each { |guest| puts guest }
+end
+```
+# Klassen
+## Werden mit dem class Schlüsselwort definiert
+```
+class Human
+```
+
+### Konstruktor bzw. Initializer
+```
+ def initialize(name, age = 0)
+ # Assign the argument to the "name" instance variable for the instance
+ @name = name
+ # If no age given, we will fall back to the default in the arguments list.
+ @age = age
+ end
+```
+
+### setter Methode
+```
+ def name=(name)
+ @name = name
+ end
+```
+### getter Methode
+```
+ def name
+ @name
+ end
+```
+
+#### getter können mit der attr_accessor Methode vereinfacht definiert werden
+```
+ attr_accessor :name
+ # Getter/setter methods can also be created individually like this
+ attr_reader :name
+ attr_writer :name
+ # A class method uses self to distinguish from instance methods.
+ # It can only be called on the class, not an instance.
+ def self.say(msg)
+ puts msg
+ end
+ def species
+ @@species
+ end
+end
+```
+
+## Eine Klasse instanziieren
+```
+jim = Human.new('Jim Halpert')
+dwight = Human.new('Dwight K. Schrute')
+```
+
+## Methodenaufrufe
+```
+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"
+```
+
+## Eine Klassenmethode aufrufen
+```
+Human.say('Hi') #=> "Hi"
+```
+
+## Variable Gültigkeit
+### Variablen die mit "$" starten, gelten global
+```
+$var = "I'm a global var"
+defined? $var #=> "global-variable"
+```
+
+### Variablen die mit "@" starten, gelten für die Instanz
+```
+@var = "I'm an instance var"
+defined? @var #=> "instance-variable"
+```
+
+### Variablen die mit "@@" starten, gelten für die Klasse
+```
+@@var = "I'm a class var"
+defined? @@var #=> "class variable"
+```
+
+### Variablen die mit einem Großbuchstaben anfangen, sind Konstanten
+```
+Var = "I'm a constant"
+defined? Var #=> "constant"
+```
+
+## Class ist auch ein Objekt
+### Hat also auch Instanzvariablen
+### Eine Klassenvariable wird innerhalb der Klasse und Ableitungen geteilt.
+
+### Basis Klasse
+```
+class Human
+ @@foo = 0
+ def self.foo
+ @@foo
+ end
+ def self.foo=(value)
+ @@foo = value
+ end
+end
+```
+
+### Abgeleitete Klasse
+```
+class Worker < Human
+end
+Human.foo # 0
+Worker.foo # 0
+Human.foo = 2 # 2
+Worker.foo # 2
+```
+
+### Eine Klasseninstanzvariable wird nicht geteilt
+```
+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
+```
+### Module einbinden, heisst ihre Methoden an die Instanzen der Klasse zu binden
+### Module erweitern, heisst ihre Mothden an die Klasse selbst zu binden
+```
+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'
+```
+### Callbacks werden ausgeführt, wenn ein Modul eingebunden oder erweitert wird
+```
+ 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'
+```
+
+## Weiterführende Hinweise
+
+//EN
+
+- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.
+- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/)
+- [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.
diff --git a/de-de/ruby-ecosystem-de.html.markdown b/de-de/ruby-ecosystem-de.html.markdown
new file mode 100644
index 00000000..a7e1f75f
--- /dev/null
+++ b/de-de/ruby-ecosystem-de.html.markdown
@@ -0,0 +1,149 @@
+---
+category: tool
+tool: ruby ecosystem
+contributors:
+ - ["Jon Smock", "http://github.com/jonsmock"]
+ - ["Rafal Chmiel", "http://github.com/rafalchmiel"]
+translators:
+ - ["Christian Albrecht", "https://github.com/coastalchief"]
+filename: ruby-ecosystem-de.txt
+lang: de-de
+---
+
+Hier gibt es einen Überblick über die gängigsten Tools zur Verwaltung
+von verschiedenen Ruby Versionen, Gems und Dependencies.
+
+## Ruby Managers
+
+Einige Betriebssysteme haben bereits eine Ruby Version vorinstalliert
+oder bieten sie als Package zum Download an. Die meisten Rubyisten
+benutzen diese aber eher nicht und wenn, dann um damit einen Ruby
+Manager zu installieren. Damit kann man komfortabel zwischen den
+verschiedenen Versionen hin und herspringen.
+
+Dies sind die beliebtesten:
+
+* [RVM](https://rvm.io/) - Installiert und wechselt zwischen rubies
+ RVM kennt verschiedene Ruby Versionen und hat das Konzept der gemsets,
+ um gem Abhängigkeiten pro Projekt zu managen.
+* [ruby-build](https://github.com/sstephenson/ruby-build)
+ Installiert nur rubies, kann diese aber sehr gut verwalten
+* [rbenv](https://github.com/sstephenson/rbenv) - Wechselt Ruby Versionen.
+ Wird zusammen mit ruby-build benutzt. Hiermit kann man kontrollieren,
+ wie rubies laden.
+* [chruby](https://github.com/postmodern/chruby) - Wechselt Ruby Versionen.
+ Ähnlich rbenv.
+
+## Ruby Versionen
+
+Ruby wurde von Yukihiro "Matz" Matsumoto vor gut 20 Jahren veröffentlicht.
+Matz ist nach wie vor in die Entwicklung involviert. Daher kommt auch der
+Name der Referenzimplementierung: MRI (Matz' Reference Implementation).
+
+Die aktuellste Version ist **2.2.3** und wurde im August 2015 veröffentlicht!
+
+Hier eine kurze Versionshistorie:
+
+* 2.0.0 - Release im Februar 2013 -- Release zum 20. Geburtstag der Sprache
+ [Rubies are forever](http://www.heise.de/developer/artikel/Ruby-2-0-als-Geschenk-zum-20-Geburtstag-1808109.html)
+* 1.9.3 - Release im Oktober 2011
+ [End of Life](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/)
+* 1.8.7 - Release im Juni 2006
+ [End of Life](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/).
+
+Die Veränderung zwischen 1.8.7 und 1.9.x war sehr groß und eine Migration
+nicht so einfach möglich. Der Versionssprung auf 2.0.0 war verglichen dazu
+weit weniger dramatisch.
+Beispielsweise hat 1.9. Encodings und eine Bytecode VM eingeführt.
+Es gibt immer noch Projekte die auf der stabilen Version 1.8.7 laufen,
+aber diese sind mittlerweile in der Minderheit. Die meisten Projekte
+laufen auf 1.9.x oder auf 2.x.
+
+## Ruby Implementierungen
+
+Das Ruby Ecosystem beinhaltet viele verschiedene Implementierungen von Ruby,
+jedes mit seinen eigenen Vorteilen und verschiedenen Graden von
+Kompatibilität. Auch wenn alle diese Implementierungen in verschiedenen
+Sprachen geschrieben sind, sind sie doch **alle Ruby**.
+Jede Implementierung bietet neben ihren speziellen Features immer auch
+die Möglichkeit normale ruby Dateien auszuführen.
+
+Am ausgereiftesten und stabilsten:
+
+* [MRI](https://github.com/ruby/ruby) - Geschrieben in C, das ist die Referenz Implementierung.
+ Sie ist 100% kompatibel (mit sich selbst ;-). Alle anderen rubies
+ bleiben kompatibel mit MRI (siehe [RubySpec](#rubyspec) weiter unten).
+* [JRuby](http://jruby.org/) - Geschrieben in Java and Ruby, Robust und ziemlich schnell.
+ Der größte Vorteil von JRuby ist die Interoperabilität mit JVM/Java und damit die
+ Benutzung von Ruby im Java Ecosystem.
+* [Rubinius](http://rubini.us/) - Geschrieben in Ruby mit C++ bytecode VM.
+ Auch sehr ausgereift und schnell.
+
+Mittel ausgereift / kompatibel:
+
+* [Maglev](http://maglev.github.io/) - Baut auf Gemstone, ein Smalltalk VM.
+ Dieses Projekt versucht das großartige Smalltalk Tooling in die Ruby Welt
+ zu bringen.
+* [RubyMotion](http://www.rubymotion.com/) - Ruby in der iOS Entwicklung.
+
+Weniger ausgereift/kompatibel:
+
+* [Topaz](http://topazruby.com/) - Geschrieben in RPython (via PyPy)
+ Topaz ist noch ziemlich jung und versucht die schnellste Implementierung
+ zu werden.
+* [IronRuby](http://ironruby.net/) - Geschrieben in C# für die .NET Plaftform
+ Das letzte Release von IronRuby ist mittlerweile 5 Jahre her.
+
+Die Ruby Implementierungen haben ihre eigenen Versionsnummern, sind aber
+trotzdem immer zu einer MRI Version kompatibel.
+Viele können sogar zwischen verschiedenen Modi wechseln (1.8 mode -> 1.9 mode)
+
+## RubySpec
+
+Die meisten Ruby Implementierungen vertrauen der [RubySpec](http://rubyspec.org/).
+sehr stark. Da Ruby keine offizielle Spezifikation hat, hat die
+Community ausführbare Specs (in Ruby) geschrieben, um so die Kompatibilität
+zur MRI testen zu können.
+
+## RubyGems
+
+[RubyGems](http://rubygems.org/) ist der Community Paket Manager von Ruby.
+RubyGems kommt mit Ruby zusammen, so dass kein extra Tool nötig ist.
+
+Ruby Pakete werden "gems" genannt und könnten auf RubyGems.org
+veröffentlicht werden. Jedes Gem enthält den Source Code und Meta Daten,
+wie die Versionsnummer, weitere Abhängigkeiten, Autoren und Lizenzen.
+
+## Bundler
+
+[Bundler](http://bundler.io/) ist ein Tool um Abhängigkeiten zwischen
+Gems aufzulösen und zu managen. Dazu werden diese in einem gemfile
+zusammengefasst und Bundler kümmert sich darum die Abhängigkeiten
+untereinander rekursiv aufzulösen. Entweder es klappt und alle gems
+konnten runtergeladen werden, oder es wird abgebrochen und
+der Konflikt gemeldet.
+Zum Beispiel:
+Wenn Gem A die Version 3 oder höher von Gem Z braucht, aber Gem B
+von Gem Z die Version 2, dann ist das ein Konflikt.
+
+# Testing
+
+Test-Driven Development ist ein essentieller Teil der Ruby Kultur.
+Ruby bringt sein eigenes Unit-Test framework mit, minitest. Darüberhinaus
+gibt es noch viele weitere Testframeworks mit unterschiedlichsten Zielen:
+
+* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - Eingebaut in Ruby 1.8
+ "Unit-style" Testframework
+* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - Eingebaut in Ruby 1.9/2.0
+ "Unit-style" Testframework
+* [RSpec](http://rspec.info/) - Ein Testframework welches auf verständliche Testdefinition setzt
+* [Cucumber](http://cukes.info/) - Ein BDD Testframework welches Gherkin tests parsen kann
+
+## Be Nice
+Die Ruby Community ist stolz darauf eine offene, vielfältige und einladende
+Community zu sein. Es gibt viele aktive Ruby User Gruppen und diverse
+Ruby Konferenzen. Matz selbst ist so oft es geht dabei.
+
+* [Euruko](http://www.euruko2015.org)
+* [User Groups](https://www.ruby-lang.org/de/community/user-groups/)
+
diff --git a/de-de/scala-de.html.markdown b/de-de/scala-de.html.markdown
new file mode 100644
index 00000000..456403a2
--- /dev/null
+++ b/de-de/scala-de.html.markdown
@@ -0,0 +1,840 @@
+---
+language: Scala
+contributors:
+ - ["George Petrov", "http://github.com/petrovg"]
+ - ["Dominic Bou-Samra", "http://dbousamra.github.com"]
+ - ["Geoff Liu", "http://geoffliu.me"]
+ - ["Ha-Duong Nguyen", "http://reference-error.org"]
+ - ["Dennis Keller", "github.com/denniskeller"]
+translators:
+ - ["Christian Albrecht", "https://github.com/coastalchief"]
+filename: learnscala-de.scala
+lang: de-de
+---
+
+Scala ist eine funktionale und objektorientierte Programmiersprache
+für die Java Virtual Machine (JVM), um allgemeine Programmieraufgaben
+zu erledigen. Scala hat einen akademischen Hintergrund und wurde an
+der EPFL (Lausanne / Schweiz) unter der Leitung von Martin Odersky entwickelt.
+
+```scala
+/*
+Scala Umgebung einrichten:
+
+1. Scala binaries herunterladen- http://www.scala-lang.org/downloads
+2. Unzip/untar in ein Verzeichnis
+3. das bin Unterverzeichnis der `PATH` Umgebungsvariable hinzufügen
+4. Mit dem Kommando `scala` wird die REPL gestartet und zeigt als Prompt:
+
+scala>
+
+Die REPL (Read-Eval-Print Loop) ist der interaktive Scala Interpreter.
+Hier kann man jeden Scala Ausdruck verwenden und das Ergebnis wird direkt
+ausgegeben.
+Als nächstes beschäftigen wir uns mit ein paar Scala Basics.
+*/
+
+
+/////////////////////////////////////////////////
+// 1. Basics
+/////////////////////////////////////////////////
+
+// Einzeilige Kommentare beginnen mit zwei Slashes
+
+/*
+ Mehrzeilige Kommentare, starten
+ mit einem Slash-Stern und enden mit einem Stern-Slash
+*/
+
+// Einen Wert, und eine zusätzliche neue Zeile ausgeben
+
+println("Hello world!")
+println(10)
+
+
+// Einen Wert, ohne eine zusätzliche neue Zeile ausgeben
+
+print("Hello world")
+
+/*
+ Variablen werden entweder mit var oder val deklariert.
+ Deklarationen mit val sind immutable, also unveränderlich
+ Deklarationen mit var sind mutable, also veränderlich
+ Immutability ist gut.
+*/
+val x = 10 // x ist 10
+x = 20 // error: reassignment to val
+var y = 10
+y = 20 // y ist jetzt 20
+
+/*
+Scala ist eine statisch getypte Sprache, auch wenn wir in dem o.g. Beispiel
+keine Typen an x und y geschrieben haben.
+In Scala ist etwas eingebaut, was sich Type Inference nennt. Das heißt das der
+Scala Compiler in den meisten Fällen erraten kann, von welchen Typ eine Variable ist,
+so dass der Typ nicht jedes mal angegeben werden muss.
+Einen Typ gibt man bei einer Variablendeklaration wie folgt an:
+*/
+val z: Int = 10
+val a: Double = 1.0
+
+
+// Bei automatischer Umwandlung von Int auf Double wird aus 10 eine 10.0
+
+val b: Double = 10
+
+
+// Boolean Werte
+
+true
+false
+
+
+// Boolean Operationen
+
+!true // false
+!false // true
+true == false // false
+10 > 5 // true
+
+
+// Mathematische Operationen sind wie gewohnt
+
+1 + 1 // 2
+2 - 1 // 1
+5 * 3 // 15
+6 / 2 // 3
+6 / 4 // 1
+6.0 / 4 // 1.5
+
+
+// Die Auswertung eines Ausdrucks in der REPL gibt den Typ
+// und das Ergebnis zurück.
+
+ scala> 1 + 7
+ res29: Int = 8
+
+/*
+Das bedeutet, dass das Resultat der Auswertung von 1 + 7 ein Objekt
+von Typ Int ist und einen Wert 0 hat.
+"res29" ist ein sequentiell generierter name, um das Ergebnis des
+Ausdrucks zu speichern. Dieser Wert kann bei Dir anders sein...
+*/
+
+"Scala strings werden in doppelten Anführungszeichen eingeschlossen"
+'a' // A Scala Char
+// 'Einzeln ge-quotete strings gibt es nicht!' <= This causes an error
+
+// Für Strings gibt es die üblichen Java Methoden
+
+"hello world".length
+"hello world".substring(2, 6)
+"hello world".replace("C", "3")
+
+
+// Zusätzlich gibt es noch extra Scala Methoden
+// siehe: scala.collection.immutable.StringOps
+
+"hello world".take(5)
+"hello world".drop(5)
+
+
+// String interpolation: prefix "s"
+
+val n = 45
+s"We have $n apples" // => "We have 45 apples"
+
+
+// Ausdrücke im Innern von interpolierten Strings gibt es auch
+
+val a = Array(11, 9, 6)
+val n = 100
+s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old."
+s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples."
+s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4"
+
+
+// Formatierung der interpolierten Strings mit dem prefix "f"
+
+f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25"
+f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454"
+
+
+// Raw Strings, ignorieren Sonderzeichen.
+
+raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r."
+
+
+// Manche Zeichen müssen "escaped" werden, z.B.
+// ein doppeltes Anführungszeichen in innern eines Strings.
+
+"They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown""
+
+
+// Dreifache Anführungszeichen erlauben es, dass ein String über mehrere Zeilen geht
+// und Anführungszeichen enthalten kann.
+
+val html = """<form id="daform">
+ <p>Press belo', Joe</p>
+ <input type="submit">
+ </form>"""
+
+
+/////////////////////////////////////////////////
+// 2. Funktionen
+/////////////////////////////////////////////////
+
+// Funktionen werden so definiert
+//
+// def functionName(args...): ReturnType = { body... }
+//
+// Beachte: Es gibt kein return Schlüsselwort. In Scala ist der letzte Ausdruck
+// in einer Funktion der Rückgabewert.
+
+def sumOfSquares(x: Int, y: Int): Int = {
+ val x2 = x * x
+ val y2 = y * y
+ x2 + y2
+}
+
+
+// Die geschweiften Klammern können weggelassen werden, wenn
+// die Funktion nur aus einem einzigen Ausdruck besteht:
+
+def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y
+
+
+// Syntax für Funktionsaufrufe:
+
+sumOfSquares(3, 4) // => 25
+
+
+// In den meisten Fällen (mit Ausnahme von rekursiven Funktionen), können
+// Rückgabetypen auch weggelassen werden, da dieselbe Typ Inference, wie bei
+// Variablen, auch bei Funktionen greift:
+
+def sq(x: Int) = x * x // Compiler errät, dass der return type Int ist
+
+
+// Funktionen können default parameter haben:
+
+def addWithDefault(x: Int, y: Int = 5) = x + y
+addWithDefault(1, 2) // => 3
+addWithDefault(1) // => 6
+
+
+// Anonyme Funktionen sehen so aus:
+
+(x: Int) => x * x
+
+
+// Im Gegensatz zu def bei normalen Funktionen, kann bei anonymen Funktionen
+// sogar der Eingabetyp weggelassen werden, wenn der Kontext klar ist.
+// Beachte den Typ "Int => Int", dies beschreibt eine Funktion,
+// welche Int als Parameter erwartet und Int zurückgibt.
+
+val sq: Int => Int = x => x * x
+
+
+// Anonyme Funktionen benutzt man ganz normal:
+
+sq(10) // => 100
+
+
+// Wenn ein Parameter einer anonymen Funktion nur einmal verwendet wird,
+// bietet Scala einen sehr kurzen Weg diesen Parameter zu benutzen,
+// indem die Parameter als Unterstrich "_" in der Parameterreihenfolge
+// verwendet werden. Diese anonymen Funktionen werden sehr häufig
+// verwendet.
+
+val addOne: Int => Int = _ + 1
+val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3)
+addOne(5) // => 6
+weirdSum(2, 4) // => 16
+
+
+// Es gibt einen keyword return in Scala. Allerdings ist seine Verwendung
+// nicht immer ratsam und kann fehlerbehaftet sein. "return" gibt nur aus
+// dem innersten def, welches den return Ausdruck umgibt, zurück.
+// "return" hat keinen Effekt in anonymen Funktionen:
+
+def foo(x: Int): Int = {
+ val anonFunc: Int => Int = { z =>
+ if (z > 5)
+ return z // Zeile macht z zum return Wert von foo
+ else
+ z + 2 // Zeile ist der return Wert von anonFunc
+ }
+ anonFunc(x) // Zeile ist der return Wert von foo
+}
+
+
+/////////////////////////////////////////////////
+// 3. Flow Control
+/////////////////////////////////////////////////
+
+// Wertebereiche und Schleifen
+
+1 to 5
+val r = 1 to 5
+r.foreach(println)
+r foreach println
+(5 to 1 by -1) foreach (println)
+
+// Scala ist syntaktisch sehr großzügig, Semikolons am Zeilenende
+// sind optional, beim Aufruf von Methoden können die Punkte
+// und Klammern entfallen und Operatoren sind im Grunde austauschbare Methoden
+
+// while Schleife
+
+var i = 0
+while (i < 10) { println("i " + i); i += 1 }
+i // i ausgeben, res3: Int = 10
+
+
+// Beachte: while ist eine Schleife im klassischen Sinne -
+// Sie läuft sequentiell ab und verändert die loop-Variable.
+// While in Scala läuft schneller ab als in Java und die o.g.
+// Kombinatoren und Zusammenlegungen sind einfacher zu verstehen
+// und zu parellelisieren.
+
+// Ein do while Schleife
+
+do {
+ println("x ist immer noch weniger wie 10")
+ x += 1
+} while (x < 10)
+
+
+// Endrekursionen sind ideomatisch um sich wiederholende
+// Dinge in Scala zu lösen. Rekursive Funtionen benötigen explizit einen
+// return Typ, der Compiler kann ihn nicht erraten.
+// Unit, in diesem Beispiel.
+
+def showNumbersInRange(a: Int, b: Int): Unit = {
+ print(a)
+ if (a < b)
+ showNumbersInRange(a + 1, b)
+}
+showNumbersInRange(1, 14)
+
+
+// Conditionals
+
+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")
+println(if (x == 10) "yeah" else "nope")
+val text = if (x == 10) "yeah" else "nope"
+
+
+/////////////////////////////////////////////////
+// 4. Daten Strukturen (Array, Map, Set, Tuples)
+/////////////////////////////////////////////////
+
+// Array
+
+val a = Array(1, 2, 3, 5, 8, 13)
+a(0)
+a(3)
+a(21) // Exception
+
+
+// Map - Speichert Key-Value-Paare
+
+val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo")
+m("fork")
+m("spoon")
+m("bottle") // Exception
+val safeM = m.withDefaultValue("no lo se")
+safeM("bottle")
+
+// Set - Speichert Unikate, unsortiert (sortiert -> SortedSet)
+
+val s = Set(1, 3, 7)
+s(0) //false
+s(1) //true
+val s = Set(1,1,3,3,7)
+s: scala.collection.immutable.Set[Int] = Set(1, 3, 7)
+
+// Tuple - Speichert beliebige Daten und "verbindet" sie miteinander
+// Ein Tuple ist keine Collection.
+
+(1, 2)
+(4, 3, 2)
+(1, 2, "three")
+(a, 2, "three")
+
+
+// Hier ist der Rückgabewert der Funktion ein Tuple
+// Die Funktion gibt das Ergebnis, so wie den Rest zurück.
+
+val divideInts = (x: Int, y: Int) => (x / y, x % y)
+divideInts(10, 3)
+
+
+// Um die Elemente eines Tuples anzusprechen, benutzt man diese
+// Notation: _._n wobei n der index des Elements ist (Index startet bei 1)
+
+val d = divideInts(10, 3)
+d._1
+d._2
+
+
+/////////////////////////////////////////////////
+// 5. Objektorientierte Programmierung
+/////////////////////////////////////////////////
+
+/*
+ Bislang waren alle gezeigten Sprachelemente einfache Ausdrücke, welche zwar
+ zum Ausprobieren und Lernen in der REPL gut geeignet sind, jedoch in
+ einem Scala file selten alleine zu finden sind.
+ Die einzigen Top-Level Konstrukte in Scala sind nämlich:
+
+ - Klassen (classes)
+ - Objekte (objects)
+ - case classes
+ - traits
+
+ Diesen Sprachelemente wenden wir uns jetzt zu.
+*/
+
+// Klassen
+
+// Zum Erstellen von Objekten benötigt man eine Klasse, wie in vielen
+// anderen Sprachen auch.
+
+// erzeugt Klasse mit default Konstruktor
+
+class Hund
+scala> val t = new Hund
+t: Hund = Hund@7103745
+
+
+// Der Konstruktor wird direkt hinter dem Klassennamen deklariert.
+
+class Hund(sorte: String)
+scala> val t = new Hund("Dackel")
+t: Hund = Hund@14be750c
+scala> t.sorte //error: value sorte is not a member of Hund
+
+
+// Per val wird aus dem Attribut ein unveränderliches Feld der Klasse
+// Per var wird aus dem Attribut ein veränderliches Feld der Klasse
+
+class Hund(val sorte: String)
+scala> val t = new Hund("Dackel")
+t: Hund = Hund@74a85515
+scala> t.sorte
+res18: String = Dackel
+
+
+// Methoden werden mit def geschrieben
+
+def bark = "Woof, woof!"
+
+
+// Felder und Methoden können public, protected und private sein
+// default ist public
+// private ist nur innerhalb des deklarierten Bereichs sichtbar
+
+class Hund {
+ private def x = ...
+ def y = ...
+}
+
+
+// protected ist nur innerhalb des deklarierten und aller
+// erbenden Bereiche sichtbar
+
+class Hund {
+ protected def x = ...
+}
+class Dackel extends Hund {
+ // x ist sichtbar
+}
+
+// Object
+// Wird ein Objekt ohne das Schlüsselwort "new" instanziert, wird das sog.
+// "companion object" aufgerufen. Mit dem "object" Schlüsselwort wird so
+// ein Objekt (Typ UND Singleton) erstellt. Damit kann man dann eine Klasse
+// benutzen ohne ein Objekt instanziieren zu müssen.
+// Ein gültiges companion Objekt einer Klasse ist es aber erst dann, wenn
+// es genauso heisst und in derselben Datei wie die Klasse definiert wurde.
+
+object Hund {
+ def alleSorten = List("Pitbull", "Dackel", "Retriever")
+ def createHund(sorte: String) = new Hund(sorte)
+}
+
+// Case classes
+// Fallklassen bzw. Case classes sind Klassen die normale Klassen um extra
+// Funktionalität erweitern. Mit Case Klassen bekommt man ein paar
+// Dinge einfach dazu, ohne sich darum kümmern zu müssen. Z.B.
+// ein companion object mit den entsprechenden Methoden,
+// Hilfsmethoden wie toString(), equals() und hashCode() und auch noch
+// Getter für unsere Attribute (das Angeben von val entfällt dadurch)
+
+class Person(val name: String)
+class Hund(val sorte: String, val farbe: String, val halter: Person)
+
+
+// Es genügt das Schlüsselwort case vor die Klasse zu schreiben.
+
+case class Person(name: String)
+case class Hund(sorte: String, farbe: String, halter: Person)
+
+
+// Für neue Instanzen brauch man kein "new"
+
+val dackel = Hund("dackel", "grau", Person("peter"))
+val dogge = Hund("dogge", "grau", Person("peter"))
+
+
+// getter
+
+dackel.halter // => Person = Person(peter)
+
+
+// equals
+
+dogge == dackel // => false
+
+
+// copy
+// otherGeorge == Person("george", "9876")
+
+val otherGeorge = george.copy(phoneNumber = "9876")
+
+// Traits
+// Ähnlich wie Java interfaces, definiert man mit traits einen Objekttyp
+// und Methodensignaturen. Scala erlaubt allerdings das teilweise
+// implementieren dieser Methoden. Konstruktorparameter sind nicht erlaubt.
+// Traits können von anderen Traits oder Klassen erben, aber nur von
+// parameterlosen.
+
+trait Hund {
+ def sorte: String
+ def farbe: String
+ def bellen: Boolean = true
+ def beissen: Boolean
+}
+class Bernhardiner extends Hund{
+ val sorte = "Bernhardiner"
+ val farbe = "braun"
+ def beissen = false
+}
+
+
+
+scala> b
+res0: Bernhardiner = Bernhardiner@3e57cd70
+scala> b.sorte
+res1: String = Bernhardiner
+scala> b.bellen
+res2: Boolean = true
+scala> b.beissen
+res3: Boolean = false
+
+
+// Traits können auch via Mixins (Schlüsselwort "with") eingebunden werden
+
+trait Bellen {
+ def bellen: String = "Woof"
+}
+trait Hund {
+ def sorte: String
+ def farbe: String
+}
+class Bernhardiner extends Hund with Bellen{
+ val sorte = "Bernhardiner"
+ val farbe = "braun"
+}
+scala> val b = new Bernhardiner
+b: Bernhardiner = Bernhardiner@7b69c6ba
+scala> b.bellen
+res0: String = Woof
+
+/////////////////////////////////////////////////
+// 6. Pattern Matching
+/////////////////////////////////////////////////
+
+// Pattern matching in Scala ist ein sehr nützliches und wesentlich
+// mächtigeres Feature als Vergleichsfunktionen in Java. In Scala
+// benötigt ein case Statement kein "break", ein fall-through gibt es nicht.
+// Mehrere Überprüfungen können mit einem Statement gemacht werden.
+// Pattern matching wird mit dem Schlüsselwort "match" gemacht.
+
+val x = ...
+x match {
+ case 2 =>
+ case 3 =>
+ case _ =>
+}
+
+
+// Pattern Matching kann auf beliebige Typen prüfen
+
+val any: Any = ...
+val gleicht = any match {
+ case 2 | 3 | 5 => "Zahl"
+ case "woof" => "String"
+ case true | false => "Boolean"
+ case 45.35 => "Double"
+ case _ => "Unbekannt"
+}
+
+
+// und auf Objektgleichheit
+
+def matchPerson(person: Person): String = person match {
+ case Person("George", nummer) => "George! Die Nummer ist " + number
+ case Person("Kate", nummer) => "Kate! Die Nummer ist " + nummer
+ case Person(name, nummer) => "Irgendjemand: " + name + ", Telefon: " + nummer
+}
+
+
+// Und viele mehr...
+
+val email = "(.*)@(.*)".r // regex
+def matchEverything(obj: Any): String = obj match {
+ // Werte:
+ case "Hello world" => "Got the string Hello world"
+ // Typen:
+ case x: Double => "Got a Double: " + x
+ // Conditions:
+ case x: Int if x > 10000 => "Got a pretty big number!"
+ // Case Classes:
+ case Person(name, number) => s"Got contact info for $name!"
+ // RegEx:
+ case email(name, domain) => s"Got email address $name@$domain"
+ // Tuples:
+ case (a: Int, b: Double, c: String) => s"Got a tuple: $a, $b, $c"
+ // Strukturen:
+ case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c"
+ // Patterns kann man ineinander schachteln:
+ case List(List((1, 2, "YAY"))) => "Got a list of list of tuple"
+}
+
+
+// Jedes Objekt mit einer "unapply" Methode kann per Pattern geprüft werden
+// Ganze Funktionen können Patterns sein
+
+val patternFunc: Person => String = {
+ case Person("George", number) => s"George's number: $number"
+ case Person(name, number) => s"Random person's number: $number"
+}
+
+
+/////////////////////////////////////////////////
+// 37. Higher-order functions
+/////////////////////////////////////////////////
+
+Scala erlaubt, das Methoden und Funktion wiederum Funtionen und Methoden
+als Aufrufparameter oder Return Wert verwenden. Diese Methoden heissen
+higher-order functions
+Es gibt zahlreiche higher-order functions nicht nur für Listen, auch für
+die meisten anderen Collection Typen, sowie andere Klassen in Scala
+Nennenswerte sind:
+"filter", "map", "reduce", "foldLeft"/"foldRight", "exists", "forall"
+
+## List
+
+def isGleichVier(a:Int) = a == 4
+val list = List(1, 2, 3, 4)
+val resultExists4 = list.exists(isEqualToFour)
+
+
+## map
+// map nimmt eine Funktion und führt sie auf jedem Element aus und erzeugt
+// eine neue Liste
+
+// Funktion erwartet ein Int und returned ein Int
+
+val add10: Int => Int = _ + 10
+
+
+// add10 wird auf jedes Element angewendet
+
+List(1, 2, 3) map add10 // => List(11, 12, 13)
+
+
+// Anonyme Funktionen können anstatt definierter Funktionen verwendet werden
+
+List(1, 2, 3) map (x => x + 10)
+
+
+// Der Unterstrich wird anstelle eines Parameters einer anonymen Funktion
+// verwendet. Er wird an die Variable gebunden.
+
+List(1, 2, 3) map (_ + 10)
+
+
+// Wenn der anonyme Block und die Funtion beide EIN Argument erwarten,
+// kann sogar der Unterstrich weggelassen werden.
+
+List("Dom", "Bob", "Natalia") foreach println
+
+
+// filter
+// filter nimmt ein Prädikat (eine Funktion von A -> Boolean) und findet
+// alle Elemente die auf das Prädikat passen
+
+List(1, 2, 3) filter (_ > 2) // => List(3)
+case class Person(name: String, age: Int)
+List(
+ Person(name = "Dom", age = 23),
+ Person(name = "Bob", age = 30)
+).filter(_.age > 25) // List(Person("Bob", 30))
+
+
+// reduce
+// reduce nimmt zwei Elemente und kombiniert sie zu einem Element,
+// und zwar solange bis nur noch ein Element da ist.
+
+// foreach
+// foreach gibt es für einige Collections
+
+val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100)
+aListOfNumbers foreach (x => println(x))
+aListOfNumbers foreach println
+
+// For comprehensions
+// Eine for-comprehension definiert eine Beziehung zwischen zwei Datensets.
+// Dies ist keine for-Schleife.
+
+for { n <- s } yield sq(n)
+val nSquared2 = for { n <- s } yield sq(n)
+for { n <- nSquared2 if n < 10 } yield n
+for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared
+
+
+/////////////////////////////////////////////////
+// 8. Implicits
+/////////////////////////////////////////////////
+
+// **ACHTUNG:**
+// Implicits sind ein sehr mächtiges Sprachfeature von Scala.
+// Es sehr einfach
+// sie falsch zu benutzen und Anfänger sollten sie mit Vorsicht oder am
+// besten erst dann benutzen, wenn man versteht wie sie funktionieren.
+// Dieses Tutorial enthält Implicits, da sie in Scala an jeder Stelle
+// vorkommen und man auch mit einer Lib die Implicits benutzt nichts sinnvolles
+// machen kann.
+// Hier soll ein Grundverständnis geschaffen werden, wie sie funktionieren.
+
+// Mit dem Schlüsselwort implicit können Methoden, Werte, Funktion, Objekte
+// zu "implicit Methods" werden.
+
+implicit val myImplicitInt = 100
+implicit def myImplicitFunction(sorte: String) = new Hund("Golden " + sorte)
+
+
+// implicit ändert nicht das Verhalten eines Wertes oder einer Funktion
+
+myImplicitInt + 2 // => 102
+myImplicitFunction("Pitbull").sorte // => "Golden Pitbull"
+
+
+// Der Unterschied ist, dass diese Werte ausgewählt werden können, wenn ein
+// anderer Codeteil einen implicit Wert benötigt, zum Beispiel innerhalb von
+// implicit Funktionsparametern
+
+// Diese Funktion hat zwei Parameter: einen normalen und einen implicit
+
+def sendGreetings(toWhom: String)(implicit howMany: Int) =
+ s"Hello $toWhom, $howMany blessings to you and yours!"
+
+
+// Werden beide Parameter gefüllt, verhält sich die Funktion wie erwartet
+
+sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!"
+
+
+// Wird der implicit Parameter jedoch weggelassen, wird ein anderer
+// implicit Wert vom gleichen Typ genommen. Der Compiler sucht im
+// lexikalischen Scope und im companion object nach einem implicit Wert,
+// der vom Typ passt, oder nach einer implicit Methode mit der er in den
+// geforderten Typ konvertieren kann.
+
+// Hier also: "myImplicitInt", da ein Int gesucht wird
+
+sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!"
+
+
+// bzw. "myImplicitFunction"
+// Der String wird erst mit Hilfe der Funktion in Hund konvertiert, und
+// dann wird die Methode aufgerufen
+
+"Retriever".sorte // => "Golden Retriever"
+
+
+/////////////////////////////////////////////////
+// 19. Misc
+/////////////////////////////////////////////////
+// Importe
+
+import scala.collection.immutable.List
+
+
+// Importiere alle Unterpackages
+
+import scala.collection.immutable._
+
+
+// Importiere verschiedene Klassen mit einem Statement
+
+import scala.collection.immutable.{List, Map}
+
+
+// Einen Import kann man mit '=>' umbenennen
+
+import scala.collection.immutable.{List => ImmutableList}
+
+
+// Importiere alle Klasses, mit Ausnahem von....
+// Hier ohne: Map and Set:
+
+import scala.collection.immutable.{Map => _, Set => _, _}
+
+// Main
+
+object Application {
+ def main(args: Array[String]): Unit = {
+ // Sachen kommen hierhin
+ }
+}
+
+
+// I/O
+// Eine Datei Zeile für Zeile lesen
+
+import scala.io.Source
+for(line <- Source.fromFile("myfile.txt").getLines())
+ println(line)
+
+
+// Eine Datei schreiben
+
+val writer = new PrintWriter("myfile.txt")
+writer.write("Schreibe Zeile" + util.Properties.lineSeparator)
+writer.write("Und noch eine Zeile" + util.Properties.lineSeparator)
+writer.close()
+
+```
+
+## Weiterführende Hinweise
+
+// DE
+* [Scala Tutorial](https://scalatutorial.wordpress.com)
+* [Scala Tutorial](http://scalatutorial.de)
+
+// EN
+* [Scala for the impatient](http://horstmann.com/scala/)
+* [Twitter Scala school](http://twitter.github.io/scala_school/)
+* [The scala documentation](http://docs.scala-lang.org/)
+* [Try Scala in your browser](http://scalatutorials.com/tour/)
+* [Neophytes Guide to Scala](http://danielwestheide.com/scala/neophytes.html)
+* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user)
diff --git a/de-de/yaml-de.html.markdown b/de-de/yaml-de.html.markdown
index 19ea9e87..a46c30f6 100644
--- a/de-de/yaml-de.html.markdown
+++ b/de-de/yaml-de.html.markdown
@@ -30,7 +30,7 @@ null_Wert: null
Schlüssel mit Leerzeichen: value
# Strings müssen nicht immer mit Anführungszeichen umgeben sein, können aber:
jedoch: "Ein String in Anführungzeichen"
-"Ein Schlüssel in Anführungszeichen": "Nützlich, wenn du einen Doppelpunkt im Schluessel haben willst."
+"Ein Schlüssel in Anführungszeichen": "Nützlich, wenn du einen Doppelpunkt im Schlüssel haben willst."
# Mehrzeilige Strings schreibst du am besten als 'literal block' (| gefolgt vom Text)
# oder ein 'folded block' (> gefolgt vom text).
@@ -64,7 +64,7 @@ eine_verschachtelte_map:
hallo: hallo
# Schlüssel müssen nicht immer String sein.
-0.25: ein Float-Wert als Schluessel
+0.25: ein Float-Wert als Schlüssel
# Schlüssel können auch mehrzeilig sein, ? symbolisiert den Anfang des Schlüssels
? |
diff --git a/edn.html.markdown b/edn.html.markdown
new file mode 100644
index 00000000..ca04df89
--- /dev/null
+++ b/edn.html.markdown
@@ -0,0 +1,108 @@
+---
+language: edn
+filename: learnedn.edn
+contributors:
+ - ["Jason Yeo", "https://github.com/jsyeo"]
+---
+
+Extensible Data Notation (EDN) is a format for serializing data.
+
+The notation is used internally by Clojure to represent programs. It is also
+used as a data transfer format like JSON. Though it is more commonly used in
+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
+; Comments start with a semicolon.
+; Anything after the semicolon is ignored.
+
+;;;;;;;;;;;;;;;;;;;
+;;; Basic Types ;;;
+;;;;;;;;;;;;;;;;;;;
+
+nil ; also known in other languages as null
+
+; Booleans
+true
+false
+
+; Strings are enclosed in double quotes
+"hungarian breakfast"
+"farmer's cheesy omelette"
+
+; Characters are preceeded by backslashes
+\g \r \a \c \e
+
+; Keywords start with a colon. They behave like enums. Kind of
+; like symbols in Ruby.
+:eggs
+:cheese
+:olives
+
+; Symbols are used to represent identifiers. They start with #.
+; You can namespace symbols by using /. Whatever preceeds / is
+; the namespace of the name.
+#spoon
+#kitchen/spoon ; not the same as #spoon
+#kitchen/fork
+#github/fork ; you can't eat with this
+
+; Integers and floats
+42
+3.14159
+
+; Lists are sequences of values
+(:bun :beef-patty 9 "yum!")
+
+; Vectors allow random access
+[:gelato 1 2 -2]
+
+; Maps are associative data structures that associate the key with its value
+{:eggs 2
+ :lemon-juice 3.5
+ :butter 1}
+
+; You're not restricted to using keywords as keys
+{[1 2 3 4] "tell the people what she wore",
+ [5 6 7 8] "the more you see the more you hate"}
+
+; You may use commas for readability. They are treated as whitespace.
+
+; Sets are collections that contain unique elements.
+#{:a :b 88 "huat"}
+
+;;;;;;;;;;;;;;;;;;;;;;;
+;;; Tagged Elements ;;;
+;;;;;;;;;;;;;;;;;;;;;;;
+
+; EDN can be extended by tagging elements with # symbols.
+
+#MyYelpClone/MenuItem {:name "eggs-benedict" :rating 10}
+
+; Let me explain this with a clojure example. Suppose I want to transform that
+; piece of EDN into a MenuItem record.
+
+(defrecord MenuItem [name rating])
+
+; To transform EDN to clojure values, I will need to use the built in EDN
+; reader, edn/read-string
+
+(edn/read-string "{:eggs 2 :butter 1 :flour 5}")
+; -> {:eggs 2 :butter 1 :flour 5}
+
+; To transform tagged elements, define the reader function and pass a map
+; that maps tags to reader functions to edn/read-string like so
+
+(edn/read-string {:readers {'MyYelpClone/MenuItem map->menu-item}}
+ "#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}")
+; -> #user.MenuItem{:name "eggs-benedict", :rating 10}
+
+```
+
+# References
+
+- [EDN spec](https://github.com/edn-format/edn)
+- [Implementations](https://github.com/edn-format/edn/wiki/Implementations)
+- [Tagged Elements](http://www.compoundtheory.com/clojure-edn-walkthrough/)
diff --git a/el-gr/css-gr.html.markdown b/el-gr/css-gr.html.markdown
new file mode 100644
index 00000000..327dc1a0
--- /dev/null
+++ b/el-gr/css-gr.html.markdown
@@ -0,0 +1,243 @@
+---
+language: css
+contributors:
+ - ["Kostas Bariotis", "http://kostasbariotis.com"]
+filename: css-gr.html.markdown
+lang: el-gr
+---
+
+Η αρχική μορφή του Παγκόσμιου Ιστού αποτελούταν απο καθαρό κείμενο, χωρίς οπτικά αντικείμενα. Με το πέρας
+του χρόνου και την εξέλιξη των Φυλλομετρητών, οι πλούσιες σελίδες, σε οπτικά και πολυμεσικά αντικείμενα,
+γίναν καθημερινότητα.
+
+Η CSS μας βοηθάει να διαχωρήσουμε το περιεχόμενο της σελίδας μας (HTML) απο την οπτική της περιγραφή.
+
+Με την CSS ορίζουμε οπτικές ιδιότητες (χρώμα, μέγεθος, κλπ) σε HTML αντικείμενα (H1, div, κλπ).
+
+```css
+/* Σχόλια εμφανίζονται εντός καθέτου-αστερίσκου, όπως εδώ.
+ Δεν υπάρχουν σχόλια μια γραμμής και πολλών. */
+
+/* ####################
+ ## ΚΑΝΟΝΕΣ
+ #################### */
+
+/* ένας κανόνας χρησιμοποιείτε για να στοχεύσουμε ένα αντικείμενο (selector).
+selector { property: value; /* περισσότερες ιδιότητες...*/ }
+
+/*
+Αυτό είναι ενα παράδειγμα αντικειμένου¨
+
+<div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' />
+*/
+
+/* Μπορούμε να το στοχεύσουμε με την χρήση CSS κλάσεων */
+.class1 { }
+
+/* Ή και με τις δύο κλάσεις! */
+.class1.class2 { }
+
+/* Και με το όνομα του */
+div { }
+
+/* Ή με το id του */
+#anID { }
+
+/* Ή με το γεγονός ότι περιέχει ενα attribute */
+[attr] { font-size:smaller; }
+
+/* Ή οτι το attribute αυτό έχει μια συγκεκριμένη τιμή */
+[attr='value'] { font-size:smaller; }
+
+/* Ξεκινάει απο το λεκτικό (CSS 3) */
+[attr^='val'] { font-size:smaller; }
+
+/* Καταλήγει σε αυτο το λεκτικό (CSS 3) */
+[attr$='ue'] { font-size:smaller; }
+
+/* Περιέχει κάποιο λεκτικό */
+[otherAttr~='foo'] { }
+[otherAttr~='bar'] { }
+
+/* περιέχει το λεκτικό σε λίστα χωρισμένη με παύλες, δηλαδή: "-" (U+002D) */
+[otherAttr|='en'] { font-size:smaller; }
+
+
+/* Μπορούμε να προσθέσουμε μεταξύ τους selectors για να δημιουργήσουμε πιο αυστηρούς.
+ Δεν βάζουμε κενά ανάμεσα. */
+div.some-class[attr$='ue'] { }
+
+/* Μπορούμε να επιλέξουμε αντικείμενα που βρίσκονται μέσα σε άλλα. */
+div.some-parent > .class-name { }
+
+/* Ή κάποιο αντικείμενο απόγονο ανεξαρτήτου του βάθους της σχέσης τους. */
+div.some-parent .class-name { }
+
+/* ΠΡΟΣΟΧΗ: ο ίδιος selector χωρίς κενά έχει άλλο νόημα. (Άσκηση προς τον αναγνώστη) */
+div.some-parent.class-name { }
+
+/* Μπορούμε να επιλέξουμε αντικείμενα με βάση το αμέσως επόμενο αντικείμενο στο ίδιο επίπεδο. */
+.i-am-just-before + .this-element { }
+
+/* Ή οποιοδήποτε αντικείμενο που προηγείται */
+.i-am-any-element-before ~ .this-element { }
+
+/* Με την βοήθεια των ψευδο-κλάσεων μπορούμε να επιλέξουμε αντικείμενα που βρίσκονται σε μια
+ ορισμένη κατάασταση. */
+
+/* π.χ. όταν ο κέρσορας είναι πάνω απο ένα αντικείμενο */
+selector:hover { }
+
+/* ή ένας υπερσύνδεσμος που πατήθηκε */
+selector:visited { }
+
+/* ή που δεν πατήθηκε */
+selected:link { }
+
+/* ή ένα αντικείμενο που επιλέχθηκε */
+selected:focus { }
+
+/* οποιοδήποτε αντικείμενο είναι το πρώτο παιδί των γονέων του */
+selector:first-child {}
+
+/* οποιοδήποτε αντικείμενο είναι το πρώτοτελευταίο παιδί των γονέων του */
+selector:last-child {}
+
+/* Όπως και με τις ψευδο-κλάσεις, τα ψευδο-αντικείμενα μας επιτρέπουν τα τροποοιήσουμε συγκεκριμένα
+ κομμάτια της σελίδας */
+
+/* επιλέγει το ψευδο-αντικείμενο ακριβώς πριν απο το αντικείμενο */
+selector::before {}
+
+/* επιλέγει το ψευδο-αντικείμενο ακριβώς μετά απο τον αντικείμενο */
+selector::after {}
+
+/* Σε σωστά σημεία (όχι πολύ ψηλά στην ιεραρχία) ο αστερίσκος μπορείς να χρησιμοποιηθεί για να
+ επιλέξουμε όλα τα αντικείμενα */
+* { } /* όλα τα αντικείμενα της σελίδας */
+.parent * { } /* όλους τους απόγονους */
+.parent > * { } /* όλους τους απόγονους πρώτου επιπέδου */
+
+/* ####################
+ ## Ιδιότητες
+ #################### */
+
+selector {
+
+ /* Οι μονάδες μπορούν να είναι είτε απόλυτες είτε σχετικές */
+
+ /* Σχετικές μονάδες */
+ width: 50%; /* ποσοστό επί του πλάτους του γονέα */
+ font-size: 2em; /* πολλαπλασιαστής της αρχικής τιμής του αντικειμένου */
+ font-size: 2rem; /* ή της τιμής του πρώτου αντικειμένου στην ιεραρχία */
+ font-size: 2vw; /* πολλαπλαστιαστής του 1% του οπτικού πλάτους */
+ font-size: 2vh; /* ή τους ύψους */
+ font-size: 2vmin; /* οποιοδήποτε απο αυτα τα δύο είναι το μικρότερο */
+ font-size: 2vmax; /* ή το μεγαλύτερο */
+
+ /* Απόλυτες μονάδες */
+ width: 200px; /* pixels */
+ font-size: 20pt; /* στιγμες */
+ width: 5cm; /* εκατοστά */
+ min-width: 50mm; /* χιλιοστά */
+ max-width: 5in; /* ίντσες */
+
+ /* Χρώματα */
+ color: #F6E; /* σύντομη δεκαεξαδική μορφή */
+ color: #FF66EE; /* δεκαεξαδική μορφή */
+ color: tomato; /* χρώμα με το όνομα του (συγκεκριμένα χρώματα) */
+ color: rgb(255, 255, 255); /* τιμή RGB */
+ color: rgb(10%, 20%, 50%); /* τιμή RGB με ποσοστά */
+ color: rgba(255, 0, 0, 0.3); /* τιμή RGBA (CSS3) σσ. 0 < a < 1 */
+ color: transparent; /* όπως και το παραπάνω με a = 0 */
+ color: hsl(0, 100%, 50%); /* τιμή hsl με ποσοστά (CSS 3) */
+ color: hsla(0, 100%, 50%, 0.3); /* τιμή hsla με ποσοστά και a */
+
+ /* Εικόνες μπορούν να τοποθετηθούν στον φόντο ενός αντικειμένου */
+ background-image: url(/img-path/img.jpg);
+
+ /* Γραμματοσειρές */
+ font-family: Arial;
+ /* εάν η γραμματοσειρα περιέχει κενά */
+ font-family: "Courier New";
+ /* εάν η πρώτη γραμματοσειρα δε βρεθεί εγκατεστημένη στο Λειτουργικό Σύστυμα, αυτόματα
+ επιλέγετε η δεύτερη, κ.κ.ε. */
+ font-family: "Courier New", Trebuchet, Arial, sans-serif;
+}
+```
+
+## Χρήση
+
+Αποθηκεύουμε ένα αρχείο CSS με την επέκταση `.css`.
+
+```xml
+<!-- Πρέπει να συμπεριλάβουμε το αρχείο στην επικεφαλίδα(head) ενος HTML αρχείου.
+ σσ. http://stackoverflow.com/questions/8284365 -->
+<link rel='stylesheet' type='text/css' href='path/to/style.css' />
+
+<!-- Μπορούμε να το ενσωματώσουμε -->
+<style>
+ a { color: purple; }
+</style>
+
+<!-- Ή απευθείας σε κάποιο αντικείμενο (inline) -->
+<div style="border: 1px solid red;">
+</div>
+```
+
+## Ειδικότητα των κανόνων (Cascading απο το αγγλικό τίτλο Cascading Style Sheets)
+
+Ένα αντικείμενο μπορεί να στοχευθεί απο πολλούς κανόνες και μπορεί η ίδια ιδιότητα να
+περιλαμβάνετε σε πολλούς κανόνες. Σε αυτές της περιπτώσεις υπερισχύει πάντα ο πιο ειδικός
+κανόνας και απο αυτούς, αυτός που εμφανίζεται τελευταίος.
+
+```css
+/* A */
+p.class1[attr='value']
+
+/* B */
+p.class1 { }
+
+/* C */
+p.class2 { }
+
+/* D */
+p { }
+
+/* E */
+p { property: value !important; }
+```
+
+```xml
+<p style='/*F*/ property:value;' class='class1 class2' attr='value' />
+```
+
+Η σειρά θα είναι:
+
+* `E` έχει μεγαλύτερο βάρος λόγω του `!important`. Κάλες πρακτικές λένε να το αποφεύγουμε.
+* `F` επόμενο λόγω του inline κανόνα.
+* `A` επόμενο λόγω του το οτι είναι πιο ειδικό. Περιέχει τρεις selectors.
+* `C` επόμενο, λόγω του οτι εμφανίζεται μετα το Β και ας έχει την ίδια ειδικότητα.
+* `B` επόμενο.
+* `D` τελευταίο.
+
+## Συμβατότητα
+
+Τα περισσότερα απο τα παραπάνω ήδη υποστηρίζονται απο τους γνωστούς φυλλομετρητές. Άλλα θα πρέπει
+πάντα να ελέγχουμε πρωτου τους χρησιμοποιήσουμε.
+
+## Περισσότερα
+
+* Έλεγχος συμβατότητας, [CanIUse](http://caniuse.com).
+* CSS Playground [Dabblet](http://dabblet.com/).
+* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS)
+* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/)
+
+## Μελέτη
+
+* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
+* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/)
+* [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)
+* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing
+* [CSS-Tricks](https://css-tricks.com)
diff --git a/el-gr/racket-gr.html.markdown b/el-gr/racket-gr.html.markdown
index 4c4576bb..589adfeb 100644
--- a/el-gr/racket-gr.html.markdown
+++ b/el-gr/racket-gr.html.markdown
@@ -31,12 +31,12 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ
;; Τα σχόλια S-expression (εκφράσεις S) comments απορρίπτουν την
;; έκφραση που ακολουθεί, δυνατότητα που είναι χρήσιμη για να
-;; κάνουμε σχόλια κάποιες εκφράσεις κατα τη διάρκεια του debugging
+;; κάνουμε σχόλια κάποιες εκφράσεις κατά τη διάρκεια του debugging
#; (αυτή η έκφραση δεν θα εκτελεστεί)
;; (Αν δεν καταλαβαίνεται τι είναι οι εκφράσεις , περιμένετε... Θα το μάθουμε
-;; πολύ συντομα!)
+;; πολύ σύντομα!)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@@ -57,8 +57,8 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ
;; όπου το f είναι η συνάρτηση και τα x y z
;; είναι οι όροι που η συνάρτηση δέχεται
;; ως ορίσματα. Αν θέλουμε να δημιουργήσουμε
-;; μια λίστα στην κυριολεξία απο δίαφορα δεδομένα,
-;; χρησιμοποιούμε το ' για να το εμποδίσουμε απο το να
+;; μια λίστα στην κυριολεξία από δίαφορα δεδομένα,
+;; χρησιμοποιούμε το ' για να το εμποδίσουμε από το να
;; αξιολογηθεί σαν έκφραση. Για παράδειγμα:
'(+ 1 2) ; => Παραμένει (+ 1 2) και δεν γίνεται η πράξη
;; Τώρα , ας κάνουμε μερικές πράξεις
@@ -88,15 +88,15 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ
;;; Τα αλφαριθμητικά είναι πίνακες χαρακτήρων συγκεκριμένου μήκους
"Hello, world!"
"Benjamin \"Bugsy\" Siegel" ; Το backslash είναι χαρακτήρας διαφυγής
-"Foo\tbar\41\x21\u0021\a\r\n" ; Συμπεριλαμβάνονται οι χαρακτήες διαφυγής της C,
+"Foo\tbar\41\x21\u0021\a\r\n" ; Συμπεριλαμβάνονται οι χαρακτήρες διαφυγής της C,
; σε Unicode
"λx:(μα.α→α).xx" ; Μπορούν να υπάρχουν και Unicode χαρακτήρες
-;; Μπορούμε να εννώσουμε αλφαριθμητικά!
+;; Μπορούμε να ενώσουμε αλφαριθμητικά!
(string-append "Hello " "world!") ; => "Hello world!"
-;; Ένα αλφαριθμητικό μπορούμε να το χρησιμοπιησουμε
-;; όπως και μια λίστα απο χαρακτήρες
+;; Ένα αλφαριθμητικό μπορούμε να το χρησιμοποιήσουμε
+;; όπως και μια λίστα από χαρακτήρες
(string-ref "Apple" 0) ; => #\A ;; Παίρνουμε το πρώτο στοιχείο
;; Η συνάρτηση format μπορεί να χρησιμοποιηθεί για
@@ -117,18 +117,18 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ
some-var ; => 5
;; Μπορούμε επίσης να χρησιμοποιήσουμε unicode χαρακτήρες.
-(define ⊆ subset?) ;; Εδώ ουστιαστικά δίνουμε στη ήδη ύπαρχουσα συνάρτηση subset?
+(define ⊆ subset?) ;; Εδώ ουσιαστικά δίνουμε στη ήδη υπάρχουσα συνάρτηση subset?
;; ένα νέο όνομα ⊆ , και παρακάτω την καλούμε με το νέο της όνομα.
(⊆ (set 3 2) (set 1 2 3)) ; => #t
-;; Αν ζητήσουμε μια μεταβλητή που δεν έχει οριστεί πρίν π.χ
+;; Αν ζητήσουμε μια μεταβλητή που δεν έχει οριστεί πριν π.χ.
(printf name)
;; θα πάρουμε το παρακάτω μήνυμα
;name: undefined;
; cannot reference undefined identifier
; context...:
-;; Η τοπική δέσμευση : `me' δευσμεύεται με το "Bob" μόνο μέσα στο (let ...)
+;; Η τοπική δέσμευση : `me' δεσμεύεται με το "Bob" μόνο μέσα στο (let ...)
(let ([me "Bob"])
"Alice"
me) ; => "Bob"
@@ -156,7 +156,7 @@ my-pet ; => #<dog>
;;; Λίστες
;; Οι λίστες είναι linked-list δομές δεδομένων,
-;; που έχουν δημιουργηθεί απο ζευγάρια 'cons'
+;; που έχουν δημιουργηθεί από ζευγάρια 'cons'
;; και τελειώνουν με 'null' (ή αλλιώς '()) για να
;; δηλώσουν ότι αυτό είναι το τέλος της λίστας
(cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3)
@@ -191,12 +191,12 @@ my-pet ; => #<dog>
;; Τα διανύσματα είναι πίνακες σταθερού μήκους
#(1 2 3) ; => '#(1 2 3)
-;; Χρησιμοποιύμε το `vector-append' για να προσθέσουμε διανύσματα
+;; Χρησιμοποιούμε το `vector-append' για να προσθέσουμε διανύσματα
(vector-append #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6)
;;; Σύνολα
-;; Δημιουργούμε ένα σύνολο απο μία λίστα
+;; Δημιουργούμε ένα σύνολο από μία λίστα
(list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3)
;; Προσθέτουμε έναν αριθμό στο σύνολο χρησιμοποιώντας το `set-add'
@@ -214,10 +214,10 @@ my-pet ; => #<dog>
;; Δημιουργήστε ένα αμετάβλητο πίνακα κατακερματισμού
(define m (hash 'a 1 'b 2 'c 3))
-;; Παίρνουμε μια τιμή απο τον πίνακα
+;; Παίρνουμε μια τιμή από τον πίνακα
(hash-ref m 'a) ; => 1
-;; Άν ζητήσουμε μια τιμή που δέν υπάρχει παίρνουμε μία εξαίρεση
+;; Αν ζητήσουμε μια τιμή που δεν υπάρχει παίρνουμε μία εξαίρεση
; (hash-ref m 'd) => no value found for key
;; Μπορούμε να δώσουμε μια default τιμή για τα κλειδιά που λείπουν
@@ -234,7 +234,7 @@ m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3))
m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d'
;; Χρησιμοποιούμε το `hash-remove' για να αφαιρέσουμε
-;; κλειδία
+;; κλειδιά
(hash-remove m 'a) ; => '#hash((b . 2) (c . 3))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@@ -247,12 +247,12 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d'
;; Μπορούμε επίσης να χρησιμοποιήσουμε το `λ'
(λ () "Hello World") ; => Ίδια συνάρτηση
-;; Χρησιμοποιύμε τις παρενθέσεις για να καλέσουμε όλες τις συναρτήσεις
+;; Χρησιμοποιούμε τις παρενθέσεις για να καλέσουμε όλες τις συναρτήσεις
;; συμπεριλαμβανομένων και των εκφράσεων 'λάμδα'
((lambda () "Hello World")) ; => "Hello World"
((λ () "Hello World")) ; => "Hello World"
-;; Εκχωρούμε σε μια μετάβλητη την συνάρτηση
+;; Εκχωρούμε σε μια μεταβλητή την συνάρτηση
(define hello-world (lambda () "Hello World"))
(hello-world) ; => "Hello World"
@@ -302,7 +302,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d'
(lambda (name . args)
(format "Hello ~a, you passed ~a extra args" name (length args))))
-;; Και με λέξεις κλειδία
+;; Και με λέξεις κλειδιά
(define (hello-k #:name [name "World"] #:greeting [g "Hello"] . args)
(format "~a ~a, ~a extra args" g name (length args)))
(hello-k) ; => "Hello World, 0 extra args"
@@ -347,7 +347,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d'
(eq? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f
-;; Το `eqv?' υποστηρίζει την σύκριση αριθμών αλλα και χαρακτήρων
+;; Το `eqv?' υποστηρίζει την σύγκριση αριθμών αλλά και χαρακτήρων
;; Για άλλα ήδη μεταβλητών το `eqv?' και το `eq?' επιστρέφουν το ίδιο.
(eqv? 3 3.0) ; => #f
(eqv? (expt 2 100) (expt 2 100)) ; => #t
@@ -365,12 +365,12 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d'
(equal? (list 3) (list 3)) ; => #t
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;; 5. Έλεχγος Ροής
+;; 5. Έλεγχος Ροής
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Συνθήκες (conditionals)
-(if #t ; έκφραση ελέχγου
+(if #t ; έκφραση ελέγχου
"this is true" ; έκφραση then
"this is false") ; έκφραση else
; => "this is true"
@@ -483,7 +483,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d'
(values i (number->string i)))
; => '#hash((1 . "1") (2 . "2") (3 . "3"))
-;; Υπάρχουν πολλά είδη απο προϋπάρχοντες τρόπους για να συλλέγουμε
+;; Υπάρχουν πολλά είδη από προϋπάρχοντες τρόπους για να συλλέγουμε
;; τιμές από τους βρόχους
(for/sum ([i 10]) (* i i)) ; => 285
@@ -491,7 +491,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d'
(for/and ([i 10] [j (in-range 10 20)]) (< i j)) ; => #t
(for/or ([i 10] [j (in-range 0 20 2)]) (= i j)) ; => #t
-;; Και για να χρησιμοποιήσουμε ένα αφθαίρετο συνδιασμό χρησιμοποιούμε
+;; Και για να χρησιμοποιήσουμε ένα αυθαίρετο συνδυασμό χρησιμοποιούμε
;; το 'for/fold'
(for/fold ([sum 0]) ([i '(1 2 3 4)]) (+ sum i)) ; => 10
@@ -524,17 +524,17 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d'
(set! n (add1 n))
n ; => 6
-;; Χρησιμοποιούμε τα boxes για να δηλώσουμε ρητά ότι μια μεταβητή
-;; θα είναι mutable (θα μπορεί να αλλάξη η τιμή της)
+;; Χρησιμοποιούμε τα boxes για να δηλώσουμε ρητά ότι μια μεταβλητή
+;; θα είναι mutable (θα μπορεί να αλλάξει η τιμή της)
;; Αυτό είναι παρόμοιο με τους pointers σε άλλες γλώσσες
(define n* (box 5))
(set-box! n* (add1 (unbox n*)))
(unbox n*) ; => 6
-;; Πολλοί τύποι μεταβλητών στη Racket είναι αμετάβλητοι πχ τα ζεύγη, οι
+;; Πολλοί τύποι μεταβλητών στη Racket είναι αμετάβλητοι π.χ. τα ζεύγη, οι
;; λίστες κτλ. Άλλοι υπάρχουν και σε μεταβλητή και σε αμετάβλητη μορφή
-;; πχ αλφαριθμητικά, διανύσματα κτλ
+;; π.χ. αλφαριθμητικά, διανύσματα κτλ.
(define vec (vector 2 2 3 4))
(define wall (make-vector 100 'bottle-of-beer))
;; Χρησιμοποιούμε το 'vector-set!' για να ανεώσουμε κάποια
@@ -579,7 +579,7 @@ vec ; => #(1 2 3 4)
(printf fmt (make-string n ch))
(newline)))
-;; Χρησιμοποιομε το 'require' για να πάρουμε όλα τα
+;; Χρησιμοποιουμε το 'require' για να πάρουμε όλα τα
;; παρεχόμενα ονόματα από μία ενότητα
(require 'cake) ; το ' είναι για τοπική υποενότητα
(print-cake 3)
@@ -634,7 +634,7 @@ vec ; => #(1 2 3 4)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Οι μακροεντολές μας επιτρέπουν να επεκτείνουμε
-;; το συντακτικό μιάς γλώσσας.
+;; το συντακτικό μιας γλώσσας.
;; Ας προσθέσουμε έναν βρόχο while
(define-syntax-rule (while condition body ...)
@@ -664,20 +664,20 @@ vec ; => #(1 2 3 4)
;; (set! tmp other)
;; (set! other tmp_1))
-;; Αλλά ακόμα υπάρχουν ακόμη μετασχηματισμοί του κώδικα, π.χ:
+;; Αλλά ακόμα υπάρχουν ακόμη μετασχηματισμοί του κώδικα, π.χ.:
(define-syntax-rule (bad-while condition body ...)
(when condition
body ...
(bad-while condition body ...)))
-;; αυτή η μακροεντολή είναι χαλασμένη: δημιουγεί ατέρμονα βρόχο
+;; αυτή η μακροεντολή είναι χαλασμένη: δημιουργεί ατέρμονα βρόχο
;; και αν προσπαθήσουμε να το χρησιμοποιήσουμε, ο μεταγλωττιστής
-;; θα μπεί στον ατέρμονα βρόχο.
+;; θα μπει στον ατέρμονα βρόχο.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 10. Συμβόλαια (Contracts)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;; Τα συμβόλαια βάζουν περιορισμόυς σε τιμές που προέρχονται
+;; Τα συμβόλαια βάζουν περιορισμούς σε τιμές που προέρχονται
;; από ενότητες (modules)
(module bank-account racket
(provide (contract-out
@@ -719,7 +719,7 @@ vec ; => #(1 2 3 4)
(displayln "Hola mundo" out-port)
(close-output-port out-port)
-;; Διαβάζουμε απο αρχείο ξανά
+;; Διαβάζουμε από αρχείο ξανά
(define in-port (open-input-file "/tmp/tmp.txt"))
(displayln (read-line in-port))
; => "Hello World"
diff --git a/el-gr/scala-gr.html.markdown b/el-gr/scala-gr.html.markdown
index e29c7e70..415fda5c 100644
--- a/el-gr/scala-gr.html.markdown
+++ b/el-gr/scala-gr.html.markdown
@@ -40,7 +40,7 @@ Scala - Η επεκτάσιμη γλώσσα
/*
Τα σχόλια που επεκτείνονται σε πολλές γραμμές , όπως μπορείτε
- να δείτε , φαίνοται κάπως έτσι.
+ να δείτε , φαίνονται κάπως έτσι.
*/
// Εκτύπωση με νέα γραμμή στην επόμενη εκτύπωση
@@ -59,12 +59,12 @@ var y = 10
y = 20 // το y είναι τώρα 20
/*
- Η Scala είναι στατικού τύπου γλώσσα, εν τούτις προσέξτε ότι στις παραπάνω
+ Η Scala είναι στατικού τύπου γλώσσα, εν τούτοις προσέξτε ότι στις παραπάνω
δηλώσεις , δεν προσδιορίσαμε κάποιον τύπο. Αυτό συμβαίνει λόγω ενός
χαρακτηριστικού της Scala που λέγεται συμπερασματολογία τύπων. Στις
περισσότερες των περιπτώσεων, ο μεταγλωττιστής της Scala μπορεί να
- μαντέψει ποιός είναι ο τύπος μιας μεταβλητής. Μπορούμε να δηλώσουμε
- αναλυτικά τον τύπο μιάς μεταβλητής ως εξής:
+ μαντέψει ποιος είναι ο τύπος μιας μεταβλητής. Μπορούμε να δηλώσουμε
+ αναλυτικά τον τύπο μιας μεταβλητής ως εξής:
*/
val z: Int = 10
val a: Double = 1.0
@@ -85,7 +85,7 @@ false
true == false // false
10 > 5 // true
-// Η αριθμιτική είναι όπως τα συνηθισμένα
+// Η αριθμητική είναι όπως τα συνηθισμένα
1 + 1 // 2
2 - 1 // 1
5 * 3 // 15
@@ -117,14 +117,14 @@ true == false // false
"Τα αλφαριθμητικά στην Scala περικλείονται από διπλά εισαγωγικά"
'a' // Ένας χαρακτήρας στην Scala
// res30: Char = a
-// 'Αλφαριθημτικά με μονά εισαγωγικά δεν υφίστανται <= Αυτό θα προκαλέσει σφάλμα.
+// Αλφαριθημτικά με μονά εισαγωγικά δεν υφίστανται <= Αυτό θα προκαλέσει σφάλμα.
// Τα αλφαριθμητικά έχουν τις συνηθισμένες μεθόδους της Java ορισμένες πάνω τους.
"hello world".length
"hello world".substring(2, 6)
"hello world".replace("C", "3")
-// Έχουν επίσης μερικές επιπλένον μεθόδους Scala.
+// Έχουν επίσης μερικές επιπλέον μεθόδους Scala.
// Δείτε επίσης : scala.collection.immutable.StringOps
"hello world".take(5)
"hello world".drop(5)
@@ -253,7 +253,7 @@ r foreach println
var i = 0
while (i < 10) { println("i " + i); i+=1 }
-while (i < 10) { println("i " + i); i+=1 } // Ναι ξανά! Τι συνέβει; Γιατί;
+while (i < 10) { println("i " + i); i+=1 } // Ναι ξανά! Τι συνέβη; Γιατί;
i // Εμφάνισε την τιμή του i. Σημειώστε ότι ένας βρόχος while είναι βρόχος
// με την κλασική έννοια - εκτελείται σειριακά καθώς αλλάζει η μεταβλητή
@@ -268,8 +268,8 @@ do {
} while (x < 10)
// Η αναδρομή ουράς είναι ένας ιδιωματικός τρόπος να κάνεις επαναλαμβανόμενα
-// πράγματα στην Scala. Οι αναδρομικές συναρτήσεις απαιτούν να γράφτεί
-// ρητά ο τύπος που θα επιστρέψουν , αλλιώς ο μεταγλωττιστής δεν μπορεί
+// πράγματα στην Scala. Οι αναδρομικές συναρτήσεις απαιτούν να γραφτεί
+// ρητά ο τύπος που θα επιστρέψουν, αλλιώς ο μεταγλωττιστής δεν μπορεί
// αλλιώς να τον συνάγει. Παρακάτω είναι μια συνάρτηση που επιστρέφει Unit.
def showNumbersInRange(a:Int, b:Int):Unit = {
print(a)
@@ -332,7 +332,7 @@ s(1)
val divideInts = (x:Int, y:Int) => (x / y, x % y)
divideInts(10,3) // Η συνάρτηση divideInts επιστρέφει το αποτέλεσμα
- // της ακαίρεας διαίρεσης και το υπόλοιπο.
+ // της ακέραιας διαίρεσης και το υπόλοιπο.
// Για να έχουμε πρόσβαση στα στοιχεία μιας πλειάδας, χρησιμοποιούμε το _._n
// όπου το n είναι ο δείκτης με βάση το 1 του στοιχείου.
@@ -349,7 +349,7 @@ d._2
/*
Ότι έχουμε κάνει ως τώρα σε αυτό το tutorial ήταν απλές εκφράσεις
- (τιμές , συναρτήσεις , κτλ). Αυτές οι εκφράσεις βολεύουν όταν τις
+ (τιμές, συναρτήσεις, κτλ.). Αυτές οι εκφράσεις βολεύουν όταν τις
γράφουμε στο REPL για γρήγορες δοκιμές, αλλά δεν μπορούν να υπάρχουν
από μόνες τους σε ένα αρχείο Scala. Για παράδειγμα , δεν μπορούμε να
έχουμε μόνο ένα "val x = 5" στο αρχείο Scala. Αντί αυτού , τα μόνα
@@ -394,7 +394,7 @@ println(mydog.bark) // => "Woof, woof!"
// αυτές καθ' αυτές, αλλά η συμπρεριφορά που σχετίζεται με όλα τα instances
// της κλάσης πάνε μέσα στο object. Η διαφορά είναι παρόμοια με τις
// μεθόδους κλάσεων σε σχέση με στατικές μεθόδους σε άλλες γλώσσες.
-// Προσέξτε οτι τα objects και οι κλάσεις μπορούν να έχουν το ίδιο όνομα.
+// Προσέξτε ότι τα objects και οι κλάσεις μπορούν να έχουν το ίδιο όνομα.
object Dog {
def allKnownBreeds = List("pitbull", "shepherd", "retriever")
def createDog(breed: String) = new Dog(breed)
@@ -402,7 +402,7 @@ object Dog {
// Οι κλάσεις περίπτωσης (case classes) είναι που έχουν την επιπλέον
// λειτουργικότητα ενσωματωμένη. Μιά συνήθης ερώτηση για αρχάριους στην
-// Scala είναι πότε να χρησιμοπούνται κλάσεις και πότε case κλάσεις.
+// Scala είναι πότε να χρησιμοποιούνται κλάσεις και πότε case κλάσεις.
// Γενικά οι κλάσεις τείνουν να εστιάζουν στην ενθυλάκωση, τον
// πολυμορφισμό και τη συμπεριφορά. Οι τιμές μέσα σε αυτές τις κλάσεις
// τείνουν να είναι private , και μόνο οι μέθοδοι είναι εκτεθειμένες.
@@ -411,7 +411,7 @@ object Dog {
// έχουν παρενέργειες.
case class Person(name: String, phoneNumber: String)
-// Δημιουργία ενός instance. Πραρατηρήστε ότι τα case classes
+// Δημιουργία ενός instance. Παρατηρήστε ότι τα case classes
// δεν χρειάζονται την λέξη "new" .
val george = Person("George", "1234")
val kate = Person("Kate", "4567")
@@ -419,7 +419,7 @@ val kate = Person("Kate", "4567")
// Με τα case classes, παίρνεις μερικά προνόμια δωρεάν , όπως:
george.phoneNumber // => "1234"
-// Ελέχγεται η ισότητα για κάθε πεδίο (δεν χρειάζεται να
+// Ελέγχεται η ισότητα για κάθε πεδίο (δεν χρειάζεται να
// κάνουμε override στο .equals)
Person("George", "1234") == Person("Kate", "1236") // => false
@@ -509,7 +509,7 @@ List(1, 2, 3) map (x => x + 10)
// ένα όρισμα στην ανώνυμη συνάρτηση. Έτσι δεσμεύεται ως η μεταβλητή.
List(1, 2, 3) map (_ + 10)
-// Αν το μπλόκ της ανώνυμης συνάρτησης ΚΑΙ η συνάρτηση που εφαρμόζεται
+// Αν το μπλοκ της ανώνυμης συνάρτησης ΚΑΙ η συνάρτηση που εφαρμόζεται
// (στην περίπτωσή μας το foreach και το println) παίρνουν ένα όρισμα
// μπορείτε να παραλείψετε την κάτω παύλα.
List("Dom", "Bob", "Natalia") foreach println
diff --git a/elisp.html.markdown b/elisp.html.markdown
index 3bed5d1c..da86cab3 100644
--- a/elisp.html.markdown
+++ b/elisp.html.markdown
@@ -2,6 +2,7 @@
language: elisp
contributors:
- ["Bastien Guerry", "http://bzg.fr"]
+ - ["Saurabh Sandav", "http://github.com/SaurabhSandav"]
filename: learn-emacs-lisp.el
---
@@ -26,7 +27,7 @@ filename: learn-emacs-lisp.el
;;
;; Going through this tutorial won't damage your computer unless
;; you get so angry that you throw it on the floor. In that case,
-;; I hereby decline any responsability. Have fun!
+;; I hereby decline any responsibility. Have fun!
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
diff --git a/elixir.html.markdown b/elixir.html.markdown
index c8599838..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
@@ -343,6 +343,7 @@ rescue
RuntimeError -> "rescued a runtime error"
_error -> "this will rescue any error"
end
+#=> "rescued a runtime error"
# All exceptions have a message
try do
@@ -351,6 +352,7 @@ rescue
x in [RuntimeError] ->
x.message
end
+#=> "some error"
## ---------------------------
## -- Concurrency
@@ -369,6 +371,13 @@ spawn(f) #=> #PID<0.40.0>
# messages to the process. To do message passing we use the `send` operator.
# For all of this to be useful we need to be able to receive messages. This is
# achieved with the `receive` mechanism:
+
+# The `receive do` block is used to listen for messages and process
+# them when they are received. A `receive do` block will only
+# process one received message. In order to process multiple
+# messages, a function with a `receive do` block must recursively
+# call itself to get into the `receive do` block again.
+
defmodule Geometry do
def area_loop do
receive do
@@ -384,6 +393,8 @@ end
# Compile the module and create a process that evaluates `area_loop` in the shell
pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0>
+# Alternatively
+pid = spawn(Geometry, :area_loop, [])
# Send a message to `pid` that will match a pattern in the receive statement
send pid, {:rectangle, 2, 3}
@@ -400,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/erlang.html.markdown b/erlang.html.markdown
index d6ed7b86..a57f295f 100644
--- a/erlang.html.markdown
+++ b/erlang.html.markdown
@@ -177,7 +177,7 @@ is_dog(A) -> false.
% A guard sequence is either a single guard or a series of guards, separated
% by semicolons (`;`). The guard sequence `G1; G2; ...; Gn` is true if at
% least one of the guards `G1`, `G2`, ..., `Gn` evaluates to `true`.
-is_pet(A) when is_atom(A), (A =:= dog) or (A =:= cat) -> true;
+is_pet(A) when is_atom(A), (A =:= dog);(A =:= cat) -> true;
is_pet(A) -> false.
% Warning: not all valid Erlang expressions can be used as guard expressions;
diff --git a/es-es/amd-es.html.markdown b/es-es/amd-es.html.markdown
new file mode 100644
index 00000000..7a59ddd6
--- /dev/null
+++ b/es-es/amd-es.html.markdown
@@ -0,0 +1,214 @@
+---
+
+category: tool
+tool: amd
+contributors:
+ - ["Frederik Ring", "https://github.com/m90"]
+
+translators:
+ - ["Damaso Sanoja", "https://github.com/damasosanoja"]
+filename: learnamd-es.js
+lang: es-es
+---
+
+## Iniciando con AMD
+
+El API del **Módulo de Definición Asíncrono** especifica un mecanismo para definir módulos JavaScript de manera tal que tanto el módulo como sus dependencias puedan ser cargadas de manera asíncrona. Esto es particularmente adecuado para el entorno del navegador donde la carga sincronizada de los módulos genera problemas de rendimiento, usabilidad, depuración y acceso de multi-dominios.
+
+### Conceptos básicos
+```javascript
+// El API básico de AMD consiste en tan solo dos métodos: `define` y `require`
+// y se basa en la definición y consumo de los módulos:
+// `define(id?, dependencias?, fábrica)` define un módulo
+// `require(dependencias, callback)` importa un conjunto de dependencias y
+// las consume al invocar el callback
+
+// Comencemos usando define para definir un nuevo módulo
+// que no posee dependencias. Lo haremos enviando un nombre
+// y una función fábrica para definirla:
+define('awesomeAMD', function(){
+ var isAMDAwesome = function(){
+ return true;
+ };
+ // El valor que regresa la función fábrica del módulo será
+ // lo que los otros módulos o llamados require recibirán cuando
+ // soliciten nuestro módulo `awesomeAMD`.
+ // El valor exportado puede ser cualquier cosa, funciones (constructores),
+ // objetos, primitivos, incluso indefinidos (aunque eso no ayuda mucho).
+ return isAMDAwesome;
+});
+
+// Ahora definamos otro módulo que dependa de nuestro módulo `awesomeAMD`.
+// Observe que ahora hay un argumento adicional que define
+// las dependencias de nuestro módulo:
+define('loudmouth', ['awesomeAMD'], function(awesomeAMD){
+ // las dependencias serán enviadas a los argumentos de la fábrica
+ // en el orden que sean especificadas
+ var tellEveryone = function(){
+ if (awesomeAMD()){
+ alert('This is sOoOo rad!');
+ } else {
+ alert('Pretty dull, isn\'t it?');
+ }
+ };
+ return tellEveryone;
+});
+
+// Como ya sabemos utilizar define usemos ahora `require` para poner en marcha
+// nuestro programa. La firma de `require` es `(arrayOfDependencies, callback)`.
+require(['loudmouth'], function(loudmouth){
+ loudmouth();
+});
+
+// Para hacer que este tutorial corra código, vamos a implementar una
+// versión muy básica (no-asíncrona) de AMD justo aquí:
+function define(name, deps, factory){
+ // observa como son manejados los módulos sin dependencias
+ define[name] = require(factory ? deps : [], factory || deps);
+}
+
+function require(deps, callback){
+ var args = [];
+ // primero recuperemos todas las dependencias que necesita
+ // el llamado require
+ for (var i = 0; i < deps.length; i++){
+ args[i] = define[deps[i]];
+ }
+ // satisfacer todas las dependencias del callback
+ return callback.apply(null, args);
+}
+// puedes ver este código en acción aquí: http://jsfiddle.net/qap949pd/
+```
+
+### Uso en el mundo real con require.js
+
+En contraste con el ejemplo introductorio, `require.js` (la librería AMD más popular) implementa la **A** de **AMD**, permitiéndote cargar los módulos y sus dependencias asincrónicamente via XHR:
+
+```javascript
+/* file: app/main.js */
+require(['modules/someClass'], function(SomeClass){
+ // el callback es diferido hasta que la dependencia sea cargada
+ var thing = new SomeClass();
+});
+console.log('So here we are, waiting!'); // esto correrá primero
+```
+
+Por convención, usualmente guardas un módulo en un fichero. `require.js` puede resolver los nombres de los módulos basados en rutas de archivo, de forma que no tienes que nombrar tus módulos, simplemente referenciarlos usando su ubicación. En el ejemplo `someClass` asumimos que se ubica en la carpeta `modules`, relativa a tu `baseUrl` configurada:
+
+* app/
+ * main.js
+ * modules/
+ * someClass.js
+ * someHelpers.js
+ * ...
+ * daos/
+ * things.js
+ * ...
+
+Esto significa que podemos definir `someClass` sin especificar su id de módulo:
+
+```javascript
+/* file: app/modules/someClass.js */
+define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){
+ // definición de módulo, por supuesto, ocurrirá también asincrónicamente
+ function SomeClass(){
+ this.method = function(){/**/};
+ // ...
+ }
+ return SomeClass;
+});
+```
+
+Para alterar el comportamiento del mapeo de ruta usa `requirejs.config(configObj)` en tu `main.js`:
+
+```javascript
+/* file: main.js */
+requirejs.config({
+ baseUrl : 'app',
+ paths : {
+ // también puedes cargar módulos desde otras ubicaciones
+ jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min',
+ coolLibFromBower : '../bower_components/cool-lib/coollib'
+ }
+});
+require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolLib, helpers){
+ // un fichero `main` necesita llamar a require al menos una vez,
+ // de otra forma jamás correrá el código
+ coolLib.doFancyStuffWith(helpers.transform($('#foo')));
+});
+```
+Las aplicaciones basadas en `require.js` usualmente tendrán un solo punto de entrada (`main.js`) que se pasa a la etiqueta del script `require.js` como un atributo de datos. Será cargado y ejecutado automáticamente al cargar la página:
+
+```html
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Cien etiquetas de script? Nunca más!</title>
+</head>
+<body>
+ <script src="require.js" data-main="app/main"></script>
+</body>
+</html>
+```
+
+### Optimizar todo un proyecto usando r.js
+
+Muchas personas prefieren usar AMD para la organización del código durante el desarrollo, pero quieren enviar para producción un solo fichero en vez de ejecutar cientos de XHRs en las cargas de página.
+
+`require.js` incluye un script llamado `r.js` (el que probablemente correrás en node.js, aunque Rhino también es soportado) que puede analizar el gráfico de dependencias de tu proyecto, y armar un solo fichero que contenga todos tus módulos (adecuadamente nombrados), minificado y listo para consumo.
+
+Instálalo usando `npm`:
+```shell
+$ npm install requirejs -g
+```
+
+Ahora puedes alimentarlo con un fichero de configuración:
+```shell
+$ r.js -o app.build.js
+```
+
+Para nuestro ejemplo anterior el archivo de configuración luciría así:
+```javascript
+/* file : app.build.js */
+({
+ name : 'main', // nombre del punto de entrada
+ out : 'main-built.js', // nombre del fichero donde se escribirá la salida
+ baseUrl : 'app',
+ paths : {
+ // `empty:` le dice a r.js que esto aún debe ser cargado desde el CDN, usando
+ // la ubicación especificada en `main.js`
+ jquery : 'empty:',
+ coolLibFromBower : '../bower_components/cool-lib/coollib'
+ }
+})
+```
+
+Para usar el fichero creado en producción, simplemente intercambia `data-main`:
+```html
+<script src="require.js" data-main="app/main-built"></script>
+```
+
+Un increíblemente detallado [resumen de opciones de generación](https://github.com/jrburke/r.js/blob/master/build/example.build.js) está disponible en el repositorio de GitHub.
+
+### Tópicos no cubiertos en este tutorial
+* [Cargador de plugins / transformaciones](http://requirejs.org/docs/plugins.html)
+* [Cargando y exportando estilos CommonJS](http://requirejs.org/docs/commonjs.html)
+* [Configuración avanzada](http://requirejs.org/docs/api.html#config)
+* [Configuración de Shim (cargando módulos no-AMD)](http://requirejs.org/docs/api.html#config-shim)
+* [Cargando y optimizando CSS con require.js](http://requirejs.org/docs/optimization.html#onecss)
+* [Usando almond.js para construcciones](https://github.com/jrburke/almond)
+
+### Otras lecturas:
+
+* [Especificaciones oficiales](https://github.com/amdjs/amdjs-api/wiki/AMD)
+* [¿Por qué AMD?](http://requirejs.org/docs/whyamd.html)
+* [Definición Universal de Módulos](https://github.com/umdjs/umd)
+
+### Implementaciones:
+
+* [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/es-es/brainfuck-es.html.markdown b/es-es/bf-es.html.markdown
index e33d672d..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/"]
@@ -9,8 +9,10 @@ lang: es-es
---
Brainfuck (con mayúscula sólo al inicio de una oración) es un
-lenguaje de programación mínimo, computacionalmente universal
-en tamaño con sólo 8 comandos.
+lenguaje de programación extremadamente pequeño, Turing completo con sólo 8 comandos.
+
+Puedes probar brainfuck en tu navegador con [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/).
+
```
@@ -18,7 +20,7 @@ Cualquier caracter que no sea "><+-.,[]" (sin incluir las comillas)
será ignorado.
Brainfuck es representado por un arreglo de 30,000 celdas inicializadas
-en cero y un apuntador en la celda actual.
+en cero y un puntero apuntando la celda actual.
Existen ocho comandos:
@@ -26,7 +28,7 @@ Existen ocho comandos:
- : Decrementa 1 al valor de la celda actual.
> : Mueve el apuntador a la siguiente celda. (a la derecha)
< : Mueve el apuntador a la celda anterior. (a la izquierda)
-. : Imprime el valor en ASCII de la celda actual (i.e. 65 = 'A')
+. : Imprime el valor en ASCII de la celda actual (p.e. 65 = 'A')
, : Lee un caracter como input y lo escribe en la celda actual.
[ : Si el valor en la celda actual es cero mueve el apuntador
hasta el primer ']' que encuentre. Si no es cero sigue a la
@@ -37,7 +39,7 @@ Existen ocho comandos:
[ y ] forman un while. Obviamente, deben estar balanceados.
-Ahora unos ejemplos de programas escritos con brainfuck.
+Estos son algunos ejemplos de programas escritos con brainfuck.
++++++ [ > ++++++++++ < - ] > +++++ .
@@ -63,7 +65,7 @@ Esto continúa hasta que la celda #1 contenga un cero. Cuando #1 contenga un
cero la celda #2 tendrá el valor inicial de #1. Como este ciclo siempre
terminara en la celda #1 nos movemos a la celda #2 e imprimimos (.).
-Ten en mente que los espacios son sólo para fines de legibilidad.
+Ten en cuenta que los espacios son sólo para fines de legibilidad.
Es lo mismo escribir el ejemplo de arriba que esto:
,[>+<-]>.
@@ -81,7 +83,7 @@ hasta la próxima vez. Para resolver este problema también incrementamos la
celda #4 y luego copiamos la celda #4 a la celda #2. La celda #3 contiene
el resultado.
```
-Y eso es brainfuck. ¿No tan difícil o sí? Como diversión, puedes escribir
+Y eso es brainfuck. No es tan difícil, ¿verdad? Como diversión, puedes escribir
tu propio intérprete de brainfuck o tu propio programa en brainfuck. El
intérprete es relativamente sencillo de hacer, pero si eres masoquista,
-intenta construir tu proprio intérprete de brainfuck... en brainfuck.
+puedes intentar construir tu propio intérprete de brainfuck... en brainfuck.
diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown
index 18b544b4..4e1e68ba 100644
--- a/es-es/git-es.html.markdown
+++ b/es-es/git-es.html.markdown
@@ -18,11 +18,11 @@ versionar y administrar nuestro código fuente.
## Versionamiento, conceptos.
-### Qué es el control de versiones?
+### ¿Qué es el control de versiones?
El control de versiones es un sistema que guarda todos los cambios realizados en
uno o varios archivos, a lo largo del tiempo.
-### Versionamiento centralizado vs Versionamiento Distribuido.
+### Versionamiento centralizado vs versionamiento distribuido.
+ El versionamiento centralizado se enfoca en sincronizar, rastrear, y respaldar
archivos.
@@ -33,9 +33,9 @@ uno o varios archivos, a lo largo del tiempo.
[Información adicional](http://git-scm.com/book/es/Empezando-Acerca-del-control-de-versiones)
-### Por qué usar Git?
+### ¿Por qué usar Git?
-* Se puede trabajar sin conexion.
+* Se puede trabajar sin conexión.
* ¡Colaborar con otros es sencillo!.
* Derivar, crear ramas del proyecto (aka: Branching) es fácil.
* Combinar (aka: Merging)
@@ -47,7 +47,7 @@ uno o varios archivos, a lo largo del tiempo.
### Repositorio
Un repositorio es un conjunto de archivos, directorios, registros, cambios (aka:
-comits), y encabezados (aka: heads). Imagina que un repositorio es una clase,
+commits), y encabezados (aka: heads). Imagina que un repositorio es una clase,
y que sus atributos otorgan acceso al historial del elemento, además de otras
cosas.
@@ -62,12 +62,12 @@ y mas.
### Directorio de trabajo (componentes del repositorio)
-Es basicamente los directorios y archivos dentro del repositorio. La mayoría de
+Es básicamente los directorios y archivos dentro del repositorio. La mayoría de
las veces se le llama "directorio de trabajo".
### Índice (componentes del directorio .git)
-El índice es el área de inicio en git. Es basicamente la capa que separa el
+El índice es el área de inicio en git. Es básicamente la capa que separa el
directorio de trabajo del repositorio en git. Esto otorga a los desarrolladores
más poder sobre lo que se envía y se recibe del repositorio.
diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown
index 036d7082..9ef0c63e 100644
--- a/es-es/javascript-es.html.markdown
+++ b/es-es/javascript-es.html.markdown
@@ -16,7 +16,7 @@ con Java para aplicaciones más complejas. Debido a su integracion estrecha con
web y soporte por defecto de los navegadores modernos se ha vuelto mucho más común
para front-end que Java.
-JavaScript no sólo se limita a los navegadores web, aunque: Node.js, Un proyecto que proporciona un entorno de ejecución independiente para el motor V8 de Google Chrome, se está volviendo más y más popular.
+Aunque JavaScript no sólo se limita a los navegadores web: Node.js, Un proyecto que proporciona un entorno de ejecución independiente para el motor V8 de Google Chrome, se está volviendo más y más popular.
¡La retroalimentación es bienvenida! Puedes encontrarme en:
[@adambrenecki](https://twitter.com/adambrenecki), o
@@ -30,7 +30,7 @@ JavaScript no sólo se limita a los navegadores web, aunque: Node.js, Un proyect
// Cada sentencia puede ser terminada con punto y coma ;
hazAlgo();
-// ... aunque no es necesario, ya que el punto y coma se agrega automaticamente
+// ... aunque no es necesario, ya que el punto y coma se agrega automáticamente
// cada que se detecta una nueva línea, a excepción de algunos casos.
hazAlgo()
@@ -109,7 +109,7 @@ null == undefined; // = true
null === undefined; // false
// Los Strings funcionan como arreglos de caracteres
-// Puedes accesar a cada caracter con la función charAt()
+// Puedes acceder a cada caracter con la función charAt()
"Este es un String".charAt(0); // = 'E'
// ...o puedes usar la función substring() para acceder a pedazos más grandes
@@ -124,7 +124,7 @@ undefined; // usado para indicar que un valor no está presente actualmente
// (aunque undefined es un valor en sí mismo)
// false, null, undefined, NaN, 0 y "" es false; todo lo demás es true.
-// Note que 0 is false y "0" es true, a pesar de que 0 == "0".
+// Note que 0 es false y "0" es true, a pesar de que 0 == "0".
// Aunque 0 === "0" sí es false.
///////////////////////////////////
@@ -186,7 +186,7 @@ miObjeto.miLlave; // = "miValor"
// agregar nuevas llaves.
miObjeto.miTerceraLlave = true;
-// Si intentas accesar con una llave que aún no está asignada tendrás undefined.
+// Si intentas acceder con una llave que aún no está asignada tendrás undefined.
miObjeto.miCuartaLlave; // = undefined
///////////////////////////////////
@@ -301,7 +301,7 @@ i; // = 5 - en un lenguaje que da ámbitos por bloque esto sería undefined, per
//inmediatamente", que preveé variables temporales de fugarse al ámbito global
(function(){
var temporal = 5;
- // Podemos accesar al ámbito global asignando al 'objeto global', el cual
+ // Podemos acceder al ámbito global asignando al 'objeto global', el cual
// en un navegador siempre es 'window'. El objeto global puede tener
// un nombre diferente en ambientes distintos, por ejemplo Node.js .
window.permanente = 10;
@@ -321,7 +321,7 @@ function decirHolaCadaCincoSegundos(nombre){
alert(texto);
}
setTimeout(interna, 5000);
- // setTimeout es asíncrono, así que la funcion decirHolaCadaCincoSegundos
+ // setTimeout es asíncrono, así que la función decirHolaCadaCincoSegundos
// terminará inmediatamente, y setTimeout llamará a interna() a los cinco segundos
// Como interna está "cerrada dentro de" decirHolaCadaCindoSegundos, interna todavía tiene
// acceso a la variable 'texto' cuando es llamada.
@@ -339,7 +339,7 @@ var miObjeto = {
};
miObjeto.miFuncion(); // = "¡Hola Mundo!"
-// Cuando las funciones de un objeto son llamadas, pueden accesar a las variables
+// Cuando las funciones de un objeto son llamadas, pueden acceder a las variables
// del objeto con la palabra clave 'this'.
miObjeto = {
miString: "¡Hola Mundo!",
@@ -401,11 +401,11 @@ var MiConstructor = function(){
miNuevoObjeto = new MiConstructor(); // = {miNumero: 5}
miNuevoObjeto.miNumero; // = 5
-// Todos los objetos JavaScript tienen un 'prototipo'. Cuando vas a accesar a una
+// Todos los objetos JavaScript tienen un 'prototipo'. Cuando vas a acceder a una
// propiedad en un objeto que no existe en el objeto el intérprete buscará en
// el prototipo.
-// Algunas implementaciones de JavaScript te permiten accesar al prototipo de
+// Algunas implementaciones de JavaScript te permiten acceder al prototipo de
// un objeto con la propiedad __proto__. Mientras que esto es útil para explicar
// prototipos, no es parte del estándar; veremos formas estándar de usar prototipos
// más adelante.
@@ -440,7 +440,7 @@ miPrototipo.sentidoDeLaVida = 43;
miObjeto.sentidoDeLaVida; // = 43
// Mencionabamos anteriormente que __proto__ no está estandarizado, y que no
-// existe una forma estándar de accesar al prototipo de un objeto. De todas formas.
+// existe una forma estándar de acceder al prototipo de un objeto. De todas formas.
// hay dos formas de crear un nuevo objeto con un prototipo dado.
// El primer método es Object.create, el cual es una adición reciente a JavaScript,
@@ -476,7 +476,7 @@ typeof miNumero; // = 'number'
typeof miNumeroObjeto; // = 'object'
miNumero === miNumeroObjeyo; // = false
if (0){
- // Este código no se ejecutara porque 0 es false.
+ // Este código no se ejecutará porque 0 es false.
}
// Aún así, los objetos que envuelven y los prototipos por defecto comparten
diff --git a/es-es/json-es.html.markdown b/es-es/json-es.html.markdown
index fff678eb..c98049f9 100644
--- a/es-es/json-es.html.markdown
+++ b/es-es/json-es.html.markdown
@@ -21,22 +21,22 @@ JSON en su forma más pura no tiene comentarios, pero la mayoría de los parsead
"llaves": "siempre debe estar entre comillas (ya sean dobles o simples)",
"numeros": 0,
"strings": "Høla, múndo. Todo el unicode está permitido, así como \"escapar\".",
- "soporta booleanos?": true,
- "vacios": null,
+ "¿soporta booleanos?": true,
+ "vacíos": null,
"numero grande": 1.2e+100,
"objetos": {
- "comentario": "La mayoria de tu estructura vendra de objetos.",
+ "comentario": "La mayoría de tu estructura vendrá de objetos.",
"arreglo": [0, 1, 2, 3, "Los arreglos pueden contener cualquier cosa.", 5],
"otro objeto": {
- "comentario": "Estas cosas pueden estar anidadas, muy util."
+ "comentario": "Estas cosas pueden estar anidadas, muy útil."
}
},
- "tonteria": [
+ "tontería": [
{
"fuentes de potasio": ["bananas"]
},
@@ -50,10 +50,10 @@ JSON en su forma más pura no tiene comentarios, pero la mayoría de los parsead
"estilo alternativo": {
"comentario": "Mira esto!"
- , "posicion de la coma": "no importa - mientras este antes del valor, entonces sera valido"
- , "otro comentario": "que lindo"
+ , "posición de la coma": "no importa - mientras este antes del valor, entonces sera válido"
+ , "otro comentario": "qué lindo"
},
- "eso fue rapido": "Y, estas listo. Ahora sabes todo lo que JSON tiene para ofrecer."
+ "eso fue rapido": "Y, estás listo. Ahora sabes todo lo que JSON tiene para ofrecer."
}
```
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 d90e3eb5..0505b4cb 100644
--- a/es-es/markdown-es.html.markdown
+++ b/es-es/markdown-es.html.markdown
@@ -11,7 +11,7 @@ lang: es-es
Markdown fue creado por John Gruber en 2004. Su propósito es ser una sintaxis fácil de leer y escribir que se convierta
fácilmente a HTML (y, actualmente, otros formatos también).
-¡Denme todo la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests!
+¡Denme toda la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests!
```markdown
@@ -44,7 +44,7 @@ Esto es un h2
-------------
<!-- Estilos para texto plano -->
-<!-- El texto puede ser fácilmente estilizaedo con italicas, negritas o tachado
+<!-- El texto puede ser fácilmente estilizado con italicas, negritas o tachado
usando markdown -->
*Este texto está en itálicas.*
@@ -57,12 +57,12 @@ __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.~~
-<!-- Los párrafos son una o múltuples líneas de texto adyacentes separadas por
+<!-- Los párrafos son una o múltiples líneas de texto adyacentes separadas por
una o múltiples líneas en blanco-->
Este es un párrafo. Estoy escribiendo un párrafo, ¿No es divertido?
@@ -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/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/python3-es.html.markdown b/es-es/python3-es.html.markdown
index 1c69481a..05fd7065 100644
--- a/es-es/python3-es.html.markdown
+++ b/es-es/python3-es.html.markdown
@@ -97,7 +97,7 @@ not False # => True
None # => None
# No uses el símbolo de igualdad `==` para comparar objetos con None
-# Usa `is` en lugar de
+# Usa `is` en su lugar
"etc" is None #=> False
None is None #=> True
@@ -383,7 +383,7 @@ def keyword_args(**kwargs):
keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"}
-# You can do both at once, if you like# Puedes hacer ambas a la vez si quieres
+# Puedes hacer ambas a la vez si quieres
def todos_los_argumentos(*args, **kwargs):
print args
print kwargs
@@ -478,7 +478,7 @@ Humano.roncar() #=> "*roncar*"
# Puedes importar módulos
import math
-print(math.sqrt(16)) #=> 4
+print(math.sqrt(16)) #=> 4.0
# Puedes obtener funciones específicas desde un módulo
from math import ceil, floor
@@ -511,7 +511,7 @@ def duplicar_numeros(iterable):
for i in iterable:
yield i + i
-# Un generador cera valores sobre la marcha.
+# Un generador crea valores sobre la marcha.
# En vez de generar y retornar todos los valores de una vez, crea uno en cada iteración.
# Esto significa que valores más grandes que 15 no serán procesados en 'duplicar_numeros'.
# Fíjate que 'range' es un generador. Crear una lista 1-900000000 tomaría mucho tiempo en crearse.
diff --git a/es-es/ruby-es.html.markdown b/es-es/ruby-es.html.markdown
index 66a5d0fe..e3e43c18 100644
--- a/es-es/ruby-es.html.markdown
+++ b/es-es/ruby-es.html.markdown
@@ -5,8 +5,18 @@ 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"]
translators:
- ["Camilo Garrido", "http://www.twitter.com/hirohope"]
+ - ["Erick Bernal", "http://www.twitter.com/billowkib"]
lang: es-es
---
@@ -19,7 +29,7 @@ Nadie los usa.
Tu tampoco deberías
=end
-# Lo primero y principal: Todo es un objeto
+# En primer lugar: Todo es un objeto
# Los números son objetos
@@ -33,6 +43,8 @@ Tu tampoco deberías
8 - 1 #=> 7
10 * 2 #=> 20
35 / 5 #=> 7
+2**5 #=> 32
+5 % 3 #=> 2
# La aritmética es sólo azúcar sintáctico
# para llamar un método de un objeto
@@ -55,8 +67,6 @@ false.class #=> FalseClass
# Desigualdad
1 != 1 #=> false
2 != 1 #=> true
-!true #=> false
-!false #=> true
# Además de 'false', 'nil' es otro valor falso
@@ -70,14 +80,29 @@ false.class #=> FalseClass
2 <= 2 #=> true
2 >= 2 #=> true
+# Operadores lógicos
+true && false #=> false
+true || false #=> true
+!true #=> false
+
+# Existen versiones alternativas de los operadores lógicos con menor prioridad
+# Estos son usados como constructores controladores de flujo que encadenan
+# sentencias hasta que una de ellas retorne verdadero o falso
+
+# `has_otra_cosa` solo se llama si `has_algo` retorna verdadero.
+has_algo() and has_otra_cosa()
+# `registra_error` solo se llama si `has_algo` falla
+has_algo() or registra_error()
+
+
# Los strings son objetos
'Soy un string'.class #=> String
"Soy un string también".class #=> String
-referente = "usar interpolacion de strings"
+referente = "usar interpolación de strings"
"Yo puedo #{referente} usando strings de comillas dobles"
-#=> "Yo puedo usar interpolacion de strings usando strings de comillas dobles"
+#=> "Yo puedo usar interpolación de strings usando strings de comillas dobles"
# Imprime a la salida estándar
@@ -103,7 +128,7 @@ ruta = '/mal/nombre/'
# Los símbolos (son objetos)
# Los símbolos son inmutables, constantes reusables representadas internamente por un
-# valor entero. Son usalmente usados en vez de strings para expresar eficientemente
+# valor entero. Son normalmente usados en vez de strings para expresar eficientemente
# valores específicos y significativos
:pendiente.class #=> Symbol
@@ -119,18 +144,19 @@ status == :aprovado #=> false
# Arreglos
# Esto es un arreglo
-[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+arreglo = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
# Arreglos pueden contener elementos de distintos tipos
-arreglo = [1, "hola", false] #=> => [1, "hola", false]
+[1, "hola", false] #=> => [1, "hola", false]
# Arreglos pueden ser indexados
# Desde el frente
arreglo[0] #=> 1
+arreglo.first #=> 1
arreglo[12] #=> nil
-# Tal como la aritmética, el acceso como variable[índice]
+# Al igual que en aritmética, el acceso como variable[índice]
# es sólo azúcar sintáctica
# para llamar el método [] de un objeto
arreglo.[] 0 #=> 1
@@ -138,15 +164,25 @@ arreglo.[] 12 #=> nil
# Desde el final
arreglo[-1] #=> 5
+arreglo.last #=> 5
+
+# Con un índice de inicio y longitud
+arreglo[2, 3] #=> [3, 4, 5]
-# Con un índice de inicio y final
-arreglo[2, 4] #=> [3, 4, 5]
+# Invertir un arreglo
+a = [1, 2, 3]
+a.reverse! #=> [3, 2, 1]
# O con rango
arreglo[1..3] #=> [2, 3, 4]
# Añade elementos a un arreglo así
arreglo << 6 #=> [1, 2, 3, 4, 5, 6]
+# O así
+arreglo.push(6) #=> [1, 2, 3, 4, 5, 6]
+
+#Verifica si un elemento ya existe en ese arreglo
+arreglo.include?(1) #=> true
# Hashes son los diccionarios principales de Ruby con pares llave/valor.
# Hashes se denotan con llaves:
@@ -161,17 +197,16 @@ hash['numero'] #=> 5
# Preguntarle a un hash por una llave que no existe retorna 'nil':
hash['nada aqui'] #=> nil
-# Itera sobre un hash con el método 'each':
-hash.each do |k, v|
- puts "#{k} is #{v}"
-end
-
# Desde Ruby 1.9, hay una sintaxis especial cuando se usa un símbolo como llave:
nuevo_hash = { defcon: 3, accion: true}
nuevo_hash.keys #=> [:defcon, :accion]
+# Verifica la existencia de llaves y valores en el hash
+new_hash.has_key?(:defcon) #=> true
+new_hash.has_value?(3) #=> true
+
# Tip: Tanto los arreglos como los hashes son Enumerable (enumerables)
# Comparten muchos métodos útiles tales como 'each', 'map', 'count', y más
@@ -194,9 +229,15 @@ end
#=> iteracion 4
#=> iteracion 5
-# Aunque
-# Nadie usa los ciclos `for`
-# Usa `each`, así:
+# SIN EMBARGO, nadie usa ciclos `for`
+# En su lugar debes usar el método "each" y pasarle un block (bloque).
+# Un bloque es un fragmento código que puedes pasar a métodos como `each`.
+# Es símilar a las funciones lambda, funciones anónimas o `closures` en otros
+# lenguajes de programación.
+#
+# El método `each` de un Range (rango) ejecuta el bloque una vez por cada elemento.
+# Al bloque se le pasa un contador como parametro.
+# Usar el método `each` con un bloque se ve así:
(1..5).each do |contador|
puts "iteracion #{contador}"
@@ -207,10 +248,27 @@ end
#=> iteracion 4
#=> iteracion 5
-counter = 1
-while counter <= 5 do
- puts "iteracion #{counter}"
- counter += 1
+# También puedes envolver el bloque entre llaves:
+(1..5).each { |counter| puts "iteración #{contador}" }
+
+#El contenido de las estructuras de datos en ruby puede ser iterado usando `each`.
+arreglo.each do |elemento|
+ puts "#{elemento} es parte del arreglo"
+end
+hash.each do |llave, valor|
+ puts "#{llave} es #{valor}"
+end
+
+# Si aún necesitas un índice puedes usar "each_with_index" y definir una variable
+# índice.
+arreglo.each_with_index do |element, index|
+ puts "#{element} tiene la posición #{index} en el arreglo"
+end
+
+contador = 1
+while contador <= 5 do
+ puts "iteracion #{contador}"
+ contador += 1
end
#=> iteracion 1
#=> iteracion 2
@@ -218,6 +276,19 @@ end
#=> iteracion 4
#=> iteracion 5
+# Hay una gran variedad de otras funciones iterativas útiles en Ruby,
+# por ejemplo `map`, `reduce`, `inject`, entre otras. Map, por ejemplo,
+# toma el arreglo sobre el cuál está iterando, le hace cambios
+# definidos en el bloque, y retorna un arreglo completamente nuevo.
+arreglo = [1,2,3,4,5]
+duplicado = array.map do |elemento|
+ elemento * 2
+end
+puts duplicado
+#=> [2,4,6,8,10]
+puts array
+#=> [1,2,3,4,5]
+
nota = 'B'
case nota
@@ -234,6 +305,34 @@ when 'F'
else
puts "Sistema alternativo de notas, ¿eh?"
end
+#=> "Mejor suerte para la proxima"
+
+# Los casos también pueden usar rangos
+nota = 82
+
+case nota
+when 90..100
+ puts 'Excelente!'
+when 80..100
+ puts 'Buen trabajo'
+else
+ puts '¡Reprobaste!'
+end
+#=> "Buen trabajo"
+
+# Manejo de excepciones
+begin
+ # código que podría causar excepción
+ raise NoMemoryError, 'Se te acabó la memoria'
+rescue NoMemoryError => variable_de_excepcion
+ puts 'El error NoMemoryError ocurrió', variable_de_excepcion
+rescue RuntimeError => otra_variable_de_excepcion
+ puts 'El error RuntimeError ocurrió'
+else
+ puts 'Esto se ejecuta si ningun error ocurrió'
+ensure
+ puts 'Este código siempre se ejecuta, sin importar que'
+end
# Funciones
@@ -244,7 +343,7 @@ end
# Funciones (y todos los bloques) implícitamente retornan el valor de la última instrucción
doble(2) #=> 4
-# Paréntesis son opcionales cuando el resultado es ambiguo
+# Paréntesis son opcionales cuando el resultado no es ambiguo
doble 3 #=> 6
doble doble 3 #=> 12
@@ -259,7 +358,7 @@ suma 3, 4 #=> 7
suma suma(3,4), 5 #=> 12
# yield
-# Todos los métodos tienen un parámetro de bloqueo opcional e implícitp
+# Todos los métodos tienen un parámetro bloque opcional e implícito
# puede llamarse con la palabra clave 'yield'
def alrededor
@@ -274,6 +373,17 @@ alrededor { puts 'hola mundo' }
# hola mundo
# }
+# Puedes pasar un bloque a una función
+# '&' representa una referencia a un bloque
+def visitantes(&bloque)
+ bloque.call
+end
+
+# Puedes pasar una lista de argumentos, que serán convertidos en un arreglo
+# Para eso sirve el operador ('*')
+def visitantes(*arreglo)
+ arreglo.each { |visitante| puts visitante }
+end
# Define una clase con la palabra clave 'class'
class Humano
@@ -299,16 +409,26 @@ class Humano
@nombre
end
+ # La funcionalidad anterior puede ser encapsulada usando el método attr_accessor
+ # de la siguiente manera
+
+ attr_accessor :name
+
+ # Los métodos de tipo getter y setter también se pueden crear de manera individual
+ # de la siguiente manera
+
+ attr_reader :name
+ attr_writer :name
+
# Un método de clase usa 'self' (sí mismo) para distinguirse de métodos de instancia.
# Sólo puede ser llamado en la clase, no por una instancia.
def self.decir(mensaje)
- puts "#{mensaje}"
+ puts mensaje
end
def especie
@@especie
end
-
end
@@ -328,6 +448,23 @@ dwight.nombre #=> "Dwight K. Schrute"
# Llama el método de clase
Humano.decir("Hi") #=> "Hi"
+# El alcance de las variables es definido por la manera en que las nombramos.
+# Las variables que inician con $ tienen un alcance global
+$var = "Soy una variable global"
+defined? $var #=> "global-variable"
+
+# Las variables que empiezan con @ tienen un alcance de instancia
+@var = "Soy una variable de instancia"
+defined? @var #=> "instance-variable"
+
+# Variables que empiezan con @@ tienen un alcance de clase
+@@var = "Soy una variable de clase"
+defined? @@var #=> "class variable"
+
+# Las variables que empiezan con letra mayuscula son constantes
+Var = "Soy una constante"
+defined? Var #=> "constant"
+
# Las clases también son un objeto en ruby. Por lo cual, las clases también pueden tener variables de instancia.
# Variables de clase son compartidas a través de la clase y todos sus descendientes.
@@ -371,7 +508,67 @@ end
class Doctor < Humano
end
-Human.bar # 0
+Humano.bar # 0
Doctor.bar # nil
+module ModuloEjemplo
+ def foo
+ 'foo'
+ end
+end
+
+# Al incluir un módulo sus métodos se comparten con las instancias de la clase
+# Al extender un módulo sus métodos se comparten con la clase misma
+
+class Persona
+ include ModuloEjemplo
+end
+
+class Libro
+ extend ModuloEjemplo
+end
+
+Persona.foo # => NoMethodError: undefined method `foo' for Persona:Class
+Persona.new.foo # => 'foo'
+Libro.foo # => 'foo'
+Libro.new.foo # => NoMethodError: undefined method `foo'
+
+# Las llamadas de retorno (callbacks) son ejecutadas cuando se incluye o
+# extiende un módulo
+module EjemploConcern
+ def self.incluido(base)
+ base.extend(MetodosClase)
+ base.send(:include, MetodosInstancia)
+ end
+
+ module MetodosClase
+ def bar
+ 'bar'
+ end
+ end
+
+ module MetodosInstancia
+ def qux
+ 'qux'
+ end
+ end
+end
+
+class Algo
+ include EjemploConcern
+end
+
+Algo.bar #=> 'bar'
+Algo.qux #=> NoMethodError: undefined method `qux'
+Algo.new.bar # => NoMethodError: undefined method `bar'
+Algo.new.qux # => 'qux'
```
+
+## Recursos adicionales
+- [Aprende Ruby Mediante Ejemplo con Ejercicios](http://www.learneroo.com/modules/61/nodes/338) - Una variante de
+esta referencia con ejercicios en navegador.
+- [Documentación Oficial](http://www.ruby-doc.org/core-2.1.1/)
+- [Ruby desde otros lenguajes](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
+- [Programando Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Una
+[edición antigua](http://ruby-doc.com/docs/ProgrammingRuby/) gratuita disponible en línea.
+- [Guía de estilo de Ruby](https://github.com/bbatsov/ruby-style-guide) - Guía de estilo creada por la comunidad.
diff --git a/es-es/swift-es.html.markdown b/es-es/swift-es.html.markdown
new file mode 100644
index 00000000..c04ab02b
--- /dev/null
+++ b/es-es/swift-es.html.markdown
@@ -0,0 +1,596 @@
+---
+language: swift
+contributors:
+ - ["Grant Timmerman", "http://github.com/grant"]
+ - ["Christopher Bess", "http://github.com/cbess"]
+ - ["Joey Huang", "http://github.com/kamidox"]
+ - ["Anthony Nguyen", "http://github.com/anthonyn60"]
+translators:
+ - ["David Hsieh", "http://github.com/deivuh"]
+lang: es-es
+filename: learnswift-es.swift
+---
+
+Swift es un lenguaje de programación para el desarrollo en iOS y OS X creado
+por Apple. Diseñado para coexistir con Objective-C y ser más resistente contra
+el código erroneo, Swift fue introducido en el 2014 en el WWDC, la conferencia
+de desarrolladores de Apple.
+
+Véase también la guía oficial de Apple, [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/), el cual tiene un completo tutorial de Swift.
+
+
+```swift
+// Importar un módulo
+import UIKit
+
+//
+// MARK: Básicos
+//
+
+// XCode soporta referencias para anotar tu código y agregarlos a lista de la
+// barra de saltos.
+// MARK: Marca de sección
+// TODO: Hacer algo pronto
+// FIXME: Arreglar este código
+
+// En Swift 2, println y print fueron combinados en un solo método print.
+// Print añade una nueva línea automáticamente.
+print("Hola, mundo") // println ahora es print
+print("Hola, mundo", appendNewLine: false) // print sin agregar nueva línea
+
+// Valores de variables (var) pueden cambiar después de ser asignados
+// Valores de constrantes (let) no pueden cambiarse después de ser asignados
+
+var myVariable = 42
+let øπΩ = "value" // nombres de variable unicode
+let π = 3.1415926
+let convenience = "keyword" // nombre de variable contextual
+// Las declaraciones pueden ser separadas por punto y coma (;)
+let weak = "keyword"; let override = "another keyword"
+// Los acentos abiertos (``) permiten utilizar palabras clave como nombres de
+// variable
+let `class` = "keyword"
+let explicitDouble: Double = 70
+let intValue = 0007 // 7
+let largeIntValue = 77_000 // 77000
+let label = "some text " + String(myVariable) // Conversión (casting)
+let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Interpolación de string
+
+// Valores específicos de la compilación (build)
+// utiliza la configuración -D
+#if false
+ print("No impreso")
+ let buildValue = 3
+#else
+ let buildValue = 7
+#endif
+print("Build value: \(buildValue)") // Build value: 7
+
+/*
+ Las opcionales son un aspecto del lenguaje Swift que permite el
+ almacenamiento de un valor `Some` (algo) o `None` (nada).
+
+ Debido a que Swift requiere que cada propiedad tenga un valor,
+ hasta un valor 'nil' debe de ser explicitamente almacenado como un
+ valor opcional.
+
+ Optional<T> es un enum.
+*/
+var someOptionalString: String? = "opcional" // Puede ser nil
+// Al igual que lo anterior, pero ? es un operador postfix (sufijo)
+var someOptionalString2: Optional<String> = "opcional"
+
+if someOptionalString != nil {
+ // No soy nil
+ if someOptionalString!.hasPrefix("opt") {
+ print("Tiene el prefijo")
+ }
+
+ let empty = someOptionalString?.isEmpty
+}
+someOptionalString = nil
+
+// Opcional implícitamente desenvuelto
+var unwrappedString: String! = "Un valor esperado."
+// Al igual que lo anterior, pero ! es un operador postfix (sufijo)
+var unwrappedString2: ImplicitlyUnwrappedOptional<String> = "Un valor esperado."
+
+if let someOptionalStringConstant = someOptionalString {
+ // tiene valor `Some` (algo), no nil
+ if !someOptionalStringConstant.hasPrefix("ok") {
+ // No tiene el prefijo
+ }
+}
+
+// Swift tiene soporte de almacenamiento para cualquier tipo de valor.
+// AnyObject == id
+// A diferencia de Objective-C `id`, AnyObject funciona con cualquier
+// valor (Class, Int, struct, etc)
+var anyObjectVar: AnyObject = 7
+anyObjectVar = "Cambiado a un valor string, no es buena práctica, pero posible."
+
+/*
+ Comentar aquí
+
+ /*
+ Comentarios anidados también son soportados
+ */
+*/
+
+//
+// MARK: Colecciones
+//
+
+/*
+ Tipos Array (arreglo) y Dictionary (diccionario) son structs (estructuras).
+ Así que `let` y `var` también indican si son mudables (var) o
+ inmutables (let) durante la declaración de sus tipos.
+*/
+
+// Array (arreglo)
+var shoppingList = ["catfish", "water", "lemons"]
+shoppingList[1] = "bottle of water"
+let emptyArray = [String]() // let == inmutable
+let emptyArray2 = Array<String>() // igual que lo anterior
+var emptyMutableArray = [String]() // var == mudable
+
+
+// Dictionary (diccionario)
+var occupations = [
+ "Malcolm": "Captain",
+ "kaylee": "Mechanic"
+]
+occupations["Jayne"] = "Public Relations"
+let emptyDictionary = [String: Float]() // let == inmutable
+let emptyDictionary2 = Dictionary<String, Float>() // igual que lo anterior
+var emptyMutableDictionary = [String: Float]() // var == mudable
+
+
+//
+// MARK: Flujo de control
+//
+
+// Ciclo for (array)
+let myArray = [1, 1, 2, 3, 5]
+for value in myArray {
+ if value == 1 {
+ print("Uno!")
+ } else {
+ print("No es uno!")
+ }
+}
+
+// Ciclo for (dictionary)
+var dict = ["uno": 1, "dos": 2]
+for (key, value) in dict {
+ print("\(key): \(value)")
+}
+
+// Ciclo for (range)
+for i in -1...shoppingList.count {
+ print(i)
+}
+shoppingList[1...2] = ["steak", "peacons"]
+// Utilizar ..< para excluir el último valor
+
+// Ciclo while
+var i = 1
+while i < 1000 {
+ i *= 2
+}
+
+// Ciclo do-while
+do {
+ print("Hola")
+} while 1 == 2
+
+// Switch
+// Muy potente, se puede pensar como declaraciones `if` con _azúcar sintáctico_
+// Soportan String, instancias de objetos, y primitivos (Int, Double, etc)
+let vegetable = "red pepper"
+switch vegetable {
+case "celery":
+ let vegetableComment = "Add some raisins and make ants on a log."
+case "cucumber", "watercress":
+ let vegetableComment = "That would make a good tea sandwich."
+case let localScopeValue where localScopeValue.hasSuffix("pepper"):
+ let vegetableComment = "Is it a spicy \(localScopeValue)?"
+default: // obligatorio (se debe cumplir con todos los posibles valores de entrada)
+ let vegetableComment = "Everything tastes good in soup."
+}
+
+
+//
+// MARK: Funciones
+//
+
+// Funciones son un tipo de primera-clase, quiere decir que pueden ser anidados
+// en funciones y pueden ser pasados como parámetros
+
+// Función en documentación de cabeceras Swift (formato reStructedText)
+
+/**
+ Una operación de saludo
+
+ - Una viñeta en la documentación
+ - Otra viñeta en la documentación
+
+ :param: name Un nombre
+ :param: day Un día
+ :returns: Un string que contiene el valor de name y day
+*/
+func greet(name: String, day: String) -> String {
+ return "Hola \(name), hoy es \(day)."
+}
+greet("Bob", "Martes")
+
+// Similar a lo anterior, a excepción del compartamiento de los parámetros
+// de la función
+func greet2(requiredName: String, externalParamName localParamName: String) -> String {
+ return "Hola \(requiredName), hoy es el día \(localParamName)"
+}
+greet2(requiredName:"John", externalParamName: "Domingo")
+
+// Función que devuelve múltiples valores en una tupla
+func getGasPrices() -> (Double, Double, Double) {
+ return (3.59, 3.69, 3.79)
+}
+let pricesTuple = getGasPrices()
+let price = pricesTuple.2 // 3.79
+// Ignorar tupla (u otros) valores utilizando _ (guión bajo)
+let (_, price1, _) = pricesTuple // price1 == 3.69
+print(price1 == pricesTuple.1) // true
+print("Gas price: \(price)")
+
+// Cantidad variable de argumentos
+func setup(numbers: Int...) {
+ // Es un arreglo
+ let number = numbers[0]
+ let argCount = numbers.count
+}
+
+// Pasando y devolviendo funciones
+func makeIncrementer() -> (Int -> Int) {
+ func addOne(number: Int) -> Int {
+ return 1 + number
+ }
+ return addOne
+}
+var increment = makeIncrementer()
+increment(7)
+
+// Pasando como referencia
+func swapTwoInts(inout a: Int, inout b: Int) {
+ let tempA = a
+ a = b
+ b = tempA
+}
+var someIntA = 7
+var someIntB = 3
+swapTwoInts(&someIntA, &someIntB)
+print(someIntB) // 7
+
+
+//
+// MARK: Closures (Clausuras)
+//
+var numbers = [1, 2, 6]
+
+// Las funciones son un caso especial de closure ({})
+
+// Ejemplo de closure.
+// `->` Separa los argumentos del tipo de retorno
+// `in` Separa la cabecera del cuerpo del closure
+numbers.map({
+ (number: Int) -> Int in
+ let result = 3 * number
+ return result
+})
+
+// Cuando se conoce el tipo, como en lo anterior, se puede hacer esto
+numbers = numbers.map({ number in 3 * number })
+// o esto
+//numbers = numbers.map({ $0 * 3 })
+
+print(numbers) // [3, 6, 18]
+
+// Closure restante
+numbers = sorted(numbers) { $0 > $1 }
+
+print(numbers) // [18, 6, 3]
+
+// Bastante corto, debido a que el operador < infiere los tipos
+
+numbers = sorted(numbers, < )
+
+print(numbers) // [3, 6, 18]
+
+//
+// MARK: Estructuras
+//
+
+// Las estructuras y las clases tienen capacidades similares
+struct NamesTable {
+ let names = [String]()
+
+ // Subscript personalizado
+ subscript(index: Int) -> String {
+ return names[index]
+ }
+}
+
+// Las estructuras tienen un inicializador designado autogenerado (implícitamente)
+let namesTable = NamesTable(names: ["Me", "Them"])
+let name = namesTable[1]
+print("Name is \(name)") // Name is Them
+
+//
+// MARK: Clases
+//
+
+// Las clases, las estructuras y sus miembros tienen tres niveles de control de acceso
+// Éstos son: internal (predeterminado), public, private
+
+public class Shape {
+ public func getArea() -> Int {
+ return 0;
+ }
+}
+
+// Todos los métodos y las propiedades de una clase son public (públicas)
+// Si solo necesitas almacenar datos en un objecto estructurado,
+// debes de utilizar `struct`
+
+internal class Rect: Shape {
+ var sideLength: Int = 1
+
+ // Getter y setter personalizado
+ private var perimeter: Int {
+ get {
+ return 4 * sideLength
+ }
+ set {
+ // `newValue` es una variable implícita disponible para los setters
+ sideLength = newValue / 4
+ }
+ }
+
+ // Lazily loading (inicialización bajo demanda) a una propiedad
+ // subShape queda como nil (sin inicializar) hasta que getter es llamado
+ lazy var subShape = Rect(sideLength: 4)
+
+ // Si no necesitas un getter y setter personalizado
+ // pero aún quieres ejecutar código antes y después de hacer get o set
+ // a una propiedad, puedes utilizar `willSet` y `didSet`
+ var identifier: String = "defaultID" {
+ // El argumento `willSet` será el nombre de variable para el nuevo valor
+ willSet(someIdentifier) {
+ print(someIdentifier)
+ }
+ }
+
+ init(sideLength: Int) {
+ self.sideLength = sideLength
+ // Siempre poner super.init de último al momento de inicializar propiedades
+ // personalizadas
+ super.init()
+ }
+
+ func shrink() {
+ if sideLength > 0 {
+ --sideLength
+ }
+ }
+
+ override func getArea() -> Int {
+ return sideLength * sideLength
+ }
+}
+
+// Una clase simple `Square` que extiende de `Rect`
+class Square: Rect {
+ convenience init() {
+ self.init(sideLength: 5)
+ }
+}
+
+var mySquare = Square()
+print(mySquare.getArea()) // 25
+mySquare.shrink()
+print(mySquare.sideLength) // 4
+
+// Conversión de tipo de instancia
+let aShape = mySquare as Shape
+
+// Comparar instancias, no es igual a == que compara objetos (equal to)
+if mySquare === mySquare {
+ print("Yep, it's mySquare")
+}
+
+// Inicialización (init) opcional
+class Circle: Shape {
+ var radius: Int
+ override func getArea() -> Int {
+ return 3 * radius * radius
+ }
+
+ // Un signo de interrogación como sufijo después de `init` es un init opcional
+ // que puede devolver nil
+ init?(radius: Int) {
+ self.radius = radius
+ super.init()
+
+ if radius <= 0 {
+ return nil
+ }
+ }
+}
+
+var myCircle = Circle(radius: 1)
+print(myCircle?.getArea()) // Optional(3)
+print(myCircle!.getArea()) // 3
+var myEmptyCircle = Circle(radius: -1)
+print(myEmptyCircle?.getArea()) // "nil"
+if let circle = myEmptyCircle {
+ // no será ejecutado debido a que myEmptyCircle es nil
+ print("circle is not nil")
+}
+
+
+//
+// MARK: Enums
+//
+
+
+// Los enums pueden ser opcionalmente de un tipo específico o de su propio tipo
+// Al igual que las clases, pueden contener métodos
+
+enum Suit {
+ case Spades, Hearts, Diamonds, Clubs
+ func getIcon() -> String {
+ switch self {
+ case .Spades: return "♤"
+ case .Hearts: return "♡"
+ case .Diamonds: return "♢"
+ case .Clubs: return "♧"
+ }
+ }
+}
+
+// Los valores de enum permite la sintaxis corta, sin necesidad de poner
+// el tipo del enum cuando la variable es declarada de manera explícita
+var suitValue: Suit = .Hearts
+
+// Enums de tipo no-entero requiere asignaciones de valores crudas directas
+enum BookName: String {
+ case John = "John"
+ case Luke = "Luke"
+}
+print("Name: \(BookName.John.rawValue)")
+
+// Enum con valores asociados
+enum Furniture {
+ // Asociación con Int
+ case Desk(height: Int)
+ // Asociación con String e Int
+ case Chair(String, Int)
+
+ func description() -> String {
+ switch self {
+ case .Desk(let height):
+ return "Desk with \(height) cm"
+ case .Chair(let brand, let height):
+ return "Chair of \(brand) with \(height) cm"
+ }
+ }
+}
+
+var desk: Furniture = .Desk(height: 80)
+print(desk.description()) // "Desk with 80 cm"
+var chair = Furniture.Chair("Foo", 40)
+print(chair.description()) // "Chair of Foo with 40 cm"
+
+
+//
+// MARK: Protocolos
+//
+
+// `protocol` puede requerir que los tipos tengan propiedades
+// de instancia específicas, métodos de instancia, métodos de tipo,
+// operadores, y subscripts
+
+
+protocol ShapeGenerator {
+ var enabled: Bool { get set }
+ func buildShape() -> Shape
+}
+
+// Protocolos declarados con @objc permiten funciones opcionales,
+// que te permite evaluar conformidad
+@objc protocol TransformShape {
+ optional func reshaped()
+ optional func canReshape() -> Bool
+}
+
+class MyShape: Rect {
+ var delegate: TransformShape?
+
+ func grow() {
+ sideLength += 2
+
+ // Pon un signo de interrogación después de la propiedad opcional,
+ // método, o subscript para ignorar un valor nil y devolver nil
+ // en lugar de tirar un error de tiempo de ejecución
+ // ("optional chaining")
+ if let allow = self.delegate?.canReshape?() {
+ // test for delegate then for method
+ self.delegate?.reshaped?()
+ }
+ }
+}
+
+
+//
+// MARK: Otros
+//
+
+// `extension`: Agrega funcionalidades a tipos existentes
+
+// Square ahora se "conforma" al protocolo `Printable`
+extension Square: Printable {
+ var description: String {
+ return "Area: \(self.getArea()) - ID: \(self.identifier)"
+ }
+}
+
+print("Square: \(mySquare)")
+
+// También puedes hacer extend a tipos prefabricados (built-in)
+extension Int {
+ var customProperty: String {
+ return "This is \(self)"
+ }
+
+ func multiplyBy(num: Int) -> Int {
+ return num * self
+ }
+}
+
+print(7.customProperty) // "This is 7"
+print(14.multiplyBy(3)) // 42
+
+// Generics: Similar Java y C#. Utiliza la palabra clave `where` para
+// especificar los requerimientos de los genéricos.
+
+func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
+ for (index, value) in enumerate(array) {
+ if value == valueToFind {
+ return index
+ }
+ }
+ return nil
+}
+let foundAtIndex = findIndex([1, 2, 3, 4], 3)
+print(foundAtIndex == 2) // true
+
+// Operadores:
+// Operadores personalizados puede empezar con los siguientes caracteres:
+// / = - + * % < > ! & | ^ . ~
+// o
+// Caracteres unicode: math, symbol, arrow, dingbat, y line/box.
+prefix operator !!! {}
+
+// Un operador prefix que triplica la longitud del lado cuando es utilizado
+prefix func !!! (inout shape: Square) -> Square {
+ shape.sideLength *= 3
+ return shape
+}
+
+// Valor actual
+print(mySquare.sideLength) // 4
+
+// Cambiar la longitud del lado utilizando el operador !!!,
+// incrementa el tamaño por 3
+!!!mySquare
+print(mySquare.sideLength) // 12
+```
diff --git a/es-es/tmux-es.html.markdown b/es-es/tmux-es.html.markdown
new file mode 100644
index 00000000..a7354be1
--- /dev/null
+++ b/es-es/tmux-es.html.markdown
@@ -0,0 +1,253 @@
+---
+category: tool
+tool: tmux
+contributors:
+ - ["mdln", "https://github.com/mdln"]
+filename: LearnTmux-es.txt
+translators:
+ - ["Damaso Sanoja", "https://github.com/damasosanoja"]
+lang: es-es
+---
+
+
+[tmux](http://tmux.sourceforge.net)
+es un terminal multiplexor: habilita la creación, acceso y control
+de múltiples terminales controlados desde una sola pantalla. tmux
+puede ser separado de una pantalla y continuar corriendo en el fondo
+y luego ser insertado nuevamente.
+
+
+```
+
+ tmux [command] # Corre un comando
+ # 'tmux' sin comandos creará una nueva sesión
+
+ new # Crea una nueva sesión
+ -s "Session" # Crea sesión con nombre
+ -n "Window" # Crea ventana con nombre
+ -c "/dir" # Comienza en el directorio destino
+
+ attach # Adjunta sesión última/disponible
+ -t "#" # Adjunta sesión destino
+ -d # Separa la sesión de otras instancias
+
+ ls # Lista las sesiones abiertas
+ -a # Lista todas las sesiones abiertas
+
+ lsw # Lista las ventanas
+ -a # Lista todas las ventanas
+ -s # Lista todas las ventanas en la sesión
+
+ lsp # Lista los páneles
+ -a # Lista todos los páneles
+ -s # Lista todos los páneles de la sesión
+ -t # Lista los páneles de aplicación en el destino
+
+ kill-window # Cierra la ventana actual
+ -t "#" # Cierra la ventana destino
+ -a # Cierra todas las ventanas
+ -a -t "#" # Cierra todas las ventanas menos el destino
+
+ kill-session # Cierra la sesión actual
+ -t "#" # Cierra la sesión destino
+ -a # Cierra todas las sesiones
+ -a -t "#" # Cierra todas las sesiones menos el destino
+
+```
+
+
+### Atajos de Teclado
+
+El método para controlar una sesión adjunta tmux es mediante
+combinaciones de teclas llamadas teclas 'Prefijo'.
+
+```
+----------------------------------------------------------------------
+ (C-b) = Ctrl + b # combinación 'Prefijo' necesaria para usar atajos
+
+ (M-1) = Meta + 1 -o- Alt + 1
+----------------------------------------------------------------------
+
+ ? # Lista todos los atajos de teclado
+ : # Entra en la línea de comandos tmux
+ r # Fuerza el redibujado del cliente adjuntado
+ c # Crea una nueva ventana
+
+ ! # Separa el panel actual fuera de la ventana.
+ % # Separa el panel actual en dos, izquierdo y derecho
+ " # Separa el panel actual en dos, superior e inferior
+
+ n # Cambia a la siguiente ventana
+ p # Cambia a la ventana previa
+ { # Intercambia el panel actual con el anterior
+ } # Intercambia el panel actual con el próximo
+
+ s # Selecciona una nueva sesión para el cliente adjuntado
+ interactivamente
+ w # Elegir la ventana actual interactivamente
+ 0 al 9 # Seleccionar ventanas 0 al 9
+
+ d # Separa el cliente actual
+ D # Elige un cliente para separar
+
+ & # Cierra la ventana actual
+ x # Cierra el panel actual
+
+ Up, Down # Cambia al panel superior, inferior, izquierdo, o derecho
+ Left, Right
+
+ M-1 to M-5 # Organizar páneles:
+ # 1) uniformes horizontales
+ # 2) uniformes verticales
+ # 3) principal horizontal
+ # 4) principal vertical
+ # 5) mozaico
+
+ C-Up, C-Down # Redimensiona el panel actual en pasos de una celda
+ C-Left, C-Right
+
+ M-Up, M-Down # Redimensiona el panel actual en pasos de cinco celdas
+ M-Left, M-Right
+
+```
+
+
+### Configurando ~/.tmux.conf
+
+tmux.conf puede usarse para establecer opciones automáticas al arrancar, parecido a como .vimrc o init.el hacen.
+
+```
+# Ejemplo de tmux.conf
+# 2014.10
+
+
+### General
+###########################################################################
+
+# Habilita UTF-8
+setw -g utf8 on
+set-option -g status-utf8 on
+
+# Fuera de pantalla/Historia límite
+set -g history-limit 2048
+
+# Comienzo de índice
+set -g base-index 1
+
+# Ratón
+set-option -g mouse-select-pane on
+
+# Forza recarga de fichero de configuración
+unbind r
+bind r source-file ~/.tmux.conf
+
+
+### Atajos de teclado
+###########################################################################
+
+# Desvincula C-b como el prefijo por defecto
+unbind C-b
+
+# Establece el nuevo prefijo
+set-option -g prefix `
+
+# Regresa a la ventana previa cuando el prefijo es accionado dos veces
+bind C-a last-window
+bind ` last-window
+
+# Permite intercambiar C-a y ` usando F11/F12
+bind F11 set-option -g prefix C-a
+bind F12 set-option -g prefix `
+
+# Preferencias de atajos
+setw -g mode-keys vi
+set-option -g status-keys vi
+
+# Moviéndose entre paneles con movimientos de teclas vim
+bind h select-pane -L
+bind j select-pane -D
+bind k select-pane -U
+bind l select-pane -R
+
+# Ciclo/Intercambio de Ventana
+bind e previous-window
+bind f next-window
+bind E swap-window -t -1
+bind F swap-window -t +1
+
+# División rápida de paneles
+bind = split-window -h
+bind - split-window -v
+unbind '"'
+unbind %
+
+# Activar sesión mas interna (cuando se anida tmux) para enviar comandos
+bind a send-prefix
+
+
+### Temas
+###########################################################################
+
+# Paleta de Colores de la Barra de estado
+set-option -g status-justify left
+set-option -g status-bg black
+set-option -g status-fg white
+set-option -g status-left-length 40
+set-option -g status-right-length 80
+
+# Paleta de Colores del Borde del Panel
+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
+
+# Paleta de Colores de Mensajes
+set-option -g message-fg black
+set-option -g message-bg green
+
+# Paleta de Colores de la Ventana
+setw -g window-status-bg black
+setw -g window-status-current-fg green
+setw -g window-status-bell-attr default
+setw -g window-status-bell-fg red
+setw -g window-status-content-attr default
+setw -g window-status-content-fg yellow
+setw -g window-status-activity-attr default
+setw -g window-status-activity-fg yellow
+
+
+### UI
+###########################################################################
+
+# Notificación
+setw -g monitor-activity on
+set -g visual-activity on
+set-option -g bell-action any
+set-option -g visual-bell off
+
+# Establece automáticamente títulos de ventanas
+set-option -g set-titles on
+set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not)
+
+# Ajustes de barra de estado
+set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]"
+
+# Muestra indicadores de rendimiento en barra de estado
+# Requiere https://github.com/thewtex/tmux-mem-cpu-load/
+set -g status-interval 4
+set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]"
+
+```
+
+
+### Referencias
+
+[Tmux | Inicio](http://tmux.sourceforge.net)
+
+[Tmux Manual](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)
+
+[Mostrar CPU/MEM % en barra de estado](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux)
diff --git a/es-es/visualbasic-es.html.markdown b/es-es/visualbasic-es.html.markdown
new file mode 100644
index 00000000..c7f581c0
--- /dev/null
+++ b/es-es/visualbasic-es.html.markdown
@@ -0,0 +1,286 @@
+---
+language: Visual Basic
+contributors:
+ - ["Brian Martin", "http://brianmartin.biz"]
+translators:
+ - ["Adolfo Jayme Barrientos", "https://github.com/fitojb"]
+author: Brian Martin
+author_url: https://github.com/fitojb
+filename: learnvisualbasic-es.vb
+lang: es-es
+---
+
+```vb
+Module Module1
+
+ Sub Main()
+ ' Un vistazo rápido a las aplicaciones de consola de Visual Basic antes
+ ' de que profundicemos en el tema.
+ ' El apóstrofo inicia una línea de comentario.
+ ' Para explorar este tutorial dentro del Compilador de Visual Basic,
+ ' he creado un sistema de navegación.
+ ' Dicho sistema se explicará a medida que avancemos en este
+ ' tutorial; gradualmente entenderás lo que significa todo.
+ Console.Title = ("Aprende X en Y minutos")
+ Console.WriteLine("NAVEGACIÓN") 'Mostrar
+ Console.WriteLine("")
+ Console.ForegroundColor = ConsoleColor.Green
+ Console.WriteLine("1. Salida «Hola, mundo»")
+ Console.WriteLine("2. Entrada «Hola, mundo»")
+ Console.WriteLine("3. Calcular números enteros")
+ Console.WriteLine("4. Calcular números decimales")
+ Console.WriteLine("5. Una calculadora funcional")
+ Console.WriteLine("6. Uso de bucles «Do While»")
+ Console.WriteLine("7. Uso de bucles «For While»")
+ Console.WriteLine("8. Declaraciones condicionales")
+ Console.WriteLine("9. Selecciona una bebida")
+ Console.WriteLine("50. Acerca de")
+ Console.WriteLine("Elige un número de la lista anterior")
+ Dim selection As String = Console.ReadLine
+ Select Case selection
+ Case "1" 'Salida «hola, mundo»
+ Console.Clear() 'Limpia la consola y abre la subrutina privada
+ SalidaHolaMundo() 'Abre la subrutina privada nombrada
+ Case "2" 'Entrada «hola, mundo»
+ Console.Clear()
+ EntradaHolaMundo()
+ Case "3" 'Calcular números enteros
+ Console.Clear()
+ CalcularNumerosEnteros()
+ Case "4" 'Calcular números decimales
+ Console.Clear()
+ CalcularNumerosDecimales()
+ Case "5" 'Una calculadora funcional
+ Console.Clear()
+ CalculadoraFuncional()
+ Case "6" 'Uso de bucles «Do While»
+ Console.Clear()
+ UsoBuclesDoWhile()
+ Case "7" 'Uso de bucles «For While»
+ Console.Clear()
+ UsoBuclesFor()
+ Case "8" 'Declaraciones condicionales
+ Console.Clear()
+ DeclaracionCondicional()
+ Case "9" 'Declaración «If/Else»
+ Console.Clear()
+ DeclaracionIfElse() 'Selecciona una bebida
+ Case "50" 'Cuadro de mensaje «Acerca de»
+ Console.Clear()
+ Console.Title = ("Aprende X en Y minutos :: Acerca de")
+ MsgBox("Tutorial escrito por Brian Martin (@BrianMartinn")
+ Console.Clear()
+ Main()
+ Console.ReadLine()
+
+ End Select
+ End Sub
+
+ 'Uno - He usado números para guiarme por el sistema de navegación anterior
+ 'cuando regrese posteriormente a implementarlo.
+
+ 'Usamos subrutinas privadas para separar distintas secciones del programa.
+ Private Sub SalidaHolaMundo()
+ 'Título de la aplicación de consola
+ Console.Title = "Salida «Hola, mundo» | Aprende X en Y minutos"
+ 'Usa Console.Write("") o Console.WriteLine("") para mostrar salidas.
+ 'Seguido por Console.Read(), o bien, Console.Readline()
+ 'Console.ReadLine() muestra la salida en la consola.
+ Console.WriteLine("Hola, mundo")
+ Console.ReadLine()
+ End Sub
+
+ 'Dos
+ Private Sub EntradaHolaMundo()
+ Console.Title = "«Hola, mundo, soy...» | Aprende X en Y minutos"
+ ' Variables
+ ' Los datos que introduzca un usuario deben almacenarse.
+ ' Las variables también empiezan por Dim y terminan por As VariableType.
+
+ ' En este tutorial queremos conocer tu nombre y hacer que el programa
+ ' responda a este.
+ Dim nombredeusuario As String
+ 'Usamos «string» porque es una variable basada en texto.
+ Console.WriteLine("Hola, ¿cómo te llamas? ") 'Preguntar nombre de usuario.
+ nombredeusuario = Console.ReadLine() 'Almacenar nombre del usuario.
+ Console.WriteLine("Hola, " + nombredeusuario) 'La salida es Hola, nombre
+ Console.ReadLine() 'Muestra lo anterior.
+ 'El código anterior te hará una pregunta y mostrará la respuesta.
+ 'Entre otras variables está Integer, la cual usaremos para números enteros.
+ End Sub
+
+ 'Tres
+ Private Sub CalcularNumerosEnteros()
+ Console.Title = "Calcular números enteros | Aprende X en Y minutos"
+ Console.Write("Primer número: ") 'Escribe un núm. entero, 1, 2, 104, etc
+ Dim a As Integer = Console.ReadLine()
+ Console.Write("Segundo número: ") 'Escribe otro número entero.
+ Dim b As Integer = Console.ReadLine()
+ Dim c As Integer = a + b
+ Console.WriteLine(c)
+ Console.ReadLine()
+ 'Lo anterior es una calculadora sencilla
+ End Sub
+
+ 'Cuatro
+ Private Sub CalcularNumerosDecimales()
+ Console.Title = "Calcular con tipo doble | Aprende X en Y minutos"
+ 'Por supuesto, nos gustaría sumar decimales.
+ 'Por ello podríamos cambiar del tipo Integer al Double.
+
+ 'Escribe un número fraccionario, 1.2, 2.4, 50.1, 104.9 etc
+ Console.Write("Primer número: ")
+ Dim a As Double = Console.ReadLine
+ Console.Write("Segundo número: ") 'Escribe el segundo número.
+ Dim b As Double = Console.ReadLine
+ Dim c As Double = a + b
+ Console.WriteLine(c)
+ Console.ReadLine()
+ 'Este programa puede sumar 1.1 y 2.2
+ End Sub
+
+ 'Cinco
+ Private Sub CalculadoraFuncional()
+ Console.Title = "La calculadora funcional | Aprende X en Y minutos"
+ 'Pero si quieres que la calculadora reste, divida, multiplique y
+ 'sume.
+ 'Copia y pega lo anterior.
+ Console.Write("Primer número: ")
+ Dim a As Double = Console.ReadLine
+ Console.Write("Segundo número: ")
+ Dim b As Integer = Console.ReadLine
+ Dim c As Integer = a + b
+ Dim d As Integer = a * b
+ Dim e As Integer = a - b
+ Dim f As Integer = a / b
+
+ 'Mediante las líneas siguientes podremos restar,
+ 'multiplicar y dividir los valores a y b
+ Console.Write(a.ToString() + " + " + b.ToString())
+ 'Queremos dar un margen izquierdo de 3 espacios a los resultados.
+ Console.WriteLine(" = " + c.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " * " + b.ToString())
+ Console.WriteLine(" = " + d.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " - " + b.ToString())
+ Console.WriteLine(" = " + e.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " / " + b.ToString())
+ Console.WriteLine(" = " + f.ToString.PadLeft(3))
+ Console.ReadLine()
+
+ End Sub
+
+ 'Seis
+ Private Sub UsoBuclesDoWhile()
+ 'Igual que la subrutina privada anterior
+ 'Esta vez preguntaremos al usuario si quiere continuar (¿sí o no?)
+ 'Usamos el bucle Do While porque no sabemos si el usuario quiere
+ 'usar el programa más de una vez.
+ Console.Title = "Uso de bucles «Do While» | Aprende X en Y minutos"
+ Dim respuesta As String 'Usamos la variable «String» porque la resp. es texto
+ Do 'Comenzamos el programa con
+ Console.Write("Primer número: ")
+ Dim a As Double = Console.ReadLine
+ Console.Write("Segundo número: ")
+ Dim b As Integer = Console.ReadLine
+ Dim c As Integer = a + b
+ Dim d As Integer = a * b
+ Dim e As Integer = a - b
+ Dim f As Integer = a / b
+
+ Console.Write(a.ToString() + " + " + b.ToString())
+ Console.WriteLine(" = " + c.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " * " + b.ToString())
+ Console.WriteLine(" = " + d.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " - " + b.ToString())
+ Console.WriteLine(" = " + e.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " / " + b.ToString())
+ Console.WriteLine(" = " + f.ToString.PadLeft(3))
+ Console.ReadLine()
+ 'Preguntar si el usuario quiere continuar. Desafortunadamente,
+ 'distingue entre mayúsculas y minúsculas.
+ Console.Write("¿Quieres continuar? (s / n)")
+ 'El programa toma la variable, la muestra y comienza de nuevo.
+ respuesta = Console.ReadLine
+ 'La orden que hará funcionar esta variable es en este caso «s»
+ Loop While respuesta = "s"
+
+ End Sub
+
+ 'Siete
+ Private Sub UsoBuclesFor()
+ 'A veces el programa debe ejecutarse solo una vez.
+ 'En este programa contaremos a partir de 10.
+
+ Console.Title = "Uso de bucles «For» | Aprende X en Y minutos"
+ 'Declarar Variable y desde qué número debe contar en Step -1,
+ 'Step -2, Step -3, etc.
+ For i As Integer = 10 To 0 Step -1
+ Console.WriteLine(i.ToString) 'Muestra el valor del contador
+ Next i 'Calcular el valor nuevo
+ Console.WriteLine("Iniciar") '¡¡Comencemos el programa, nene!!
+ Console.ReadLine() '¡¡ZAS!! - Quizá me he emocionado bastante :)
+ End Sub
+
+ 'Ocho
+ Private Sub DeclaracionCondicional()
+ Console.Title = "Declaraciones condicionales | Aprende X en Y minutos"
+ Dim nombredeUsuario As String = Console.ReadLine
+ Console.WriteLine("Hola, ¿cómo te llamas? ") 'Preguntar nombre de usuario.
+ nombredeUsuario = Console.ReadLine() 'Almacena el nombre de usuario.
+ If nombredeUsuario = "Adam" Then
+ Console.WriteLine("Hola, Adam")
+ Console.WriteLine("Gracias por crear este útil sitio web")
+ Console.ReadLine()
+ Else
+ Console.WriteLine("Hola, " + nombredeUsuario)
+ Console.WriteLine("¿Has visitado www.learnxinyminutes.com?")
+ Console.ReadLine() 'Termina y muestra la declaración anterior.
+ End If
+ End Sub
+
+ 'Nueve
+ Private Sub DeclaracionIfElse()
+ Console.Title = "Declaración «If / Else» | Aprende X en Y minutos"
+ 'A veces es importante considerar más de dos alternativas.
+ 'A veces, algunas de estas son mejores.
+ 'Cuando esto sucede, necesitaríamos más de una declaración «if».
+ 'Una declaración «if» es adecuada para máquinas expendedoras.
+ 'En las que el usuario escribe un código (A1, A2, A3) para elegir.
+ 'Pueden combinarse todas las elecciones en una sola declaración «if».
+
+ Dim seleccion As String = Console.ReadLine 'Valor de la selección
+ Console.WriteLine("A1. para 7Up")
+ Console.WriteLine("A2. para Fanta")
+ Console.WriteLine("A3. para Dr. Pepper")
+ Console.WriteLine("A4. para Coca-Cola")
+ Console.ReadLine()
+ If selection = "A1" Then
+ Console.WriteLine("7up")
+ Console.ReadLine()
+ ElseIf selection = "A2" Then
+ Console.WriteLine("fanta")
+ Console.ReadLine()
+ ElseIf selection = "A3" Then
+ Console.WriteLine("dr. pepper")
+ Console.ReadLine()
+ ElseIf selection = "A4" Then
+ Console.WriteLine("coca-cola")
+ Console.ReadLine()
+ Else
+ Console.WriteLine("Selecciona un producto")
+ Console.ReadLine()
+ End If
+
+ End Sub
+
+End Module
+
+```
+
+## Referencias
+
+Aprendí Visual Basic en la aplicación de consola. Esta me permitió entender los principios de la programación para, posteriormente, aprender otros lenguajes con facilidad.
+
+He creado un <a href="http://www.vbbootcamp.co.uk/" Title="Tutorial de Visual Basic">tutorial de Visual Basic</a> más exhaustivo para quienes quieran saber más.
+
+Toda la sintaxis es válida. Copia el código y pégalo en el compilador de Visual Basic y ejecuta (F5) el programa.
diff --git a/fa-ir/brainfuck.html.markdown b/fa-ir/bf-fa.html.markdown
index ef2bcba3..bc5d8dc4 100644
--- a/fa-ir/brainfuck.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/javascript.html.markdown b/fa-ir/javascript-fa.html.markdown
index fe3555af..fe3555af 100644
--- a/fa-ir/javascript.html.markdown
+++ b/fa-ir/javascript-fa.html.markdown
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/go-fi.html.markdown b/fi-fi/go-fi.html.markdown
new file mode 100644
index 00000000..9ed4e0d2
--- /dev/null
+++ b/fi-fi/go-fi.html.markdown
@@ -0,0 +1,441 @@
+---
+name: Go
+category: language
+language: Go
+filename: learngo-fi.go
+contributors:
+ - ["Sonia Keys", "https://github.com/soniakeys"]
+ - ["Christopher Bess", "https://github.com/cbess"]
+ - ["Jesse Johnson", "https://github.com/holocronweaver"]
+ - ["Quint Guvernator", "https://github.com/qguv"]
+ - ["Jose Donizetti", "https://github.com/josedonizetti"]
+ - ["Alexej Friesen", "https://github.com/heyalexej"]
+ - ["Clayton Walker", "https://github.com/cwalk"]
+translators:
+ - ["Timo Virkkunen", "https://github.com/ComSecNinja"]
+lang: fi-fi
+---
+
+Go luotiin työn tekemistä varten. Se ei ole tietojenkäsittelyn uusin trendi,
+mutta se on uusin nopein tapa ratkaista oikean maailman ongelmia.
+
+Sillä on staattisesti tyypitetyistä imperatiivisista kielistä tuttuja
+konsepteja. Se kääntyy ja suorittuu nopeasti, lisää helposti käsitettävän
+samanaikaisten komentojen suorittamisen nykyaikaisten moniytimisten
+prosessoreiden hyödyntämiseksi ja antaa käyttäjälle ominaisuuksia suurten
+projektien käsittelemiseksi.
+
+Go tuo mukanaan loistavan oletuskirjaston sekä innokkaan yhteisön.
+
+```go
+// Yhden rivin kommentti
+/* Useamman
+ rivin kommentti */
+
+// Package -lausekkeella aloitetaan jokainen lähdekooditiedosto.
+// Main on erityinen nimi joka ilmoittaa
+// suoritettavan tiedoston kirjaston sijasta.
+package main
+
+// Import -lauseke ilmoittaa tässä tiedostossa käytetyt kirjastot.
+import (
+ "fmt" // Paketti Go:n oletuskirjastosta.
+ "io/ioutil" // Implementoi hyödyllisiä I/O -funktioita.
+ m "math" // Matematiikkakirjasto jolla on paikallinen nimi m.
+ "net/http" // Kyllä, web-palvelin!
+ "strconv" // Kirjainjonojen muuntajia.
+)
+
+// Funktion määrittelijä. Main on erityinen: se on ohjelman suorittamisen
+// aloittamisen alkupiste. Rakasta tai vihaa sitä, Go käyttää aaltosulkeita.
+func main() {
+ // Println tulostaa rivin stdoutiin.
+ // Se tulee paketin fmt mukana, joten paketin nimi on mainittava.
+ fmt.Println("Hei maailma!")
+
+ // Kutsu toista funktiota tämän paketin sisällä.
+ beyondHello()
+}
+
+// Funktioilla voi olla parametrejä sulkeissa.
+// Vaikkei parametrejä olisikaan, sulkeet ovat silti pakolliset.
+func beyondHello() {
+ var x int // Muuttujan ilmoittaminen: ne täytyy ilmoittaa ennen käyttöä.
+ x = 3 // Arvon antaminen muuttujalle.
+ // "Lyhyet" ilmoitukset käyttävät := joka päättelee tyypin, ilmoittaa
+ // sekä antaa arvon muuttujalle.
+ y := 4
+ sum, prod := learnMultiple(x, y) // Funktio palauttaa kaksi arvoa.
+ fmt.Println("summa:", sum, "tulo:", prod) // Yksinkertainen tuloste.
+ learnTypes() // < y minuuttia, opi lisää!
+}
+
+/* <- usean rivin kommentti
+Funktioilla voi olla parametrejä ja (useita!) palautusarvoja.
+Tässä `x`, `y` ovat argumenttejä ja `sum`, `prod` ovat ne, mitä palautetaan.
+Huomaa että `x` ja `sum` saavat tyyin `int`.
+*/
+func learnMultiple(x, y int) (sum, prod int) {
+ return x + y, x * y // Palauta kaksi arvoa.
+}
+
+// Sisäänrakennettuja tyyppejä ja todellisarvoja.
+func learnTypes() {
+ // Lyhyt ilmoitus antaa yleensä haluamasi.
+ str := "Opi Go!" // merkkijonotyyppi.
+
+ s2 := `"raaka" todellisarvoinen merrkijono
+voi sisältää rivinvaihtoja.` // Sama merkkijonotyyppi.
+
+ // Ei-ASCII todellisarvo. Go-lähdekoodi on UTF-8.
+ g := 'Σ' // riimutyyppi, lempinimi int32:lle, sisältää unicode-koodipisteen.
+
+ f := 3.14195 //float64, IEEE-754 64-bittinen liukuluku.
+ c := 3 + 4i // complex128, sisäisesti ilmaistu kahdella float64:lla.
+
+ // var -syntaksi alkuarvoilla.
+ var u uint = 7 // Etumerkitön, toteutus riippuvainen koosta kuten int.
+ var pi float32 = 22. / 7
+
+ // Muuntosyntaksi lyhyellä ilmoituksella.
+ n := byte('\n') // byte on leminimi uint8:lle.
+
+ // Listoilla on kiinteä koko kääntöhetkellä.
+ var a4 [4]int // 4 int:in lista, alkiot ovat alustettu nolliksi.
+ a3 := [...]int{3, 1, 5} // Listan alustaja jonka kiinteäksi kooksi tulee 3
+ // alkiota, jotka saavat arvot 3, 1, ja 5.
+
+ // Siivuilla on muuttuva koko. Sekä listoilla että siivuilla on puolensa,
+ // mutta siivut ovat yleisempiä käyttötapojensa vuoksi.
+ s3 := []int{4, 5, 9} // Vertaa a3: ei sananheittoa (...).
+ s4 := make([]int, 4) // Varaa 4 int:n siivun, alkiot alustettu nolliksi.
+ var d2 [][]float64 // Vain ilmoitus, muistia ei varata.
+ bs := []byte("a slice") // Tyypinmuuntosyntaksi.
+
+ // Koska siivut ovat dynaamisia, niitä voidaan yhdistellä sellaisinaan.
+ // Lisätäksesi alkioita siivuun, käytä sisäänrakennettua append()-funktiota.
+ // Ensimmäinen argumentti on siivu, johon alkoita lisätään.
+ s := []int{1, 2, 3} // Tuloksena on kolmen alkion pituinen lista.
+ s = append(s, 4, 5, 6) // Lisätty kolme alkiota. Siivun pituudeksi tulee 6.
+ fmt.Println(s) // Päivitetty siivu on nyt [1 2 3 4 5 6]
+
+ // Lisätäksesi siivun toiseen voit antaa append-funktiolle referenssin
+ // siivuun tai todellisarvoiseen siivuun lisäämällä sanaheiton argumentin
+ // perään. Tämä tapa purkaa siivun alkiot ja lisää ne siivuun s.
+ s = append(s, []int{7, 8, 9}...) // 2. argumentti on todellisarvoinen siivu.
+ fmt.Println(s) // Päivitetty siivu on nyt [1 2 3 4 5 6 7 8 9]
+
+ p, q := learnMemory() // Ilmoittaa p ja q olevan tyyppiä osoittaja int:iin.
+ fmt.Println(*p, *q) // * seuraa osoittajaa. Tämä tulostaa kaksi int:ä.
+
+ // Kartat ovat dynaamisesti kasvavia assosiatiivisia listoja, kuten hash tai
+ // dictionary toisissa kielissä.
+ m := map[string]int{"three": 3, "four": 4}
+ m["one"] = 1
+
+ // Käyttämättömät muuttujat ovat virheitä Go:ssa.
+ // Alaviiva antaa sinun "käyttää" muuttujan mutta hylätä sen arvon.
+ _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs
+ // Tulostaminen tietysti lasketaan muuttujan käyttämiseksi.
+ fmt.Println(s, c, a4, s3, d2, m)
+
+ learnFlowControl() // Takaisin flowiin.
+}
+
+// Go:ssa on useista muista kielistä poiketen mahdollista käyttää nimettyjä
+// palautusarvoja.
+// Nimen antaminen palautettavan arvon tyypille funktion ilmoitusrivillä
+// mahdollistaa helpon palaamisen useasta eri funktion suorituskohdasta sekä
+// pelkän return-lausekkeen käytön ilman muita mainintoja.
+func learnNamedReturns(x, y int) (z int) {
+ z = x * y
+ return // z on epäsuorasti tässä, koska nimesimme sen aiemmin.
+}
+
+// Go kerää kaikki roskansa. Siinä on osoittajia mutta ei niiden laskentoa.
+// Voit tehdä virheen mitättömällä osoittajalla, mutta et
+// kasvattamalla osoittajaa.
+func learnMemory() (p, q *int) {
+ // Nimetyillä palautusarvoilla p ja q on tyyppi osoittaja int:iin.
+ p = new(int) // Sisäänrakennettu funktio new varaa muistia.
+ // Varattu int on alustettu nollaksi, p ei ole enää mitätön.
+ s := make([]int, 20) // Varaa 20 int:ä yhteen kohtaan muistissa.
+ s[3] = 7 // Anna yhdelle niistä arvo.
+ r := -2 // Ilmoita toinen paikallinen muuttuja.
+ return &s[3], &r // & ottaa asian osoitteen muistissa.
+}
+
+func expensiveComputation() float64 {
+ return m.Exp(10)
+}
+
+func learnFlowControl() {
+ // If -lausekkeet vaativat aaltosulkeet mutta ei tavallisia sulkeita.
+ if true {
+ fmt.Println("mitä mä sanoin")
+ }
+ // Muotoilu on standardoitu käyttämällä komentorivin komentoa "go fmt".
+ if false {
+ // Nyrpistys.
+ } else {
+ // Nautinto.
+ }
+ // Käytä switch -lauseketta ketjutettujen if -lausekkeiden sijasta.
+ x := 42.0
+ switch x {
+ case 0:
+ case 1:
+ case 42:
+ // Tapaukset eivät "tipu läpi".
+ /*
+ Kuitenkin meillä on erikseen `fallthrough` -avainsana. Katso:
+ https://github.com/golang/go/wiki/Switch#fall-through
+ */
+ case 43:
+ // Saavuttamaton.
+ default:
+ // Oletustapaus (default) on valinnainen.
+ }
+ // Kuten if, for -lauseke ei myöskään käytä tavallisia sulkeita.
+ // for- ja if- lausekkeissa ilmoitetut muuttujat ovat paikallisia niiden
+ // piireissä.
+ for x := 0; x < 3; x++ { // ++ on lauseke. Sama kuin "x = x + 1".
+ fmt.Println("iteraatio", x)
+ }
+ // x == 42 tässä.
+
+ // For on kielen ainoa silmukkalauseke mutta sillä on vaihtoehtosia muotoja.
+ for { // Päättymätön silmukka.
+ break // Kunhan vitsailin.
+ continue // Saavuttamaton.
+ }
+
+ // Voit käyttää range -lauseketta iteroidaksesi listojen, siivujen, merkki-
+ // jonojen, karttojen tai kanavien läpi. range palauttaa yhden (kanava) tai
+ // kaksi arvoa (lista, siivu, merkkijono ja kartta).
+ for key, value := range map[string]int{"yksi": 1, "kaksi": 2, "kolme": 3} {
+ // jokaista kartan paria kohden, tulosta avain ja arvo
+ fmt.Printf("avain=%s, arvo=%d\n", key, value)
+ }
+
+ // Kuten for -lausekkeessa := if -lausekkeessa tarkoittaa ilmoittamista ja
+ // arvon asettamista.
+ // Aseta ensin y, sitten testaa onko y > x.
+ if y := expensiveComputation(); y > x {
+ x = y
+ }
+ // Todellisarvoiset funktiot ovat sulkeumia.
+ xBig := func() bool {
+ return x > 10000 // Viittaa ylempänä ilmoitettuun x:ään.
+ }
+ fmt.Println("xBig:", xBig()) // tosi (viimeisin arvo on e^10).
+ x = 1.3e3 // Tämä tekee x == 1300
+ fmt.Println("xBig:", xBig()) // epätosi nyt.
+
+ // Lisäksi todellisarvoiset funktiot voidaan samalla sekä ilmoittaa että
+ // kutsua, jolloin niitä voidaan käyttää funtioiden argumentteina kunhan:
+ // a) todellisarvoinen funktio kutsutaan välittömästi (),
+ // b) palautettu tyyppi vastaa odotettua argumentin tyyppiä.
+ fmt.Println("Lisää ja tuplaa kaksi numeroa: ",
+ func(a, b int) int {
+ return (a + b) * 2
+ }(10, 2)) // Kutsuttu argumenteilla 10 ja 2
+ // => Lisää ja tuplaa kaksi numeroa: 24
+
+ // Kun tarvitset sitä, rakastat sitä.
+ goto love
+love:
+
+ learnFunctionFactory() // Funktioita palauttavat funktiot
+ learnDefer() // Nopea kiertoreitti tärkeään avainsanaan.
+ learnInterfaces() // Hyvää kamaa tulossa!
+}
+
+func learnFunctionFactory() {
+ // Seuraavat kaksi ovat vastaavia, mutta toinen on käytännöllisempi
+ fmt.Println(sentenceFactory("kesä")("Kaunis", "päivä!"))
+
+ d := sentenceFactory("kesä")
+ fmt.Println(d("Kaunis", "päivä!"))
+ fmt.Println(d("Laiska", "iltapäivä!"))
+}
+
+// Somisteet ovat yleisiä toisissa kielissä. Sama saavutetaan Go:ssa käyttämällä
+// todellisarvoisia funktioita jotka ottavat vastaan argumentteja.
+func sentenceFactory(mystring string) func(before, after string) string {
+ return func(before, after string) string {
+ return fmt.Sprintf("%s %s %s", before, mystring, after) // uusi jono
+ }
+}
+
+func learnDefer() (ok bool) {
+ // Lykätyt lausekkeet suoritetaan juuri ennen funktiosta palaamista.
+ defer fmt.Println("lykätyt lausekkeet suorittuvat")
+ defer fmt.Println("käänteisessä järjestyksessä (LIFO).")
+ defer fmt.Println("\nTämä rivi tulostuu ensin, koska")
+ // Defer -lauseketta käytetään yleisesti tiedoston sulkemiseksi, jotta
+ // tiedoston sulkeva funktio pysyy lähellä sen avannutta funktiota.
+ return true
+}
+
+// Määrittele Stringer rajapintatyypiksi jolla on
+// yksi jäsenfunktio eli metodi, String.
+type Stringer interface {
+ String() string
+}
+
+// Määrittele pair rakenteeksi jossa on kaksi kenttää, x ja y tyyppiä int.
+type pair struct {
+ x, y int
+}
+
+// Määrittele jäsenfunktio pair:lle. Pair tyydyttää nyt Stringer -rajapinnan.
+func (p pair) String() string { // p:tä kutsutaan nimellä "receiver"
+ // Sprintf on toinen julkinen funktio paketissa fmt.
+ // Pistesyntaksilla viitataan P:n kenttiin.
+ return fmt.Sprintf("(%d, %d)", p.x, p.y)
+}
+
+func learnInterfaces() {
+ // Aaltosuljesyntaksi on "todellisarvoinen rakenne". Se todentuu alustetuksi
+ // rakenteeksi. := -syntaksi ilmoittaa ja alustaa p:n täksi rakenteeksi.
+ p := pair{3, 4}
+ fmt.Println(p.String()) // Kutsu p:n (tyyppiä pair) jäsenfunktiota String.
+ var i Stringer // Ilmoita i Stringer-rajapintatyypiksi.
+ i = p // Pätevä koska pair tyydyttää rajapinnan Stringer.
+ // Kutsu i:n (Stringer) jäsenfunktiota String. Tuloste on sama kuin yllä.
+ fmt.Println(i.String())
+
+ // Funktiot fmt-paketissa kutsuvat argumenttien String-jäsenfunktiota
+ // selvittääkseen onko niistä saatavilla tulostettavaa vastinetta.
+ fmt.Println(p) // Tuloste on sama kuin yllä. Println kutsuu String-metodia.
+ fmt.Println(i) // Tuloste on sama kuin yllä.
+
+ learnVariadicParams("loistavaa", "oppimista", "täällä!")
+}
+
+// Funktioilla voi olla muuttuva eli variteettinen
+// määrä argumentteja eli parametrejä.
+func learnVariadicParams(myStrings ...interface{}) {
+ // Iteroi jokaisen argumentin läpi.
+ // Tässä alaviivalla sivuutetaan argumenttilistan kunkin kohdan indeksi.
+ for _, param := range myStrings {
+ fmt.Println("param:", param)
+ }
+
+ // Luovuta variteettinen arvo variteettisena parametrinä.
+ fmt.Println("params:", fmt.Sprintln(myStrings...))
+
+ learnErrorHandling()
+}
+
+func learnErrorHandling() {
+ // "; ok" -muotoa käytetään selvittääksemme toimiko jokin vai ei.
+ m := map[int]string{3: "kolme", 4: "neljä"}
+ if x, ok := m[1]; !ok { // ok on epätosi koska 1 ei ole kartassa.
+ fmt.Println("ei ketään täällä")
+ } else {
+ fmt.Print(x) // x olisi arvo jos se olisi kartassa.
+ }
+ // Virhearvo voi kertoa muutakin ongelmasta.
+ if _, err := strconv.Atoi("ei-luku"); err != nil { // _ sivuuttaa arvon
+ // tulostaa strconv.ParseInt: parsing "ei-luku": invalid syntax
+ fmt.Println(err)
+ }
+ // Palaamme rajapintoihin hieman myöhemmin. Sillä välin,
+ learnConcurrency()
+}
+
+// c on kanava, samanaikaisturvallinen viestintäolio.
+func inc(i int, c chan int) {
+ c <- i + 1 // <- on "lähetysoperaattori" kun kanava on siitä vasemmalla.
+}
+
+// Käytämme inc -funktiota samanaikaiseen lukujen lisäämiseen.
+func learnConcurrency() {
+ // Sama make -funktio jota käytimme aikaisemmin siivun luomiseksi. Make
+ // varaa muistin ja alustaa siivut, kartat ja kanavat.
+ c := make(chan int)
+ // Aloita kolme samanaikaista gorutiinia (goroutine). Luvut kasvavat
+ // samanaikaisesti ja ehkäpä rinnakkain jos laite on kykenevä ja oikein
+ // määritelty. Kaikki kolme lähettävät samalle kanavalle.
+ go inc(0, c) // go -lauseke aloittaa uuden gorutiinin.
+ go inc(10, c)
+ go inc(-805, c)
+ // Lue kolme palautusarvoa kanavalta ja tulosta ne.
+ // Niiden saapumisjärjestystä ei voida taata!
+ // <- on "vastaanotto-operaattori" jos kanava on oikealla
+ fmt.Println(<-c, <-c, <-c)
+
+ cs := make(chan string) // Toinen kanava joka käsittelee merkkijonoja.
+ ccs := make(chan chan string) // Kanava joka käsittelee merkkijonokanavia.
+ go func() { c <- 84 }() // Aloita uusi gorutiini arvon lähettämiseksi.
+ go func() { cs <- "sanaa" }() // Uudestaan, mutta cs -kanava tällä kertaa.
+ // Select -lausekkeella on syntaksi kuten switch -lausekkeella mutta
+ // jokainen tapaus sisältää kanavaoperaation. Se valitsee satunnaisen
+ // tapauksen niistä kanavista, jotka ovat kommunikaatiovalmiita
+ select {
+ case i := <-c: // Vastaanotettu arvo voidaan antaa muuttujalle
+ fmt.Printf("se on %T", i)
+ case <-cs: // tai vastaanotettu arvo voidaan sivuuttaa.
+ fmt.Println("se on merkkijono")
+ case <-ccs: // Tyhjä kanava; ei valmis kommunikaatioon.
+ fmt.Println("ei tapahtunut.")
+ }
+ // Tässä vaiheessa arvo oli otettu joko c:ltä tai cs:ltä. Yksi kahdesta
+ // ylempänä aloitetusta gorutiinista on valmistunut, toinen pysyy tukossa.
+
+ learnWebProgramming() // Go tekee sitä. Sinäkin haluat tehdä sitä.
+}
+
+// Yksittäinen funktio http -paketista aloittaa web-palvelimen.
+func learnWebProgramming() {
+
+ // ListenAndServe:n ensimmäinen parametri on TCP-osoite, jota kuunnellaan.
+ // Toinen parametri on rajapinta, http.Handler.
+ go func() {
+ err := http.ListenAndServe(":8080", pair{})
+ fmt.Println(err) // älä sivuuta virheitä.
+ }()
+
+ requestServer()
+}
+
+// Tee pair:sta http.Handler implementoimalla sen ainoa metodi, ServeHTTP.
+func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ // Tarjoa dataa metodilla http.ResponseWriter.
+ w.Write([]byte("Opit Go:n Y minuutissa!"))
+}
+
+func requestServer() {
+ resp, err := http.Get("http://localhost:8080")
+ fmt.Println(err)
+ defer resp.Body.Close()
+ body, err := ioutil.ReadAll(resp.Body)
+ fmt.Printf("\nWeb-palvelin sanoo: `%s`", string(body))
+}
+```
+
+## Lisää luettavaa
+
+Go-tietämyksen alku ja juuri on sen [virallinen verkkosivu]()(http://golang.org/).
+Siellä voit seurata oppitunteja, askarrella vuorovaikutteisesti sekä lukea paljon.
+Kierroksen lisäksi [dokumentaatio](https://golang.org/doc/) pitää sisällään tietoa
+siistin Go-koodin kirjoittamisesta, pakettien ja komentojen käytöstä sekä julkaisuhistoriasta.
+
+Kielen määritelmä itsessään on suuresti suositeltavissa. Se on helppolukuinen ja
+yllättävän lyhyt (niissä määrin kuin kielimääritelmät nykypäivänä ovat.)
+
+Voit askarrella parissa kanssa [Go playgroundissa](https://play.golang.org/p/tnWMjr16Mm).
+Muuttele sitä ja aja se selaimestasi! Huomaa, että voit käyttää [https://play.golang.org](https://play.golang.org)
+[REPL:na](https://en.wikipedia.org/wiki/Read-eval-print_loop) testataksesi ja koodataksesi selaimessasi, ilman Go:n asentamista.
+
+Go:n opiskelijoiden lukulistalla on [oletuskirjaston lähdekoodi](http://golang.org/src/pkg/).
+Kattavasti dokumentoituna se antaa parhaan kuvan helppolukuisesta ja ymmärrettävästä Go-koodista,
+-tyylistä ja -tavoista. Voit klikata funktion nimeä [doukumentaatiossa](http://golang.org/pkg/) ja
+lähdekoodi tulee esille!
+
+Toinen loistava paikka oppia on [Go by example](https://gobyexample.com/).
+
+Go Mobile lisää tuen mobiilialustoille (Android ja iOS). Voit kirjoittaa pelkällä Go:lla natiiveja applikaatioita tai tehdä kirjaston joka sisältää sidoksia
+Go-paketista, jotka puolestaan voidaan kutsua Javasta (Android) ja Objective-C:stä (iOS). Katso [lisätietoja](https://github.com/golang/go/wiki/Mobile).
diff --git a/fi-fi/markdown-fi.html.markdown b/fi-fi/markdown-fi.html.markdown
new file mode 100644
index 00000000..c5ee52b0
--- /dev/null
+++ b/fi-fi/markdown-fi.html.markdown
@@ -0,0 +1,259 @@
+---
+language: markdown
+filename: markdown-fi.md
+contributors:
+ - ["Dan Turkel", "http://danturkel.com/"]
+translators:
+ - ["Timo Virkkunen", "https://github.com/ComSecNinja"]
+lang: fi-fi
+---
+
+John Gruber loi Markdownin vuona 2004. Sen tarkoitus on olla helposti luettava ja kirjoitettava syntaksi joka muuntuu helposti HTML:ksi (ja nyt myös moneksi muuksi formaatiksi).
+
+```markdown
+<!-- Jokainen HTML-tiedosto on pätevää Markdownia. Tämä tarkoittaa että voimme
+käyttää HTML-elementtejä Markdownissa, kuten kommentteja, ilman että markdown
+-jäsennin vaikuttaa niihin. Tästä johtuen et voi kuitenkaan käyttää markdownia
+HTML-elementtien sisällä jos luot sellaisen markdown-tiedostoon. -->
+
+<!-- Markdownin toteutus vaihtelee jäsentimestä toiseen. Tämä opas yrittää
+selventää mitkä ominaisuudet ovat yleisiä ja mitkä ovat eritysesti tiettyjen
+jäsentimien ominaisuuksia. -->
+
+<!-- Otsikot -->
+<!-- Voit luoda HTML-elementtejä <h1> - <h6> helposti aloittamalla rivin
+haluamallasi määrällä ristikkomerkkejä (#). -->
+# Tämä on <h1>
+## Tämä on <h2>
+### Tämä on <h3>
+#### Tämä on <h4>
+##### Tämä on <h5>
+###### Tämä on <h6>
+
+<!-- Markdownissa on myös vaihtoehtoisia tapoja ilmaista h1 ja h2. -->
+Tämä on h1
+=============
+
+Tämä on h2
+-------------
+
+<!-- Yksinkertaiset tekstimuotoilut -->
+<!-- Tekstin voi helposti muotoilla kursiiviksi tai lihavoiduksi. -->
+
+*Tämä teksti on kursivoitua.*
+_Kuten on myös tämä teksti._
+
+**Tämä teksti on lihavoitua.**
+__Kuten on tämäkin teksti.__
+
+***Tämä teksti on molempia.***
+**_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: -->
+
+~~Tämä teksti on yliviivattua.~~
+
+<!-- Kappaleet ovat yhdellä tai useammalla peräkkäisellä tekstirivillä jotka
+erotellaan yhdellä tai useammalla tyhjällä rivillä -->
+
+Tämä on kappala. Kirjoittelen kappaleeseen, eikö tämä olekin hauskaa?
+
+Nyt olen kappaleessa 2.
+Olen edelleen toisessa kappaleessa!
+
+
+Olen kolmannessa kappaleessa!
+
+<!-- Jos haluat lisätä <br /> HTML-elementin, päätä kappale kahdella tai
+useammalla välilyönnillä ja aloita sitten uusi kappale -->
+
+Päätän tämän kahteen välilyöntiin (maalaa minut nähdäksesi ne).
+
+There's a <br /> above me!
+
+<!-- Lainaukset ovat helppoja ja ne tehdään >-merkillä -->
+
+> Tämä on lainaus. Voit joko
+> manuaalisesti rivittää tekstisi ja laittaa >-merkin jokaisen rivin eteen tai antaa jäsentimen rivittää pitkät tekstirivit.
+> Sillä ei ole merkitystä kunhan rivit alkavat >-merkillä.
+
+> Voit myös käyttää useampaa
+>> sisennystasoa
+> Kuinka hienoa se on?
+
+<!-- Listat -->
+<!-- Järjestämättömät listat tehdään asteriskilla, plussalla tai viivalla -->
+
+* Kohta
+* Kohta
+* Kolmas kohta
+
+tai
+
++ Kohta
++ Kohta
++ Kolmas kohta
+
+tai
+
+- Kohta
+- Kohta
+- Kolmas kohta
+
+<!-- Järjestetyt listat tehdään järjestysluvuilla. -->
+
+1. Kohta yksi
+2. Kohta kaksi
+3. Kohta kolme
+
+<!-- Sinun ei tarvitse edes merkitä kohtia oikein ja silti markdown näyttää
+oikean järjestyksen, mutta se ei välttämättä ole hyvä idea. -->
+
+1. Kohta yksi
+1. Kohta kaksi
+1. Kohta kolme
+<!-- (Tämä korjaantuu samanlaiseksi kuin yllä oleva esimerkki) -->
+
+<!-- Voit myös käyttää alalistoja. -->
+
+1. Kohta yksi
+2. Kohta kaksi
+3. Kohta kolme
+ * Alakohta
+ * Alakohta
+4. Kohta neljä
+
+<!-- Myös tehtävälistoja on olemassa. Tämä tekee HTML-valintaruutuja. -->
+
+Alla olevat ruudut ilman x-merkkiä ovat merkitsemättömiä HTML-valintaruutuja.
+- [ ] Ensimmäinen suoritettava tehtävä.
+- [ ] Toinen tehtävä joka täytyy tehdä
+Tämä alla oleva ruutu on merkitty HTML-valintaruutu.
+- [x] Tämä tehtävä on suoritettu
+
+<!-- Koodiosiot -->
+<!-- Voit merkitä koodiosion (jaka käyttää <code> -elementtiä) sisentämällä
+rivin neljällä välilyönnillä tai tabulaattorilla. -->
+
+ Tämä on koodia
+ Kuten tämäkin
+
+<!-- Voit myös sisentää koodia samalla tavalla. -->
+
+ my_array.each do |item|
+ puts item
+ end
+
+<!-- Muun tekstin seassa oleva koodi merkitään kahden `-merkin väliin -->
+
+John ei tiennyt edes mitä `go_to()` -funktio teki!
+
+<!-- GitHubin Markdownissa voit käyttää erityissyntaksia koodille. -->
+
+\`\`\`ruby <!-- paitsi että poista nuo kenoviivat, vain ```ruby ! -->
+def foobar
+ puts "Hello world!"
+end
+\`\`\` <!-- tästä myös, ei kenoviivoja, vain ``` -->
+
+<!-- Yllä oleva teksti ei vaadi sisennystä. Lisäksi GitHub käyttää ``` jälkeen
+mainitsemasi kielen syntaksin korostusta -->
+
+<!-- Vaakaviiva (<hr />) -->
+<!-- Vaakaviivojen lisääminen käy näppärästi kolmella tai useammalla
+asteriskilla taikka viivalla, välilyönneillä tai ilman -->
+
+***
+---
+- - -
+****************
+
+<!-- Linkit -->
+<!-- yksi markdownin parhaita ominaisuuksia on yksinkertaiset hyperlinkit. Laita
+näytettävä teksti hakasulkuihin [] ja URL-osoite perään sulkeissa (). -->
+
+[Klikkaa tästä!](http://example.com/)
+
+<!-- Voit myös lisätä linkin otsikon heittomerkeissä osoitteen perään. -->
+
+[Klikkaa tästä!](http://example.com/ "Linkki Example.com:iin")
+
+<!-- Suhteelliset polut toimivat myös. -->
+
+[Musiikkia](/musiikki/).
+
+<!-- Markdown tukee myös viittaustyylisiä linkkejä. -->
+
+[Klikkaa tätä linkkiä][link1] saadaksesi lisätietoja!
+[Katso myös tämä linkki][foobar] jos haluat.
+
+[link1]: http://example.com/ "Siistii!"
+[foobar]: http://foobar.biz/ "Selkis!"
+
+<!-- Otsikko voi olla myös ykittäisissä heittomerkeissä tai sulkeissa, tai
+ohitettu kokonaan. Viittaukset voivat olla missä tahansa kohdassa dokumenttia ja
+viittausten ID:t voivat olla mitä tahansa kunhan ne ovat uniikkeja. -->
+
+<!-- Voit myös käyttää linkin tekstiä ID:nä näin: -->
+
+[This][] is a link.
+
+[this]: http://tämäonlinkki.com/
+
+<!-- Mutta tämä tapa ei ole yleinen. -->
+
+<!-- Kuvat -->
+<!-- Kuvat tehdään samalla tavalla kuin linkitkin, mutta huutomerkki edessä! -->
+
+![Kuvan alt-attribuutti](http://imgur.com/munkuva.jpg "Vaihtoehtoinen otsikko")
+
+<!-- Ja viittaukset toimivat odotetusti. -->
+
+![Tämä on se alt-attribuutti][munkuva]
+
+[munkuva]: suhteellinen/polku/siitii/kuva.jpg "otsikko tähän tarvittaessa"
+
+<!-- Sekalaista -->
+<!-- Automaattiset linkit -->
+
+<http://testwebsite.com/> on sama kuin
+[http://testwebsite.com/](http://testwebsite.com/)
+
+<!-- Automaattiset sähköpostilinkit -->
+
+<foo@bar.com>
+
+<!-- Varattujen merkkien käyttö -->
+
+haluan kirjoittaa *tämän tekstin jonka ympärillä on asteriskit* mutta en halua
+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ä -->
+
+Tietokoneesi kaatui? Kokeile painaa
+<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
+
+<!-- Taulukot -->
+<!-- Taulukot ovat saatavilla vain GitHubin markdownissa ja ne ovat melko
+vaivalloisia käyttää, mutta jos todella haluat: -->
+
+| Kolumni1 | Kolumni2 | Kolumni3 |
+| :----------- | :------: | ------------: |
+| Vasemmalle | Keskelle | Oikealle |
+| blaa | blaa | blaa |
+
+<!-- vaihtoehtoisesti, sama tulos -->
+
+Kolumni 1 | Kolumni 2 | Kolumni 3
+:-- | :-: | --:
+Hyi tämä on ruma | saa se | loppumaan
+
+<!-- Loppu! -->
+
+```
+
+Lisää tietoa löydät John Gruberin [virallisesta julkaisusta](http://daringfireball.net/projects/markdown/syntax)
+ja Adam Pritchardin loistavasta [lunttilapusta](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
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 f7c0bf34..b4a5581b 100644
--- a/forth.html.markdown
+++ b/forth.html.markdown
@@ -117,7 +117,7 @@ one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok
: threes ( n n -- ) ?do i . 3 +loop ; \ ok
15 0 threes \ 0 3 6 9 12 ok
-\ Indefinite loops with `begin` <stuff to do> <flag> `unil`:
+\ Indefinite loops with `begin` <stuff to do> <flag> `until`:
: death ( -- ) begin ." Are we there yet?" 0 until ; \ ok
\ ---------------------------- Variables and Memory ----------------------------
@@ -133,7 +133,7 @@ variable age \ ok
age @ . \ 21 ok
age ? \ 21 ok
-\ Constants are quite simiar, except we don't bother with memory addresses:
+\ Constants are quite similar, except we don't bother with memory addresses:
100 constant WATER-BOILING-POINT \ ok
WATER-BOILING-POINT . \ 100 ok
diff --git a/fr-fr/HTML-fr.html.markdown b/fr-fr/HTML-fr.html.markdown
new file mode 100644
index 00000000..4d2da921
--- /dev/null
+++ b/fr-fr/HTML-fr.html.markdown
@@ -0,0 +1,116 @@
+---
+language: html
+filename: learnhtml-fr.html
+contributors:
+ - ["Christophe THOMAS", "https://github.com/WinChris"]
+lang: fr-fr
+---
+
+HTML signifie HyperText Markup Language.
+C'est un langage (format de fichiers) qui permet d'écrire des pages internet.
+C’est un langage de balisage, il nous permet d'écrire des pages HTML au moyen de balises (Markup, en anglais).
+Les fichiers HTML sont en réalité de simple fichier texte.
+Qu'est-ce que le balisage ? C'est une façon de hiérarchiser ses données en les entourant par une balise ouvrante et une balise fermante.
+Ce balisage sert à donner une signification au texte ainsi entouré.
+Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parlons de HTML5.
+
+**NOTE :** Vous pouvez tester les différentes balises que nous allons voir au fur et à mesure du tutoriel sur des sites comme [codepen](http://codepen.io/pen/) afin de voir les résultats, comprendre, et vous familiariser avec le langage.
+Cet article porte principalement sur la syntaxe et quelques astuces.
+
+
+```html
+<!-- Les commentaires sont entouré comme cette ligne! -->
+
+<!-- #################### Les balises #################### -->
+
+<!-- Voici un exemple de fichier HTML que nous allons analyser -->
+<!-- Venez voir ce que ça donne -->
+
+<!doctype html>
+ <html>
+ <head>
+ <title>Mon Site</title>
+ </head>
+ <body>
+ <h1>Hello, world!</h1>
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Venez voir ce que ça donne</a>
+ <p>Ceci est un paragraphe</p>
+ <p>Ceci est un autre paragraphe</p>
+ <ul>
+ <li>Ceci est un item d'une liste non ordonnée (liste à puces)</li>
+ <li>Ceci est un autre item</li>
+ <li>Et ceci est le dernier item de la liste</li>
+ </ul>
+ </body>
+ </html>
+
+<!-- Un fichier HTML débute toujours par indiquer au navigateur que notre page est faite en HTML -->
+
+<!doctype html>
+
+<!-- Après ça on commence par ouvrir une balise <html> -->
+<html>
+</html>
+<!-- Et puis on la referme à la fin du fichier avec </html> -->
+<!-- après cette balise de fin, plus rien ne doit apparaître. -->
+
+<!-- À l'intérieur (entre la balise ouvrant et fermante <html></html>), on trouve : -->
+
+<!-- Un entête (<head> en anglais ; il faut le refermer avec </head>) -->
+<!-- L'entête contient des descriptions et informations annexes qui ne sont pas affichées : se sont les métadonnées -->
+
+<head>
+ <title>Mon Site</title><!-- La balise <title> permet d'indiquer au navigateur le titre à afficher dans la barre de l'onglet de la fenêtre -->
+</head>
+
+<!-- Après la balise <head>, on trouve la balise <body> -->
+<!-- Pour le moment, rien n'est encore affiché dans la fenêtre du navigateur. -->
+<!-- Il faut ensuite remplir le corps (balise <body>) avec du contenu -->
+
+<body>
+ <h1>Hello, world!</h1> <!-- La balise h1 permet de structurer le texte, c'est un titre -->
+ <!-- Il exite différents sous-titres à <h1> qui sont hiérarchisés du plus important (h2) au plus précis (h6) -->
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Venez voir ce que ça donne</a> <!-- Lien vers la source cible indiqué dans href="" -->
+ <p>Ceci est un paragraphe </p> <!-- La balise <p> permet d'inclure du texte à la page html -->
+ <p>Ceci est un autre paragraphe</p>
+ <ul> <!-- La balise <ul> permet d'introduire une liste à puces -->
+ <!-- Si on souhaite une liste ordonnée : <ol> liste numérotée, 1. pour le premier élément, 2. pour le second, etc -->
+ <li>Ceci est un item d'une liste non ordonnée (liste à puces)</li>
+ <li>Ceci est un autre item</li>
+ <li>Et ceci est le dernier item de la liste</li>
+ </ul>
+</body>
+
+<!-- Voilà comment créer un fichier HTML simple -->
+
+<!-- Mais il est possible d'ajouter encore des balises plus spécifiques -->
+
+<!-- Pour insérer une image -->
+<img src="http://i.imgur.com/XWG0O.gif"/> <!-- On indique la source de l'image dans src="" -->
+<!-- La source peut-être un URL ou encore la destination d'un fichier de votre ordinateur -->
+
+<!-- Il est possible de réaliser des tableaux également -->
+
+<table> <!-- On ouvre la balise <table> -->
+ <tr> <!-- <tr> permet de créer une ligne -->
+ <th>First Header</th> <!-- <th> permet de créer un titre au tableau -->
+ <th>Second Header</th>
+ </tr>
+ <tr>
+ <td>Première ligne, première cellule</td> <!-- <td> permet de créer une cellule -->
+ <td>Première ligne, deuxième cellule</td>
+ </tr>
+ <tr>
+ <td>Deuxième ligne, première cellule</td>
+ <td>Deuxième ligne, deuxième cellule</td>
+ </tr>
+</table>
+
+## Utilisation
+
+Le HTML s'écrit dans des fichiers `.html`.
+
+## En savoir plus
+
+* [Tutoriel HTML](http://slaout.linux62.org/html_css/html.html)
+* [W3School](http://www.w3schools.com/html/html_intro.asp)
diff --git a/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/clojure-fr.html.markdown b/fr-fr/clojure-fr.html.markdown
index d3c5a67b..63bc25b5 100644
--- a/fr-fr/clojure-fr.html.markdown
+++ b/fr-fr/clojure-fr.html.markdown
@@ -248,7 +248,7 @@ keymap ; => {:a 1, :b 2, :c 3}
; Il y a encore d'autres fonctions dans l'espace de nom clojure.sets.
-; Formes utiles
+; Formes et macros utiles
;;;;;;;;;;;;;;;
; Les constructions logiques en Clojure sont juste des macros, et
@@ -275,6 +275,33 @@ ressemblent à toutes les autres formes:
(let [name "Urkel"]
(print "Saying hello to " name)
(str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel")
+
+; Utilisez les Threading Macros (-> et ->>) pour exprimer plus
+; clairement vos transformations, en y pensant de manière multi-niveaux.
+
+; La "flèche simple" ou "Thread-first", insère, à chaque niveau
+; de la transformation, la forme courante en la seconde position
+; de la forme suivante, constituant à chaque fois un nouvel étage
+; de transformation. Par exemple:
+(->
+ {:a 1 :b 2}
+ (assoc :c 3) ;=> Génère ici (assoc {:a 1 :b 2} :c 3)
+ (dissoc :b)) ;=> Génère ici (dissoc (assoc {:a 1 :b 2} :c 3) :b)
+
+; Cette expression est ré-écrite en:
+; (dissoc (assoc {:a 1 :b 2} :c 3) :b)
+; et est évaluée en : {:a 1 :c 3}
+
+; La "flèche double" ou "Thread-last" procède de la même manière
+; que "->", mais insère le résultat de la réécriture de chaque
+; étage en dernière position. Par exemple:
+(->>
+ (range 10)
+ (map inc) ;=> Génère ici (map inc (range 10)
+ (filter odd?) ;=> Génère ici (filter odd? (map inc (range 10))
+ (into [])) ;=> Génère ici (into [] (filter odd? (map inc (range 10))), ce qui est évalué au final à;
+ ; [1 3 5 7 9]
+
; Modules
;;;;;;;;;;;;;;;
diff --git a/fr-fr/css-fr.html.markdown b/fr-fr/css-fr.html.markdown
index bdab9715..35673c47 100644
--- a/fr-fr/css-fr.html.markdown
+++ b/fr-fr/css-fr.html.markdown
@@ -8,7 +8,7 @@ translators:
lang: fr-fr
---
-Au début du web, il n'y avait pas d'élements visuels, simplement du texte pure. Mais avec le dévelopement des navigateurs,
+Au début du web, il n'y avait pas d'élements visuels, simplement du texte pur. Mais avec le dévelopement des navigateurs,
des pages avec du contenu visuel sont arrivées.
CSS est le langage standard qui existe et permet de garder une séparation entre
le contenu (HTML) et le style d'une page web.
@@ -16,8 +16,8 @@ le contenu (HTML) et le style d'une page web.
En résumé, CSS fournit une syntaxe qui vous permet de cibler des élements présents
sur une page HTML afin de leur donner des propriétés visuelles différentes.
-Comme tous les autres langages, CSS a plusieurs versions. Ici, nous allons parlons de CSS2.0
-qui n'est pas le plus récent, mais qui reste le plus utilisé et le plus compatible avec les différents navigateur.
+Comme tous les autres langages, CSS a plusieurs versions. Ici, nous allons parler de CSS2.0
+qui n'est pas le plus récent, mais qui reste le plus utilisé et le plus compatible avec les différents navigateurs.
**NOTE :** Vous pouvez tester les effets visuels que vous ajoutez au fur et à mesure du tutoriel sur des sites comme [dabblet](http://dabblet.com/) afin de voir les résultats, comprendre, et vous familiariser avec le langage.
Cet article porte principalement sur la syntaxe et quelques astuces.
@@ -33,7 +33,7 @@ Cet article porte principalement sur la syntaxe et quelques astuces.
/* Généralement, la première déclaration en CSS est très simple */
selecteur { propriete: valeur; /* autres proprietés...*/ }
-/* Le sélécteur sert à cibler un élément du HTML
+/* Le sélecteur sert à cibler un élément du HTML
Vous pouvez cibler tous les éléments d'une page! */
* { color:red; }
diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown
new file mode 100644
index 00000000..bfb9f2ce
--- /dev/null
+++ b/fr-fr/d.html.markdown
@@ -0,0 +1,264 @@
+---
+language: D
+filename: learnd-fr.d
+contributors:
+ - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"]
+translators:
+ - ["Quentin Ladeveze", "aceawan.eu"]
+lang: fr-fr
+---
+
+```c
+// Commençons par un classique
+module hello;
+
+import std.stdio;
+
+// args n'est pas obligatoire
+void main(string[] args) {
+ writeln("Bonjour le monde !");
+}
+```
+
+Si vous êtes comme moi et que vous passez beaucoup trop de temps sur internet, il y a
+de grandes chances pour que vous ayez déjà entendu parler du [D](http://dlang.org/).
+D est un langage de programmation moderne, généraliste, multi-paradigmes qui contient
+des fonctionnalités aussi bien de bas niveau que de haut niveau.
+
+D est activement développé par de nombreuses personnes très intelligents, guidées par
+[Walter Bright](https://fr.wikipedia.org/wiki/Walter_Bright))) et
+[Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu).
+Après cette petite introduction, jetons un coup d'oeil à quelques exemples.
+
+```c
+import std.stdio;
+
+void main() {
+ //Les conditions et les boucles sont classiques.
+ for(int i = 0; i < 10000; i++) {
+ writeln(i);
+ }
+
+ // On peut utiliser auto pour inférer automatiquement le
+ // type d'une variable.
+ auto n = 1;
+
+ // On peut faciliter la lecture des valeurs numériques
+ // en y insérant des `_`.
+ while(n < 10_000) {
+ n += n;
+ }
+
+ do {
+ n -= (n / 2);
+ } while(n > 0);
+
+ // For et while sont très utiles, mais en D, on préfère foreach.
+ // Les deux points : '..', créent un intervalle continue de valeurs
+ // incluant la première mais excluant la dernière.
+ foreach(i; 1..1_000_000) {
+ if(n % 2 == 0)
+ writeln(i);
+ }
+
+ // On peut également utiliser foreach_reverse pour itérer à l'envers.
+ foreach_reverse(i; 1..int.max) {
+ if(n % 2 == 1) {
+ writeln(i);
+ } else {
+ writeln("Non !");
+ }
+ }
+}
+```
+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.
+
+```c
+// Ici, 'T' est un paramètre de type. Il est similaire au <T> de C++/C#/Java.
+struct LinkedList(T) {
+ T data = null;
+
+ // Utilisez '!' pour instancier un type paramétré.
+ // Encore une fois semblable à '<T>'
+ LinkedList!(T)* next;
+}
+
+class BinTree(T) {
+ T data = null;
+
+ // Si il n'y a qu'un seul paramètre de template,
+ // on peut s'abstenir de mettre des parenthèses.
+ BinTree!T left;
+ BinTree!T right;
+}
+
+enum Day {
+ Sunday,
+ Monday,
+ Tuesday,
+ Wednesday,
+ Thursday,
+ Friday,
+ Saturday,
+}
+
+// Utilisez alias pour créer des abreviations pour les types.
+alias IntList = LinkedList!int;
+alias NumTree = BinTree!double;
+
+// On peut tout aussi bien créer des templates de function !
+T max(T)(T a, T b) {
+ if(a < b)
+ return b;
+
+ return a;
+}
+
+// On peut utiliser le mot-clé ref pour s'assurer que quelque chose est passé
+// par référence, et ceci, même si a et b sont d'ordinaire passés par valeur.
+// Ici ils seront toujours passés par référence à 'swap()'.
+void swap(T)(ref T a, ref T b) {
+ auto temp = a;
+
+ a = b;
+ b = temp;
+}
+
+// Avec les templates, on peut également passer des valeurs en paramètres.
+class Matrix(uint m, uint n, T = int) {
+ T[m] rows;
+ T[n] columns;
+}
+
+auto mat = new Matrix!(3, 3); // T est 'int' par défaut
+
+```
+À propos de classes, parlons des propriétés. Une propriété est, en gros,
+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.
+
+```c
+// Considérons une classe paramétrée avec les types 'T' et 'U'
+class MyClass(T, U) {
+ T _data;
+ U _other;
+}
+
+// Et des méthodes "getter" et "setter" comme suit:
+class MyClass(T, U) {
+ T _data;
+ U _other;
+
+ // Les constructeurs s'apellent toujours 'this'.
+ this(T t, U u) {
+ // Ceci va appeller les setters ci-dessous.
+ data = t;
+ other = u;
+ }
+
+ // getters
+ @property T data() {
+ return _data;
+ }
+
+ @property U other() {
+ return _other;
+ }
+
+ // setters
+ @property void data(T t) {
+ _data = t;
+ }
+
+ @property void other(U u) {
+ _other = u;
+ }
+}
+
+// Et on l'utilise de cette façon:
+void main() {
+ auto mc = new MyClass!(int, string)(7, "seven");
+
+ // Importer le module 'stdio' de la bibliothèque standard permet
+ // d'écrire dans la console (les imports peuvent être locaux à une portée)
+ import std.stdio;
+
+ // On appelle les getters pour obtenir les valeurs.
+ writefln("Earlier: data = %d, str = %s", mc.data, mc.other);
+
+ // On appelle les setter pour assigner de nouvelles valeurs.
+ mc.data = 8;
+ mc.other = "eight";
+
+ // On appelle les setter pour obtenir les nouvelles valeurs.
+ writefln("Later: data = %d, str = %s", mc.data, mc.other);
+}
+```
+Avec les propriétés, on peut constuire nos setters et nos getters
+comme on le souhaite, tout en gardant un syntaxe très propre,
+comme si on accédait directement à des membres de la classe.
+
+Les autres fonctionnalités orientées objets à notre disposition
+incluent les interfaces, les classes abstraites, et la surcharge
+de méthodes. D gère l'héritage comme Java: On ne peut hériter que
+d'une seule classe et implémenter autant d'interface que voulu.
+
+Nous venons d'explorer les fonctionnalités objet du D, mais changeons
+un peu de domaine. D permet la programmation fonctionelle, avec les fonctions
+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`.
+
+```c
+import std.algorithm : map, filter, reduce;
+import std.range : iota; // construit un intervalle excluant la dernière valeur.
+
+void main() {
+ // On veut un algorithm qui affiche la somme de la listes des carrés
+ // des entiers paires de 1 à 100. Un jeu d'enfant !
+
+ // On se content de passer des expressions lambda en paramètre à des templates.
+ // On peut fournier au template n'importe quelle fonction, mais dans notre
+ // cas, les lambdas sont pratiques.
+ auto num = iota(1, 101).filter!(x => x % 2 == 0)
+ .map!(y => y ^^ 2)
+ .reduce!((a, b) => a + b);
+
+ writeln(num);
+}
+```
+
+Vous voyez comme on a calculé `num` comme on le ferait en haskell par exemple ?
+C'est grâce à une innvoation de D qu'on appelle "Uniform Function Call Syntax".
+Avec l'UFCS, on peut choisir d'écrire un appelle à une fonction de manière
+classique, ou comme un appelle à une méthode. Walter Brighter a écrit un
+article en anglais sur l'UFCS [ici.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
+Pour faire court, on peut appeller une fonction dont le premier paramètre
+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 !
+
+```c
+import std.stdio;
+import std.parallelism : parallel;
+import std.math : sqrt;
+
+void main() {
+ // On veut calculer la racine carré de tous les nombres
+ // dans notre tableau, et profiter de tous les coeurs
+ // à notre disposition.
+ auto arr = new double[1_000_000];
+
+ // On utilise un index et une référence à chaque élément du tableau.
+ // On appelle juste la fonction parallel sur notre tableau !
+ foreach(i, ref elem; parallel(arr)) {
+ ref = sqrt(i + 1.0);
+ }
+}
+
+
+```
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/haml-fr.html.markdown b/fr-fr/haml-fr.html.markdown
new file mode 100644
index 00000000..24be8bf9
--- /dev/null
+++ b/fr-fr/haml-fr.html.markdown
@@ -0,0 +1,157 @@
+---
+language: haml
+filename: learnhaml.haml
+contributors:
+ - ["Simon Neveu", "https://github.com/sneveu"]
+ - ["Thibault", "https://github.com/iTech-"]
+lang: fr-fr
+---
+
+Haml est un langage de balisage utilisé majoritairement avec Ruby, qui décrit de manière simple et propre le HTML de n'importe quelle page web sans l'utilisation des traditionnelles lignes de code. Le langage est une alternative très populaire au langage de templates Rails (.erb) et permet d'intégrer du code en Ruby dans votre balisage.
+
+Son but est de réduire le nombre de répétitions dans le balisage en fermant des balises pour vous en se basant sur l'indentation de votre code. Finalement, le balisage est bien structuré, ne contient pas de répétition, est logique et facile à lire.
+
+Vous pouvez aussi utiliser Haml sur un projet indépendant de Ruby, en installant les gems de Haml et en le convertissant en html grâce aux commandes.
+
+$ haml fichier_entree.haml fichier_sortie.html
+
+
+```haml
+/ -------------------------------------------
+/ Indentation
+/ -------------------------------------------
+
+/
+ A cause de l'importance de l'indentation sur la manière dont votre code sera
+ converti, l'indentation doit être constante à travers votre document. Un
+ simple changement d'indentation entrainera une erreur. En général, on utilise
+ deux espaces, mais ce genre de décision sur l'indentation vous appartient, du
+ moment que vous vous y tenez.
+
+/ -------------------------------------------
+/ Commentaires
+/ -------------------------------------------
+
+/ Ceci est un commentaire en Haml.
+
+/
+ Pour écrire un commentaire sur plusieurs lignes, indentez votre code
+ commenté en le commençant par un slash
+
+-# Ceci est un commentaire silencieux, qui n'apparaîtra pas dans le fichier
+
+
+/ -------------------------------------------
+/ Eléments HTML
+/ -------------------------------------------
+
+/ Pour écrire vos balises, utilisez un pourcentage suivi du nom de votre balise
+%body
+ %header
+ %nav
+
+/ Remarquez qu'il n'y a aucunes balises fermées. Le code produira alors ceci
+ <body>
+ <header>
+ <nav></nav>
+ </header>
+ </body>
+
+/ La balise div est l'élément par défaut, vous pouvez donc l'écrire comme ceci
+.balise
+
+/ Pour ajouter du contenu à votre balise, ajoutez le texte après sa déclaration
+%h1 Titre contenu
+
+/ Pour écrire du contenu sur plusieurs lignes, imbriquez le
+%p
+ Ce paragraphe contient beaucoup de contenu qui pourrait
+ probablement tenir sur deux lignes séparées.
+
+/
+ Vous pouvez utiliser des caractères html spéciaux en utilisant &=. Cela va
+ convertir les caractères comme &, /, : en leur équivalent HTML. Par exemple
+
+%p
+ &= "Oui & oui"
+
+/ Produira 'Oui &amp; oui'
+
+/ Vous pouvez écrire du contenu html sans qu'il soit converti en utilisant !=
+%p
+ != "Voici comment écrire une balise de paragraphe <p></p>"
+
+/ Cela produira 'Voici comment écrire une balise de paragraphe <p></p>'
+
+/ Une classe CSS peut être ajouté à votre balise en chainant le nom de la classe
+%div.truc.machin
+
+/ ou en utilisant un hash de Ruby
+%div{:class => 'truc machin'}
+
+/ Des attributs pour n'importe quelles balises peuvent être ajoutés au hash
+%a{:href => '#', :class => 'machin', :title => 'Titre machin'}
+
+/ Pour affecter une valeur à un booléen, utilisez 'true'
+%input{:selected => true}
+
+/ Pour écrire des data-attributes, utilisez le :data avec la valeur d'un hash
+%div{:data => {:attribute => 'machin'}}
+
+
+/ -------------------------------------------
+/ Insérer du Ruby
+/ -------------------------------------------
+
+/
+ Pour transférer une valeur de Ruby comme contenu d'une balise, utilisez le
+ signe égal suivi du code Ruby
+
+%h1= livre.titre
+
+%p
+ = livre.auteur
+ = livre.editeur
+
+
+/ Pour lancer du code Ruby sans le convertir en HTML, utilisez un trait d'union
+- livres = ['livre 1', 'livre 2', 'livre 3']
+
+/ Ceci vous permet de faire des choses géniales comme des blocs Ruby
+- livre.shuffle.each_with_index do |livre, index|
+ %h1= livre
+
+ if livre do
+ %p Ceci est un livre
+
+/
+ Encore une fois il n'est pas nécessaire d'ajouter une balise fermante, même
+ pour Ruby.
+ L'indentation le fera pour vous.
+
+
+/ -------------------------------------------
+/ Ruby en-ligne / Interpolation en Ruby
+/ -------------------------------------------
+
+/ Inclure une variable Ruby dans une ligne en utilisant #{}
+%p Votre meilleur score est #{record}
+
+
+/ -------------------------------------------
+/ Filtres
+/ -------------------------------------------
+
+/
+ Utilisez les deux points pour définir un filtre Haml, vous pouvez par exemple
+ utiliser un filtre :javascript pour écrire du contenu en-ligne js
+
+:javascript
+ console.log('Ceci est la balise en-ligne <script>');
+
+```
+
+## Lectures complémentaires
+
+- [Qu'est-ce que HAML ?](http://haml.info/) - Une bonne introduction qui explique très bien les avantages d'utiliser HAML.
+- [Documentation officielle](http://haml.info/docs/yardoc/file.REFERENCE.html) - Si vous souhaitez en apprendre plus et aller plus loin.
diff --git a/fr-fr/hy-fr.html.markdown b/fr-fr/hy-fr.html.markdown
new file mode 100644
index 00000000..bd7c6839
--- /dev/null
+++ b/fr-fr/hy-fr.html.markdown
@@ -0,0 +1,180 @@
+---
+language: hy
+filename: learnhy-fr.hy
+contributors:
+ - ["Abhishek L", "http://twitter.com/abhishekl"]
+translators:
+ - ["Hughes Perreault", "https://github.com/hperreault"]
+lang: fr-fr
+---
+
+Hy est un dialecte du lisp bâti par dessus python. Il fonctionne en
+convertissant le code hy en un arbre de syntaxe abstraite de python (ast).
+Ceci permet à hy d'appeler du code python et à python d'appeler du code hy.
+
+Ce tutoriel fonctionne pour hy > 0.9.12
+
+```clojure
+;; Ceci est une introduction simple à hy, pour un tutoriel rapide aller à
+;; http://try-hy.appspot.com
+;;
+; Les commentaires se font avec des points-virgules, comme les autres LISPS
+
+;; les s-expression de bases
+; Les programmes Lisp sont fait d'expressions symboliques ou sexps qui
+; ressemblent à
+(some-function args)
+; maintenant le quintessentiel hello world
+(print "hello world")
+
+;; les types de données simples
+; Tous les types de données simples sont exactement similaires à leurs
+; homologues de python
+42 ; => 42
+3.14 ; => 3.14
+True ; => True
+4+10j ; => (4+10j) un nombre complexe
+
+; Commençons par un peu d'arithmétique très simple
+(+ 4 1) ;=> 5
+; l'opérateur est appliqué à tous les arguments, comme les autres lisps
+(+ 4 1 2 3) ;=> 10
+(- 2 1) ;=> 1
+(* 4 2) ;=> 8
+(/ 4 1) ;=> 4
+(% 4 2) ;=> 0 l'opérateur modulo
+; l'opérateur d'élévation à la puissance est représenté par ** comme en python
+(** 3 2) ;=> 9
+; les expressions imbriquées vont se comporter comme on s'y attend
+(+ 2 (* 4 2)) ;=> 10
+; aussi, les opérateurs logiques and or not et equal to etc. vont se comporter
+; comme on s'y attend
+(= 5 4) ;=> False
+(not (= 5 4)) ;=> True
+
+;; variables
+; les variables sont déclarées en utilisant setv, les noms de variables
+; peuvent utiliser l'UTF-8 à l'exception de ()[]{}",'`;#|
+(setv a 42)
+(setv π 3.14159)
+(def *foo* 42)
+;; d'autres types de conteneurs
+; les chaînes, les listes, les tuples et dicts
+; ce sont exactement les mêmes que les types de conteneurs de python
+"hello world" ;=> "hello world"
+; les opérations sur les chaînes fonctionnent comme en python
+(+ "hello " "world") ;=> "hello world"
+; les listes sont créés en utilisant [], l'indexation commence à 0
+(setv mylist [1 2 3 4])
+; les tuples sont des structures de données immuables
+(setv mytuple (, 1 2))
+; les dictionnaires sont des paires clé-valeur
+(setv dict1 {"key1" 42 "key2" 21})
+; :nom peut être utilisé pour définir des mots clés dans hy qui peuvent être
+; utilisées comme clés
+(setv dict2 {:key1 41 :key2 20})
+; utilisez `get' pour obtenir l'élément à l'index / clé
+(get mylist 1) ;=> 2
+(get dict1 "key1") ;=> 42
+; Alternativement, si des mots clés ont été utilisés, l'élément peut être
+; obtenu directement
+(:key1 dict2) ;=> 41
+
+;; fonctions et autres constructions de programme
+; les fonctions sont définies en utilisant defn, la dernière sexp est renvoyé par défaut
+(defn greet [name]
+ "A simple greeting" ; une docstring optionnelle
+ (print "hello " name))
+
+(greet "bilbo") ;=> "hello bilbo"
+
+; les fonctions peuvent prendre des arguments optionnels ainsi que des
+; arguments sous forme de mots clés
+(defn foolists [arg1 &optional [arg2 2]]
+ [arg1 arg2])
+
+(foolists 3) ;=> [3 2]
+(foolists 10 3) ;=> [10 3]
+
+; les fonctions anonymes sont créés en utilisant `fn' ou `lambda'
+; qui sont semblable à `defn '
+(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16]
+
+;; Opérations sur les séquences
+; hy a des utilitaires natifs pour les opérations sur les séquences etc.
+; récupérez le premier élément en utilisant `first' ou `car'
+(setv mylist [1 2 3 4])
+(setv mydict {"a" 1 "b" 2})
+(first mylist) ;=> 1
+
+; découpez les listes en utilisant slice
+(slice mylist 1 3) ;=> [2 3]
+
+; obtenez les éléments d'une liste ou dict en utilisant `get'
+(get mylist 1) ;=> 2
+(get mydict "b") ;=> 2
+; l'indexation des listes commence à 0 comme en python
+; assoc peut définir les éléments à clés/index
+(assoc mylist 2 10) ; makes mylist [1 2 10 4]
+(assoc mydict "c" 3) ; makes mydict {"a" 1 "b" 2 "c" 3}
+; il ya tout un tas d'autres fonctions de base qui rend le travail avec
+; les séquences amusant
+
+;; les importations fonctionnent comme en pyhtonn
+(import datetime)
+(import [functools [partial reduce]]) ; importe fun1 et fun2 de module1
+(import [matplotlib.pyplot :as plt]) ; faire une importation foo comme bar
+; toutes les méthodes natives de python sont accessibles à partir de hy
+; a.foo(arg) est appelé (.foo a arg)
+(.split (.strip "hello world ")) ;=> ["hello" "world"]
+
+;; Conditionelles
+; (if condition (body-if-true) (body-if-false)
+(if (= passcode "moria")
+ (print "welcome")
+ (print "Speak friend, and Enter!"))
+
+; imbriquez plusieurs if else if avec le mot clé cond
+(cond
+ [(= someval 42)
+ (print "Life, universe and everything else!")]
+ [(> someval 42)
+ (print "val too large")]
+ [(< someval 42)
+ (print "val too small")])
+
+; groupez les expressions avec do, ceux-ci seront executé séquentiellemnt
+; les expressions comme defn ont un do implicite
+(do
+ (setv someval 10)
+ (print "someval is set to " someval)) ;=> 10
+
+; créer une liaison lexicale avec `let', toutes les variables déclarées
+; comme cela ont une portée locale
+(let [[nemesis {"superman" "lex luther"
+ "sherlock" "moriarty"
+ "seinfeld" "newman"}]]
+ (for [(, h v) (.items nemesis)]
+ (print (.format "{0}'s nemesis was {1}" h v))))
+
+;; classes
+; les classes sont définies comme ceci
+(defclass Wizard [object]
+ [[--init-- (fn [self spell]
+ (setv self.spell spell) ; init the spell attr
+ None)]
+ [get-spell (fn [self]
+ self.spell)]])
+
+;; allez voir hylang.org
+```
+
+### Lectures complémentaires
+
+Ce tutoriel est juste une simple introduction à hy/lisp/python.
+
+La documentation de HY: [http://hy.readthedocs.org](http://hy.readthedocs.org)
+
+Le repo GitHub de HY: [http://github.com/hylang/hy](http://github.com/hylang/hy)
+
+Sur freenode irc #hy, twitter hashtag #hylang
diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown
index 15478cdb..f1977dac 100644
--- a/fr-fr/javascript-fr.html.markdown
+++ b/fr-fr/javascript-fr.html.markdown
@@ -6,23 +6,26 @@ contributors:
filename: javascript-fr.js
translators:
- ['@nbrugneaux', 'https://nicolasbrugneaux.me']
+ - ['Michel Antoine', 'https://github.com/antoin-m']
lang: fr-fr
---
JavaScript a été créé par Brendan Eich, travaillant alors a Netscape, en 1995.
Le langage avait à l'origine pour but d'être un langage de scripting simple
pour les sites web, complétant le Java (à ne pas confondre avec JavaScript)
-pour des applications web complexes. Mais son intégration très proche et
-simple des pages web, ainsi que le support natif des navigateurs a rendu
-le JavaScript incontournable aujourd'hui tant bien dans le front-end que
+pour des applications web complexes. Mais son intégration très proche et
+simple des pages web, ainsi que le support natif des navigateurs a rendu
+le JavaScript incontournable aujourd'hui tant bien dans le front-end que
dans le back-end.
En effet, le JavaScript n'est plus uniquement limité aux navigateurs, grâce à
-Node.JS, un projet qui offre un environnement indépendant dans lequel un
-interpréteur Javascript, basé sur le célèbre moteur V8 de Google Chrome,
+Node.JS, un projet qui offre un environnement indépendant dans lequel un
+interpréteur Javascript, basé sur le célèbre moteur V8 de Google Chrome,
peut être utilisé directement côté serveur pour exécuter des programmes écrits
en JavaScript.
+ECMAScript (la norme du langage Javascript) entre en version 6. Cette version introduit de nombreuses mises à jour tout en restant rétrocompatible. L'implémentation de ces nouvelles fonctionnalités est en cours et celles-ci ne sont donc pas forcément compatibles avec tous les navigateurs.
+
```js
// Les commentaires sont comme en C. Les commentaires mono-ligne commencent par 2 slashs,
/* et les commentaires sur plusieurs lignes commencent avec slash-étoile
@@ -31,7 +34,7 @@ en JavaScript.
// Toutes les expressions peuvent finir par ;
doStuff();
-// ... mais n'en n'ont pas forcément besoin, les point-virgules sont ajoutés
+// ... mais n'en n'ont pas forcément besoin, les point-virgules sont ajoutés
// lors de l’interprétation aux sauts de ligne, sauf exceptions
doStuff()
@@ -79,6 +82,12 @@ false; // faux
"abc";
'Hello, world';
+// *ES6:* Les chaines de caractères peuvent être crées en utilisant un modèle
+// entouré des quotes inverses (`) à la place des quotes classiques (' ou ").
+// Les variables sont interprétées avec ${var}
+let banta = "Harry", santa = "Hermione";
+`${banta}, your santa is ${santa}.` // = "Harry, your santa is Hermione."
+
// La négation utilise le symbole !
!true; // = false
!false; // = true
@@ -117,26 +126,34 @@ false; // faux
// Il y a également null et undefined
null; // utilisé pour une non-valeur
-undefined; // utilisé pour une valeur actuellement non présente (cependant,
+undefined; // utilisé pour une valeur actuellement non présente (cependant,
// undefined est aussi une valeur valide)
// false, null, undefined, NaN, 0 and '' sont 'presque-faux' (falsy), tout le reste
// est 'presque-vrai' (truthy)
// Notez que 0 est falsy mais '0' est truthy, alors même que 0 == '0' (mais 0 !== '0')
+// *ES6:* Introduction d'un nouveau type primitif : Symbol
+var symbol_one = Symbol();
+var symbol_two = Symbol('This is optional description, for debugging');
+typeof symbol_one === 'symbol' // = true
+
+// *ES6:* Un Symbol est immutable et unique
+Symbol() === Symbol() // = false
+Symbol('learnx') === Symbol('learnx') // = false
///////////////////////////////////
-// 2. Variables, Tableaux et Objets
+// 2. Variables, Tableaux, Objets, Maps et Sets
-// Les variables sont déclarées avec le mot clé var. Le typage en JavaScript est
+// Les variables sont déclarées avec le mot clé var. Le typage en JavaScript est
// dynamique, donc pas besoin de spécifier le type. L'assignement utilise un seul =.
var someVar = 5;
// si vous oubliez le mot clé var, vous n'aurez pas d'erreur (sauf en mode strict)
someOtherVar = 10;
-// ... mais la variable aura une portée globale (plus communément trouvé en tant
-// que "global scope" en anglais), et non pas une portée limitée à la fonction
+// ... mais la variable aura une portée globale (plus communément trouvé en tant
+// que "global scope" en anglais), et non pas une portée limitée à la fonction
// dans laquelle vous l'aviez définie.
// Les variables déclarées et non assignées sont undefined par défaut
@@ -145,6 +162,32 @@ var someThirdVar = undefined;
// ... sont deux déclarations identiques.
+// Il est possible de déclarer plusieurs variables en séparant leur déclaration
+// avec l'opérateur virgule
+var someFourthVar = 2, someFifthVar = 4;
+
+// *ES6:* Les variables peuvent maintenant être déclarées avec les mots-clés
+// `let` et `const`
+let someSixthVar = 6;
+const someSeventhVar = 7;
+
+// *ES6:* Le mot-clé `let` attache la variable au block de code et non à la fonction
+// à l'inverse de `var`
+for (let i = 0; i < 10; i++) {
+ x += 10;
+}
+i; // = raises ReferenceError
+
+// *ES6:* Les variables "const" doivent être assignées lors de l'initialisation
+const someEighthVar = 7;
+const someNinthVar; // raises SyntaxError
+
+// *ES6:* Modifier une variable constante ne lève par d'erreur mais échoue
+// silencieusement
+const someNinthVar = 9;
+someNinthVar = 10;
+someNinthVar; // = 9
+
// Il y a des raccourcis pour les opérations mathématiques:
someVar += 5; // équivalent pour someVar = someVar + 5;
someVar *= 10; // de même, someVar = someVar * 100;
@@ -165,6 +208,22 @@ myArray.length; // = 4
// Ajout/Modification à un index spécifique
myArray[3] = 'Hello';
+// *ES6:* Les Arrays peuvent maintenant être déstructurés en utilisant le pattern matching
+var [a, b] = [1, 2];
+var [a, , b] = [1, -2, 2]
+
+a; // = 1
+b; // = 2
+
+// *ES6:* La déstructuration peut échouer silencieusement.
+// Il est aussi possible d'utiliser des valeurs par défaut
+var [a] = [];
+a; // = undefined;
+var [a = 1] = [];
+a; // = 1;
+var [a = 1] = [2];
+a; // = 2;
+
// Les objets JavaScript sont appelés 'dictionnaires' ou 'maps' dans certains autres
// langages : ils sont une liste non-ordonnée de paires clé-valeur.
var myObj = {key1: 'Hello', key2: 'World'};
@@ -179,12 +238,55 @@ myObj['my other key']; // = 4
// .. ou avec un point si la clé est un identifiant valide.
myObj.myKey; // = 'myValue'
+// *ES6:* Un Symbol peut être utilisé en tant que clé. Puisque ceux-ci sont uniques,
+// le seul moyen d'accéder à la propriété est d'avoir une référence sur ce Symbol.
+myObj["key"] = "public value";
+myObj[Symbol("key")] = "secret value";
+myObj[Symbol("key")]; // = undefined
+
// Les objets sont eux aussi modifiables.
myObj.myThirdKey = true;
// Si vous essayez d'accéder à une valeur non-définie, vous obtiendrez undefined
myObj.myFourthKey; // = undefined
+// *ES6:* Comme les Arrays, les Objects peuvent être déstructurés en utilisant le pattern matching
+var {foo} = {foo: "bar"};
+foo // = "bar"
+
+// *ES6:* Les Objects déstructurés peuvent utiliser des noms de variables différents
+// de ceux d'origine grâce au pattern matching
+var {foo, moo: baz} = {foo: "bar", moo: "car"};
+foo // = "bar"
+baz // = "car"
+
+// *ES6:* Il est possible d'utiliser des valeurs par défaut lor de la déstructuration d'un Object
+var {foo="bar"} = {moo: "car"};
+foo // = "bar"
+
+// *ES6:* Une erreur lors de la déstructuration restera silencieuse
+var {foo} = {};
+foo // = undefined
+
+// *ES6:* Les Maps sont des objets itérables de type clé-valeur.
+// Il est possible de créer une nouvelle map en utilisant `new Map()`
+var myMap = new Map();
+
+// *ES6:* Il est possible d'ajouter un couple clé-valeur avec la méthode `.set()`,
+// de récupérer une valeur avec `.get()`,
+// de vérifier qu'une clé existe avec `.has()`
+// et enfin de supprimer un couple clé-valeur avec `.delete()`
+
+myMap.set("name", "Douglas");
+myMap.get("name"); // = "Douglas"
+myMap.has("name"); // = true
+myMap.delete("name");
+
+// *ES6:* Les Sets sont des ensembles de valeurs uniques.
+// Il est possible de créer un set avec `new Set()`.
+// Toute valeur non unique est ignorée.
+var mySet = new Set([1,2,2]);
+console.log([...mySet]); // = [1,2]
///////////////////////////////////
// 3. Logique et structures de contrôle
@@ -198,7 +300,7 @@ else if (count === 4) {
// uniquement quand count est 4
}
else {
- // le reste du temps, si ni 3, ni 4.
+ // le reste du temps, si ni 3, ni 4.
}
// De même pour while.
@@ -218,6 +320,22 @@ for (var i = 0; i < 5; i++){
// sera exécutée 5 fois
}
+// La boucle for...in permet d'itérer sur les noms des propriétés d'un objet
+var description = "";
+var person = {fname:"Paul", lname:"Ken", age:18};
+for (var x in person){
+ description += person[x] + " ";
+}
+description; // = "Paul Ken 18 "
+
+// *ES6:* La boucle for...of permet d'itérer sur les propriétés d'un objet
+var description = "";
+var person = {fname:"Paul", lname:"Ken", age:18};
+for (var x of person){
+ description += x + " ";
+}
+description; // = "Paul Ken 18 "
+
// && est le "et" logique, || est le "ou" logique
if (house.size === 'big' && house.colour === 'blue'){
house.contains = 'bear';
@@ -264,7 +382,21 @@ function myFunction(thing){
}
myFunction('foo'); // = 'FOO'
-// Les fonctions JavaScript sont des objets de première classe, donc peuvent
+// Attention, la valeur à retourner doit se trouver sur la même ligne que
+// le mot-clé `return` sinon la fonction retournera systématiquement `undefined`
+function myFunction(){
+ return // <- semicolon automatically inserted here
+ {thisIsAn: 'object literal'}
+}
+myFunction(); // = undefined
+
+// *ES6:* Les paramètres des fonctions peuvent désormais avoir des valeurs par défaut
+function default(x, y = 2) {
+ return x + y;
+}
+default(10); // == 12
+
+// Les fonctions JavaScript sont des objets de première classe, donc peuvent
// être réassignées à d'autres variables et passées en tant que paramètres pour
// d'autres fonctions
function myFunction(){
@@ -274,13 +406,17 @@ setTimeout(myFunction, 5000);
// Note: setTimeout ne fait pas parti du langage, mais les navigateurs ainsi
// que Node.js le rendent disponible
-// Les fonctions n'ont pas nécessairement besoin d'un nom, elles peuvent être
+// Les fonctions n'ont pas nécessairement besoin d'un nom, elles peuvent être
// anonymes
setTimeout(function(){
// ce code s'exécutera dans 5 secondes
}, 5000);
-// Le Javascript crée uniquement un scope, une portée d'action limitée, pour
+// *ES6:* Introduction d'un sucre syntaxique permettant de créer
+// une fonction anonyme de la forme : `param => returnValue`.
+setTimeout(() => console.log('5 seconds, are up.'), 5000);
+
+// Le Javascript crée uniquement un scope, une portée d'action limitée, pour
// les fonctions, et pas dans les autres blocs.
if (true){
var i = 5;
@@ -293,7 +429,7 @@ i; // = 5 - et non undefined comme vous pourriez vous y attendre
var temporary = 5;
// Nous pouvons accéder au scope global en assignant à l'objet global,
// qui dans les navigateurs est "window". Il est différent dans Node.js,
- // le scope global sera en fait local au module dans lequel vous
+ // le scope global sera en fait local au module dans lequel vous
// vous trouvez. http://nodejs.org/api/globals.html
window.permanent = 10;
})();
@@ -302,8 +438,8 @@ i; // = 5 - et non undefined comme vous pourriez vous y attendre
temporary; // raises ReferenceError
permanent; // = 10
-// Une des fonctionnalités les plus puissantes de Javascript est le système de
-// closures. Si une fonction est définie dans une autre fonction, alors la
+// Une des fonctionnalités les plus puissantes de Javascript est le système de
+// closures. Si une fonction est définie dans une autre fonction, alors la
// fonction interne aura accès aux variables de la fonction parente, même si
// celle-ci a déjà finie son exécution.
function sayHelloInFiveSeconds(name){
@@ -318,6 +454,18 @@ function sayHelloInFiveSeconds(name){
}
sayHelloInFiveSeconds('Adam'); // ouvre un popup avec 'Hello, Adam!' dans 5sec
+// *ES6:* Les paramètres des fonctions appelées avec un tableau en entré
+// préfixé par `...` vont se peupler avec les éléments du tableau
+function spread(x, y, z) {
+ return x + y + z;
+}
+spread(...[1,2,3]); // == 6
+
+// *ES6:* Les fonctions peuvent recevoir les paramètres dans un tableau en utilisant l'opérateur `...`
+function spread(x, y, z) {
+ return x + y + z;
+}
+spread(...[1,2,3]); // == 6
///////////////////////////////////
// 5. Encore plus à propos des Objets; Constructeurs and Prototypes
@@ -340,7 +488,7 @@ myObj = {
};
myObj.myFunc(); // = 'Hello world!'
-// La valeur de "this" change de par l'endroit où la fonction est appelée, et
+// La valeur de "this" change de par l'endroit où la fonction est appelée, et
// non de l'endroit où elle est définie. Donc elle ne fonctionnera pas si elle
// est appelée hors du contexte l'objet.
var myFunc = myObj.myFunc;
@@ -356,7 +504,7 @@ myObj.myOtherFunc = myOtherFunc;
myObj.myOtherFunc(); // = 'HELLO WORLD!'
// Le contexte correspond à la valeur de "this".
-// Nous pouvons aussi spécifier un contexte, forcer la valeur de "this,
+// Nous pouvons aussi spécifier un contexte, forcer la valeur de "this,
// pour une fonction quand elle est appelée grâce à "call" ou "apply".
var anotherFunc = function(s){
return this.myString + s;
@@ -371,19 +519,19 @@ Math.min(42, 6, 27); // = 6
Math.min([42, 6, 27]); // = NaN (uh-oh!)
Math.min.apply(Math, [42, 6, 27]); // = 6
-// Mais, "call" and "apply" fonctionnenent uniquement au moment de l'appel de la
-// fonction. Pour lier le contexte de façon permanente, nous pouvons utiliser
+// Mais, "call" and "apply" fonctionnenent uniquement au moment de l'appel de la
+// fonction. Pour lier le contexte de façon permanente, nous pouvons utiliser
// "bind" pour garder une référence à la fonction avec ce "this".
var boundFunc = anotherFunc.bind(myObj);
boundFunc(' And Hello Saturn!'); // = 'Hello World! And Hello Saturn!'
-// "bind" peut aussi être utilisé pour créer une application partielle de la
+// "bind" peut aussi être utilisé pour créer une application partielle de la
// fonction (curry)
var product = function(a, b){ return a * b; }
var doubler = product.bind(this, 2);
doubler(8); // = 16
-// Lorsque vous appelez une fonction avec le mot clé "new", un nouvel objet est
+// Lorsque vous appelez une fonction avec le mot clé "new", un nouvel objet est
// crée et mis à disposition de la fonction via "this". Ces fonctions sont
// communément appelées constructeurs.
var MyConstructor = function(){
@@ -395,8 +543,8 @@ myNewObj.myNumber; // = 5
// Chaque objet en Javascript a un "prototype". Quand vous essayez d'accéder à
// une propriété que l'objet n'a pas, l'interpréteur va regarder son prototype.
-// Quelques implémentations de JS vous laissent accéder au prototype avec la
-// propriété "magique" __proto__. Ceci peut être utile, mais n'est pas standard
+// Quelques implémentations de JS vous laissent accéder au prototype avec la
+// propriété "magique" __proto__. Ceci peut être utile, mais n'est pas standard
// et ne fonctionne pas dans certains des navigateurs actuels.
var myObj = {
myString: 'Hello world!'
@@ -478,7 +626,7 @@ String.prototype.firstCharacter = function(){
'abc'.firstCharacter(); // = 'a'
// C'est très souvent utilisé pour le "polyfilling", qui implémente des nouvelles
-// fonctionnalités de JavaScript dans de plus anciens environnements, tels que
+// fonctionnalités de JavaScript dans de plus anciens environnements, tels que
// les vieux navigateurs.
//Par exemple, Object.create est assez récent, mais peut être implémenté grâce à
@@ -492,31 +640,83 @@ if (Object.create === undefined){ // pour ne pas reécrire si la fonction existe
return new Constructor();
}
}
+
+// *ES6:* Les objets peuvent être équipés de proxies qui permettent d'intercepter
+// les actions sur leurs propriétés. Voici comment créer un proxy sur un objet :
+var proxyObject = new Proxy(object, handler);
+
+// *ES6:* Les méthodes d'un objet handler sont appelées lors de l'interception d'une action.
+// La méthode `.get()` est appelée à chaque lecture d'une propriété
+// tandis que la méthode `.set()` est appelée à chaque écriture.
+var handler = {
+ get (target, key) {
+ console.info('Get on property' + key);
+ return target[key];
+ },
+ set (target, key, value) {
+ console.info('Set on property' + key);
+ return true;
+ }
+}
+
+// *ES6:* Les classes peuvent désormais être définies en utilisant le mot-clé `class`.
+// Le constructeur s'appelle `constructor` et les méthodes statiques utilisent le mot-clé `static`
+class Foo {
+ constructor() {console.log("constructing Foo");}
+ bar() {return "bar";}
+ static baz() {return "baz";}
+}
+
+// *ES6:* Les objets issus des classes sont initialisés avec le mot-clé `new`.
+// Il est possible d'hériter d'une classe avec le mot-clé `extends`
+var FooObject = new Foo(); // = "constructing Foo"
+class Zoo extends Foo {}
+
+// *ES6:* Les méthodes statiques doivent être appelées par la classe, les autres méthodes par l'objet
+Foo.baz() // = "baz"
+FooObject.bar() // = "bar"
+
+// *ES6:* Il est désormais possible d'exporter des valeurs en tant que module.
+// Les exports peuvent être n'importe quel objet, valeur ou fonction.
+var api = {
+ foo: "bar",
+ baz: "ponyfoo"
+};
+export default api;
+
+// *ES6:* La syntaxe `export default` permet d'exporter l'objet sans en changer le nom.
+// Il y a plusieurs façons de l'importer:
+import coolapi from "api"; // = importe le module dans la variable `coolapi`
+import {foo, baz} from "api"; // = importe les attributs `foo` et `baz` du module
+import {foo as moo, baz} from "api"; // = importe les attributs `foo` (en le renommant `moo`) et `baz` du module
+import _, {map} from "api"; // = importe les exports par défaut ET `map`
+import * as coolapi from "api"; // = importe le namespace global du module
+
```
## Pour aller plus loin (en anglais)
The [Mozilla Developer
Network](https://developer.mozilla.org/fr-FR/docs/Web/JavaScript) expose une
-excellente documentation pour le Javascript dans les navigateurs. Et contient
+excellente documentation pour le Javascript dans les navigateurs. Et contient
également un wiki pour s'entraider.
MDN's [A re-introduction to
JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
recouvre les principaux sujets vus ici. Le guide est délibérément uniquement
-à propos du JavaScript, et ne parle pas des navigateurs; pour cela, dirigez vous
+à propos du JavaScript, et ne parle pas des navigateurs; pour cela, dirigez vous
plutôt ici :
[Document Object
Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)
-[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) quelques challenges.
+[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) quelques challenges.
[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth
un guide pour vous éviter les faux-amis dans le JavaScript.
-[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) un classique. A lire.
+[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) un classique. A lire.
-En addition aux contributeurs de cet article, du contenu provient du
+En addition aux contributeurs de cet article, du contenu provient du
"Python tutorial" de Louie Dinh, et de [JS
Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
sur le réseau Mozilla.
diff --git a/fr-fr/livescript-fr.html.markdown b/fr-fr/livescript-fr.html.markdown
index 9c3b8003..13bbffe5 100644
--- a/fr-fr/livescript-fr.html.markdown
+++ b/fr-fr/livescript-fr.html.markdown
@@ -4,7 +4,7 @@ filename: learnLivescript-fr.ls
contributors:
- ["Christina Whyte", "http://github.com/kurisuwhyte/"]
translators:
- - ["Morgan Bohn", "https://github.com/morganbohn"]
+ - ["Morgan Bohn", "https://github.com/dotmobo"]
lang: fr-fr
---
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 e5e7c73a..2e4e8461 100644
--- a/fr-fr/markdown.html.markdown
+++ b/fr-fr/markdown.html.markdown
@@ -2,7 +2,7 @@
language: markdown
contributors:
- ["Andrei Curelaru", "http://www.infinidad.fr"]
-filename: markdown.md
+filename: markdown-fr.md
lang: fr-fr
---
@@ -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 69f4d8f9..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,12 +8,11 @@ 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.
-```objective_c
+```objective-c
// Les commentaires sur une seule ligne commencent par //
/*
@@ -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/perl-fr.html.markdown b/fr-fr/perl-fr.html.markdown
new file mode 100644
index 00000000..e737b7aa
--- /dev/null
+++ b/fr-fr/perl-fr.html.markdown
@@ -0,0 +1,174 @@
+---
+name: perl
+category: language
+language: perl
+filename: learnperl-fr.pl
+contributors:
+ - ["Korjavin Ivan", "http://github.com/korjavin"]
+ - ["Matteo Taroli", "http://www.matteotaroli.be"]
+translators:
+ - ["Matteo Taroli", "http://www.matteotaroli.be"]
+lang: fr-fr
+---
+Perl 5 est un langage de programmation riche en fonctionnalité, avec plus de 25 ans de développement.
+
+Perl 5 fonctionne sur plus de 100 plateformes, allant des pc portables aux mainframes et
+est autant adapté à un prototypage rapide qu'à des projets de grande envergure.
+
+```perl
+# Les commentaires en une ligne commencent par un dièse
+
+
+#### Types de variables de Perl
+
+# Les variables comment par un symbole précisant le type.
+# Un nom de variable valide commence par une lettre ou un underscore,
+# suivi d'un nombre quelconque de lettres, chiffres ou underscores.
+
+### Perl a trois types principaux de variables: $scalaire, @tableau and %hash
+
+## Scalaires
+# Un scalaire représente une valeur unique :
+my $animal = "chameau";
+my $reponse = 42;
+
+# Les valeurs scalaires peuvent être des strings, des entiers ou des nombres à virgule flottante
+# et Perl les convertira automatiquement entre elles quand nécessaire.
+
+## Tableaux
+# Un tableau représente une liste de valeurs :
+my @animaux = ("chameau", "lama", "chouette");
+my @nombres = (23, 42, 69);
+my @melange = ("chameau", 42, 1.23);
+
+## Hashes
+# Un hash représente un ensemble de paires de clé/valeur :
+my %fruit_couleur = ("pomme", "rouge", "banane", "jaune");
+
+# Vous pouvez utiliser des espaces et l'opérateur "=>" pour les disposer plus joliment :
+
+my %fruit_couleur = (
+ pomme => "rouge",
+ banane => "jaune"
+);
+
+# Les scalaires, tableaux et hashes sont plus amplement documentés dans le perldata
+# (perldoc perldata)
+
+# Des types de données plus complexes peuvent être construits en utilisant des références,
+# vous permettant de construire des listes et des hashes à l'intérieur d'autres listes et hashes.
+
+#### Conditions et boucles
+
+# Perl possède la plupart des conditions et boucles habituelles.
+
+if ($var) {
+ ...
+} elsif ($var eq 'bar') {
+ ...
+} else {
+ ...
+}
+
+unless (condition) {
+ ...
+}
+# Ceci est fourni en tant que version plus lisible de "if (!condition)"
+
+# la postcondition à la sauce Perl
+
+print "Yow!" if $zippy;
+print "Nous n'avons pas de banane." unless $bananes;
+
+# while
+while (condition) {
+ ...
+}
+
+# boucle for et iteration
+for (my $i = 0; $i < $max; $i++) {
+ print "l'index est $i";
+}
+
+for (my $i = 0; $i < @elements; $i++) {
+ print "L'élément courant est " . $elements[$i];
+}
+
+for my $element (@elements) {
+ print $element;
+}
+
+# implicitement
+
+# La variable de contexte scalaire $_ est utilisée par défaut dans différentes
+# situations, comme par exemple dans la boucle foreach ou en argument par défaut
+# de la plupart des fonctions pour en simplifier l'écriture.
+
+# Dans l'exemple suivant, $_ prends successivement la valeur de
+# chaque élément de la liste.
+
+for (@elements) {
+ print; # affiche le contenu de $_
+}
+
+
+#### Expressions régulières
+
+# Le support des expressions régulières par Perl est aussi large que profond
+# et est sujet à une longue documentation sur perlrequick, perlretut et ailleurs.
+# Cependant, pour faire court :
+
+# Simple correspondance
+if (/foo/) { ... } # vrai si $_ contient "foo"
+if ($a =~ /foo/) { ... } # vrai si $a contient "foo"
+
+# Simple substitution
+
+$a =~ s/foo/bar/; # remplace le premier foo par bar dans $a
+$a =~ s/foo/bar/g; # remplace TOUTES LES INSTANCES de foo par bar dans $a
+
+
+#### Fichiers et E/S
+
+# Vous pouvez ouvrir un fichier pour y écrire ou pour le lire avec la fonction "open()".
+
+open(my $in, "<", "input.txt") or die "Impossible d'ouvrir input.txt: $!";
+open(my $out, ">", "output.txt") or die "Impossible d'ouvrir output.txt: $!";
+open(my $log, ">>", "my.log") or die "Impossible d'ouvrir my.log: $!";
+
+# Vous pouvez lire depuis un descripteur de fichier grâce à l'opérateur "<>".
+# Dans un contexte scalaire, il lit une seule ligne depuis le descripteur de fichier
+# et dans un contexte de liste, il lit le fichier complet, assignant chaque ligne à un
+# élément de la liste :
+
+my $ligne = <$in>
+my $lignes = <$in>
+
+#### Ecrire des fonctions
+
+# Ecrire des fonctions est facile :
+
+sub logger {
+ my $logmessage = shift;
+
+ open my $logfile, ">>", "my.log" or die "Impossible d'ouvrir my.log: $!";
+
+ print $logfile $logmessage;
+}
+
+# Maintenant, nous pouvons utiliser cette fonction comme n'importe quelle fonction intégrée :
+
+logger("On a une fonction de logging!!");
+```
+
+#### Utiliser des modules Perl
+
+Les modules Perl fournissent une palette de fonctionnalités vous évitant de réinventer la roue et peuvent être téléchargés depuis CPAN (http://www.cpan.org/). Un certain nombre de modules populaires sont inclus dans la distribution même de Perl.
+
+Perlfaq contiens des questions et réponses liées aux tâches habituelles et propose souvent des suggestions quant aux bons modules à utiliser.
+
+#### Pour en savoir plus
+ - [perl-tutorial](http://perl-tutorial.org/)
+ - [Learn at www.perl.com](http://www.perl.org/learn.html)
+ - [perldoc](http://perldoc.perl.org/)
+ - and perl built-in : `perldoc perlintro`
diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown
index 3f6dcabb..d78291be 100644
--- a/fr-fr/python-fr.html.markdown
+++ b/fr-fr/python-fr.html.markdown
@@ -14,8 +14,7 @@ Je suis tombé amoureux de Python de par la clarté de sa syntaxe. C'est pratiqu
Vos retours sont grandement appréciés. Vous pouvez me contacter sur Twitter [@louiedinh](http://twitter.com/louiedinh) ou par e-mail: louiedinh [at] [google's email service]
-NB: Cet artice s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x
-Vous pourrez bientôt trouver un article pour Python 3 en Français. Pour le moment vous pouvez jettez un coup d'oeil à l'article [Python 3 en Anglais](http://learnxinyminutes.com/docs/python3/).
+N.B. : Cet article s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x. Python 2.7 est en fin de vie et ne sera plus maintenu à partir de 2020, il est donc recommandé d'apprendre Python avec Python 3. Pour Python 3.x, il existe un autre [tutoriel pour Python 3](http://learnxinyminutes.com/docs/fr-fr/python3-fr/).
```python
# Une ligne simple de commentaire commence par un dièse
diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown
new file mode 100644
index 00000000..3d60157c
--- /dev/null
+++ b/fr-fr/python3-fr.html.markdown
@@ -0,0 +1,723 @@
+---
+language: python3
+contributors:
+ - ["Louie Dinh", "http://pythonpracticeprojects.com"]
+ - ["Steven Basart", "http://github.com/xksteven"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+ - ["Zachary Ferguson", "http://github.com/zfergus2"]
+translators:
+ - ["Gnomino", "https://github.com/Gnomino"]
+filename: learnpython3-fr.py
+lang: fr-fr
+---
+
+Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des
+langages les populaires. Je suis tombé amoureux de Python pour la clarté de sa syntaxe.
+C'est tout simplement du pseudo-code exécutable.
+
+L'auteur original apprécierait les retours (en anglais): vous pouvez le contacter sur Twitter à [@louiedinh](http://twitter.com/louiedinh) ou par mail à l'adresse louiedinh [at] [google's email service]
+
+Note : Cet article s'applique spécifiquement à Python 3. Jettez un coup d'oeil [ici](http://learnxinyminutes.com/docs/fr-fr/python-fr/) pour apprendre le vieux Python 2.7
+
+```python
+
+# Un commentaire d'une ligne commence par un dièse
+
+""" Les chaînes de caractères peuvent être écrites
+ avec 3 guillemets doubles ("), et sont souvent
+ utilisées comme des commentaires.
+"""
+
+####################################################
+## 1. Types de données primaires et opérateurs
+####################################################
+
+# On a des nombres
+3 # => 3
+
+# Les calculs sont ce à quoi on s'attend
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+
+# Sauf pour la division qui retourne un float (nombre à virgule flottante)
+35 / 5 # => 7.0
+
+# Résultats de divisions entières tronqués pour les nombres positifs et négatifs
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # works on floats too
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
+
+# Quand on utilise un float, le résultat est un float
+3 * 2.0 # => 6.0
+
+# Modulo (reste de la division)
+7 % 3 # => 1
+
+# Exponentiation (x**y, x élevé à la puissance y)
+2**4 # => 16
+
+# Forcer la priorité de calcul avec des parenthèses
+(1 + 3) * 2 # => 8
+
+# Les valeurs booléennes sont primitives
+True
+False
+
+# Négation avec not
+not True # => False
+not False # => True
+
+# Opérateurs booléens
+# On note que "and" et "or" sont sensibles à la casse
+True and False #=> False
+False or True #=> True
+
+# Utilisation des opérations booléennes avec des entiers :
+0 and 2 #=> 0
+-5 or 0 #=> -5
+0 == False #=> True
+2 == True #=> False
+1 == True #=> True
+
+# On vérifie une égalité avec ==
+1 == 1 # => True
+2 == 1 # => False
+
+# On vérifie une inégalité avec !=
+1 != 1 # => False
+2 != 1 # => True
+
+# Autres opérateurs de comparaison
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
+
+# On peut enchaîner les comparaisons
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
+
+# (is vs. ==) is vérifie si deux variables pointent sur le même objet, mais == vérifie
+# si les objets ont la même valeur.
+a = [1, 2, 3, 4] # a pointe sur une nouvelle liste, [1, 2, 3, 4]
+b = a # b pointe sur a
+b is a # => True, a et b pointent sur le même objet
+b == a # => True, les objets a et b sont égaux
+b = [1, 2, 3, 4] # b pointe sur une nouvelle liste, [1, 2, 3, 4]
+b is a # => False, a et b ne pointent pas sur le même objet
+b == a # => True, les objets a et b ne pointent pas sur le même objet
+
+# Les chaînes (ou strings) sont créées avec " ou '
+"Ceci est une chaine"
+'Ceci est une chaine aussi.'
+
+# On peut additionner des chaînes aussi ! Mais essayez d'éviter de le faire.
+"Hello " + "world!" # => "Hello world!"
+# On peut aussi le faire sans utiliser '+'
+"Hello " "world!" # => "Hello world!"
+
+# On peut traîter une chaîne comme une liste de caractères
+"This is a string"[0] # => 'T'
+
+# .format peut être utilisé pour formatter des chaînes, comme ceci:
+"{} peuvent etre {}".format("Les chaînes", "interpolées")
+
+# On peut aussi réutiliser le même argument pour gagner du temps.
+"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
+#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick"
+
+# On peut aussi utiliser des mots clés pour éviter de devoir compter.
+"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna"
+
+# Si votre code doit aussi être compatible avec Python 2.5 et moins,
+# vous pouvez encore utiliser l'ancienne syntaxe :
+"Les %s peuvent être %s avec la %s méthode" % ("chaînes", "interpolées", "vieille")
+
+
+# None est un objet
+None # => None
+
+# N'utilisez pas "==" pour comparer des objets à None
+# Utilisez plutôt "is". Cela permet de vérifier l'égalité de l'identité des objets.
+"etc" is None # => False
+None is None # => True
+
+# None, 0, and les strings/lists/dicts (chaînes/listes/dictionnaires) valent False lorsqu'ils sont convertis en booléens.
+# Toutes les autres valeurs valent True
+bool(0) # => False
+bool("") # => False
+bool([]) #=> False
+bool({}) #=> False
+
+
+####################################################
+## 2. Variables et Collections
+####################################################
+
+# Python a une fonction print pour afficher du texte
+print("I'm Python. Nice to meet you!")
+
+# Par défaut, la fonction print affiche aussi une nouvelle ligne à la fin.
+# Utilisez l'argument optionnel end pour changer ce caractère de fin.
+print("Hello, World", end="!") # => Hello, World!
+
+# Pas besoin de déclarer des variables avant de les définir.
+# La convention est de nommer ses variables avec des minuscules_et_underscores
+some_var = 5
+some_var # => 5
+
+# Tenter d'accéder à une variable non définie lève une exception.
+# Voir Structures de contrôle pour en apprendre plus sur le traitement des exceptions.
+une_variable_inconnue # Lève une NameError
+
+# Les listes permettent de stocker des séquences
+li = []
+# On peut initialiser une liste pré-remplie
+other_li = [4, 5, 6]
+
+# On ajoute des objets à la fin d'une liste avec .append
+li.append(1) # li vaut maintenant [1]
+li.append(2) # li vaut maintenant [1, 2]
+li.append(4) # li vaut maintenant [1, 2, 4]
+li.append(3) # li vaut maintenant [1, 2, 4, 3]
+# On enlève le dernier élément avec .pop
+li.pop() # => 3 et li vaut maintenant [1, 2, 4]
+# Et on le remet
+li.append(3) # li vaut de nouveau [1, 2, 4, 3]
+
+# Accès à un élément d'une liste :
+li[0] # => 1
+# Accès au dernier élément :
+li[-1] # => 3
+
+# Accéder à un élément en dehors des limites lève une IndexError
+li[4] # Lève une IndexError
+
+# On peut accéder à une intervalle avec la syntaxe "slice"
+# (c'est un rang du type "fermé/ouvert")
+li[1:3] # => [2, 4]
+# Omettre les deux premiers éléments
+li[2:] # => [4, 3]
+# Prendre les trois premiers
+li[:3] # => [1, 2, 4]
+# Sélectionner un élément sur deux
+li[::2] # =>[1, 4]
+# Avoir une copie de la liste à l'envers
+li[::-1] # => [3, 4, 2, 1]
+# Pour des "slices" plus élaborées :
+# li[debut:fin:pas]
+
+# Faire une copie d'une profondeur de un avec les "slices"
+li2 = li[:] # => li2 = [1, 2, 4, 3] mais (li2 is li) vaut False.
+
+# Enlever des éléments arbitrairement d'une liste
+del li[2] # li is now [1, 2, 3]
+
+# On peut additionner des listes
+# Note: les valeurs de li et other_li ne sont pas modifiées.
+li + other_li # => [1, 2, 3, 4, 5, 6]
+
+# Concaténer des listes avec "extend()"
+li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
+
+# Vérifier la présence d'un objet dans une liste avec "in"
+1 in li # => True
+
+# Examiner la longueur avec "len()"
+len(li) # => 6
+
+
+# Les tuples sont comme des listes mais sont immuables.
+tup = (1, 2, 3)
+tup[0] # => 1
+tup[0] = 3 # Lève une TypeError
+
+# Note : un tuple de taille un doit avoir une virgule après le dernier élément,
+# mais ce n'est pas le cas des tuples d'autres tailles, même zéro.
+type((1)) # => <class 'int'>
+type((1,)) # => <class 'tuple'>
+type(()) # => <class 'tuple'>
+
+# On peut utiliser la plupart des opérations des listes sur des tuples.
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# Vous pouvez décomposer des tuples (ou des listes) dans des variables
+a, b, c = (1, 2, 3) # a vaut 1, b vaut 2 et c vaut 3
+# Les tuples sont créés par défaut sans parenthèses
+d, e, f = 4, 5, 6
+# Voyez comme il est facile d'intervertir deux valeurs :
+e, d = d, e # d vaut maintenant 5 et e vaut maintenant 4
+
+
+# Créer un dictionnaire :
+empty_dict = {}
+# Un dictionnaire pré-rempli :
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# Note : les clés des dictionnaires doivent être de types immuables.
+# Elles doivent être convertibles en une valeur constante pour une recherche rapide.
+# Les types immuables incluent les ints, floats, strings et tuples.
+invalid_dict = {[1,2,3]: "123"} # => Lève une TypeError: unhashable type: 'list'
+valid_dict = {(1,2,3):[1,2,3]} # Par contre, les valeurs peuvent être de tout type.
+
+# On trouve une valeur avec []
+filled_dict["one"] # => 1
+
+# On obtient toutes les clés sous forme d'un itérable avec "keys()" Il faut l'entourer
+# de list() pour avoir une liste Note: l'ordre n'est pas garanti.
+list(filled_dict.keys()) # => ["three", "two", "one"]
+
+
+# On obtient toutes les valeurs sous forme d'un itérable avec "values()".
+# Là aussi, il faut utiliser list() pour avoir une liste.
+# Note : l'ordre n'est toujours pas garanti.
+list(filled_dict.values()) # => [3, 2, 1]
+
+
+# On vérifie la présence d'une clé dans un dictionnaire avec "in"
+"one" in filled_dict # => True
+1 in filled_dict # => False
+
+# L'accès à une clé non-existente lève une KeyError
+filled_dict["four"] # KeyError
+
+# On utilise "get()" pour éviter la KeyError
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
+# La méthode get accepte une valeur de retour par défaut en cas de valeur non-existante.
+filled_dict.get("one", 4) # => 1
+filled_dict.get("four", 4) # => 4
+
+# "setdefault()" insère une valeur dans un dictionnaire si la clé n'est pas présente.
+filled_dict.setdefault("five", 5) # filled_dict["five"] devient 5
+filled_dict.setdefault("five", 6) # filled_dict["five"] est toujours 5
+
+# Ajouter à un dictionnaire
+filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}
+#filled_dict["four"] = 4 # une autre méthode
+
+# Enlever des clés d'un dictionnaire avec del
+del filled_dict["one"] # Enlever la clé "one" de filled_dict.
+
+
+# Les sets stockent des ensembles
+empty_set = set()
+# Initialiser un set avec des valeurs. Oui, ça ressemble aux dictionnaires, désolé.
+some_set = {1, 1, 2, 2, 3, 4} # some_set est maintenant {1, 2, 3, 4}
+
+# Comme les clés d'un dictionnaire, les éléments d'un set doivent être immuables.
+invalid_set = {[1], 1} # => Lève une TypeError: unhashable type: 'list'
+valid_set = {(1,), 1}
+
+# On peut changer un set :
+filled_set = some_set
+
+# Ajouter un objet au set :
+filled_set.add(5) # filled_set vaut maintenant {1, 2, 3, 4, 5}
+
+# Chercher les intersections de deux sets avec &
+other_set = {3, 4, 5, 6}
+filled_set & other_set # => {3, 4, 5}
+
+# On fait l'union de sets avec |
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+
+# On fait la différence de deux sets avec -
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+
+# On vérifie la présence d'un objet dans un set avec in
+2 in filled_set # => True
+10 in filled_set # => False
+
+
+
+####################################################
+## 3. Structures de contrôle et Itérables
+####################################################
+
+# On crée juste une variable
+some_var = 5
+
+# Voici une condition "si". L'indentation est significative en Python!
+# Affiche: "some_var is smaller than 10"
+if some_var > 10:
+ print("some_var is totally bigger than 10.")
+elif some_var < 10: # La clause elif ("sinon si") est optionelle
+ print("some_var is smaller than 10.")
+else: # La clause else ("sinon") l'est aussi.
+ print("some_var is indeed 10.")
+
+
+"""
+Les boucles "for" itèrent sur une liste
+Affiche:
+ chien est un mammifère
+ chat est un mammifère
+ souris est un mammifère
+"""
+for animal in ["chien", "chat", "souris"]:
+ # On peut utiliser format() pour interpoler des chaînes formattées
+ print("{} est un mammifère".format(animal))
+
+"""
+"range(nombre)" retourne un itérable de nombres
+de zéro au nombre donné
+Affiche:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print(i)
+
+"""
+"range(debut, fin)" retourne un itérable de nombre
+de debut à fin.
+Affiche:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print(i)
+
+"""
+"range(debut, fin, pas)" retourne un itérable de nombres
+de début à fin en incrémentant de pas.
+Si le pas n'est pas indiqué, la valeur par défaut est 1.
+Affiche:
+ 4
+ 6
+ 8
+"""
+for i in range(4, 8, 2):
+ print(i)
+"""
+
+Les boucles "while" bouclent jusqu'à ce que la condition devienne fausse.
+Affiche:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print(x)
+ x += 1 # Raccourci pour x = x + 1
+
+# On gère les exceptions avec un bloc try/except
+try:
+ # On utilise "raise" pour lever une erreur
+ raise IndexError("Ceci est une erreur d'index")
+except IndexError as e:
+ pass # Pass signifie simplement "ne rien faire". Généralement, on gère l'erreur ici.
+except (TypeError, NameError):
+ pass # Si besoin, on peut aussi gérer plusieurs erreurs en même temps.
+else: # Clause optionelle des blocs try/except. Doit être après tous les except.
+ print("Tout va bien!") # Uniquement si aucune exception n'est levée.
+finally: # Éxécuté dans toutes les circonstances.
+ print("On nettoie les ressources ici")
+
+# Au lieu de try/finally pour nettoyer les ressources, on peut utiliser with
+with open("myfile.txt") as f:
+ for line in f:
+ print(line)
+
+# Python offre une abstraction fondamentale : l'Iterable.
+# Un itérable est un objet pouvant être traîté comme une séquence.
+# L'objet retourné par la fonction range() est un itérable.
+
+filled_dict = {"one": 1, "two": 2, "three": 3}
+our_iterable = filled_dict.keys()
+print(our_iterable) #=> range(1,10). C'est un objet qui implémente l'interface Iterable
+
+# On peut boucler dessus
+for i in our_iterable:
+ print(i) # Affiche one, two, three
+
+# Cependant, on ne peut pas accéder aux éléments par leur adresse.
+our_iterable[1] # Lève une TypeError
+
+# Un itérable est un objet qui sait créer un itérateur.
+our_iterator = iter(our_iterable)
+
+# Notre itérateur est un objet qui se rappelle de notre position quand on le traverse.
+# On passe à l'élément suivant avec "next()".
+next(our_iterator) #=> "one"
+
+# Il garde son état quand on itère.
+next(our_iterator) #=> "two"
+next(our_iterator) #=> "three"
+
+# Après que l'itérateur a retourné toutes ses données, il lève une exception StopIterator
+next(our_iterator) # Lève une StopIteration
+
+# On peut mettre tous les éléments d'un itérateur dans une liste avec list()
+list(filled_dict.keys()) #=> Returns ["one", "two", "three"]
+
+
+####################################################
+## 4. Fonctions
+####################################################
+
+# On utilise "def" pour créer des fonctions
+def add(x, y):
+ print("x est {} et y est {}".format(x, y))
+ return x + y # On retourne une valeur avec return
+
+# Appel d'une fonction avec des paramètres :
+add(5, 6) # => affiche "x est 5 et y est 6" et retourne 11
+
+# Une autre manière d'appeller une fonction : avec des arguments
+add(y=6, x=5) # Les arguments peuvent être dans n'importe quel ordre.
+
+# Définir une fonction qui prend un nombre variable d'arguments
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) # => (1, 2, 3)
+
+# On peut aussi définir une fonction qui prend un nombre variable de paramètres.
+def keyword_args(**kwargs):
+ return kwargs
+
+# Appelons la pour voir ce qu'il se passe :
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+
+
+# On peut aussi faire les deux à la fois :
+def all_the_args(*args, **kwargs):
+ print(args)
+ print(kwargs)
+"""
+all_the_args(1, 2, a=3, b=4) affiche:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# En appelant des fonctions, on peut aussi faire l'inverse :
+# utiliser * pour étendre un tuple de paramètres
+# et ** pour étendre un dictionnaire d'arguments.
+args = (1, 2, 3, 4)
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # équivalent à foo(1, 2, 3, 4)
+all_the_args(**kwargs) # équivalent à foo(a=3, b=4)
+all_the_args(*args, **kwargs) # équivalent à foo(1, 2, 3, 4, a=3, b=4)
+
+# Retourne plusieurs valeurs (avec un tuple)
+def swap(x, y):
+ return y, x # Retourne plusieurs valeurs avec un tuple sans parenthèses.
+ # (Note: on peut aussi utiliser des parenthèses)
+
+x = 1
+y = 2
+x, y = swap(x, y) # => x = 2, y = 1
+# (x, y) = swap(x,y) # Là aussi, rien ne nous empêche d'ajouter des parenthèses
+
+# Portée des fonctions :
+x = 5
+
+def setX(num):
+ # La variable locale x n'est pas la même que la variable globale x
+ x = num # => 43
+ print (x) # => 43
+
+def setGlobalX(num):
+ global x
+ print (x) # => 5
+ x = num # la variable globale x est maintenant 6
+ print (x) # => 6
+
+setX(43)
+setGlobalX(6)
+
+
+# Python a des fonctions de première classe
+def create_adder(x):
+ def adder(y):
+ return x + y
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) # => 13
+
+# Mais aussi des fonctions anonymes
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
+
+# TODO - Fix for iterables
+# Il y a aussi des fonctions de base
+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]
+
+# On peut utiliser les compréhensions de listes pour de jolies maps et filtres.
+# Une compréhension de liste stocke la sortie comme une liste qui peut elle même être une liste imbriquée.
+[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. Classes
+####################################################
+
+
+# On utilise l'opérateur "classe" pour définir une classe
+class Human:
+
+ # Un attribut de la classe. Il est partagé par toutes les instances de la classe.
+ species = "H. sapiens"
+
+ # L'initialiseur de base. Il est appelé quand la classe est instanciée.
+ # Note : les doubles underscores au début et à la fin sont utilisés pour
+ # les fonctions et attributs utilisés par Python mais contrôlés par l'utilisateur.
+ # Les méthodes (ou objets ou attributs) comme: __init__, __str__,
+ # __repr__ etc. sont appelés méthodes magiques.
+ # Vous ne devriez pas inventer de noms de ce style.
+ def __init__(self, name):
+ # Assigner l'argument à l'attribut de l'instance
+ self.name = name
+
+ # Une méthode de l'instance. Toutes prennent "self" comme premier argument.
+ def say(self, msg):
+ return "{name}: {message}".format(name=self.name, message=msg)
+
+ # Une méthode de classe est partagée avec entre les instances
+ # Ils sont appelés avec la classe comme premier argument
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # Une méthode statique est appelée sans référence à une instance ni à une classe.
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+
+# Instantier une classe
+i = Human(name="Ian")
+print(i.say("hi")) # affiche "Ian: hi"
+
+j = Human("Joel")
+print(j.say("hello")) # affiche "Joel: hello"
+
+# Appeller notre méthode de classe
+i.get_species() # => "H. sapiens"
+
+# Changer les attributs partagés
+Human.species = "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
+
+# Appeller la méthode statique
+Human.grunt() # => "*grunt*"
+
+
+####################################################
+## 6. Modules
+####################################################
+
+# On peut importer des modules
+import math
+print(math.sqrt(16)) # => 4.0
+
+# On peut importer des fonctions spécifiques d'un module
+from math import ceil, floor
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
+
+# On peut importer toutes les fonctions d'un module
+# Attention: ce n'est pas recommandé.
+from math import *
+
+# On peut raccourcir un nom de module
+import math as m
+math.sqrt(16) == m.sqrt(16) # => True
+
+# Les modules Python sont juste des fichiers Python.
+# Vous pouvez écrire les vôtres et les importer. Le nom du module
+# est le nom du fichier.
+
+# On peut voir quels fonctions et objets un module définit
+import math
+dir(math)
+
+
+####################################################
+## 7. Avancé
+####################################################
+
+# Les générateurs aident à faire du code paresseux (lazy)
+def double_numbers(iterable):
+ for i in iterable:
+ yield i + i
+
+# Un générateur crée des valeurs à la volée.
+# Au lieu de générer et retourner toutes les valeurs en une fois, il en crée une à chaque
+# itération. Cela signifie que les valeurs supérieures à 15 ne seront pas traîtées par
+# double_numbers.
+# Note : range est un générateur aussi.
+# Créer une liste 1-900000000 prendrait beaucoup de temps
+# On met un underscore à la fin d'un nom de variable normalement réservé par Python.
+range_ = range(1, 900000000)
+# Double tous les nombres jusqu'à ce qu'un nombre >=30 soit trouvé
+for i in double_numbers(range_):
+ print(i)
+ if i >= 30:
+ break
+
+
+# Decorateurs
+# Dans cet exemple, beg enveloppe say
+# Beg appellera say. Si say_please vaut True le message retourné sera changé
+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()) # affiche Can you buy me a beer?
+print(say(say_please=True)) # affiche Can you buy me a beer? Please! I am poor :(
+```
+
+## Prêt pour encore plus ?
+
+### En ligne et gratuit (en anglais)
+
+* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
+* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
+* [Dive Into Python](http://www.diveintopython.net/)
+* [Ideas for Python Projects](http://pythonpracticeprojects.com)
+* [The Official Docs](http://docs.python.org/3/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+* [Python Course](http://www.python-course.eu/index.php)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+
+### Livres (en anglais)
+
+* [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/fr-fr/scala.html.markdown b/fr-fr/scala.html.markdown
index a43edf16..c6d06361 100644
--- a/fr-fr/scala.html.markdown
+++ b/fr-fr/scala.html.markdown
@@ -208,6 +208,7 @@ sSquared.reduce (_+_)
// La fonction filter prend un prédicat (une fonction de type A -> Booléen) et
// sélectionne tous les éléments qui satisfont ce prédicat
List(1, 2, 3) filter (_ > 2) // List(3)
+case class Person(name: String, age: Int)
List(
Person(name = "Dom", age = 23),
Person(name = "Bob", age = 30)
@@ -217,6 +218,7 @@ List(
// Scala a une méthode foreach définie pour certaines collections
// qui prend en argument une fonction renvoyant Unit (une méthode void)
+val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100)
aListOfNumbers foreach (x => println(x))
aListOfNumbers foreach println
@@ -271,11 +273,12 @@ i // Montre la valeur de i. Notez que while est une boucle au sens classique.
// mais utiliser des combinateurs et des compréhensions comme ci-dessus est plus
// facile pour comprendre et pour faire la parallélisation
+i = 0
// La boucle do while
do {
println("x is still less then 10");
- x += 1
-} while (x < 10)
+ i += 1
+} while (i < 10)
// La récursivité est un moyen idiomatique de faire une chose répétitive en Scala.
@@ -370,7 +373,7 @@ val email(user, domain) = "henry@zkpr.com"
"Les chaînes de caractères Scala sont entourées de doubles guillements"
'a' // Un caractère de Scala
-'Les simples guillemets n'existent pas en Scala // Erreur
+// 'Les simples guillemets n'existent pas en Scala' // Erreur
"Les chaînes de caractères possèdent les méthodes usuelles de Java".length
"Il y a aussi quelques méthodes extra de Scala.".reverse
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/fr-fr/yaml-fr.html.markdown b/fr-fr/yaml-fr.html.markdown
index 43b1df54..1e8296d3 100644
--- a/fr-fr/yaml-fr.html.markdown
+++ b/fr-fr/yaml-fr.html.markdown
@@ -8,113 +8,117 @@ lang: fr-fr
Proposé à l'origine par Clark Evans en Mai 2001, YAML est un un format de
représentation de données par sérialisation, conçu pour être aisément
-éditable et lisible par nous même, les humains.
+modifiable et lisible par nous-mêmes, les humains.
-YAML est plus concis que le XML auquel il est parfois comparé par ceux qui le découvre, plus lisible et clair que le CSV, et emprunte beaucoup au JSON dont il est un parent naturel. Toutefois, YAML emprunte également des idées et concepts de chez Python, et s'intègre bien avec bon nombre de langages.
+YAML est plus concis que le XML auquel il est parfois comparé par ceux qui le
+découvre, plus lisible et clair que le CSV, et emprunte beaucoup au JSON dont
+il est un parent naturel. Toutefois, YAML emprunte également des idées et
+concepts de Python, et s'intègre bien avec bon nombre de langages.
+Contrairement à ce dernier, YAML interdit l'utilisation des tabulations.
```yaml
-# les Commentaires sont précédés d'un signe "#", comme cette ligne.
+# Les commentaires sont précédés d'un signe "#", comme cette ligne.
#############
# SCALAIRES #
#############
-# Les scalaires sont l'ensemble des types YAML qui ne sont pas des collections
-# ( listes ou tableaux associatifs ).
+# Les scalaires sont l'ensemble des types YAML qui ne sont pas des collections
+# (listes ou tableaux associatifs).
-# Notre objet root ( racine ), sera une map ( carte ) et englobera
-# l'intégralité du document. Cette map est l'équivalent d'un dictionnaire,
+# Notre objet root (racine), sera une map (carte) et englobera
+# l'intégralité du document. Cette map est l'équivalent d'un dictionnaire,
# hash ou objet dans d'autres langages.
clé: valeur
-aurtre_clé: une autre valeur
+autre_clé: une autre valeur
valeur_numérique: 100
notation_scientifique: 1e+12
-boolean: true
+booléen: true
valeur_null: null
clé avec espaces: valeur
-# Bien qu'il ne soit pas nécessaire d'enfermer les chaînes de caractères
+# Bien qu'il ne soit pas nécessaire de mettre les chaînes de caractères
# entre guillemets, cela reste possible, et parfois utile.
toutefois: "Une chaîne, peut être contenue entre guillemets."
-"Une clé entre guillemets.": "Utile si on veut utiliser ':' dans la clé."
+"Une clé entre guillemets.": "Utile si l'on veut utiliser ':' dans la clé."
-# Les chaînes couvrant plusieurs lignes, peuvent être écrites au choix,
-# comme un 'bloc littéral' ( avec | ) ou bien 'bloc replié' avec ( > ).
+# Les chaînes couvrant plusieurs lignes, peuvent être écrites au choix,
+# comme un "bloc littéral" (avec '|') ou bien un "bloc replié" (avec '>').
bloc_littéral: |
- Tout ce bloc de texte sera la valeur de la clé 'bloc_littéral',
- avec préservation des retours à la ligne. ( chaque ligne vide à
- l'intérieur du même bloc, sera remplacée par "\n\n" )
+ Tout ce bloc de texte sera la valeur de la clé "bloc_littéral",
+ avec préservation des retours à la ligne.
Le littéral continue jusqu'à ce que l'indentation soit annulée.
- Toutes lignes qui serait "d'avantage indentées" conservent leur
+ Toutes lignes qui seraient "davantage indentées" conservent leur
indentation, constituée de 4 espaces.
bloc_replié: >
- Tout ce bloc de texte sera la valeur de la clé 'bloc_replié', mais
- cette fois ci, toutes les nouvelles lignes deviendront un simple espace.
+ Tout ce bloc de texte sera la valeur de la clé "bloc_replié", mais
+ cette fois-ci, toutes les nouvelles lignes deviendront un simple espace.
- Les lignes vides, comme ci-dessus, seront converties en caractère "\n".
+ Les lignes vides, comme ci-dessus, seront converties en caractère de
+ nouvelle ligne.
- Les lignes 'plus-indentées' gardent leurs retours à la ligne -
+ Les lignes "plus-indentées" gardent leurs retours à la ligne -
ce texte apparaîtra sur deux lignes.
###############
# COLLECTIONS #
###############
-# l'Imbrication est créée par indentation.
+# L'imbrication est créée par indentation.
une_map_imbriquée:
clé: valeur
autre_clé: autre valeur
autre_map_imbriquée:
bonjour: bonjour
-# les Clés des Maps ne sont pas nécessairement des chaînes de caractères.
-0.25: une clé de type float
+# Les clés des maps ne sont pas nécessairement des chaînes de caractères.
+0.25: une clé de type flottant
-# les Clés peuvent également être des objets s'étendant sur plusieurs lignes,
+# Les clés peuvent également être des objets s'étendant sur plusieurs lignes,
# en utilisant le signe "?" pour indiquer le début de la clé.
? |
- ceci est une Clé
+ ceci est une clé
sur de multiples lignes
-: et ceci est sa Valeur
+: et ceci est sa valeur
# YAML autorise aussi l'usage des collections à l'intérieur des clés,
# mais certains langages de programmation ne le tolère pas si bien.
-# les Séquences (équivalent des listes ou tableaux) ressemblent à cela:
+# Les séquences (équivalent des listes ou tableaux) ressemblent à cela :
une_séquence:
- - Item 1
- - Item 2
+ - Objet 1
+ - Objet 2
- 0.5 # les séquences peuvent contenir des types variés.
- - Item 4
+ - Objet 4
- clé: valeur
autre_clé: autre_valeur
-
- Ceci est une séquence
- dans une autre séquence
-# YAML étant un proche parent de JSON, vous pouvez écrire directement
+# YAML étant un proche parent de JSON, vous pouvez écrire directement
# des maps et séquences façon JSON
json_map: {"clé": "valeur"}
json_seq: [1, 2, 3, "soleil"]
-#################################
+################################
# AUTRES FONCTIONNALITÉES YAML #
-#################################
+################################
-# YAML possède une fonctionnalité fort utile nommée 'ancres'. Celle-ci
+# YAML possède une fonctionnalité fort utile nommée "ancres". Celle-ci
# vous permet de dupliquer aisément du contenu au sein de votre document.
-# Les deux clés suivantes auront la même valeur:
+# Les deux clés suivantes auront la même valeur :
contenu_ancré: &nom_ancre Cette chaîne sera la valeur des deux clés.
autre_ancre: *nom_ancre
-# Avec les Tags YAML, vous pouvez explicitement déclarer des types de données.
+# Avec les tags YAML, vous pouvez explicitement déclarer des types de données.
chaine_explicite: !!str 0.5
-# Certains parsers implémentent des tags spécifiques à d'autres langages,
-# comme par exemple le "complex number" de Python.
+# Certains analyseurs syntaxiques (parsers) implémentent des tags spécifiques à
+# d'autres langages, comme par exemple celui des nombres complexes de Python.
python_complex_number: !!python/complex 1+2j
#####################
@@ -122,7 +126,7 @@ python_complex_number: !!python/complex 1+2j
#####################
# YAML interprète également les données formatées ISO de type date et datetime,
-# pas seulement les chaînes et nombres.
+# pas seulement les chaînes et nombres.
datetime: 2001-12-15T02:59:43.1Z
datetime_avec_espaces: 2001-12-14 21:59:43.10 -5
date: 2002-12-14
@@ -135,14 +139,14 @@ fichier_gif: !!binary |
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
-# YAML a de même un type "set", qui ressemble à cela:
+# YAML a de même un type "set", semblable à ceci :
set:
? item1
? item2
? item3
# Comme dans Python, les sets ne sont que des maps contenant des valeurs null ;
-# le set précédent est l'équivalent du suivant:
+# le set précédent est l'équivalent du suivant :
set2:
item1: null
item2: null
@@ -152,6 +156,6 @@ set2:
Quelques références et outils :
-- Doc officielle [YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais*,
+- Documentation officielle [YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais*,
- Une [Introduction à YAML](http://sweetohm.net/html/introduction-yaml.html) très bien construite et claire,
-- Un outil pour tester [live](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples.
+- Un outil pour tester [en ligne](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples.
diff --git a/fsharp.html.markdown b/fsharp.html.markdown
index 62118006..809a1da2 100644
--- a/fsharp.html.markdown
+++ b/fsharp.html.markdown
@@ -31,14 +31,14 @@ If you want to try out the code below, you can go to [tryfsharp.org](http://www.
// The "let" keyword defines an (immutable) value
let myInt = 5
let myFloat = 3.14
-let myString = "hello" //note that no types needed
+let myString = "hello" // note that no types needed
// ------ Lists ------
-let twoToFive = [2;3;4;5] // Square brackets create a list with
+let twoToFive = [2; 3; 4; 5] // Square brackets create a list with
// semicolon delimiters.
let oneToFive = 1 :: twoToFive // :: creates list with new 1st element
-// The result is [1;2;3;4;5]
-let zeroToFive = [0;1] @ twoToFive // @ concats two lists
+// The result is [1; 2; 3; 4; 5]
+let zeroToFive = [0; 1] @ twoToFive // @ concats two lists
// IMPORTANT: commas are never used as delimiters, only semicolons!
@@ -53,7 +53,7 @@ add 2 3 // Now run the function.
// to define a multiline function, just use indents. No semicolons needed.
let evens list =
- let isEven x = x%2 = 0 // Define "isEven" as a sub function
+ let isEven x = x % 2 = 0 // Define "isEven" as a sub function
List.filter isEven list // List.filter is a library function
// with two parameters: a boolean function
// and a list to work on
@@ -75,7 +75,7 @@ let sumOfSquaresTo100piped =
// you can define lambdas (anonymous functions) using the "fun" keyword
let sumOfSquaresTo100withFun =
- [1..100] |> List.map (fun x -> x*x) |> List.sum
+ [1..100] |> List.map (fun x -> x * x) |> List.sum
// In F# there is no "return" keyword. A function always
// returns the value of the last expression used.
@@ -109,7 +109,7 @@ optionPatternMatch invalidValue
// The printf/printfn functions are similar to the
// Console.Write/WriteLine functions in C#.
printfn "Printing an int %i, a float %f, a bool %b" 1 2.0 true
-printfn "A string %s, and something generic %A" "hello" [1;2;3;4]
+printfn "A string %s, and something generic %A" "hello" [1; 2; 3; 4]
// There are also sprintf/sprintfn functions for formatting data
// into a string, similar to String.Format in C#.
@@ -119,7 +119,7 @@ printfn "A string %s, and something generic %A" "hello" [1;2;3;4]
// ================================================
// F# is a true functional language -- functions are first
-// class entities and can be combined easy to make powerful
+// class entities and can be combined easily to make powerful
// constructs
// Modules are used to group functions together
@@ -131,19 +131,19 @@ module FunctionExamples =
// basic usage of a function
let a = add 1 2
- printfn "1+2 = %i" a
+ printfn "1 + 2 = %i" a
// partial application to "bake in" parameters
let add42 = add 42
let b = add42 1
- printfn "42+1 = %i" b
+ printfn "42 + 1 = %i" b
// composition to combine functions
let add1 = add 1
let add2 = add 2
let add3 = add1 >> add2
let c = add3 7
- printfn "3+7 = %i" c
+ printfn "3 + 7 = %i" c
// higher order functions
[1..10] |> List.map add3 |> printfn "new list is %A"
@@ -151,7 +151,7 @@ module FunctionExamples =
// lists of functions, and more
let add6 = [add1; add2; add3] |> List.reduce (>>)
let d = add6 7
- printfn "1+2+3+7 = %i" d
+ printfn "1 + 2 + 3 + 7 = %i" d
// ================================================
// Lists and collection
@@ -168,12 +168,12 @@ module FunctionExamples =
module ListExamples =
// lists use square brackets
- let list1 = ["a";"b"]
+ let list1 = ["a"; "b"]
let list2 = "c" :: list1 // :: is prepending
let list3 = list1 @ list2 // @ is concat
// list comprehensions (aka generators)
- let squares = [for i in 1..10 do yield i*i]
+ let squares = [for i in 1..10 do yield i * i]
// prime number generator
let rec sieve = function
@@ -190,8 +190,8 @@ module ListExamples =
| [first; second] -> printfn "list is %A and %A" first second
| _ -> printfn "the list has more than two elements"
- listMatcher [1;2;3;4]
- listMatcher [1;2]
+ listMatcher [1; 2; 3; 4]
+ listMatcher [1; 2]
listMatcher [1]
listMatcher []
@@ -219,7 +219,7 @@ module ListExamples =
module ArrayExamples =
// arrays use square brackets with bar
- let array1 = [| "a";"b" |]
+ let array1 = [| "a"; "b" |]
let first = array1.[0] // indexed access using dot
// pattern matching for arrays is same as for lists
@@ -230,13 +230,13 @@ module ArrayExamples =
| [| first; second |] -> printfn "array is %A and %A" first second
| _ -> printfn "the array has more than two elements"
- arrayMatcher [| 1;2;3;4 |]
+ arrayMatcher [| 1; 2; 3; 4 |]
// Standard library functions just as for List
[| 1..10 |]
- |> Array.map (fun i -> i+3)
- |> Array.filter (fun i -> i%2 = 0)
+ |> Array.map (fun i -> i + 3)
+ |> Array.filter (fun i -> i % 2 = 0)
|> Array.iter (printfn "value is %i. ")
@@ -248,14 +248,14 @@ module SequenceExamples =
// sequences can use yield and
// can contain subsequences
let strange = seq {
- // "yield! adds one element
+ // "yield" adds one element
yield 1; yield 2;
// "yield!" adds a whole subsequence
yield! [5..10]
yield! seq {
for i in 1..10 do
- if i%2 = 0 then yield i }}
+ if i % 2 = 0 then yield i }}
// test
strange |> Seq.toList
@@ -280,11 +280,11 @@ module DataTypeExamples =
// Tuples are quick 'n easy anonymous types
// -- Use a comma to create a tuple
- let twoTuple = 1,2
- let threeTuple = "a",2,true
+ let twoTuple = 1, 2
+ let threeTuple = "a", 2, true
// Pattern match to unpack
- let x,y = twoTuple //sets x=1 y=2
+ let x, y = twoTuple // sets x = 1, y = 2
// ------------------------------------
// Record types have named fields
@@ -297,7 +297,7 @@ module DataTypeExamples =
let person1 = {First="John"; Last="Doe"}
// Pattern match to unpack
- let {First=first} = person1 //sets first="john"
+ let {First = first} = person1 // sets first="John"
// ------------------------------------
// Union types (aka variants) have a set of choices
@@ -331,14 +331,14 @@ module DataTypeExamples =
| Worker of Person
| Manager of Employee list
- let jdoe = {First="John";Last="Doe"}
+ let jdoe = {First="John"; Last="Doe"}
let worker = Worker jdoe
// ------------------------------------
- // Modelling with types
+ // Modeling with types
// ------------------------------------
- // Union types are great for modelling state without using flags
+ // Union types are great for modeling state without using flags
type EmailAddress =
| ValidEmailAddress of string
| InvalidEmailAddress of string
@@ -383,8 +383,8 @@ module DataTypeExamples =
type Rank = Two | Three | Four | Five | Six | Seven | Eight
| Nine | Ten | Jack | Queen | King | Ace
- let hand = [ Club,Ace; Heart,Three; Heart,Ace;
- Spade,Jack; Diamond,Two; Diamond,Ace ]
+ let hand = [ Club, Ace; Heart, Three; Heart, Ace;
+ Spade, Jack; Diamond, Two; Diamond, Ace ]
// sorting
List.sort hand |> printfn "sorted hand is (low to high) %A"
@@ -419,14 +419,14 @@ module ActivePatternExamples =
| _ -> printfn "%c is something else" ch
// print a list
- ['a';'b';'1';' ';'-';'c'] |> List.iter printChar
+ ['a'; 'b'; '1'; ' '; '-'; 'c'] |> List.iter printChar
// -----------------------------------
// FizzBuzz using active patterns
// -----------------------------------
// You can create partial matching patterns as well
- // Just use undercore in the defintion, and return Some if matched.
+ // Just use underscore in the defintion, 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
@@ -479,7 +479,7 @@ module AlgorithmExamples =
List.concat [smallerElements; [firstElem]; largerElements]
// test
- sort [1;5;23;18;9;1;3] |> printfn "Sorted = %A"
+ sort [1; 5; 23; 18; 9; 1; 3] |> printfn "Sorted = %A"
// ================================================
// Asynchronous Code
@@ -526,7 +526,7 @@ module AsyncExample =
|> Async.RunSynchronously // start them off
// ================================================
-// .NET compatability
+// .NET compatibility
// ================================================
module NetCompatibilityExamples =
@@ -536,7 +536,7 @@ module NetCompatibilityExamples =
// ------- work with existing library functions -------
- let (i1success,i1) = System.Int32.TryParse("123");
+ let (i1success, i1) = System.Int32.TryParse("123");
if i1success then printfn "parsed as %i" i1 else printfn "parse failed"
// ------- Implement interfaces on the fly! -------
@@ -570,12 +570,12 @@ module NetCompatibilityExamples =
// abstract base class with virtual methods
[<AbstractClass>]
type Shape() =
- //readonly properties
+ // readonly properties
abstract member Width : int with get
abstract member Height : int with get
- //non-virtual method
+ // non-virtual method
member this.BoundingArea = this.Height * this.Width
- //virtual method with base implementation
+ // virtual method with base implementation
abstract member Print : unit -> unit
default this.Print () = printfn "I'm a shape"
@@ -586,19 +586,19 @@ module NetCompatibilityExamples =
override this.Height = y
override this.Print () = printfn "I'm a Rectangle"
- //test
- let r = Rectangle(2,3)
+ // test
+ let r = Rectangle(2, 3)
printfn "The width is %i" r.Width
printfn "The area is %i" r.BoundingArea
r.Print()
// ------- extension methods -------
- //Just as in C#, F# can extend existing classes with extension methods.
+ // Just as in C#, F# can extend existing classes with extension methods.
type System.String with
member this.StartsWithA = this.StartsWith "A"
- //test
+ // test
let s = "Alice"
printfn "'%s' starts with an 'A' = %A" s s.StartsWithA
diff --git a/git.html.markdown b/git.html.markdown
index b1347309..35f24b2d 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -5,6 +5,8 @@ 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"]
+ - ["Andrew Taylor", "http://github.com/andrewjt71"]
filename: LearnGit.txt
---
@@ -76,6 +78,11 @@ other repositories, or not!
A branch is essentially a pointer to the last commit you made. As you go on
committing, this pointer will automatically update to point the latest commit.
+### Tag
+
+A tag is a mark on specific point in history. Typically people use this
+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.
@@ -206,6 +213,28 @@ $ git branch -m myBranchName myNewBranchName
$ git branch myBranchName --edit-description
```
+### tag
+
+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.
@@ -305,6 +334,9 @@ $ git log --oneline
# Show merge commits only
$ git log --merges
+
+# Show all commits represented by an ASCII graph
+$ git log --graph
```
### merge
@@ -343,9 +375,12 @@ Pulls from a repository and merges it with another branch.
# Update your local repo, by merging in new changes
# from the remote "origin" and "master" branch.
# git pull <remote> <branch>
-# git pull => implicitly defaults to => git pull origin master
$ git pull origin master
+# By default, git pull will update your current branch
+# by merging in new changes from its remote-tracking branch
+$ git pull
+
# Merge in changes from remote branch and rebase
# branch commits onto your local repo, like: "git pull <remote> <branch>, git rebase <branch>"
$ git pull origin master --rebase
@@ -359,9 +394,12 @@ Push and merge changes from a branch to a remote & branch.
# Push and merge changes from a local repo to a
# remote named "origin" and "master" branch.
# git push <remote> <branch>
-# git push => implicitly defaults to => git push origin master
$ git push origin master
+# By default, git push will push and merge changes from
+# the current branch to its remote-tracking branch
+$ git push
+
# To link up current local branch with a remote branch, add -u flag:
$ git push -u origin master
# Now, anytime you want to push from that same local branch, use shortcut:
@@ -465,6 +503,16 @@ $ git reset 31f2bb1
# after the specified commit).
$ git reset --hard 31f2bb1
```
+### revert
+
+Revert can be used to undo a commit. It should not be confused with reset which restores
+the state of a project to a previous point. Revert will add a new commit which is the
+inverse of the specified commit, thus reverting it.
+
+```bash
+# Revert a specified commit
+$ git revert <commit>
+```
### rm
@@ -484,16 +532,21 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [Udemy Git Tutorial: A Comprehensive Guide](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/)
+* [Git Immersion - A Guided tour that walks through the fundamentals of git](http://gitimmersion.com/)
+
* [git-scm - Video Tutorials](http://git-scm.com/videos)
* [git-scm - Documentation](http://git-scm.com/docs)
* [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/)
* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html)
* [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/go.html.markdown b/go.html.markdown
index 34b855e3..dc684227 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -10,6 +10,7 @@ contributors:
- ["Quint Guvernator", "https://github.com/qguv"]
- ["Jose Donizetti", "https://github.com/josedonizetti"]
- ["Alexej Friesen", "https://github.com/heyalexej"]
+ - ["Clayton Walker", "https://github.com/cwalk"]
---
Go was created out of the need to get work done. It's not the latest trend
@@ -107,15 +108,16 @@ can include line breaks.` // Same string type.
bs := []byte("a slice") // Type conversion syntax.
// Because they are dynamic, slices can be appended to on-demand.
- // To append elements to a slice, built-in append() function is used.
+ // To append elements to a slice, the built-in append() function is used.
// First argument is a slice to which we are appending. Commonly,
// the array variable is updated in place, as in example below.
s := []int{1, 2, 3} // Result is a slice of length 3.
s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6.
fmt.Println(s) // Updated slice is now [1 2 3 4 5 6]
+
// To append another slice, instead of list of atomic elements we can
// pass a reference to a slice or a slice literal like this, with a
- // trailing elipsis, meaning take a slice and unpack its elements,
+ // trailing ellipsis, meaning take a slice and unpack its elements,
// appending them to slice s.
s = append(s, []int{7, 8, 9}...) // Second argument is a slice literal.
fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9]
@@ -129,7 +131,7 @@ can include line breaks.` // Same string type.
m["one"] = 1
// Unused variables are an error in Go.
- // The underbar lets you "use" a variable but discard its value.
+ // The underscore lets you "use" a variable but discard its value.
_, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs
// Output of course counts as using a variable.
fmt.Println(s, c, a4, s3, d2, m)
@@ -164,7 +166,7 @@ func expensiveComputation() float64 {
}
func learnFlowControl() {
- // If statements require brace brackets, and do not require parens.
+ // If statements require brace brackets, and do not require parentheses.
if true {
fmt.Println("told ya")
}
@@ -407,6 +409,8 @@ func requestServer() {
The root of all things Go is the [official Go web site](http://golang.org/).
There you can follow the tutorial, play interactively, and read lots.
+Aside from a tour, [the docs](https://golang.org/doc/) contain information on
+how to write clean and effective Go code, package and command docs, and release history.
The language definition itself is highly recommended. It's easy to read
and amazingly short (as language definitions go these days.)
@@ -420,3 +424,5 @@ idioms. Or you can click on a function name in [the
documentation](http://golang.org/pkg/) and the source code comes up!
Another great resource to learn Go is [Go by example](https://gobyexample.com/).
+
+Go Mobile adds support for mobile platforms (Android and iOS). You can write all-Go native mobile apps or write a library that contains bindings from a Go package, which can be invoked via Java (Android) and Objective-C (iOS). Check out the [Go Mobile page](https://github.com/golang/go/wiki/Mobile) for more information.
diff --git a/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/haml.html.markdown b/haml.html.markdown
index 847714e6..0948e9ef 100644
--- a/haml.html.markdown
+++ b/haml.html.markdown
@@ -122,11 +122,36 @@ $ haml input_file.haml output_file.html
if book do
%p This is a book
+
+/ Adding ordered / unordered list
+%ul
+ %li
+ =item1
+ =item2
/
Again, no need to add the closing tags to the block, even for the Ruby.
Indentation will take care of that for you.
+/ -------------------------------------------
+/ Inserting Table with bootstrap classes
+/ -------------------------------------------
+
+%table.table.table-hover
+ %thead
+ %tr
+ %th Header 1
+ %th Header 2
+
+ %tr
+ %td Value1
+ %td value2
+
+ %tfoot
+ %tr
+ %td
+ Foot value
+
/ -------------------------------------------
/ Inline Ruby / Ruby interpolation
diff --git a/haskell.html.markdown b/haskell.html.markdown
index 369b1b20..4ce1a839 100644
--- a/haskell.html.markdown
+++ b/haskell.html.markdown
@@ -81,7 +81,7 @@ not False -- True
[5,4..1] -- [5, 4, 3, 2, 1]
-- indexing into a list
-[0..] !! 5 -- 5
+[1..10] !! 3 -- 4
-- You can also have infinite lists in Haskell!
[1..] -- a list of all the natural numbers
@@ -189,17 +189,17 @@ 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 5, and then returns the final value.
-foo = (*5) . (+10)
+-- multiplies the result of that by 4, and then returns the final value.
+foo = (4*) . (10+)
--- (5 + 10) * 5 = 75
-foo 5 -- 75
+-- 4*(10 + 5) = 60
+foo 5 -- 60
-- fixing precedence
-- Haskell has another operator called `$`. This operator applies a function
@@ -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/coffeescript-hu.html.markdown b/hu-hu/coffeescript-hu.html.markdown
new file mode 100644
index 00000000..b5ae2107
--- /dev/null
+++ b/hu-hu/coffeescript-hu.html.markdown
@@ -0,0 +1,107 @@
+---
+language: coffeescript
+contributors:
+ - ["Tenor Biel", "http://github.com/L8D"]
+ - ["Xavier Yao", "http://github.com/xavieryao"]
+translators:
+ - ["Tamás Diószegi", "http://github.com/ditam"]
+lang: hu-hu
+filename: coffeescript-hu.coffee
+---
+
+A CoffeeScript egy apró nyelv ami egy-az-egyben egyenértékű Javascript kódra fordul, és így futásidőben már nem szükséges interpretálni.
+Mint a JavaScript egyik követője, a CoffeeScript mindent megtesz azért, hogy olvasható, jól formázott és jól futó JavaScript kódot állítson elő, ami minden JavaScript futtatókörnyezetben jól működik.
+
+Rézletekért lásd még a [CoffeeScript weboldalát](http://coffeescript.org/), ahol egy teljes CoffeScript tutorial is található.
+
+```coffeescript
+# A CoffeeScript egy hipszter nyelv.
+# Követi több modern nyelv trendjeit.
+# Így a kommentek, mint Ruby-ban és Python-ban, a szám szimbólummal kezdődnek.
+
+###
+A komment blokkok ilyenek, és közvetlenül '/ *' és '* /' jelekre fordítódnak
+az eredményül kapott JavaScript kódban.
+
+Mielőtt tovább olvasol, jobb, ha a JavaScript alapvető szemantikájával
+tisztában vagy.
+
+(A kód példák alatt kommentként látható a fordítás után kapott JavaScript kód.)
+###
+
+# Értékadás:
+number = 42 #=> var number = 42;
+opposite = true #=> var opposite = true;
+
+# Feltételes utasítások:
+number = -42 if opposite #=> if(opposite) { number = -42; }
+
+# Függvények:
+square = (x) -> x * x #=> var square = function(x) { return x * x; }
+
+fill = (container, liquid = "coffee") ->
+ "Filling the #{container} with #{liquid}..."
+#=>var fill;
+#
+#fill = function(container, liquid) {
+# if (liquid == null) {
+# liquid = "coffee";
+# }
+# return "Filling the " + container + " with " + liquid + "...";
+#};
+
+# Szám tartományok:
+list = [1..5] #=> var list = [1, 2, 3, 4, 5];
+
+# Objektumok:
+math =
+ root: Math.sqrt
+ square: square
+ cube: (x) -> x * square x
+#=> var math = {
+# "root": Math.sqrt,
+# "square": square,
+# "cube": function(x) { return x * square(x); }
+# };
+
+# "Splat" jellegű függvény-paraméterek:
+race = (winner, runners...) ->
+ print winner, runners
+#=>race = function() {
+# var runners, winner;
+# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
+# return print(winner, runners);
+# };
+
+# Létezés-vizsgálat:
+alert "I knew it!" if elvis?
+#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
+
+# Tömb értelmezések: (array comprehensions)
+cubes = (math.cube num for num in list)
+#=>cubes = (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;
+# })();
+
+foods = ['broccoli', 'spinach', 'chocolate']
+eat food for food in foods when food isnt 'chocolate'
+#=>foods = ['broccoli', 'spinach', 'chocolate'];
+#
+#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) {
+# food = foods[_k];
+# if (food !== 'chocolate') {
+# eat(food);
+# }
+#}
+```
+
+## További források
+
+- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/)
+- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read)
diff --git a/hu-hu/go.html.markdown b/hu-hu/go-hu.html.markdown
index 638c9489..638c9489 100644
--- a/hu-hu/go.html.markdown
+++ b/hu-hu/go-hu.html.markdown
diff --git a/hu-hu/ruby-hu.html.markdown b/hu-hu/ruby-hu.html.markdown
new file mode 100644
index 00000000..f2fe4e5d
--- /dev/null
+++ b/hu-hu/ruby-hu.html.markdown
@@ -0,0 +1,555 @@
+---
+language: ruby
+lang: hu-hu
+filename: learnruby-hu.rb
+contributors:
+ - ["David Underwood", "http://theflyingdeveloper.com"]
+ - ["Joel Walden", "http://joelwalden.net"]
+ - ["Luke Holder", "http://twitter.com/lukeholder"]
+ - ["Tristan Hume", "http://thume.ca/"]
+ - ["Nick LaMuro", "https://github.com/NickLaMuro"]
+ - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
+ - ["Dzianis Dashkevich", "https://github.com/dskecse"]
+ - ["Levi Bostian", "https://github.com/levibostian"]
+ - ["Rahil Momin", "https://github.com/iamrahil"]
+translators:
+ - ["Zsolt Prontvai", "https://github.com/prozsolt"]
+---
+
+```ruby
+# Ez egy komment
+
+=begin
+Ez egy többsoros komment
+Senki sem használja
+Neked sem kellene
+=end
+
+# Először is: Minden objektum
+
+# A számok objektumok
+
+3.class #=> Fixnum
+
+3.to_s #=> "3"
+
+
+# Néhány alapvető számtani művelet
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+2**5 #=> 32
+
+# A számtani művelet csak szintaktikus cukor
+# az objektumon történő függvény hívásra
+1.+(3) #=> 4
+10.* 5 #=> 50
+
+# A speciális értékek objektumok
+nil # Nincs itt semmi látnivaló
+true # igaz
+false # hamis
+
+nil.class #=> NilClass
+true.class #=> TrueClass
+false.class #=> FalseClass
+
+# Egyenlőség
+1 == 1 #=> true
+2 == 1 #=> false
+
+# Egyenlőtlenség
+1 != 1 #=> false
+2 != 1 #=> true
+
+# A false-on kívül, nil az egyetlen hamis érték
+
+!nil #=> true
+!false #=> true
+!0 #=> false
+
+# Még több összehasonlítás
+1 < 10 #=> true
+1 > 10 #=> false
+2 <= 2 #=> true
+2 >= 2 #=> true
+
+# Logikai operátorok
+true && false #=> false
+true || false #=> true
+!true #=> false
+
+# A logikai operátoroknak alternatív verziójuk is van sokkal kisebb
+# precedenciával. Ezeket arra szánták, hogy több állítást összeláncoljanak
+# amíg egyikük igaz vagy hamis értékkel nem tér vissza.
+
+# `csinalj_valami_mast` csak akkor fut le, ha `csinalj_valamit` igaz értékkel
+# tért vissza.
+csinalj_valamit() and csinalj_valami_mast()
+# `log_error` csak akkor fut le, ha `csinalj_valamit` hamis értékkel
+# tért vissza.
+csinalj_valamit() or log_error()
+
+
+# A sztringek objektumok
+
+'Én egy sztring vagyok'.class #=> String
+"Én is egy sztring vagyok".class #=> String
+
+helykitolto = 'interpolációt használhatok'
+"Sztring #{helykitolto}, ha dupla időzőjelben van a sztringem"
+#=> "Sztring interpolációt használhatok, ha dupla időzőjelben van a sztringem"
+
+# A szimpla idézőjelet preferáljuk, ahol csak lehet,
+# mert a dupla idézőjel extra számításokat végez.
+
+# Kombinálhatunk sztringeket, de nem számokkal
+'hello ' + 'world' #=> "hello world"
+'hello ' + 3 #=> TypeError: can't convert Fixnum into String
+'hello ' + 3.to_s #=> "hello 3"
+
+# kiírás a kimenetre
+puts "Írok"
+
+# Változók
+x = 25 #=> 25
+x #=> 25
+
+# Értékadás az adott értékkel tér vissza
+# Ez azt jelenti, hogy használhatunk többszörös értékadást:
+
+x = y = 10 #=> 10
+x #=> 10
+y #=> 10
+
+# Konvencióból, snake_case változó neveket használj
+snake_case = true
+
+# Leíró változó neveket használj
+ut_a_projekt_gyokerehez = '/jo/nev/'
+ut = '/rossz/nev/'
+
+# A szimbólumok (objektumok)
+# A szimbólumok megváltoztathatatlan, újra felhasználható konstans,
+# mely belsőleg egész számként reprezentált. Sokszor sztring helyett használják,
+# hogy effektíven közvetítsünk konkrét, értelmes értékeket
+
+:fuggoben.class #=> Symbol
+
+statusz = :fuggoben
+
+statusz == :fuggoben #=> true
+
+statusz == 'fuggoben' #=> false
+
+statusz == :jovahagyott #=> false
+
+# Tömbök
+
+# Ez egy tömb
+tomb = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+
+# A tömmbök különböző tipusú dolgokat tartalmazhat
+
+[1, 'hello', false] #=> [1, "hello", false]
+
+# Tömbök indexelhetőek
+# Az elejéről
+tomb[0] #=> 1
+tomb[12] #=> nil
+
+# Akárcsak a számtani műveletek [var] hozzáférés
+# is csak szintaktikus cukor
+# a [] függvény hívására az objektumon
+tomb.[] 0 #=> 1
+tomb.[] 12 #=> nil
+
+# A végéről
+tomb[-1] #=> 5
+
+# Kezdőértékkel és hosszal
+tomb[2, 3] #=> [3, 4, 5]
+
+# Tömb megfordítása
+a=[1,2,3]
+a.reverse! #=> [3,2,1]
+
+# Vagy tartománnyal
+tomb[1..3] #=> [2, 3, 4]
+
+# Így adhatunk a tömbhöz
+tomb << 6 #=> [1, 2, 3, 4, 5, 6]
+# Vagy így
+tomb.push(6) #=> [1, 2, 3, 4, 5, 6]
+
+# Ellenőrízük, hogy a tömb tartalmaz egy elemet
+tomb.include?(1) #=> true
+
+# Hash-ek a ruby elsődleges szótárjai kulcs/érték párokkal
+# Hash-eket kapcsos zárójellel jelöljük
+hash = { 'szin' => 'zold', 'szam' => 5 }
+
+hash.keys #=> ['szin', 'szam']
+
+# Hash-ekben könnyen kreshetünk a kulcs segítségével:
+hash['szin'] #=> 'zold'
+hash['szam'] #=> 5
+
+# Nem létező kulcsra keresve nil-t kapunk:
+hash['nincs itt semmi'] #=> nil
+
+# Ruby 1.9-től, egy külnleges szintaxist is használhatunk a szimbólumot
+# használunk kulcsnak
+
+uj_hash = { defcon: 3, action: true }
+
+uj_hash.keys #=> [:defcon, :action]
+
+# Ellenőrizzük, hogy az adott kulcs és érték bene-e van a hash-ben
+uj_hash.has_key?(:defcon) #=> true
+uj_hash.has_value?(3) #=> true
+
+# Tip: A tömbök és hash-ek is felsorolhatóak
+# Sok közös függvényük van, akár az each, map, count, és több
+
+# Kontroll Struktúrák
+
+if true
+ 'ha állítás'
+elsif false
+ 'különben ha, opcionális'
+else
+ 'különben, szintén opcionális'
+end
+
+for szamlalo in 1..5
+ puts "iteracio #{szamlalo}"
+end
+#=> iteracio 1
+#=> iteracio 2
+#=> iteracio 3
+#=> iteracio 4
+#=> iteracio 5
+
+# HOWEVER, No-one uses for loops.
+# Instead you should use the "each" method and pass it a block.
+# A block is a bunch of code that you can pass to a method like "each".
+# It is analogous to lambdas, anonymous functions or closures in other
+# programming languages.
+#
+# The "each" method of a range runs the block once for each element of the range.
+# The block is passed a counter as a parameter.
+# Calling the "each" method with a block looks like this:
+
+(1..5).each do |counter|
+ puts "iteration #{counter}"
+end
+#=> iteration 1
+#=> iteration 2
+#=> iteration 3
+#=> iteration 4
+#=> iteration 5
+
+# You can also surround blocks in curly brackets:
+(1..5).each { |counter| puts "iteration #{counter}" }
+
+# The contents of data structures can also be iterated using each.
+array.each do |element|
+ puts "#{element} is part of the array"
+end
+hash.each do |key, value|
+ puts "#{key} is #{value}"
+end
+
+counter = 1
+while counter <= 5 do
+ puts "iteration #{counter}"
+ counter += 1
+end
+#=> iteration 1
+#=> iteration 2
+#=> iteration 3
+#=> iteration 4
+#=> iteration 5
+
+jegy = '4'
+
+case jegy
+when '5'
+ puts 'Kitünő'
+when '4'
+ puts 'Jó'
+when '3'
+ puts 'Közepes'
+when '2'
+ puts 'Elégsége'
+when '1'
+ puts 'Elégtelen'
+else
+ puts 'Alternatív értékelés, hm?'
+end
+#=> "Jó"
+
+# case-ek tartományokat is használhatnak
+jegy = 82
+case jegy
+when 90..100
+ puts 'Hurrá!'
+when 80...90
+ puts 'Jó munka'
+else
+ puts 'Megbuktál!'
+end
+#=> "Jó munka"
+
+# kivétel kezelés:
+begin
+ # kód ami kivételt dobhat
+ raise NoMemoryError, 'Megtelt a memória'
+rescue NoMemoryError => kivetel_valtozo
+ puts 'NoMemoryError-t dobott', kivetel_valtozo
+rescue RuntimeError => mas_kivetel_valtozo
+ puts 'RuntimeError dobott most'
+else
+ puts 'Ez akkor fut ha nem dob kivételt'
+ensure
+ puts 'Ez a kód mindenképpen lefut'
+end
+
+# Függvények
+
+def ketszeres(x)
+ x * 2
+end
+
+# Függvények (és egyébb blokkok) implicit viszatértnek az utolsó értékkel
+ketszeres(2) #=> 4
+
+# Zárójelezés opcionális, ha az eredmény félreérthetetlen
+ketszeres 3 #=> 6
+
+ketszeres ketszeres 3 #=> 12
+
+def osszeg(x, y)
+ x + y
+end
+
+# Függvény argumentumait vesszővel választjuk el.
+osszeg 3, 4 #=> 7
+
+osszeg osszeg(3, 4), 5 #=> 12
+
+# yield
+# Minden függvénynek van egy implicit, opcionális block paramétere
+# 'yield' kulcsszóval hívhatjuk
+
+def korulvesz
+ puts '{'
+ yield
+ puts '}'
+end
+
+korulvesz { puts 'hello world' }
+
+# {
+# hello world
+# }
+
+
+# Fuggvénynek átadhatunk blokkot
+# "&" jelöli az átadott blokk referenciáját
+def vendegek(&block)
+ block.call 'valami_argumentum'
+end
+
+# Argumentum lisát is átadhatunk, ami tömbé lesz konvertálva
+# Erre való a splat operátor ("*")
+def vendegek(*array)
+ array.each { |vendeg| puts vendeg }
+end
+
+# Osztályt a class kulcsszóval definiálhatunk
+class Ember
+
+ # Az osztály változó. Az osztály minden példánnyával megvan osztva
+ @@faj = 'H. sapiens'
+
+ # Alap inicializáló
+ def initialize(nev, kor = 0)
+ # Hozzárendeli az argumentumot a "nev" példány változóhoz
+ @nev = nev
+ # Ha nem adtunk meg kort akkor az alapértemezet értéket fogja használni
+ @kor = kor
+ end
+
+ # Alap setter függvény
+ def nev=(nev)
+ @nev = nev
+ end
+
+ # Alap getter függvény
+ def nev
+ @nev
+ end
+
+ # A fönti funkcionalítást az attr_accessor függvénnyel is elérhetjük
+ attr_accessor :nev
+
+ # Getter/setter függvények egyenként is kreálhatóak
+ attr_reader :nev
+ attr_writer :nev
+
+ # Az osztály függvények "self"-et hasznalnak, hogy megkülönböztessék magukat a
+ # példány függvényektől
+ # Az osztályn hívhatóak, nem a példányon
+ def self.mond(uzenet)
+ puts uzenet
+ end
+
+ def faj
+ @@faj
+ end
+end
+
+
+# Példányosítsuk az osztályt
+jim = Ember.new('Jim Halpert')
+
+dwight = Ember.new('Dwight K. Schrute')
+
+# Hívjunk meg pár függvényt
+jim.faj #=> "H. sapiens"
+jim.nev #=> "Jim Halpert"
+jim.nev = "Jim Halpert II" #=> "Jim Halpert II"
+jim.nev #=> "Jim Halpert II"
+dwight.faj #=> "H. sapiens"
+dwight.nev #=> "Dwight K. Schrute"
+
+# Hívjuk meg az osztály függvényt
+Ember.mond('Hi') #=> "Hi"
+
+# Változók szókjait az elnevezésük definiálja
+# $ kezdetű változók globálisak
+$var = "Én egy globális változó vagyok"
+defined? $var #=> "global-variable"
+
+# Változók amik @-al kezdődnek példány szkópjuk van
+@var = "Én egy példány változó vagyok"
+defined? @var #=> "instance-variable"
+
+# Változók amik @@-al kezdődnek példány szkópjuk van
+@@var = "Én egy osztály változó vagyok"
+defined? @@var #=> "class variable"
+
+# Változók amik nagy betűvel kezdődnek a konstansok
+Var = "Konstans vagyok"
+defined? Var #=> "constant"
+
+# Az osztály is objetum. Tehát az osztálynak lehet példány változója
+# Az osztályváltozón osztozik minden pédány és leszármazott
+
+# Ős osztály
+class Ember
+ @@foo = 0
+
+ def self.foo
+ @@foo
+ end
+
+ def self.foo=(ertek)
+ @@foo = ertek
+ end
+end
+
+# Leszarmazott osztály
+class Dolgozo < Ember
+end
+
+Ember.foo # 0
+Dolgozo.foo # 0
+
+Ember.foo = 2 # 2
+Dolgozo.foo # 2
+
+# Az osztálynak példány változóját nem látja az osztály leszármazottja.
+
+class Ember
+ @bar = 0
+
+ def self.bar
+ @bar
+ end
+
+ def self.bar=(ertek)
+ @bar = ertek
+ end
+end
+
+class Doctor < Ember
+end
+
+Ember.bar # 0
+Doctor.bar # nil
+
+module ModulePelda
+ def foo
+ 'foo'
+ end
+end
+
+# Modulok include-olása a fügvényeiket az osztály példányaihoz köti.
+# Modulok extend-elésa a fügvényeiket magához az osztályhoz köti.
+
+class Szemely
+ include ModulePelda
+end
+
+class Konyv
+ extend ModulePelda
+end
+
+Szemely.foo # => NoMethodError: undefined method `foo' for Szemely:Class
+Szemely.new.foo # => 'foo'
+Konyv.foo # => 'foo'
+Konyv.new.foo # => NoMethodError: undefined method `foo'
+
+# Callback-ek végrehajtódnak amikor include-olunk és extend-elünk egy modult
+
+module ConcernPelda
+ 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 Valami
+ include ConcernPelda
+end
+
+Valami.bar # => 'bar'
+Valami.qux # => NoMethodError: undefined method `qux'
+Valami.new.bar # => NoMethodError: undefined method `bar'
+Valami.new.qux # => 'qux'
+```
+
+## Egyéb források
+
+- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338)
+- [Official Documentation](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/) - A régebbi [ingyenes változat](http://ruby-doc.com/docs/ProgrammingRuby/) elérhető online.
+- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide)
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..fa039bfd 100644
--- a/hy.html.markdown
+++ b/hy.html.markdown
@@ -169,6 +169,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/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/xml-id.html.markdown b/id-id/xml-id.html.markdown
index c1e985aa..fedba711 100644
--- a/id-id/xml-id.html.markdown
+++ b/id-id/xml-id.html.markdown
@@ -1,23 +1,80 @@
---
language: xml
-filename: learnxml.xml
+filename: learnxml-id.xml
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 f892845f..af8823c4 100644
--- a/it-it/bash-it.html.markdown
+++ b/it-it/bash-it.html.markdown
@@ -13,13 +13,14 @@ contributors:
filename: LearnBash.sh
translators:
- ["Robert Margelli", "http://github.com/sinkswim/"]
+ - ["Tommaso Pifferi", "http://github.com/neslinesli93/"]
lang: it-it
---
Bash è il nome della shell di unix, la quale è stata distribuita anche come shell del sistema oprativo GNU e la shell di default su Linux e Mac OS X.
Quasi tutti gli esempi sottostanti possono fare parte di uno shell script o eseguiti direttamente nella shell.
-[Per saperne di piu'.](http://www.gnu.org/software/bash/manual/bashref.html)
+[Per saperne di più.](http://www.gnu.org/software/bash/manual/bashref.html)
```bash
#!/bin/bash
@@ -34,32 +35,34 @@ echo Ciao mondo!
echo 'Questa è la prima riga'; echo 'Questa è la seconda riga'
# Per dichiarare una variabile:
-VARIABILE="Una stringa"
+Variabile="Una stringa"
# Ma non così:
-VARIABILE = "Una stringa"
-# Bash stabilirà che VARIABILE è un comando da eseguire e darà un errore
+Variabile = "Una stringa"
+# Bash stabilirà che Variabile è un comando da eseguire e darà un errore
# perchè non esiste.
# Usare la variabile:
-echo $VARIABILE
-echo "$VARIABILE"
-echo '$VARIABILE'
+echo $Variabile
+echo "$Variabile"
+echo '$Variabile'
# Quando usi la variabile stessa - assegnala, esportala, oppure — scrivi
# il suo nome senza $. Se vuoi usare il valore della variabile, devi usare $.
# Nota che ' (singolo apice) non espande le variabili!
# Sostituzione di stringhe nelle variabili
-echo ${VARIABILE/Una/A}
+echo ${Variabile/Una/A}
# Questo sostituirà la prima occorrenza di "Una" con "La"
# Sottostringa di una variabile
-echo ${VARIABILE:0:7}
+Lunghezza=7
+echo ${Variabile:0:Lunghezza}
# Questo ritornerà solamente i primi 7 caratteri
# Valore di default per la variabile
-echo ${FOO:-"ValoreDiDefaultSeFOOMancaOÈ Vuoto"}
-# Questo funziona per null (FOO=), stringa vuota (FOO=""), zero (FOO=0) ritorna 0
+echo ${Foo:-"ValoreDiDefaultSeFooMancaOppureÈVuoto"}
+# Questo funziona per null (Foo=), stringa vuota (Foo=""), zero (Foo=0) ritorna 0
+# Nota: viene ritornato il valore di default, il contenuto della variabile pero' non cambia.
# Variabili builtin:
# Ci sono delle variabili builtin molto utili, come
@@ -71,31 +74,40 @@ echo "Argomenti dello script separati in variabili distinte: $1 $2..."
# Leggere un valore di input:
echo "Come ti chiami?"
-read NOME # Nota che non abbiamo dovuto dichiarare una nuova variabile
-echo Ciao, $NOME!
+read Nome # Nota che non abbiamo dovuto dichiarare una nuova variabile
+echo Ciao, $Nome!
# Classica struttura if:
# usa 'man test' per maggiori informazioni sulle condizionali
-if [ $NOME -ne $USER ]
+if [ $Nome -ne $USER ]
then
echo "Il tuo nome non è lo username"
else
echo "Il tuo nome è lo username"
fi
+# Nota: se $Name è vuoto, la condizione precedente viene interpretata come:
+if [ -ne $USER ]
+# che genera un errore di sintassi. Quindi il metodo sicuro per usare
+# variabili che possono contenere stringhe vuote è il seguente:
+if [ "$Name" -ne $USER ] ...
+# che viene interpretato come:
+if [ "" -ne $USER ] ...
+# e dunque funziona correttamente.
+
# C'è anche l'esecuzione condizionale
echo "Sempre eseguito" || echo "Eseguito solo se la prima condizione fallisce"
echo "Sempre eseguito" && echo "Eseguito solo se la prima condizione NON fallisce"
# Per usare && e || con l'if, c'è bisogno di piu' paia di parentesi quadre:
-if [ $NOME == "Steve" ] && [ $ETA -eq 15 ]
+if [ "$Nome" == "Steve" ] && [ "$Eta" -eq 15 ]
then
- echo "Questo verrà eseguito se $NOME è Steve E $ETA è 15."
+ echo "Questo verrà eseguito se $Nome è Steve E $Eta è 15."
fi
-if [ $NOME == "Daniya" ] || [ $NOME == "Zach" ]
+if [ "$Nome" == "Daniya" ] || [ "$Nome" == "Zach" ]
then
- echo "Questo verrà eseguito se $NAME è Daniya O Zach."
+ echo "Questo verrà eseguito se $Nome è Daniya O Zach."
fi
# Le espressioni sono nel seguente formato:
@@ -137,7 +149,7 @@ python hello.py > /dev/null 2>&1
# se invece vuoi appendere usa ">>":
python hello.py >> "output.out" 2>> "error.err"
-# Sovrascrivi output.txt, appendi a error.err, e conta le righe:
+# Sovrascrivi output.out, appendi a error.err, e conta le righe:
info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err
wc -l output.out error.err
@@ -145,7 +157,7 @@ wc -l output.out error.err
# vedi: man fd
echo <(echo "#ciaomondo")
-# Sovrascrivi output.txt con "#helloworld":
+# Sovrascrivi output.out con "#helloworld":
cat > output.out <(echo "#helloworld")
echo "#helloworld" > output.out
echo "#helloworld" | cat > output.out
@@ -164,7 +176,7 @@ echo "Ci sono $(ls | wc -l) oggetti qui."
echo "Ci sono `ls | wc -l` oggetti qui."
# Bash utilizza uno statemente case che funziona in maniera simile allo switch in Java e C++:
-case "$VARIABILE" in
+case "$Variabile" in
#Lista di pattern per le condizioni che vuoi soddisfare
0) echo "C'è uno zero.";;
1) echo "C'è un uno.";;
@@ -172,10 +184,10 @@ case "$VARIABILE" in
esac
# I cicli for iterano per ogni argomento fornito:
-# I contenuti di $VARIABILE sono stampati tre volte.
-for VARIABILE in {1..3}
+# I contenuti di $Variabile sono stampati tre volte.
+for Variabile in {1..3}
do
- echo "$VARIABILE"
+ echo "$Variabile"
done
# O scrivilo con il "ciclo for tradizionale":
@@ -186,16 +198,16 @@ done
# Possono essere usati anche per agire su file..
# Questo eseguirà il comando 'cat' su file1 e file2
-for VARIABILE in file1 file2
+for Variabile in file1 file2
do
- cat "$VARIABILE"
+ cat "$Variabile"
done
# ..o dall'output di un comando
# Questo eseguirà cat sull'output di ls.
-for OUTPUT in $(ls)
+for Output in $(ls)
do
- cat "$OUTPUT"
+ cat "$Output"
done
# while loop:
@@ -223,7 +235,7 @@ bar ()
}
# Per chiamare la funzione
-foo "Il mio nome è" $NOME
+foo "Il mio nome è" $Nome
# Ci sono un sacco di comandi utili che dovresti imparare:
# stampa le ultime 10 righe di file.txt
@@ -245,7 +257,7 @@ grep "^foo.*bar$" file.txt
grep -c "^foo.*bar$" file.txt
# se vuoi letteralmente cercare la stringa,
# e non la regex, usa fgrep (o grep -F)
-fgrep "^foo.*bar$" file.txt
+fgrep "^foo.*bar$" file.txt
# Leggi la documentazione dei builtin di bash con il builtin 'help' di bash:
diff --git a/it-it/bf-it.html.markdown b/it-it/bf-it.html.markdown
new file mode 100644
index 00000000..a79710d0
--- /dev/null
+++ b/it-it/bf-it.html.markdown
@@ -0,0 +1,92 @@
+---
+language: bf
+contributors:
+ - ["Prajit Ramachandran", "http://prajitr.github.io/"]
+ - ["Mathias Bynens", "http://mathiasbynens.be/"]
+translators:
+ - ["Ivan Sala", "http://slavni96.github.io/"]
+ - ["Christian Grasso", "http://chris54721.net"]
+lang: it-it
+---
+
+Brainfuck è un linguaggio di programmazione
+[Turing equivalente](https://it.wikipedia.org/wiki/Turing_equivalenza)
+estremamente minimale, composto da solo 8 comandi.
+
+Puoi provarlo nel tuo browser utilizzando
+[brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/).
+
+```
+
+Qualsiasi carattere diverso da "><+-.,[]" (escludendo gli apici)
+viene ignorato.
+Branfuck è caratterizzato da un array di 30,000 celle inizializzate a zero
+e da un puntatore che punta alla cella corrente.
+
+Vi sono otto comandi:
++ : Incrementa il valore della cella attuale di uno.
+- : Decrementa il valore della cella attuale di uno.
+> : Sposta il puntatore sulla cella seguente (sulla destra).
+< : Sposta il puntatore sulla cella precendete (sulla sinistra).
+. : Stampa il valore ASCII della cella corrente. (es. 65 = 'A')
+, : Legge un singolo carattere come input e lo salva nella cella corrente.
+[ : Se il valore della cella corrente è zero, prosegue fino alla ] corrispondente.
+ Altrimenti, passa alla prossima istruzione.
+] : Se il valore della cella corrente è zero, passa alla prossima istruzione.
+ Altrimenti, torna indietro fino alla [ corrispondente.
+
+[ e ] formano un ciclo while. Ovviamente dovranno essere bilanciati.
+(Ad ogni [ dovrà corrispondere una ])
+
+Ecco alcuni semplici esempi di programmi scritti in Brainfuck:
+
+++++++ [ > ++++++++++ < - ] > +++++ .
+
+Questo programma stampa in output la lettera 'A'. Prima di tutto, incrementa
+la cella #1 fino al valore 6. La cella #1 verrà utilizzata per il ciclo.
+Poi, entra nel ciclo ([) e si sposta alla cella #2. Incrementa la cella #2 10
+volte, torna alla cella #1, e decrementa quest'ultima.
+Il ciclo si ripete 6 volte (la cella #1 viene decrementata 6 volte prima di
+raggiungere lo 0, quindi prosegue oltre la corrispondente ]).
+
+A questo punto, siamo sulla cella #1, che ha valore 0, mentre la cella #2 ha
+valore 60. Ci spostiamo sulla cella #2, la incrementiamo per 5 volte, ottenendo
+il valore 65, quindi stampiamo il valore della cella #2.
+Il valore 65 equivale ad 'A' in ASCII, per cui viene stampato 'A' nel terminale.
+
+
+, [ > + < - ] > .
+
+Questo programma legge un carattere come input dall'utente, quindi salva il
+carattere nella cella #1. Dopodichè entra in un ciclo. Si sposta alla cella #2,
+incrementa quest'ultima, torna alla cella #1, e decrementa quest'ultima.
+Il ciclo continua fino a quando la cella #1 diventa 0, e quindi la cella #2
+avrà il valore iniziale della cella #1. Infine, visto che ci troviamo sulla
+cella #1 alla fine del ciclo, si sposta sulla cella #2 e stampa il valore in
+ASCII.
+
+Gli spazi nel codice sovrastante sono presenti solo a scopo di ottenere
+una maggiore leggibilità. Lo stesso programma poteva essere scritto senza spazi:
+
+,[>+<-]>.
+
+Proviamo, adesso, a capire cosa fa invece questo programma:
+
+,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >>
+
+Il programma legge 2 numeri come input dall'utente, e li moltiplica.
+
+Innanzitutto, legge in input i due numeri. Poi entra nel ciclo più esterno
+basandosi sulla cella #1. Quindi si sposta sulla cella #2, e inizia il ciclo
+più interno basandosi sul valore della cella #2, incrementando la cella #3.
+Arrivati a questo punto abbiamo un problema: alla fine del ciclo interno
+la cella #2 avrà valore 0. Ciò impedirà di eseguire nuovamente il ciclo interno.
+Per ovviare a questo problema, incrementiamo anche la cella #4, e copiamo il
+valore di quest'ultima nella cella #2.
+Il risultato sarà infine contenuto nella cella #3.
+```
+
+E questo è brainfuck. Non è così difficile, eh? Se vuoi, ora puoi scrivere per
+divertimento altri programmi in brainfuck, oppure scrivere un interprete
+brainfuck in un altro linguaggio. L'interprete è abbastanza semplice da
+implementare, ma se sei veramente masochista, prova ad implementare un interprete brainfuck... in brainfuck.
diff --git a/it-it/brainfuck-it.html.markdown b/it-it/brainfuck-it.html.markdown
deleted file mode 100644
index 4999d7e6..00000000
--- a/it-it/brainfuck-it.html.markdown
+++ /dev/null
@@ -1,101 +0,0 @@
----
-
-language: brainfuck
-contributors:
- - ["Prajit Ramachandran", "http://prajitr.github.io/"]
- - ["Mathias Bynens", "http://mathiasbynens.be/"]
-translators:
- - ["Ivan Sala", "http://slavni96.github.io/"]
-lang: it-it
-
----
-
-Brainfuck è un linguaggio di programmazione estremamente minimale,
-ma è ingrado di rappresentare completamente una macchina di turnig,
-e sfrutta solo 8 caratteri.
-[Per saperne di più](http://it.wikipedia.org/wiki/Brainfuck)
-
-```
-
-Qualsiasi carattere che non sia "><+-.,[]" (escludendo gli apici)
-viene ignorato.
-Branfuck è caratterizzato da un array (vettore) di 30,000 celle
-inizializzare a zero, e un puntatore che punta alla cella corrente.
-
-Vi sono solo otto comando:
-+ : Incrementa il valore della cella attuale di uno.
-- : Decrementa il valore della cella attuale di uno.
-> : Sposta il puntatore sulla cella seguente (prossima a destra).
-< : Sposta il puntatore sulla cella precendete (precedente a sinistra).
-. : Stampa il valore in ASCII della cella corrente. (es: 65 = 'A')
-, : Legge un singolo carattere come input per la cella corrente.
-[ : Se il valore della cella corrente è zero, conclude il ciclo
- andando alla sua corrispondente ].
- Altrimenti, passa alla prossima istruzione.
-] : Se il valore della cella corrente è zero, passa alla prossima istruzione.
- Altrimenti torna indetro fino alla [ corrispondente.
-
-[ e ] creano un loop (while). Ovviamente dovranno essere bilanciati.
-Per ogni [ dovrà corrispondere una ]
-
-Alcuni semplici esempi di programmi scritti in Brainfuck:
-
-++++++ [ > ++++++++++ < - ] > +++++ .
-
-Questo programma stampa in output la lettera 'A'. Priam incrementa
-la cella #1 fino a 6, Quindi la cella #1 viene usata per crare un ciclo.
-Poi, entra in un loop ([) e si sposta alla cella #2.
-Incrementa la cella #2 10 volte, e torna alla cella #1, e la decrementa.
-Questo avviene 6 volte (servono che la cella #1 venga decrementata 6 volte
-per raggiungere lo 0. Quindi passa alla corrispondente ] e prosegue).
-
-A questo punto, siamo sulla cella #1, che ha valore 0,
-la cella #2 ha valore 60 (6*10). Ci spostiamo sulla cella #2, incrementiamo
-per 5 volte, e otteniamo il valore 65, quindi stampaimo il valore della cella
-#2 (.).
-65 è 'A' in ASCII, quindi alla fine viene stampata 'A'.
-
-
-, [ > + < - ] > .
-
-Questo programma legge un carattere come input dall'utente,
-quindi salva il carattere dentro la cella #1.
-In seguito, incominca a ciclare.
-Si sposta alla cella #², e increementa il valore della cella (#2).
-Quindi torna alla cella #1, e decrementa il valore della cella (#1).
-Questo continua fino a quando la cella #²1 diventa 0, e quindi la cella #2
-avrà il valore iniziale della cella #1.
-Infine, visto che ci troviamo sulla cella #1 alla fine del ciclo, si sposta
-sulla cella #2 e stampa il valore in ASCII.
-
-Gli spazi nel codice sovrastante, sono presenti solo a scopo di ottenere
-una maggiore leggibilità, si poteva anche scrivere senza:
-
-,[>+<-]>.
-
-Proviamo, adesso, a capire cosa fa invece questo programma:
-
-,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >>
-
-Prende due numeri in input e quindi li moltiplica.
-
-Prima prende in input i due numeri (,>,<), quindi inizia un cilclo
-basandosi sulla cella #1.
-Quindi si sposta sulla cella #2, e inizia un altro ciclo condizionato
-dal valore della cella #2, incrementando la cella #3.
-Arrivati a questo punto abbiamo un problema: alla fine del ciclo interno
-la cella #2 ha valore 0. In questo caso, quando il ciclo esterno rifarà
-partire il ciclo interno, non funzionerà più perchè la cella #2 ha valore 0.
-Per ovviare a questo problema, oltre alla cella 3, incrementiamo anche la cella
-#4, e alla fine di ogni ciclo interno copiala il valore della cella #4
-nella cella #2, in modo che il ciclo interno
-possa essere eseguito una altra volta.
-Alla fine la cella #3 contiene il risultato.
-```
-
-E questo è brainfuck...Non è difficele, vero?
-Per divertimento adesso puoi scrivere i tuoi programmi in brainfuck,
-oppure puoi scrivere un interprete brainfuck in un altro linguaggio.
-L'interprete è abbastanza semplice da implementare, ma se sei veramente
-masochista prova ad implementare un interprete brainfuck in...
-brainfuck.
diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown
index e7e1d89e..92ebc165 100644
--- a/it-it/c++-it.html.markdown
+++ b/it-it/c++-it.html.markdown
@@ -4,6 +4,8 @@ filename: learncpp-it.cpp
contributors:
- ["Steven Basart", "http://github.com/xksteven"]
- ["Matt Kline", "https://github.com/mrkline"]
+ - ["Geoff Liu", "http://geoffliu.me"]
+ - ["Connor Waters", "http://github.com/connorwaters"]
translators:
- ["Robert Margelli", "http://github.com/sinkswim/"]
lang: it-it
@@ -54,11 +56,11 @@ int main(int argc, char** argv)
// Tuttavia, il C++ varia nei seguenti modi:
-// In C++, i caratteri come letterali sono da un byte.
-sizeof('c') == 1
+// In C++, i caratteri come letterali sono dei char.
+sizeof('c') == sizeof(char) == 1
-// In C, i caratteri come letterali sono della stessa dimensione degli interi.
-sizeof('c') == sizeof(10)
+// In C, i caratteri come letterali sono degli interi.
+sizeof('c') == sizeof(int)
// C++ ha prototipizzazione rigida
@@ -160,11 +162,14 @@ void foo()
int main()
{
- // Assume che tutto venga dal namespace "Secondo"
- // a meno che non venga dichiarato altrimenti.
+ // Include tutti i simboli del namespace Secondo nello scope attuale.
+ // Osserva che chiamare semplicemente foo() non va più bene perché è ambiguo:
+ // bisogna specificare se vogliamo chiamare foo definita nel namespace Secondo
+ // o foo definita nel livello principale del programma.
+
using namespace Secondo;
- foo(); // stampa "Questa è Secondo::foo"
+ Secondo::foo(); // stampa "Questa è Secondo::foo"
Primo::Annidato::foo(); // stampa "Questa è Primo::Annidato::foo"
::foo(); // stampa "Questa è foo globale"
}
@@ -244,12 +249,137 @@ cout << fooRef; // Stampa "Io sono foo. Ciao!"
// Non riassegna "fooRef". Questo è come scrivere "foo = bar", e
// foo == "Io sono bar"
// dopo questa riga.
+cout << &fooRef << endl; // Stampa l'indirizzo di foo
fooRef = bar;
+cout << &fooRef << endl; // Stampa lo stesso l'indirizzo di foo
+cout << fooRef; // Stampa "Io sono bar"
+
+// L'indirizzo di fooRef rimane lo stesso, ovvero si riferisce ancora a foo.
+
const string& barRef = bar; // Crea un riferimento const a bar.
// Come in C, i valori const (i puntatori e i riferimenti) non possono essere modificati.
barRef += ". Ciao!"; // Errore, i riferimenti const non possono essere modificati.
+// Facciamo un piccolo excursus: prima di approfondire ancora i riferimenti, è necessario
+// introdurre il concetto di oggetto temporaneo. Supponiamo di avere il seguente codice:
+string tempObjectFun() { ... }
+string retVal = tempObjectFun();
+
+// Nella seconda riga si ha che:
+// - un oggetto di tipo stringa viene ritornato da tempObjectFun
+// - viene costruita una nuova stringa, utilizzando l'oggetto ritornato come
+// argomento per il costruttore
+// - l'oggetto ritornato da tempObjectFun viene distrutto
+// L'oggetto ritornato da tempObjectFun viene detto oggetto temporaneo.
+// Un oggetto temporaneo viene creato quando una funzione ritorna un oggetto, e viene
+// distrutto quando l'espressione che lo racchiude termina la sua esecuzione - questo
+// comportamento viene definito dallo standard, ma i compilatori possono modificarlo
+// a piacere. Cerca su google "return value optimization" se vuoi approfondire.
+// Dunque nel seguente codice:
+foo(bar(tempObjectFun()))
+
+// dando per scontato che foo e bar esistano, l'oggetto ritornato da tempObjectFun
+// è passato a bar ed è distrutto prima dell'invocazione di foo.
+
+// Tornando ai riferimenti, c'è un'eccezione a quanto appena detto.
+// Infatti un oggetto temporaneo "viene distrutto quando l'espressione
+// che lo racchiude termina la sua esecuzione", tranne quando è legato ad un
+// riferimento di tipo const. In tal caso la sua vita viene estesa per tutto
+// lo scope attuale:
+
+void constReferenceTempObjectFun() {
+ // constRef riceve l'oggetto temporaneo, che non viene distrutto fino
+ // alla fine di questa funzione.
+ const string& constRef = tempObjectFun();
+ ...
+}
+
+// Un altro tipo di riferimento introdotto nel C++11 è specifico per gli
+// oggetti temporanei. Non puoi dichiarare una variabile di quel tipo, ma
+// ha la precedenza nella risoluzione degli overload:
+
+void someFun(string& s) { ... } // Riferimento normale
+void someFun(string&& s) { ... } // Riferimento ad un oggetto temporaneo
+
+string foo;
+someFun(foo); // Chiama la versione con il riferimento normale
+someFun(tempObjectFun()); // Chiama la versione con il riferimento temporaneo
+
+// Ad esempio potrai vedere questi due costruttori per std::basic_string:
+basic_string(const basic_string& other);
+basic_string(basic_string&& other);
+
+// L'idea è che se noi costruiamo una nuova stringa a partire da un oggetto temporaneo
+// (che in ogni caso verrà distrutto), possiamo avere un costruttore più efficiente
+// che in un certo senso "recupera" parti di quella stringa temporanea.
+// Ci si riferisce a questo concetto come "move semantics".
+
+/////////////////////
+// Enum
+/////////////////////
+
+// Gli enum sono un modo per assegnare un valore ad una costante, e sono
+// principalmente usati per rendere il codice più leggibile.
+enum ETipiMacchine
+{
+ AlfaRomeo,
+ Ferrari,
+ SUV,
+ Panda
+};
+
+ETipiMacchine GetPreferredCarType()
+{
+ return ETipiMacchine::Ferrari;
+}
+
+// Dal C++11 in poi c'è un modo molto semplice per assegnare un tipo ad un enum,
+// che può essere utile per la serializzazione dei dati o per convertire gli enum
+// tra il tipo desiderato e le rispettive costanti.
+enum ETipiMacchine : uint8_t
+{
+ AlfaRomeo, // 0
+ Ferrari, // 1
+ SUV = 254, // 254
+ Ibrida // 255
+};
+
+void WriteByteToFile(uint8_t InputValue)
+{
+ // Serializza InputValue in un file
+}
+
+void WritePreferredCarTypeToFile(ETipiMacchine InputCarType)
+{
+ // L'enum viene implicitamente convertito ad un uint8_t poiché
+ // è stato dichiarato come tale
+ WriteByteToFile(InputCarType);
+}
+
+// D'altro canto potresti voler evitare che un enum venga accidentalmente convertito
+// in un intero o in un altro tipo, quindi è possibile create una classe enum che
+// impedisce la conversione implicita.
+enum class ETipiMacchine : uint8_t
+{
+ AlfaRomeo, // 0
+ Ferrari, // 1
+ SUV = 254, // 254
+ Ibrida // 255
+};
+
+void WriteByteToFile(uint8_t InputValue)
+{
+ // Serializza InputValue in un file
+}
+
+void WritePreferredCarTypeToFile(ETipiMacchine InputCarType)
+{
+ // Il compilatore darà errore anche se ETipiMacchine è un uint8_t: questo
+ // perchè abbiamo dichiarato l'enum come "enum class"!
+ WriteByteToFile(InputCarType);
+}
+
//////////////////////////////////////////////////
// Classi e programmazione orientata agli oggetti
/////////////////////////////////////////////////
@@ -296,13 +426,16 @@ public:
// Questi sono chiamati quando un oggetto è rimosso o esce dalla visibilità.
// Questo permette paradigmi potenti come il RAII
// (vedi sotto)
- // I distruttori devono essere virtual per permettere a classi di essere derivate da questa.
+ // I distruttori devono essere virtual per permettere a classi di essere
+ // derivate da questa; altrimenti, il distruttore della classe derivata
+ // non viene chiamato se l'oggetto viene distrutto tramite un riferimento alla
+ // classe da cui ha ereditato o tramite un puntatore.
virtual ~Dog();
}; // Un punto e virgola deve seguire la definizione della funzione
// Le funzioni membro di una classe sono generalmente implementate in files .cpp .
-void Cane::Cane()
+Cane::Cane()
{
std::cout << "Un cane è stato costruito\n";
}
@@ -325,7 +458,7 @@ void Cane::print() const
std::cout << "Il cane è " << nome << " e pesa " << peso << "kg\n";
}
-void Cane::~Cane()
+Cane::~Cane()
{
cout << "Ciao ciao " << nome << "\n";
}
@@ -340,10 +473,12 @@ int main() {
// Ereditarietà:
-// Questa classe eredita tutto ciò che è public e protected dalla classe Cane
+// Questa classe eredita tutto ciò che è public e protected dalla classe Cane,
+// ma anche ciò che privato: tuttavia non potrà accedere direttamente a membri/metodi
+// privati se non c'è un metodo pubblico o privato che permetta di farlo.
class MioCane : public Cane {
- void impostaProprietario(const std::string& proprietarioCane)
+ void impostaProprietario(const std::string& proprietarioCane);
// Sovrascrivi il comportamento della funzione print per tutti i MioCane. Vedi
// http://it.wikipedia.org/wiki/Polimorfismo_%28informatica%29
@@ -447,6 +582,7 @@ int main () {
// definire una classe o una funzione che prende un parametro di un dato tipo:
template<class T>
class Box {
+public:
// In questa classe, T può essere usato come qualsiasi tipo.
void inserisci(const T&) { ... }
};
@@ -519,19 +655,23 @@ printMessage<10>(); // Stampa "Impara il C++ più velocemente in soli 10 minuti
// (vedi http://en.cppreference.com/w/cpp/error/exception)
// ma ogni tipo può essere lanciato come eccezione
#include <exception>
+#include <stdexcept>
// Tutte le eccezioni lanciate all'interno del blocco _try_ possono essere catturate dai successivi
// handlers _catch_.
try {
// Non allocare eccezioni nello heap usando _new_.
- throw std::exception("È avvenuto un problema");
+ throw std::runtime_error("C'è stato un problema.");
}
+
// Cattura le eccezioni come riferimenti const se sono oggetti
catch (const std::exception& ex)
{
- std::cout << ex.what();
+ std::cout << ex.what();
+}
+
// Cattura ogni eccezioni non catturata dal blocco _catch_ precedente
-} catch (...)
+catch (...)
{
std::cout << "Catturata un'eccezione sconosciuta";
throw; // Rilancia l'eccezione
@@ -541,7 +681,7 @@ catch (const std::exception& ex)
// RAII
///////
-// RAII sta per Resource Allocation Is Initialization.
+// RAII sta per "Resource Allocation Is Initialization".
// Spesso viene considerato come il più potente paradigma in C++.
// È un concetto semplice: un costruttore di un oggetto
// acquisisce le risorse di tale oggetto ed il distruttore le rilascia.
@@ -563,9 +703,9 @@ void faiQualcosaConUnFile(const char* nomefile)
// Sfortunatamente, le cose vengono complicate dalla gestione degli errori.
// Supponiamo che fopen fallisca, e che faiQualcosaConUnFile e
// faiQualcosAltroConEsso ritornano codici d'errore se falliscono.
-// (Le eccezioni sono la maniera preferita per gestire i fallimenti,
-// ma alcuni programmatori, specialmente quelli con un passato in C,
-// non sono d'accordo con l'utilità delle eccezioni).
+// (Le eccezioni sono la maniera preferita per gestire i fallimenti,
+// ma alcuni programmatori, specialmente quelli con un passato in C,
+// non sono d'accordo con l'utilità delle eccezioni).
// Adesso dobbiamo verificare che ogni chiamata per eventuali fallimenti e chiudere il gestore di file
// se un problema è avvenuto.
bool faiQualcosaConUnFile(const char* nomefile)
@@ -615,7 +755,7 @@ void faiQualcosaConUnFile(const char* nomefile)
{
FILE* fh = fopen(nomefile, "r"); // Apre il file in modalità lettura
if (fh == nullptr)
- throw std::exception("Non è stato possibile aprire il file.").
+ throw std::runtime_error("Errore nell'apertura del file.");
try {
faiQualcosaConIlFile(fh);
@@ -678,26 +818,29 @@ class Foo {
virtual void bar();
};
class FooSub : public Foo {
- virtual void bar(); // sovrascrive Foo::bar!
+ virtual void bar(); // Sovrascrive Foo::bar!
};
// 0 == false == NULL (la maggior parte delle volte)!
bool* pt = new bool;
-*pt = 0; // Setta il valore puntato da 'pt' come falso.
+*pt = 0; // Setta il valore puntato da 'pt' come falso.
pt = 0; // Setta 'pt' al puntatore null. Entrambe le righe vengono compilate senza warnings.
// nullptr dovrebbe risolvere alcune di quei problemi:
int* pt2 = new int;
-*pt2 = nullptr; // Non compila
+*pt2 = nullptr; // Non compila
pt2 = nullptr; // Setta pt2 a null.
-// Ma in qualche modo il tipo 'bool' è una eccezione (questo è per rendere compilabile `if (ptr)`.
-*pt = nullptr; // Questo compila, anche se '*pt' è un bool!
+// C'è un'eccezione per i bool.
+// Questo permette di testare un puntatore a null con if(!ptr), ma
+// come conseguenza non puoi assegnare nullptr a un bool direttamente!
+*pt = nullptr; // Questo compila, anche se '*pt' è un bool!
// '=' != '=' != '='!
-// Chiama Foo::Foo(const Foo&) o qualche variante del costruttore di copia.
+// Chiama Foo::Foo(const Foo&) o qualche variante (vedi "move semantics")
+// del costruttore di copia.
Foo f2;
Foo f1 = f2;
@@ -711,6 +854,22 @@ Foo f1 = fooSub;
Foo f1;
f1 = f2;
+
+// Come deallocare realmente le risorse all'interno di un vettore:
+class Foo { ... };
+vector<Foo> v;
+for (int i = 0; i < 10; ++i)
+ v.push_back(Foo());
+
+// La riga seguente riduce la dimensione di v a 0, ma il distruttore non
+// viene chiamato e dunque le risorse non sono deallocate!
+v.empty();
+v.push_back(Foo()); // Il nuovo valore viene copiato nel primo Foo che abbiamo inserito
+
+// Distrugge realmente tutti i valori dentro v. Vedi la sezione riguardante gli
+// oggetti temporanei per capire come mai funziona così.
+v.swap(vector<Foo>());
+
```
Letture consigliate:
diff --git a/it-it/coffeescript-it.html.markdown b/it-it/coffeescript-it.html.markdown
index 16eb9bd4..d30ba819 100644
--- a/it-it/coffeescript-it.html.markdown
+++ b/it-it/coffeescript-it.html.markdown
@@ -59,34 +59,34 @@ matematica =
quadrato: quadrato
cubo: (x) -> x * quadrato x
#=> var matematica = {
-# "radice": Math.sqrt,
-# "quadrato": quadrato,
-# "cubo": function(x) { return x * quadrato(x); }
-#}
+# "radice": Math.sqrt,
+# "quadrato": quadrato,
+# "cubo": function(x) { return x * quadrato(x); }
+# }
# Splats:
gara = (vincitore, partecipanti...) ->
print vincitore, partecipanti
#=>gara = function() {
-# var partecipanti, vincitore;
-# vincitore = arguments[0], partecipanti = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
-# return print(vincitore, partecipanti);
-#};
+# var partecipanti, vincitore;
+# vincitore = arguments[0], partecipanti = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
+# return print(vincitore, partecipanti);
+# };
# Esistenza:
alert "Lo sapevo!" if elvis?
#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Lo sapevo!"); }
# Comprensione degli Array:
-cubi = (matematica.cubo num for num in lista)
+cubi = (matematica.cubo num for num in lista)
#=>cubi = (function() {
-# var _i, _len, _results;
-# _results = [];
-# for (_i = 0, _len = lista.length; _i < _len; _i++) {
-# num = lista[_i];
-# _results.push(matematica.cubo(num));
-# }
-# return _results;
+# var _i, _len, _results;
+# _results = [];
+# for (_i = 0, _len = lista.length; _i < _len; _i++) {
+# num = lista[_i];
+# _results.push(matematica.cubo(num));
+# }
+# return _results;
# })();
cibi = ['broccoli', 'spinaci', 'cioccolato']
diff --git a/it-it/elixir-it.html.markdown b/it-it/elixir-it.html.markdown
index f5d0c172..60301b1a 100644
--- a/it-it/elixir-it.html.markdown
+++ b/it-it/elixir-it.html.markdown
@@ -4,6 +4,8 @@ contributors:
- ["Luca 'Kino' Maroni", "https://github.com/kino90"]
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
+translators:
+ - ["Tommaso Pifferi","http://github.com/neslinesli93"]
filename: learnelixir-it.ex
lang: it-it
---
@@ -379,6 +381,12 @@ spawn(f) #=> #PID<0.40.0>
# Per passare messaggi si usa l'operatore `send`.
# Perché tutto questo sia utile dobbiamo essere capaci di ricevere messaggi,
# oltre ad inviarli. Questo è realizzabile con `receive`:
+
+# Il blocco `receive do` viene usato per mettersi in ascolto di messaggi
+# ed elaborarli quando vengono ricevuti. Un blocco `receive do` elabora
+# un solo messaggio ricevuto: per fare elaborazione multipla di messaggi,
+# una funzione con un blocco `receive do` al suo intero dovrà chiamare
+# ricorsivamente sé stessa per entrare di nuovo nel blocco `receive do`.
defmodule Geometria do
def calcolo_area do
receive do
@@ -394,6 +402,8 @@ end
# Compila il modulo e crea un processo che esegue `calcolo_area` nella shell
pid = spawn(fn -> Geometria.calcolo_area() end) #=> #PID<0.40.0>
+# Alternativamente
+pid = spawn(Geometria, :calcolo_area, [])
# Invia un messaggio a `pid` che farà match su un pattern nel blocco in receive
send pid, {:rettangolo, 2, 3}
diff --git a/it-it/java-it.html.markdown b/it-it/java-it.html.markdown
index 6eabd61f..54602cff 100644
--- a/it-it/java-it.html.markdown
+++ b/it-it/java-it.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Madison Dickson", "http://github.com/mix3d"]
translators:
- ["Ivan Sala","http://github.com/slavni96"]
+ - ["Tommaso Pifferi","http://github.com/neslinesli93"]
lang: it-it
---
@@ -31,9 +32,9 @@ import java.security.*;
// Ogni file .java contiene una classe pubblica, con lo stesso nome del file
public class LearnJava {
- // Un programma deve avere un metodo main come punto di partenza
- // Ma si possono creare anche file senza main, che però per essere usati
- // devono essere richiamati da altri file.
+ // Un programma deve avere un metodo main come punto di partenza.
+ // Tuttavia si possono creare anche file senza main, che però
+ // per essere usati devono essere richiamati da altri file.
public static void main (String[] args) {
// Per stampare a schermo si usa System.out.println
@@ -47,88 +48,157 @@ public class LearnJava {
System.out.print("Ciao ");
System.out.print("Mondo ");
+ // Per stampare del testo formattato, si puo' usare System.out.printf
+ System.out.printf("pi greco = %.5f", Math.PI); // => pi greco = 3.14159
///////////////////////////////////////
- // Tipi e Variabili
+ // Variabili
///////////////////////////////////////
- // Si dichiara una variabile usando <tipo> <nome>
- // Byte - variabile intera da 8 bit con segno
+
+ /*
+ * Dichiarazione delle Variabili
+ */
+ // Per dichiarare una variabile basta fare <tipoDato> <nomeVariabile>
+ int fooInt;
+ // Per dichiarare piu' di una variabile dello lo stesso tipo si usa:
+ // <tipoDato> <nomeVariabile1>, <nomeVariabile2>, <nomeVariabile3>
+ int fooInt1, fooInt2, fooInt3;
+
+ /*
+ * Inizializzazione delle Variabili
+ */
+
+ // Per inizializzare una variabile si usa
+ // <tipoDato> <nomeVariabile> = <valore>
+ int fooInt = 1;
+ // Per inizializzare piu' di una variabile dello lo stesso tipo
+ // si usa <tipoDato> <nomeVariabile1>, <nomeVariabile2>, <nomeVariabile3> = <valore>
+ int fooInt1, fooInt2, fooInt3;
+ fooInt1 = fooInt2 = fooInt3 = 1;
+
+ /*
+ * Tipi di Variabili
+ */
+ // Byte - intero con segno a 8 bit (in complemento a 2)
// (-128 <= byte <= 127)
byte fooByte = 100;
- // Short - variabile intera da 18 bit con segno
+ // Short - intero con segno a 16 bit (in complemento a 2)
// (-32,768 <= short <= 32,767)
short fooShort = 10000;
- // Integer - variabile intera da 32 bit con segno
+ // Integer - intero con segno a 32 bit (in complemento a 2)
// (-2,147,483,648 <= int <= 2,147,483,647)
int fooInt = 1;
- // Long - variabile da 64 bit intera con segno
+ // Long - intero con segno a 64 bit (in complemento a 2)
// (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
long fooLong = 100000L;
- // L viene usato per specificare che il valore dalla variabile
- // e' di tipo "Long", qualsiasi variabile che non viene contrassegnata
- // e' trattata di base come un intero.
+ // L viene usato per indicare che il valore e' di tipo Long;
+ // altrimenti il valore viene considerato come intero.
- // Nota: Java non dispone di variabili senza segno
+ // Nota: Java non dispone di interi senza segno.
- // Float - variabile piu' precisa, con virgola [numeri reali]
- // di grandezza 32 bit
+ // Float - Numero in virgola mobile a 32 bit con precisione singola (IEEE 754)
+ // 2^-149 <= float <= (2-2^-23) * 2^127
float fooFloat = 234.5f;
- // f e' usato per specificare che la variabile e'' di tipo "float"
- // altrimenti di default viene trattata come un "dobule"
+ // f o F indicano the la variabile e' di tipo float;
+ // altrimenti il valore viene considerato come double.
- // Double - ancora piu' precisione la si puo' ottenere con una variabile
- // Double, con granzezza di 64 bit.
+ // Double - Numero in virgola mobile a 64 bit con precisione doppia (IEEE 754)
+ // 2^-1074 <= x <= (2-2^-52) * 2^1023
double fooDouble = 123.4;
- // Boolean - vero & falso
+ // Boolean - Puo' assumere il valore vero (true) o falso (false)
boolean fooBoolean = true;
boolean barBoolean = false;
- // Char - un singolo carattere con grandezza 16 bit
+ // Char - Un singolo carattere Unicode a 16-bit
char fooChar = 'A';
- // final - Costanti, non possono essere riassegnate ad un altro oggetto
- final int ORE_LAVORATIVE_DI_UNA_SETTIMANA = 9001;
-
- // String - Stringhe, array di caratteri
- String fooString = "Ecco una stringa!";
-
- // \n e' un carattere speciale che permette di andare a capo.
- String barString = "Andare a capo?\nNessun problema!";
- // \t e' un carattere speciale che permette di aggiungere un 'Tab'
- String bazString = "Vuoi inserire tab?\tNessun problema";
+ // Le variabili precedute da final possono essere inizializzate una volta sola,
+ final int HOURS_I_WORK_PER_WEEK = 9001;
+ // pero' e' possibile dichiararle e poi inizializzarle in un secondo momento.
+ final double E;
+ E = 2.71828;
+
+
+ // BigInteger - Interi a precisione arbitraria
+ //
+ // BigInteger e' un tipo di dato che permette ai programmatori di
+ // gestire interi piu' grandi di 64 bit. Internamente, le variabili
+ // di tipo BigInteger vengono memorizzate come un vettore di byte e
+ // vengono manipolate usando funzioni dentro la classe BigInteger.
+ //
+ // Una variabile di tipo BigInteger puo' essere inizializzata usando
+ // un array di byte oppure una stringa.
+
+ BigInteger fooBigInteger = new BigDecimal(fooByteArray);
+
+ // BigDecimal - Numero con segno, immutabile, a precisione arbitraria
+ //
+ // Una variabile di tipo BigDecimal e' composta da due parti: un intero
+ // a precisione arbitraria detto 'non scalato', e un intero a 32 bit
+ // che rappresenta la 'scala', ovvero la potenza di 10 con cui
+ // moltiplicare l'intero non scalato.
+ //
+ // I BigDecimal permettono un controllo completo sull'arrotondamento
+ // dei numeri. Essi sono molto usati in ambito finanziario, nella
+ // gestione delle valute, e in ogni altro posto in cui serve
+ // precisione esatta.
+ //
+ // Le variabili di tipo BigDecimal possono essere inizializzate con un
+ // int, long, double o String, oppure con un intero non scalato
+ // (di tipo BigInteger) e una scala (int).
+
+ BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt);
+
+
+
+ // Stringhe
+ String fooString = "Questa e' la mia stringa!";
+
+ // \n e' un carattere di escape che rappresenta l'andare a capo
+ String barString = "Stampare su una nuova riga?\nNessun problema!";
+ // \t e' un carattere di escape che aggiunge un tab
+ String bazString = "Vuoi aggiungere un tab?\tNessun problema!";
System.out.println(fooString);
System.out.println(barString);
System.out.println(bazString);
- // Vettori [array]
- //La lunghezza del vettore deve essere decisa quando viene istanziato
- //Si puo' dichiarare come segue:
- //<tipodato> [] <nomevariabile> = new <tipodato>[<grandezza vettore>];
- //<tipodato> <nomevariabile>[] = new <tipodato>[<grandezza vettore>];
- int [] intArray = new int[10];
- String [] stringArray = new String[1];
- boolean boolArray [] = new boolean[100];
-
- // Un altro modo per dichiarare & inizializzare un vettore
- int [] y = {9000, 1000, 1337};
- String nomi [] = {"Andrea", "Bob", "Pippo", "Susan"};
+ // Vettori
+ // La dimensione di un array deve essere decisa in fase di
+ // istanziazione. Per dichiarare un array si puo' fare in due modi:
+ // <tipoDato>[] <nomeVariabile> = new <tipoDato>[<dimensioneArray>];
+ // <tipoDato> <nomeVariabile>[] = new <tipoDato>[<dimensioneArray>];
+ int[] intArray = new int[10];
+ String[] stringArray = new String[1];
+ boolean boolArray[] = new boolean[100];
+
+ // Un altro modo per dichiarare ed insieme inizializzare un vettore.
+ int[] y = {9000, 1000, 1337};
+ String names[] = {"Gianni", "Anna", "Luca", "Cristina"};
boolean bools[] = new boolean[] {true, false, false};
-
- // I vettori vengono indicizzati a parire dallo 0
+
+ // Per accedere ad un elemento di un vettore
System.out.println("intArray @ 0: " + intArray[0]);
- // e' possibile un accesso diretto ad un elemento
+ // I vettori non sono immutabili (ma la loro dimensione si!)
+ // e gli indici partono da 0.
intArray[1] = 1;
System.out.println("intArray @ 1: " + intArray[1]); // => 1
- // Altro da vedere:
- // Liste di array - come i vettori ma piu' funzionali
- // e la loro grandezza puo' variare in corso di esecuzione
- // Liste concatenate di memoria
+ // Ci sono altri tipo di dato interessanti.
+ // ArrayList - Simili ai vettori, pero' offrono altre funzionalita',
+ // e la loro dimensione puo' essere modificata.
+ // LinkedList - Si tratta di una lista linkata doppia, e come tale
+ // implementa tutte le operazioni del caso.
+ // Map - Un insieme di oggetti che fa corrispondere delle chiavi
+ // a dei valori. Non permette l'inserimento di chiavi uguali.
+ // HashMap - Questa classe usa una tabella di hash per implementare
+ // l'interfaccia di tipo Map. Questo permette di effettuare
+ // operazioni basilari, come inserimento e cancellazione,
+ // in tempo costante anche su insiemi molto grandi.
///////////////////////////////////////
// Operatori
diff --git a/it-it/json-it.html.markdown b/it-it/json-it.html.markdown
index 0c401753..379bad73 100644
--- a/it-it/json-it.html.markdown
+++ b/it-it/json-it.html.markdown
@@ -1,29 +1,36 @@
---
-
language: json
contributors:
- - ["Anna Harren", "https://github.com/iirelu"]
- - ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["Anna Harren", "https://github.com/iirelu"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["himanshu", "https://github.com/himanshu81494"]
translators:
- ["Robert Margelli", "http://github.com/sinkswim/"]
+ - ["Christian Grasso", "http://chris54721.net"]
lang: it-it
-
---
-Dato che JSON è un formato per lo scambio di dati estremamente semplice, questo sarà con molta probabilità
-il più semplice Learn X in Y Minutes.
+JSON è un formato per l'interscambio di dati estremamente semplice, per cui questo sarà
+con molta probabilità il più semplice Learn X in Y Minutes.
Nella sua forma più pura JSON non ha commenti, ma molti parser accettano
commenti in stile C (//, /\* \*/). Per lo scopo prefissato, tuttavia, tutto sarà
100% JSON valido. Fortunatamente, si spiega da sè.
+I tipi supportati da JSON comprendono: numeri, stringhe, boolean, array, oggetti e null.
+I browser supportati sono: Firefox (Mozilla) 3.5+, Internet Explorer 8+, Google Chrome,
+Opera 10+, Safari 4+.
+I file JSON sono salvati nel formato ".json". Il MIME type per documenti JSON è
+"application/json". Gli svantaggi del JSON includono l'assenza di una definizione dei tipi
+e di una sorta di [DTD](https://it.wikipedia.org/wiki/Document_Type_Definition).
+
```json
{
"chiave": "valore",
"chiavi": "devono sempre essere racchiuse tra doppi apici",
"numeri": 0,
- "stringhe": "Ciaø, møndø. Tutti gli unicode sono permessi, assieme con l \"escaping\".",
+ "stringhe": "Ciaø, møndø. Tutti i caratteri Unicode sono permessi, insieme all'\"escaping\".",
"ha booleani?": true,
"il nulla": null,
@@ -52,8 +59,8 @@ commenti in stile C (//, /\* \*/). Per lo scopo prefissato, tuttavia, tutto sar
],
"stile alternativo": {
- "commento": "Guarda quà!"
- , "posizione della virgola": "non conta - fintantochè è prima del valore, allora è valida"
+ "commento": "Guarda qua!"
+ , "posizione della virgola": "non conta - se è prima della chiave successiva, allora è valida"
, "un altro commento": "che bello"
},
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/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 fc7948d6..50629ce1 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -5,6 +5,9 @@ contributors:
- ["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"]
filename: LearnJava.java
---
@@ -31,7 +34,7 @@ import java.security.*;
// the file.
public class LearnJava {
- // A program 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.
@@ -45,6 +48,8 @@ public class LearnJava {
System.out.print("Hello ");
System.out.print("World");
+ // Use System.out.printf() for easy formatted printing.
+ System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159
///////////////////////////////////////
// Variables
@@ -92,11 +97,13 @@ public class LearnJava {
// Note: Java has no unsigned types.
// Float - Single-precision 32-bit IEEE 754 Floating Point
+ // 2^-149 <= float <= (2-2^-23) * 2^127
float fooFloat = 234.5f;
- // f is used to denote that this variable value is of type float;
+ // f or F is used to denote that this variable value is of type float;
// otherwise it is treated as double.
// Double - Double-precision 64-bit IEEE 754 Floating Point
+ // 2^-1074 <= x <= (2-2^-52) * 2^1023
double fooDouble = 123.4;
// Boolean - true & false
@@ -106,8 +113,44 @@ public class LearnJava {
// Char - A single 16-bit Unicode character
char fooChar = 'A';
- // final variables can't be reassigned to another object.
+ // final variables can't be reassigned to another object,
final int HOURS_I_WORK_PER_WEEK = 9001;
+ // but they can be initialized later.
+ 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 fooBigInteger = new BigInteger(fooByteArray);
+
+
+ // BigDecimal - Immutable, arbitrary-precision signed decimal number
+ //
+ // A BigDecimal takes two parts: an arbitrary precision integer
+ // unscaled value and a 32-bit integer scale
+ //
+ // BigDecimal allows the programmer complete control over decimal
+ // rounding. It is recommended to use BigDecimal with currency values
+ // and where exact decimal precision is required.
+ //
+ // 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!";
@@ -132,7 +175,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]);
@@ -147,8 +190,12 @@ public class LearnJava {
// LinkedLists - Implementation of doubly-linked list. All of the
// operations perform as could be expected for a
// doubly-linked list.
- // Maps - A set of objects that maps keys to values. A map cannot
- // contain duplicate keys; each key can map to at most one value.
+ // Maps - A set of objects that map keys to values. Map is
+ // an interface and therefore cannot be instantiated.
+ // The type of keys and values contained in a Map must
+ // be specified upon instantiation of the implementing
+ // class. Each key may map to only one corresponding value,
+ // and each key may appear only once (no duplicates).
// HashMaps - This class uses a hashtable to implement the Map
// interface. This allows the execution time of basic
// operations, such as get and insert element, to remain
@@ -165,7 +212,8 @@ public class LearnJava {
System.out.println("1+2 = " + (i1 + i2)); // => 3
System.out.println("2-1 = " + (i2 - i1)); // => 1
System.out.println("2*1 = " + (i2 * i1)); // => 2
- System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down)
+ System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns an int)
+ System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5
// Modulo
System.out.println("11%3 = "+(11 % 3)); // => 2
@@ -178,12 +226,17 @@ public class LearnJava {
System.out.println("2 <= 2? " + (2 <= 2)); // => true
System.out.println("2 >= 2? " + (2 >= 2)); // => true
+ // Boolean operators
+ 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
+
// Bitwise operators!
/*
~ Unary bitwise complement
<< Signed left shift
- >> Signed right shift
- >>> Unsigned right shift
+ >> Signed/Arithmetic right shift
+ >>> Unsigned/Logical right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
@@ -207,7 +260,7 @@ public class LearnJava {
// If statements are c-like
int j = 10;
- if (j == 10){
+ if (j == 10) {
System.out.println("I get printed");
} else if (j > 10) {
System.out.println("I don't");
@@ -236,14 +289,24 @@ public class LearnJava {
System.out.println("fooDoWhile Value: " + fooDoWhile);
// For Loop
- int fooFor;
// for loop structure => for(<start_statement>; <conditional>; <step>)
- for (fooFor = 0; fooFor < 10; fooFor++) {
+ for (int fooFor = 0; fooFor < 10; fooFor++) {
System.out.println(fooFor);
// Iterated 10 times, fooFor 0->9
}
System.out.println("fooFor Value: " + fooFor);
-
+
+ // Nested For Loop Exit with Label
+ outer:
+ for (int i = 0; i < 10; i++) {
+ for (int j = 0; j < 10; j++) {
+ if (i == 5 && j ==5) {
+ break outer;
+ // breaks out of outer loop instead of only the inner one
+ }
+ }
+ }
+
// For Each Loop
// The for loop is also able to iterate over arrays as well as objects
// that implement the Iterable interface.
@@ -275,6 +338,23 @@ public class LearnJava {
break;
}
System.out.println("Switch Case Result: " + monthString);
+
+ // Starting in Java 7 and above, switching Strings works like this:
+ String myAnswer = "maybe";
+ switch(myAnswer) {
+ case "yes":
+ System.out.println("You answered yes.");
+ break;
+ case "no":
+ System.out.println("You answered no.");
+ break;
+ case "maybe":
+ System.out.println("You answered maybe.");
+ break;
+ default:
+ System.out.println("You answered " + myAnswer);
+ break;
+ }
// Conditional Shorthand
// You can use the '?' operator for quick assignments or logic forks.
@@ -332,24 +412,24 @@ public class LearnJava {
private static final Set<String> COUNTRIES = new HashSet<String>();
static {
- validCodes.add("DENMARK");
- validCodes.add("SWEDEN");
- validCodes.add("FINLAND");
+ validCodes.add("DENMARK");
+ validCodes.add("SWEDEN");
+ validCodes.add("FINLAND");
}
- // But there's a nifty way to achive the same thing in an
+ // 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 = HashSet<String>() {{
+ private static final Set<String> COUNTRIES = new HashSet<String>() {{
add("DENMARK");
add("SWEDEN");
add("FINLAND");
}}
- // The first brace is creating an new AnonymousInnerClass and the
- // second one declares and instance initializer block. This block
- // is called with the anonymous inner class is created.
+ // The first brace is creating a new AnonymousInnerClass and the
+ // second one declares an instance initializer block. This block
+ // is called when the anonymous inner class is created.
// This does not only work for Collections, it works for all
// non-final classes.
@@ -357,7 +437,8 @@ public class LearnJava {
} // End LearnJava class
-// You can include other, non-public outer-level classes in a .java file
+// You can include other, non-public outer-level classes in a .java file,
+// but it is not good practice. Instead split classes into separate files.
// Class Declaration Syntax:
@@ -374,9 +455,22 @@ class Bicycle {
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
+ // Java has no implementation of static constructors, but
+ // has a static block that can be used to initialize class variables
+ // (static variables).
+ // This block will be called when the class is loaded.
+ static {
+ className = "Bicycle";
+ }
+
// Constructors are a way of creating classes
// This is a constructor
public Bicycle() {
+ // You can also call another constructor:
+ // this(1, 50, 5, "Bontrager");
gear = 1;
cadence = 50;
speed = 5;
@@ -392,13 +486,13 @@ class Bicycle {
this.name = name;
}
- // Function Syntax:
+ // Method Syntax:
// <public/private/protected> <return type> <function name>(<args>)
// Java classes often implement getters and setters for their fields
// Method declaration syntax:
- // <scope> <return type> <method name>(<args>)
+ // <access modifier> <return type> <method name>(<args>)
public int getCadence() {
return cadence;
}
@@ -429,7 +523,7 @@ class Bicycle {
}
//Method to display the attribute values of this Object.
- @Override
+ @Override // Inherited from the Object class.
public String toString() {
return "gear: " + gear + " cadence: " + cadence + " speed: " + speed +
" name: " + name;
@@ -441,7 +535,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");
}
@@ -464,108 +558,210 @@ class PennyFarthing extends Bicycle {
// Example - Food:
public interface Edible {
- public void eat(); // Any class that implements this interface, must
+ public void eat(); // Any class that implements this interface, must
// implement this method.
}
public interface Digestible {
- public void digest();
+ public void digest();
}
// We can now create a class that implements both of these interfaces.
public class Fruit implements Edible, Digestible {
+
@Override
- public void eat() {
- // ...
- }
+ public void eat() {
+ // ...
+ }
@Override
- public void digest() {
- // ...
- }
+ public void digest() {
+ // ...
+ }
}
// In Java, you can extend only one class, but you can implement many
// interfaces. For example:
public class ExampleClass extends ExampleClassParent implements InterfaceOne,
InterfaceTwo {
+
@Override
- public void InterfaceOneMethod() {
- }
+ public void InterfaceOneMethod() {
+ }
@Override
- public void InterfaceTwoMethod() {
- }
-}
+ public void InterfaceTwoMethod() {
+ }
+}
// Abstract Classes
+
// Abstract Class declaration syntax
// <access-level> abstract <abstract-class-name> extends <super-abstract-classes> {
// // Constants and variables
// // Method declarations
// }
-// Methods can't have bodies in an interface, unless the method is
-// static. Also variables are NOT final by default, unlike an interface.
-// Also abstract classes CAN have the "main" method.
-// Abstract classes solve these problems.
+// 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
+// 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.
public abstract class Animal
{
- public abstract void makeSound();
-
- // Method can have a body
- public void eat()
- {
- System.out.println("I am an animal and I am Eating.");
- // Note: We can access private variable here.
- age = 30;
- }
-
- // No need to initialize, however in an interface
- // a variable is implicitly final and hence has
- // to be initialized.
- private int age;
-
- public void printAge()
- {
- System.out.println(age);
- }
-
- // Abstract classes can have main function.
- public static void main(String[] args)
- {
- System.out.println("I am abstract");
- }
+ public abstract void makeSound();
+
+ // Method can have a body
+ public void eat()
+ {
+ System.out.println("I am an animal and I am Eating.");
+ // Note: We can access private variable here.
+ age = 30;
+ }
+
+ // No need to initialize, however in an interface
+ // a variable is implicitly final and hence has
+ // to be initialized.
+ protected int age;
+
+ public void printAge()
+ {
+ System.out.println(age);
+ }
+
+ // Abstract classes can have main function.
+ public static void main(String[] args)
+ {
+ System.out.println("I am abstract");
+ }
}
class Dog extends Animal
{
- // Note still have to override the abstract methods in the
- // abstract class.
- @Override
- public void makeSound()
- {
- System.out.println("Bark");
- // age = 30; ==> ERROR! age is private to Animal
- }
-
- // NOTE: You will get an error if you used the
- // @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/
- public static void main(String[] args)
- {
- Dog pluto = new Dog();
- pluto.makeSound();
- pluto.eat();
- pluto.printAge();
- }
+ // Note still have to override the abstract methods in the
+ // abstract class.
+ @Override
+ public void makeSound()
+ {
+ System.out.println("Bark");
+ // age = 30; ==> ERROR! age is private to Animal
+ }
+
+ // NOTE: You will get an error if you used the
+ // @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/
+ public static void main(String[] args)
+ {
+ Dog pluto = new Dog();
+ pluto.makeSound();
+ pluto.eat();
+ pluto.printAge();
+ }
}
+// Final Classes
+
+// Final Class declaration syntax
+// <access-level> final <final-class-name> {
+// // Constants and variables
+// // Method declarations
+// }
+
+// Final classes are classes that cannot be inherited from and are therefore a
+// final child. In a way, final classes are the opposite of abstract classes
+// because abstract classes must be extended, but final classes cannot be
+// extended.
+public final class SaberToothedCat extends Animal
+{
+ // Note still have to override the abstract methods in the
+ // abstract class.
+ @Override
+ public void makeSound()
+ {
+ System.out.println("Roar");
+ }
+}
+
+// Final Methods
+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.
+ 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:
+
+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;
+
+ public EnumTest(Day day) {
+ this.day = day;
+ }
+
+ public void tellItLikeItIs() {
+ switch (day) {
+ case MONDAY:
+ System.out.println("Mondays are bad.");
+ break;
+
+ case FRIDAY:
+ System.out.println("Fridays are better.");
+ break;
+
+ case SATURDAY:
+ case SUNDAY:
+ System.out.println("Weekends are best.");
+ break;
+
+ default:
+ System.out.println("Midweek days are so-so.");
+ break;
+ }
+ }
+
+ public static void main(String[] args) {
+ EnumTest firstDay = new EnumTest(Day.MONDAY);
+ firstDay.tellItLikeItIs(); // => Mondays are bad.
+ EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
+ thirdDay.tellItLikeItIs(); // => Midweek days are so-so.
+ }
+}
+
+// Enum types are much more powerful than we show above.
+// The enum body can include methods and other fields.
+// You can se more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
+
```
## Further Reading
@@ -589,7 +785,7 @@ The links provided here below are just to get an understanding of the topic, fee
* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html)
-* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html)
+* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html)
**Online Practice and Tutorials**
diff --git a/javascript.html.markdown b/javascript.html.markdown
index 754832f1..98261334 100644
--- a/javascript.html.markdown
+++ b/javascript.html.markdown
@@ -16,13 +16,14 @@ JavaScript isn't just limited to web browsers, though: Node.js, a project that
provides a standalone runtime for Google Chrome's V8 JavaScript engine, is
becoming more and more popular.
-Feedback would be highly appreciated! You can reach me at
-[@adambrenecki](https://twitter.com/adambrenecki), or
-[adam@brenecki.id.au](mailto:adam@brenecki.id.au).
+JavaScript has a C-like syntax, so if you've used languages like C or Java,
+a lot of the basic syntax will already be familiar. Despite this, and despite
+the similarity in name, JavaScript's object model is significantly different to
+Java's.
```js
-// Comments are like C. Single-line comments start with two slashes,
-/* and multiline comments start with slash-star
+// Single-line comments start with two slashes.
+/* Multiline comments start with slash-star,
and end with star-slash */
// Statements can be terminated by ;
@@ -40,7 +41,7 @@ doStuff()
// JavaScript has one number type (which is a 64-bit IEEE 754 double).
// Doubles have a 52-bit mantissa, which is enough to store integers
-// up to about 9✕10¹⁵ precisely.
+// up to about 9✕10¹⁵ precisely.
3; // = 3
1.5; // = 1.5
@@ -54,6 +55,11 @@ doStuff()
// Including uneven division.
5 / 2; // = 2.5
+// And modulo division.
+10 % 2; // = 0
+30 % 4; // = 2
+18.5 % 7; // = 4.5
+
// Bitwise operations also work; when you perform a bitwise operation your float
// is converted to a signed int *up to* 32 bits.
1 << 2; // = 4
@@ -95,6 +101,10 @@ false;
// Strings are concatenated with +
"Hello " + "world!"; // = "Hello world!"
+// ... which works with more than just strings
+"1, 2, " + 3; // = "1, 2, 3"
+"Hello " + ["world", "!"] // = "Hello world,!"
+
// and are compared with < and >
"a" < "b"; // = true
@@ -104,7 +114,7 @@ null == undefined; // = true
// ...unless you use ===
"5" === 5; // = false
-null === undefined; // = false
+null === undefined; // = false
// ...which can result in some weird behaviour...
13 + !0; // 14
@@ -135,7 +145,7 @@ undefined; // used to indicate a value is not currently present (although
// character.
var someVar = 5;
-// if you leave the var keyword off, you won't get an error...
+// If you leave the var keyword off, you won't get an error...
someOtherVar = 10;
// ...but your variable will be created in the global scope, not in the scope
@@ -144,6 +154,10 @@ someOtherVar = 10;
// Variables declared without being assigned to are set to undefined.
var someThirdVar; // = undefined
+// If you want to declare a couple of variables, then you could use a comma
+// separator
+var someFourthVar = 2, someFifthVar = 4;
+
// There's shorthand for performing math operations on variables:
someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now
someVar *= 10; // now someVar is 100
@@ -189,8 +203,6 @@ myObj.myFourthKey; // = undefined
///////////////////////////////////
// 3. Logic and Control Structures
-// The syntax for this section is almost identical to Java's.
-
// The `if` structure works as you'd expect.
var count = 1;
if (count == 3){
@@ -218,6 +230,27 @@ for (var i = 0; i < 5; i++){
// will run 5 times
}
+// The for/in statement iterates over every property across the entire prototype chain.
+var description = "";
+var person = {fname:"Paul", lname:"Ken", age:18};
+for (var x in person){
+ description += person[x] + " ";
+}
+
+// To only consider properties attached to the object itself
+// and not its prototypes, use the `hasOwnProperty()` check.
+var description = "";
+var person = {fname:"Paul", lname:"Ken", age:18};
+for (var x in person){
+ if (person.hasOwnProperty(x)){
+ description += person[x] + " ";
+ }
+}
+
+// For/in should not be used to iterate over an Array where the index order
+// is important, as there is no guarantee that for/in will return the indexes
+// in any particular order.
+
// && is logical and, || is logical or
if (house.size == "big" && house.colour == "blue"){
house.contains = "bear";
@@ -231,7 +264,7 @@ var name = otherName || "default";
// The `switch` statement checks for equality with `===`.
-// use 'break' after each case
+// Use 'break' after each case
// or the cases after the correct one will be executed too.
grade = 'B';
switch (grade) {
@@ -262,12 +295,9 @@ myFunction("foo"); // = "FOO"
// Note that the value to be returned must start on the same line as the
// `return` keyword, otherwise you'll always return `undefined` due to
// automatic semicolon insertion. Watch out for this when using Allman style.
-function myFunction()
-{
+function myFunction(){
return // <- semicolon automatically inserted here
- {
- thisIsAn: 'object literal'
- }
+ {thisIsAn: 'object literal'}
}
myFunction(); // = undefined
@@ -281,6 +311,12 @@ setTimeout(myFunction, 5000);
// Note: setTimeout isn't part of the JS language, but is provided by browsers
// and Node.js.
+// Another function provided by browsers is setInterval
+function myFunction(){
+ // this code will be called every 5 seconds
+}
+setInterval(myFunction, 5000);
+
// Function objects don't even have to be declared with a name - you can write
// an anonymous function definition directly into the arguments of another.
setTimeout(function(){
@@ -299,7 +335,7 @@ i; // = 5 - not undefined as you'd expect in a block-scoped language
// scope.
(function(){
var temporary = 5;
- // We can access the global scope by assiging to the "global object", which
+ // We can access the global scope by assigning to the "global object", which
// in a web browser is always `window`. The global object may have a
// different name in non-browser environments such as Node.js.
window.permanent = 10;
@@ -393,7 +429,7 @@ var doubler = product.bind(this, 2);
doubler(8); // = 16
// When you call a function with the `new` keyword, a new object is created, and
-// made available to the function via the this keyword. Functions designed to be
+// made available to the function via the `this` keyword. Functions designed to be
// called like that are called constructors.
var MyConstructor = function(){
@@ -475,6 +511,10 @@ myNumber === myNumberObj; // = false
if (0){
// This code won't execute, because 0 is falsy.
}
+if (new Number(0)){
+ // This code will execute, because wrapped numbers are objects, and objects
+ // are always truthy.
+}
// However, the wrapper objects and the regular builtins share a prototype, so
// you can actually add functionality to a string, for instance.
@@ -502,28 +542,42 @@ if (Object.create === undefined){ // don't overwrite it if it exists
## Further Reading
-The [Mozilla Developer
-Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides
-excellent documentation for JavaScript as it's used in browsers. Plus, it's a
-wiki, so as you learn more you can help others out by sharing your own
-knowledge.
+The [Mozilla Developer Network][1] provides excellent documentation for
+JavaScript as it's used in browsers. Plus, it's a wiki, so as you learn more you
+can help others out by sharing your own knowledge.
+
+MDN's [A re-introduction to JavaScript][2] covers much of the concepts covered
+here in more detail. This guide has quite deliberately only covered the
+JavaScript language itself; if you want to learn more about how to use
+JavaScript in web pages, start by learning about the [Document Object Model][3].
+
+[Learn Javascript by Example and with Challenges][4] is a variant of this
+reference with built-in challenges.
+
+[JavaScript Garden][5] is an in-depth guide of all the counter-intuitive parts
+of the language.
+
+[JavaScript: The Definitive Guide][6] is a classic guide and reference book.
+
+[Eloquent Javascript][8] by Marijn Haverbeke is an excellent JS book/ebook with attached terminal
+
+[Eloquent Javascript - The Annotated Version][9] by Gordon Zhu is also a great derivative of Eloquent Javascript with extra explanations and clarifications for some of the more complicated examples.
-MDN's [A re-introduction to
-JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
-covers much of the concepts covered here in more detail. This guide has quite
-deliberately only covered the JavaScript language itself; if you want to learn
-more about how to use JavaScript in web pages, start by learning about the
-[Document Object
-Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)
+[Javascript: The Right Way][10] is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices.
-[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges.
-[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth
-guide of all the counter-intuitive parts of the language.
+In addition to direct contributors to this article, some content is adapted from
+Louie Dinh's Python tutorial on this site, and the [JS Tutorial][7] on the
+Mozilla Developer Network.
-[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book.
-In addition to direct contributors to this article, some content is adapted
-from Louie Dinh's Python tutorial on this site, and the [JS
-Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
-on the Mozilla Developer Network.
+[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript
+[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
+[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core
+[4]: http://www.learneroo.com/modules/64/nodes/350
+[5]: http://bonsaiden.github.io/JavaScript-Garden/
+[6]: http://www.amazon.com/gp/product/0596805527/
+[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
+[8]: http://eloquentjavascript.net/
+[9]: http://watchandcode.com/courses/eloquent-javascript-the-annotated-version
+[10]: http://jstherightway.org/
diff --git a/json.html.markdown b/json.html.markdown
index 6aff2ce2..a612cffe 100644
--- a/json.html.markdown
+++ b/json.html.markdown
@@ -4,14 +4,28 @@ filename: learnjson.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"]
---
-As JSON is an extremely simple data-interchange format, this is most likely going
-to be the simplest Learn X in Y Minutes ever.
+JSON is an extremely simple data-interchange format. As [json.org](http://json.org) says, it is easy for humans to read and write and for machines to parse and generate.
-JSON in its purest form has no actual comments, but most parsers will accept
-C-style (`//`, `/* */`) comments. For the purposes of this, however, everything is
-going to be 100% valid JSON. Luckily, it kind of speaks for itself.
+A piece of JSON must represent either:
+* A collection of name/value pairs (`{ }`). In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
+* An ordered list of values (`[ ]`). In various languages, this is realized as an array, vector, list, or sequence.
+ an array/list/sequence (`[ ]`) or a dictionary/object/associated array (`{ }`).
+
+JSON in its purest form has no actual comments, but most parsers will accept C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma (i.e. a comma after the last element of an array or the after the last property of an object), but they should be avoided for better compatibility.
+
+For the purposes of this tutorial, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself.
+
+Supported data types:
+
+* Strings: `"hello"`, `"\"A quote.\""`, `"\u0abe"`, `"Newline.\n"`
+* Numbers: `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4`
+* Objects: `{ "key": "value" }`
+* Arrays: `["Values"]`
+* Miscellaneous: `true`, `false`, `null`
```json
{
@@ -49,10 +63,20 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself.
"alternative style": {
"comment": "check this out!"
- , "comma position": "doesn't matter - as long as it's before the value, then it's valid"
+ , "comma position": "doesn't matter, if it's before the next key, it's valid"
, "another comment": "how nice"
},
- "that was short": "And, you're done. You now know everything JSON has to offer."
+
+
+ "whitespace": "Does not matter.",
+
+
+
+ "that was short": "And done. You now know everything JSON has to offer."
}
```
+
+## Further Reading
+
+* [JSON.org](http://json.org) All of JSON beautifully explained using flowchart-like graphics.
diff --git a/julia.html.markdown b/julia.html.markdown
index 66329feb..db72e8ba 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -2,6 +2,7 @@
language: Julia
contributors:
- ["Leah Hanson", "http://leahhanson.us"]
+ - ["Pranit Bauva", "http://github.com/pranitbauva1997"]
filename: learnjulia.jl
---
@@ -81,10 +82,13 @@ false
# Strings are created with "
"This is a string."
+# Julia has several types of strings, including ASCIIString and UTF8String.
+# More on this in the Types section.
+
# Character literals are written with '
'a'
-# A string can be indexed like an array of characters
+# Some strings can be indexed like an array of characters
"This is a string"[1] # => 'T' # Julia indexes from 1
# However, this is will not work well for UTF8 strings,
# so iterating over strings is recommended (map, for loops, etc).
@@ -99,6 +103,11 @@ false
# Printing is easy
println("I'm Julia. Nice to meet you!")
+# String can be compared lexicographically
+"good" > "bye" # => true
+"good" == "good" # => true
+"1 + 2 = 3" == "1 + 2 = $(1+2)" # => true
+
####################################################
## 2. Variables and Collections
####################################################
@@ -114,11 +123,11 @@ catch e
println(e)
end
-# Variable names start with a letter.
+# Variable names start with a letter or underscore.
# After that, you can use letters, digits, underscores, and exclamation points.
SomeOtherVar123! = 6 # => 6
-# You can also use unicode characters
+# You can also use certain unicode characters
☃ = 8 # => 8
# These are especially handy for mathematical notation
2 * π # => 6.283185307179586
@@ -142,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]
@@ -314,7 +327,7 @@ end
# For loops iterate over iterables.
-# Iterable types include Range, Array, Set, Dict, and String.
+# Iterable types include Range, Array, Set, Dict, and AbstractString.
for animal=["dog", "cat", "mouse"]
println("$animal is a mammal")
# You can use $ to interpolate variables or expression into strings
@@ -387,6 +400,14 @@ end
add(5, 6) # => 11 after printing out "x is 5 and y is 6"
+# Compact assignment of functions
+f_add(x, y) = x + y # => "f (generic function with 1 method)"
+f_add(3, 4) # => 7
+
+# Function can also return multiple values as tuple
+f(x, y) = x + y, x - y
+f(3, 4) # => (7, -1)
+
# You can define functions that take a variable number of
# positional arguments
function varargs(args...)
@@ -399,7 +420,7 @@ 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)
@@ -537,6 +558,17 @@ subtypes(Number) # => 6-element Array{Any,1}:
# Real
subtypes(Cat) # => 0-element Array{Any,1}
+# AbstractString, as the name implies, is also an abstract type
+subtypes(AbstractString) # 8-element Array{Any,1}:
+ # Base.SubstitutionString{T<:AbstractString}
+ # DirectIndexString
+ # RepString
+ # RevString{T<:AbstractString}
+ # RopeString
+ # SubString{T<:AbstractString}
+ # UTF16String
+ # UTF8String
+
# Every type has a super type; use the `super` function to get it.
typeof(5) # => Int64
super(Int64) # => Signed
@@ -546,17 +578,21 @@ super(Number) # => Any
super(super(Signed)) # => Number
super(Any) # => Any
# All of these type, except for Int64, are abstract.
+typeof("fire") # => ASCIIString
+super(ASCIIString) # => DirectIndexString
+super(DirectIndexString) # => AbstractString
+# Likewise here with ASCIIString
# <: is the subtyping operator
type Lion <: Cat # Lion is a subtype of Cat
mane_color
- roar::String
+ roar::AbstractString
end
# You can define more constructors for your type
# Just define a function of the same name as the type
# and call an existing constructor to get a value of the correct type
-Lion(roar::String) = Lion("green",roar)
+Lion(roar::AbstractString) = Lion("green",roar)
# This is an outer constructor because it's outside the type definition
type Panther <: Cat # Panther is also a subtype of Cat
@@ -705,7 +741,7 @@ code_native(square_area, (Float64,))
# ret
#
# Note that julia will use floating point instructions if any of the
-# arguements are floats.
+# arguments are floats.
# Let's calculate the area of a circle
circle_area(r) = pi * r * r # circle_area (generic function with 1 method)
circle_area(5) # 78.53981633974483
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/latex.html.markdown b/latex.html.markdown
new file mode 100644
index 00000000..d41f6b2f
--- /dev/null
+++ b/latex.html.markdown
@@ -0,0 +1,247 @@
+---
+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"]
+filename: learn-latex.tex
+---
+
+```tex
+% All comment lines start with %
+% There are no multi-line comments
+
+% LaTeX is NOT a "What You See Is What You Get" word processing software like
+% MS Word, or OpenOffice Writer
+
+% Every LaTeX command starts with a backslash (\)
+
+% LaTeX documents start with a defining the type of document it's compiling
+% Other document types include book, report, presentations, etc.
+% The options for the document appear in the [] brackets. In this case
+% it specifies we want to use 12pt font.
+\documentclass[12pt]{article}
+
+% Next we define the packages the document uses.
+% If you want to include graphics, colored text, or
+% source code from another language file into your document,
+% you need to enhance the capabilities of LaTeX. This is done by adding packages.
+% I'm going to include the float and caption packages for figures.
+\usepackage{caption}
+\usepackage{float}
+
+% We can define some other document properties too!
+\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu}
+\date{\today}
+\title{Learn LaTeX in Y Minutes!}
+
+% Now we're ready to begin the document
+% Everything before this line is called "The Preamble"
+\begin{document}
+% if we set the author, date, title fields, we can have LaTeX
+% create a title page for us.
+\maketitle
+
+% Most research papers have abstract, you can use the predefined commands for this.
+% This should appear in its logical order, therefore, after the top matter,
+% but before the main sections of the body.
+% This command is available in the document classes article and report.
+\begin{abstract}
+ LaTeX documentation written as LaTeX! How novel and totally not my idea!
+\end{abstract}
+
+% Section commands are intuitive.
+% All the titles of the sections are added automatically to the table of contents.
+\section{Introduction}
+Hello, my name is Colton and together we're going to explore LaTeX!
+
+\section{Another section}
+This is the text for another section. I think it needs a subsection.
+
+\subsection{This is a subsection} % Subsections are also intuitive.
+I think we need another one
+
+\subsubsection{Pythagoras}
+Much better now.
+\label{subsec:pythagoras}
+
+% By using the asterisk we can suppress LaTeX's inbuilt numbering.
+% This works for other LaTeX commands as well.
+\section*{This is an unnumbered section}
+However not all sections have to be numbered!
+
+\section{Some Text notes}
+LaTeX is generally pretty good about placing text where it should go. If
+a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash to
+the source code. \\
+
+\section{Lists}
+Lists are one of the easiest things to create in LaTeX! I need to go shopping
+tomorrow, so let's make a grocery list.
+\begin{enumerate} % This creates an "enumerate" environment.
+ % \item tells the enumerate to increment
+ \item Salad.
+ \item 27 watermelon.
+ \item A single jackrabbit.
+ % we can even override the item number by using []
+ \item[how many?] Medium sized squirt guns.
+
+ Not a list item, but still part of the enumerate.
+
+\end{enumerate} % All environments must have an end.
+
+\section{Math}
+
+One of the primary uses for LaTeX is to produce academic articles or
+technical papers. Usually in the realm of math and science. As such,
+we need to be able to add special symbols to our paper! \\
+
+Math has many symbols, far beyond what you can find on a keyboard;
+Set and relation symbols, arrows, operators, and Greek letters to name a few.\\
+
+Sets and relations play a vital role in many mathematical research papers.
+Here's how you state all y that belong to X, $\forall$ x $\in$ X. \\
+% Notice how I needed to add $ signs before and after the symbols. This is
+% because when writing, we are in text-mode.
+% However, the math symbols only exist in math-mode.
+% We can enter math-mode from text mode with the $ signs.
+% The opposite also holds true. Variable can also be rendered in math-mode.
+% We can also enter math mode with \[\]
+
+\[a^2 + b^2 = c^2 \]
+
+My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$.
+I haven't found a Greek letter that yet that LaTeX doesn't know about!
+
+Operators are essential parts of a mathematical document:
+trigonometric functions ($\sin$, $\cos$, $\tan$),
+logarithms and exponentials ($\log$, $\exp$),
+limits ($\lim$), etc.
+have per-defined LaTeX commands.
+Let's write an equation to see how it's done: \\
+
+$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$
+
+Fractions(Numerator-denominators) can be written in these forms:
+
+% 10 / 7
+$^{10}/_{7}$
+
+% Relatively complex fractions can be written as
+% \frac{numerator}{denominator}
+$\frac{n!}{k!(n - k)!}$ \\
+
+We can also insert equations in an "equation environment".
+
+% Display math with the equation 'environment'
+\begin{equation} % enters math-mode
+ c^2 = a^2 + b^2.
+ \label{eq:pythagoras} % for referencing
+\end{equation} % all \begin statements must have an end statement
+
+We can then reference our new equation!
+Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also
+the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled:
+figures, equations, sections, etc.
+
+Summations and Integrals are written with sum and int commands:
+
+% Some LaTeX compilers will complain if there are blank lines
+% In an equation environment.
+\begin{equation}
+ \sum_{i=0}^{5} f_{i}
+\end{equation}
+\begin{equation}
+ \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
+\end{equation}
+
+\section{Figures}
+
+Let's insert a Figure. Figure placement can get a little tricky.
+I definitely have to lookup the placement options each time.
+
+\begin{figure}[H] % H here denoted the placement option.
+ \centering % centers the figure on the page
+ % Inserts a figure scaled to 0.8 the width of the page.
+ %\includegraphics[width=0.8\linewidth]{right-triangle.png}
+ % Commented out for compilation purposes. Please use your imagination.
+ \caption{Right triangle with sides $a$, $b$, $c$}
+ \label{fig:right-triangle}
+\end{figure}
+
+\subsection{Table}
+We can also insert Tables in the same way as figures.
+
+\begin{table}[H]
+ \caption{Caption for the Table.}
+ % 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 $
+ \hline % a horizontal line
+ 1 & Biggus & Dickus \\
+ 2 & Monty & Python
+ \end{tabular}
+\end{table}
+
+% \section{Hyperlinks} % Coming soon
+
+\section{Getting LaTeX to not compile something (i.e. Source Code)}
+Let's say we want to include some code into our LaTeX document,
+we would then need LaTeX to not try and interpret that text and
+instead just print it to the document. We do this we a verbatim
+environment.
+
+% There are other packages that exist (i.e. minty, lstlisting, etc.)
+% but verbatim is the bare-bones basic one.
+\begin{verbatim}
+ print("Hello World!")
+ a%b; % look! We can use % signs in verbatim.
+ random = 4; #decided by fair random dice roll
+\end{verbatim}
+
+\section{Compiling}
+
+By now you're probably wondering how to compile this fabulous document
+and look at the glorious glory that is a LaTeX pdf.
+(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
+ \end{verbatim}
+ \end{enumerate}
+
+A number of LaTeX editors combine both Step 1 and Step 2 in the same piece of
+software. So, you get to see Step 1, but not Step 2 completely.
+Step 2 is still happening behind the scenes.
+
+You write all your formatting information in plain text in Step 1.
+The compilation part in Step 2 takes care of producing the document in the
+format you defined in Step 1.
+
+\section{End}
+
+That's all for now!
+
+% Most often, you would want to have a references section in your document.
+% The easiest way to set this up would be by using the bibliography section
+\begin{thebibliography}{1}
+ % similar to other lists, the \bibitem command can be used to list items
+ % each entry can then be cited directly in the body of the text
+ \bibitem{latexwiki} The amazing LaTeX wikibook: {\em https://en.wikibooks.org/wiki/LaTeX}
+ \bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com}
+\end{thebibliography}
+
+% end the document
+\end{document}
+```
+
+## More on LaTeX
+
+* The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX)
+* An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
diff --git a/less.html.markdown b/less.html.markdown
new file mode 100644
index 00000000..a1018ca3
--- /dev/null
+++ b/less.html.markdown
@@ -0,0 +1,379 @@
+---
+language: less
+filename: learnless.less
+contributors:
+ - ["Saravanan Ganesh", "http://srrvnn.me"]
+---
+
+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.
+
+```css
+
+
+//Single line comments are removed when Less is compiled to CSS.
+
+/*Multi line comments are preserved. */
+
+
+/*Variables
+==============================*/
+
+
+
+/* You can store a CSS value (such as a color) in a variable.
+Use the '@' symbol to create a variable. */
+
+@primary-color: #A3A4FF;
+@secondary-color: #51527F;
+@body-font: 'Roboto', sans-serif;
+
+/* You can use the variables throughout your stylesheet.
+Now if you want to change a color, you only have to make the change once.*/
+
+body {
+ background-color: @primary-color;
+ color: @secondary-color;
+ font-family: @body-font;
+}
+
+/* This would compile to: */
+body {
+ background-color: #A3A4FF;
+ color: #51527F;
+ font-family: 'Roboto', sans-serif;
+}
+
+
+/* This is much more maintainable than having to change the color
+each time it appears throughout your stylesheet. */
+
+
+/*Mixins
+==============================*/
+
+
+
+/* If you find you are writing the same code for more than one
+element, you might want to reuse that easily.*/
+
+.center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+/* You can use the mixin by simply adding the selector as a style */
+
+div {
+ .center;
+ background-color: @primary-color;
+}
+
+/*Which would compile to: */
+.center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #A3A4FF;
+}
+
+/* You can omit the mixin code from being compiled by adding parenthesis
+ after the selector */
+
+.center() {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+div {
+ .center;
+ background-color: @primary-color;
+}
+
+/*Which would compile to: */
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #A3A4FF;
+}
+
+
+/*Functions
+==============================*/
+
+
+
+/* Less provides functions that can be used to accomplish a variety of
+ tasks. Consider the following */
+
+/* Functions can be invoked by using their name and passing in the
+ required arguments */
+body {
+ width: round(10.25px);
+}
+
+.footer {
+ background-color: fadeout(#000000, 0.25)
+}
+
+/* Compiles to: */
+
+body {
+ width: 10px;
+}
+
+.footer {
+ background-color: rgba(0, 0, 0, 0.75);
+}
+
+/* You may also define your own functions. Functions are very similar to
+ mixins. When trying to choose between a function or a mixin, remember
+ that mixins are best for generating CSS while functions are better for
+ logic that might be used throughout your Less code. The examples in
+ the Math Operators' section are ideal candidates for becoming a reusable
+ function. */
+
+/* This function will take a target size and the parent size and calculate
+ and return the percentage */
+
+.average(@x, @y) {
+ @average_result: ((@x + @y) / 2);
+}
+
+div {
+ .average(16px, 50px); // "call" the mixin
+ padding: @average_result; // use its "return" value
+}
+
+/* Compiles to: */
+
+div {
+ padding: 33px;
+}
+
+/*Extend (Inheritance)
+==============================*/
+
+
+
+/*Extend is a way to share the properties of one selector with another. */
+
+.display {
+ height: 50px;
+}
+
+.display-success {
+ &:extend(.display);
+ border-color: #22df56;
+}
+
+/* Compiles to: */
+.display,
+.display-success {
+ height: 50px;
+}
+.display-success {
+ border-color: #22df56;
+}
+
+/* Extending a CSS statement is preferable to creating a mixin
+ because of the way it groups together the classes that all share
+ the same base styling. If this was done with a mixin, the properties
+ would be duplicated for each statement that
+ called the mixin. While it won't affect your workflow, it will
+ add unnecessary bloat to the files created by the Less compiler. */
+
+
+
+/*Nesting
+==============================*/
+
+
+
+/*Less allows you to nest selectors within selectors */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: #FF0000;
+ }
+}
+
+/* '&' will be replaced by the parent selector. */
+/* You can also nest pseudo-classes. */
+/* Keep in mind that over-nesting will make your code less maintainable.
+Best practices recommend going no more than 3 levels deep when nesting.
+For example: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: red;
+
+ &:hover {
+ background-color: blue;
+ }
+
+ a {
+ color: white;
+ }
+ }
+}
+
+/* Compiles to: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+}
+
+ul li {
+ background-color: red;
+}
+
+ul li:hover {
+ background-color: blue;
+}
+
+ul li a {
+ color: white;
+}
+
+
+
+/*Partials and Imports
+==============================*/
+
+
+
+/* Less allows you to create partial files. This can help keep your Less
+ code modularized. Partial files conventionally begin with an '_',
+ e.g. _reset.less. and are imported into a main less file that gets
+ compiled into CSS */
+
+/* Consider the following CSS which we'll put in a file called _reset.less */
+
+html,
+body,
+ul,
+ol {
+ margin: 0;
+ padding: 0;
+}
+
+/* Less offers @import which can be used to import partials into a file.
+ This differs from the traditional CSS @import statement which makes
+ another HTTP request to fetch the imported file. Less takes the
+ imported file and combines it with the compiled code. */
+
+@import 'reset';
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+/* Compiles to: */
+
+html, body, ul, ol {
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+
+/*Math Operations
+==============================*/
+
+
+
+/* Less provides the following operators: +, -, *, /, and %. These can
+ be useful for calculating values directly in your Less files instead
+ of using values that you've already calculated by hand. Below is an example
+ of a setting up a simple two column design. */
+
+@content-area: 960px;
+@main-content: 600px;
+@sidebar-content: 300px;
+
+@main-size: @main-content / @content-area * 100%;
+@sidebar-size: @sidebar-content / @content-area * 100%;
+@gutter: 100% - (@main-size + @sidebar-size);
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: @main-size;
+}
+
+.sidebar {
+ width: @sidebar-size;
+}
+
+.gutter {
+ width: @gutter;
+}
+
+/* Compiles to: */
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+.gutter {
+ width: 6.25%;
+}
+
+
+```
+
+## Practice Less
+
+If you want to play with Less in your browser, check out [LESS2CSS](http://lesscss.org/less-preview/).
+
+## Compatibility
+
+Less can be used in any project as long as you have a program to compile it
+into CSS. You'll want to verify that the CSS you're using is compatible
+with your target browsers.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility.
+
+## Further reading
+* [Official Documentation](http://lesscss.org/features/)
diff --git a/lt-lt/json-lt.html.markdown b/lt-lt/json-lt.html.markdown
new file mode 100644
index 00000000..8c97e598
--- /dev/null
+++ b/lt-lt/json-lt.html.markdown
@@ -0,0 +1,81 @@
+---
+language: json
+filename: learnjson.json
+lang: lt-lt
+contributors:
+ - ["Zygimantus", "https://github.com/zygimantus"]
+---
+
+JSON („džeisonas“) yra itin paprastas duomenų mainų formatas, todėl tai bus pati lengviausia „Learn X in Y Minutes“ pamoka.
+
+JSON savo gryniausioje formoje neturi jokių komentarų, tačiau dauguma analizatorių priimtų C stiliaus komentarus (`//`, `/* */`). Kai kurie analizatoriai taip pat toleruoja gale esantį kablelį, pvz., kablelis po kiekvieno masyvo paskutinio elemento arba po paskutinio objekto lauko, tačiau jų reikėtų vengti dėl geresnio suderinamumo.
+
+JSON reikšmė privalo būti skaičius, eilutė, masyvas, objektas arba viena reikšmė iš šių: true, false, null.
+
+Palaikančios naršyklės yra: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, and Safari 4.0+.
+
+Failo plėtinys JSON failams yra „.json“, o MIME tipas yra „application/json“.
+
+Dauguma programavimo kalbų palaiko JSON duomenų serializaciją (kodavimą) ir deserializaciją (dekodavimą) į natyviasias duomenų struktūras. Javascript turi visišką JSON teksto kaip duomenų manipuliavimo palaikymą.
+
+Daugiau informacijos galima rasti http://www.json.org/
+
+JSON yra pastatytas iš dviejų struktūrų:
+* Vardų/reikšmių porų rinkinys. Daugomoje kalbų, tai yra realizuojama kaip objektas, įrašas, struktūra, žodynas, hash lentelė, sąrašas su raktais arba asociatyvusis masyvas.
+* Rūšiuotas reikšmių sąrašas. Daugumoje kalbų, toks sąrašas yra realizuojama kaip masyvas, vektorius, sąrašas arba seka.
+
+Objektas su įvairiomis vardo/reikšmės poromis.
+
+```json
+{
+ "raktas": "reikšmė",
+
+ "raktai": "privalo visada būti uždaryti dvigubomis kabutėmis",
+ "skaičiai": 0,
+ "eilutės": "Labas, pasauli. Visas unikodas yra leidžiamas, kartu su \"vengimu\".",
+ "turi logiką?": true,
+ "niekas": null,
+
+ "didelis skaičius": 1.2e+100,
+
+ "objektai": {
+ "komentaras": "Dauguma tavo struktūrų ateis iš objektų.",
+
+ "masyvas": [0, 1, 2, 3, "Masyvas gali turėti bet ką savyje.", 5],
+
+ "kitas objektas": {
+ "komentaras": "Šie dalykai gali būti įdedami naudingai."
+ }
+ },
+
+ "kvailumas": [
+ {
+ "kalio šaltiniai": ["bananai"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "neo"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "alternativus stilius": {
+ "komentaras": "tik pažiūrėk!"
+ , "kablelio padėti": "nesvarbi - kol jis prieš kitą raktą, tada teisingas"
+ , "kitas komentaras": "kaip gražu"
+ }
+}
+```
+
+Paprastas reikšmių masyvas pats savaime yra galiojantis JSON.
+
+```json
+[1, 2, 3, "tekstas", true]
+```
+
+Objektai taip pat gali būti masyvų dalis.
+
+```json
+[{"vardas": "Jonas", "amžius": 25}, {"vardas": "Eglė", "amžius": 29}, {"vardas": "Petras", "amžius": 31}]
+```
diff --git a/lua.html.markdown b/lua.html.markdown
index 0809215f..2cd4d7bb 100644
--- a/lua.html.markdown
+++ b/lua.html.markdown
@@ -190,7 +190,7 @@ end
--------------------------------------------------------------------------------
-- A table can have a metatable that gives the table operator-overloadish
--- behavior. Later we'll see how metatables support js-prototypey behavior.
+-- behaviour. Later we'll see how metatables support js-prototypey behaviour.
f1 = {a = 1, b = 2} -- Represents the fraction a/b.
f2 = {a = 2, b = 3}
diff --git a/make.html.markdown b/make.html.markdown
index 563139d1..b3425b8a 100644
--- a/make.html.markdown
+++ b/make.html.markdown
@@ -11,7 +11,7 @@ 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.
-There are many varieties of make in existance, this article assumes that
+There are many varieties of make in existence, this article assumes that
we are using GNU make which is the standard on Linux.
```make
@@ -145,11 +145,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.
@@ -234,10 +234,8 @@ bar = 'hello'
endif
```
-
### More Resources
+ [gnu make documentation](https://www.gnu.org/software/make/manual/)
+ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/)
+ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)
-
diff --git a/markdown.html.markdown b/markdown.html.markdown
index 2333110f..b4ad3202 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -2,45 +2,65 @@
language: markdown
contributors:
- ["Dan Turkel", "http://danturkel.com/"]
+ - ["Jacob Ward", "http://github.com/JacobCWard/"]
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).
-Give me as much feedback as you want! / Feel free to fork and pull request!
+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
+specific to a certain parser.
+
+- [HTML Elements](#html-elements)
+- [Headings](#headings)
+- [Simple Text Styles](#simple-text-styles)
+- [Paragraphs](#paragraphs)
+- [Lists](#lists)
+- [Code blocks](#code-blocks)
+- [Horizontal rule](#horizontal-rule)
+- [Links](#links)
+- [Images](#images)
+- [Miscellany](#miscellany)
+
+## HTML Elements
+Markdown is a superset of HTML, so any HTML file is valid Markdown.
```markdown
-<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown, that
-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.-->
+```
-<!-- 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
-specific to a certain parser. -->
+## Headings
-<!-- Headers -->
-<!-- You can create HTML elements <h1> through <h6> easily by prepending the
-text you want to be in that element by a number of hashes (#) -->
+You can create HTML elements `<h1>` through `<h6>` easily by prepending the
+text you want to be in that element by a number of hashes (#).
+
+```markdown
# This is an <h1>
## This is an <h2>
### This is an <h3>
#### This is an <h4>
##### This is an <h5>
###### This is an <h6>
+```
+Markdown also provides us with two alternative ways of indicating h1 and h2.
-<!-- Markdown also provides us with two alternative ways of indicating h1 and h2 -->
+```markdown
This is an h1
=============
This is an h2
-------------
+```
+
+## Simple text styles
-<!-- Simple text styles -->
-<!-- Text can be easily styled as italic or bold using markdown -->
+Text can be easily styled as italic or bold using markdown.
+```markdown
*This text is in italics.*
_And so is this text._
@@ -50,15 +70,20 @@ __And so is this text.__
***This text is in both.***
**_As is this!_**
*__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.~~
+```
+## Paragraphs
-<!-- Paragraphs are a one or multiple adjacent lines of text separated by one or
-multiple blank lines. -->
+Paragraphs are a one or multiple adjacent lines of text separated by one or
+multiple blank lines.
+```markdown
This is a paragraph. I'm typing in a paragraph isn't this fun?
Now I'm in paragraph 2.
@@ -66,16 +91,20 @@ I'm still in paragraph 2 too!
I'm in paragraph three!
+```
-<!-- Should you ever want to insert an HTML <br /> tag, you can end a paragraph
-with two or more spaces and then begin a new paragraph. -->
+Should you ever want to insert an HTML <br /> tag, you can end a paragraph
+with two or more spaces and then begin a new paragraph.
+```markdown
I end with two spaces (highlight me to see them).
There's a <br /> above me!
+```
-<!-- Block quotes are easy and done with the > character. -->
+Block quotes are easy and done with the > character.
+```markdown
> This is a block quote. You can either
> manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own.
> It doesn't make a difference so long as they start with a `>`.
@@ -84,9 +113,12 @@ There's a <br /> above me!
>> of indentation?
> How neat is that?
-<!-- Lists -->
-<!-- Unordered lists can be made using asterisks, pluses, or hyphens -->
+```
+## Lists
+Unordered lists can be made using asterisks, pluses, or hyphens.
+
+```markdown
* Item
* Item
* Another item
@@ -102,159 +134,194 @@ or
- Item
- Item
- One last item
+```
-<!-- Ordered lists are done with a number followed by a period -->
+Ordered lists are done with a number followed by a period.
+```markdown
1. Item one
2. Item two
3. Item three
+```
-<!-- You don't even have to label the items correctly and markdown will still
-render the numbers in order, but this may not be a good idea -->
+You don't even have to label the items correctly and markdown will still
+render the numbers in order, but this may not be a good idea.
+```markdown
1. Item one
1. Item two
1. Item three
-<!-- (This renders the same as the above example) -->
+```
+(This renders the same as the above example)
-<!-- You can also use sublists -->
+You can also use sublists
+```markdown
1. Item one
2. Item two
3. Item three
* Sub-item
* Sub-item
4. Item four
+```
-<!-- There are even task lists. This creates HTML checkboxes. -->
+There are even task lists. This creates HTML checkboxes.
+```markdown
Boxes below without the 'x' are unchecked HTML checkboxes.
- [ ] First task to complete.
- [ ] Second task that needs done
This checkbox below will be a checked HTML checkbox.
- [x] This task has been completed
+```
+
+## Code blocks
-<!-- Code blocks -->
-<!-- You can indicate a code block (which uses the <code> element) by indenting
-a line with four spaces or a tab -->
+You can indicate a code block (which uses the `<code>` element) by indenting
+a line with four spaces or a tab.
+```markdown
This is code
So is this
+```
-<!-- You can also re-tab (or add an additional four spaces) for indentation
-inside your code -->
+You can also re-tab (or add an additional four spaces) for indentation
+inside your code
+```markdown
my_array.each do |item|
puts item
end
+```
-<!-- Inline code can be created using the backtick character ` -->
+Inline code can be created using the backtick character `
+```markdown
John didn't even know what the `go_to()` function did!
+```
-<!-- In Github Flavored Markdown, you can use a special syntax for code -->
+In GitHub Flavored Markdown, you can use a special syntax for code
-\`\`\`ruby <!-- except remove those backslashes when you do this, just ```ruby ! -->
+<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
+highlighting of the language you specify after the \`\`\`
-<!-- The above text doesn't require indenting, plus Github will use syntax
-highlighting of the language you specify after the ``` -->
+## Horizontal rule
-<!-- Horizontal rule (<hr />) -->
-<!-- Horizontal rules 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
***
---
- - -
****************
+```
-<!-- Links -->
-<!-- One of the best things about markdown is how easy it is to make links. Put
-the text to display in hard brackets [] followed by the url in parentheses () -->
+## Links
-[Click me!](http://test.com/)
+One of the best things about markdown is how easy it is to make links. Put
+the text to display in hard brackets [] followed by the url in parentheses ()
-<!-- You can also add a link title using quotes inside the parentheses -->
+```markdown
+[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.
-<!-- Relative paths work too. -->
-
+```markdown
[Go to music](/music/).
+```
-<!-- Markdown also supports reference style links -->
+Markdown also supports reference style links.
-[Click this link][link1] for more info about it!
-[Also check out this link][foobar] if you want to.
+<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.
-[link1]: http://test.com/ "Cool!"
-[foobar]: http://foobar.biz/ "Alright!"
+&#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
+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. -->
+can be anything so long as they are unique.
-<!-- There is also "implicit naming" which lets you use the link text as the id -->
+There is also "implicit naming" which lets you use the link text as the id.
-[This][] is a link.
+<pre><code class="highlight">&#x5b;<span class="nv">This</span>][] is a link.
-[this]: http://thisisalink.com/
+&#x5b;<span class="nv">this</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
-<!-- But it's not that commonly used. -->
+But it's not that commonly used.
-<!-- Images -->
-<!-- Images are done the same way as links but with an exclamation point in front! -->
+## 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 -->
-
-![This is the alt-attribute.][myimage]
+And reference style works as expected.
-[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>]
-<!-- Miscellany -->
-<!-- Auto-links -->
+&#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 -->
+### Auto-links for emails
+```markdown
<foo@bar.com>
+```
-<!-- Escaping characters -->
+### 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\*.
+```
-<!-- Keyboard keys -->
-<!-- In Github Flavored Markdown, you can use a <kbd> tag to represent keyboard keys -->
+### 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 -->
-<!-- Tables are only available in Github Flavored Markdown and are slightly
-cumbersome, but if you really want it: -->
+Tables are only available in GitHub Flavored Markdown and are slightly
+cumbersome, but if you really want it:
+```markdown
| Col1 | Col2 | Col3 |
| :----------- | :------: | ------------: |
| Left-aligned | Centered | Right-aligned |
| blah | blah | blah |
+```
+or, for the same results
-<!-- or, for the same results -->
-
+```markdown
Col 1 | Col2 | Col3
:-- | :-: | --:
Ugh this is so ugly | make it | stop
-
-<!-- The end! -->
-
```
+---
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/matlab.html.markdown b/matlab.html.markdown
index 02fe5962..ddc0cb40 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -1,9 +1,11 @@
---
language: Matlab
+filename: learnmatlab.mat
contributors:
- ["mendozao", "http://github.com/mendozao"]
- ["jamesscottbrown", "http://jamesscottbrown.com"]
-
+ - ["Colton Kohnke", "http://github.com/voltnor"]
+ - ["Claudson Martins", "http://github.com/claudsonm"]
---
MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics.
@@ -13,6 +15,7 @@ If you have any feedback please feel free to reach me at
[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com).
```matlab
+%% Code sections start with two percent signs. Section titles go on the same line.
% Comments start with a percent sign.
%{
@@ -70,7 +73,7 @@ c = exp(a)*sin(pi/2) % c = 7.3891
% Calling functions can be done in either of two ways:
% Standard function syntax:
-load('myFile.mat', 'y') % arguments within parantheses, spererated by commas
+load('myFile.mat', 'y') % arguments within parentheses, separated by commas
% Command syntax:
load myFile.mat y % no parentheses, and spaces instead of commas
% Note the lack of quote marks in command form: inputs are always passed as
@@ -121,6 +124,7 @@ x(2:end) % ans = 32 53 7 1
x = [4; 32; 53; 7; 1] % Column vector
x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
+x = [1:2:10] % Increment by 2, i.e. x = 1 3 5 7 9
% Matrices
A = [1 2 3; 4 5 6; 7 8 9]
@@ -203,6 +207,8 @@ transpose(A) % Transpose the matrix, which is the same as:
A one
ctranspose(A) % Hermitian transpose the matrix
% (the transpose, followed by taking complex conjugate of each element)
+A' % Concise version of complex transpose
+A.' % Concise version of transpose (without taking complex conjugate)
@@ -252,6 +258,8 @@ axis equal % Set aspect ratio so data units are the same in every direction
scatter(x, y); % Scatter-plot
hist(x); % Histogram
+stem(x); % Plot values as stems, useful for displaying discrete data
+bar(x); % Plot bar graph
z = sin(x);
plot3(x,y,z); % 3D line plot
@@ -260,7 +268,7 @@ pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value
contour(A) % Contour plot of matrix
mesh(A) % Plot as a mesh surface
-h = figure % Create new figure object, with handle f
+h = figure % Create new figure object, with handle h
figure(h) % Makes the figure corresponding to handle h the current figure
close(h) % close figure with handle h
close all % close all open figure windows
@@ -271,7 +279,7 @@ clf clear % clear current figure window, and reset most figure properties
% Properties can be set and changed through a figure handle.
% You can save a handle to a figure when you create it.
-% The function gcf returns a handle to the current figure
+% The function get returns a handle to the current figure
h = plot(x, y); % you can save a handle to a figure when you create it
set(h, 'Color', 'r')
% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black
@@ -328,7 +336,7 @@ double_input(6) % ans = 12
% anonymous function. Useful when quickly defining a function to pass to
% another function (eg. plot with fplot, evaluate an indefinite integral
% with quad, find roots with fzero, or find minimum with fminsearch).
-% Example that returns the square of it's input, assigned to to the handle sqr:
+% Example that returns the square of it's input, assigned to the handle sqr:
sqr = @(x) x.^2;
sqr(10) % ans = 100
doc function_handle % find out more
@@ -398,7 +406,7 @@ exp(x)
sqrt(x)
log(x)
log10(x)
-abs(x)
+abs(x) %If x is complex, returns magnitude
min(x)
max(x)
ceil(x)
@@ -409,6 +417,14 @@ rand % Uniformly distributed pseudorandom numbers
randi % Uniformly distributed pseudorandom integers
randn % Normally distributed pseudorandom numbers
+%Complex math operations
+abs(x) % Magnitude of complex variable x
+phase(x) % Phase (or angle) of complex variable x
+real(x) % Returns the real part of x (i.e returns a if x = a +jb)
+imag(x) % Returns the imaginary part of x (i.e returns b if x = a+jb)
+conj(x) % Returns the complex conjugate
+
+
% Common constants
pi
NaN
@@ -458,11 +474,67 @@ length % length of a vector
sort % sort in ascending order
sum % sum of elements
prod % product of elements
-mode % modal value
+mode % modal value
median % median value
mean % mean value
std % standard deviation
perms(x) % list all permutations of elements of x
+find(x) % Finds all non-zero elements of x and returns their indexes, can use comparison operators,
+ % i.e. find( x == 3 ) returns indexes of elements that are equal to 3
+ % i.e. find( x >= 3 ) returns indexes of elements greater than or equal to 3
+
+
+% Classes
+% Matlab can support object-oriented programming.
+% Classes must be put in a file of the class name with a .m extension.
+% To begin, we create a simple class to store GPS waypoints.
+% Begin WaypointClass.m
+classdef WaypointClass % The class name.
+ properties % The properties of the class behave like Structures
+ latitude
+ longitude
+ end
+ methods
+ % This method that has the same name of the class is the constructor.
+ function obj = WaypointClass(lat, lon)
+ obj.latitude = lat;
+ obj.longitude = lon;
+ end
+
+ % Other functions that use the Waypoint object
+ function r = multiplyLatBy(obj, n)
+ r = n*[obj.latitude];
+ end
+
+ % If we want to add two Waypoint objects together without calling
+ % a special function we can overload Matlab's arithmetic like so:
+ function r = plus(o1,o2)
+ r = WaypointClass([o1.latitude] +[o2.latitude], ...
+ [o1.longitude]+[o2.longitude]);
+ end
+ end
+end
+% End WaypointClass.m
+
+% We can create an object of the class using the constructor
+a = WaypointClass(45.0, 45.0)
+
+% Class properties behave exactly like Matlab Structures.
+a.latitude = 70.0
+a.longitude = 25.0
+
+% Methods can be called in the same way as functions
+ans = multiplyLatBy(a,3)
+
+% The method can also be called using dot notation. In this case, the object
+% does not need to be passed to the method.
+ans = a.multiplyLatBy(a,1/3)
+
+% Matlab functions can be overloaded to handle objects.
+% In the method above, we have overloaded how Matlab handles
+% the addition of two Waypoint objects.
+b = WaypointClass(15.0, 32.0)
+c = a + b
```
diff --git a/ms-my/coffeescript-my.html.markdown b/ms-my/coffeescript-my.html.markdown
new file mode 100644
index 00000000..9820a561
--- /dev/null
+++ b/ms-my/coffeescript-my.html.markdown
@@ -0,0 +1,105 @@
+---
+language: coffeescript
+contributors:
+ - ["Tenor Biel", "http://github.com/L8D"]
+ - ["Xavier Yao", "http://github.com/xavieryao"]
+filename: coffeescript-ms.coffee
+translators:
+ - ["hack1m", "https://github.com/hack1m"]
+lang: ms-my
+---
+
+CoffeeScript adalah bahasa kecil yang menyusun/kompil satu-per-satu menjadi setara JavaScript, dan tidak ada interpretasi di runtime.
+Sebagai salah satu pengganti kepada JavaScript, CoffeeScript mencuba yang terbaik untuk output kod JavaScript yang mudah dibaca, cantik-dicetak dan berfungsi lancar, yang mana berfungsi baik pada setiap runtime JavaScript.
+
+Lihat juga [Laman sesawang CoffeeScript](http://coffeescript.org/), yang mana ada tutorial lengkap untuk CoffeeScript.
+
+```coffeescript
+# CoffeeScript adalah bahasa hipster.
+# Ia beredar mengikut trend kebanyakkan bahasa moden.
+# Jadi komen sama seperti Ruby dan Python, ia menggunakan simbol nombor.
+
+###
+Blok komen seperti ini, dan ia terjemah terus ke '/ *'s dan '* /'s
+untuk keputusan kod JavaScript.
+
+Sebelum meneruskan anda perlu faham kebanyakkan daripada
+JavaScript adalah semantik.
+###
+
+# Menetapkan:
+number = 42 #=> var number = 42;
+opposite = true #=> var opposite = true;
+
+# Bersyarat:
+number = -42 if opposite #=> if(opposite) { number = -42; }
+
+# Fungsi:
+square = (x) -> x * x #=> var square = function(x) { return x * x; }
+
+fill = (container, liquid = "coffee") ->
+ "Filling the #{container} with #{liquid}..."
+#=>var fill;
+#
+#fill = function(container, liquid) {
+# if (liquid == null) {
+# liquid = "coffee";
+# }
+# return "Filling the " + container + " with " + liquid + "...";
+#};
+
+# Julat:
+list = [1..5] #=> var list = [1, 2, 3, 4, 5];
+
+# Objek:
+math =
+ root: Math.sqrt
+ square: square
+ cube: (x) -> x * square x
+#=> var math = {
+# "root": Math.sqrt,
+# "square": square,
+# "cube": function(x) { return x * square(x); }
+# };
+
+# Splats:
+race = (winner, runners...) ->
+ print winner, runners
+#=>race = function() {
+# var runners, winner;
+# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
+# return print(winner, runners);
+# };
+
+# Kewujudan:
+alert "I knew it!" if elvis?
+#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
+
+# Pemahaman array:
+cubes = (math.cube num for num in list)
+#=>cubes = (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;
+# })();
+
+foods = ['broccoli', 'spinach', 'chocolate']
+eat food for food in foods when food isnt 'chocolate'
+#=>foods = ['broccoli', 'spinach', 'chocolate'];
+#
+#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) {
+# food = foods[_k];
+# if (food !== 'chocolate') {
+# eat(food);
+# }
+#}
+```
+
+## Sumber tambahan
+
+- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/)
+- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read)
diff --git a/ms-my/javascript-my.html.markdown b/ms-my/javascript-my.html.markdown
new file mode 100644
index 00000000..90e37133
--- /dev/null
+++ b/ms-my/javascript-my.html.markdown
@@ -0,0 +1,588 @@
+---
+language: javascript
+contributors:
+ - ["Adam Brenecki", "http://adam.brenecki.id.au"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
+filename: javascript-ms.js
+translators:
+ - ["abdalim", "https://github.com/abdalim"]
+lang: ms-my
+---
+
+Javascript dicipta oleh Brendan Eich dari Netscape pada 1995. Pada awalnya, ia
+dicipta sebagai bahasa skrip yang ringkas untuk laman web, melengkapi penggunaan
+Java untuk aplikasi web yang lebih rumit, namun begitu, integrasi rapat pada
+halaman web dan sokongan tersedia dalam pelayar web telah menyebabkan ia menjadi
+lebih kerap digunakan berbanding Java pada bahagian hadapan laman web.
+
+Namun begitu, Javascript tidak terhad pada pelayar web; Node.js, sebuah projek
+yang menyediakan 'runtime' berdiri sendiri untuk enjin V8 Google Chrome sedang
+kian mendapat sambutan yang hangat.
+
+```js
+// Komentar adalah seperti dalam C. Komentar sebaris bermula dengan dua sengkang
+/* dan komentar banyak baris bermula dengan sengkang-bintang
+ dan berakhir dengan bintang-sengkang */
+
+// Pernyataan boleh ditamatkan dengan ';'
+doStuff();
+
+// ... tetapi ia tidak wajib, kerana koma bertitik secara automatik akan
+// dimasukkan dimana tempat yang ada baris baru, kecuali dalam kes - kes
+// tertentu.
+doStuff()
+
+// Disebabkan kes - kes itu boleh menyebabkan hasil yang tidak diduga, kami
+// akan sentiasa menggunakan koma bertitik dalam panduan ini.
+
+///////////////////////////////////
+// 1. Nombor, String dan Operator
+
+// Javascript mempunyai satu jenis nombor (iaitu 64-bit IEEE 754 double).
+// Double mempunyai 52-bit mantissa, iaitu ia cukup untuk menyimpan integer
+// sehingga 9✕10¹⁵ secara tepatnya.
+3; // = 3
+1.5; // = 1.5
+
+// Sebahagian aritmetic asas berfungsi seperti yang anda jangkakan.
+1 + 1; // = 2
+0.1 + 0.2; // = 0.30000000000000004
+8 - 1; // = 7
+10 * 2; // = 20
+35 / 5; // = 7
+
+// Termasuk pembahagian tidak rata.
+5 / 2; // = 2.5
+
+// Dan pembahagian modulo.
+10 % 2; // = 0
+30 % 4; // = 2
+18.5 % 7; // = 4.5
+
+// Operasi bitwise juga boleh digunakan; bila anda melakukan operasi bitwise,
+// float anda akan ditukarkan kepada int bertanda *sehingga* 32 bit.
+1 << 2; // = 4
+
+// Keutamaan ditekankan menggunakan kurungan.
+(1 + 3) * 2; // = 8
+
+// Terdapat tiga nilai nombor-tidak-nyata istimewa
+Infinity; // hasil operasi seperti 1/0
+-Infinity; // hasil operasi seperti -1/0
+NaN; // hasil operasi seperti 0/0, bermaksud 'Bukan Sebuah Nombor'
+
+// Terdapat juga jenis boolean
+true;
+false;
+
+// Talian dicipta dengan ' atau ''.
+'abc';
+"Hello, world";
+
+// Penafian menggunakan simbol !
+!true; // = tidak benar
+!false; // = benar
+
+// Sama ialah ===
+1 === 1; // = benar
+2 === 1; // = tidak benar
+
+// Tidak sama ialah !==
+1 !== 1; // = tidak benar
+2 !== 1; // = benar
+
+// Lagi perbandingan
+1 < 10; // = benar
+1 > 10; // = tidak benar
+2 <= 2; // = benar
+2 >= 2; // = benar
+
+// Talian disambungkan dengan +
+"Hello " + "world!"; // = "Hello world!"
+
+// dan dibandingkan dengan < dan >
+"a" < "b"; // = benar
+
+// Paksaan jenis dilakukan untuk perbandingan menggunakan dua sama dengan...
+"5" == 5; // = benar
+null == undefined; // = benar
+
+// ...melainkan anda menggunakan ===
+"5" === 5; // = tidak benar
+null === undefined; // = tidak benar
+
+// ...yang boleh menghasilkan keputusan yang pelik...
+13 + !0; // 14
+"13" + !0; // '13true'
+
+// Anda boleh akses huruf dalam perkataan dengan `charAt`
+"This is a string".charAt(0); // = 'T'
+
+// ...atau menggunakan `substring` untuk mendapatkan bahagian yang lebih besar.
+"Hello world".substring(0, 5); // = "Hello"
+
+// `length` adalah ciri, maka jangan gunakan ().
+"Hello".length; // = 5
+
+// Selain itu, terdapat juga `null` dan `undefined`.
+null; // digunakan untuk menandakan bukan-nilai yang disengajakan
+undefined; // digunakan untuk menandakan nilai yang tidak wujud pada waktu ini (walaupun `undefined` adalah nilai juga)
+
+// false, null, undefined, NaN, 0 dan "" adalah tidak benar; semua selain itu adalah benar.
+// Peringatan, 0 adalah tidak benar dan "0" adalah benar, walaupun 0 == "0".
+
+///////////////////////////////////
+// 2. Pembolehubah, Array dan Objek
+
+// Pembolehubah digunakan dengan kata kunci 'var'. Javascript ialah sebuah
+// bahasa aturcara yang jenisnya dinamik, maka anda tidak perlu spesifikasikan
+// jenis pembolehubah. Penetapan menggunakan satu '=' karakter.
+var someVar = 5;
+
+// jika anda tinggalkan kata kunci var, anda tidak akan dapat ralat...
+someOtherVar = 10;
+
+// ...tetapi pembolehubah anda akan dicipta di dalam skop global, bukan di
+// dalam skop anda menciptanya.
+
+// Pembolehubah yang dideklarasikan tanpa ditetapkan sebarang nilai akan
+// ditetapkan kepada undefined.
+var someThirdVar; // = undefined
+
+// jika anda ingin mendeklarasikan beberapa pembolehubah, maka anda boleh
+// menggunakan koma sebagai pembahagi
+var someFourthVar = 2, someFifthVar = 4;
+
+// Terdapat cara mudah untuk melakukan operasi - operasi matematik pada
+// pembolehubah:
+someVar += 5; // bersamaan dengan someVar = someVar +5; someVar sama dengan 10 sekarang
+someVar *= 10; // sekarang someVar bernilai 100
+
+// dan cara lebih mudah untuk penambahan atau penolakan 1
+someVar++; // sekarang someVar ialah 101
+someVar--; // kembali kepada 100
+
+// Array adalah senarai nilai yang tersusun, yang boleh terdiri daripada
+// pembolehubah pelbagai jenis.
+var myArray = ["Hello", 45, true];
+
+// Setiap ahli array boleh diakses menggunakan syntax kurungan-petak.
+// Indeks array bermula pada sifar.
+myArray[1]; // = 45
+
+// Array boleh diubah dan mempunyai panjang yang tidak tetap dan boleh ubah.
+myArray.push("World");
+myArray.length; // = 4
+
+// Tambah/Ubah di index yang spesifik
+myArray[3] = "Hello";
+
+// Objek javascript adalah sama dengan "dictionaries" atau "maps" dalam bahasa
+// aturcara yang lain: koleksi pasangan kunci-nilai yang tidak mempunyai
+// sebarang susunan.
+var myObj = {key1: "Hello", key2: "World"};
+
+// Kunci adalah string, tetapi 'quote' tidak diperlukan jika ia adalah pengecam
+// javascript yang sah. Nilai boleh mempunyai sebarang jenis.
+var myObj = {myKey: "myValue", "my other key": 4};
+
+// Ciri - ciri objek boleh juga diakses menggunakan syntax subskrip (kurungan-
+// petak),
+myObj["my other key"]; // = 4
+
+// ... atau menggunakan syntax titik, selagi kuncinya adalah pengecam yang sah.
+myObj.myKey; // = "myValue"
+
+// Objek adalah boleh diubah; nilai boleh diubah dan kunci baru boleh ditambah.
+myObj.myThirdKey = true;
+
+// Jika anda cuba untuk akses nilai yang belum ditetapkan, anda akan mendapat
+// undefined.
+myObj.myFourthKey; // = undefined
+
+///////////////////////////////////
+// 3. Logik dan Struktur Kawalan
+
+// Syntax untuk bahagian ini adalah hampir sama dengan Java.
+
+// Struktur `if` berfungsi seperti yang anda jangkakan.
+var count = 1;
+if (count == 3){
+ // dinilai jika count ialah 3
+} else if (count == 4){
+ // dinilai jika count ialah 4
+} else {
+ // dinilai jika count bukan 3 atau 4
+}
+
+// Sama juga dengan `while`.
+while (true){
+ // Sebuah ulangan yang tidak terhingga!
+ // An infinite loop!
+}
+
+// Ulangan do-while adalah sama dengan ulangan while, kecuali ia akan diulang
+// sekurang-kurangnya sekali.
+var input;
+do {
+ input = getInput();
+} while (!isValid(input))
+
+// Ulangan `for` adalah sama dengan C dan Java:
+// Persiapan; kondisi untuk bersambung; pengulangan.
+for (var i = 0; i < 5; i++){
+ // akan berulang selama 5 kali
+}
+
+// Pernyataan ulangan For/In akan mengulang setiap ciri seluruh jaringan
+// 'prototype'
+var description = "";
+var person = {fname:"Paul", lname:"Ken", age:18};
+for (var x in person){
+ description += person[x] + " ";
+}
+
+// Jika anda cuma mahu mengambil kira ciri - ciri yang ditambah pada objek it
+// sendiri dan bukan 'prototype'nya, sila gunakan semakan hasOwnProperty()
+var description = "";
+var person = {fname:"Paul", lname:"Ken", age:18};
+for (var x in person){
+ if (person.hasOwnProperty(x)){
+ description += person[x] + " ";
+ }
+}
+
+// for/in tidak sepatutnya digunakan untuk mengulang sebuah Array di mana
+// indeks susunan adalah penting.
+// Tiada sebarang jaminan bahawa for/in akan mengembalikan indeks dalam
+// mana - mana susunan
+
+// && adalah logikal dan, || adalah logikal atau
+if (house.size == "big" && house.colour == "blue"){
+ house.contains = "bear";
+}
+if (colour == "red" || colour == "blue"){
+ // warna adalah sama ada 'red' atau 'blue'
+}
+
+// && dan || adalah "lintar pintas", di mana ia berguna untuk menetapkan
+// nilai asal.
+var name = otherName || "default";
+
+
+// Pernyataan `switch` menyemak persamaan menggunakan `===`.
+// gunakan pernyataan `break` selepas setiap kes
+// atau tidak, kes - kes selepas kes yang betul akan dijalankan juga.
+grade = 'B';
+switch (grade) {
+ case 'A':
+ console.log("Great job");
+ break;
+ case 'B':
+ console.log("OK job");
+ break;
+ case 'C':
+ console.log("You can do better");
+ break;
+ default:
+ console.log("Oy vey");
+ break;
+}
+
+
+///////////////////////////////////
+// 4. Functions, Skop dan Closures
+
+// Function javascript dideklarasikan dengan kata kunci `function`.
+function myFunction(thing){
+ return thing.toUpperCase();
+}
+myFunction("foo"); // = "FOO"
+
+// Perhatikan yang nilai yang dikembalikan mesti bermula pada baris yang sama
+// dengan kata kunci `return`, jika tidak, anda akan sentiasa mengembalikan
+// `undefined` disebabkan kemasukan 'semicolon' secara automatik. Sila berjaga -
+// jaga dengan hal ini apabila menggunakan Allman style.
+function myFunction(){
+ return // <- semicolon dimasukkan secara automatik di sini
+ {thisIsAn: 'object literal'}
+}
+myFunction(); // = undefined
+
+// Function javascript adalah objek kelas pertama, maka ia boleh diberikan
+// nama pembolehubah yang lain dan diberikan kepada function yang lain sebagai
+// input - sebagai contoh, apabila membekalkan pengendali event:
+function myFunction(){
+ // kod ini akan dijalankan selepas 5 saat
+}
+setTimeout(myFunction, 5000);
+// Nota: setTimeout bukan sebahagian daripada bahasa JS, tetapi ia disediakan
+// oleh pelayar web dan Node.js.
+
+// Satu lagi function yang disediakan oleh pelayar web adalah setInterval
+function myFunction(){
+ // kod ini akan dijalankan setiap 5 saat
+}
+setInterval(myFunction, 5000);
+
+// Objek function tidak perlu dideklarasikan dengan nama - anda boleh menulis
+// function yang tidak bernama didalam input sebuah function lain.
+setTimeout(function(){
+ // kod ini akan dijalankan dalam 5 saat
+}, 5000);
+
+// Javascript mempunyai skop function; function mempunyai skop mereka
+// tersendiri tetapi blok tidak.
+if (true){
+ var i = 5;
+}
+i; // = 5 - bukan undefined seperti yang anda jangkakan di dalam bahasa blok-skop
+
+// Ini telah menyebabkan corak biasa iaitu "immediately-executing anonymous
+// functions", yang mengelakkan pembolehubah sementara daripada bocor ke
+// skop global.
+(function(){
+ var temporary = 5;
+ // Kita boleh akses skop global dengan menetapkan nilai ke "objek global",
+ // iaitu dalam pelayar web selalunya adalah `window`. Objek global mungkin
+ // mempunyai nama yang berlainan dalam alam bukan pelayar web seperti Node.js.
+ window.permanent = 10;
+})();
+temporary; // akan menghasilkan ralat ReferenceError
+permanent; // = 10
+
+// Salah satu ciri terhebat Javascript ialah closure. Jika sebuah function
+// didefinisikan di dalam sebuah function lain, function yang di dalam akan
+// mempunyai akses kepada semua pembolehubah function yang di luar, mahupun
+// selepas function yang di luar tersebut selesai.
+function sayHelloInFiveSeconds(name){
+ var prompt = "Hello, " + name + "!";
+ // Function dalam diletakkan di dalam skop lokal secara asal, seperti
+ // ia dideklarasikan dengan `var`.
+ function inner(){
+ alert(prompt);
+ }
+ setTimeout(inner, 5000);
+ // setTimeout adalah tak segerak atau asinkroni, maka function sayHelloInFiveSeconds akan selesai serta merta, dan setTimeout akan memanggil
+ // inner selepas itu. Walaubagaimanapun, disebabkan inner terletak didalam
+ // sayHelloInFiveSeconds, inner tetap mempunyai akses kepada pembolehubah
+ // `prompt` apabila ia dipanggil.
+}
+sayHelloInFiveSeconds("Adam"); // akan membuka sebuah popup dengan "Hello, Adam!" selepas 5s
+
+///////////////////////////////////
+// 5. Lagi tentang Objek, Constructor dan Prototype
+
+// Objek boleh mengandungi function.
+var myObj = {
+ myFunc: function(){
+ return "Hello world!";
+ }
+};
+myObj.myFunc(); // = "Hello world!"
+
+// Apabila function sesebuah object dipanggil, ia boleh mengakses objek asalnya
+// dengan menggunakan kata kunci `this`.
+myObj = {
+ myString: "Hello world!",
+ myFunc: function(){
+ return this.myString;
+ }
+};
+myObj.myFunc(); // = "Hello world!"
+
+// Nilai sebenar yang ditetapkan kepada this akan ditentukan oleh bagaimana
+// sesebuah function itu dipanggil, bukan dimana ia didefinisikan. Oleh it,
+// sesebuah function tidak akan berfungsi jika ia dipanggil bukan pada konteks
+// objeknya.
+var myFunc = myObj.myFunc;
+myFunc(); // = undefined
+
+// Sebaliknya, sebuah function boleh ditetapkan kepada objek dan mendapat akses
+// kepada objek itu melalui `this`, walaupun ia tidak ditetapkan semasa ia
+// didefinisikan.
+var myOtherFunc = function(){
+ return this.myString.toUpperCase();
+}
+myObj.myOtherFunc = myOtherFunc;
+myObj.myOtherFunc(); // = "HELLO WORLD!"
+
+// Kita juga boleh menentukan konteks untuk sebuah function dijalankan apabila
+// ia dipanggil menggunakan `call` atau `apply`.
+
+var anotherFunc = function(s){
+ return this.myString + s;
+}
+anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"
+
+// Function `apply` adalah hampir sama, tetapi ia mengambil sebuah array
+// sebagai senarai input.
+
+anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!"
+
+// Ini sangat berguna apabila menggunakan sebuah function yang menerima senarai
+// input dan anda mahu menggunakan sebuah array sebagai input.
+
+Math.min(42, 6, 27); // = 6
+Math.min([42, 6, 27]); // = NaN (uh-oh!)
+Math.min.apply(Math, [42, 6, 27]); // = 6
+
+// Tetapi, `call` dan `apply` adalah hanya sementara, sebagaimana hidup ini.
+// Apabila kita mahu ia kekal, kita boleh menggunakan `bind`.
+
+var boundFunc = anotherFunc.bind(myObj);
+boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!"
+
+// `bind` boleh juga digunakan untuk menggunakan sebuah function tidak
+// sepenuhnya (curry).
+
+var product = function(a, b){ return a * b; }
+var doubler = product.bind(this, 2);
+doubler(8); // = 16
+
+// Apabila anda memanggil sebuah function dengan kata kunci `new`, sebuah
+// objek baru akan dicipta dan dijadikan tersedia kepada function itu melalui
+// kata kunci `this`. Function yang direka bentuk untuk dipanggil sebegitu rupa
+// dikenali sebagai constructors.
+
+var MyConstructor = function(){
+ this.myNumber = 5;
+}
+myNewObj = new MyConstructor(); // = {myNumber: 5}
+myNewObj.myNumber; // = 5
+
+// Setiap objek JavaScript mempunyai `prototype`. Apabila anda akses sesuatu
+// ciri sebuah objek yang tidak wujud dalam objek sebenar itu, interpreter akan
+// mencari ciri itu didalam `prototype`nya.
+
+// Sebahagian implementasi JS membenarkan anda untuk akses prototype sebuah
+// objek pada ciri istimewa `__proto__`. Walaupun ini membantu dalam menerangkan
+// mengenai prototypes, ia bukan sebahagian dari piawai; kita akan melihat
+// cara - cara piawai untuk menggunakan prototypes nanti.
+var myObj = {
+ myString: "Hello world!"
+};
+var myPrototype = {
+ meaningOfLife: 42,
+ myFunc: function(){
+ return this.myString.toLowerCase()
+ }
+};
+
+myObj.__proto__ = myPrototype;
+myObj.meaningOfLife; // = 42
+
+// Ini berfungsi untuk function juga.
+myObj.myFunc(); // = "hello world!"
+
+// Sudah pasti, jika ciri anda bukan pada prototype anda, prototype kepada
+// prototype anda akan disemak, dan seterusnya.
+myPrototype.__proto__ = {
+ myBoolean: true
+};
+myObj.myBoolean; // = true
+
+// Tiada penyalinan terlibat disini; setiap objek menyimpan rujukan kepada
+// prototypenya sendiri. Ini bermaksud, kita boleh mengubah prototypenya dan
+// pengubahsuaian itu akan dilihat dan berkesan dimana sahaja.
+myPrototype.meaningOfLife = 43;
+myObj.meaningOfLife; // = 43
+
+// Kami menyatakan yang `__proto__` adalah bukan piawai, dan tiada cara rasmi
+// untuk mengubah prototype sesebuah objek. Walaubagaimanapun, terdapat dua
+// cara untuk mencipta objek baru dengan sesebuah prototype.
+
+// Yang pertama ialah Object.create, yang merupakan tambahan terbaru pada JS,
+// dan oleh itu tiada dalam semua implementasi buat masa ini.
+var myObj = Object.create(myPrototype);
+myObj.meaningOfLife; // = 43
+
+// Cara kedua, yang boleh digunakan dimana sahaja, adalah berkaitan dengan
+// constructor. Constructors mempunyai sebuah ciri yang dipanggil prototype.
+// Ini *bukan* prototype constructor terbabit; tetapi, ia adalah prototype yang
+// diberikan kepada objek baru apabila ia dicipta menggunakan constructor dan
+// kata kunci new.
+MyConstructor.prototype = {
+ myNumber: 5,
+ getMyNumber: function(){
+ return this.myNumber;
+ }
+};
+var myNewObj2 = new MyConstructor();
+myNewObj2.getMyNumber(); // = 5
+myNewObj2.myNumber = 6
+myNewObj2.getMyNumber(); // = 6
+
+// Jenis yang terbina sedia seperti string dan nombor juga mempunyai constructor
+// yang mencipta objek pembalut yang serupa.
+var myNumber = 12;
+var myNumberObj = new Number(12);
+myNumber == myNumberObj; // = true
+
+// Kecuali, mereka sebenarnya tak sama sepenuhnya.
+typeof myNumber; // = 'number'
+typeof myNumberObj; // = 'object'
+myNumber === myNumberObj; // = false
+if (0){
+ // Kod ini tidak akan dilaksanakan, kerana 0 adalah tidak benar.
+}
+
+// Walaubagaimanapun, pembalut objek dan jenis terbina yang biasa berkongsi
+// prototype, maka sebagai contoh, anda sebenarnya boleh menambah fungsi
+// kepada string.
+String.prototype.firstCharacter = function(){
+ return this.charAt(0);
+}
+"abc".firstCharacter(); // = "a"
+
+// Fakta ini selalu digunakan dalam "polyfilling", iaitu melaksanakan fungsi
+// baru JavaScript didalam subset JavaScript yang lama, supaya ia boleh
+// digunakan di dalam persekitaran yang lama seperti pelayar web yang lama.
+
+// Sebagai contoh, kami menyatakan yang Object.create belum lagi tersedia
+// di semua implementasi, tetapi kita masih boleh menggunakannya dengan polyfill:
+if (Object.create === undefined){ // jangan ganti jika ia sudah wujud
+ Object.create = function(proto){
+ // buat satu constructor sementara dengan prototype yang betul
+ var Constructor = function(){};
+ Constructor.prototype = proto;
+ // kemudian gunakannya untuk mencipta objek baru yang diberikan
+ // prototype yang betul
+ return new Constructor();
+ }
+}
+```
+## Bacaan Lanjut
+
+[Mozilla Developer Network][1] menyediakan dokumentasi yang sangat baik untuk
+JavaScript kerana ia digunakan di dalam pelayar - pelayar web. Tambahan pula,
+ia adalah sebuah wiki, maka, sambil anda belajar lebih banyak lagi, anda boleh
+membantu orang lain dengan berkongsi pengetahuan anda.
+
+[A re-introduction to JavaScript][2] oleh MDN meliputi semua konsep yang
+diterangkan di sini dengan lebih terperinci. Panduan ini menerangkan bahasa
+aturcara JavaScript dengan agak mudah; jika anda mahu belajar lebih lanjut
+tentang menggunakan JavaScript didalam laman web, mulakan dengan mempelajari
+tentang [Document Object Model][3].
+
+[Learn Javascript by Example and with Challenges][4] adalah variasi panduan ini
+dengan cabaran yang tersedia pakai.
+
+[JavaScript Garden][5] pula adalah panduan yang lebih terperinci mengenai
+semua bahagian bahasa aturcara ini yang bertentangan dengan naluri atau
+kebiasaan.
+
+[JavaScript: The Definitive Guide][6] adalah panduan klasik dan buku rujukan.
+
+Selain daripada penyumbang terus kepada artikel ini, sebahagian kandungannya
+adalah adaptasi daripada tutorial Python Louie Dinh di dalam laman web ini,
+dan [JS Tutorial][7] di Mozilla Developer Network.
+
+
+[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript
+[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
+[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core
+[4]: http://www.learneroo.com/modules/64/nodes/350
+[5]: http://bonsaiden.github.io/JavaScript-Garden/
+[6]: http://www.amazon.com/gp/product/0596805527/
+[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
diff --git a/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/nim.html.markdown b/nim.html.markdown
index c9548a1c..4901ebfe 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
+```javascript
var # Declare (and assign) variables,
letter: char = 'n' # with or without type annotations
lang = "N" & "im"
@@ -235,7 +235,7 @@ proc ask(question: string): Answer =
else: echo("Please be clear: yes or no")
proc addSugar(amount: int = 2) = # Default amount is 2, returns nothing
- assert(amount > 0 or amount < 9000, "Crazy Sugar")
+ assert(amount > 0 and amount < 9000, "Crazy Sugar")
for a in 1..amount:
echo(a, " sugar...")
diff --git a/nl-nl/brainfuck-nl.html.markdown b/nl-nl/bf.html.markdown
index cd12b1d0..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/"]
@@ -15,7 +15,7 @@ minimalistische Turing-complete programmeertaal met maar acht commando's.
```
Elk karakter behalve "><+-.,[]" (en de quotes) wordt genegeerd.
-Brainfuck wordt gerepresenteerd door een array met 30,000 cellen die initieel
+Brainfuck wordt gerepresenteerd door een array met 30.000 cellen die initieel
gevuld is met nullen en een pointer die wijst naar de huidige cel.
Dit zijn de acht commando's:
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/nl-nl/yaml-nl.html.markdown b/nl-nl/yaml-nl.html.markdown
new file mode 100644
index 00000000..a4a9d5fc
--- /dev/null
+++ b/nl-nl/yaml-nl.html.markdown
@@ -0,0 +1,139 @@
+---
+language: yaml
+filename: learnyaml-nl.yaml
+contributors:
+ - ["Adam Brenecki", "https://github.com/adambrenecki"]
+translators:
+ - ["Niels van Velzen", "https://nielsvanvelzen.me"]
+lang: nl-nl
+---
+
+YAML is een data serialisatie taal ontworpen om snel te kunnen worden begrepen door mensen.
+
+Het is een strikte superset van JSON en bevat nieuwe regels en een stricte manier van inspringen, zoals bij Python. In tegenstelling tot Python kan je alleen geen tab tekens gebruiken.
+
+```yaml
+# Commentaar in YAML ziet er zo uit
+
+################
+# SCALAR TYPES #
+################
+
+# Ons hoofd object (Wat in het hele document gebruikt wordt) is een map,
+# dit staat gelijk aan een dictionary, hash of object in andere talen.
+sleutel: waarde
+nog_een_sleutel: Een andere waarde
+nummer_waarde: 100
+wetenschappelijke_waarde: 1e+12
+boolean_waarde: true
+null_waarde: null
+sleutel met spaties: waarde
+# Merk op dat strings niet verplicht in quotes moeten, maar dit kan wel.
+quote_waarde: "Een string in quotes"
+"Ook sleutels kunnen in quotes": "Dit is bijvoorbeeld handig als je een dubbelepunt wilt gebruiken in je key"
+
+# Tekst over meerdere lijnen kan je schrijven als een 'letterlijk blok' (met |)
+# Of een 'gevouwen blok' (met >)
+letterlijk_blok: |
+ Dit hele blok met tekst is de waarde van de 'letterlijk_blok' sleutel,
+ met nieuwe lijnen behouden.
+
+ Het blok blijft door gaan tot het geeindigd wordt door korter te inspringen.
+
+ Lijnen die groter zijn ingesprongen behouden dit.
+gevouwen_stijl: >
+ Dit blok met tekst zal de waarde zijn van 'gevouwen_stijl',
+ maar deze keer zullen alle nieuwe lijnen worden vervangen met een spatie.
+
+ Lege lijnen, zoals hierboven, zullen worden vertaald naar een nieuwe lijn.
+
+ Meer ingesprongen lijnen zullen hun nieuwe lijnen ook behouden,
+ deze tekst zal over 2 lijnen te zien zijn.
+
+####################
+# COLLECTION TYPES #
+####################
+
+# Nesten wordt bereikt met inspringen.
+geneste_map:
+ sleutel: waarde
+ andere_sleutel: andere waarde
+ andere_geneste_map:
+ hallo: wereld
+
+# In een map is een sleutel niet verplicht om een string te gebruiken
+0.25: een float als sleutel
+
+# Sleutels kunnen ook meerdere lijnen gebruiken met behulp van het vraagteken
+? |
+ Dit is een sleutel
+ met meerdere lijnen
+: en dit is de waarde
+
+# YAML staat ook collection types toe in sleutels, maar veel programmeertalen
+# zullen hierover klagen.
+
+# Sequences (gelijk aan lijsten of arrays) zien er zo uit:
+een_sequence:
+ - Item 1
+ - Item 2
+ - 0.5 # sequences kunnen meerdere type waardes bevatten.
+ - Item 4
+ - sleutel: waarde
+ andere_sleutel: andere waarde
+ -
+ - Dit is een sequence
+ - in een andere sequence
+
+# Doordat YAML een superset van JSON is kan je ook JSON-stijl mappen en
+# sequences maken:
+json_map: {"sleutel": "waarde"}
+json_seq: [3, 2, 1, "takeoff"]
+
+#######################
+# EXTRA YAML FUNCTIES #
+#######################
+
+# YAML heeft ook een handige functie genaamd 'anchors' (ankers), deze laten je
+# makkelijk de waarde van ergens anders in je document kopieëren. Beide sleutels
+# krijgen dezelfde waarde:
+geankert_content: &anker_naam Deze string zal verschijnen als waarde voor de twee sleutels
+andere_anker: *anker_naam
+
+# YAML heeft ook tags, deze gebruik je om een expliciet type te verklaren
+expliciete_string: !!str 0.5
+# Sommige parsers gebruiken taal specifieke tags, zoals deze voor Python's
+# complexe nummer type:
+python_complex_nummer: !!python/complex 1+2j
+
+####################
+# EXTRA YAML TYPES #
+####################
+
+# Strings en nummer zijn niet de enige types die YAML begrijpt.
+# ISO opgemaakte datum en datumtijd notaties werken ook:
+datumtijd: 2001-12-15T02:59:43.1Z
+datumtijd_met_spaties: 2001-12-14 21:59:43.10 -5
+datum: 2002-12-14
+
+# De !!binary tag geeft aan dat de string een base64-gecodeerde
+# binary blob is.
+gif_bestand: !!binary |
+ R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
+ OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+ +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
+ AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
+
+# YAML heeft ook een set type, dat ziet er zo uit:
+set:
+ ? item1
+ ? item2
+ ? item3
+
+# Zoals in Python zijn sets gewoon mappen met null waardes;
+# bovenstaand is gelijk aan:
+set2:
+ item1: null
+ item2: null
+ item3: null
+```
diff --git a/objective-c.html.markdown b/objective-c.html.markdown
index 89901308..097cb846 100644
--- a/objective-c.html.markdown
+++ b/objective-c.html.markdown
@@ -1,25 +1,28 @@
---
-
language: Objective-C
contributors:
- ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
- ["Yannick Loriot", "https://github.com/YannickL"]
- ["Levi Bostian", "https://github.com/levibostian"]
- ["Clayton Walker", "https://github.com/cwalk"]
+ - ["Fernando Valverde", "http://visualcosita.xyz"]
filename: LearnObjectiveC.m
-
---
Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.
-```objective_c
+```objective-c
// Single-line comments start with //
/*
Multi-line comments look like this
*/
+// XCode supports pragma mark directive that improve jump bar readability
+#pragma mark Navigation Functions // New tag on jump bar named 'Navigation Functions'
+#pragma mark - Navigation Functions // Same tag, now with a separator
+
// Imports the Foundation headers with #import
// Use <> to import global files (in general frameworks)
// Use "" to import local files (from project)
@@ -149,6 +152,12 @@ int main (int argc, const char * argv[])
[mutableDictionary setObject:@"value2" forKey:@"key2"];
[mutableDictionary removeObjectForKey:@"key1"];
+ // Change types from Mutable To Immutable
+ //In general [object mutableCopy] will make the object mutable whereas [object copy] will make the object immutable
+ NSMutableDictionary *aMutableDictionary = [aDictionary mutableCopy];
+ NSDictionary *mutableDictionaryChanged = [mutableDictionary copy];
+
+
// Set object
NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil];
NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order)
@@ -593,6 +602,52 @@ int main (int argc, const char * argv[]) {
@end
+// Starting in Xcode 7.0, you can create Generic classes,
+// allowing you to provide greater type safety and clarity
+// without writing excessive boilerplate.
+@interface Result<__covariant A> : NSObject
+
+- (void)handleSuccess:(void(^)(A))success
+ failure:(void(^)(NSError *))failure;
+
+@property (nonatomic) A object;
+
+@end
+
+// we can now declare instances of this class like
+Result<NSNumber *> *result;
+Result<NSArray *> *result;
+
+// Each of these cases would be equivalent to rewriting Result's interface
+// and substituting the appropriate type for A
+@interface Result : NSObject
+- (void)handleSuccess:(void(^)(NSArray *))success
+ failure:(void(^)(NSError *))failure;
+@property (nonatomic) NSArray * object;
+@end
+
+@interface Result : NSObject
+- (void)handleSuccess:(void(^)(NSNumber *))success
+ failure:(void(^)(NSError *))failure;
+@property (nonatomic) NSNumber * object;
+@end
+
+// It should be obvious, however, that writing one
+// Class to solve a problem is always preferable to writing two
+
+// Note that Clang will not accept generic types in @implementations,
+// so your @implemnation of Result would have to look like this:
+
+@implementation Result
+
+- (void)handleSuccess:(void (^)(id))success
+ failure:(void (^)(NSError *))failure {
+ // Do something
+}
+
+@end
+
+
///////////////////////////////////////
// Protocols
///////////////////////////////////////
@@ -682,7 +737,7 @@ addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any pa
mutableVar = 32; // Assigning new value to __block variable.
return n + outsideVar; // Return statements are optional.
}
-int addUp = add(10 + 16); // Calls block code with arguments.
+int addUp = addUp(10 + 16); // Calls block code with arguments.
// Blocks are often used as arguments to functions to be called later, or for callbacks.
@implementation BlockExample : NSObject
diff --git a/ocaml.html.markdown b/ocaml.html.markdown
index 02435e4d..a346550c 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" ;;
@@ -196,7 +196,7 @@ let (~/) x = 1.0 /. x ;;
~/4.0 (* = 0.25 *)
-(*** Built-in datastructures ***)
+(*** Built-in data structures ***)
(* Lists are enclosed in square brackets, items are separated by
semicolons. *)
@@ -341,10 +341,10 @@ let say x =
say (Cat "Fluffy") ;; (* "Fluffy says meow". *)
-(** Traversing datastructures with pattern matching **)
+(** Traversing data structures with pattern matching **)
(* Recursive types can be traversed with pattern matching easily.
- Let's see how we can traverse a datastructure of the built-in list type.
+ Let's see how we can traverse a data structure of the built-in list type.
Even though the built-in cons ("::") looks like an infix operator,
it's actually a type constructor and can be matched like any other. *)
let rec sum_list l =
diff --git a/perl.html.markdown b/perl.html.markdown
index 4e172406..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
@@ -102,6 +142,11 @@ for (@elements) {
print;
}
+# 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
@@ -149,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 63c0830a..5082a433 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -1,19 +1,16 @@
---
-name: perl6
category: language
language: perl6
filename: learnperl6.pl
contributors:
- - ["Nami-Doc", "http://github.com/Nami-Doc"]
+ - ["vendethiel", "http://github.com/vendethiel"]
---
Perl 6 is a highly capable, feature-rich programming language made for at
least the next hundred years.
The primary Perl 6 compiler is called [Rakudo](http://rakudo.org), which runs on
-the JVM and [the MoarVM](http://moarvm.com) and
-[prior to March 2015](http://pmthium.com/2015/02/suspending-rakudo-parrot/),
-[the Parrot VM](http://parrot.org/).
+the JVM and [the MoarVM](http://moarvm.com).
Meta-note : the triple pound signs are here to denote headlines,
double paragraphs, and single notes.
@@ -75,7 +72,7 @@ say @array; #=> a 6 b
# except they get "flattened" (hash context), removing duplicated keys.
my %hash = 1 => 2,
3 => 4;
-my %hash = autoquoted => "key", # keys get auto-quoted
+my %hash = foo => "bar", # keys get auto-quoted
"some other" => "value", # trailing commas are okay
;
my %hash = <key1 value1 key2 value2>; # you can also create a hash
@@ -96,7 +93,6 @@ say %hash<key2>; # If it's a string, you can actually use <>
# (`{key1}` doesn't work, as Perl6 doesn't have barewords)
## * Subs (subroutines, or functions in most other languages).
-# Stored in variable, they use `&`.
sub say-hello { say "Hello, world" }
sub say-hello-to(Str $name) { # You can provide the type of an argument
@@ -107,8 +103,8 @@ 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)` if I don't have an argument passed,
- or I'll return my argument";
+ 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;
}
with-optional; # returns Any
@@ -125,14 +121,14 @@ hello-to('You'); #=> Hello, You !
## You can also, by using a syntax akin to the one of hashes (yay unified syntax !),
## pass *named* arguments to a `sub`.
-# They're optional, and will default to "Any" (Perl's "null"-like value).
+# They're optional, and will default to "Any".
sub with-named($normal-arg, :$named) {
say $normal-arg + $named;
}
with-named(1, named => 6); #=> 7
# There's one gotcha to be aware of, here:
# If you quote your key, Perl 6 won't be able to see it at compile time,
-# and you'll have a single Pair object as a positional paramater,
+# and you'll have a single Pair object as a positional parameter,
# which means this fails:
with-named(1, 'named' => 6);
@@ -162,7 +158,7 @@ named-def; #=> 5
named-def(def => 15); #=> 15
# Since you can omit parenthesis to call a function with no arguments,
-# you need "&" in the name to capture `say-hello`.
+# you need "&" in the name to store `say-hello` in a variable.
my &s = &say-hello;
my &other-s = sub { say "Anonymous function !" }
@@ -173,8 +169,8 @@ sub as-many($head, *@rest) { # `*@` (slurpy) will basically "take everything els
say @rest.join(' / ') ~ " !";
}
say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday !
- # Note that the splat did not consume
- # the parameter before.
+ # Note that the splat (the *) did not
+ # consume the parameter before.
## You can call a function with an array using the
# "argument list flattening" operator `|`
@@ -197,7 +193,7 @@ sub mutate($n is rw) {
say "\$n is now $n !";
}
-# If what you want is a copy instead, use `is copy`.
+# If what you want a copy instead, use `is copy`.
# A sub itself returns a container, which means it can be marked as rw:
my $x = 42;
@@ -234,7 +230,7 @@ say "Quite truthy" if True;
# - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages)
my $a = $condition ?? $value-if-true !! $value-if-false;
-# - `given`-`when` looks like other languages `switch`, but much more
+# - `given`-`when` looks like other languages' `switch`, but much more
# powerful thanks to smart matching and thanks to Perl 6's "topic variable", $_.
#
# This variable contains the default argument of a block,
@@ -377,10 +373,14 @@ say @array[^10]; # you can pass arrays as subscripts and it'll return
say join(' ', @array[15..*]); #=> 15 16 17 18 19
# which is equivalent to:
say join(' ', @array[-> $n { 15..$n }]);
+# Note: if you try to do either of those with an infinite array,
+# you'll trigger an infinite loop (your program won't finish)
# You can use that in most places you'd expect, even assigning to an array
my @numbers = ^20;
-my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99
+
+# Here numbers increase by "6"; more on `...` operator later.
+my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99;
@numbers[5..*] = 3, 9 ... *; # even though the sequence is infinite,
# only the 15 needed values will be calculated.
say @numbers; #=> 0 1 2 3 4 3 9 15 21 [...] 81 87
@@ -525,7 +525,7 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`)
# The constructs for declaring types are "class", "role",
# which you'll see later.
-# For now, let us examinate "subset":
+# For now, let us examine "subset":
# a "subset" is a "sub-type" with additional checks.
# For example: "a very big integer is an Int that's greater than 500"
# You can specify the type you're subtyping (by default, Any),
@@ -608,27 +608,26 @@ sub foo {
bar(); # call `bar` in-place
}
sub bar {
- say $*foo; # `$*a` will be looked in the call stack, and find `foo`'s,
+ say $*foo; # `$*foo` will be looked in the call stack, and find `foo`'s,
# even though the blocks aren't nested (they're call-nested).
#=> 1
}
### Object Model
-## Perl 6 has a quite comprehensive object model
# You declare a class with the keyword `class`, fields with `has`,
-# methods with `method`. Every field to private, and is named `$!attr`,
-# but you have `$.` to get a public (immutable) accessor along with it.
-# (using `$.` is like using `$!` plus a `method` with the same name)
+# methods with `method`. Every attribute that is private is named `$!attr`.
+# Immutable public attributes are named `$.attr`
+# (you can make them mutable with `is rw`)
-# (Perl 6's object model ("SixModel") is very flexible,
+# Perl 6's object model ("SixModel") is very flexible,
# and allows you to dynamically add methods, change semantics, etc ...
# (this will not be covered here, and you should refer to the Synopsis).
class A {
has $.field; # `$.field` is immutable.
# From inside the class, use `$!field` to modify it.
- has $.other-field is rw; # You can obviously mark a public field `rw`.
+ has $.other-field is rw; # You can mark a public attribute `rw`.
has Int $!private-field = 10;
method get-value {
@@ -656,7 +655,6 @@ $a.other-field = 10; # This, however, works, because the public field
# is mutable (`rw`).
## Perl 6 also has inheritance (along with multiple inheritance)
-# (though considered a misfeature by many)
class A {
has $.val;
@@ -738,7 +736,7 @@ try {
# You can throw an exception using `die`:
die X::AdHoc.new(payload => 'Error !');
-# You can access the last exception with `$!` (usually used in a `CATCH` block)
+# You can access the last exception with `$!` (use `$_` in a `CATCH` block)
# There are also some subtelties to exceptions. Some Perl 6 subs return a `Failure`,
# which is a kind of "unthrown exception". They're not thrown until you tried to look
@@ -751,7 +749,7 @@ fail "foo"; # We're not trying to access the value, so no problem.
try {
fail "foo";
CATCH {
- default { say "It threw because we try to get the fail's value!" }
+ default { say "It threw because we tried to get the fail's value!" }
}
}
@@ -763,25 +761,21 @@ try {
### Packages
# Packages are a way to reuse code. Packages are like "namespaces", and any
# element of the six model (`module`, `role`, `class`, `grammar`, `subset`
-# and `enum`) are actually packages. (Packages are the lowest common denomitor)
+# and `enum`) are actually packages. (Packages are the lowest common denominator)
# Packages are important - especially as Perl is well-known for CPAN,
# the Comprehensive Perl Archive Network.
-# You usually don't use packages directly: you use `class Package::Name::Here;`,
-# or if you only want to export variables/subs, you can use `module`:
+# You're not supposed to use the package keyword, usually:
+# you use `class Package::Name::Here;` to declare a class,
+# or if you only want to export variables/subs, you can use `module`:
module Hello::World { # Bracketed form
# If `Hello` doesn't exist yet, it'll just be a "stub",
# that can be redeclared as something else later.
# ... declarations here ...
}
-module Parse::Text; # file-scoped form
+unit module Parse::Text; # file-scoped form
grammar Parse::Text::Grammar { # A grammar is a package, which you could `use`
}
-# NOTE for Perl 5 users: even though the `package` keyword exists,
-# the braceless form is invalid (to catch a "perl5ism"). This will error out:
-# package Foo; # because Perl 6 will think the entire file is Perl 5
-# Just use `module` or the brace version of `package`.
-
# You can use a module (bring its declarations into scope) with `use`
use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module
say from-json('[1]').perl; #=> [1]
@@ -797,10 +791,8 @@ my $actions = JSON::Tiny::Actions.new;
# You've already seen `my` and `has`, we'll now explore the others.
## * `our` (happens at `INIT` time -- see "Phasers" below)
-# Along with `my`, there are several others declarators you can use.
-# The first one you'll want for the previous part is `our`.
+# It's like `my`, but it also creates a package variable.
# (All packagish things (`class`, `role`, etc) are `our` by default)
-# it's like `my`, but it also creates a package variable:
module Foo::Bar {
our $n = 1; # note: you can't put a type constraint on an `our` variable
our sub inc {
@@ -811,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
@@ -829,7 +820,7 @@ constant why-not = 5, 15 ... *;
say why-not[^5]; #=> 5 15 25 35 45
## * `state` (happens at run time, but only once)
-# State variables are only executed one time
+# State variables are only initialized one time
# (they exist in other langages such as C as `static`)
sub fixed-rand {
state $val = rand;
@@ -862,7 +853,7 @@ for ^5 -> $a {
## * Compile-time phasers
BEGIN { say "[*] Runs at compile time, as soon as possible, only once" }
-CHECK { say "[*] Runs at compile time, instead as late as possible, only once" }
+CHECK { say "[*] Runs at compile time, as late as possible, only once" }
## * Run-time phasers
INIT { say "[*] Runs at run time, as soon as possible, only once" }
@@ -870,10 +861,21 @@ END { say "Runs at run time, as late as possible, only once" }
## * Block phasers
ENTER { say "[*] Runs everytime you enter a block, repeats on loop blocks" }
-LEAVE { say "Runs everytime you leave a block, even when an exception happened. Repeats on loop blocks." }
+LEAVE { say "Runs everytime you leave a block, even when an exception
+ happened. Repeats on loop blocks." }
+
+PRE { say "Asserts a precondition at every block entry,
+ before ENTER (especially useful for loops)" }
+# exemple:
+for 0..2 {
+ PRE { $_ > 1 } # This is going to blow up with "Precondition failed"
+}
-PRE { say "Asserts a precondition at every block entry, before ENTER (especially useful for loops)" }
-POST { say "Asserts a postcondition at every block exit, after LEAVE (especially useful for loops)" }
+POST { say "Asserts a postcondition at every block exit,
+ after LEAVE (especially useful for loops)" }
+for 0..2 {
+ POST { $_ < 2 } # This is going to blow up with "Postcondition failed"
+}
## * Block/exceptions phasers
sub {
@@ -891,12 +893,12 @@ for ^5 {
## * Role/class phasers
COMPOSE { "When a role is composed into a class. /!\ NOT YET IMPLEMENTED" }
-# They allow for cute trick or clever code ...:
-say "This code took " ~ (time - CHECK time) ~ "s to run";
+# They allow for cute tricks or clever code ...:
+say "This code took " ~ (time - CHECK time) ~ "s to compile";
# ... or clever organization:
sub do-db-stuff {
- ENTER $db.start-transaction; # New transaction everytime we enter the sub
+ $db.start-transaction; # start a new transaction
KEEP $db.commit; # commit the transaction if all went well
UNDO $db.rollback; # or rollback if all hell broke loose
}
@@ -1020,7 +1022,7 @@ sub circumfix:<[ ]>(Int $n) {
$n ** $n
}
say [5]; #=> 3125
- # circumfix is around. Again, not whitespace.
+ # circumfix is around. Again, no whitespace.
sub postcircumfix:<{ }>(Str $s, Int $idx) {
# post-circumfix is
@@ -1052,9 +1054,9 @@ postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that)
# Basically, they're operators that apply another operator.
## * Reduce meta-operator
-# It's a prefix meta-operator that takes a binary functions and
+# It's a prefix meta-operator that takes a binary function and
# one or many lists. If it doesn't get passed any argument,
-# it either return a "default value" for this operator
+# it either returns a "default value" for this operator
# (a meaningless value) or `Any` if there's none (examples below).
#
# Otherwise, it pops an element from the list(s) one at a time, and applies
@@ -1089,7 +1091,7 @@ say [[&add]] 1, 2, 3; #=> 6
# This one is an infix meta-operator than also can be used as a "normal" operator.
# It takes an optional binary function (by default, it just creates a pair),
# and will pop one value off of each array and call its binary function on these
-# until it runs out of elements. It runs the an array with all these new elements.
+# until it runs out of elements. It returns an array with all of these new elements.
(1, 2) Z (3, 4); # ((1, 3), (2, 4)), since by default, the function makes an array
1..3 Z+ 4..6; # (5, 7, 9), using the custom infix:<+> function
@@ -1109,8 +1111,7 @@ say [[&add]] 1, 2, 3; #=> 6
# (and might include a closure), and on the right, a value or the predicate
# that says when to stop (or Whatever for a lazy infinite list).
my @list = 1, 2, 3 ... 10; # basic deducing
-#my @list = 1, 3, 6 ... 10; # this throws you into an infinite loop,
- # because Perl 6 can't figure out the end
+#my @list = 1, 3, 6 ... 10; # this dies because Perl 6 can't figure out the end
my @list = 1, 2, 3 ...^ 10; # as with ranges, you can exclude the last element
# (the iteration when the predicate matches).
my @list = 1, 3, 9 ... * > 30; # you can use a predicate
@@ -1222,7 +1223,7 @@ so 'abbbbbbc' ~~ / a b ** 3..* c /; # `True` (infinite ranges are okay)
# they use a more perl6-ish syntax:
say 'fooa' ~~ / f <[ o a ]>+ /; #=> 'fooa'
# You can use ranges:
-say 'aeiou' ~~ / a <[ e..w ]> /; #=> 'aeiou'
+say 'aeiou' ~~ / a <[ e..w ]> /; #=> 'ae'
# Just like in normal regexes, if you want to use a special character, escape it
# (the last one is escaping a space)
say 'he-he !' ~~ / 'he-' <[ a..z \! \ ]> + /; #=> 'he-he !'
@@ -1242,14 +1243,14 @@ so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (the + doesn't replace the left
# Group: you can group parts of your regexp with `[]`.
# These groups are *not* captured (like PCRE's `(?:)`).
so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing
-so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /;
+so 'foo012012bar' ~~ / foo [ '01' <[0..9]> ] + bar /;
# The previous line returns `True`.
-# We match the "abc" 1 or more time (the `+` was applied to the group).
+# We match the "012" 1 or more time (the `+` was applied to the group).
# But this does not go far enough, because we can't actually get back what
# we matched.
# Capture: We can actually *capture* the results of the regexp, using parentheses.
-so 'fooABCABCbar' ~~ / foo ( A B C ) + bar /; # `True`. (using `so` here, `$/` below)
+so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # `True`. (using `so` here, `$/` below)
# So, starting with the grouping explanations.
# As we said before, our `Match` object is available as `$/`:
@@ -1287,10 +1288,12 @@ say $/[0][0].Str; #=> ~
# This stems from a very simple fact: `$/` does not contain strings, integers or arrays,
# it only contains match objects. These contain the `.list`, `.hash` and `.Str` methods.
-# (but you can also just use `match<key>` for hash access and `match[idx]` for array access)
+# (but you can also just use `match<key>` for hash access
+# and `match[idx]` for array access)
say $/[0].list.perl; #=> (Match.new(...),).list
- # We can see it's a list of Match objects. Those contain a bunch of infos:
- # where the match started/ended, the "ast" (see actions later), etc.
+ # We can see it's a list of Match objects. Those contain
+ # a bunch of infos: where the match started/ended,
+ # the "ast" (see actions later), etc.
# You'll see named capture below with grammars.
## Alternatives - the `or` of regexps
@@ -1326,9 +1329,9 @@ 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 argument
+# 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`)
# and will even go as far as to autogenerate a `--help`
sub MAIN($name) { say "Hello, $name !" }
@@ -1346,7 +1349,7 @@ multi MAIN('add', $key, $value, Bool :$replace) { ... }
multi MAIN('remove', $key) { ... }
multi MAIN('import', File, Str :$as) { ... } # omitting parameter name
# This produces:
-# $ perl 6 cli.pl
+# $ perl6 cli.pl
# Usage:
# t.pl [--replace] add <key> <value>
# t.pl remove <key>
@@ -1429,7 +1432,7 @@ for <well met young hero we shall meet later> {
# A flip-flop can change state as many times as needed:
for <test start print it stop not printing start print again stop not anymore> {
.say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop",
- #=> "print this printing again"
+ #=> "print it print again"
}
# you might also use a Whatever Star,
@@ -1461,4 +1464,3 @@ If you want to go further, you can:
- Come along on `#perl6` at `irc.freenode.net`. The folks here are always helpful.
- Check the [source of Perl 6's functions and classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset easier to implement and optimize).
- Read [the language design documents](http://design.perl6.org). They explain P6 from an implementor point-of-view, but it's still very interesting.
-
diff --git a/php.html.markdown b/php.html.markdown
index 2b1fe1dc..6944390c 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -12,7 +12,7 @@ This document describes PHP 5+.
<?php // PHP code must be enclosed with <?php tags
// If your php file only contains PHP code, it is best practice
-// to omit the php closing tag.
+// to omit the php closing tag to prevent accidental output.
// Two forward slashes start a one-line comment.
@@ -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;
@@ -103,6 +105,9 @@ END;
// String concatenation is done with .
echo 'This string ' . 'is concatenated';
+// Strings can be passed in as parameters to echo
+echo 'Multiple', 'Parameters', 'Valid'; // Returns 'MultipleParametersValid'
+
/********************************
* Constants
@@ -113,10 +118,12 @@ echo 'This string ' . 'is concatenated';
// 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'
-// access to a constant is possible by direct using the choosen name
-echo 'This outputs '.FOO;
/********************************
@@ -135,12 +142,17 @@ $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"
// Add an element to the end of an array
$array[] = 'Four';
+// or
+array_push($array, 'Five');
// Remove element from array
unset($array[3]);
@@ -155,9 +167,9 @@ echo('Hello World!');
print('Hello World!'); // The same as echo
-// echo is actually a language construct, so you can drop the parentheses.
+// echo and print are language constructs too, so you can drop the parentheses
echo 'Hello World!';
-print 'Hello World!'; // So is print
+print 'Hello World!';
$paragraph = 'paragraph';
@@ -215,7 +227,11 @@ assert($a !== $d);
assert(1 === '1');
assert(1 !== '1');
-// spaceship operator since PHP 7
+// 'Spaceship' operator (since PHP 7)
+// Returns 0 if values on either side are equal
+// Returns 1 if value on the left is greater
+// Returns -1 if the value on the right is greater
+
$a = 100;
$b = 1000;
@@ -379,7 +395,7 @@ for ($i = 0; $i < 5; $i++) {
// Define a function with "function":
function my_function () {
- return 'Hello';
+ return 'Hello';
}
echo my_function(); // => "Hello"
@@ -388,8 +404,8 @@ echo my_function(); // => "Hello"
// number of letters, numbers, or underscores.
function add ($x, $y = 1) { // $y is optional and defaults to 1
- $result = $x + $y;
- return $result;
+ $result = $x + $y;
+ return $result;
}
echo add(4); // => 5
@@ -400,21 +416,21 @@ echo add(4, 2); // => 6
// Since PHP 5.3 you can declare anonymous functions;
$inc = function ($x) {
- return $x + 1;
+ return $x + 1;
};
echo $inc(2); // => 3
function foo ($x, $y, $z) {
- echo "$x - $y - $z";
+ echo "$x - $y - $z";
}
// Functions can return functions
function bar ($x, $y) {
- // Use 'use' to bring in outside variables
- return function ($z) use ($x, $y) {
- foo($x, $y, $z);
- };
+ // Use 'use' to bring in outside variables
+ return function ($z) use ($x, $y) {
+ foo($x, $y, $z);
+ };
}
$bar = bar('A', 'B');
@@ -426,6 +442,31 @@ echo $function_name(1, 2); // => 3
// Useful for programatically determining which function to run.
// Or, use call_user_func(callable $callback [, $parameter [, ... ]]);
+
+// You can get the all the parameters passed to a function
+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 |
+
+// Since PHP 5.6 you can get a variable number of arguments
+function variable($word, ...$list) {
+ echo $word . " || ";
+ foreach ($list as $item) {
+ echo $item . ' | ';
+ }
+}
+
+variable("Separate", "Hello", "World") // Separate || Hello | World |
+
/********************************
* Includes
*/
@@ -693,8 +734,111 @@ use My\Namespace as SomeOtherNamespace;
$cls = new SomeOtherNamespace\MyClass();
+
+/**********************
+* Late Static Binding
+*
+*/
+
+class ParentClass {
+ public static function who() {
+ echo "I'm a " . __CLASS__ . "\n";
+ }
+ public static function test() {
+ // self references the class the method is defined within
+ self::who();
+ // static references the class the method was invoked on
+ static::who();
+ }
+}
+
+ParentClass::test();
+/*
+I'm a ParentClass
+I'm a ParentClass
+*/
+
+class ChildClass extends ParentClass {
+ public static function who() {
+ echo "But I'm " . __CLASS__ . "\n";
+ }
+}
+
+ChildClass::test();
+/*
+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
+*
*/
+// Simple error handling can be done with try catch block
+
+try {
+ // Do something
+} catch (Exception $e) {
+ // Handle exception
+}
+
+// When using try catch blocks in a namespaced enviroment use the following
+
+try {
+ // Do something
+} catch (\Exception $e) {
+ // Handle exception
+}
+
+// Custom exceptions
+
+class MyException extends Exception {}
+
+try {
+
+ $condition = true;
+
+ if ($condition) {
+ throw new MyException('Something just happend');
+ }
+
+} catch (MyException $e) {
+ // Handle my exception
+}
+
```
## More Information
@@ -709,4 +853,4 @@ If you're coming from a language with good package management, check out
[Composer](http://getcomposer.org/).
For common standards, visit the PHP Framework Interoperability Group's
-[PSR standards](https://github.com/php-fig/fig-standards). \ No newline at end of file
+[PSR standards](https://github.com/php-fig/fig-standards).
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/python-pl.html.markdown b/pl-pl/python-pl.html.markdown
index c3e8287a..023c3e6b 100644
--- a/pl-pl/python-pl.html.markdown
+++ b/pl-pl/python-pl.html.markdown
@@ -30,7 +30,7 @@ działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stron
# Pojedyncze komentarze oznaczamy takim symbolem.
""" Wielolinijkowe napisy zapisywane są przy użyciu
- trzech znaków cudzysłowiu i często
+ potrójnych cudzysłowów i często
wykorzystywane są jako komentarze.
"""
@@ -47,11 +47,11 @@ działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stron
10 * 2 # => 20
35 / 5 # => 7
-# Dzielenie może być kłopotliwe. Poniższe to dzielenie
+# Dzielenie może być kłopotliwe. Poniższe działanie to dzielenie
# całkowitoliczbowe(int) i wynik jest automatycznie zaokrąglany.
5 / 2 # => 2
-# Aby to naprawić musimy powiedzieć nieco o liczbach zmiennoprzecinkowych.
+# Aby to naprawić, musimy powiedzieć nieco o liczbach zmiennoprzecinkowych.
2.0 # To liczba zmiennoprzecinkowa, tzw. float
11.0 / 4.0 # => 2.75 ahhh...znacznie lepiej
@@ -65,7 +65,7 @@ działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stron
# Operator modulo - wyznaczanie reszty z dzielenia
7 % 3 # => 1
-# Potęgowanie (x do potęgi ytej)
+# Potęgowanie (x do potęgi y-tej)
2**4 # => 16
# Wymuszanie pierwszeństwa w nawiasach
@@ -83,7 +83,7 @@ False or True #=> True # Prawda
2 == True #=> False
k1 == True #=> True
-# aby zanegować użyj "not"
+# aby zanegować, użyj "not"
not True # => False
not False # => True
@@ -112,7 +112,7 @@ not False # => True
# Napisy można dodawać!
"Witaj " + "świecie!" # => "Witaj świecie!"
-# ... a nawet mnożone
+# ... a nawet mnożyć
"Hej" * 3 # => "HejHejHej"
# Napis może być traktowany jako lista znaków
@@ -124,8 +124,8 @@ not False # => True
# Jednak nowszym sposobem formatowania jest metoda "format".
# Ta metoda jest obecnie polecana:
"{0} są {1}".format("napisy", "fajne")
-# Jeśli nie chce ci się liczyć użyj słów kluczowych.
-"{imie} chce zjeść {jadlo}".format(imie="Bob", jasno="lasagne")
+# Jeśli nie chce ci się liczyć, użyj słów kluczowych.
+"{imie} chce zjeść {jadlo}".format(imie="Bob", jadlo="makaron")
# None jest obiektem
None # => None
@@ -135,12 +135,12 @@ None # => None
"etc" is None # => False
None is None # => True
-# Operator 'is' testuje identyczność obiektów. To nie jest zbyt
+# Operator 'is' testuje identyczność obiektów. Nie jest to zbyt
# pożyteczne, gdy działamy tylko na prostych wartościach,
# ale przydaje się, gdy mamy do czynienia z obiektami.
-# None, 0, i pusty napis "" są odpowiednikami logicznego False.
-# Wszystkie inne wartości są True
+# None, 0 i pusty napis "" są odpowiednikami logicznego False.
+# Wszystkie inne wartości są uznawane za prawdę (True)
bool(0) # => False
bool("") # => False
@@ -149,20 +149,20 @@ bool("") # => False
## 2. Zmienne i zbiory danych
####################################################
-# Python ma wyrażenie wypisujące "print" we wszystkich wersjach 2.x, ale
-# zostało usunięte z wersji 3.
-print "Jestem Python. Miło poznać!"
-# Python ma też funkcję "print" dostępną w wersjach 2.7 and 3...
+# Python ma instrukcję wypisującą "print" we wszystkich wersjach 2.x, ale
+# została ona usunięta z wersji 3.
+print "Jestem Python. Miło Cię poznać!"
+# Python ma też funkcję "print" dostępną w wersjach 2.7 i 3...
# ale w 2.7 musisz dodać import (odkomentuj):
# from __future__ import print_function
print("Ja też jestem Python! ")
# Nie trzeba deklarować zmiennych przed przypisaniem.
-jakas_zmienna = 5 # Konwencja mówi: używaj małych znaków i podłogi _
+jakas_zmienna = 5 # Konwencja mówi: używaj małych liter i znaków podkreślenia _
jakas_zmienna # => 5
# Próba dostępu do niezadeklarowanej zmiennej da błąd.
-# Przejdź do sekcji Obsługa wyjątków po więcej...
+# Przejdź do sekcji Obsługa wyjątków, aby dowiedzieć się więcej...
inna_zmienna # Wyrzuca nazwę błędu
# "if" może być użyte jako wyrażenie
@@ -173,7 +173,7 @@ li = []
# Możesz zacząć od wypełnionej listy
inna_li = [4, 5, 6]
-# Dodaj na koniec używając "append"
+# Dodaj na koniec, używając "append"
li.append(1) # li to teraz [1]
li.append(2) # li to teraz [1, 2]
li.append(4) # li to teraz [1, 2, 4]
@@ -185,7 +185,7 @@ li.append(3) # li to znowu [1, 2, 4, 3].
# Dostęp do list jak do każdej tablicy
li[0] # => 1
-# Użyj = aby nadpisać wcześniej wypełnione miejsca w liście
+# Aby nadpisać wcześniej wypełnione miejsca w liście, użyj znaku =
li[0] = 42
li[0] # => 42
li[0] = 1 # Uwaga: ustawiamy starą wartość
@@ -195,7 +195,7 @@ li[-1] # => 3
# Jeżeli wyjdziesz poza zakres...
li[4] # ... zobaczysz IndexError
-# Możesz tworzyć wyniki.
+# Możesz też tworzyć wycinki.
li[1:3] # => [2, 4]
# Bez początku
li[2:] # => [4, 3]
@@ -213,12 +213,12 @@ del li[2] # li to teraz [1, 2, 3]
# Listy można dodawać
li + inna_li # => [1, 2, 3, 4, 5, 6]
-# Uwaga: wartości poszczególnych list się nie zmieniają.
+# Uwaga: wartości oryginalnych list li i inna_li się nie zmieniają.
# Do łączenia list użyj "extend()"
li.extend(other_li) # li to teraz [1, 2, 3, 4, 5, 6]
-# Sprawdź czy jest w liście używając "in"
+# Sprawdź, czy element jest w liście używając "in"
1 in li # => True
# "len()" pokazuje długość listy
@@ -238,7 +238,7 @@ tup[:2] # => (1, 2)
# Można rozpakować krotki i listy do poszczególych zmiennych
a, b, c = (1, 2, 3) # a to teraz 1, b jest 2, a c to 3
-# Jeżeli zapomnisz nawiasów automatycznie tworzone są krotki
+# Jeżeli zapomnisz nawiasów, automatycznie tworzone są krotki
d, e, f = 4, 5, 6
# Popatrz jak prosto zamienić wartości
e, d = d, e # d to teraz 5 a e to 4
@@ -252,28 +252,28 @@ pelen_slownik = {"raz": 1, "dwa": 2, "trzy": 3}
# Podglądany wartość
pelen_slownik["one"] # => 1
-# Wypisz wszystkie klucze używając "keys()"
+# Wypisz wszystkie klucze, używając "keys()"
pelen_slownik.keys() # => ["trzy", "dwa", "raz"]
-# Uwaga: słowniki nie gwarantują kolejności występowania kluczy.
+# Uwaga: słowniki nie zapamiętują kolejności kluczy.
# A teraz wszystkie wartości "values()"
pelen_slownik.values() # => [3, 2, 1]
# Uwaga: to samo dotyczy wartości.
-# Sprawdzanie czy występuje to "in"
+# Sprawdzanie czy klucz występuje w słowniku za pomocą "in"
"raz" in pelen_slownik # => True
1 in pelen_slownik # => False
# Próba dobrania się do nieistniejącego klucza da KeyError
pelen_slownik["cztery"] # KeyError
-# Użyj "get()" method aby uniknąć KeyError
+# Użyj metody "get()", aby uniknąć błędu KeyError
pelen_slownik.get("raz") # => 1
pelen_slownik.get("cztery") # => None
# Metoda get zwraca domyślną wartość gdy brakuje klucza
pelen_slownik.get("one", 4) # => 1
pelen_slownik.get("cztery", 4) # => 4
-# zauważ, że pelen_slownik.get("cztery") jest wciąż => None
+# zauważ, że pelen_slownik.get("cztery") wciąż zwraca => None
# (get nie ustawia wartości słownika)
# przypisz wartość do klucza podobnie jak w listach
@@ -284,12 +284,12 @@ pelen_slownik.setdefault("piec", 5) # pelen_slownik["piec"] daje 5
pelen_slownik.setdefault("piec", 6) # pelen_slownik["piec"] to wciąż 5
-# Teraz zbiory (set) ... cóż zbiory (to po prostu listy ale bez potórzeń)
+# Teraz zbiory (set) - działają jak zwykłe listy, ale bez potórzeń
pusty_zbior = set()
# Inicjalizujemy "set()" pewnymi wartościami
jakis_zbior = set([1, 2, 2, 3, 4]) # jakis_zbior to teraz set([1, 2, 3, 4])
-# kolejność nie jest gwarantowana, nawet gdy wydaje się posortowane
+# kolejność nie jest zachowana, nawet gdy wydaje się posortowane
inny_zbior = set([4, 3, 2, 2, 1]) # inny_zbior to set([1, 2, 3, 4])
# Od Pythona 2.7 nawiasy klamrowe {} mogą być użyte do deklarowania zbioru
@@ -298,7 +298,7 @@ pelen_zbior = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
# Dodaj więcej elementów przez "add()"
pelen_zbior.add(5) # pelen_zbior is now {1, 2, 3, 4, 5}
-# Znajdź przecięcie zbiorów używając &
+# Znajdź przecięcie (część wspólną) zbiorów, używając &
inny_zbior = {3, 4, 5, 6}
pelen_zbior & other_set # => {3, 4, 5}
@@ -317,32 +317,32 @@ pelen_zbior | other_set # => {1, 2, 3, 4, 5, 6}
## 3. Kontrola przepływu
####################################################
-# Tworzymy zmienną some_var
-some_var = 5
+# Tworzymy zmienną jakas_zm
+jakas_zm = 5
-# Tutaj widzisz wyrażenie warunkowe "if". Wcięcia są ważne Pythonie!
-# wypisze "some_var jest mniejsza niż 10"
-if some_var > 10:
- print("some_var jest wieksza niż 10")
-elif some_var < 10: # This elif clause is optional.
- print("some_var jest mniejsza niż 10")
-else: # This is optional too.
- print("some_var jest równa 10")
+# Tutaj widzisz wyrażenie warunkowe "if". Wcięcia w Pythonie są ważne!
+# Poniższy kod wypisze "jakas_zm jest mniejsza niż 10"
+if jakas_zm > 10:
+ print("jakas_zm jest wieksza niż 10")
+elif some_var < 10: # Opcjonalna klauzula elif
+ print("jakas_zm jest mniejsza niż 10")
+else: # Również opcjonalna klauzula else
+ print("jakas_zm jest równa 10")
"""
-Pętla for iteruje po elementach listy wypisując:
+Pętla for iteruje po elementach listy, wypisując:
pies to ssak
kot to ssak
mysz to ssak
"""
for zwierze in ["pies", "kot", "mysz"]:
- # Możesz użyć % aby stworzyć sformatowane napisy
- print("%s to ssak" % zwierze)
+ # Użyj metody format, aby umieścić wartość zmiennej w ciągu
+ print("{0} to ssak".format(zwierze))
"""
"range(liczba)" zwraca listę liczb
-od zera do danej liczby:
+z przedziału od zera do wskazanej liczby (bez niej):
0
1
2
@@ -352,7 +352,7 @@ for i in range(4):
print(i)
"""
-While to pętla która jest wykonywana dopóki spełniony jest warunek:
+While to pętla, która jest wykonywana, dopóki spełniony jest warunek:
0
1
2
@@ -363,46 +363,46 @@ while x < 4:
print(x)
x += 1 # Skrót od x = x + 1
-# Wyjątki wyłapujemy używając try, except
+# Wyjątki wyłapujemy, używając try i except
# Działa w Pythonie 2.6 i wyższych:
try:
- # Użyj "raise" aby wyrzucić wyjąte
+ # Użyj "raise" aby wyrzucić wyjątek
raise IndexError("To błąd indeksu")
except IndexError as e:
- pass # Pass to brak reakcji na błąd. Zazwyczaj nanosisz tu poprawki.
+ pass # Pass to brak reakcji na błąd. Zwykle opisujesz tutaj, jak program ma się zachować w przypadku błędu.
except (TypeError, NameError):
- pass # kilka wyjątków może być przechwyce razem.
+ pass # kilka wyjątków można przechwycić jednocześnie.
else: # Opcjonalna część bloku try/except. Musi wystąpić na końcu
print "Wszystko ok!" # Zadziała tylko, gdy program nie napotka wyjatku.
####################################################
-## 4. Funkcjie
+## 4. Funkcje
####################################################
-# Użyj "def" aby stworzyć nową funkcję
+# Użyj "def", aby stworzyć nową funkcję
def dodaj(x, y):
- print("x to %s a y to %s" % (x, y))
- return x + y # słówko kluczowe return zwraca wynik działania
+ print("x to %s, a y to %s" % (x, y))
+ return x + y # słowo kluczowe return zwraca wynik działania
-# Tak wywołuje się funkcję z parametrami (args):
-dodaj(5, 6) # => wypisze "x to 5 a y to 6" i zwróci 11
+# Tak wywołuje się funkcję z parametrami:
+dodaj(5, 6) # => wypisze "x to 5, a y to 6" i zwróci 11
# Innym sposobem jest wywołanie z parametrami nazwanymi.
dodaj(y=6, x=5) # tutaj kolejność podania nie ma znaczenia.
-# Można też stworzyć funkcję, które przyjmują różną ilość parametrów
-# nienazwanych args, co będzie interpretowane jako krotka jeśli nie użyjesz *
+# Można też stworzyć funkcję, które przyjmują zmienną liczbę parametrów pozycyjnych,
+# które zostaną przekazana jako krotka, pisząc w definicji funkcji "*args"
def varargs(*args):
return args
varargs(1, 2, 3) # => (1, 2, 3)
-# Można też stworzyć funkcję, które przyjmują różną ilość parametrów
-# nazwanych kwargs, które będa interpretowane jako słownik jeśli nie dasz **
+# Można też stworzyć funkcję, które przyjmują zmienną liczbę parametrów
+# nazwanych kwargs, które zostaną przekazane jako słownik, pisząc w definicji funkcji "**kwargs"
def keyword_args(**kwargs):
return kwargs
@@ -410,12 +410,12 @@ def keyword_args(**kwargs):
keyword_args(wielka="stopa", loch="ness") # => {"wielka": "stopa", "loch": "ness"}
-# Możesz też to pomieszać
+# Możesz też przyjmować jednocześnie zmienną liczbę parametrów pozycyjnych i nazwanych
def all_the_args(*args, **kwargs):
print(args)
print(kwargs)
"""
-all_the_args(1, 2, a=3, b=4) wyrzuci:
+all_the_args(1, 2, a=3, b=4) wypisze:
(1, 2)
{"a": 3, "b": 4}
"""
@@ -435,7 +435,7 @@ def pass_all_the_args(*args, **kwargs):
print varargs(*args)
print keyword_args(**kwargs)
-# Zakres widoczności
+# Zasięg zmiennych
x = 5
def setX(num):
@@ -461,14 +461,14 @@ def rob_dodawacz(x):
dodaj_10 = rob_dodawacz(10)
dodaj_10(3) # => 13
-# Są również funkcje nienazwane "lambda"
+# Są również funkcje anonimowe "lambda"
(lambda x: x > 2)(3) # => True
-# Są także wbudowane funkcje wysokiego poziomu
+# Python ma też wbudowane funkcje wyższego rzędu (przyjmujące inną funkcje jako parametr)
map(add_10, [1, 2, 3]) # => [11, 12, 13]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
-# Można używać wyrażeń listowych do mapowania (map) i filtrowania (filter)
+# Można używać wyrażeń listowych (list comprehensions) do mapowania i filtrowania
[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]
@@ -485,18 +485,18 @@ class Czlowiek(object):
# Podstawowa inicjalizacja - wywoływana podczas tworzenia instacji.
# Zauważ, że podwójne podkreślenia przed i za nazwą oznaczają
- # obietky lub atrybuty, który żyją tylko w kontrolowanej przez
- # użytkownika przestrzeni nazw. Nie używaj ich we własnych metodach.
+ # specjalne obiekty lub atrybuty wykorzystywane wewnętrznie przez Pythona.
+ # Nie używaj ich we własnych metodach.
def __init__(self, nazwa):
# przypisz parametr "nazwa" do atrybutu instancji
self.nazwa = nazwa
- # Metoda instancji. Wszystkie metody biorą "self" jako pierwszy argument
+ # Metoda instancji. Wszystkie metody przyjmują "self" jako pierwszy argument
def mow(self, wiadomosc):
return "%s: %s" % (self.nazwa, wiadomosc)
# Metoda klasowa współdzielona przez instancje.
- # Ma wywołującą klasę jako pierwszy argument.
+ # Przyjmuje wywołującą klasę jako pierwszy argument.
@classmethod
def daj_gatunek(cls):
return cls.gatunek
@@ -540,7 +540,8 @@ print(ceil(3.7)) # => 4.0
print(floor(3.7)) # => 3.0
# Można zaimportować wszystkie funkcje z danego modułu.
-# Ostrzeżenie: nie jest to polecane.
+# Uwaga: nie jest to polecane, bo później w kodzie trudno połapać się,
+# która funkcja pochodzi z którego modułu.
from math import *
# Można skracać nazwy modułów.
@@ -550,7 +551,7 @@ math.sqrt(16) == m.sqrt(16) # => True
from math import sqrt
math.sqrt == m.sqrt == sqrt # => True
-# Moduły pythona to zwykłe skrypty napisane w tym języku. Możesz
+# Moduły Pythona to zwykłe skrypty napisane w tym języku. Możesz
# pisać własne i importować je. Nazwa modułu to nazwa pliku.
# W ten sposób sprawdzisz jakie funkcje wchodzą w skład modułu.
@@ -568,14 +569,16 @@ def podwojne_liczby(iterowalne):
yield i + i
# Generatory tworzą wartości w locie.
-# W przeciwienstwie do wygenerowania wartości raz i ich zachowania,
-# powstają one na bieżąco, w wyniku iteracji. To oznacza, że wartości
-# większe niż 15 nie będą przetworzone w funkcji "podwojne_liczby".
+# Zamiast generować wartości raz i zapisywać je (np. w liście),
+# generator tworzy je na bieżąco, w wyniku iteracji. To oznacza,
+# że w poniższym przykładzie wartości większe niż 15 nie będą przetworzone
+# w funkcji "podwojne_liczby".
# Zauważ, że xrange to generator, który wykonuje tę samą operację co range.
# Stworzenie listy od 1 do 900000000 zajęłoby sporo czasu i pamięci,
-# a xrange tworzy obiekt generatora zamiast tworzyć całą listę jak range.
-# Użyto podkreślinika, aby odróżnić nazwę zmiennej od słówka kluczowego
-# Pythona.
+# a xrange tworzy obiekt generatora zamiast budować całą listę jak range.
+
+# Aby odróżnić nazwę zmiennej od nazwy zarezerwowanej w Pythonie, używamy
+# zwykle na końcu znaku podkreślenia
xrange_ = xrange(1, 900000000)
# poniższa pętla będzie podwajać liczby aż do 30
@@ -587,7 +590,7 @@ for i in podwojne_liczby(xrange_):
# Dekoratory
# w tym przykładzie "beg" jest nakładką na "say"
-# Beg wywołuje say. Jeśli say_please jest prawdziwe wtedy wzracana wartość
+# Beg wywołuje say. Jeśli say_please jest prawdziwe, wtedy zwracana wartość
# zostanie zmieniona
from functools import wraps
diff --git a/pl-pl/ruby-pl.html.markdown b/pl-pl/ruby-pl.html.markdown
new file mode 100644
index 00000000..73b1a7d8
--- /dev/null
+++ b/pl-pl/ruby-pl.html.markdown
@@ -0,0 +1,593 @@
+---
+language: ruby
+filename: learnruby.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"]
+translators:
+ - ["Marcin Klocek", "https://github.com/mklocek"]
+lang: pl-pl
+---
+
+```ruby
+# To jest komentarz
+
+=begin
+To jest wielolinijkowy komentarz
+Nikt ich nie używa
+Ty też nie powinieneś
+=end
+
+# Przede wszystkim: Wszystko jest obiektem.
+
+# Liczby są obiektami
+
+3.class #=> Fixnum
+
+3.to_s #=> "3"
+
+
+# Trochę podstawowej arytmetyki
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+2**5 #=> 32
+5 % 3 #=> 2
+5 ^ 6 #=> 3
+
+# Arytmetyka jest zastąpeniem składni
+# metod wywoływanych na obiektach
+1.+(3) #=> 4
+10.* 5 #=> 50
+
+# Wartości specjalne są obiektami
+nil # To na prawdę jest niczym
+true # prawda
+false # fałsz
+
+nil.class #=> NilClass
+true.class #=> TrueClass
+false.class #=> FalseClass
+
+# Równość
+1 == 1 #=> true
+2 == 1 #=> false
+
+# Nierówność
+1 != 1 #=> false
+2 != 1 #=> true
+
+# jedyną 'fałszywą' wartością poza false, jest nil
+
+!nil #=> true
+!false #=> true
+!0 #=> false
+
+# Więcej porównań
+1 < 10 #=> true
+1 > 10 #=> false
+2 <= 2 #=> true
+2 >= 2 #=> true
+
+# Operatory logiczne
+true && false #=> false
+true || false #=> true
+!true #=> false
+
+# Istnieją alternatywne wersje operatorów logicznych ze znacznie mniejszym
+# pierwszeństwem. Używane są by kontrolować wyrażenia w łańcuchach wyrażeń
+# aż jedno z nich wróci true lub false.
+
+# `zrob_cos_innego` wywołaj tylko wtedy gdy `zrob_cos` zakończy się sukcesem.
+zrob_cos_innego() and zrob_cos()
+# `log_error` wywołaj tylko wtedy gdy `zrob_cos` nie zakończy się sukcesem.
+zrob_cos() or log_error()
+
+
+# Stringi są obiektami
+
+'Jestem stringiem.'.class #=> String
+"Ja również jestem stringiem.".class #=> String
+
+wypelnienie = 'użyć interpolacji stringa'
+"Potrafię #{wypelnienie} używając podwójnych cudzysłowów."
+#=> "Potrafię użyć interpolacji stringa używając podwójnych cudzysłowów."
+
+# Staraj się zapisywać stringi za pomocą apostrof, zamiast cudzysłowów tam, gdzie to możliwe
+# Cudzysłowy wykonują dodatkowe wewnętrzne operacje
+
+
+# Łączenie stringów, ale nie liczb
+'hej ' + 'świecie' #=> "hej świecie"
+'hej ' + 3 #=> TypeError: can't convert Fixnum into String
+'hej ' + 3.to_s #=> "hej 3"
+
+# Łączenie stringów i operatorów
+'hej ' * 3 #=> "hej hej hej "
+
+# Dodawanie do stringa
+'hej' << ' świecie' #=> "hej świecie"
+
+# wydrukowanie wartości wraz z nową linią na końcu
+puts "Drukuję!"
+#=> Drukuję!
+#=> nil
+
+# wydrukowanie wartości bez nowej linii na końcu
+print "Drukuję!"
+#=> Drukuję! => nill
+
+# Zmienne
+x = 25 #=> 25
+x #=> 25
+
+# Zauważ, że przypisanie zwraca przypisywaną wartość
+# To znaczy, że możesz wykonać wielokrotne przypisanie:
+
+x = y = 10 #=> 10
+x #=> 10
+y #=> 10
+
+# Zwyczajowo, używaj notacji nazwa_zmiennej dla nazw zmiennych
+nazwa_zmiennej = true
+
+# Używaj opisowych nazw zmiennych
+sciezka_do_projektu = '/dobra/nazwa/'
+sciezka = '/zla/nazwa/'
+
+# Symbole (są obiektami)
+# Symbole są niezmiennymi, wielokrotnie używanymi stałymi reprezentowanymi wewnętrznie jako
+# liczby całkowite. Często używane są zamiast stringów w celu wydajniejszego przekazywania danych
+
+:oczekujacy.class #=> Symbol
+
+status = :oczekujacy
+
+status == :oczekujacy #=> true
+
+status == 'oczekujacy' #=> false
+
+status == :zatwierdzony #=> false
+
+# Tablice
+
+# To jest tablica
+array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+
+# Tablice mogą zwierać różne typy danych
+
+[1, 'hej', false] #=> [1, "hej", false]
+
+# Tablice mogę być indeksowane
+# Od początku
+tablica[0] #=> 1
+tablica.first #=> 1
+tablica[12] #=> nil
+
+# Podobnie jak przy arytmetyce, dostęp poprzez [zmienna]
+# jest tylko czytelniejszą składnią
+# dla wywoływania metody [] na obiekcie
+tablica.[] 0 #=> 1
+tablica.[] 12 #=> nil
+
+# Od końca
+tablica[-1] #=> 5
+tablica.last #=> 5
+
+# Z początkowym indeksem i długością
+tablica[2, 3] #=> [3, 4, 5]
+
+# Odwrotność tablicy
+a=[1,2,3]
+a.reverse! #=> [3,2,1]
+
+# Lub zakres
+array[1..3] #=> [2, 3, 4]
+
+# Dodawanie do tablicy w taki sposób
+tablica << 6 #=> [1, 2, 3, 4, 5, 6]
+# Lub taki
+tablica.push(6) #=> [1, 2, 3, 4, 5, 6]
+
+# Sprawdzanie, czy tablica zawiera element
+tablica.include?(1) #=> true
+
+# Hasze są Ruby'owymi podstawowymi słownikami z parami klucz/wartość.
+# Hasze są zapisywane za pomocą nawiasów klamrowych
+hasz = { 'kolor' => 'zielony', 'numer' => 5 }
+
+hasz.keys #=> ['kolor', 'numer']
+
+# Można szybko sprawdzić zawartość hasza za pomocą kluczy:
+hasz['kolor'] #=> 'zielony'
+hasz['numer'] #=> 5
+
+# Sprawdzenie wartośći dla nieistniejącego klucza zwraca nil:
+hasz['nic tutaj nie ma'] #=> nil
+
+# Od wersji 1.9, Ruby posiada specjalną składnię, gdy używamy symboli jako kluczy:
+
+nowy_hasz = { stan: 3, akcja: true }
+
+nowy_hasz.keys #=> [:stan, :akcja]
+
+# Sprawdzenie istnienia kluczy i wartości w haszu
+new_hash.has_key?(:defcon) #=> true
+new_hash.has_value?(3) #=> true
+
+# Wskazówka: Zarówno tablice, jak i hasze, są policzalne
+# Współdzielą wiele metod takich jak each, map, count, i inne
+
+# Instrukcje warunkowe
+
+if true
+ 'wyrażenie if'
+elsif false
+ 'wyrażenie if, opcjonalne'
+else
+ 'wyrażenie else, również opcjonalne'
+end
+
+for licznik in 1..5
+ puts "powtórzenie #{licznik}"
+end
+#=> powtórzenie 1
+#=> powtórzenie 2
+#=> powtórzenie 3
+#=> powtórzenie 4
+#=> powtórzenie 5
+
+# JEDNAKŻE, Nikt nie używa pętli for.
+# Zamiast tego, powinno się używać metody "each" i podawać jej blok.
+# Blok jest kawałkiem kodu, który możesz podać metodzie podobnej do "each".
+# Jest analogiczny do wyrażeń lambda, funkcji anonimowych lub zamknięć w innych
+# językach programowania.
+#
+# Metoda "each" danego zakresu, wykonuje blok dla każdego elementu w zakresie.
+# Do bloku zostaje przekazany licznik jako parametr.
+# Wykonanie metody "each" z przekazaniem bloku wygląda następująco:
+
+(1..5).each do |licznik|
+ puts "powtórzenie #{licznik}"
+end
+#=> powtórzenie 1
+#=> powtórzenie 2
+#=> powtórzenie 3
+#=> powtórzenie 4
+#=> powtórzenie 5
+
+# Możesz również otoczyć blok nawiasami klamrowymi:
+(1..5).each { |licznik| puts "powtórzenie #{licznik}" }
+
+# Zawartość struktur danych również może być powtarzana używając each.
+tablica.each do |element|
+ puts "#{element} jest częścią tablicy"
+end
+hasz.each do |klucz, wartosc|
+ puts "#{klucz} jest #{wartosc}"
+end
+
+# Jeśli nadal potrzebujesz indeksum, możesz użyć "each_with_index" i zdefiniować
+# zmienną odpowiadającą indeksowi
+tablica.each_with_index do |element, indeks|
+ puts "#{element} jest numerem #{indeks} w tablicy"
+end
+
+licznik = 1
+while licznik <= 5 do
+ puts "powtórzenie #{licznik}"
+ licznik += 1
+end
+#=> powtórzenie 1
+#=> powtórzenie 2
+#=> powtórzenie 3
+#=> powtórzenie 4
+#=> powtórzenie 5
+
+# W Ruby istnieje dużo pomocnych funkcji wykonujących pętle,
+# na przykład "map", "reduce", "inject" i wiele innych. Map,
+# w każdym wywołaniu, pobiera tablicę, na której wykonuję pętlę,
+# wykonuje kod zapisany za pomocą bloku i zwraca całkowicie nową tablicę.
+tablica = [1,2,3,4,5]
+podwojone = tablica.map do |element|
+ element * 2
+end
+puts podwojona
+#=> [2,4,6,8,10]
+puts tablica
+#=> [1,2,3,4,5]
+
+ocena = 2
+
+case ocena
+when 1
+ puts 'Dobra robota, masz wolne'
+when 2
+ puts 'Następnym razem będziesz miał więcej szczęścia'
+when 3
+ puts 'Możesz to zrobić lepiej'
+when 4
+ puts 'Przebrnąłeś'
+when 5
+ puts 'Oblałeś!'
+else
+ puts 'Inny system oceniania?'
+end
+#=> "Następnym razem będziesz miał więcej szczęścia"
+
+# case może również użwać zakresów
+ocena = 82
+case ocena
+when 90..100
+ puts 'Hurra!'
+when 80...90
+ puts 'Dobra robota'
+else
+ puts 'Oblałeś!'
+end
+#=> "Dobra robota"
+
+# obsługa błędów:
+begin
+ # kod, który może wywołać wyjątek
+ raise NoMemoryError, 'Zabrakło pamięci.'
+rescue NoMemoryError => zmienna_wyjatku
+ puts 'Został wywołany NoMemoryError', zmienna_wyjatku
+rescue RuntimeError => inna_zmienna_wyjatku
+ puts 'Teraz został wywołany RuntimeError'
+else
+ puts 'To zostanie uruchomione, jeśli nie wystąpi żaden wyjątek'
+ensure
+ puts 'Ten kod wykona się zawsze'
+end
+
+# Funkcje
+
+def podwojenie(x)
+ x * 2
+end
+
+# Funkcje (i wszystkie bloki) zawsze zwracają wartość ostatniego wyrażenia
+podwojenie(2) #=> 4
+
+# Okrągłe nawiady są opcjonalne, gdy wynik jest jednoznaczny
+podwojenie 3 #=> 6
+
+podwojenie podwojenie 3 #=> 12
+
+def suma(x, y)
+ x + y
+end
+
+# Argumenty metod są oddzielone przecinkami
+suma 3, 4 #=> 7
+
+suma suma(3, 4), 5 #=> 12
+
+# yield
+# Wszystkie metody mają ukryty, opcjonalny parametr bloku,
+# który może być wykonany używając słowa kluczowego 'yield'
+
+def otoczenie
+ puts '{'
+ yield
+ puts '}'
+end
+
+otoczenie { puts 'hej świecie' }
+
+# {
+# hej świecie
+# }
+
+
+# Możesz przekazać blok do funkcji
+# "&" oznacza referencję to przekazanego bloku
+def goscie(&blok)
+ blok.call 'jakis_argument'
+end
+
+# Możesz przekazać listę argumentów, które będę przekonwertowane na tablicę
+# Do tego służy operator ("*")
+def goscie(*tablica)
+ tablica.each { |gosc| puts gosc }
+end
+
+# Definiowanie klas używając słowa kluczowego class
+class Czlowiek
+
+ # Zmienna klasowa. Jest współdzielona przez wszystkie instancje tej klasy.
+ @@gatunek = 'H. sapiens'
+
+ # Podstawowe inicjalizowanie
+ def initialize(imie, wiek = 0)
+ # Przypisanie argumentu do zmiennej danej instancji o nazwie "imie"
+ @imie = imie
+ # Jeśli nie podano wieku, zostanie użyta domyślna wartość z listy argumentów.
+ @wiek = wiek
+ end
+
+ # Podstawowa metoda przypisująca wartość
+ def imie=(imie)
+ @imie = imie
+ end
+
+ # Podstawowa metoda pobierająca wartość
+ def imie
+ @imie
+ end
+
+ # Powyższa funkcjonalność może być zastąpiona używając metody attr_accessor w taki sposób
+ attr_accessor :imie
+
+ # Metody przypisujące/pobierające mogą być stworzone indywidualnie
+ attr_reader :imie
+ attr_writer :imie
+
+ # Metody klasowe używają self aby odróżnić się od metody instancji.
+ # To może być wywołane na klasie, nie na instancji.
+ def self.powiedz(wiadomosc)
+ puts wiadomosc
+ end
+
+ def gatunek
+ @@gatunek
+ end
+end
+
+
+# Tworzenie instancji klasy
+jim = Czlowiek.new('Jim Halpert')
+
+dwight = Czlowiek.new('Dwight K. Schrute')
+
+# Wywołajmy parę metod
+jim.gatunek #=> "H. sapiens"
+jim.imie #=> "Jim Halpert"
+jim.imie = "Jim Halpert II" #=> "Jim Halpert II"
+jim.imie #=> "Jim Halpert II"
+dwight.gatunek #=> "H. sapiens"
+dwight.imie #=> "Dwight K. Schrute"
+
+# Wywołanie metody klasowej
+Czlowiek.powiedz('Cześć') #=> "Cześć"
+
+# Zasięg zmiennej jest definiowany poprzez jej nazwę.
+# Zmienne, które zaczynają się na $ mają zasięg globalny
+$zmienna = "Jestem zmienną globalną"
+defined? $zmienna #=> "global-variable"
+
+# Zmienne zczynające się na @ mają zasięg danej instancji
+@zmienna = "Jestem zmienną instancji"
+defined? @zmienna #=> "instance-variable"
+
+# Zmienne, które zaczynają się na @@ mają zasięg danej klasy
+@@zmienna = "Jestem zmienną klasową"
+defined? @@zmienna #=> "class variable"
+
+# Zmienne, które zaczynają się na dużą literę, są stałymi
+Zmienna = "Jestem stałą"
+defined? Zmienna #=> "constant"
+
+# Klasa jest również obiektem w ruby. Może więc mieć zmienne instancji.
+# Zmienna klasowa może być współdzielona między klasą i jej potomstwem.
+
+# podstawowa klasa
+class Czlowiek
+ @@cokolwiek = 0
+
+ def self.cokolwiek
+ @@cokolwiek
+ end
+
+ def self.cokolwiek=(wartosc)
+ @@cokolwiek = wartosc
+ end
+end
+
+# klasa pochodna
+class Pracownik < Czlowiek
+end
+
+Czlowiek.cokolwiek # 0
+Pracownik.cokolwiek # 0
+
+Czlowiek.cokolwiek = 2 # 2
+Pracownik.cokolwiek # 2
+
+# Zmienna instancji danej klasy nie jest współdzielona przez jej potomstwo.
+
+class Czlowiek
+ @cos = 0
+
+ def self.cos
+ @cos
+ end
+
+ def self.cos=(wartosc)
+ @cos = wartosc
+ end
+end
+
+class Doktor < Czlowiek
+end
+
+Czlowiek.cos # 0
+Doktor.cos # nil
+
+module PrzykladowyModul
+ def cokolwiek
+ 'cokolwiek'
+ end
+end
+
+# Włączanie modułów łączy ich metody z metodami instancji klasy
+# Rozszerzanie modułów łączy ich metody z metodami klasy
+
+class Osoba
+ include PrzykladowyModul
+end
+
+class Ksiazka
+ extend PrzykladowyModul
+end
+
+Osoba.cokolwiek # => NoMethodError: undefined method `cokolwiek' for Osoba:Class
+Osoba.new.cokolwiek # => 'cokolwiek'
+Ksiazka.cokolwiek # => 'cokolwiek'
+Ksiazka.new.cokolwiek # => NoMethodError: undefined method `cokolwiek'
+
+# Gdy włączamy lub rozszerzamy muduły, wykonywane są tzw. wywołania zwrotne
+
+module PrzykladowyModul
+ def self.included(baza)
+ baza.extend(MotodyKlasowe)
+ baza.send(:include, MetodyInstancji)
+ end
+
+ module MotodyKlasowe
+ def cos
+ 'cos'
+ end
+ end
+
+ module MetodyInstancji
+ def xyz
+ 'xyz'
+ end
+ end
+end
+
+class Cokolwiek
+ include PrzykladowyModul
+end
+
+Cokolwiek.cos # => 'cos'
+Cokolwiek.xyz # => NoMethodError: undefined method `xyz'
+Cokolwiek.new.cos # => NoMethodError: undefined method `cos'
+Cokolwiek.new.xyz # => 'qux'
+```
+
+## Dodatkowe źródła
+### Polskie
+
+- [Dokumentacja](https://www.ruby-lang.org/pl/documentation/quickstart/)
+
+### Angielskie
+
+- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.
+- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/)
+- [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.
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
new file mode 100644
index 00000000..fc944b85
--- /dev/null
+++ b/powershell.html.markdown
@@ -0,0 +1,330 @@
+---
+category: tool
+tool: powershell
+contributors:
+ - ["Wouter Van Schandevijl", "https://github.com/laoujin"]
+filename: LearnPowershell.ps1
+---
+
+PowerShell is the Windows scripting language and configuration management
+framework from Microsoft built on the .NET Framework. Windows 7 and up ship
+with PowerShell.
+Nearly all examples below can be a part of a shell script or executed directly
+in the shell.
+
+A key difference with Bash is that it is mostly objects that you manipulate
+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
+# Execution policies include:
+# - Restricted: Scripts won't run.
+# - RemoteSigned: Downloaded scripts run only if signed by a trusted publisher.
+# - AllSigned: Scripts need to be signed by a trusted publisher.
+# - Unrestricted: Run all scripts.
+help about_Execution_Policies # for more info
+
+# Current PowerShell version:
+$PSVersionTable
+```
+
+Getting help:
+
+```
+# Find commands
+Get-Command about_* # alias: gcm
+Get-Command -Verb Add
+Get-Alias ps
+Get-Alias -Definition Get-Process
+
+Get-Help ps | less # alias: help
+ps | Get-Member # alias: gm
+
+Show-Command Get-EventLog # Display GUI to fill in the parameters
+
+Update-Help # Run as admin
+```
+
+The tutorial starts here:
+
+```
+# As you already figured, comments start with #
+
+# Simple hello world example:
+echo Hello world!
+# echo is an alias for Write-Output (=cmdlet)
+# Most cmdlets and functions follow the Verb-Noun naming convention
+
+# Each command starts on a new line, or after a semicolon:
+echo 'This is the first line'; echo 'This is the second line'
+
+# Declaring a variable looks like this:
+$aString="Some string"
+# Or like this:
+$aNumber = 5 -as [double]
+$aList = 1,2,3,4,5
+$aString = $aList -join '--' # yes, -split exists also
+$aHashtable = @{name1='val1'; name2='val2'}
+
+# Using variables:
+echo $aString
+echo "Interpolation: $aString"
+echo "`$aString has length of $($aString.Length)"
+echo '$aString'
+echo @"
+This is a Here-String
+$aString
+"@
+# Note that ' (single quote) won't expand the variables!
+# Here-Strings also work with single quote
+
+# Builtin variables:
+# There are some useful builtin variables, like
+echo "Booleans: $TRUE and $FALSE"
+echo "Empty value: $NULL"
+echo "Last program's return value: $?"
+echo "Exit code of last run Windows-based program: $LastExitCode"
+echo "The last token in the last line received by the session: $$"
+echo "The first token: $^"
+echo "Script's PID: $PID"
+echo "Full path of current script directory: $PSScriptRoot"
+echo 'Full path of current script: ' + $MyInvocation.MyCommand.Path
+echo "FUll path of current directory: $Pwd"
+echo "Bound arguments in a function, script or code block: $PSBoundParameters"
+echo "Unbound arguments: $($Args -join ', ')."
+# More builtins: `help about_Automatic_Variables`
+
+# Inline another file (dot operator)
+. .\otherScriptName.ps1
+
+
+### Control Flow
+# We have the usual if structure:
+if ($Age -is [string]) {
+ echo 'But.. $Age cannot be a string!'
+} elseif ($Age -lt 12 -and $Age -gt 0) {
+ echo 'Child (Less than 12. Greater than 0)'
+} else {
+ echo 'Adult'
+}
+
+# Switch statements are more powerfull compared to most languages
+$val = "20"
+switch($val) {
+ { $_ -eq 42 } { "The answer equals 42"; break }
+ '20' { "Exactly 20"; break }
+ { $_ -like 's*' } { "Case insensitive"; break }
+ { $_ -clike 's*'} { "clike, ceq, cne for case sensitive"; break }
+ { $_ -notmatch '^.*$'} { "Regex matching. cnotmatch, cnotlike, ..."; break }
+ { 'x' -contains 'x'} { "FALSE! -contains is for lists!"; break }
+ default { "Others" }
+}
+
+# The classic for
+for($i = 1; $i -le 10; $i++) {
+ "Loop number $i"
+}
+# Or shorter
+1..10 | % { "Loop number $_" }
+
+# PowerShell also offers
+foreach ($var in 'val1','val2','val3') { echo $var }
+# while () {}
+# do {} while ()
+# do {} until ()
+
+# Exception handling
+try {} catch {} finally {}
+try {} catch [System.NullReferenceException] {
+ echo $_.Exception | Format-List -Force
+}
+
+
+### Providers
+# List files and directories in the current directory
+ls # or `dir`
+cd ~ # goto home
+
+Get-Alias ls # -> Get-ChildItem
+# Uh!? These cmdlets have generic names because unlike other scripting
+# languages, PowerShell does not only operate in the current directory.
+cd HKCU: # go to the HKEY_CURRENT_USER registry hive
+
+# Get all providers in your session
+Get-PSProvider
+
+
+### Pipeline
+# Cmdlets have parameters that control their execution:
+Get-ChildItem -Filter *.txt -Name # Get just the name of all txt files
+# Only need to type as much of a parameter name until it is no longer ambiguous
+ls -fi *.txt -n # -f is not possible because -Force also exists
+# Use `Get-Help Get-ChildItem -Full` for a complete overview
+
+# Results of the previous cmdlet can be passed to the next as input.
+# `$_` is the current object in the pipeline object.
+ls | Where-Object { $_.Name -match 'c' } | Export-CSV export.txt
+ls | ? { $_.Name -match 'c' } | ConvertTo-HTML | Out-File export.html
+
+# If you get confused in the pipeline use `Get-Member` for an overview
+# of the available methods and properties of the pipelined objects:
+ls | Get-Member
+Get-Date | gm
+
+# ` is the line continuation character. Or end the line with a |
+Get-Process | Sort-Object ID -Descending | Select-Object -First 10 Name,ID,VM `
+ | Stop-Process -WhatIf
+
+Get-EventLog Application -After (Get-Date).AddHours(-2) | Format-List
+
+# Use % as a shorthand for ForEach-Object
+(a,b,c) | ForEach-Object `
+ -Begin { "Starting"; $counter = 0 } `
+ -Process { "Processing $_"; $counter++ } `
+ -End { "Finishing: $counter" }
+
+# Get-Process as a table with three columns
+# The third column is the value of the VM property in MB and 2 decimal places
+# Computed columns can be written more verbose as:
+# `@{name='lbl';expression={$_}`
+ps | Format-Table ID,Name,@{n='VM(MB)';e={'{0:n2}' -f ($_.VM / 1MB)}} -autoSize
+
+
+### Functions
+# The [string] attribute is optional.
+function foo([string]$name) {
+ echo "Hey $name, have a function"
+}
+
+# Calling your function
+foo "Say my name"
+
+# Functions with named parameters, parameter attributes, parsable documention
+<#
+.SYNOPSIS
+Setup a new website
+.DESCRIPTION
+Creates everything your new website needs for much win
+.PARAMETER siteName
+The name for the new website
+.EXAMPLE
+New-Website -Name FancySite -Po 5000
+New-Website SiteWithDefaultPort
+New-Website siteName 2000 # ERROR! Port argument could not be validated
+('name1','name2') | New-Website -Verbose
+#>
+function New-Website() {
+ [CmdletBinding()]
+ param (
+ [Parameter(ValueFromPipeline=$true, Mandatory=$true)]
+ [Alias('name')]
+ [string]$siteName,
+ [ValidateSet(3000,5000,8000)]
+ [int]$port = 3000
+ )
+ BEGIN { Write-Verbose 'Creating new website(s)' }
+ PROCESS { echo "name: $siteName, port: $port" }
+ END { Write-Verbose 'Website(s) created' }
+}
+
+
+### It's all .NET
+# A PS string is in fact a .NET System.String
+# All .NET methods and properties are thus available
+'string'.ToUpper().Replace('G', 'ggg')
+# Or more powershellish
+'string'.ToUpper() -replace 'G', 'ggg'
+
+# Unsure how that .NET method is called again?
+'string' | gm
+
+# Syntax for calling static .NET methods
+[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
+
+# Note that .NET functions MUST 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)
+$writer.Dispose()
+
+### IO
+# Reading a value from input:
+$Name = Read-Host "What's your name?"
+echo "Hello, $Name!"
+[int]$Age = Read-Host "What's your age?"
+
+# Test-Path, Split-Path, Join-Path, Resolve-Path
+# Get-Content filename # returns a string[]
+# Set-Content, Add-Content, Clear-Content
+Get-Command ConvertTo-*,ConvertFrom-*
+
+
+### Useful stuff
+# 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
+
+# Open Windows Explorer in working directory
+ii .
+
+# Any key to exit
+$host.UI.RawUI.ReadKey()
+return
+
+# Create a shortcut
+$WshShell = New-Object -comObject WScript.Shell
+$Shortcut = $WshShell.CreateShortcut($link)
+$Shortcut.TargetPath = $file
+$Shortcut.WorkingDirectory = Split-Path $file
+$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
+if (-not (Test-Path $Profile)) {
+ New-Item -Type file -Path $Profile -Force
+ notepad $Profile
+}
+# More info: `help about_profiles`
+# For a more usefull shell, be sure to check the project PSReadLine below
+```
+
+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!)
+* [Posh-Git](https://github.com/dahlbyk/posh-git/) Fancy Git Prompt (Recommended!)
+* [PSake](https://github.com/psake/psake) Build automation tool
+* [Pester](https://github.com/pester/Pester) BDD Testing Framework
+* [Jump-Location](https://github.com/tkellogg/Jump-Location) Powershell `cd` that reads your mind
+* [PowerShell Community Extensions](http://pscx.codeplex.com/) (Dead)
+
+Not covered
+
+* WMI: Windows Management Intrumentation (Get-CimInstance)
+* Multitasking: Start-Job -scriptBlock {...},
+* Code Signing
+* Remoting (Enter-PSSession/Exit-PSSession; Invoke-Command)
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/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/c-pt.html.markdown b/pt-br/c-pt.html.markdown
index 451df4f3..2c274f12 100644
--- a/pt-br/c-pt.html.markdown
+++ b/pt-br/c-pt.html.markdown
@@ -6,29 +6,31 @@ contributors:
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
translators:
- ["João Farias", "https://github.com/JoaoGFarias"]
+ - ["Elton Viana", "https://github.com/eltonvs"]
+ - ["Cássio Böck", "https://github.com/cassiobsilva"]
lang: pt-br
filename: c-pt.el
---
Ah, C. Ainda é **a** linguagem de computação de alta performance.
-C é a liguangem de mais baixo nível que a maioria dos programadores
-irão usar, e isso dá a ela uma grande velocidade bruta. Apenas fique
-antento que este manual de gerenciamento de memória e C vai levanter-te
-tão longe quanto você precisa.
+C é a linguagem de mais baixo nível que a maioria dos programadores
+utilizarão, e isso dá a ela uma grande velocidade bruta. Apenas fique
+atento se este manual de gerenciamento de memória e C vai te levar
+tão longe quanto precisa.
```c
// Comentários de uma linha iniciam-se com // - apenas disponível a partir do C99
/*
-Comentários de multiplas linhas se parecem com este.
+Comentários de múltiplas linhas se parecem com este.
Funcionam no C89 também.
*/
// Constantes: #define <palavra-chave>
#definie DAY_IN_YEAR 365
-//enumarações também são modos de definir constantes.
+//enumerações também são modos de definir constantes.
enum day {DOM = 1, SEG, TER, QUA, QUI, SEX, SAB};
// SEG recebe 2 automaticamente, TER recebe 3, etc.
@@ -53,13 +55,13 @@ int soma_dois_ints(int x1, int x2); // protótipo de função
// O ponto de entrada do teu programa é uma função
// chamada main, com tipo de retorno inteiro
int main() {
- // Usa-se printf para escrever na tela,
+ // Usa-se printf para escrever na tela,
// para "saída formatada"
// %d é um inteiro, \n é uma nova linha
printf("%d\n", 0); // => Imprime 0
// Todos as declarações devem acabar com
// ponto e vírgula
-
+
///////////////////////////////////////
// Tipos
///////////////////////////////////////
@@ -77,7 +79,7 @@ int main() {
// longs tem entre 4 e 8 bytes; longs long tem garantia
// de ter pelo menos 64 bits
long x_long = 0;
- long long x_long_long = 0;
+ long long x_long_long = 0;
// floats são normalmente números de ponto flutuante
// com 32 bits
@@ -92,7 +94,7 @@ int main() {
unsigned int ux_int;
unsigned long long ux_long_long;
- // caracteres dentro de aspas simples são inteiros
+ // caracteres dentro de aspas simples são inteiros
// no conjunto de caracteres da máquina.
'0' // => 48 na tabela ASCII.
'A' // => 65 na tabela ASCII.
@@ -103,7 +105,7 @@ int main() {
// Se o argumento do operador `sizeof` é uma expressão, então seus argumentos
// não são avaliados (exceto em VLAs (veja abaixo)).
- // O valor devolve, neste caso, é uma constante de tempo de compilação.
+ // O valor devolve, neste caso, é uma constante de tempo de compilação.
int a = 1;
// size_t é um inteiro sem sinal com pelo menos 2 bytes que representa
// o tamanho de um objeto.
@@ -119,7 +121,7 @@ int main() {
// Você pode inicializar um array com 0 desta forma:
char meu_array[20] = {0};
- // Indexar um array é semelhante a outras linguages
+ // Indexar um array é semelhante a outras linguagens
// Melhor dizendo, outras linguagens são semelhantes a C
meu_array[0]; // => 0
@@ -128,7 +130,7 @@ int main() {
printf("%d\n", meu_array[1]); // => 2
// No C99 (e como uma features opcional em C11), arrays de tamanho variável
- // VLA (do inglês), podem ser declarados também. O tamanho destes arrays
+ // VLA (do inglês), podem ser declarados também. O tamanho destes arrays
// não precisam ser uma constante de tempo de compilação:
printf("Entre o tamanho do array: "); // Pergunta ao usuário pelo tamanho
char buf[0x100];
@@ -139,22 +141,22 @@ int main() {
int var_length_array[size]; // declara o VLA
printf("sizeof array = %zu\n", sizeof var_length_array);
- //Uma possível saída para esse programa seria:
- // > Entre o tamanho do array:: 10
+ // Uma possível saída para esse programa seria:
+ // > Entre o tamanho do array: 10
// > sizeof array = 40
- // String são apenas arrays de caracteres terminados por um
- // byte NUL (0x00), representado em string pelo caracter especial '\0'.
- // (Não precisamos incluir o byte NUL em literais de string; o compilador
+ // String são apenas arrays de caracteres terminados por um
+ // byte nulo (0x00), representado em string pelo caracter especial '\0'.
+ // (Não precisamos incluir o byte nulo em literais de string; o compilador
// o insere ao final do array para nós.)
- char uma_string[20] = "Isto é uma string";
+ char uma_string[20] = "Isto é uma string";
// Observe que 'é' não está na tabela ASCII
// A string vai ser salva, mas a saída vai ser estranha
- // Porém, comentários podem conter acentos
+ // Porém, comentários podem conter acentos
printf("%s\n", uma_string); // %s formata a string
- printf("%d\n", uma_string[16]); // => 0
- // i.e., byte #17 é 0 (assim como 18, 19, e 20)
+ printf("%d\n", uma_string[17]); // => 0
+ // i.e., byte #18 é 0 (assim como o 19°, 20°, 21°...)
// Se temos caracteres entre aspas simples, temos um caracter literal.
// Seu tipo é `int`, *não* `char` (por razões históricas).
@@ -174,7 +176,7 @@ int main() {
///////////////////////////////////////
// Atalho para multiplas declarações:
- int i1 = 1, i2 = 2;
+ int i1 = 1, i2 = 2;
float f1 = 1.0, f2 = 2.0;
int a, b, c;
@@ -205,7 +207,7 @@ int main() {
2 <= 2; // => 1
2 >= 2; // => 1
- // C não é Python - comparações não se encadeam.
+ // C não é Python - comparações não se encadeiam.
int a = 1;
// Errado:
int entre_0_e_2 = 0 < a < 2;
@@ -220,17 +222,17 @@ int main() {
0 || 1; // => 1 (Ou lógico)
0 || 0; // => 0
- //Expressão condicional ( ? : )
+ //Expressão condicional ternária ( ? : )
int a = 5;
int b = 10;
int z;
- z = (a > b) ? a : b; // => 10 "se a > b retorne a, senão retorne b."
+ z = (a > b) ? a : b; // => 10 "se a > b retorne a, senão retorne b."
//Operadores de incremento e decremento:
char *s = "iLoveC";
int j = 0;
s[j++]; // => "i". Retorna o j-ésimo item de s E DEPOIS incrementa o valor de j.
- j = 0;
+ j = 0;
s[++j]; // => "L". Incrementa o valor de j. E DEPOIS retorna o j-ésimo item de s.
// o mesmo com j-- e --j
@@ -290,6 +292,8 @@ int main() {
for (i = 0; i <= 5; i++) {
; // Use ponto e vírgula para agir como um corpo (declaração nula)
}
+ // Ou
+ for (i = 0; i <= 5; i++);
// Criando branchs com escolhas múltiplas: switch()
switch (alguma_expressao_integral) {
@@ -305,7 +309,7 @@ int main() {
exit(-1);
break;
}
-
+
///////////////////////////////////////
// Cast de tipos
@@ -324,8 +328,8 @@ int main() {
// Tipos irão ter overflow sem aviso
printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 se char tem 8 bits)
- // Para determinar o valor máximo de um `char`, de um `signed char` e de
- // um `unisigned char`, respectivamente, use as macros CHAR_MAX, SCHAR_MAX
+ // Para determinar o valor máximo de um `char`, de um `signed char` e de
+ // um `unisigned char`, respectivamente, use as macros CHAR_MAX, SCHAR_MAX
// e UCHAR_MAX de <limits.h>
// Tipos inteiros podem sofrer cast para pontos-flutuantes e vice-versa.
@@ -338,7 +342,7 @@ int main() {
///////////////////////////////////////
// Um ponteiro é uma variável declarada para armazenar um endereço de memória.
- // Seu declaração irá também dizer o tipo de dados para o qual ela aponta. Você
+ // Sua declaração irá também dizer o tipo de dados para o qual ela aponta. Você
// Pode usar o endereço de memória de suas variáveis, então, brincar com eles.
int x = 0;
@@ -360,13 +364,13 @@ int main() {
printf("%d\n", *px); // => Imprime 0, o valor de x
// Você também pode mudar o valor que o ponteiro está apontando.
- // Teremo que cercar a de-referência entre parenteses, pois
+ // Temos que cercar a de-referência entre parênteses, pois
// ++ tem uma precedência maior que *.
(*px)++; // Incrementa o valor que px está apontando por 1
printf("%d\n", *px); // => Imprime 1
printf("%d\n", x); // => Imprime 1
- // Arrays são um boa maneira de alocar um bloco contínuo de memória
+ // Arrays são uma boa maneira de alocar um bloco contínuo de memória
int x_array[20]; // Declara um array de tamanho 20 (não pode-se mudar o tamanho
int xx;
for (xx = 0; xx < 20; xx++) {
@@ -376,7 +380,7 @@ int main() {
// Declara um ponteiro do tipo int e inicialize ele para apontar para x_array
int* x_ptr = x_array;
// x_ptr agora aponta para o primeiro elemento do array (o inteiro 20).
- // Isto funciona porque arrays são apenas ponteiros para seu primeiros elementos.
+ // Isto funciona porque arrays são apenas ponteiros para seus primeiros elementos.
// Por exemplo, quando um array é passado para uma função ou é atribuído a um
// ponteiro, ele transforma-se (convertido implicitamente) em um ponteiro.
// Exceções: quando o array é o argumento de um operador `&` (endereço-de):
@@ -392,7 +396,7 @@ int main() {
printf("%zu, %zu\n", sizeof arr, sizeof ptr); // provavelmente imprime "40, 4" ou "40, 8"
// Ponteiros podem ser incrementados ou decrementados baseado no seu tipo
- // (isto é chamado aritimética de ponteiros
+ // (isto é chamado aritmética de ponteiros
printf("%d\n", *(x_ptr + 1)); // => Imprime 19
printf("%d\n", x_array[1]); // => Imprime 19
@@ -410,9 +414,9 @@ int main() {
// "resultados imprevisíveis" - o programa é dito ter um "comportamento indefinido"
printf("%d\n", *(my_ptr + 21)); // => Imprime quem-sabe-o-que? Talvez até quebre o programa.
- // Quando termina-se de usar um bloco de memória alocado, você pode liberá-lo,
+ // Quando se termina de usar um bloco de memória alocado, você pode liberá-lo,
// ou ninguém mais será capaz de usá-lo até o fim da execução
- // (Isto cham-se "memory leak"):
+ // (Isto chama-se "memory leak"):
free(my_ptr);
// Strings são arrays de char, mas elas geralmente são representadas
@@ -534,7 +538,7 @@ int area(retan r)
return r.largura * r.altura;
}
-// Se você tiver structus grande, você pode passá-las "por ponteiro"
+// Se você tiver structus grande, você pode passá-las "por ponteiro"
// para evitar cópia de toda a struct:
int area(const retan *r)
{
@@ -551,8 +555,8 @@ conhecidos. Ponteiros para funções são como qualquer outro ponteiro
diretamente e passá-las para por toda parte.
Entretanto, a sintaxe de definição por ser um pouco confusa.
-Exemplo: use str_reverso através de um ponteiro
-*/
+Exemplo: use str_reverso através de um ponteiro
+*/
void str_reverso_através_ponteiro(char *str_entrada) {
// Define uma variável de ponteiro para função, nomeada f.
void (*f)(char *); //Assinatura deve ser exatamente igual à função alvo.
@@ -572,7 +576,7 @@ typedef void (*minha_função_type)(char *);
// Declarando o ponteiro:
// ...
-// minha_função_type f;
+// minha_função_type f;
//Caracteres especiais:
'\a' // Alerta (sino)
@@ -583,7 +587,7 @@ typedef void (*minha_função_type)(char *);
'\r' // Retorno de carroça
'\b' // Backspace
'\0' // Caracter nulo. Geralmente colocado ao final de string em C.
- // oi\n\0. \0 é usado por convenção para marcar o fim da string.
+ // oi\n\0. \0 é usado por convenção para marcar o fim da string.
'\\' // Barra invertida
'\?' // Interrogação
'\'' // Aspas simples
@@ -603,7 +607,7 @@ typedef void (*minha_função_type)(char *);
"%p" // ponteiro
"%x" // hexadecimal
"%o" // octal
-"%%" // imprime %
+"%%" // imprime %
///////////////////////////////////////
// Ordem de avaliação
diff --git a/pt-br/clojure-macros-pt.html.markdown b/pt-br/clojure-macros-pt.html.markdown
new file mode 100644
index 00000000..dbc0c25c
--- /dev/null
+++ b/pt-br/clojure-macros-pt.html.markdown
@@ -0,0 +1,154 @@
+---
+language: clojure
+filename: learnclojure-pt.clj
+contributors:
+ - ["Adam Bard", "http://adambard.com/"]
+translators:
+ - ["Raphael Bezerra do Nascimento"]
+lang: pt-br
+---
+
+Como todas as Lisps, a inerente [homoiconicity](https://en.wikipedia.org/wiki/Homoiconic)
+do Clojure lhe dá acesso a toda a extensão da linguagem
+para escrever rotinas de geração de código chamados "macros". Macros fornecem uma poderosa forma de adequar a linguagem
+às suas necessidades.
+
+Pórem Tenha cuidado. É considerado má pratica escrever uma macro quando uma função vai fazer. Use uma macro apenas
+quando você precisar do controle sobre quando ou se os argumentos para um formulário será avaliado.
+
+Você vai querer estar familiarizado com Clojure. Certifique-se de entender tudo em
+[Clojure em Y Minutos](/docs/clojure/).
+
+```clojure
+;; Defina uma macro utilizando defmacro. Sua macro deve ter como saida uma lista que possa
+;; ser avaliada como codigo Clojure.
+;;
+;; Essa macro é a mesma coisa que se você escrever (reverse "Hello World")
+(defmacro my-first-macro []
+ (list reverse "Hello World"))
+
+;; Inspecione o resultado de uma macro utilizando macroexpand or macroexpand-1.
+;;
+;; Note que a chamada deve utilizar aspas simples.
+(macroexpand '(my-first-macro))
+;; -> (#<core$reverse clojure.core$reverse@xxxxxxxx> "Hello World")
+
+;; Você pode avaliar o resultad de macroexpand diretamente:
+(eval (macroexpand '(my-first-macro)))
+; -> (\d \l \o \r \W \space \o \l \l \e \H)
+
+;; mas você deve usar esse mais suscinto, sintax como de função:
+(my-first-macro) ; -> (\d \l \o \r \W \space \o \l \l \e \H)
+
+;; Você pode tornar as coisas mais faceis pra você, utilizando a sintaxe de citação mais suscinta
+;; para criar listas nas suas macros:
+(defmacro my-first-quoted-macro []
+ '(reverse "Hello World"))
+
+(macroexpand '(my-first-quoted-macro))
+;; -> (reverse "Hello World")
+;; Note que reverse não é mais uma função objeto, mas um simbolo.
+
+;; Macros podem ter argumentos.
+(defmacro inc2 [arg]
+ (list + 2 arg))
+
+(inc2 2) ; -> 4
+
+;; Mas se você tentar fazer isso com uma lista entre aspas simples, você vai receber um erro, por que o
+;; argumento irá entra aspas simples também. Para contornar isso, Clojure prover uma maneira de utilizar aspas simples
+;; em macros: `. Dentro `, você pode usar ~ para chegar ao escopo externo.
+(defmacro inc2-quoted [arg]
+ `(+ 2 ~arg))
+
+(inc2-quoted 2)
+
+;; Você pode usar os argumentos de destruturação habituais. Expandir lista de variaveis usando ~@
+(defmacro unless [arg & body]
+ `(if (not ~arg)
+ (do ~@body))) ; Lembrar o do!
+
+(macroexpand '(unless true (reverse "Hello World")))
+;; ->
+;; (if (clojure.core/not true) (do (reverse "Hello World")))
+
+;; (unless) avalia e retorna seu corpo, se o primeiro argumento é falso.
+;; caso contrario, retorna nil
+
+(unless true "Hello") ; -> nil
+(unless false "Hello") ; -> "Hello"
+
+;; Usado sem cuidados, macros podem fazer muito mal por sobreporem suas variaveis
+(defmacro define-x []
+ '(do
+ (def x 2)
+ (list x)))
+
+(def x 4)
+(define-x) ; -> (2)
+(list x) ; -> (2)
+
+;;s Para evitar isso, use gensym para receber um identificador unico
+(gensym 'x) ; -> x1281 (ou outra coisa)
+
+(defmacro define-x-safely []
+ (let [sym (gensym 'x)]
+ `(do
+ (def ~sym 2)
+ (list ~sym))))
+
+(def x 4)
+(define-x-safely) ; -> (2)
+(list x) ; -> (4)
+
+;; Você pode usar # dentro de ` para produzir uma gensym para cada simbolo automaticamente
+(defmacro define-x-hygenically []
+ `(do
+ (def x# 2)
+ (list x#)))
+
+(def x 4)
+(define-x-hygenically) ; -> (2)
+(list x) ; -> (4)
+
+;; É típico o uso de funções de auxilio com macros. Vamos criar um pouco
+;; Vamos criar um pouco para nos ajudar a suportar uma sintaxe aritmética inline (estupida)
+(declare inline-2-helper)
+(defn clean-arg [arg]
+ (if (seq? arg)
+ (inline-2-helper arg)
+ arg))
+
+(defn apply-arg
+ "Given args [x (+ y)], return (+ x y)"
+ [val [op arg]]
+ (list op val (clean-arg arg)))
+
+(defn inline-2-helper
+ [[arg1 & ops-and-args]]
+ (let [ops (partition 2 ops-and-args)]
+ (reduce apply-arg (clean-arg arg1) ops)))
+
+;; Podemos testar isso imediatamente, sem criar uma macro
+(inline-2-helper '(a + (b - 2) - (c * 5))) ; -> (- (+ a (- b 2)) (* c 5))
+
+; Entretanto, temos que tornar isso uma macro caso quisermos que isso seja rodado em tempo de compilação
+(defmacro inline-2 [form]
+ (inline-2-helper form)))
+
+(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1)))
+; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1)
+
+(inline-2 (1 + (3 / 2) - (1 / 2) + 1))
+; -> 3 (Na verdade, 3N, desde que o numero ficou convertido em uma fração racional com /
+
+### Leitura adicional
+
+Escrevendo Macros de [Clojure para o Brave e True](http://www.braveclojure.com/)
+[http://www.braveclojure.com/writing-macros/](http://www.braveclojure.com/writing-macros/)
+
+Documentos oficiais
+[http://clojure.org/macros](http://clojure.org/macros)
+
+Quando utilizar macros?
+[http://dunsmor.com/lisp/onlisp/onlisp_12.html](http://dunsmor.com/lisp/onlisp/onlisp_12.html)
diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown
new file mode 100644
index 00000000..b1fbd961
--- /dev/null
+++ b/pt-br/css-pt.html.markdown
@@ -0,0 +1,257 @@
+---
+language: css
+filename: learncss-pt.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"]
+translators:
+ - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"]
+lang: pt-br
+---
+
+Nos primeiros dias da web não havia elementos visuais, apenas texto puro. Mas com maior desenvolvimento de navegadores da web, páginas web totalmente visuais também se tornou comum.
+
+CSS ajuda a manter a separação entre o conteúdo (HTML) e o look-and-feel de uma página web.
+
+CSS permite atingir diferentes elementos em uma página HTML e atribuir diferentes propriedades visuais para eles.
+
+Este guia foi escrito para CSS2, embora CSS3 está rapidamente se tornando popular.
+
+**NOTA:** Porque CSS produz resultados visuais, a fim de aprender, você precisa tentar de tudo em um playground CSS como [dabblet](http://dabblet.com/).
+O foco principal deste artigo é sobre a sintaxe e algumas dicas gerais.
+
+```css
+/* Comentários aparecem dentro do slash-asterisk, tal como esta linha!
+ não há "comentários de uma linha"; este é o único estilo de comentário * /
+
+/* ####################
+ ## SELETORES
+ #################### */
+
+/* O seletor é usado para direcionar um elemento em uma página.
+ seletor { propriedade: valor; / * Mais propriedades ... * / }
+
+/*
+Abaixo um elemento de exemplo:
+
+<div class='class1 class2' id='anID' attr='value' otherAttr='pt-br foo bar' />
+*/
+
+/* Você pode direciona-lo usando uma das suas classes CSS */
+.class1 { }
+
+/* ou ambas as classes! */
+.class1.class2 { }
+
+/* ou o seu nome */
+div { }
+
+/* ou o seu id */
+#anID { }
+
+/* ou utilizando o fator de que tem um atributo!*/
+[attr] { font-size:smaller; }
+
+/* ou que o atributo tem um valor específico */
+[attr='value'] { font-size:smaller; }
+
+/* começa com um valor (CSS 3) */
+[attr^='val'] { font-size:smaller; }
+
+/* ou terminando com um valor (CSS 3) */
+[attr$='ue'] { font-size:smaller; }
+
+
+/* Ou contém um valor em uma lista separada por espaços */
+[otherAttr ~ = 'foo'] {}
+[otherAttr ~ = 'bar'] {}
+
+/* Ou contém um valor em uma lista separada por hífen, ou seja, "-" (U + 002D) */
+[otherAttr | = 'en'] {font-size: smaller; }
+
+
+/* Você pode concatenar diferentes seletores para criar um seletor mais estreito. Não
+   colocar espaços entre eles. */
+classe div.some [attr $ = 'ue'] {}
+
+/* Você pode selecionar um elemento que é filho de outro elemento */
+div.some-parent> .class-name {}
+
+/* Ou um descendente de um outro elemento. As crianças são os descendentes diretos de
+   seu elemento pai, apenas um nível abaixo da árvore. Pode ser qualquer descendentes
+   nivelar por baixo da árvore. */
+div.some-parent class-name {}
+
+/* Atenção: o mesmo seletor sem espaço tem um outro significado.
+   Você consegue adivinhar o que? */
+div.some-parent.class-name {}
+
+/* Você também pode selecionar um elemento com base em seu irmão adjacente */
+.i am just-antes + .Este elemento {}
+
+/* Ou qualquer irmão que o precede */
+.i am-qualquer-elemento antes ~ .Este elemento {}
+
+/* Existem alguns selectores chamado pseudo classes que podem ser usados para selecionar um
+   elemento quando ele está em um determinado estado */
+
+/* Por exemplo, quando o cursor passa sobre um elemento */
+seletor:hover {}
+
+/* Ou um link foi visitado */
+seletor:visited {}
+
+/* Ou não tenha sido visitado */
+seletor:link {}
+
+/* Ou um elemento em foco */
+seletor:focus {}
+
+/* Qualquer elemento que é o primeiro filho de seu pai */
+seletor:first-child {}
+
+/* Qualquer elemento que é o último filho de seu pai */
+seletor:last-child {}
+
+/* Assim como pseudo classes, pseudo elementos permitem que você estilo certas partes de um documento */
+
+/* Corresponde a um primeiro filho virtual do elemento selecionado */
+seletor::before {}
+
+/* Corresponde a um último filho virtual do elemento selecionado */
+seletor::after {}
+
+/* Nos locais apropriados, um asterisco pode ser utilizado como um curinga para selecionar todos
+   elemento */
+* {} /* */ Todos os elementos
+.parent * {} /* */ todos os descendentes
+.parent> * {} /* */ todas as crianças
+
+/* ####################
+   ## PROPRIEDADES
+   #################### */
+
+seletor {
+
+    /* Unidades de comprimento pode ser absoluta ou relativa. */
+
+    /* Unidades relativas */
+    width: 50%; /* Percentagem de largura elemento pai */
+    font-size: 2em; /* Múltiplos de font-size original de elemento */
+    font-size: 2rem; /* Ou do elemento raiz font-size */
+    font-size: 2vw; /* Múltiplos de 1% da largura da janela de exibição (CSS 3) */
+    font-size: 2vh; /* Ou a sua altura */
+    font-size: 2vmin; /* Qualquer um de VH ou um VW é menor */
+    font-size: 2vmax; /* Ou superior */
+
+    /* Unidades absolutas */
+    width: 200px; /* píxeis */
+    font-size: 20pt; /* Pontos */
+    width: 5cm; /* Centímetros */
+    min-width: 50mm; /* Milímetros */
+    max-width: 5 polegadas; /* Polegadas */
+
+    /* Cores */
+    color: # F6E; /* Formato hexadecimal curto */
+    color: # FF66EE; /* Formato hexadecimal longo */
+    color: tomato; /* Uma cor nomeada */
+    color: rgb (255, 255, 255); /* Como valores rgb */
+    color: RGB (10%, 20%, 50%); /* Como porcentagens rgb */
+    color: rgba (255, 0, 0, 0,3); /* Como valores RGBA (CSS 3) NOTA: 0 <a <1 */
+    color: transparent; /* Equivale a definir o alfa a 0 */
+    color: HSL (0, 100%, 50%); /* Como porcentagens HSL (CSS 3) */
+    color: HSLA (0, 100%, 50%, 0,3); /* Como porcentagens HSLA com alfa */
+
+    /* Imagens como fundos de elementos */
+    background-image: url (/img-path/img.jpg); /* Citações dentro url () opcional */
+
+    /* Fontes */
+    font-family: Arial;
+    /* Se o nome da família de fonte tem um espaço, deve ser citado */
+    font-family: "Courier New";
+    /* Se o primeiro não for encontrada, o navegador usa o próximo, e assim por diante */
+    font-family: "Courier New", Trebuchet, Arial, sans-serif;
+}
+```
+
+## Uso
+
+Guardar uma folha de estilo CSS com a extensão `.css`.
+
+```xml
+<!-- Você precisa incluir o arquivo css no da sua página <head>. Isto é o
+     método recomendado. Consulte http://stackoverflow.com/questions/8284365 -->
+<link rel='stylesheet' type='text/css' href='path/to/style.css' />
+
+<!-- Você também pode incluir alguns CSS inline na sua marcação. -->
+<style>
+   a { color: purple; }
+</style>
+
+<!-- Ou diretamente definir propriedades CSS no elemento. -->
+<div style="border: 1px solid red;">
+</div>
+```
+
+## Precedência ou Cascata
+
+Um elemento pode ser alvo de vários seletores e pode ter um conjunto de propriedades em que mais de uma vez. Nestes casos, uma das regras tem precedência sobre os outros. Geralmente, uma regra em um seletor mais específico têm precedência sobre um menos específico, e uma regra que ocorre mais tarde na folha de estilo substitui uma anterior.
+
+Este processo é chamado de cascata, portanto, as Fichas de nome de estilo em cascata.
+
+Dado o seguinte CSS:
+
+```css
+/* UMA */
+p.class1[attr="value"]
+
+/* B */
+p.class1 {}
+
+/* C */
+p.class2 {}
+
+/* D */
+p { }
+
+/* E */
+p { property: value !important; }
+```
+
+e a seguinte marcação:
+
+```xml
+<p style='/*F*/ property:value;' class='class1 class2' attr='value' />
+```
+
+A precedência de estilo é a seguinte. Lembre-se, a precedência é para cada **propriedade**, não para todo o bloco.
+
+* `E` tem a precedência mais alta por causa de uma palavra-chave`!important`. É recomendável que você evitar seu uso.
+* `F` é a próxima, porque é um estilo interno.
+* `A` é a próxima, porque é mais" específico "do que qualquer outra coisa. Tem 3 especificadores: O nome do elemento `p`, o seu `class1` classe, um atributo `attr='value'`.
+* `C` está próximo, mesmo que ele tenha a mesma especificidade que `B`. Isso é porque ele aparece depois de `B`.
+* `B` é o próximo.
+* `D` é a última.
+
+## Compatibilidade
+
+A maior parte dos recursos do CSS 2 (e muitos em CSS 3) estão disponíveis em todos os navegadores e dispositivos. Mas é sempre boa prática para verificar antes de usar um novo recurso.
+
+## Recursos
+
+* Para executar uma verificação de compatibilidade rápida, [CanIUse](http://caniuse.com).
+* CSS Playground [Dabblet](http://dabblet.com/).
+* [Documentação CSS Mozilla Developer Rede](https://developer.mozilla.org/en-US/docs/Web/CSS)
+* [Codrops 'Referência CSS](http://tympanus.net/codrops/css_reference/)
+
+## Leitura adicional
+
+* [Entendendo Estilo Precedência em CSS: Especificidade, Herança, eo Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
+* [Selecionando elementos usando atributos](https://css-tricks.com/almanac/selectors/a/attribute/)
+* [QuirksMode CSS](http://www.quirksmode.org/css/)
+* [Z-Index - O empilhamento context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
+* [SASS](http://sass-lang.com/) e [menos](http://lesscss.org/) para CSS pré-processamento
+* [CSS-Tricks](https://css-tricks.com)
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 a884f273..3c9512aa 100644
--- a/pt-br/java-pt.html.markdown
+++ b/pt-br/java-pt.html.markdown
@@ -405,6 +405,219 @@ class Velocipede extends Bicicleta {
}
+// Interfaces
+// Sintaxe de declaração de Interface
+// <nível de acesso> Interface <nome-da-interface> extends <super-interfaces> {
+// // Constantes
+// // Declarações de método
+//}
+
+// Exemplo - Comida:
+public interface Comestivel {
+ public void comer(); // Qualquer classe que implementa essa interface, deve
+                        // Implementar este método.
+}
+
+public interface Digestivel {
+ public void digerir();
+}
+
+
+// Agora podemos criar uma classe que implementa ambas as interfaces.
+public class Fruta implements Comestivel, Digestivel {
+
+ @Override
+ public void comer() {
+ // ...
+ }
+
+ @Override
+ public void digerir() {
+ // ...
+ }
+}
+
+// Em Java, você pode estender somente uma classe, mas você pode implementar muitas
+// Interfaces. Por exemplo:
+public class ClasseExemplo extends ExemploClassePai implements InterfaceUm,
+ InterfaceDois {
+
+ @Override
+ public void InterfaceUmMetodo() {
+ }
+
+ @Override
+ public void InterfaceDoisMetodo() {
+ }
+
+}
+
+// Classes abstratas
+
+// Sintaxe de declaração de classe abstrata
+// <Nível de acesso> abstract <nome-da-classe-abstrata> extends <estende super-abstratas-classes> {
+// // Constantes e variáveis
+// // Declarações de método
+//}
+
+// Marcar uma classe como abstrata significa que ela contém métodos abstratos que devem
+// ser definido em uma classe filha. Semelhante às interfaces, classes abstratas não podem
+// ser instanciadas, ao invés disso devem ser extendidas e os métodos abstratos
+// definidos. Diferente de interfaces, classes abstratas podem conter uma mistura de
+// métodos concretos e abstratos. Métodos em uma interface não podem ter um corpo,
+// a menos que o método seja estático, e as variáveis sejam finais, por padrão, ao contrário de um
+// classe abstrata. Classes abstratas também PODEM ter o método "main".
+
+public abstract class Animal
+{
+ public abstract void fazerSom();
+
+ // Método pode ter um corpo
+ public void comer()
+ {
+ System.out.println("Eu sou um animal e estou comendo.");
+ //Nota: Nós podemos acessar variáveis privadas aqui.
+ idade = 30;
+ }
+
+ // Não há necessidade de inicializar, no entanto, em uma interface
+    // a variável é implicitamente final e, portanto, tem
+    // de ser inicializado.
+ protected int idade;
+
+ public void mostrarIdade()
+ {
+ System.out.println(idade);
+ }
+
+ //Classes abstratas podem ter o método main.
+ public static void main(String[] args)
+ {
+ System.out.println("Eu sou abstrata");
+ }
+}
+
+class Cachorro extends Animal
+{
+
+ // Nota: ainda precisamos substituir os métodos abstratos na
+    // classe abstrata
+ @Override
+ public void fazerSom()
+ {
+ System.out.println("Bark");
+ // idade = 30; ==> ERRO! idade é privada de Animal
+ }
+
+ // NOTA: Você receberá um erro se usou a
+    // anotação Override aqui, uma vez que java não permite
+    // sobrescrita de métodos estáticos.
+    // O que está acontecendo aqui é chamado de "esconder o método".
+    // Vejá também este impressionante SO post: http://stackoverflow.com/questions/16313649/
+ public static void main(String[] args)
+ {
+ Cachorro pluto = new Cachorro();
+ pluto.fazerSom();
+ pluto.comer();
+ pluto.mostrarIdade();
+ }
+}
+
+// Classes Finais
+
+// Sintaxe de declaração de classe final
+// <nível de acesso> final <nome-da-classe-final> {
+// // Constantes e variáveis
+// // Declarações de método
+//}
+
+// Classes finais são classes que não podem ser herdadas e são, portanto, um
+// filha final. De certa forma, as classes finais são o oposto de classes abstratas
+// Porque classes abstratas devem ser estendidas, mas as classes finais não pode ser
+// estendidas.
+public final class TigreDenteDeSabre extends Animal
+{
+ // Nota: Ainda precisamos substituir os métodos abstratos na
+     // classe abstrata.
+ @Override
+ public void fazerSom();
+ {
+ System.out.println("Roar");
+ }
+}
+
+// Métodos Finais
+public abstract class Mamifero()
+{
+ // Sintaxe de Métodos Finais:
+ // <modificador-de-acesso> final <tipo-de-retorno> <nome-do-método>(<argumentos>)
+
+ // Métodos finais, como, classes finais não podem ser substituídas por uma classe filha,
+    // e são, portanto, a implementação final do método.
+ public final boolean EImpulsivo()
+ {
+ return true;
+ }
+}
+
+
+// Tipo Enum
+//
+// Um tipo enum é um tipo de dado especial que permite a uma variável ser um conjunto de constantes predefinidas. A
+// variável deve ser igual a um dos valores que foram previamente definidos para ela.
+// Por serem constantes, os nomes dos campos de um tipo de enumeração estão em letras maiúsculas.
+// Na linguagem de programação Java, você define um tipo de enumeração usando a palavra-chave enum. Por exemplo, você poderia
+// especificar um tipo de enum dias-da-semana como:
+
+public enum Dia {
+ DOMINGO, SEGUNDA, TERÇA, QUARTA,
+ QUINTA, SEXTA, SABADO
+}
+
+// Nós podemos usar nosso enum Dia assim:
+
+public class EnumTeste {
+
+ // Variável Enum
+ Dia dia;
+
+ public EnumTeste(Dia dia) {
+ this.dia = dia;
+ }
+
+ public void digaComoE() {
+ switch (dia) {
+ case SEGUNDA:
+ System.out.println("Segundas são ruins.");
+ break;
+
+ case SEXTA:
+ System.out.println("Sextas são melhores.");
+ break;
+
+ case SABADO:
+ case DOMINGO:
+ System.out.println("Finais de semana são os melhores.");
+ break;
+
+ default:
+ System.out.println("Dias no meio da semana são mais ou menos.");
+ break;
+ }
+ }
+
+ public static void main(String[] args) {
+ EnumTeste primeiroDia = new EnumTeste(Dia.SEGUNDA);
+ primeiroDia.digaComoE(); // => Segundas-feiras são ruins.
+ EnumTeste terceiroDia = new EnumTeste(Dia.QUARTA);
+ terceiroDia.digaComoE(); // => Dias no meio da semana são mais ou menos.
+ }
+}
+
+// Tipos Enum são muito mais poderosos do que nós mostramos acima.
+// O corpo de um enum pode incluir métodos e outros campos.
+// Você pode ver mais em https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
+
```
## Leitura Recomendada
diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown
index 406042fa..59c6890e 100644
--- a/pt-br/javascript-pt.html.markdown
+++ b/pt-br/javascript-pt.html.markdown
@@ -436,7 +436,6 @@ var myPrototype = {
myObj.__proto__ = myPrototype;
myObj.meaningOfLife; // = 42
-// This works for functions, too.
// Isto funciona para funções, também.
myObj.myFunc(); // = "olá mundo!"
@@ -506,7 +505,7 @@ String.prototype.firstCharacter = function(){
// Havíamos mencionado que `Object.create` não estava ainda disponível em
// todos as implementações, mas nós podemos usá-lo com esse polyfill:
-if (Object.create === undefined){ // don't overwrite it if it exists
+if (Object.create === undefined){ // Não o sobrescreve se já existir
Object.create = function(proto){
// faz um construtor temporário com o prototype certo
var Constructor = function(){};
@@ -520,13 +519,13 @@ if (Object.create === undefined){ // don't overwrite it if it exists
## 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
@@ -543,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/json-pt.html.markdown b/pt-br/json-pt.html.markdown
index fc63b126..fd822c03 100644
--- a/pt-br/json-pt.html.markdown
+++ b/pt-br/json-pt.html.markdown
@@ -3,6 +3,7 @@ language: json
contributors:
- ["Anna Harren", "https://github.com/iirelu"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["Francisco Marques", "https://github.com/ToFran"]
translators:
- ["Miguel Araújo", "https://github.com/miguelarauj1o"]
lang: pt-br
@@ -12,10 +13,16 @@ filename: learnjson-pt.json
Como JSON é um formato de intercâmbio de dados, este será, muito provavelmente, o
"Learn X in Y minutes" mais simples existente.
-JSON na sua forma mais pura não tem comentários em reais, mas a maioria dos analisadores
-aceitarão comentários no estilo C (//, /\* \*/). Para os fins do presente, no entanto,
-tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si.
+JSON na sua forma mais pura não tem comentários, mas a maioria dos analisadores
+aceitarão comentários no estilo C (//, /\* \*/). No entanto estes devem ser evitados para otimizar a compatibilidade.
+Um valor JSON pode ser um numero, uma string, um array, um objeto, um booleano (true, false) ou null.
+
+Os browsers suportados são: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, e Safari 4.0+.
+
+A extensão dos ficheiros JSON é “.json” e o tipo de mídia de Internet (MIME) é “application/json”.
+
+Mais informação em: http://www.json.org/
```json
{
@@ -35,7 +42,7 @@ tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si.
"array": [0, 1, 2, 3, "Arrays podem ter qualquer coisa em si.", 5],
"outro objeto": {
- "ccomentário": "Estas coisas podem ser aninhadas, muito úteis."
+ "comentário": "Estas coisas podem ser aninhadas, muito úteis."
}
},
@@ -57,6 +64,6 @@ tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si.
, "outro comentário": "que bom"
},
- "que foi curto": "E, você está feito. Você já sabe tudo que JSON tem para oferecer.".
+ "que foi curto": "E, você está feito. Você já sabe tudo que JSON tem para oferecer."
}
```
diff --git a/pt-br/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/matlab-pt.html.markdown b/pt-br/matlab-pt.html.markdown
new file mode 100644
index 00000000..eb660d4c
--- /dev/null
+++ b/pt-br/matlab-pt.html.markdown
@@ -0,0 +1,540 @@
+---
+language: Matlab
+contributors:
+ - ["mendozao", "http://github.com/mendozao"]
+ - ["jamesscottbrown", "http://jamesscottbrown.com"]
+ - ["Colton Kohnke", "http://github.com/voltnor"]
+translators:
+ - ["Claudson Martins", "https://github.com/claudsonm"]
+lang: pt-br
+filename: learnmatlab-pt.mat
+
+---
+
+MATLAB significa MATrix LABoratory. É uma poderosa linguagem de computação numérica geralmente utilizada em engenharia e matemática.
+
+Se você tem algum feedback, por favor fique a vontade para me contactar via
+[@the_ozzinator](https://twitter.com/the_ozzinator), ou
+[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com).
+
+```matlab
+% Comentários iniciam com um sinal de porcentagem
+
+%{
+Comentários de múltiplas linhas
+parecem
+com
+algo assim
+%}
+
+% Comandos podem ocupar várinhas linhas, usando '...':
+ a = 1 + 2 + ...
+ + 4
+
+% Comandos podem ser passados para o sistema operacional
+!ping google.com
+
+who % Exibe todas as variáveis na memória
+whos % Exibe todas as variáveis na memória, com seus tipos
+clear % Apaga todas as suas variáveis da memória
+clear('A') % Apaga uma variável em particular
+openvar('A') % Abre a variável no editor de variável
+
+clc % Apaga o conteúdo escrito na sua janela de comando
+diary % Alterna o conteúdo escrito na janela de comando para um arquivo de texto
+ctrl-c % Aborta a computação atual
+
+edit('minhafuncao.m') % Abre a função/script no editor
+type('minhafuncao.m') % Imprime o código-fonte da função/script na janela de comando
+
+profile on % Ativa o perfil de código
+profile off % Desativa o perfil de código
+profile viewer % Visualiza os resultados na janela de Profiler
+
+help comando % Exibe a documentação do comando na janela de comando
+doc comando % Exibe a documentação do comando na janela de ajuda
+lookfor comando % Procura por comando na primeira linha comentada de todas as funções
+lookfor comando -all % Procura por comando em todas as funções
+
+
+% Formatação de saída
+format short % 4 casas decimais em um número flutuante
+format long % 15 casas decimais
+format bank % 2 dígitos após o ponto decimal - para cálculos financeiros
+fprintf('texto') % Imprime na tela "texto"
+disp('texto') % Imprime na tela "texto"
+
+% Variáveis & Expressões
+minhaVariavel = 4 % O painel Workspace mostra a variável recém-criada
+minhaVariavel = 4; % Ponto e vírgula suprime a saída para a janela de comando
+4 + 6 % Resposta = 10
+8 * minhaVariavel % Resposta = 32
+2 ^ 3 % Resposta = 8
+a = 2; b = 3;
+c = exp(a)*sin(pi/2) % c = 7.3891
+
+% A chamada de funções pode ser feita por uma das duas maneiras:
+% Sintaxe de função padrão:
+load('arquivo.mat', 'y') % Argumentos entre parênteses, separados por vírgula
+% Sintaxe de comando:
+load arquivo.mat y % Sem parênteses, e espaços ao invés de vírgulas
+% Observe a falta de aspas na forma de comando: entradas são sempre passadas
+% como texto literal - não pode passar valores de variáveis.
+% Além disso, não pode receber saída:
+[V,D] = eig(A); % Isto não tem um equivalente na forma de comando
+[~,D] = eig(A); % Se você só deseja D e não V
+
+
+
+% Operadores Lógicos e Relacionais
+1 > 5 % Resposta = 0
+10 >= 10 % Resposta = 1
+3 ~= 4 % Diferente de -> Resposta = 1
+3 == 3 % Igual a -> Resposta = 1
+3 > 1 && 4 > 1 % E -> Resposta = 1
+3 > 1 || 4 > 1 % OU -> Resposta = 1
+~1 % NOT -> Resposta = 0
+
+% Operadores Lógicos e Relacionais podem ser aplicados a matrizes
+A > 5
+% Para cada elemento, caso seja verdade, esse elemento será 1 na matriz retornada
+A( A > 5 )
+% Retorna um vetor com os elementos de A para os quais a condição é verdadeira
+
+% Cadeias de caracteres (Strings)
+a = 'MinhaString'
+length(a) % Resposta = 11
+a(2) % Resposta = i
+[a,a] % Resposta = MinhaStringMinhaString
+
+
+% Vetores de células
+a = {'um', 'dois', 'três'}
+a(1) % Resposta = 'um' - retorna uma célula
+char(a(1)) % Resposta = um - retorna uma string
+
+% Estruturas
+A.b = {'um','dois'};
+A.c = [1 2];
+A.d.e = false;
+
+% Vetores
+x = [4 32 53 7 1]
+x(2) % Resposta = 32, índices no Matlab começam por 1, não 0
+x(2:3) % Resposta = 32 53
+x(2:end) % Resposta = 32 53 7 1
+
+x = [4; 32; 53; 7; 1] % Vetor coluna
+
+x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
+
+% Matrizes
+A = [1 2 3; 4 5 6; 7 8 9]
+% Linhas são separadas por um ponto e vírgula;
+% Elementos são separados com espaço ou vírgula
+% A =
+
+% 1 2 3
+% 4 5 6
+% 7 8 9
+
+A(2,3) % Resposta = 6, A(linha, coluna)
+A(6) % Resposta = 8
+% (implicitamente encadeia as colunas do vetor, e então as indexa)
+
+
+A(2,3) = 42 % Atualiza a linha 2 coluna 3 com o valor 42
+% A =
+
+% 1 2 3
+% 4 5 42
+% 7 8 9
+
+A(2:3,2:3) % Cria uma nova matriz a partir da antiga
+%Resposta =
+
+% 5 42
+% 8 9
+
+A(:,1) % Todas as linhas na coluna 1
+%Resposta =
+
+% 1
+% 4
+% 7
+
+A(1,:) % Todas as colunas na linha 1
+%Resposta =
+
+% 1 2 3
+
+[A ; A] % Concatenação de matrizes (verticalmente)
+%Resposta =
+
+% 1 2 3
+% 4 5 42
+% 7 8 9
+% 1 2 3
+% 4 5 42
+% 7 8 9
+
+% Isto é o mesmo de
+vertcat(A,A);
+
+
+[A , A] % Concatenação de matrizes (horizontalmente)
+
+%Resposta =
+
+% 1 2 3 1 2 3
+% 4 5 42 4 5 42
+% 7 8 9 7 8 9
+
+% Isto é o mesmo de
+horzcat(A,A);
+
+
+A(:, [3 1 2]) % Reorganiza as colunas da matriz original
+%Resposta =
+
+% 3 1 2
+% 42 4 5
+% 9 7 8
+
+size(A) % Resposta = 3 3
+
+A(1, :) =[] % Remove a primeira linha da matriz
+A(:, 1) =[] % Remove a primeira coluna da matriz
+
+transpose(A) % Transposta a matriz, que é o mesmo de:
+A one
+ctranspose(A) % Transposta a matriz
+% (a transposta, seguida pelo conjugado complexo de cada elemento)
+
+
+
+
+% Aritmética Elemento por Elemento vs. Aritmética com Matriz
+% Naturalmente, os operadores aritméticos agem em matrizes inteiras. Quando
+% precedidos por um ponto, eles atuam em cada elemento. Por exemplo:
+A * B % Multiplicação de matrizes
+A .* B % Multiplica cada elemento em A por seu correspondente em B
+
+% Existem vários pares de funções nas quais uma atua sob cada elemento, e a
+% outra (cujo nome termina com m) age na matriz por completo.
+exp(A) % Exponencia cada elemento
+expm(A) % Calcula o exponencial da matriz
+sqrt(A) % Tira a raiz quadrada de cada elemento
+sqrtm(A) % Procura a matriz cujo quadrado é A
+
+
+% Gráficos
+x = 0:.10:2*pi; % Vetor que começa em 0 e termina em 2*pi com incrementos de 0,1
+y = sin(x);
+plot(x,y)
+xlabel('eixo x')
+ylabel('eixo y')
+title('Gráfico de y = sin(x)')
+axis([0 2*pi -1 1]) % x vai de 0 a 2*pi, y vai de -1 a 1
+
+plot(x,y1,'-',x,y2,'--',x,y3,':') % Para várias funções em um só gráfico
+legend('Descrição linha 1', 'Descrição linha 2') % Curvas com uma legenda
+
+% Método alternativo para traçar várias funções em um só gráfico:
+% Enquanto 'hold' estiver ativo, os comandos serão adicionados ao gráfico
+% existente ao invés de o substituirem.
+plot(x, y)
+hold on
+plot(x, z)
+hold off
+
+loglog(x, y) % Plotar em escala loglog
+semilogx(x, y) % Um gráfico com eixo x logarítmico
+semilogy(x, y) % Um gráfico com eixo y logarítmico
+
+fplot (@(x) x^2, [2,5]) % Plotar a função x^2 para x=2 até x=5
+
+grid on % Exibe as linhas de grade; Oculta com 'grid off'
+axis square % Torna quadrada a região dos eixos atuais
+axis equal % Taxa de proporção onde as unidades serão as mesmas em todas direções
+
+scatter(x, y); % Gráfico de dispersão ou bolha
+hist(x); % Histograma
+
+z = sin(x);
+plot3(x,y,z); % Plotar em espaço em 3D
+
+pcolor(A) % Mapa de calor da matriz: traça uma grade de retângulos, coloridos pelo valor
+contour(A) % Plotar de contorno da matriz
+mesh(A) % Plotar malha 3D
+
+h = figure % Cria uma nova figura objeto, com identificador h
+figure(h) % Cria uma nova janela de figura com h
+close(h) % Fecha a figura h
+close all % Fecha todas as janelas de figuras abertas
+close % Fecha a janela de figura atual
+
+shg % Traz uma janela gráfica existente para frente, ou cria uma nova se necessário
+clf clear % Limpa a janela de figura atual e redefine a maioria das propriedades da figura
+
+% Propriedades podem ser definidas e alteradas através de um identificador.
+% Você pode salvar um identificador para uma figura ao criá-la.
+% A função gcf retorna o identificador da figura atual
+h = plot(x, y); % Você pode salvar um identificador para a figura ao criá-la
+set(h, 'Color', 'r')
+% 'y' amarelo; 'm' magenta, 'c' ciano, 'r' vermelho, 'g' verde, 'b' azul, 'w' branco, 'k' preto
+set(h, 'LineStyle', '--')
+ % '--' linha sólida, '---' tracejada, ':' pontilhada, '-.' traço-ponto, 'none' sem linha
+get(h, 'LineStyle')
+
+
+% A função gca retorna o identificador para os eixos da figura atual
+set(gca, 'XDir', 'reverse'); % Inverte a direção do eixo x
+
+% Para criar uma figura que contém vários gráficos use subplot, o qual divide
+% a janela de gráficos em m linhas e n colunas.
+subplot(2,3,1); % Seleciona a primeira posição em uma grade de 2-por-3
+plot(x1); title('Primeiro Plot') % Plota algo nesta posição
+subplot(2,3,2); % Seleciona a segunda posição na grade
+plot(x2); title('Segundo Plot') % Plota algo ali
+
+
+% Para usar funções ou scripts, eles devem estar no caminho ou na pasta atual
+path % Exibe o caminho atual
+addpath /caminho/para/pasta % Adiciona o diretório ao caminho
+rmpath /caminho/para/pasta % Remove o diretório do caminho
+cd /caminho/para/mudar % Muda o diretório
+
+
+% Variáveis podem ser salvas em arquivos *.mat
+save('meuArquivo.mat') % Salva as variáveis do seu Workspace
+load('meuArquivo.mat') % Carrega as variáveis em seu Workspace
+
+% Arquivos M (M-files)
+% Um arquivo de script é um arquivo externo contendo uma sequência de instruções.
+% Eles evitam que você digite os mesmos códigos repetidamente na janela de comandos.
+% Possuem a extensão *.m
+
+% Arquivos M de Funções (M-file Functions)
+% Assim como scripts e têm a mesma extensão *.m
+% Mas podem aceitar argumentos de entrada e retornar uma saída.
+% Além disso, possuem seu próprio workspace (ex. diferente escopo de variáveis).
+% O nome da função deve coincidir com o nome do arquivo (salve o exemplo como dobra_entrada.m)
+% 'help dobra_entrada.m' retorna os comentários abaixo da linha de início da função
+function output = dobra_entrada(x)
+ %dobra_entrada(x) retorna duas vezes o valor de x
+ output = 2*x;
+end
+dobra_entrada(6) % Resposta = 12
+
+
+% Você também pode ter subfunções e funções aninhadas.
+% Subfunções estão no mesmo arquivo da função primária, e só podem ser chamados
+% por funções dentro do arquivo. Funções aninhadas são definidas dentro de
+% outras funções, e têm acesso a ambos workspaces.
+
+% Se você quer criar uma função sem criar um novo arquivo, você pode usar uma
+% função anônima. Úteis para definir rapidamente uma função para passar a outra
+% função (ex. plotar com fplot, avaliar uma integral indefinida com quad,
+% procurar raízes com fzero, ou procurar mínimo com fminsearch).
+% Exemplo que retorna o quadrado de sua entrada, atribuído ao identificador sqr:
+sqr = @(x) x.^2;
+sqr(10) % Resposta = 100
+doc function_handle % Saiba mais
+
+% Entrada do usuário
+a = input('Digite o valor: ')
+
+% Para a execução do arquivo e passa o controle para o teclado: o usuário pode
+% examinar ou alterar variáveis. Digite 'return' para continuar a execução, ou 'dbquit' para sair
+keyboard
+
+% Leitura de dados (ou xlsread/importdata/imread para arquivos excel/CSV/imagem)
+fopen(nomedoarquivo)
+
+% Saída
+disp(a) % Imprime o valor da variável a
+disp('Olá Mundo') % Imprime a string
+fprintf % Imprime na janela de comandos com mais controle
+
+% Estruturas Condicionais (os parênteses são opicionais, porém uma boa prática)
+if (a > 15)
+ disp('Maior que 15')
+elseif (a == 23)
+ disp('a é 23')
+else
+ disp('Nenhuma condição reconheceu')
+end
+
+% Estruturas de Repetição
+% Nota: fazer o loop sobre elementos de um vetor/matriz é lento!
+% Sempre que possível, use funções que atuem em todo o vetor/matriz de uma só vez.
+for k = 1:5
+ disp(k)
+end
+
+k = 0;
+while (k < 5)
+ k = k + 1;
+end
+
+% Tempo de Execução de Código (Timing Code Execution): 'toc' imprime o tempo
+% passado desde que 'tic' foi chamado.
+tic
+A = rand(1000);
+A*A*A*A*A*A*A;
+toc
+
+% Conectando a uma base de dados MySQL
+dbname = 'nome_base_de_dados';
+username = 'root';
+password = 'root';
+driver = 'com.mysql.jdbc.Driver';
+dburl = ['jdbc:mysql://localhost:8889/' dbname];
+%Abaixo, o xx depende da versão, download disponível em http://dev.mysql.com/downloads/connector/j/
+javaclasspath('mysql-connector-java-5.1.xx-bin.jar');
+conn = database(dbname, username, password, driver, dburl);
+sql = ['SELECT * FROM nome_tabela WHERE id = 22'] % Exemplo de uma consulta SQL
+a = fetch(conn, sql) %a will contain your data
+
+
+% Funções Matemáticas Comuns
+sin(x)
+cos(x)
+tan(x)
+asin(x)
+acos(x)
+atan(x)
+exp(x)
+sqrt(x)
+log(x)
+log10(x)
+abs(x)
+min(x)
+max(x)
+ceil(x)
+floor(x)
+round(x)
+rem(x)
+rand % Números pseudo-aleatórios uniformemente distribuídos
+randi % Inteiros pseudo-aleatórios uniformemente distribuídos
+randn % Números pseudo-aleatórios normalmente distribuídos
+
+% Constantes Comuns
+pi
+NaN
+inf
+
+% Resolvendo equações matriciais (se não houver solução, retorna uma solução de mínimos quadrados)
+% Os operadores \ e / são equivalentes às funções mldivide e mrdivide
+x=A\b % Resolve Ax=b. Mais rápido e numericamente mais preciso do que inv(A)*b.
+x=b/A % Resolve xA=b
+
+inv(A) % Calcula a matriz inversa
+pinv(A) % Calcula a pseudo-inversa
+
+% Funções Matriciais Comuns
+zeros(m,n) % Matriz de zeros m x n
+ones(m,n) % Matriz de 1's m x n
+diag(A) % Extrai os elementos diagonais da matriz A
+diag(x) % Constrói uma matriz com os elementos diagonais listados em x, e zero nas outras posições
+eye(m,n) % Matriz identidade
+linspace(x1, x2, n) % Retorna n pontos igualmente espaçados, com min x1 e max x2
+inv(A) % Inverso da matriz A
+det(A) % Determinante da matriz A
+eig(A) % Valores e vetores próprios de A
+trace(A) % Traço da matriz - equivalente a sum(diag(A))
+isempty(A) % Testa se a matriz está vazia
+all(A) % Testa se todos os elementos são diferentes de zero ou verdadeiro
+any(A) % Testa se algum elemento é diferente de zero ou verdadeiro
+isequal(A, B) % Testa a igualdade de duas matrizes
+numel(A) % Número de elementos na matriz
+triu(x) % Retorna a parte triangular superior de x
+tril(x) % Retorna a parte triangular inferior de x
+cross(A,B) % Retorna o produto cruzado das matrizes A e B
+dot(A,B) % Retorna o produto escalar de duas matrizes (devem possuir mesmo tamanho)
+transpose(A) % Retorna a matriz transposta de A
+fliplr(A) % Inverte a matriz da esquerda para a direita
+flipud(A) % Inverte a matriz de cima para baixo
+
+% Fatorações de Matrizes
+% Decomposição LU: PA = LU,L é triangular inferior, U é triangular superior, P é a matriz de permutação
+[L, U, P] = lu(A)
+% Decomposição em Autovalores: AP = PD, colunas de P são autovetores e as diagonais de D são autovalores
+[P, D] = eig(A)
+% SVD: XV = US, U e V são matrizes unitárias, S possui elementos não negativos na diagonal em ordem decrescente
+[U,S,V] = svd(X)
+
+% Funções Vetoriais Comuns
+max % Maior componente
+min % Menor componente
+length % Tamanho do vetor
+sort % Ordena em orcer ascendente
+sum % Soma de elementos
+prod % Produto de elementos
+mode % Valor modal
+median % Valor mediano
+mean % Valor médio
+std % Desvio padrão
+perms(x) % Lista todas as permutações de elementos de x
+
+
+% Classes
+% Matlab pode suportar programação orientada a objetos.
+% Classes devem ser colocadas em um arquivo de mesmo nome com a extensão *.m
+% Para começar, criamos uma simples classe que armazena posições de GPS
+% Início ClassePosicoesGPS.m
+classdef ClassePosicoesGPS % O nome da classe.
+ properties % As propriedades da classe comportam-se como estruturas
+ latitude
+ longitude
+ end
+ methods
+ % Este método que tem o mesmo nome da classe é o construtor.
+ function obj = ClassePosicoesGPS(lat, lon)
+ obj.latitude = lat;
+ obj.longitude = lon;
+ end
+
+ % Outras funções que usam os objetos de PosicoesGPS
+ function r = multiplicarLatPor(obj, n)
+ r = n*[obj.latitude];
+ end
+
+ % Se quisermos somar dois objetos de PosicoesGPS juntos sem chamar
+ % uma função especial nós podemos sobrepor a aritmética do Matlab, desta maneira:
+ function r = plus(o1,o2)
+ r = ClassePosicoesGPS([o1.latitude] +[o2.latitude], ...
+ [o1.longitude]+[o2.longitude]);
+ end
+ end
+end
+% End ClassePosicoesGPS.m
+
+% Podemos criar um objeto da classe usando o construtor
+a = ClassePosicoesGPS(45.0, 45.0)
+
+% Propriedades da classe se comportam exatamente como estruturas Matlab
+a.latitude = 70.0
+a.longitude = 25.0
+
+% Métodos podem ser chamados da mesma forma que funções
+ans = multiplicarLatPor(a,3)
+
+% O método também pode ser chamado usando a notação de ponto. Neste caso,
+% o objeto não precisa ser passado para o método.
+ans = a.multiplicarLatPor(a,1/3)
+
+% Funções do Matlab podem ser sobrepostas para lidar com objetos.
+% No método abaixo, nós sobrepomos a forma como o Matlab lida com a soma de
+% dois objetos PosicoesGPS.
+b = ClassePosicoesGPS(15.0, 32.0)
+c = a + b
+
+```
+
+## Mais sobre Matlab
+
+* O site oficial [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/)
+* O fórum oficial de respostas: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/)
+
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/sass-pt.html.markdown b/pt-br/sass-pt.html.markdown
new file mode 100644
index 00000000..3d91f1ca
--- /dev/null
+++ b/pt-br/sass-pt.html.markdown
@@ -0,0 +1,452 @@
+---
+language: sass
+filename: learnsass-pt.scss
+contributors:
+ - ["Laura Kyle", "https://github.com/LauraNK"]
+ - ["Sean Corrales", "https://github.com/droidenator"]
+translators:
+ - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"]
+ - ["Cássio Böck", "https://github.com/cassiobsilva"]
+lang: pt-br
+---
+
+Sass é uma linguagem de extensão CSS que adiciona recursos, como variáveis, aninhamento, mixins e muito mais.
+Sass (e outros pré-processadores, como [Less](http://lesscss.org/)) ajudam os desenvolvedores a escrever código de fácil manutenção e DRY (Do not Repeat Yourself).
+
+Sass tem duas opções de sintaxe diferentes para escolher. SCSS, que tem a mesma sintaxe de CSS, mas com os recursos adicionais de Sass. Ou Sass (a sintaxe original), que usa o recuo, em vez de chaves e ponto e vírgula.
+Este tutorial é escrito usando SCSS.
+
+Se você já está familiarizado com CSS3, você será capaz de pegar Sass de forma relativamente rápida. Ele não fornece quaisquer novas opções de estilo, mas sim as ferramentas para escrever sua CSS de forma mais eficiente e fazer a manutenção mais fácilmente.
+
+```scss
+
+
+// Comentários de linha única são removidos quando Sass é compilado para CSS.
+
+/* Comentários multi-line são preservados. */
+
+
+
+/*Variáveis
+==============================*/
+
+
+
+/* É possível armazenar um valor CSS (tais como a cor) de uma variável.
+Use o símbolo "$" para criar uma variável. */
+
+$primary-color: #A3A4FF;
+$secondary-color: #51527F;
+$body-font: 'Roboto', sans-serif;
+
+/* Você pode usar as variáveis em toda a sua folha de estilo.
+Agora, se você quer mudar a cor, você só tem que fazer a mudança uma vez. */
+
+body {
+ background-color: $primary-color;
+ color: $secondary-color;
+ font-family: $body-font;
+}
+
+/* Quando compilar ficaria assim: */
+body {
+ background-color: #A3A4FF;
+ color: #51527F;
+ font-family: 'Roboto', sans-serif;
+}
+
+
+/ * Este é muito mais fácil de manter do que ter de mudar a cor
+cada vez que aparece em toda a sua folha de estilo. * /
+
+
+
+
+/*Mixins
+==============================*/
+
+
+
+/* Se você achar que você está escrevendo o mesmo código para mais de um
+elemento, você pode querer armazenar esse código em um mixin.
+
+Use a diretiva '@mixin', além de um nome para o seu mixin. */
+
+@mixin center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+/* Você pode usar o mixin com '@include' e o nome mixin. */
+
+div {
+ @include center;
+ background-color: $primary-color;
+}
+
+/* Apoś compilar ficaria assim: */
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #A3A4FF;
+}
+
+
+/* Você pode usar mixins para criar uma propriedade estenográfica. */
+
+@mixin size($width, $height) {
+ width: $width;
+ height: $height;
+}
+
+/* O que você pode invocar passando argumentos de largura e altura. */
+
+.rectangle {
+ @include size(100px, 60px);
+}
+
+.square {
+ @include size(40px, 40px);
+}
+
+/* Isso compilado ficará assim: */
+.rectangle {
+ width: 100px;
+ height: 60px;
+}
+
+.square {
+ width: 40px;
+ height: 40px;
+}
+
+
+
+/*Funções
+==============================*/
+
+
+
+/* Sass fornece funções que podem ser utilizados para realizar uma variedade de
+    tarefas. Considere o seguinte */
+
+/* Funções pode ser chamado usando seu nome e passando o
+    argumentos necessários */
+body {
+ width: round(10.25px);
+}
+
+.footer {
+ background-color: fade_out(#000000, 0.25)
+}
+
+/* Compiles to: */
+
+body {
+ width: 10px;
+}
+
+.footer {
+ background-color: rgba(0, 0, 0, 0.75);
+}
+
+/* Você também pode definir suas próprias funções. As funções são muito semelhantes aos
+   mixins. Ao tentar escolher entre uma função ou um mixin, lembre-
+   que mixins são os melhores para gerar CSS enquanto as funções são melhores para
+   lógica que pode ser usado em todo o seu código Sass. Os exemplos
+   seção Operadores Math 'são candidatos ideais para se tornar um reutilizável
+   função. */
+
+/* Esta função terá um tamanho de destino eo tamanho do pai e calcular
+   e voltar a percentagem */
+
+@function calculate-percentage($target-size, $parent-size) {
+ @return $target-size / $parent-size * 100%;
+}
+
+$main-content: calculate-percentage(600px, 960px);
+
+.main-content {
+ width: $main-content;
+}
+
+.sidebar {
+ width: calculate-percentage(300px, 960px);
+}
+
+/* Compila para: */
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+
+
+/* Extend (Herança)
+============================== */
+
+
+
+/*Extend é uma maneira de compartilhar as propriedades de um seletor com outro. */
+
+.display {
+ @include size(5em, 5em);
+ border: 5px solid $secondary-color;
+}
+
+.display-success {
+ @extend .display;
+ border-color: #22df56;
+}
+
+/* Compiles to: */
+.display, .display-success {
+ width: 5em;
+ height: 5em;
+ border: 5px solid #51527F;
+}
+
+.display-success {
+ border-color: #22df56;
+}
+
+/* Ampliando uma declaração CSS é preferível a criação de um mixin
+   por causa da maneira agrupa as classes que todos compartilham
+   o mesmo estilo base. Se isso for feito com um mixin, a largura,
+   altura, e a borda seria duplicado para cada instrução que
+   o chamado mixin. Enquanto isso não irá afetar o seu fluxo de trabalho, será
+   adicionar inchaço desnecessário para os arquivos criados pelo compilador Sass. */
+
+
+
+/*Assentamento
+==============================*/
+
+
+
+/ * Sass permite seletores ninhos dentro seletores * /
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: #FF0000;
+ }
+}
+
+/* '&' será substituído pelo selector pai. */
+/* Você também pode aninhar pseudo-classes. */
+/* Tenha em mente que o excesso de nidificação vai fazer seu código menos sustentável.
+Essas práticas também recomendam não vai mais de 3 níveis de profundidade quando nidificação.
+Por exemplo: */
+
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: red;
+
+ &:hover {
+ background-color: blue;
+ }
+
+ a {
+ color: white;
+ }
+ }
+}
+
+/* Compila para: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+}
+
+ul li {
+ background-color: red;
+}
+
+ul li:hover {
+ background-color: blue;
+}
+
+ul li a {
+ color: white;
+}
+
+
+
+/*Parciais e Importações
+==============================*/
+
+
+/* Sass permite criar arquivos parciais. Isso pode ajudar a manter seu Sass
+   código modularizado. Arquivos parciais deve começar com um '_', por exemplo, _reset.css.
+   Parciais não são geradas em CSS. */
+
+
+
+/* Considere o seguinte CSS que nós vamos colocar em um arquivo chamado _reset.css */
+
+html,
+body,
+ul,
+ol {
+ margin: 0;
+ padding: 0;
+}
+
+/* Sass oferece @import que pode ser usado para importar parciais em um arquivo.
+   Isso difere da declaração CSS @import tradicional, que faz
+   outra solicitação HTTP para buscar o arquivo importado. Sass converte os
+   importadas arquivo e combina com o código compilado. */
+
+@import 'reset';
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+/* Compiles to: */
+
+html, body, ul, ol {
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+
+
+/*Placeholder Selectors
+==============================*/
+
+
+/* Os espaços reservados são úteis na criação de uma declaração CSS para ampliar. Se você
+   queria criar uma instrução CSS que foi usado exclusivamente com @extend,
+   Você pode fazer isso usando um espaço reservado. Espaços reservados começar com um '%' em vez
+   de '.' ou '#'. Espaços reservados não aparece no CSS compilado. * /
+
+%content-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ @extend %content-window;
+ background-color: #0000ff;
+}
+
+/* Compilado para: */
+
+.message-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ background-color: #0000ff;
+}
+
+
+
+/*Operações Math
+============================== * /
+
+
+/* Sass fornece os seguintes operadores: +, -, *, /, e %. estes podem
+   ser úteis para calcular os valores diretamente no seu Sass arquivos em vez
+   de usar valores que você já calculados pela mão. Abaixo está um exemplo
+   de uma criação de um projeto simples de duas colunas. * /
+
+$content-area: 960px;
+$main-content: 600px;
+$sidebar-content: 300px;
+
+$main-size: $main-content / $content-area * 100%;
+$sidebar-size: $sidebar-content / $content-area * 100%;
+$gutter: 100% - ($main-size + $sidebar-size);
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: $main-size;
+}
+
+.sidebar {
+ width: $sidebar-size;
+}
+
+.gutter {
+ width: $gutter;
+}
+
+/* Compiles to: */
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+.gutter {
+ width: 6.25%;
+}
+
+
+```
+
+
+
+## SASS ou Sass?
+Alguma vez você já se perguntou se Sass é um acrônimo ou não? Você provavelmente não tem, mas vou dizer-lhe de qualquer maneira. O nome do idioma é uma palavra, "Sass", e não uma sigla.
+Porque as pessoas estavam constantemente a escrevê-lo como "SASS", o criador da linguagem de brincadeira chamou de "StyleSheets Sintaticamente Incríveis".
+
+
+## Prática Sass
+Se você quiser jogar com Sass em seu navegador, vá para [SassMeister](http://sassmeister.com/).
+Você pode usar uma sintaxe, basta ir para as configurações e selecionar Sass ou SCSS.
+
+
+## Compatibilidade
+
+Sass pode ser usado em qualquer projeto, desde que você tenha um programa para compilá-lo
+em CSS. Você vai querer verificar se o CSS que você está usando é compatível
+com os seus navegadores de destino.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) e [CanIUse](http://caniuse.com) são ótimos recursos para verificação de compatibilidade.
+
+
+## Leitura
+* [Official Documentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html)
+* [The Sass Way](http://thesassway.com/) fornece tutoriais (iniciante avançados) e artigos.
diff --git a/pt-br/tmux-pt.html.markdown b/pt-br/tmux-pt.html.markdown
new file mode 100644
index 00000000..9d5bf292
--- /dev/null
+++ b/pt-br/tmux-pt.html.markdown
@@ -0,0 +1,254 @@
+---
+category: tool
+tool: tmux
+contributors:
+ - ["mdln", "https://github.com/mdln"]
+translators:
+ - ["Luis Custodio", "http://luiscustodio.com"]
+lang: pt-br
+filename: LearnTmux-pt.txt
+---
+
+O [tmux](http://tmux.sourceforge.net)
+é um multiplexador de terminal, ele permite que terminais sejam criados,
+acessados e controlados a partir de uma unica instância. tmux pode ser separado
+de uma tela e continuar rodando no plano de fundo e depois ser reacoplado à
+instância (ou tela original).
+
+```
+
+ tmux [command] # Roda um [comando]
+ # 'tmux' sem comandos irá criar uma nova seção
+
+ new # Cria uma nova seção
+ -s "Nome" # Cria uma nova seção com nome "Nome"
+ -n "Janela" # Cria uma janela com o nome "Janela"
+ -c "/dir" # Inícia em uma pasta específica
+
+ attach # Reacopla a última seção disponível
+ -t "#" # Reacopla a seção com nome "#"
+ -d # Separa (Desacopla) a sessaão de outras instâncias.
+
+ ls # Lista todas as seções
+ -a # Lista todas as seções abertas
+
+ lsw # Lista as janelas
+ -a # Lista todas as janelas
+ -s # Lista todas janleas em uma seção
+
+ lsp # Lista os painéis
+ -a # Lista todos os painéis
+ -s # Lista todos os painéis em uma seção
+ -t "#" # Lista os painéis baseado no nome "#"
+
+ kill-window # Encerrar a janela corrente
+ -t "#" # Encerrar a janela baseado no nome "#"
+ -a # Encerrar todas as janelas
+ -a -t "#" # Encerrar todas as janelas exceto a com nome "#"
+
+ kill-session # Encerrar seção corrente
+ -t "#" # Encerrar seção com nome "#"
+ -a # Encerrar todas as seções
+ -a -t "#" # Encerrar todas as seções exceto a com nome "#"
+
+```
+
+
+### Teclas de atalhos (comandos)
+
+A maneira de controllar uma seção tmux acoplada é através de uma
+combinação de teclas de prefixo.
+
+```
+----------------------------------------------------------------------
+ (C-b) = Ctrl + b # Combinação de prefixos para usar comandos(atalhos).
+
+ (M-1) = Meta + 1 -or- Alt + 1
+----------------------------------------------------------------------
+
+ ? # Lista todos os comandos.
+ : # Acessa o lugar (prompt command) para receber comandos do tmux
+ r # Força a redefiniçao do cliente acoplado.
+ c # Cria uma nova janela.
+
+ ! # Retira o painel corrente da janela.
+ % # Divide o painel corrente em dois para a esquerda e direita.
+ " # Divide o painel corrente em dois para cima e para baixo.
+
+ n # Move para a próxima janela.
+ p # Move para a janela anterior.
+ { # Troca o painel corrente pelo anterior.
+ } # Troca o painel corrent pelo posterior.
+
+ s # Seleciona uma nova seção para o cliente acoplado iterativamente.
+ w # Seleciona a janela corrente iterativamente.
+ 0 to 9 # Seleciona a janela de 0 à 9.
+
+ d # Separa o cliente atual.
+ D # Seleciona um cliente a ser separado.
+
+ & # Encerra a janela corrente.
+ x # Encerra o painel corrente.
+
+ Up, Down # Move para o painel acima, abaixo, a esquerda ou a direita.
+ Left, Right
+
+ M-1 to M-5 # Organiza os paines:
+ # 1) Horizontalmente de maneira igual
+ # 2) Verticalmente de maineira igual.
+ # 3) Principal horizontalmente
+ # 4) Principal verticamente.
+ # 5) Mosaico
+
+ C-Up, C-Down # Altera o tamanho do painel corrente baseado em uma célula.
+ C-Left, C-Right
+
+ M-Up, M-Down # Altera o tamanho do painel corrente baseado em cinco células.
+ M-Left, M-Right
+
+```
+
+
+### Configurando ~/.tmux.conf
+
+Existe um arquivo chamado tmux.conf, ele pode ser usado para definir opções no
+ momento de inicialização, da mesma maneira que .vimrc, init.el, .bash_profile são usados.
+
+
+```
+# Exemplo de tmux.conf
+# 2014.10
+
+
+### General
+###########################################################################
+
+# Habilita UTF-8
+setw -g utf8 on
+set-option -g status-utf8 on
+
+# Limite da história de comandos
+set -g history-limit 2048
+
+# Indíce de inicialização
+set -g base-index 1
+
+# Mouse
+set-option -g mouse-select-pane on
+
+# Recarregar o arquivo de configuração sem a necessidade de reiniciar o programa
+unbind r
+bind r source-file ~/.tmux.conf
+
+
+### Teclas de atalho
+###########################################################################
+
+# Desvincular C-b como prefixo padrão.
+unbind C-b
+
+# Define um novo prefixo padrão.
+set-option -g prefix `
+
+# Definir prefixos que podem ser usados para voltar para a janela anterior.
+bind C-a last-window
+bind ` last-window
+
+# Fazer com que F11 e F12 alterem o comportamento de C-a e `
+bind F11 set-option -g prefix C-a
+bind F12 set-option -g prefix `
+
+# Preferencia de teclas de atalho
+setw -g mode-keys vi
+set-option -g status-keys vi
+
+# Mover enter paineis com teclas de orientaçao do vim
+bind h select-pane -L
+bind j select-pane -D
+bind k select-pane -U
+bind l select-pane -R
+
+# Iterar entre as Janelas
+bind e previous-window
+bind f next-window
+bind E swap-window -t -1
+bind F swap-window -t +1
+
+# Iterar entre os painéis
+bind = split-window -h
+bind - split-window -v
+unbind '"'
+unbind %
+
+# Habilitar a sub-seção a enviar comandos.
+bind a send-prefix
+
+
+### Theme
+###########################################################################
+
+# Paleta de cores para a barra de status
+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
+
+# Paleta de cores para bordas do painel
+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
+
+# Palta de cores para mensagem
+set-option -g message-fg black
+set-option -g message-bg green
+
+# Paleta de cores para janela de status
+setw -g window-status-bg black
+setw -g window-status-current-fg green
+setw -g window-status-bell-attr default
+setw -g window-status-bell-fg red
+setw -g window-status-content-attr default
+setw -g window-status-content-fg yellow
+setw -g window-status-activity-attr default
+setw -g window-status-activity-fg yellow
+
+
+### UI
+###########################################################################
+
+# Notificações
+setw -g monitor-activity on
+set -g visual-activity on
+set-option -g bell-action any
+set-option -g visual-bell off
+
+# Definir automaticamente o título de janelas
+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)
+
+# Ajustes na barra de status
+set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]"
+
+# Mostrar indicativos de performance na barra de status
+# Requires 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]"
+
+```
+
+
+### Referências
+
+[Tmux | Início](http://tmux.sourceforge.net)
+
+[Manual Tmux (em inglês)](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)
+
+[Mostrar CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux)
+
+Possui uma sugestão? Uma correção, talvez? Abra um issue no Repositório GitHub, ou então faça um pull request.
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/pt-pt/scala-pt.html.markdown b/pt-pt/scala-pt.html.markdown
new file mode 100644
index 00000000..a4c1c02b
--- /dev/null
+++ b/pt-pt/scala-pt.html.markdown
@@ -0,0 +1,651 @@
+---
+language: Scala
+filename: learnscala-pt.scala
+contributors:
+ - ["George Petrov", "http://github.com/petrovg"]
+ - ["Dominic Bou-Samra", "http://dbousamra.github.com"]
+ - ["Geoff Liu", "http://geoffliu.me"]
+ - ["Ha-Duong Nguyen", "http://reference-error.org"]
+translators:
+ - ["João Costa", "http://joaocosta.eu"]
+lang: pt-pt
+---
+
+Scala - a linguagem escalável
+
+```scala
+
+/*
+ Prepare tudo:
+
+ 1) Faça Download do Scala - http://www.scala-lang.org/downloads
+ 2) Faça unzip/untar para onde preferir e coloque o subdirectório `bin` na
+ variável de ambiente `PATH`
+ 3) Inicie a REPL de Scala correndo o comando `scala`. Deve aparecer:
+
+ scala>
+
+ Isto é chamado de REPL (Read-Eval-Print Loop / Lê-Avalia-Imprime Repete).
+ Pode escrever qualquer expressão de Scala e o resultado será imprimido.
+ Vamos mostrar ficheiros de Scala mais à frente neste tutorial mas, para já,
+ vamos começar com os básicos.
+
+*/
+
+
+/////////////////////////////////////////////////
+// 1. Basicos
+/////////////////////////////////////////////////
+
+// Uma linha de comentários é marcada com duas barras
+
+/*
+ Comentários de multiplas linhas, como se pode ver neste exemplo, são assim.
+*/
+
+// Imprimir, forçando uma nova linha no final
+println("Hello world!")
+println(10)
+
+// Imprimir, sem forçar uma nova linha no final
+print("Hello world")
+
+// Valores são declarados com var ou val.
+// As declarações val são imutáveis, enquanto que vars são mutáveis.
+// A immutabilidade é uma propriedade geralmente vantajosa.
+val x = 10 // x é agora 10
+x = 20 // erro: reatribuição de um val
+var y = 10
+y = 20 // y é agora 12
+
+/*
+ Scala é uma linguagem estaticamente tipada, no entanto, nas declarações acima
+ não especificamos um tipo. Isto é devido a uma funcionalidade chamada
+ inferência de tipos. Na maior parte dos casos, o compilador de scala consegue
+ inferir qual o tipo de uma variável, pelo que não o temos de o declarar sempre.
+ Podemos declarar o tipo de uma variável da seguinte forma:
+*/
+val z: Int = 10
+val a: Double = 1.0
+
+// Note a conversão automática de Int para Double: o resultado é 10.0, não 10
+val b: Double = 10
+
+// Valores booleanos
+true
+false
+
+// Operações booleanas
+!true // false
+!false // true
+true == false // false
+10 > 5 // true
+
+// A matemática funciona da maneira habitual
+1 + 1 // 2
+2 - 1 // 1
+5 * 3 // 15
+6 / 2 // 3
+6 / 4 // 1
+6.0 / 4 // 1.5
+
+
+// Avaliar expressões na REPL dá o tipo e valor do resultado
+
+1 + 7
+
+/* A linha acima resulta em:
+
+ scala> 1 + 7
+ res29: Int = 8
+
+ Isto significa que o resultado de avaliar 1 + 7 é um objecto do tipo Int com
+ o valor 8.
+
+ Note que "res29" é um nome de uma variavel gerado sequencialmente para
+ armazenar os resultados das expressões que escreveu, por isso o resultado
+ pode ser ligeiramente diferente.
+*/
+
+"Strings em scala são rodeadas por aspas"
+'a' // Um caracter de Scala
+// 'Strings entre plicas não existem' <= Isto causa um erro
+
+// Strings tem os métodos de Java habituais definidos
+"olá mundo".length
+"olá mundo".substring(2, 6)
+"olá mundo".replace("á", "é")
+
+// Para além disso, também possuem métodos de Scala.
+// Ver: scala.collection.immutable.StringOps
+"olá mundo".take(5)
+"olá mundo".drop(5)
+
+// Interpolação de Strings: repare no prefixo "s"
+val n = 45
+s"Temos $n maçãs" // => "Temos 45 maçãs"
+
+// Expressões dentro de Strings interpoladas também são possíveis
+val a = Array(11, 9, 6)
+s"A minha segunda filha tem ${a(0) - a(2)} anos." // => "A minha segunda filha tem 5 anos."
+s"Temos o dobro de ${n / 2.0} em maçãs." // => "Temos o dobro de 22.5 em maçãs."
+s"Potência de 2: ${math.pow(2, 2)}" // => "Potência de 2: 4"
+
+// Strings interpoladas são formatadas com o prefixo "f"
+f"Potência de 5: ${math.pow(5, 2)}%1.0f" // "Potência de 5: 25"
+f"Raíz quadrada 122: ${math.sqrt(122)}%1.4f" // "Raíz quadrada de 122: 11.0454"
+
+// Strings prefixadas com "raw" ignoram caracteres especiais
+raw"Nova linha: \n. Retorno: \r." // => "Nova Linha: \n. Retorno: \r."
+
+// Alguns caracteres tem de ser "escapados", e.g. uma aspa dentro de uma string:
+"Esperaram fora do \"Rose and Crown\"" // => "Esperaram fora do "Rose and Crown""
+
+// Strings rodeadas por três aspas podem-se estender por varias linhas e conter aspas
+val html = """<form id="daform">
+ <p>Carrega aqui, Zé</p>
+ <input type="submit">
+ </form>"""
+
+
+/////////////////////////////////////////////////
+// 2. Funções
+/////////////////////////////////////////////////
+
+// Funções são definidas como:
+//
+// def nomeDaFuncao(args...): TipoDeRetorno = { corpo... }
+//
+// Se vem de linugagens mais tradicionais, repare na omissão da palavra
+// return keyword. Em Scala, a ultima expressão de um bloco é o seu
+// valor de retorno
+def somaQuadrados(x: Int, y: Int): Int = {
+ val x2 = x * x
+ val y2 = y * y
+ x2 + y2
+}
+
+// As { } podem ser omitidas se o corpo da função for apenas uma expressão:
+def somaQuadradosCurto(x: Int, y: Int): Int = x * x + y * y
+
+// A sintaxe para chamar funções deve ser familiar:
+somaQuadrados(3, 4) // => 25
+
+// Na maior parte dos casos (sendo funções recursivas a principal excepção), o
+// tipo de retorno da função pode ser omitido, sendo que a inferencia de tipos
+// é aplicada aos valores de retorno
+def quadrado(x: Int) = x * x // O compilador infere o tipo de retorno Int
+
+// Funções podem ter parâmetros por omissão:
+def somaComOmissão(x: Int, y: Int = 5) = x + y
+somaComOmissão(1, 2) // => 3
+somaComOmissão(1) // => 6
+
+
+// Funções anónimas são definidas da seguinte forma:
+(x: Int) => x * x
+
+// Ao contrário de defs, o tipo de input de funções anónimas pode ser omitido
+// se o contexto o tornar óbvio. Note que o tipo "Int => Int" representa uma
+// funão que recebe Int e retorna Int.
+val quadrado: Int => Int = x => x * x
+
+// Funcões anónimas são chamadas como funções normais:
+quadrado(10) // => 100
+
+// Se cada argumento de uma função anónima for usado apenas uma vez, existe
+// uma forma ainda mais curta de os definir. Estas funções anónumas são
+// extremamente comuns, como será visto na secção sobre estruturas de dados.
+val somaUm: Int => Int = _ + 1
+val somaEstranha: (Int, Int) => Int = (_ * 2 + _ * 3)
+
+somaUm(5) // => 6
+somaEstranha(2, 4) // => 16
+
+
+// O código return existe em Scala, mas apenas retorna do def mais interior
+// que o rodeia.
+// AVISO: Usar return em Scala deve ser evitado, pois facilmente leva a erros.
+// Não tem qualquer efeito em funções anónimas, por exemplo:
+def foo(x: Int): Int = {
+ val funcAnon: Int => Int = { z =>
+ if (z > 5)
+ return z // Esta linha faz com que z seja o retorno de foo!
+ else
+ z + 2 // Esta linha define o retorno de funcAnon
+ }
+ funcAnon(x) // Esta linha define o valor de retorno de foo
+}
+
+
+/////////////////////////////////////////////////
+// 3. Controlo de fluxo
+/////////////////////////////////////////////////
+
+1 to 5
+val r = 1 to 5
+r.foreach(println)
+
+r foreach println
+// NB: Scala é bastante brando no que toca a pontos e parentisis - estude as
+// regras separadamente. Isto permite escrever APIs e DSLs bastante legiveis
+
+(5 to 1 by -1) foreach (println)
+
+// Ciclos while
+var i = 0
+while (i < 10) { println("i " + i); i += 1 }
+
+while (i < 10) { println("i " + i); i += 1 } // Sim, outra vez. O que aconteceu? Porquê?
+
+i // Mostra o valor de i. Note que o while é um ciclo no sentido clássico -
+ // executa sequencialmente enquanto muda uma variável. Ciclos while são
+ // rápidos, por vezes até mais que ciclos de Java, mas combinadores e
+ // compreensões (usados anteriormente) são mais fáceis de entender e
+ // paralelizar
+
+// Um ciclo do while
+i = 0
+do {
+ println("i ainda é menor que 10")
+ i += 1
+} while (i < 10)
+
+// A forma idiomática em Scala de definir acções recorrentes é através de
+// recursão em cauda.
+// Funções recursivas necessitam de um tipo de retorno definido explicitamente.
+// Neste caso, é Unit.
+def mostraNumerosEntre(a: Int, b: Int): Unit = {
+ print(a)
+ if (a < b)
+ mostraNumerosEntre(a + 1, b)
+}
+mostraNumerosEntre(1, 14)
+
+
+// Condicionais
+
+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")
+
+println(if (x == 10) "yeah" else "nope")
+val text = if (x == 10) "yeah" else "nope"
+
+
+/////////////////////////////////////////////////
+// 4. Estruturas de dados
+/////////////////////////////////////////////////
+
+val a = Array(1, 2, 3, 5, 8, 13)
+a(0)
+a(3)
+a(21) // Lança uma excepção
+
+val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo")
+m("fork")
+m("spoon")
+m("bottle") // Lança uma excepção
+
+val safeM = m.withDefaultValue("no lo se")
+safeM("bottle")
+
+val s = Set(1, 3, 7)
+s(0)
+s(1)
+
+/* Veja a documentação de mapas de scala em -
+ * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map
+ * e verifique que a consegue aceder
+ */
+
+
+// Tuplos
+
+(1, 2)
+
+(4, 3, 2)
+
+(1, 2, "três")
+
+(a, 2, "três")
+
+// Porquê ter isto?
+val divideInts = (x: Int, y: Int) => (x / y, x % y)
+
+divideInts(10, 3) // A função divideInts returna o resultado e o resto
+
+// Para aceder aos elementos de um tuplo, pode-se usar _._n, onde n é o indice
+// (começado em 1) do elemento
+val d = divideInts(10, 3)
+
+d._1
+
+d._2
+
+
+/////////////////////////////////////////////////
+// 5. Programação Orientada a Objectos
+/////////////////////////////////////////////////
+
+/*
+ Aparte: Até agora tudo o que fizemos neste tutorial foram expressões simples
+ (valores, funções, etc). Estas expressões são suficientes para executar no
+ interpretador da linha de comandos para testes rápidos, mas não podem existir
+ isoladas num ficheiro de Scala. Por exemplo, não é possivel correr um
+ ficheiro scala que apenas contenha "val x = 5". Em vez disso, as únicas
+ construções de topo permitidas são:
+
+ - object
+ - class
+ - case class
+ - trait
+
+ Vamos agora explicar o que são:
+*/
+
+// Classes são semelhantes a classes noutras linguagens. Os argumentos do
+// construtor são declarados após o nome da classe, sendo a inicialização feita
+// no corpo da classe.
+class Cão(rc: String) {
+ // Código de construção
+ var raça: String = rc
+
+ // Define um método chamado "ladra", que retorna uma String
+ def ladra = "Woof, woof!"
+
+ // Valores e métodos são assumidos como públicos, mas é possivel usar
+ // os códigos "protected" and "private".
+ private def dormir(horas: Int) =
+ println(s"Vou dormir por $horas horas")
+
+ // Métodos abstractos são métodos sem corpo. Se descomentarmos a próxima
+ // linha, a classe Cão é declarada como abstracta
+ // abstract class Cão(...) { ... }
+ // def persegue(oQue: String): String
+}
+
+val oMeuCão = new Cão("greyhound")
+println(oMeuCão.raça) // => "greyhound"
+println(oMeuCão.ladra) // => "Woof, woof!"
+
+
+// O termo "object" cria um tipo e uma instancia singleton desse tipo. É comum
+// que classes de Scala possuam um "objecto companheiro", onde o comportamento
+// por instância é capturado nas classes, equanto que o comportamento
+// relacionado com todas as instancias dessa classe ficam no objecto.
+// A diferença é semelhante a métodos de classes e métodos estáticos noutras
+// linguagens. Note que objectos e classes podem ter o mesmo nome.
+object Cão {
+ def raçasConhecidas = List("pitbull", "shepherd", "retriever")
+ def criarCão(raça: String) = new Cão(raça)
+}
+
+
+// Case classes são classes com funcionalidades extra incluidas. Uma questão
+// comum de iniciantes de scala é quando devem usar classes e quando devem usar
+// case classes. A linha é difusa mas, em geral, classes tendem a concentrar-se
+// em encapsulamento, polimorfismo e comportamento. Os valores nestas classes
+// tendem a ser privados, sendo apenas exposotos métodos. O propósito principal
+// das case classes é armazenarem dados imutáveis. Geralmente possuem poucos
+// métods, sendo que estes raramente possuem efeitos secundários.
+case class Pessoa(nome: String, telefone: String)
+
+// Cria uma nova instancia. De notar que case classes não precisam de "new"
+val jorge = Pessoa("Jorge", "1234")
+val cátia = Pessoa("Cátia", "4567")
+
+// Case classes trazem algumas vantagens de borla, como acessores:
+jorge.telefone // => "1234"
+
+// Igualdade por campo (não é preciso fazer override do .equals)
+Pessoa("Jorge", "1234") == Pessoa("Cátia", "1236") // => false
+
+// Cópia simples
+// outroJorge == Person("jorge", "9876")
+val outroJorge = jorge.copy(telefone = "9876")
+
+// Entre outras. Case classes também suportam correspondência de padrões de
+// borla, como pode ser visto de seguida.
+
+
+// Traits em breve!
+
+
+/////////////////////////////////////////////////
+// 6. Correspondência de Padrões
+/////////////////////////////////////////////////
+
+// A correspondência de padrões é uma funcionalidade poderosa e bastante
+// utilizada em Scala. Eis como fazer correspondência de padrões numa case class:
+// Nota: Ao contrário de outras linguagens, cases em scala não necessitam de
+// breaks, a computação termina no primeiro sucesso.
+
+def reconhecePessoa(pessoa: Pessoa): String = pessoa match {
+ // Agora, especifique os padrões:
+ case Pessoa("Jorge", tel) => "Encontramos o Jorge! O seu número é " + tel
+ case Pessoa("Cátia", tel) => "Encontramos a Cátia! O seu número é " + tel
+ case Pessoa(nome, tel) => "Econtramos alguém : " + nome + ", telefone : " + tel
+}
+
+val email = "(.*)@(.*)".r // Define uma regex para o próximo exemplo.
+
+// A correspondência de padrões pode parecer familiar aos switches em linguagens
+// derivadas de C, mas é muto mais poderoso. Em Scala, é possível fazer
+// correspondências com muito mais:
+def correspondeTudo(obj: Any): String = obj match {
+ // Pode-se corresponder valores:
+ case "Olá mundo" => "Recebi uma string Olá mundo."
+
+ // Corresponder por tipo:
+ case x: Double => "Recebi um Double: " + x
+
+ // Corresponder tendo em conta condições especificas:
+ case x: Int if x > 10000 => "Recebi um número bem grande!"
+
+ // Fazer correspondências com case classes (visto anteriormente):
+ case Pessoa(nome, tel) => s"Recebi o contacto para $nome!"
+
+ // Fazer correspondência com expressões regulares:
+ case email(nome, dominio) => s"Recebi o endereço de email $nome@$dominio"
+
+ // Corresponder tuplos:
+ case (a: Int, b: Double, c: String) => s"Recebi o tuplo: $a, $b, $c"
+
+ // Corresponder estruturas de dados:
+ case List(1, b, c) => s"Recebi uma lista de 3 elementos começada em 1: 1, $b, $c"
+
+ // Combinar padrões:
+ case List(List((1, 2, "YAY"))) => "Recebi uma lista de lista de triplo"
+}
+
+// Na realidade, é possível fazer correspondência com qualquer objecto que
+// defina o método "unapply". Esta funcionalidade é tão poderosa que permite
+// definir funções sob a forma de padrões:
+val funcPaddrao: Pessoa => String = {
+ case Pessoa("Jorge", tel) => s"Número do Jorge: $tel"
+ case Pessoa(nome, tel) => s"Número de alguém: $tel"
+}
+
+
+/////////////////////////////////////////////////
+// 7. Programação Funcional
+/////////////////////////////////////////////////
+
+// Scala permite que funções e métodos retornem, ou recebam como parámetros,
+// outras funções ou métodos
+
+val soma10: Int => Int = _ + 10 // Função que recebe um Int e retorna um Int
+List(1, 2, 3) map soma10 // List(11, 12, 13) - soma10 é aplicado a cada elemento
+
+// Funções anónimas também podem ser usadas
+List(1, 2, 3) map (x => x + 10)
+
+// Sendo que o símbolo _ também pode ser usado se a função anónima só receber
+// um argumento. Este fica com o valor da variável
+List(1, 2, 3) map (_ + 10)
+
+// Se tanto o bloco como a função apenas receberem um argumento, o próprio
+// _ pode ser omitido
+List("Dom", "Bob", "Natalia") foreach println
+
+
+// Combinadores
+
+s.map(quadrado)
+
+val sQuadrado = s.map(quadrado)
+
+sQuadrado.filter(_ < 10)
+
+sQuadrado.reduce (_+_)
+
+// O método filter recebe um predicado (uma função de A => Boolean) e escolhe
+// todos os elementos que satisfazem o predicado
+List(1, 2, 3) filter (_ > 2) // List(3)
+case class Pessoa(nome: String, idade: Int)
+List(
+ Pessoa(nome = "Dom", idade = 23),
+ Pessoa(nome = "Bob", idade = 30)
+).filter(_.idade > 25) // List(Pessoa("Bob", 30))
+
+
+// O método foreach recebe uma função de A => Unit, executando essa função em
+// cada elemento da colecção
+val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100)
+aListOfNumbers foreach (x => println(x))
+aListOfNumbers foreach println
+
+// Compreensões For
+
+for { n <- s } yield quadrado(n)
+
+val nQuadrado2 = for { n <- s } yield quadrado(n)
+
+for { n <- nQuadrado2 if n < 10 } yield n
+
+for { n <- s; nQuadrado = n * n if nQuadrado < 10} yield nQuadrado
+
+/* Nota: isto não são ciclos for: A semântica de um ciclo é 'repetir', enquanto
+ que uma compreensão define a relação entre dois conjuntos de dados. */
+
+
+/////////////////////////////////////////////////
+// 8. Implicitos
+/////////////////////////////////////////////////
+
+/* AVISO IMPORTANTE: Implicitos são um conjunto de funcionalidades muito
+ * poderosas em Scala, que podem ser fácilmente abusadas. Iniciantes devem
+ * resistir a tentação de usá-los até que compreendam não só como funcionam,
+ * mas também as melhores práticas. Apenas incluimos esta secção no tutorial
+ * devido a estes serem tão comuns em bibliotecas de Scala que muitas delas
+ * se tornam impossíveis de usar sem conhecer implicitos. Este capítulo serve
+ * para compreender como trabalhar com implicitos, não como declará-los.
+*/
+
+// Qualquer valor (vals, funções, objectos, etc) pode ser declarado como
+// implicito usando a palavra "implicit". Vamos usar a classe Cão da secção 5
+// nestes exemplos
+
+implicit val oMeuIntImplicito = 100
+implicit def aMinhaFunçãoImplicita(raça: String) = new Cão("Golden " + raça)
+
+// Por si só, a palavra implicit não altera o comportamento de um valor, sendo
+// que estes podem ser usados da forma habitual.
+oMeuIntImplicito + 2 // => 102
+aMinhaFunçãoImplicita("Pitbull").raça // => "Golden Pitbull"
+
+// A diferença é que estes valores podem ser utilizados quando outro pedaço de
+// código "necessite" de uma valor implicito. Um exemplo são argumentos
+// implicitos de funções:
+def enviaCumprimentos(aQuem: String)(implicit quantos: Int) =
+ s"Olá $aQuem, $quantos cumprimentos para ti e para os teus!"
+
+// Se dermos um valor a "quantos", a função comporta-se normalmente
+enviaCumprimentos("João")(1000) // => "Olá João, 1000 cumprimentos para ti e para os teus!"
+
+// Mas, se omitirmos o parâmetro implicito, um valor implicito do mesmo tipo é
+// usado, neste caso, "oMeuInteiroImplicito"
+enviaCumprimentos("Joana") // => "Olá Joana, 100 cumprimentos para ti e para os teus!"
+
+// Parâmentros implicitos de funções permitem-nos simular classes de tipos de
+// outras linguagens funcionais. Isto é tão comum que tem a sua própria notação.
+// As seguintes linhas representam a mesma coisa
+// def foo[T](implicit c: C[T]) = ...
+// def foo[T : C] = ...
+
+
+// Outra situação em que o compilador prouca um implicito é se encontrar uma
+// expressão
+// obj.método(...)
+// mas "obj" não possuir um método chamado "método". Neste cso, se houver uma
+// conversão implicita A => B, onde A é o tipo de obj, e B possui um método
+// chamado "método", a conversão é aplicada. Ou seja, tendo
+// aMinhaFunçãoImplicita definida, podemos dizer
+"Retriever".raça // => "Golden Retriever"
+"Sheperd".ladra // => "Woof, woof!"
+
+// Neste caso, a String é primeiro convertida para Cão usando a nossa funão,
+// sendo depois chamado o método apropriado. Esta é uma funcionalidade
+// incrivelmente poderosa, sendo que deve ser usada com cautela. Na verdade,
+// ao definir a função implicita, o compilador deve lançar um aviso a insisitir
+// que só deve definir a função se souber o que está a fazer.
+
+
+/////////////////////////////////////////////////
+// 9. Misc
+/////////////////////////////////////////////////
+
+// Importar coisas
+import scala.collection.immutable.List
+
+// Importar todos os "sub pacotes"
+import scala.collection.immutable._
+
+// Importar multiplas classes numa linha
+import scala.collection.immutable.{List, Map}
+
+// Renomear uma classe importada usando '=>'
+import scala.collection.immutable.{List => ImmutableList}
+
+// Importar todas as classes excepto algumas. Set e Map são excluidos:
+import scala.collection.immutable.{Map => _, Set => _, _}
+
+// O ponto de entrada de um programa em Scala é definido por un ficheiro .scala
+// com um método main:
+object Aplicação {
+ def main(args: Array[String]): Unit = {
+ // código aqui.
+ }
+}
+
+// Ficheiros podem conter várias classes o objectos. Compilar com scalac
+
+
+
+
+// Input e output
+
+// Ler um ficheiro linha a linha
+import scala.io.Source
+for(linha <- Source.fromFile("ficheiro.txt").getLines())
+ println(linha)
+
+// Escrever um ficheiro usando o PrintWriter de Java
+val writer = new PrintWriter("ficheiro.txt")
+writer.write("Escrevendo linha por linha" + util.Properties.lineSeparator)
+writer.write("Outra linha aqui" + util.Properties.lineSeparator)
+writer.close()
+
+```
+
+## Mais recursos
+
+* [Scala for the impatient](http://horstmann.com/scala/)
+* [Twitter Scala school](http://twitter.github.io/scala_school/)
+* [The scala documentation](http://docs.scala-lang.org/)
+* [Try Scala in your browser](http://scalatutorials.com/tour/)
+* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user)
diff --git a/purescript.html.markdown b/purescript.html.markdown
index a006cdff..b413a9e3 100644
--- a/purescript.html.markdown
+++ b/purescript.html.markdown
@@ -2,44 +2,53 @@
language: purescript
contributors:
- ["Fredrik Dyrkell", "http://www.lexicallyscoped.com"]
+ - ["Thimoteus", "https://github.com/Thimoteus"]
---
PureScript is a small strongly, statically typed language compiling to Javascript.
* Learn more at [http://www.purescript.org/](http://www.purescript.org/)
-* Documentation: [http://docs.purescript.org/en/latest/](http://docs.purescript.org/en/latest/)
+* Documentation: [http://pursuit.purescript.org/](http://pursuit.purescript.org/)
* Book: Purescript by Example, [https://leanpub.com/purescript/](https://leanpub.com/purescript/)
+All the noncommented lines of code can be run in the PSCI REPL, though some will
+require the `--multi-line-mode` flag.
+
```haskell
--
-- 1. Primitive datatypes that corresponds to their Javascript
-- equivalents at runtime.
+import Prelude
-- Numbers
-1 + 7*5 :: Number -- 36
+1.0 + 7.2*5.5 :: Number -- 40.6
+-- Ints
+1 + 2*5 :: Int -- 11
-- Types are inferred, so the following works fine
-9 / 2.5 + 4.4 -- 8
+9.0/2.5 + 4.4 -- 8.0
+-- But Ints and Numbers don't mix, so the following won't
+5/2 + 2.5 -- Expression 2.5 does not have type Int
-- Hexadecimal literals
0xff + 1 -- 256
-- Unary negation
6 * -3 -- -18
6 * negate 3 -- -18
--- Modulus
-3 % 2 -- 1
-4 % 2 -- 0
+-- Modulus, from purescript-math (Math)
+3.0 % 2.0 -- 1.0
+4.0 % 2.0 -- 0.0
-- Inspect the type of an expression in psci
-:t 9 / 2.5 + 4.4 -- Prim.Number
+:t 9.5/2.5 + 4.4 -- Prim.Number
-- Booleans
true :: Boolean -- true
false :: Boolean -- false
-- Negation
-not true --false
+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
@@ -49,19 +58,22 @@ true && (9 >= 19 || 1 < 2) -- true
-- Strings
"Hellow" :: String -- "Hellow"
--- Multiline string
+-- Multiline string without newlines, to run in psci use the --multi-line-mode flag
"Hellow\
\orld" -- "Helloworld"
+-- Multiline string with newlines
+"""Hello
+world""" -- "Hello\nworld"
-- Concatenate
"such " ++ "amaze" -- "such amaze"
--
-- 2. Arrays are Javascript arrays, but must be homogeneous
-[1,1,2,3,5,8] :: [Number] -- [1,1,2,3,5,8]
-[true, true, false] :: [Boolean] -- [true,true,false]
+[1,1,2,3,5,8] :: Array Number -- [1,1,2,3,5,8]
+[true, true, false] :: Array Boolean -- [true,true,false]
-- [1,2, true, "false"] won't work
--- `Cannot unify Prim.Number with Prim.Boolean`
+-- `Cannot unify Prim.Int with Prim.Boolean`
-- Cons (prepend)
1 : [2,4,3] -- [1,2,4,3]
@@ -84,91 +96,95 @@ append [1,2,3] [4,5,6] -- [1,2,3,4,5,6]
--
-- 3. Records are Javascript objects, with zero or more fields, which
--- can have different types
+-- can have different types.
+-- In psci you have to write `let` in front of the function to get a
+-- top level binding.
let book = {title: "Foucault's pendulum", author: "Umberto Eco"}
-- Access properties
book.title -- "Foucault's pendulum"
-getTitle b = b.title
+let getTitle b = b.title
-- Works on all records with a title (but doesn't require any other field)
getTitle book -- "Foucault's pendulum"
getTitle {title: "Weekend in Monaco", artist: "The Rippingtons"} -- "Weekend in Monaco"
+-- Can use underscores as shorthand
+_.title book -- "Foucault's pendulum"
-- Update a record
-changeTitle b t = b {title = t}
-changeTitle book "Ill nome della rosa" -- {title: "Ill nome della
- -- rosa", author: "Umberto Eco"}
+let changeTitle b t = b {title = t}
+getTitle (changeTitle book "Ill nome della rosa") -- "Ill nome della rosa"
--
-- 4. Functions
-sumOfSquares x y = x*x+y*y
+-- In psci's multiline mode
+let sumOfSquares :: Int -> Int -> Int
+ sumOfSquares x y = x*x + y*y
sumOfSquares 3 4 -- 25
--- In psci you have to write `let` in front of the function to get a
--- top level binding
-mod x y = x % y
-mod 3 2 -- 1
+let myMod x y = x % y
+myMod 3.0 2.0 -- 1.0
-- Infix application of function
3 `mod` 2 -- 1
--- function application have higher precedence than all other
+-- function application has higher precedence than all other
-- operators
sumOfSquares 3 4 * sumOfSquares 4 5 -- 1025
-- Conditional
-abs' n = if n>=0 then n else -n
+let abs' n = if n>=0 then n else -n
abs' (-3) -- 3
-- Guarded equations
-abs n | n >= 0 = n
- | otherwise = -n
+let abs'' n | n >= 0 = n
+ | otherwise = -n
-- Pattern matching
--- Note the type signature, input is an array of numbers The pattern
--- matching destructures and binds the array into parts
-first :: [Number] -> Number
-first (x:_) = x
-first [3,4,5] -- 3
-second :: [Number] -> Number
-second (_:y:_) = y
-second [3,4,5] -- 4
-sumTwo :: [Number] -> [Number]
-sumTwo (x:y:rest) = (x+y) : rest
-sumTwo [2,3,4,5,6] -- [5,4,5,6]
-
--- sumTwo doesn't handle when the array is empty or just have one
--- element in which case you get an error
+-- Note the type signature, input is a list of numbers. The pattern matching
+-- destructures and binds the list into parts.
+-- Requires purescript-lists (Data.List)
+let first :: forall a. List a -> a
+ first (Cons x _) = x
+first (toList [3,4,5]) -- 3
+let second :: forall a. List a -> a
+ second (Cons _ (Cons y _)) = y
+second (toList [3,4,5]) -- 4
+let sumTwo :: List Int -> List Int
+ sumTwo (Cons x (Cons y rest)) = x + y : rest
+fromList (sumTwo (toList [2,3,4,5,6])) :: Array Int -- [5,4,5,6]
+
+-- sumTwo doesn't handle when the list is empty or there's only one element in
+-- which case you get an error.
sumTwo [1] -- Failed pattern match
-- Complementing patterns to match
-- Good ol' Fibonacci
-fib 1 = 1
-fib 2 = 2
-fib x = fib (x-1) + fib (x-2)
+let fib 1 = 1
+ fib 2 = 2
+ fib x = fib (x-1) + fib (x-2)
fib 10 -- 89
-- Use underscore to match any, where you don't care about the binding name
-isZero 0 = true
-isZero _ = false
+let isZero 0 = true
+ isZero _ = false
-- Pattern matching on records
-ecoTitle {author = "Umberto Eco", title = t} = Just t
-ecoTitle _ = Nothing
+let ecoTitle {author = "Umberto Eco", title = t} = Just t
+ ecoTitle _ = Nothing
ecoTitle book -- Just ("Foucault's pendulum")
ecoTitle {title: "The Quantum Thief", author: "Hannu Rajaniemi"} -- Nothing
-- ecoTitle requires both field to type check:
-ecoTitle {title: "The Quantum Thief"} -- Object does not have property author
+ecoTitle {title: "The Quantum Thief"} -- Object lacks required property "author"
-- Lambda expressions
(\x -> x*x) 3 -- 9
(\x y -> x*x + y*y) 4 5 -- 41
-sqr = \x -> x*x
+let sqr = \x -> x*x
-- Currying
-add x y = x + y -- is equivalent with
-add = \x -> (\y -> x+y)
-add3 = add 3
-:t add3 -- Prim.Number -> Prim.Number
+let myAdd x y = x + y -- is equivalent with
+let myAdd' = \x -> \y -> x + y
+let add3 = myAdd 3
+:t add3 -- Prim.Int -> Prim.Int
-- Forward and backward function composition
-- drop 3 followed by taking 5
@@ -177,11 +193,11 @@ add3 = add 3
(drop 3 <<< take 5) (1..20) -- [4,5]
-- Operations using higher order functions
-even x = x % 2 == 0
+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]
+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
@@ -192,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 5572e38e..2e7fd8be 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -4,6 +4,7 @@ contributors:
- ["Louie Dinh", "http://ldinh.ca"]
- ["Amin Bandali", "http://aminbandali.com"]
- ["Andre Polykanine", "https://github.com/Oire"]
+ - ["evuez", "http://github.com/evuez"]
filename: learnpython.py
---
@@ -14,7 +15,13 @@ executable pseudocode.
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. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
+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.
```python
@@ -52,6 +59,12 @@ to Python 2.x. For Python 3.x, take a look at the [Python 3 tutorial](http://lea
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
+# Note that we can also import division module(Section 6 Modules)
+# to carry out normal division with just one '/'.
+from __future__ import division
+11/4 # => 2.75 ...normal division
+11//4 # => 2 ...floored division
+
# Modulo operation
7 % 3 # => 1
@@ -110,11 +123,16 @@ not False # => True
# A string can be treated like a list of characters
"This is a string"[0] # => 'T'
-# % can be used to format strings, like this:
-"%s can be %s" % ("strings", "interpolated")
+#String formatting with %
+#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'
+z = "The items in the basket are %s and %s" % (x,y)
# A newer way to format strings is the format method.
# This method is the preferred way
+"{} is a {}".format("This", "placeholder")
"{0} can be {1}".format("strings", "formatted")
# You can use keywords if you don't want to count.
"{name} wants to eat {food}".format(name="Bob", food="lasagna")
@@ -131,8 +149,16 @@ None is None # => True
# very useful when dealing with primitive values, but is
# very useful when dealing with objects.
-# None, 0, and empty strings/lists all evaluate to False.
-# All other values are True
+# Any object can be used in a Boolean context.
+# The following values are considered falsey:
+# - None
+# - zero of any numeric type (e.g., 0, 0L, 0.0, 0j)
+# - empty sequences (e.g., '', (), [])
+# - empty containers (e.g., {}, set())
+# - instances of user-defined classes meeting certain conditions
+# see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
+#
+# All other values are truthy (using the bool() function on them returns True).
bool(0) # => False
bool("") # => False
@@ -142,7 +168,13 @@ bool("") # => False
####################################################
# Python has a print statement
-print "I'm Python. Nice to meet you!"
+print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!
+
+# Simple way to get input data from console
+input_string_var = raw_input("Enter some data: ") # Returns the data as a string
+input_var = input("Enter some data: ") # Evaluates the data as python code
+# Warning: Caution is recommended for input() method usage
+# Note: In python 3, input() is deprecated and raw_input() is renamed to input()
# No need to declare variables before assigning to them.
some_var = 5 # Convention is to use lower_case_with_underscores
@@ -153,6 +185,7 @@ some_var # => 5
some_other_var # Raises a name error
# if can be used as an expression
+# Equivalent of C's '?:' ternary operator
"yahoo!" if 3 > 2 else 2 # => "yahoo!"
# Lists store sequences
@@ -206,6 +239,17 @@ li + other_li # => [1, 2, 3, 4, 5, 6]
# Concatenate lists with "extend()"
li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
+# Remove first occurrence of a value
+li.remove(2) # li is now [1, 3, 4, 5, 6]
+li.remove(2) # Raises a ValueError as 2 is not in the list
+
+# Insert an element at a specific index
+li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again
+
+# Get the index of the first item found
+li.index(2) # => 1
+li.index(7) # Raises a ValueError as 7 is not in the list
+
# Check for existence in a list with "in"
1 in li # => True
@@ -226,8 +270,9 @@ tup[:2] # => (1, 2)
# You can unpack tuples (or lists) into variables
a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3
+d, e, f = 4, 5, 6 # you can leave out the parentheses
# Tuples are created by default if you leave out the parentheses
-d, e, f = 4, 5, 6
+g = 4, 5, 6 # => (4, 5, 6)
# Now look how easy it is to swap two values
e, d = d, e # d is now 5 and e is now 4
@@ -297,6 +342,15 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# Do set difference with -
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+# Do set symmetric difference with ^
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# Check if set on the left is a superset of set on the right
+{1, 2} >= {1, 2, 3} # => False
+
+# Check if set on the left is a subset of set on the right
+{1, 2} <= {1, 2, 3} # => True
+
# Check for existence in a set with in
2 in filled_set # => True
10 in filled_set # => False
@@ -404,7 +458,7 @@ add(y=6, x=5) # Keyword arguments can arrive in any order.
# You can define functions that take a variable number of
-# positional args, which will be interpreted as a tuple if you do not use the *
+# positional args, which will be interpreted as a tuple by using *
def varargs(*args):
return args
@@ -412,7 +466,7 @@ 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 if you do not use **
+# keyword args, as well, which will be interpreted as a dict by using **
def keyword_args(**kwargs):
return kwargs
@@ -448,19 +502,19 @@ def pass_all_the_args(*args, **kwargs):
# Function Scope
x = 5
-def setX(num):
+def set_x(num):
# Local var x not the same as global variable x
x = num # => 43
print x # => 43
-def setGlobalX(num):
+def set_global_x(num):
global x
print x # => 5
x = num # global var x is now set to 6
print x # => 6
-setX(43)
-setGlobalX(6)
+set_x(43)
+set_global_x(6)
# Python has first class functions
def create_adder(x):
@@ -473,9 +527,12 @@ add_10(3) # => 13
# There are also anonymous functions
(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
# 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]
+
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
# We can use list comprehensions for nice maps and filters
@@ -501,6 +558,10 @@ class Human(object):
# Assign the argument to the instance's name attribute
self.name = name
+ # Initialize property
+ self.age = 0
+
+
# An instance method. All methods take "self" as the first argument
def say(self, msg):
return "{0}: {1}".format(self.name, msg)
@@ -516,6 +577,23 @@ class Human(object):
def grunt():
return "*grunt*"
+ # A property is just like a getter.
+ # It turns the method age() into an read-only attribute
+ # of the same name.
+ @property
+ def age(self):
+ return self._age
+
+ # This allows the property to be set
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # This allows the property to be deleted
+ @age.deleter
+ def age(self):
+ del self._age
+
# Instantiate a class
i = Human(name="Ian")
@@ -535,6 +613,16 @@ j.get_species() # => "H. neanderthalensis"
# Call the static method
Human.grunt() # => "*grunt*"
+# Update the property
+i.age = 42
+
+# Get the property
+i.age # => 42
+
+# Delete the property
+del i.age
+i.age # => raises an AttributeError
+
####################################################
## 6. Modules
@@ -633,11 +721,13 @@ 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.6/)
+* [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/)
+* [LearnPython](http://www.learnpython.org/)
+* [Fullstack Python](https://www.fullstackpython.com/)
### Dead Tree
diff --git a/python3.html.markdown b/python3.html.markdown
index acd6187c..d88ccec1 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -5,6 +5,7 @@ contributors:
- ["Steven Basart", "http://github.com/xksteven"]
- ["Andre Polykanine", "https://github.com/Oire"]
- ["Zachary Ferguson", "http://github.com/zfergus2"]
+ - ["evuez", "http://github.com/evuez"]
filename: learnpython3.py
---
@@ -33,27 +34,27 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea
3 # => 3
# Math is what you would expect
-1 + 1 # => 2
-8 - 1 # => 7
+1 + 1 # => 2
+8 - 1 # => 7
10 * 2 # => 20
# Except division which returns floats, real numbers, by default
35 / 5 # => 7.0
# Result of integer division truncated down both for positive and negative.
-5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # works on floats too
--5 // 3 # => -2
--5.0 // 3.0 # => -2.0
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # works on floats too
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
# When you use a float, results are floats
-3 * 2.0 # => 6.0
+3 * 2.0 # => 6.0
# Modulo operation
-7 % 3 # => 1
+7 % 3 # => 1
# Exponentiation (x**y, x to the yth power)
-2**4 # => 16
+2**4 # => 16
# Enforce precedence with parentheses
(1 + 3) * 2 # => 8
@@ -63,20 +64,20 @@ True
False
# negate with not
-not True # => False
+not True # => False
not False # => True
# Boolean Operators
# Note "and" and "or" are case-sensitive
-True and False #=> False
-False or True #=> True
+True and False # => False
+False or True # => True
# Note using Bool operators with ints
-0 and 2 #=> 0
--5 or 0 #=> -5
-0 == False #=> True
-2 == True #=> False
-1 == True #=> True
+0 and 2 # => 0
+-5 or 0 # => -5
+0 == False # => True
+2 == True # => False
+1 == True # => True
# Equality is ==
1 == 1 # => True
@@ -96,15 +97,15 @@ 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 is a # => False, a and b do not refer to the same object
-b == a # => True, a's and b's objects are equal
+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 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
# Strings are created with " or '
"This is a string."
@@ -113,24 +114,24 @@ b == a # => True, a's and b's objects are equal
# Strings can be added too! But try not to do this.
"Hello " + "world!" # => "Hello world!"
# Strings can be added without using '+'
-"Hello " "world!" # => "Hello world!"
+"Hello " "world!" # => "Hello world!"
# A string can be treated like a list of characters
"This is a string"[0] # => 'T'
# .format can be used to format strings, like this:
-"{} can be {}".format("strings", "interpolated")
+"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated"
# You can repeat the formatting arguments to save some typing.
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
-#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick"
+# => "Jack be nimble, Jack be quick, Jack jump over the candle stick"
# You can use keywords if you don't want to count.
-"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna"
+"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna"
# If your Python 3 code also needs to run on Python 2.5 and below, you can also
# still use the old style of formatting:
-"%s can be %s the %s way" % ("strings", "interpolated", "old")
+"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way"
# None is an object
@@ -139,14 +140,14 @@ None # => None
# Don't use the equality "==" symbol to compare objects to None
# Use "is" instead. This checks for equality of object identity.
"etc" is None # => False
-None is None # => True
+None is None # => True
# None, 0, and empty strings/lists/dicts all evaluate to False.
# All other values are True
-bool(0) # => False
+bool(0) # => False
bool("") # => False
-bool([]) #=> False
-bool({}) #=> False
+bool([]) # => False
+bool({}) # => False
####################################################
@@ -154,11 +155,15 @@ bool({}) #=> False
####################################################
# Python has a print function
-print("I'm Python. Nice to meet you!")
+print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you!
# By default the print function also prints out a newline at the end.
# Use the optional argument end to change the end character.
-print("Hello, World", end="!") # => Hello, World!
+print("Hello, World", end="!") # => Hello, World!
+
+# Simple way to get input data from console
+input_string_var = input("Enter some data: ") # Returns the data as a string
+# Note: In earlier versions of Python, input() method was named as raw_input()
# No need to declare variables before assigning to them.
# Convention is to use lower_case_with_underscores
@@ -169,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
@@ -185,7 +194,7 @@ li.pop() # => 3 and li is now [1, 2, 4]
li.append(3) # li is now [1, 2, 4, 3] again.
# Access a list like you would any array
-li[0] # => 1
+li[0] # => 1
# Look at the last element
li[-1] # => 3
@@ -194,61 +203,74 @@ li[4] # Raises an IndexError
# You can look at ranges with slice syntax.
# (It's a closed/open range for you mathy types.)
-li[1:3] # => [2, 4]
+li[1:3] # => [2, 4]
# Omit the beginning
-li[2:] # => [4, 3]
+li[2:] # => [4, 3]
# Omit the end
-li[:3] # => [1, 2, 4]
+li[:3] # => [1, 2, 4]
# Select every second entry
li[::2] # =>[1, 4]
# Return a reversed copy of the list
-li[::-1] # => [3, 4, 2, 1]
+li[::-1] # => [3, 4, 2, 1]
# Use any combination of these to make advanced slices
# li[start:end:step]
# Make a one layer deep copy using slices
-li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false.
+li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false.
# Remove arbitrary elements from a list with "del"
-del li[2] # li is now [1, 2, 3]
+del li[2] # li is now [1, 2, 3]
+
+# Remove first occurrence of a value
+li.remove(2) # li is now [1, 3]
+li.remove(2) # Raises a ValueError as 2 is not in the list
+
+# Insert an element at a specific index
+li.insert(1, 2) # li is now [1, 2, 3] again
+
+# Get the index of the first item found matching the argument
+li.index(2) # => 1
+li.index(4) # Raises a ValueError as 4 is not in the list
# You can add lists
# Note: values for li and for other_li are not modified.
-li + other_li # => [1, 2, 3, 4, 5, 6]
+li + other_li # => [1, 2, 3, 4, 5, 6]
# Concatenate lists with "extend()"
-li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
+li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
# Check for existence in a list with "in"
-1 in li # => True
+1 in li # => True
# Examine the length with "len()"
-len(li) # => 6
+len(li) # => 6
# Tuples are like lists but are immutable.
tup = (1, 2, 3)
-tup[0] # => 1
+tup[0] # => 1
tup[0] = 3 # Raises a TypeError
# Note that a tuple of length one has to have a comma after the last element but
# tuples of other lengths, even zero, do not.
-type((1)) # => <class 'int'>
-type((1,)) # => <class 'tuple'>
-type(()) # => <class 'tuple'>
+type((1)) # => <class 'int'>
+type((1,)) # => <class 'tuple'>
+type(()) # => <class 'tuple'>
# You can do most of the list operations on tuples too
-len(tup) # => 3
-tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
-tup[:2] # => (1, 2)
-2 in tup # => True
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
# You can unpack tuples (or lists) into variables
-a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3
+a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3
+# You can also do extended unpacking
+a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4
# Tuples are created by default if you leave out the parentheses
d, e, f = 4, 5, 6
# Now look how easy it is to swap two values
-e, d = d, e # d is now 5 and e is now 4
+e, d = d, e # d is now 5 and e is now 4
# Dictionaries store mappings
@@ -259,78 +281,92 @@ filled_dict = {"one": 1, "two": 2, "three": 3}
# Note keys for dictionaries have to be immutable types. This is to ensure that
# the key can be converted to a constant hash value for quick look-ups.
# Immutable types include ints, floats, strings, tuples.
-invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list'
-valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
+invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list'
+valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
# Look up values with []
-filled_dict["one"] # => 1
+filled_dict["one"] # => 1
# Get all keys as an iterable with "keys()". We need to wrap the call in list()
# to turn it into a list. We'll talk about those later. Note - Dictionary key
# ordering is not guaranteed. Your results might not match this exactly.
-list(filled_dict.keys()) # => ["three", "two", "one"]
+list(filled_dict.keys()) # => ["three", "two", "one"]
# Get all values as an iterable with "values()". Once again we need to wrap it
# in list() to get it out of the iterable. Note - Same as above regarding key
# ordering.
-list(filled_dict.values()) # => [3, 2, 1]
+list(filled_dict.values()) # => [3, 2, 1]
# Check for existence of keys in a dictionary with "in"
-"one" in filled_dict # => True
-1 in filled_dict # => False
+"one" in filled_dict # => True
+1 in filled_dict # => False
# Looking up a non-existing key is a KeyError
-filled_dict["four"] # KeyError
+filled_dict["four"] # KeyError
# Use "get()" method to avoid the KeyError
-filled_dict.get("one") # => 1
-filled_dict.get("four") # => None
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
# The get method supports a default argument when the value is missing
filled_dict.get("one", 4) # => 1
-filled_dict.get("four", 4) # => 4
+filled_dict.get("four", 4) # => 4
# "setdefault()" inserts into a dictionary only if the given key isn't present
filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5
filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5
# Adding to a dictionary
-filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}
-#filled_dict["four"] = 4 #another way to add to dict
+filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
+#filled_dict["four"] = 4 #another way to add to dict
# Remove keys from a dictionary with del
del filled_dict["one"] # Removes the key "one" from filled dict
+# From Python 3.5 you can also use the additional unpacking options
+{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2}
+{'a': 1, **{'a': 2}} # => {'a': 2}
+
+
# Sets store ... well sets
empty_set = set()
# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry.
-some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
+some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
# Similar to keys of a dictionary, elements of a set have to be immutable.
-invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list'
+invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list'
valid_set = {(1,), 1}
# Can set new variables to a set
filled_set = some_set
# Add one more item to the set
-filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
+filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
# Do set intersection with &
other_set = {3, 4, 5, 6}
-filled_set & other_set # => {3, 4, 5}
+filled_set & other_set # => {3, 4, 5}
# Do set union with |
-filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# Do set difference with -
-{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+
+# Do set symmetric difference with ^
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# Check if set on the left is a superset of set on the right
+{1, 2} >= {1, 2, 3} # => False
+
+# Check if set on the left is a subset of set on the right
+{1, 2} <= {1, 2, 3} # => True
# Check for existence in a set with in
2 in filled_set # => True
-10 in filled_set # => False
+10 in filled_set # => False
@@ -393,7 +429,6 @@ by step. If step is not indicated, the default value is 1.
prints:
4
6
- 8
"""
for i in range(4, 8, 2):
print(i)
@@ -416,12 +451,12 @@ try:
# Use "raise" to raise an error
raise IndexError("This is an index error")
except IndexError as e:
- pass # Pass is just a no-op. Usually you would do recovery here.
+ pass # Pass is just a no-op. Usually you would do recovery here.
except (TypeError, NameError):
- pass # Multiple exceptions can be handled together, if required.
-else: # Optional clause to the try/except block. Must follow all except blocks
+ pass # Multiple exceptions can be handled together, if required.
+else: # Optional clause to the try/except block. Must follow all except blocks
print("All good!") # Runs only if the code in try raises no exceptions
-finally: # Execute under all circumstances
+finally: # Execute under all circumstances
print("We can clean up resources here")
# Instead of try/finally to cleanup resources you can use a with statement
@@ -435,11 +470,11 @@ with open("myfile.txt") as f:
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
-print(our_iterable) #=> range(1,10). This is an object that implements our Iterable interface
+print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface.
# We can loop over it.
for i in our_iterable:
- print(i) # Prints one, two, three
+ print(i) # Prints one, two, three
# However we cannot address elements by index.
our_iterable[1] # Raises a TypeError
@@ -449,17 +484,17 @@ our_iterator = iter(our_iterable)
# Our iterator is an object that can remember the state as we traverse through it.
# We get the next object with "next()".
-next(our_iterator) #=> "one"
+next(our_iterator) # => "one"
# It maintains state as we iterate.
-next(our_iterator) #=> "two"
-next(our_iterator) #=> "three"
+next(our_iterator) # => "two"
+next(our_iterator) # => "three"
# After the iterator has returned all of its data, it gives you a StopIterator Exception
-next(our_iterator) # Raises StopIteration
+next(our_iterator) # Raises StopIteration
# You can grab all the elements of an iterator by calling list() on it.
-list(filled_dict.keys()) #=> Returns ["one", "two", "three"]
+list(filled_dict.keys()) # => Returns ["one", "two", "three"]
####################################################
@@ -469,20 +504,20 @@ list(filled_dict.keys()) #=> Returns ["one", "two", "three"]
# Use "def" to create new functions
def add(x, y):
print("x is {} and y is {}".format(x, y))
- return x + y # Return values with a return statement
+ return x + y # Return values with a return statement
# Calling functions with parameters
-add(5, 6) # => prints out "x is 5 and y is 6" and returns 11
+add(5, 6) # => prints out "x is 5 and y is 6" and returns 11
# Another way to call functions is with keyword arguments
-add(y=6, x=5) # Keyword arguments can arrive in any order.
+add(y=6, x=5) # Keyword arguments can arrive in any order.
# You can define functions that take a variable number of
# positional arguments
def varargs(*args):
return args
-varargs(1, 2, 3) # => (1, 2, 3)
+varargs(1, 2, 3) # => (1, 2, 3)
# You can define functions that take a variable number of
# keyword arguments, as well
@@ -490,7 +525,7 @@ def keyword_args(**kwargs):
return kwargs
# Let's call it to see what happens
-keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
# You can do both at once, if you like
@@ -507,36 +542,36 @@ all_the_args(1, 2, a=3, b=4) prints:
# Use * to expand tuples and use ** to expand kwargs.
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # equivalent to foo(1, 2, 3, 4)
-all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
-all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
+all_the_args(*args) # equivalent to foo(1, 2, 3, 4)
+all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
+all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
# Returning multiple values (with tuple assignments)
def swap(x, y):
- return y, x # Return multiple values as a tuple without the parenthesis.
- # (Note: parenthesis have been excluded but can be included)
+ return y, x # Return multiple values as a tuple without the parenthesis.
+ # (Note: parenthesis have been excluded but can be included)
x = 1
y = 2
-x, y = swap(x, y) # => x = 2, y = 1
-# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included.
+x, y = swap(x, y) # => x = 2, y = 1
+# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included.
# Function Scope
x = 5
-def setX(num):
+def set_x(num):
# Local var x not the same as global variable x
- x = num # => 43
- print (x) # => 43
+ x = num # => 43
+ print (x) # => 43
-def setGlobalX(num):
+def set_global_x(num):
global x
- print (x) # => 5
- x = num # global var x is now set to 6
- print (x) # => 6
+ print (x) # => 5
+ x = num # global var x is now set to 6
+ print (x) # => 6
-setX(43)
-setGlobalX(6)
+set_x(43)
+set_global_x(6)
# Python has first class functions
@@ -549,25 +584,28 @@ add_10 = create_adder(10)
add_10(3) # => 13
# There are also anonymous functions
-(lambda x: x > 2)(3) # => True
+(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]
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+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]
# 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
-[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]
+[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. Classes
####################################################
-# We subclass from object to get a class.
-class Human(object):
+# We use the "class" operator to get a class
+class Human:
# A class attribute. It is shared by all instances of this class
species = "H. sapiens"
@@ -582,6 +620,9 @@ class Human(object):
# Assign the argument to the instance's name attribute
self.name = name
+ # Initialize property
+ self.age = 0
+
# An instance method. All methods take "self" as the first argument
def say(self, msg):
return "{name}: {message}".format(name=self.name, message=msg)
@@ -597,6 +638,23 @@ class Human(object):
def grunt():
return "*grunt*"
+ # A property is just like a getter.
+ # It turns the method age() into an read-only attribute
+ # of the same name.
+ @property
+ def age(self):
+ return self._age
+
+ # This allows the property to be set
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # This allows the property to be deleted
+ @age.deleter
+ def age(self):
+ del self._age
+
# Instantiate a class
i = Human(name="Ian")
@@ -606,15 +664,26 @@ j = Human("Joel")
print(j.say("hello")) # prints out "Joel: hello"
# Call our class method
-i.get_species() # => "H. sapiens"
+i.get_species() # => "H. sapiens"
# Change the shared attribute
Human.species = "H. neanderthalensis"
-i.get_species() # => "H. neanderthalensis"
-j.get_species() # => "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
# Call the static method
-Human.grunt() # => "*grunt*"
+Human.grunt() # => "*grunt*"
+
+# Update the property
+i.age = 42
+
+# Get the property
+i.age # => 42
+
+# Delete the property
+del i.age
+i.age # => raises an AttributeError
+
####################################################
@@ -623,12 +692,12 @@ Human.grunt() # => "*grunt*"
# You can import modules
import math
-print(math.sqrt(16)) # => 4
+print(math.sqrt(16)) # => 4.0
# You can get specific functions from a module
from math import ceil, floor
-print(ceil(3.7)) # => 4.0
-print(floor(3.7)) # => 3.0
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
# You can import all functions from a module.
# Warning: this is not recommended
@@ -636,7 +705,7 @@ from math import *
# You can shorten module names
import math as m
-math.sqrt(16) == m.sqrt(16) # => True
+math.sqrt(16) == m.sqrt(16) # => True
# Python modules are just ordinary python files. You
# can write your own, and import them. The name of the
@@ -661,8 +730,6 @@ def double_numbers(iterable):
# Instead of generating and returning all values at once it creates one in each
# iteration. This means values bigger than 15 wont be processed in
# double_numbers.
-# Note range is a generator too. Creating a list 1-900000000 would take lot of
-# time to be made
# We use a trailing underscore in variable names when we want to use a name that
# would normally collide with a python keyword
range_ = range(1, 900000000)
@@ -697,7 +764,7 @@ def say(say_please=False):
return msg, say_please
-print(say()) # Can you buy me a beer?
+print(say()) # Can you buy me a beer?
print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
```
@@ -714,6 +781,10 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
* [Python Course](http://www.python-course.eu/index.php)
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
+* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
+* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/)
+* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/)
### Dead Tree
diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown
new file mode 100644
index 00000000..0b02dca8
--- /dev/null
+++ b/pythonstatcomp.html.markdown
@@ -0,0 +1,244 @@
+---
+language: 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,
+ matplotlib, seaborn, requests.
+ Make sure to do this tutorial in the IPython notebook so that you get
+ the inline plots and easy documentation lookup.
+"""
+
+# 1. Data acquisition ====
+
+""" One reason people choose Python over R is that they intend to interact a lot
+ with the web, either by scraping pages directly or requesting data through
+ an API. You can do those things in R, but in the context of a project
+ already using Python, there's a benefit to sticking with one language.
+"""
+
+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
+# save the page source in a file:
+os.getcwd() # check what's the working directory
+f = open("learnxinyminutes.html", "wb")
+f.write(r.text.encode("UTF-8"))
+f.close()
+
+# downloading a csv
+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.write(r.text.encode("UTF-8"))
+f.close()
+
+""" for more on the requests module, including APIs, see
+ http://docs.python-requests.org/en/latest/user/quickstart/
+"""
+
+# 2. Reading a CSV file ====
+
+""" Wes McKinney's pandas package gives you 'DataFrame' objects in Python. If
+ you've used R, you will be familiar with the idea of the "data.frame" already.
+"""
+
+import pandas as pd
+import numpy as np
+import scipy as sp
+pets = pd.read_csv(fn)
+pets
+# name age weight species
+# 0 fluffy 3 14 cat
+# 1 vesuvius 6 23 fish
+# 2 rex 5 34 dog
+
+""" R users: note that Python, like most normal programming languages, starts
+ indexing from 0. R is the unusual one for starting from 1.
+"""
+
+# two different ways to print out a column
+pets.age
+pets["age"]
+
+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
+
+# 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
+
+""" If you are doing some serious linear algebra and number-crunching, you may
+ just want arrays, not DataFrames. DataFrames are ideal for combining columns
+ of different types.
+"""
+
+# 3. Charts ====
+
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+%matplotlib inline
+
+# To do data vizualization in Python, use matplotlib
+
+plt.hist(pets.age);
+
+plt.boxplot(pets.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");
+
+# there are also some seaborn-specific plotting functions
+# notice how seaborn automatically labels the x-axis on this barplot
+sns.barplot(pets["age"])
+
+# R veterans can still use ggplot
+from ggplot import *
+ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets")
+# source: https://pypi.python.org/pypi/ggplot
+
+# there's even a d3.js port: https://github.com/mikedewar/d3py
+
+# 4. Simple data cleaning and exploratory analysis ====
+
+""" Here's a more complicated example that demonstrates a basic data
+ cleaning workflow leading to the creation of some exploratory plots
+ and the running of a linear regression.
+ The data set was transcribed from Wikipedia by hand. It contains
+ all the Holy Roman Emperors and the important milestones in their lives
+ (birth, death, coronation, etc.).
+ The goal of the analysis will be to explore whether a relationship
+ exists between emperor birth year and emperor lifespan.
+ data source: https://en.wikipedia.org/wiki/Holy_Roman_Emperor
+"""
+
+# load some data on Holy Roman Emperors
+url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv"
+r = requests.get(url)
+fp = "hre.csv"
+with open(fp, "wb") as f:
+ f.write(r.text.encode("UTF-8"))
+
+hre = pd.read_csv(fp)
+
+hre.head()
+"""
+ Ix Dynasty Name Birth Death 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
+
+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
+ finally converts the type of the Series object from string to integer. For
+ more information into what different parts of the code do, see:
+ - https://docs.python.org/2/howto/regex.html
+ - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list
+ - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html
+"""
+
+def extractYear(v):
+ return(pd.Series(reduce(lambda x, y: x + y, map(rx.findall, v), [])).astype(int))
+
+hre["BirthY"] = extractYear(hre.Birth)
+hre["DeathY"] = extractYear(hre.Death)
+
+# make a column telling estimated age
+hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int)
+
+# simple scatterplot, no trend line, color represents dynasty
+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)
+# code source: http://wiki.scipy.org/Cookbook/LinearRegression
+
+# check the slope
+slope # 0.0057672618839073328
+
+# check the R^2 value:
+rval**2 # 0.020363950027333586
+
+# check the p-value
+pval # 0.34971812581498452
+
+# use seaborn to make a scatterplot and plot the linear regression trend line
+sns.lmplot("BirthY", "EstAge", data=hre);
+
+""" For more information on seaborn, see
+ - http://web.stanford.edu/~mwaskom/software/seaborn/
+ - https://github.com/mwaskom/seaborn
+ For more information on SciPy, see
+ - http://wiki.scipy.org/SciPy
+ - http://wiki.scipy.org/Cookbook/
+ 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.
+
+You can also find plenty of interactive IPython tutorials on subjects specific to your interests, like Cam Davidson-Pilon's <a href="http://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/" Title="Probabilistic Programming and Bayesian Methods for Hackers">Probabilistic Programming and Bayesian Methods for Hackers</a>.
+
+Some more modules to research:
+ - text analysis and natural language processing: nltk, http://www.nltk.org
+ - social network analysis: igraph, http://igraph.org/python/
diff --git a/r.html.markdown b/r.html.markdown
index 93751df5..8539b10e 100644
--- a/r.html.markdown
+++ b/r.html.markdown
@@ -3,6 +3,7 @@ language: R
contributors:
- ["e99n09", "http://github.com/e99n09"]
- ["isomorphismes", "http://twitter.com/isomorphisms"]
+ - ["kalinn", "http://github.com/kalinn"]
filename: learnr.r
---
@@ -15,7 +16,8 @@ R is a statistical computing language. It has lots of libraries for uploading an
# You can't make multi-line comments,
# but you can stack multiple comments like so.
-# in Windows or Mac, hit COMMAND-ENTER to execute a line
+# in Windows you can use CTRL-ENTER to execute a line.
+# on Mac it is COMMAND-ENTER
@@ -196,6 +198,14 @@ class(NaN) # "numeric"
# You can do arithmetic on two vectors with length greater than 1,
# so long as the larger vector's length is an integer multiple of the smaller
c(1,2,3) + c(1,2,3) # 2 4 6
+# Since a single number is a vector of length one, scalars are applied
+# elementwise to vectors
+(4 * c(1,2,3) - 2) / 2 # 1 3 5
+# Except for scalars, use caution when performing arithmetic on vectors with
+# different lengths. Although it can be done,
+c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6
+# Matching lengths is better practice and easier to read
+c(1,2,3,1,2,3) * c(1,2,1,2,1,2)
# CHARACTERS
# There's no difference between strings and characters in R
@@ -234,6 +244,9 @@ class(NA) # "logical"
TRUE | FALSE # TRUE
# AND
TRUE & FALSE # FALSE
+# Applying | and & to vectors returns elementwise logic operations
+c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE
+c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE
# You can test if x is TRUE
isTRUE(TRUE) # TRUE
# Here we get a logical vector with many elements:
@@ -664,15 +677,101 @@ write.csv(pets, "pets2.csv") # to make a new .csv file
#########################
+# Statistical Analysis
+#########################
+
+# Linear regression!
+linearModel <- lm(price ~ time, data = list1)
+linearModel # outputs result of regression
+# =>
+# Call:
+# lm(formula = price ~ time, data = list1)
+#
+# Coefficients:
+# (Intercept) time
+# 0.1453 0.4943
+summary(linearModel) # more verbose output from the regression
+# =>
+# Call:
+# lm(formula = price ~ time, data = list1)
+#
+# Residuals:
+# Min 1Q Median 3Q Max
+# -8.3134 -3.0131 -0.3606 2.8016 10.3992
+#
+# Coefficients:
+# Estimate Std. Error t value Pr(>|t|)
+# (Intercept) 0.14527 1.50084 0.097 0.923
+# time 0.49435 0.06379 7.749 2.44e-09 ***
+# ---
+# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
+#
+# Residual standard error: 4.657 on 38 degrees of freedom
+# Multiple R-squared: 0.6124, Adjusted R-squared: 0.6022
+# F-statistic: 60.05 on 1 and 38 DF, p-value: 2.44e-09
+coef(linearModel) # extract estimated parameters
+# =>
+# (Intercept) time
+# 0.1452662 0.4943490
+summary(linearModel)$coefficients # another way to extract results
+# =>
+# Estimate Std. Error t value Pr(>|t|)
+# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01
+# time 0.4943490 0.06379348 7.74920901 2.440008e-09
+summary(linearModel)$coefficients[,4] # the p-values
+# =>
+# (Intercept) time
+# 9.234021e-01 2.440008e-09
+
+# GENERAL LINEAR MODELS
+# Logistic regression
+set.seed(1)
+list1$success = rbinom(length(list1$time), 1, .5) # random binary
+glModel <- glm(success ~ time, data = list1,
+ family=binomial(link="logit"))
+glModel # outputs result of logistic regression
+# =>
+# Call: glm(formula = success ~ time,
+# family = binomial(link = "logit"), data = list1)
+#
+# Coefficients:
+# (Intercept) time
+# 0.17018 -0.01321
+#
+# Degrees of Freedom: 39 Total (i.e. Null); 38 Residual
+# Null Deviance: 55.35
+# Residual Deviance: 55.12 AIC: 59.12
+summary(glModel) # more verbose output from the regression
+# =>
+# Call:
+# glm(formula = success ~ time,
+# family = binomial(link = "logit"), data = list1)
+
+# Deviance Residuals:
+# Min 1Q Median 3Q Max
+# -1.245 -1.118 -1.035 1.202 1.327
+#
+# Coefficients:
+# Estimate Std. Error z value Pr(>|z|)
+# (Intercept) 0.17018 0.64621 0.263 0.792
+# time -0.01321 0.02757 -0.479 0.632
+#
+# (Dispersion parameter for binomial family taken to be 1)
+#
+# Null deviance: 55.352 on 39 degrees of freedom
+# Residual deviance: 55.121 on 38 degrees of freedom
+# AIC: 59.121
+#
+# Number of Fisher Scoring iterations: 3
+
+
+#########################
# Plots
#########################
# BUILT-IN PLOTTING FUNCTIONS
# Scatterplots!
plot(list1$time, list1$price, main = "fake data")
-# Regressions!
-linearModel <- lm(price ~ time, data = list1)
-linearModel # outputs result of regression
# Plot regression line on existing plot
abline(linearModel, col = "red")
# Get a variety of nice diagnostics
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/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/ru-ru/.directory b/ru-ru/.directory
new file mode 100644
index 00000000..4d20336b
--- /dev/null
+++ b/ru-ru/.directory
@@ -0,0 +1,4 @@
+[Dolphin]
+SortRole=size
+Timestamp=2015,10,31,18,6,13
+Version=3
diff --git a/ru-ru/bash-ru.html.markdown b/ru-ru/bash-ru.html.markdown
index 21377b6c..5e99afc2 100644
--- a/ru-ru/bash-ru.html.markdown
+++ b/ru-ru/bash-ru.html.markdown
@@ -95,6 +95,15 @@ else
echo "Имя совпадает с именем пользователя"
fi
+# Примечание: если $Name пустой, bash интерпретирует код как:
+if [ -ne $USER ]
+# а это ошибочная команда
+# поэтому такие переменные нужно использовать так:
+if [ "$Name" -ne $USER ] ...
+# когда $Name пустой, bash видит код как:
+if [ "" -ne $USER ] ...
+# что работает правильно
+
# Также есть условное исполнение
echo "Исполнится всегда" || echo "Исполнится, если первая команда завершится ошибкой"
echo "Исполнится всегда" && echo "Исполнится, если первая команда выполнится удачно"
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/clojure-ru.html.markdown b/ru-ru/clojure-ru.html.markdown
index 2f508a00..451da312 100644
--- a/ru-ru/clojure-ru.html.markdown
+++ b/ru-ru/clojure-ru.html.markdown
@@ -144,7 +144,7 @@ Clojure, это представитель семейства Lisp-подобн
;;;;;;;;;;;;;;;;;;;;;
; Функция создается специальной формой fn.
-; "Тело"" функции может состоять из нескольких форм,
+; "Тело" функции может состоять из нескольких форм,
; но результатом вызова функции всегда будет результат вычисления
; последней из них.
(fn [] "Hello World") ; => fn
diff --git a/ru-ru/css-ru.html.markdown b/ru-ru/css-ru.html.markdown
new file mode 100644
index 00000000..2e2d40b7
--- /dev/null
+++ b/ru-ru/css-ru.html.markdown
@@ -0,0 +1,250 @@
+---
+language: css
+contributors:
+ - ["Mohammad Valipour", "https://github.com/mvalipour"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["Geoffrey Liu", "https://github.com/g-liu"]
+filename: learncss-ru.css
+lang: ru-ru
+---
+
+В свои ранние дни веб состоял в основном из чистого текста. С развитием браузеров
+веб-страницы с графическими элементами стали обычным делом.
+CSS - язык, разграничивающий содержимое (HTML) и внешний вид веб-страниц.
+
+Если коротко, то CSS предоставляет синтаксис, позволяющий выбирать различные
+HTML элементы и определять их внешний вид.
+
+Как и у других языков, у CSS много версий. Мы описываем CSS2.0 - не самую новую,
+но самую поддерживаемую и распространенную версию.
+
+**ВАЖНО:** Так как результатом применения CSS является изменение внешнего вида
+элементов, постарайтесь использовать CSS-песочницы при изучении языка.
+Например [dabblet](http://dabblet.com/).
+В данной статье рассматриваются в первую очередь синтаксис и общие рекомендации.
+
+
+```css
+/* Для комментариев используется слеш-астериск, как на этой строчке.
+ В CSS нет однострочных комментариев; все комментарии записываются таким способом */
+
+/* ####################
+ ## СЕЛЕКТОРЫ
+ #################### */
+
+/* Выражения в CSS очень просты */
+селектор { атрибут: значение; /* другие атрибуты...*/ }
+
+/* селекторы используются для выбора элементов на странице
+
+Чтобы выбрать все элементы, используйте астериск: */
+* { color:red; }
+
+/*
+Если на странице присутствует такой элемент:
+
+<div class='some-class class2' id='someId' attr='value' otherAttr='en-us foo bar' />
+*/
+
+/* его можно выбрать по одному классу */
+.some-class { }
+
+/* или по обоим классам */
+.some-class.class2 { }
+
+/* по названию тега */
+div { }
+
+/* по идентификатору */
+#someId { }
+
+/* по имеющемуся атрибуту */
+[attr] { font-size:smaller; }
+
+/* или по атрибуту с определенным значением */
+[attr='value'] { font-size:smaller; }
+
+/* можно выбрать атрибуты, начинающиеся с определенного значения (CSS3) */
+[attr^='val'] { font-size:smaller; }
+
+/* или заканчивающиеся определенным значением (CSS3) */
+[attr$='ue'] { font-size:smaller; }
+
+/* содержащие отделенное пробелами значение в названии атрибута (CSS3) */
+[otherAttr~='foo'] { font-size:smaller; }
+
+/* можно выбрать атрибут как с точным, так и со стоящим после значения “-” (U+002D) */
+[otherAttr|='en'] { font-size:smaller; }
+
+
+/* Более того, все это можно использовать вместе - между разными частями
+не должно быть пробелов, иначе селектор будет иметь совершенно иное значение */
+div.some-class[attr$='ue'] { }
+
+/* Вы можете выбрать элемент по его родителю */
+
+/* прямой потомок другого элемента (выбранного с помощью селектора) */
+div.some-parent > .class-name {}
+
+/* потомок любого родителя в дереве элементов
+ следующая строка означает: "любой элемент класса "class-name",
+ являющийся потомком div-элемента класса "some-parent"
+ НЕЗАВИСИМО ОТ УРОВНЯ ВЛОЖЕННОСТИ" */
+div.some-parent .class-name {}
+
+/* важно: этот же селектор без пробелов имеет иное значение
+ можете догадаться, какое? */
+div.some-parent.class-name {}
+
+/* вы можете выбрать элемент по первому предшествующему
+ родственному элементу */
+.i-am-before + .this-element { }
+
+/* или любому предшествующему родственнику перед элементом */
+.i-am-any-before ~ .this-element {}
+
+
+/* Существуют псевдо-классы, позволяющие изменять внешний вид элемента
+ в зависимости от событий, произошедших с элементом */
+
+/* например, когда курсор наведен на элемент */
+element:hover {}
+
+/* когда пользователь проходил по ссылке ранее */
+element:visited {}
+
+/* или еще не проходил по ней */
+element:link {}
+
+/* выбранное поле воода (input) */
+element:focus {}
+
+
+/* ####################
+ ## АТРИБУТЫ
+ #################### */
+
+selector {
+
+ /* Единицы измерения */
+ width: 50%; /* проценты */
+ font-size: 2em; /* умножается на высоту шрифта (2em - в два раза больше) */
+ width: 200px; /* пиксели */
+ font-size: 20pt; /* пункты */
+ width: 5cm; /* сантиметры */
+ min-width: 50mm; /* милиметры */
+ max-width: 5in; /* дюймы */
+ height: 0.2vh; /* умножается на высоту окна браузера (CSS3) */
+ width: 0.4vw; /* умножается на ширину окна браузера (CSS3) */
+ min-height: 0.1vmin; /* наименьшее из vh и vw (CSS3) */
+ max-width: 0.3vmax; /* наибольшее из vh и vw (CSS3) */
+
+ /* Цвета */
+ background-color: #F6E; /* сокращенная запись шестнадцатеричного кода */
+ background-color: #F262E2; /* стандартная запись шестнадцатеричного кода */
+ background-color: tomato; /* название цвета */
+ background-color: rgb(255, 255, 255); /* цветовая модель rgb */
+ background-color: rgb(10%, 20%, 50%); /* цветовая модель rgb в процентах */
+ background-color: rgba(255, 0, 0, 0.3); /* цветовая модель rgb (последний аргумент отвечает за прозрачность цвета) (CSS3) */
+ background-color: transparent; /* прозрачный цвет */
+ background-color: hsl(0, 100%, 50%); /* в формате hsl (CSS3) */
+ background-color: hsla(0, 100%, 50%, 0.3); /* в формате hsl (последний аргумент отвечает за непрозрачность цвета) (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; /* если шрифт не найден,
+ будет использован следующий за ним в списке */
+}
+
+```
+
+## Использование
+
+Сохраните готовый файл с расширением .css
+
+```xml
+<!-- добавьте css файл в тег <head> на странице: -->
+<link rel='stylesheet' type='text/css' href='path/to/style.css' />
+
+<!-- Можно использовать встроенные стили. Рекомендуется избегать подобного подхода. -->
+<body>
+ <style>
+ a { color: purple; }
+ </style>
+</body>
+
+<!-- Можно установить стиль элемента напрямую.
+Используйте этот способ только в случае крайней необходимости. -->
+<div style="border: 1px solid red;">
+</div>
+
+```
+
+## Приоритет
+
+Как вы заметили, внешний вид элемента может определяться несколькими селекторами,
+а значение атрибута элемента может быть установлено больше одного раза.
+В подобных случаях одно из значений оказывается приоритетнее остальных.
+
+Если взять следующую таблицу стилей:
+
+```css
+/*A*/
+p.class1[attr='value']
+
+/*B*/
+p.class1 {}
+
+/*C*/
+p.class2 {}
+
+/*D*/
+p {}
+
+/*E*/
+p { property: value !important; }
+
+```
+
+и следующую разметку:
+
+```xml
+<p style='/*F*/ property:value;' class='class1 class2' attr='value'>
+</p>
+```
+
+Приоритет стилей будет таким:
+Помните: приоритет выставляется для **атрибута**, а не для всего блока стилей.
+
+* `E` имеет наивысший приоритет благодаря ключевому слову `!important`.
+ Используйте только в случае крайней необходимости.
+* `F` идет следующим, так как является встроенным стилем.
+* `A` следующий, как самый конкретизированный.
+ конкретизированный == большее количество определителей.
+ В этом примере 3 определителя: 1 тег `p` +
+ название класса `class1` + 1 атрибут `attr='value'`
+* `C` следующий. Несмотря на одинаковое с `B` количество определителей,
+ `C` определен позже.
+* Затем `B`
+* И последний `D`.
+
+## Совместимость
+
+Несмотря на то, что большая часть функций CSS2 (а также CSS3) подеррживается всеми
+браузерами и устройствами, не забывайте проверять совместимость CSS-правил
+с современными браузерами.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) замечательно подходит для этого.
+
+To run a quick compatibility check, [CanIUse](http://caniuse.com) is a great resource.
+
+## Ресурсы для самостоятельного изучения
+
+* [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/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/erlang-ru.html.markdown b/ru-ru/erlang-ru.html.markdown
index 99ea79ee..69f81800 100644
--- a/ru-ru/erlang-ru.html.markdown
+++ b/ru-ru/erlang-ru.html.markdown
@@ -18,7 +18,7 @@ lang: ru-ru
% Пунктуационные знаки, используемые в Erlang:
% Запятая (`,`) разделяет аргументы в вызовах функций, структурах данных и
% образцах.
-% Точка (`.`) (с пробелом после них) разделяет функции и выражения в
+% Точка (`.`) (с пробелом после неё) разделяет функции и выражения в
% оболочке.
% Точка с запятой (`;`) разделяет выражения в следующих контекстах:
% формулы функций, выражения `case`, `if`, `try..catch` и `receive`.
diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown
index 005495cc..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 {
@@ -451,7 +475,7 @@ public class Fruit implements Edible, Digestible {
}
}
-// В Java Вы можете наследоватьтолько один класс, однако можете реализовывать
+// В Java Вы можете наследовать только один класс, однако можете реализовывать
// несколько интерфейсов. Например:
public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo {
public void InterfaceOneMethod() {
diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown
index 8655ae4a..54499f46 100644
--- a/ru-ru/javascript-ru.html.markdown
+++ b/ru-ru/javascript-ru.html.markdown
@@ -330,7 +330,7 @@ function sayHelloInFiveSeconds(name) {
sayHelloInFiveSeconds("Адам"); // Через 5 с откроется окно «Привет, Адам!»
///////////////////////////////////
-// 5. Подробнее об объектах; конструкторы и прототипы
+// 5. Подробнее об объектах; Конструкторы и Прототипы
// Объекты могут содержать в себе функции.
var myObj = {
diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown
index eb8e4881..c41e9676 100644
--- a/ru-ru/markdown-ru.html.markdown
+++ b/ru-ru/markdown-ru.html.markdown
@@ -61,7 +61,7 @@ __И этот тоже.__
**_И тут!_**
*__И даже здесь!__*
-<!-- В Github Flavored Markdown (версии Markdown, использующейся в Github,
+<!-- В GitHub Flavored Markdown (версии Markdown, использующейся в GitHub,
для рендеринга Markdown-документов) текст можно сделать зачёркнутым: -->
~~Зачёркнутый текст.~~
@@ -157,7 +157,7 @@ __И этот тоже.__
Например, можно выделить имя функции `go_to()` прямо посреди текста.
-<!-- Github Flavored Markdown позволяет указать для блока кода синтаксис оного.
+<!-- GitHub Flavored Markdown позволяет указать для блока кода синтаксис оного.
В этом случае синтаксис внутри блока будет подсвечен. Пример: -->
\`\`\`ruby <!-- Только нужно будет убрать символы "\", оставив лишь "```ruby" -->
@@ -167,7 +167,7 @@ end
\`\`\` <!-- И здесь тоже backslashes нужно убрать, т.е. оставить "```" -->
<-- Обратите внимание: фрагмент, указанный выше, не предваряется отступами,
-поскольку Github сам в состоянии определить границы блока - по строкам "```" -->
+поскольку GitHub сам в состоянии определить границы блока - по строкам "```" -->
<!-- Горизонтальный разделитель (<hr />) -->
<!-- Разделители добавляются вставкой строки из трёх и более
@@ -253,7 +253,7 @@ end
\*текст, заключённый в звёздочки!\*
<!-- Таблицы -->
-<!-- Таблицы официально поддерживаются только в Github Flavored Markdown,
+<!-- Таблицы официально поддерживаются только в GitHub Flavored Markdown,
да и синтаксис имеют не слишком удобный.
Но если очень нужно, размечайте таблицы так: -->
diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown
index ddff2e5c..d60db1d8 100644
--- a/ru-ru/objective-c-ru.html.markdown
+++ b/ru-ru/objective-c-ru.html.markdown
@@ -17,7 +17,7 @@ Cocoa Touch.
Он является объектно-ориентированным языком программирования общего назначения,
который добавляет обмен сообщениями в Smalltalk-стиле к языку программирования C.
-```objective_c
+```objective-c
// Однострочные комментарии начинаются с //
/*
@@ -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/perl-ru.html.markdown b/ru-ru/perl-ru.html.markdown
new file mode 100644
index 00000000..a907ba41
--- /dev/null
+++ b/ru-ru/perl-ru.html.markdown
@@ -0,0 +1,195 @@
+---
+category: language
+language: perl
+filename: learnperl-ru.pl
+contributors:
+ - ["Korjavin Ivan", "http://github.com/korjavin"]
+translators:
+ - ["Elena Bolshakova", "http://github.com/liruoko"]
+lang: ru-ru
+---
+
+Perl 5 -- высокоуровневый мощный язык с 25-летней историей.
+Особенно хорош для обработки разнообразных текстовых данных.
+
+Perl 5 работает более чем на 100 платформах, от портативных устройств
+до мейнфреймов, и подходит как для быстрого прототипирования,
+так и для крупных проектов.
+
+```perl
+# Комментарии начинаются с символа решетки.
+
+
+#### Типы переменных в Perl
+
+# Скалярные переменные начинаются с знака доллара $.
+# Имя переменной состоит из букв, цифр и знаков подчеркивания,
+# начиная с буквы или подчеркивания.
+
+### В Perl три основных типа переменных: скаляры, массивы, хеши.
+
+## Скаляры
+# Скаляр хранит отдельное значение:
+my $animal = "camel";
+my $answer = 42;
+
+# Скаляры могут быть строками, целыми и вещественными числами.
+# Когда требуется, Perl автоматически выполняет преобразования к нужному типу.
+
+## Массивы
+# Массив хранит список значений:
+my @animals = ("camel", "llama", "owl");
+my @numbers = (23, 42, 69);
+my @mixed = ("camel", 42, 1.23);
+
+
+## Хеши
+# Хеш хранит набор пар ключ/значение:
+
+my %fruit_color = ("apple", "red", "banana", "yellow");
+
+# Можно использовать оператор "=>" для большей наглядности:
+
+my %fruit_color = (
+ apple => "red",
+ banana => "yellow",
+ );
+
+# Важно: вставка и поиск в хеше выполняются за константное время,
+# независимо от его размера.
+
+# Скаляры, массивы и хеши подробно описаны в разделе perldata
+# (perldoc perldata).
+
+# Более сложные структуры данных можно получить, если использовать ссылки.
+# С помощью ссылок можно получить массив массивов хешей, в которых хранятся другие хеши.
+
+#### Условные операторы и циклы
+
+# В Perl есть большинсво привычных условных и циклических конструкций.
+
+if ( $var ) {
+ ...
+} elsif ( $var eq 'bar' ) {
+ ...
+} else {
+ ...
+}
+
+unless ( condition ) {
+ ...
+ }
+# Это более читаемый вариант для "if (!condition)"
+
+# Специфические Perl-овые пост-условия:
+print "Yow!" if $zippy;
+print "We have no bananas" unless $bananas;
+
+# while
+ while ( condition ) {
+ ...
+ }
+
+
+# for, foreach
+for ($i = 0; $i <= $max; $i++) {
+ ...
+ }
+
+foreach (@array) {
+ print "This element is $_\n";
+ }
+
+for my $el (@array) {
+ print "This element is $el\n";
+ }
+
+#### Регулярные выражения
+
+# Регулярные выражения занимают важное место в Perl-е,
+# и подробно описаны в разделах документации perlrequick, perlretut и других.
+# Вкратце:
+
+# Сопоставление с образцом
+if (/foo/) { ... } # выполняется, если $_ содержит "foo"
+if ($a =~ /foo/) { ... } # выполняется, если $a содержит "foo"
+
+# Простые замены
+
+$a =~ s/foo/bar/; # заменяет foo на bar в строке $a
+$a =~ s/foo/bar/g; # заменяет ВСЕ ВХОЖДЕНИЯ foo на bar в строке $a
+
+
+#### Файлы и ввод-вывод
+
+# Открыть файл на чтение или запись можно с помощью функции "open()".
+
+open(my $in, "<", "input.txt") or die "Can't open input.txt: $!";
+open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
+open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
+
+# Читать из файлового дескриптора можно с помощью оператора "<>".
+# В скалярном контексте он читает одну строку из файла, в списковом --
+# читает сразу весь файл, сохраняя по одной строке в элементе массива:
+
+my $line = <$in>;
+my @lines = <$in>;
+
+#### Подпрограммы (функции)
+
+# Объявить функцию просто:
+
+sub logger {
+ my $logmessage = shift;
+ open my $logfile, ">>", "my.log" or die "Could not open my.log: $!";
+ print $logfile $logmessage;
+}
+
+# Теперь можно использовать эту функцию так же, как и встроенные:
+
+logger("We have a logger subroutine!");
+```
+
+#### Perl-модули
+
+Perl-овые модули предоставляют широкий набор функциональности,
+так что вы можете не изобретать заново велосипеды, а просто скачать
+нужный модуль с CPAN (http://www.cpan.org/).
+Некоторое количество самых полезных модулей включено в стандартную
+поставку Perl.
+
+Раздел документации perlfaq содержит вопросы и ответы о многих частых
+задачах, и часто предлагает подходящие CPAN-модули.
+
+
+#### Unicode
+
+Вам наверняка понадобится работать с не-ASCII текстами.
+Добавьте эти прагмы в начало скрипта:
+
+```perl
+use utf8;
+use open ':std' => ':utf8';
+```
+
+Подробнее читайте в perldoc, разделы perlunicode и open.
+
+
+#### strict, warnings
+
+Прагмы strict и warnings включают полезные проверки во время компиляции:
+
+```perl
+use strict;
+use warnings;
+```
+
+Подробнее смотрите perldoc strict и perldoc warnings.
+
+
+#### Смотрите также
+
+ - [perl-tutorial](http://perl-tutorial.org/)
+ - [обучающий раздел на www.perl.com](http://www.perl.org/learn.html)
+ - [perldoc в вебе](http://perldoc.perl.org/)
+ - встроенная справка : `perldoc perlintro`
diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown
index 53b2f916..d17f24fc 100644
--- a/ru-ru/php-ru.html.markdown
+++ b/ru-ru/php-ru.html.markdown
@@ -5,6 +5,7 @@ contributors:
- ["Trismegiste", "https://github.com/Trismegiste"]
translators:
- ["SlaF", "https://github.com/SlaF"]
+ - ["Corpsee", "https://github.com/corpsee"]
lang: ru-ru
filename: learnphp-ru.php
---
@@ -14,8 +15,8 @@ filename: learnphp-ru.php
```php
<?php // PHP код должен быть заключен в теги <?php
-// Если ваш файл содержит только PHP код, то можно
-// пропустить закрывающийся ?>
+// Если ваш файл содержит только PHP-код, то можно
+пропустить закрывающий ?>
// А так начинаются комментарии
@@ -30,10 +31,10 @@ filename: learnphp-ru.php
print('Hello '); // Напечатать "Hello " без перевода строки
// () необязательно применять для print и echo
-echo "World\n"; // Печатать "World" и перейти на новую строку.
-// (все утверждения должны заканчиваться ;)
+echo "World\n"; // Напечатать "World" и перейти на новую строку.
+// (все утверждения должны заканчиваться точкой с запятой)
-// Любые символы за пределами закрывающегося тега выводятся автоматически:
+// Любые символы за пределами закрывающего тега выводятся автоматически:
?>
Hello World Again!
<?php
@@ -44,9 +45,9 @@ Hello World Again!
*/
// Переменные начинаются с символа $.
-// Правильное имя переменной начинается с буквы или знака подчеркивания,
-// и может содержать любые цифры, буквы, или знаки подчеркивания.
-// Не рекомендуется использовать кирилические символы в именах (прим. пер.)
+// Правильное имя переменной начинается с буквы или символа подчеркивания,
+// за которым следует любое количество букв, цифр или символов подчеркивания.
+// Не рекомендуется использовать кириллические символы в именах (прим. пер.)
// Логические значения нечувствительны к регистру
$boolean = true; // или TRUE или True
@@ -54,9 +55,9 @@ $boolean = false; // или FALSE или False
// Целые числа
$int1 = 12; // => 12
-$int2 = -12; // => -12-
+$int2 = -12; // => -12
$int3 = 012; // => 10 (ведущий 0 обозначает восьмеричное число)
-$int4 = 0x0F; // => 15 (ведущие символы 0x означает шестнадцатеричное число)
+$int4 = 0x0F; // => 15 (ведущие символы 0x означают шестнадцатеричное число)
// Дробные числа
$float = 1.234;
@@ -86,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 может использоваться для
@@ -105,6 +106,9 @@ END;
// Строки соединяются при помощи .
echo 'This string ' . 'is concatenated';
+// echo можно передавать строки как параметры
+echo 'Multiple', 'Parameters', 'Valid'; // печатает 'MultipleParametersValid'
+
/********************************
* Константы
@@ -113,20 +117,21 @@ 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.
// Работает во всех версиях РHP
$associative = array('One' => 1, 'Two' => 2, 'Three' => 3);
@@ -188,7 +193,7 @@ $b = '0';
$c = '1';
$d = '1';
-// Утверждение (assert) выдает предупреждение если аргумент не true
+// Утверждение (assert) выдает предупреждение, если его аргумент не true
// Эти сравнения всегда будут истинными, даже если типы будут различаться
assert($a == $b); // "равно"
@@ -199,13 +204,13 @@ assert($c > $b); // больше
assert($a <= $b); // меньше или равно
assert($c >= $d); // больше или равно
-// Следующие утверждения истинны если переменные имеют одинаковый тип.
+// Следующие утверждения истинны, если переменные имеют одинаковый тип.
assert($c === $d);
assert($a !== $d);
assert(1 == '1');
assert(1 !== '1');
-// Переменные могут изменять тип, в зависимости от их использования.
+// Переменные могут изменять тип в зависимости от их использования.
$integer = 1;
echo $integer + $integer; // => 2
@@ -235,7 +240,7 @@ $var = null; // Null
$integer = 10;
$boolen = settype($integer, "string") // теперь $integer имеет строковый тип
-// settype возвращает true - если преобразование удалось и false в противном случае
+// settype возвращает true, если преобразование удалось и false в противном случае
/********************************
* Управляющие структуры
@@ -283,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;
-} // Prints "0123456789"
+} // печатает "0123456789"
echo "\n";
@@ -320,7 +325,7 @@ $wheels = ['bicycle' => 2, 'car' => 4];
// Циклы foreach могут обходить массивы
foreach ($wheels as $wheel_count) {
echo $wheel_count;
-} // Prints "24"
+} // Напечатает "24"
echo "\n";
@@ -334,17 +339,17 @@ echo "\n";
$i = 0;
while ($i < 5) {
if ($i === 3) {
- break; // Exit out of the while loop
+ break; // выйти из цикла while
}
echo $i++;
-} // Prints "012"
+} // Напечатает "012"
for ($i = 0; $i < 5; $i++) {
if ($i === 3) {
- continue; // Skip this iteration of the loop
+ continue; // пропустить текущую итерацию цикла
}
echo $i;
-} // Prints "0124"
+} // печатает "0124"
/********************************
@@ -359,7 +364,7 @@ function my_function () {
echo my_function(); // => "Hello"
// Правильное имя функции начинается с буквы или символа подчеркивания
-// и состоит из букв, цифр или знаков подчеркивания.
+// и состоит из букв, цифр или символов подчеркивания.
function add ($x, $y = 1) { // $y по умолчанию равно 1
$result = $x + $y;
@@ -369,7 +374,7 @@ function add ($x, $y = 1) { // $y по умолчанию равно 1
echo add(4); // => 5
echo add(4, 2); // => 6
-// $result недоступна за пределами функции
+// $result недоступен за пределами функции
// print $result; // Выдает предупреждение
// Начиная с PHP 5.3 вы можете объявлять анонимные функции:
@@ -402,27 +407,25 @@ echo $function_name(1, 2); // => 3
/********************************
- * Includes
+ * Включения
*/
<?php
// PHP код внутри включаемого файла должен начинаться с тега PHP.
include 'my-file.php';
-// Код в файле my-file.php теперь доступен в текущем в текущем пространстве имен.
-// Если файл не удалось включить, будет выдано предупреждение.
+// Код в файле my-file.php теперь доступен в текущем пространстве имен.
+// Если файл не удалось подключить, то будет выдано предупреждение.
include_once 'my-file.php';
-// Если код в файле my-file.php уже был включен, он не будет включен повторно.
-// Это предотвращает ошибку повторного включения файла.
+// Если код в файле my-file.php уже был подключен, он не будет подключен повторно.
+// Это предотвращает ошибку повторного подключения файла.
require 'my-file.php';
require_once 'my-file.php';
-// Same as include(), except require() will cause a fatal error if the
-// file cannot be included.
// Действует также как и include(), но если файл не удалось подключить,
-// функция выдает неисправимую ошибку
+// функция выдает фатальную ошибку
// Содержимое файла my-include.php:
<?php
@@ -452,19 +455,19 @@ class MyClass
static $staticVar = 'static';
- // Properties must declare their visibility
+ // Свойства объявляются с указанием их видимости
public $property = 'public';
public $instanceProp;
- protected $prot = 'protected'; // Accessible from the class and subclasses
- private $priv = 'private'; // Accessible within the class only
+ protected $prot = 'protected'; // Свойство доступно только потомкам и самому классу
+ private $priv = 'private'; // Свойство доступно только самому классу
- // Create a constructor with __construct
+ // Конструктор описывается с помощью __construct
public function __construct($instanceProp) {
- // Access instance variables with $this
+ // Доступ к эземпляру класса с помощью $this
$this->instanceProp = $instanceProp;
}
- // Methods are declared as functions inside a class
+ // Методы объявляются как функции принадлежащие классу
public function myMethod()
{
print 'MyClass';
@@ -484,7 +487,7 @@ echo MyClass::MY_CONST; // Выведет 'value';
echo MyClass::$staticVar; // Выведет 'static';
MyClass::myStaticMethod(); // Выведет 'I am static';
-// Новый экземпляр класса используя new
+// Создание нового экземпляра класса используя new
$my_class = new MyClass('An instance property');
// Если аргументы отсутствуют, можно не ставить круглые скобки
@@ -502,7 +505,7 @@ class MyOtherClass extends MyClass
echo $this->prot;
}
- // Override a method
+ // Переопределение родительского метода
function myMethod()
{
parent::myMethod();
@@ -595,7 +598,7 @@ class SomeOtherClass implements InterfaceOne, InterfaceTwo
* Трейты
*/
-// Трейты появились в PHP 5.4.0 и объявляются при помощи ключевого слова trait
+// Трейты появились в PHP 5.4 и объявляются при помощи ключевого слова trait
trait MyTrait
{
@@ -611,7 +614,7 @@ class MyTraitfulClass
}
$cls = new MyTraitfulClass();
-$cls->myTraitMethod(); // Prints "I have MyTrait"
+$cls->myTraitMethod(); // Напечатает "I have MyTrait"
/********************************
@@ -657,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/python-ru.html.markdown b/ru-ru/python-ru.html.markdown
index a0e2b474..43142eff 100644
--- a/ru-ru/python-ru.html.markdown
+++ b/ru-ru/python-ru.html.markdown
@@ -167,6 +167,10 @@ li = []
# Можно сразу начать с заполненного списка
other_li = [4, 5, 6]
+# строка разделена в список
+a="adambard"
+list(a) #=> ['a','d','a','m','b','a','r','d']
+
# Объекты добавляются в конец списка методом append
li.append(1) # [1]
li.append(2) # [1, 2]
@@ -238,7 +242,6 @@ d, e, f = 4, 5, 6
# Обратите внимание, как легко поменять местами значения двух переменных
e, d = d, e # теперь d == 5, а e == 4
-
# Словари содержат ассоциативные массивы
empty_dict = {}
# Вот так описывается предзаполненный словарь
@@ -277,7 +280,7 @@ filled_dict.get("four", 4) #=> 4
# Присваивайте значение ключам так же, как и в списках
filled_dict["four"] = 4 # теперь filled_dict["four"] => 4
-# Метод setdefault вставляет() пару ключ-значение, только если такого ключа нет
+# Метод setdefault() вставляет пару ключ-значение, только если такого ключа нет
filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5
filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5
diff --git a/ru-ru/python3-ru.html.markdown b/ru-ru/python3-ru.html.markdown
index 2a7b3f7b..2b6b59a7 100644
--- a/ru-ru/python3-ru.html.markdown
+++ b/ru-ru/python3-ru.html.markdown
@@ -549,7 +549,7 @@ Human.grunt() #=> "*grunt*"
# Вы можете импортировать модули
import math
-print(math.sqrt(16)) #=> 4
+print(math.sqrt(16)) #=> 4.0
# Вы можете импортировать отдельные функции модуля
from math import ceil, floor
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 8f23b2e6..adf5ce81 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -12,7 +12,9 @@ contributors:
- ["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"]
---
```ruby
@@ -39,6 +41,12 @@ You shouldn't either
10 * 2 #=> 20
35 / 5 #=> 7
2**5 #=> 32
+5 % 3 #=> 2
+
+# Bitwise operators
+3 & 5 #=> 1
+3 | 5 #=> 7
+3 ^ 5 #=> 6
# Arithmetic is just syntactic sugar
# for calling a method on an object
@@ -46,7 +54,7 @@ You shouldn't either
10.* 5 #=> 50
# Special values are objects
-nil # Nothing to see here
+nil # equivalent to null in other languages
true # truth
false # falsehood
@@ -74,6 +82,11 @@ false.class #=> FalseClass
2 <= 2 #=> true
2 >= 2 #=> true
+# Combined comparison operator
+1 <=> 10 #=> -1
+10 <=> 1 #=> 1
+1 <=> 1 #=> 0
+
# Logical operators
true && false #=> false
true || false #=> true
@@ -106,8 +119,20 @@ placeholder = 'use string interpolation'
'hello ' + 3 #=> TypeError: can't convert Fixnum into String
'hello ' + 3.to_s #=> "hello 3"
-# print to the output
+# Combine strings and operators
+'hello ' * 3 #=> "hello hello hello "
+
+# Append to string
+'hello' << ' world' #=> "hello world"
+
+# print to the output with a newline at the end
puts "I'm printing!"
+#=> I'm printing!
+#=> nil
+
+# print to the output without a newline
+print "I'm printing!"
+#=> I'm printing! => nil
# Variables
x = 25 #=> 25
@@ -154,6 +179,7 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
# Arrays can be indexed
# From the front
array[0] #=> 1
+array.first #=> 1
array[12] #=> nil
# Like arithmetic, [var] access
@@ -164,6 +190,7 @@ array.[] 12 #=> nil
# From the end
array[-1] #=> 5
+array.last #=> 5
# With a start index and length
array[2, 3] #=> [3, 4, 5]
@@ -203,8 +230,8 @@ new_hash = { defcon: 3, action: true }
new_hash.keys #=> [:defcon, :action]
# Check existence of keys and values in hash
-new_hash.has_key?(:defcon) #=> true
-new_hash.has_value?(3) #=> true
+new_hash.key?(:defcon) #=> true
+new_hash.value?(3) #=> true
# Tip: Both Arrays and Hashes are Enumerable
# They share a lot of useful methods such as each, map, count, and more
@@ -258,6 +285,12 @@ hash.each do |key, value|
puts "#{key} is #{value}"
end
+# 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"
+end
+
counter = 1
while counter <= 5 do
puts "iteration #{counter}"
@@ -269,6 +302,19 @@ end
#=> iteration 4
#=> iteration 5
+# There are a bunch of other helpful looping functions in Ruby,
+# for example "map", "reduce", "inject", the list goes on. Map,
+# for instance, takes the array it's looping over, does something
+# to it as defined in your block, and returns an entirely new array.
+array = [1,2,3,4,5]
+doubled = array.map do |element|
+ element * 2
+end
+puts doubled
+#=> [2,4,6,8,10]
+puts array
+#=> [1,2,3,4,5]
+
grade = 'B'
case grade
@@ -365,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
@@ -543,7 +611,9 @@ Something.new.qux # => 'qux'
## Additional resources
- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.
+- [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Learn Ruby through a series of interactive tutorials.
- [Official Documentation](http://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/) - 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/rust.html.markdown b/rust.html.markdown
index b2854b0c..d0c56b4a 100644
--- a/rust.html.markdown
+++ b/rust.html.markdown
@@ -287,9 +287,9 @@ fn main() {
// While a value is mutably borrowed, it cannot be accessed at all.
let mut var2 = 4;
let ref_var2: &mut i32 = &mut var2;
- *ref_var2 += 2;
+ *ref_var2 += 2; // '*' is used to point to the mutably borrowed var2
- println!("{}", *ref_var2); // 6
+ println!("{}", *ref_var2); // 6 , //var2 would not compile. //ref_var2 is of type &mut i32, so //stores a reference to an i32 not the value.
// var2 = 2; // this would not compile because `var2` is borrowed
}
```
diff --git a/sass.html.markdown b/sass.html.markdown
new file mode 100644
index 00000000..4d4ece71
--- /dev/null
+++ b/sass.html.markdown
@@ -0,0 +1,444 @@
+---
+language: sass
+filename: learnsass.scss
+contributors:
+ - ["Laura Kyle", "https://github.com/LauraNK"]
+ - ["Sean Corrales", "https://github.com/droidenator"]
+ - ["Kyle Mendes", "https://github.com/pink401k"]
+---
+
+Sass is a CSS extension language that adds features such as variables, nesting, mixins and more.
+Sass (and other preprocessors, such as [Less](http://lesscss.org/)) help developers write maintainable and DRY (Don't Repeat Yourself) code.
+
+Sass has two different syntax options to choose from. SCSS, which has the same syntax as CSS but with the added features of Sass. Or Sass (the original syntax), which uses indentation rather than curly braces and semicolons.
+This tutorial is written using SCSS.
+
+If you're already familiar with CSS3, you'll be able to pick up Sass relatively quickly. It does not provide any new styling properties but rather the tools to write your CSS more efficiently and make maintenance much easier.
+
+```scss
+
+
+//Single line comments are removed when Sass is compiled to CSS.
+
+/* Multi line comments are preserved. */
+
+
+
+/* Variables
+============================== */
+
+
+
+/* You can store a CSS value (such as a color) in a variable.
+Use the '$' symbol to create a variable. */
+
+$primary-color: #A3A4FF;
+$secondary-color: #51527F;
+$body-font: 'Roboto', sans-serif;
+
+/* You can use the variables throughout your stylesheet.
+Now if you want to change a color, you only have to make the change once. */
+
+body {
+ background-color: $primary-color;
+ color: $secondary-color;
+ font-family: $body-font;
+}
+
+/* This would compile to: */
+body {
+ background-color: #A3A4FF;
+ color: #51527F;
+ font-family: 'Roboto', sans-serif;
+}
+
+
+/* This is much more maintainable than having to change the color
+each time it appears throughout your stylesheet. */
+
+
+
+/* Mixins
+============================== */
+
+
+
+/* If you find you are writing the same code for more than one
+element, you might want to store that code in a mixin.
+
+Use the '@mixin' directive, plus a name for your mixin. */
+
+@mixin center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+/* You can use the mixin with '@include' and the mixin name. */
+
+div {
+ @include center;
+ background-color: $primary-color;
+}
+
+/* Which would compile to: */
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #A3A4FF;
+}
+
+
+/* You can use mixins to create a shorthand property. */
+
+@mixin size($width, $height) {
+ width: $width;
+ height: $height;
+}
+
+/* Which you can invoke by passing width and height arguments. */
+
+.rectangle {
+ @include size(100px, 60px);
+}
+
+.square {
+ @include size(40px, 40px);
+}
+
+/* Compiles to: */
+.rectangle {
+ width: 100px;
+ height: 60px;
+}
+
+.square {
+ width: 40px;
+ height: 40px;
+}
+
+
+
+/* Functions
+============================== */
+
+
+
+/* Sass provides functions that can be used to accomplish a variety of
+ tasks. Consider the following */
+
+/* Functions can be invoked by using their name and passing in the
+ required arguments */
+body {
+ width: round(10.25px);
+}
+
+.footer {
+ background-color: fade_out(#000000, 0.25)
+}
+
+/* Compiles to: */
+
+body {
+ width: 10px;
+}
+
+.footer {
+ background-color: rgba(0, 0, 0, 0.75);
+}
+
+/* You may also define your own functions. Functions are very similar to
+ mixins. When trying to choose between a function or a mixin, remember
+ that mixins are best for generating CSS while functions are better for
+ logic that might be used throughout your Sass code. The examples in
+ the Math Operators' section are ideal candidates for becoming a reusable
+ function. */
+
+/* This function will take a target size and the parent size and calculate
+ and return the percentage */
+
+@function calculate-percentage($target-size, $parent-size) {
+ @return $target-size / $parent-size * 100%;
+}
+
+$main-content: calculate-percentage(600px, 960px);
+
+.main-content {
+ width: $main-content;
+}
+
+.sidebar {
+ width: calculate-percentage(300px, 960px);
+}
+
+/* Compiles to: */
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+
+
+/* Extend (Inheritance)
+============================== */
+
+
+
+/* Extend is a way to share the properties of one selector with another. */
+
+.display {
+ @include size(5em, 5em);
+ border: 5px solid $secondary-color;
+}
+
+.display-success {
+ @extend .display;
+ border-color: #22df56;
+}
+
+/* Compiles to: */
+.display, .display-success {
+ width: 5em;
+ height: 5em;
+ border: 5px solid #51527F;
+}
+
+.display-success {
+ border-color: #22df56;
+}
+
+/* Extending a CSS statement is preferable to creating a mixin
+ because of the way Sass groups together the classes that all share
+ the same base styling. If this was done with a mixin, the width,
+ height, and border would be duplicated for each statement that
+ called the mixin. While it won't affect your workflow, it will
+ add unnecessary bloat to the files created by the Sass compiler. */
+
+
+
+/* Nesting
+============================== */
+
+
+
+/* Sass allows you to nest selectors within selectors */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: #FF0000;
+ }
+}
+
+/* '&' will be replaced by the parent selector. */
+/* You can also nest pseudo-classes. */
+/* Keep in mind that over-nesting will make your code less maintainable.
+Best practices recommend going no more than 3 levels deep when nesting.
+For example: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: red;
+
+ &:hover {
+ background-color: blue;
+ }
+
+ a {
+ color: white;
+ }
+ }
+}
+
+/* Compiles to: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+}
+
+ul li {
+ background-color: red;
+}
+
+ul li:hover {
+ background-color: blue;
+}
+
+ul li a {
+ color: white;
+}
+
+
+
+/* Partials and Imports
+============================== */
+
+
+
+/* Sass allows you to create partial files. This can help keep your Sass
+ code modularized. Partial files should begin with an '_', e.g. _reset.css.
+ Partials are not generated into CSS. */
+
+/* Consider the following CSS which we'll put in a file called _reset.css */
+
+html,
+body,
+ul,
+ol {
+ margin: 0;
+ padding: 0;
+}
+
+/* Sass offers @import which can be used to import partials into a file.
+ This differs from the traditional CSS @import statement which makes
+ another HTTP request to fetch the imported file. Sass takes the
+ imported file and combines it with the compiled code. */
+
+@import 'reset';
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+/* Compiles to: */
+
+html, body, ul, ol {
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+
+
+/* Placeholder Selectors
+============================== */
+
+
+
+/* Placeholders are useful when creating a CSS statement to extend. If you
+ wanted to create a CSS statement that was exclusively used with @extend,
+ you can do so using a placeholder. Placeholders begin with a '%' instead
+ of '.' or '#'. Placeholders will not appear in the compiled CSS. */
+
+%content-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ @extend %content-window;
+ background-color: #0000ff;
+}
+
+/* Compiles to: */
+
+.message-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ background-color: #0000ff;
+}
+
+
+
+/* Math Operations
+============================== */
+
+
+
+/* Sass provides the following operators: +, -, *, /, and %. These can
+ be useful for calculating values directly in your Sass files instead
+ of using values that you've already calculated by hand. Below is an example
+ of a setting up a simple two column design. */
+
+$content-area: 960px;
+$main-content: 600px;
+$sidebar-content: 300px;
+
+$main-size: $main-content / $content-area * 100%;
+$sidebar-size: $sidebar-content / $content-area * 100%;
+$gutter: 100% - ($main-size + $sidebar-size);
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: $main-size;
+}
+
+.sidebar {
+ width: $sidebar-size;
+}
+
+.gutter {
+ width: $gutter;
+}
+
+/* Compiles to: */
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+.gutter {
+ width: 6.25%;
+}
+
+```
+
+## SASS or Sass?
+Have you ever wondered whether Sass is an acronym or not? You probably haven't, but I'll tell you anyway. The name of the language is a word, "Sass", and not an acronym.
+Because people were constantly writing it as "SASS", the creator of the language jokingly called it "Syntactically Awesome StyleSheets".
+
+
+## Practice Sass
+If you want to play with Sass in your browser, check out [SassMeister](http://sassmeister.com/).
+You can use either syntax, just go into the settings and select either Sass or SCSS.
+
+
+## Compatibility
+Sass can be used in any project as long as you have a program to compile it
+into CSS. You'll want to verify that the CSS you're using is compatible
+with your target browsers.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility.
+
+
+## Further reading
+* [Official Documentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html)
+* [The Sass Way](http://thesassway.com/) provides tutorials (beginner-advanced) and articles.
diff --git a/scala.html.markdown b/scala.html.markdown
index c482752d..745605ed 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -6,7 +6,6 @@ contributors:
- ["Dominic Bou-Samra", "http://dbousamra.github.com"]
- ["Geoff Liu", "http://geoffliu.me"]
- ["Ha-Duong Nguyen", "http://reference-error.org"]
-filename: learn.scala
---
Scala - the scalable language
@@ -43,9 +42,13 @@ Scala - the scalable language
// Printing, and forcing a new line on the next print
println("Hello world!")
println(10)
+// Hello world!
+// 10
// Printing, without forcing a new line on next print
print("Hello world")
+print(10)
+// Hello world10
// Declaring values is done using either var or val.
// val declarations are immutable, whereas vars are mutable. Immutability is
@@ -166,6 +169,12 @@ def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y
// Syntax for calling functions is familiar:
sumOfSquares(3, 4) // => 25
+// You can use parameters names to specify them in different order
+def subtract(x: Int, y: Int): Int = x - y
+
+subtract(10, 3) // => 7
+subtract(y=10, x=3) // => -7
+
// In most cases (with recursive functions the most notable exception), function
// return type can be omitted, and the same type inference we saw with variables
// will work with function return values:
@@ -228,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 }
@@ -236,16 +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("x is still less than 10")
- x += 1
-} while (x < 10)
+ 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 = {
@@ -263,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"
@@ -274,21 +285,21 @@ val text = if (x == 10) "yeah" else "nope"
/////////////////////////////////////////////////
val a = Array(1, 2, 3, 5, 8, 13)
-a(0)
-a(3)
+a(0) // Int = 1
+a(3) // Int = 5
a(21) // Throws an exception
val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo")
-m("fork")
-m("spoon")
+m("fork") // java.lang.String = tenedor
+m("spoon") // java.lang.String = cuchara
m("bottle") // Throws an exception
val safeM = m.withDefaultValue("no lo se")
-safeM("bottle")
+safeM("bottle") // java.lang.String = no lo se
val s = Set(1, 3, 7)
-s(0)
-s(1)
+s(0) // Boolean = false
+s(1) // Boolean = true
/* Look up the documentation of map here -
* http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map
@@ -309,15 +320,22 @@ s(1)
// Why have this?
val divideInts = (x: Int, y: Int) => (x / y, x % y)
-divideInts(10, 3) // The function divideInts gives you the result and the remainder
+// The function divideInts gives you the result and the remainder
+divideInts(10, 3) // (Int, Int) = (3,1)
// To access the elements of a tuple, use _._n where n is the 1-based index of
// the element
-val d = divideInts(10, 3)
+val d = divideInts(10, 3) // (Int, Int) = (3,1)
+
+d._1 // Int = 3
+d._2 // Int = 1
-d._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)
-d._2
+div // Int = 3
+mod // Int = 1
/////////////////////////////////////////////////
@@ -449,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
@@ -562,8 +583,8 @@ sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!"
// Implicit function parameters enable us to simulate type classes in other
// functional languages. It is so often used that it gets its own shorthand. The
// following two lines mean the same thing:
-def foo[T](implicit c: C[T]) = ...
-def foo[T : C] = ...
+// def foo[T](implicit c: C[T]) = ...
+// def foo[T : C] = ...
// Another situation in which the compiler looks for an implicit is if you have
@@ -601,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/sk-sk/LearnGit-sk.txt b/sk-sk/LearnGit-sk.txt
new file mode 100644
index 00000000..070a0489
--- /dev/null
+++ b/sk-sk/LearnGit-sk.txt
@@ -0,0 +1,208 @@
+$ git init
+
+# Zobraz a Nastav Základné Konfiguračné Premenné (Globálne)
+$ git config --global user.email "MôjEmail@Zoho.com"
+$ git config --global user.name "Moje Meno
+
+# Rýchlo zobraz všetky dostupné príkazy
+$ git help
+
+# Zobraz všetky dostupné príkazy
+$ git help -a
+
+# Zobraz konkrétnu pomoc - použivateľský manuál
+# git help <príkaz_tu>
+$ git help add
+$ git help commit
+$ git help init
+# alebo git <príkaz_tu> --help
+$ git add --help
+$ git commit --help
+$ git init --help
+
+# Zobrazí vetvu, nesledované súbory, zmeny a ostatné rozdiely
+$ git status
+# Zistí iné vychytávky o git statuse
+$ git help status
+
+# pridá súbor z tvojho pracovného adresára
+$ git add HelloWorld.java
+
+# pridá súbor z iného adresára
+$ git add /cesta/k/súboru/HelloWorld.c
+
+# Môžeš použiť regulárne výrazy!
+$ git add ./*.java
+
+# zobraz existujúce vetvy a vzdialené repozitáre
+$ git branch -a
+
+# vytvor novú vetvu
+$ git branch myNewBranch
+
+# vymaž vetvu
+$ git branch -d myBranch
+
+# premenuj vetvu
+# git branch -m <starémeno> <novémeno>
+$ git branch -m mojaStaraVetva mojaNovaVetva
+
+# zmeň opis vetvy
+$ git branch myBranchName --edit-description
+
+# Zobrazí tagy
+$ git tag
+# Vytvorí tag so správou
+# -m špecifikuje správu, ktorá bude s tagom uložená.
+# Ak nešpeficikuješ správu pri tagu so správou,
+# Git spustí tvoj editor, aby si ju napísal.
+$ git tag -a v2.0 -m 'moja verzia 2.0'
+
+# Ukáž informácie o tagu
+# Zobrazí zadané informácie, dátum tagnutia commitu
+# a správu pred zobrazením informácií o commite.
+$ git show v2.0
+
+# Zverejní (pushne) jediný tag do vzdialeného repozitára
+$ git push origin v2.0
+
+# Zverejní viacero tagov do vzdialeného repozitára
+$ git push origin --tags
+
+# Aktualizuj strom, aby odpovedal (predvolene)
+# hlavnej vetve repozitáru (master branch)
+$ git checkout
+
+# Aktualizuj strom, aby odpovedal konrkétnej vetve
+$ git checkout menoVetvy
+
+# Vytvor novú vetvu & prepni sa na ňu
+# ekvivalentný príkaz: "git branch <meno>; git checkout <meno>"
+$ git checkout -b nováVetva
+
+# Naklonuj learnxinyminutes-docs
+$ git clone https://github.com/adambard/learnxinyminutes-docs.git
+
+# povrchné klonovanie - rýchlejšie, uloží iba najnovšiu snímku
+$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git
+
+# naklonuj iba konkrétnu vetvu
+$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch
+
+# commitni so správou
+$ git commit -m "Pridal som multiplyNumbers() funkciu do HelloWorld.c"
+
+# automaticky pridaj zmenené a vymazané súbory do staging indexu, potom ich commitni.
+$ git commit -a -m "Zmenil som foo.php a vymazal bar.php"
+
+# zmeň posledný commit (toto nahradí predchádzajúci commit novým)
+$ git commit --amend -m "Správna správa"
+
+# Ukáž rozdiel medzi pracovným repozitárom a indexom.
+$ git diff
+
+# Ukáž rozdiely medzi indexom a najnovším commitom.
+$ git diff --cached
+
+# Ukáž rozdiely medzi pracovným adresárom a najnovším commitom.
+$ git diff HEAD
+
+# Nastav, aby sa vo výsledkoch vyhľadávania zobrazovalo číslo riadku
+$ git config --global grep.lineNumber true
+
+# Urob výsledky vyhľadávania čitateľnejšie, vrátane zoskupovania
+$ git config --global alias.g "grep --break --heading --line-number"
+
+# Vďaka Travisovi Jefferymu za túto sekciu
+# Hľadaj "názovPremennej" vo všetkých java súboroch
+$ git grep 'názovPremennej' -- '*.java'
+
+# Hľadaj riadok, ktorý obsahuje "názovPoľa" a "add" alebo "remove"
+$ git grep -e 'arrayListName' --and \( -e add -e remove \)
+
+# Zobraz všetky commity
+$ git log
+
+# Zobraz iba správy a referencie commitov
+$ git log --oneline
+
+# Zobraz zlúčené (merged) commity
+$ git log --merges
+
+# Zobraz všetky commity vo forme ASCII grafu
+$ git log --graph
+
+# Zlúč vybranú vetvu do aktuálnej.
+$ git merge názovVetvy
+
+# Vždy vytvor zlučovací commit
+$ git merge --no-ff názovVetvy
+
+# Premenuj súbor
+$ git mv HelloWorld.c HelloNewWorld.c
+
+# Presuň súbor
+$ git mv HelloWorld.c ./nová/cesta/HelloWorld.c
+
+# "Nasilu" premenuj, alebo presuň
+# "existujúciSúbor" už v adresári existuje, bude prepísaný
+$ git mv -f môjSúbor existujúciSúbor
+
+# Aktualizuje tvoj lokálny repozitár zlúčením nových zmien
+# zo vzdialených "origin" a "master" vetiev.
+# git pull <alias-vzdialeného-repo> <vetva>
+$ git pull origin master
+
+# Predvolene, git pull aktualizuje tvoju aktuálnu vetvu
+# zlúčením nových zmien zo vzdialenej vetvy
+$ git pull
+
+# Zlúč zmeny zo vzdialenej vetvy a presuň vetvu do nového základného commitu (rebase)
+# vetva commitne na tvoj lokálny repozitár, ekvivalentný príkaz: "git pull <alias-vzdialeného-repo> <vrstva>, git rebase <branch>"
+$ git pull origin master --rebase
+
+# Zverejni a zlúč zmeny z lokálneho repozitára do
+# vzdialených vetiev s názvom "origin" a "master".
+# git push <vzdialené> <vetvy>
+$ git push origin master
+
+# Predvolene git zverejní a zlúči zmeny z
+# aktuálnej vetvy do vzdialenej vetvy s ňou spojenej
+$ git push
+
+# Na spojenie lokálnej vetvy so vzdialenou pridaj -u:
+$ git push -u origin master
+# Kedykoľvek budeš chcieť zverejniť z rovnakej lokálnej vetvy, použi príkaz:
+$ git push
+
+# Aplikuj commity z experimentálnej vetvy na master
+# git rebase <základnáVetva> <ináVetva>
+$ git rebase master experimentBranch
+
+# Resetni index (vrstvu medzi pracovným stromom a Git repozitárom), aby odpovedal najnovšiemu commitu (adresár ostane nezmenený)
+$ git reset
+
+# Resetni index, aby odpovedal najnovšiemu commitu (adresár sa prepíše)
+$ git reset --hard
+
+# Presunie vrchol aktuálnuej vetvy do konkrétneho commitu (adresár ostane nezmenený)
+# všetky zmeny sú zachované v adresári.
+$ git reset 31f2bb1
+
+# Vezmi späť konkrétny commit
+$ git revert <commit>
+
+# odstráň HelloWorld.c
+$ git rm HelloWorld.c
+
+# Odstráň súbor z vnoreného adresára
+$ git rm /pather/to/the/file/HelloWorld.c
+
+
+
+
+
+
+
+
+
diff --git a/sk-sk/git.html.markdown b/sk-sk/git.html.markdown
new file mode 100644
index 00000000..21741406
--- /dev/null
+++ b/sk-sk/git.html.markdown
@@ -0,0 +1,523 @@
+---
+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"]
+ - ["Andrew Taylor", "http://github.com/andrewjt71"]
+translators:
+ - ["Terka Slanináková", "http://github.com/TerkaSlan"]
+lang: sk-sk
+filename: LearnGit-sk.txt
+---
+
+Git je distribuovaný systém riadenia revízií a správy zdrojového kódu.
+
+Funguje robením "snímkov" tvojho projektu, s ktorými ďalej pracuje na revíziach a správe zdrojových kódov.
+
+## Koncept Revízií
+
+### Čo je riadenie revízií?
+
+Riadenie revízií je systém, ktorý postupom času zaznamenáva zmeny súboru (súborov).
+
+### Centralizované Revízie VS Distribuované revízie
+
+* Centralizované riadenie revízií sa zameriava na synchronizáciu, sledovanie a zálohovanie súborov.
+* Distribuované riadenie revízií sa zameriava na zdieľanie zmien. Kaťdá zmena má jedinečný identifikátor (id).
+* Distribuované systémy nemajú definovanú štruktúru. S gitom môžeš mať centralizovaný systém v subversion (SVN) štýle.
+
+[Ďalšie informácie](http://git-scm.com/book/en/Getting-Started-About-Version-Control)
+
+### Prečo Používať Git?
+
+* Môžeš pracovať offline.
+* Spolupráca s ostatnými je jednoduchá!
+* Vetvenie je jednoduché!
+* Zlučovanie je jednoduché!
+* Git je rýchly.
+* Git je flexibilný.
+
+## Architektúra Gitu
+
+
+### Repozitár
+
+Skupina súborov, adresárov, minulých záznamov, commitov (konkrétnych revízií) a odkazy na aktuálu vetvu (HEADs). Predstav si ho ako údajovú štruktúru, kde ti každý "prvok" zdrojového kódu poskytne (okrem iného) prístup k minulým revíziam.
+
+Git repozitár sa skladá z .git adresára a pracovného stromu
+
+### .git Adresár (časť repozitára)
+
+.git adresár obsahuje všetky konfigurácie, logy, vetvy, odkaz na aktuálnu vetvu (HEAD) a ostatné.
+[Detailný zoznam.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html)
+
+### Pracovný Strom (Working Tree - časť repozitára)
+
+Toto sú adresáre a súbory v tvojom repozitári. Tiež sa tomu hovorí pracovný adresár.
+
+### Index (časť .git adresára)
+
+Index je také odpočívadlo Gitu. Je to v podstate vrstva, ktorá oddeľuje pracovný strom od Git repozitára. Toto dáva vývojárom viac možností nad tým, čo do repozitára naozaj pošlú.
+
+### Commit
+
+Commit je "snímka" zmien, či manipulácií s tvojím Pracovným Stromom. Ak si napríklad pridal 5 súborov a odstránil 2 ďalšie, tieto zmeny budú zachytené v commite. Ten môže (ale nemusí) byť zverejnený (pushed) do iných repozitárov.
+
+### Vetva (Branch)
+
+Vetva je ukazateľ na posledný vykonaný commit. Po ďalších commitnutiach sa ukazateľ bude automaticky posúvať na ten najnovší.
+
+### Tag
+
+Tag je označenie špecifického bodu v minulosti. Typicky sa používa na značenie vydaných verzií (v1.0, atď).
+
+### HEAD a head (časť .git adresára)
+
+HEAD je ukazateľ na aktuálnu vetvu. Repozitár má len 1 *aktívny* HEAD.
+head je ukazateľ, ktorý môže ukazovať na akýkoľvek commit. Repozitár môže mať niekoľko headov.
+
+### Štádia Gitu
+* Modified - Súbor bol zmenený, no nebol ešte commitnutý do Git Databázy.
+* Staged - Zmenený súbor, ktorý pôjde do najbližšieho commit snímku.
+* Committed - Súbory boli commitnuté do Git Databázy.
+
+### Koncepčné zdroje
+
+* [Git Pre Informatikov](http://eagain.net/articles/git-for-computer-scientists/)
+* [Git Pre Designerov](http://hoth.entp.com/output/git_for_designers.html)
+
+
+## Príkazy
+
+
+### init
+
+Vytvorí prázdny Git repozitár. Jeho nastavenia, uložené informácie a mnoho iného sú uložené v adresári (zložke) s názvom ".git".
+
+```bash
+$ git init
+```
+
+### config
+
+Konfiguruj nastavenia. Či už pre repozitár, samotný systém, alebo globálne konfigurácie (súbor pre globálny config je `~/.gitconfig`).
+
+
+```bash
+# Zobraz a Nastav Základné Konfiguračné Premenné (Globálne)
+$ git config --global user.email "MôjEmail@Zoho.com"
+$ git config --global user.name "Moje Meno "
+```
+
+[Prečítaj si viac o git configu.](http://git-scm.com/docs/git-config)
+
+### pomoc
+
+Máš tiež prístup k extrémne detailnej dokumentácií pre každý príkaz (po anglicky). Hodí sa, ak potrebuješ pripomenúť semantiku.
+
+```bash
+# Rýchlo zobraz všetky dostupné príkazy
+$ git help
+
+# Zobraz všetky dostupné príkazy
+$ git help -a
+
+# Zobraz konkrétnu pomoc - použivateľský manuál
+# git help <príkaz_tu>
+$ git help add
+$ git help commit
+$ git help init
+# alebo git <príkaz_tu> --help
+$ git add --help
+$ git commit --help
+$ git init --help
+```
+
+### ignoruj súbory
+
+Zámerne prestaneš sledovať súbor(y) a zložky. Typicky sa používa pre súkromné a dočasné súbory, ktoré by boli inak zdieľané v repozitári.
+```bash
+$ echo "temp/" >> .gitignore
+$ echo "private_key" >> .gitignore
+```
+
+
+### status
+
+Na zobrazenie rozdielov medzi indexovými súbormi (tvoj pracovný repozitár) a aktuálnym HEAD commitom.
+
+
+```bash
+# Zobrazí vetvu, nesledované súbory, zmeny a ostatné rozdiely
+$ git status
+
+# Zistí iné vychytávky o git statuse
+$ git help status
+```
+
+### add
+
+Pripraví súbory na commit pridaním do tzv. staging indexu. Ak ich nepridáš pomocou `git add` do staging indexu, nebudú zahrnuté v commitoch!
+
+```bash
+# pridá súbor z tvojho pracovného adresára
+$ git add HelloWorld.java
+
+# pridá súbor z iného adresára
+$ git add /cesta/k/súboru/HelloWorld.c
+
+# Môžeš použiť regulárne výrazy!
+$ git add ./*.java
+```
+Tento príkaz len pridáva súbory do staging indexu, necommituje ich do repozitára.
+
+### branch
+
+Spravuj svoje vetvy. Môžeš ich pomocou tohto príkazu zobraziť, meniť, vytvoriť, či zmazať.
+
+```bash
+# zobraz existujúce vetvy a vzdialené repozitáre
+$ git branch -a
+
+# vytvor novú vetvu
+$ git branch myNewBranch
+
+# vymaž vetvu
+$ git branch -d myBranch
+
+# premenuj vetvu
+# git branch -m <starémeno> <novémeno>
+$ git branch -m mojaStaraVetva mojaNovaVetva
+
+# zmeň opis vetvy
+$ git branch myBranchName --edit-description
+```
+
+### tag
+
+Spravuj svoje tagy
+
+```bash
+# Zobraz tagy
+$ git tag
+# Vytvor tag so správou
+# -m špecifikuje správu, ktorá bude s tagom uložená.
+# Ak nešpeficikuješ správu pri tagu so správou,
+# Git spustí tvoj editor, aby si ju napísal.
+$ git tag -a v2.0 -m 'moja verzia 2.0'
+# Ukáž informácie o tagu
+# Zobrazí zadané informácie, dátum tagnutia commitu
+# a správu pred zobrazením informácií o commite.
+$ git show v2.0
+# Zverejní (pushne) jediný tag do vzdialeného repozitára
+$ git push origin v2.0
+# Zverejní viacero tagov do vzdialeného repozitára
+$ git push origin --tags
+```
+
+### checkout
+
+Aktualizuje všetky súbory v pracovnom strome, aby odpovedali verzií v indexe, alebo v inom strome.
+
+```bash
+# Aktualizuj strom, aby odpovedal (predvolene)
+# hlavnej vetve repozitáru (master branch)
+$ git checkout
+# Aktualizuj strom, aby odpovedal konrkétnej vetve
+$ git checkout menoVetvy
+# Vytvor novú vetvu & prepni sa na ňu
+# ekvivalentný príkaz: "git branch <meno>; git checkout <meno>"
+$ git checkout -b nováVetva
+```
+
+### clone
+
+"Naklonuje", alebo vytvorí kópiu existujúceho repozitára do nového adresára. Tiež pridá špeciálne ďiaľkovo-monitorujúce vetvy (remote-tracking branches), ktoré ti umožnia zverejňovať do vzdialených vetiev.
+
+```bash
+# Naklonuj learnxinyminutes-docs
+$ git clone https://github.com/adambard/learnxinyminutes-docs.git
+# povrchné klonovanie - rýchlejšie, uloží iba najnovšiu snímku
+$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git
+# naklonuj iba konkrétnu vetvu
+$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch
+```
+
+### commit
+
+Uloží aktuálny obsah indexu v novom "commite". Ten obsahuje vytvorené zmeny a s nimi súvisiace správy vytvorené použivateľom.
+
+```bash
+# commitni so správou
+$ git commit -m "Pridal som multiplyNumbers() funkciu do HelloWorld.c"
+
+# automaticky pridaj zmenené a vymazané súbory do staging indexu, potom ich commitni.
+$ git commit -a -m "Zmenil som foo.php a vymazal bar.php"
+
+# zmeň posledný commit (toto nahradí predchádzajúci commit novým)
+$ git commit --amend -m "Správna správa"
+```
+
+### diff
+
+Ukáže rozdiel medzi súborom v pracovnom repozitári, indexe a commitoch.
+
+```bash
+# Ukáž rozdiel medzi pracovným repozitárom a indexom.
+$ git diff
+
+# Ukáž rozdiely medzi indexom a najnovším commitom.
+$ git diff --cached
+
+# Ukáž rozdiely medzi pracovným adresárom a najnovším commitom.
+$ git diff HEAD
+```
+
+### grep
+
+Umožní ti rýchlo prehľadávať repozitár.
+
+Možná konfigurácia:
+
+```bash
+# Nastav, aby sa vo výsledkoch vyhľadávania zobrazovalo číslo riadku
+$ git config --global grep.lineNumber true
+
+# Urob výsledky vyhľadávania čitateľnejšie, vrátane zoskupovania
+$ git config --global alias.g "grep --break --heading --line-number"
+```
+
+```bash
+# Vďaka Travisovi Jefferymu za túto sekciu
+# Hľadaj "názovPremennej" vo všetkých java súboroch
+$ git grep 'názovPremennej' -- '*.java'
+
+# Hľadaj riadok, ktorý obsahuje "názovPoľa" a "add" alebo "remove"
+$ git grep -e 'arrayListName' --and \( -e add -e remove \)
+```
+
+Google je tvoj kamarát; pre viac príkladov skoč na
+[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja)
+
+### log
+
+Zobral commity do repozitára.
+
+```bash
+# Zobraz všetky commity
+$ git log
+
+# Zobraz iba správy a referencie commitov
+$ git log --oneline
+
+# Zobraz zlúčené (merged) commity
+$ git log --merges
+
+# Zobraz všetky commity vo forme ASCII grafu
+$ git log --graph
+```
+
+### merge
+
+"Zlúč" zmeny externých commitov do aktuálnej vetvy.
+
+```bash
+# Zlúč vybranú vetvu do aktuálnej.
+$ git merge názovVetvy
+
+# Vždy vytvor zlučovací commit
+$ git merge --no-ff názovVetvy
+```
+
+### mv
+
+Premenuj, alebo presuň súbor
+
+```bash
+# Premenuj súbor
+$ git mv HelloWorld.c HelloNewWorld.c
+
+# Presuň súbor
+$ git mv HelloWorld.c ./nová/cesta/HelloWorld.c
+
+# "Nasilu" premenuj, alebo presuň
+# "existujúciSúbor" už v adresári existuje, bude prepísaný
+$ git mv -f môjSúbor existujúciSúbor
+```
+
+### pull
+
+Uloží obsah repozitára a zlúči ho s inou vetvou.
+
+```bash
+# Aktualizuje tvoj lokálny repozitár zlúčením nových zmien
+# zo vzdialených "origin" a "master" vetiev.
+# git pull <alias-vzdialeného-repo> <vetva>
+$ git pull origin master
+
+# Predvolene, git pull aktualizuje tvoju aktuálnu vetvu
+# zlúčením nových zmien zo vzdialenej vetvy
+$ git pull
+
+# Zlúč zmeny zo vzdialenej vetvy a presuň vetvu do nového základného commitu (rebase)
+# vetva commitne na tvoj lokálny repozitár, ekvivalentný príkaz: "git pull <alias-vzdialeného-repo> <vrstva>, git rebase <branch>"
+$ git pull origin master --rebase
+```
+
+### push
+
+Zverejní a zlúči zmeny z lokálnej do vzdialenej vetvy.
+
+```bash
+# Zverejni a zlúč zmeny z lokálneho repozitára do
+# vzdialených vetiev s názvom "origin" a "master".
+# git push <vzdialené> <vetvy>
+$ git push origin master
+
+# Predvolene git zverejní a zlúči zmeny z
+# aktuálnej vetvy do vzdialenej vetvy s ňou spojenej
+$ git push
+
+# Na spojenie lokálnej vetvy so vzdialenou pridaj -u:
+$ git push -u origin master
+# Kedykoľvek budeš chcieť zverejniť z rovnakej lokálnej vetvy, použi príkaz:
+$ git push
+```
+
+### stash
+
+Umožní ti opustiť chaotický stav pracovného adresára a uloží ho na zásobník nedokončených zmien, ku ktorým sa môžeš kedykoľvek vrátiť.
+
+Povedzme, že si urobil nejaké zmeny vo svojom git repozitári, ale teraz potrebuješ pullnúť zo vzdialenej repo. Keďže máš necommitnuté zmeny, príkaz `git pull` nebude fungovať. Namiesto toho môžeš použiť `git stash` a uložiť svoje nedokončené zmeny na zásobník!
+
+```bash
+$ git stash
+Saved working directory and index state \
+ "WIP on master: 049d078 added the index file"
+ HEAD is now at 049d078 added the index file
+ (To restore them type "git stash apply")
+```
+
+Teraz môžeš uložiť vzdialenú vetvu!
+
+```bash
+$ git pull
+```
+
+Over, či je všetko v poriadku
+
+```bash
+$ git status
+# On branch master
+nothing to commit, working directory clean
+```
+
+Môžeš si pozrieť, čo za chaos je na zásobníku cez `git stash list`.
+Nedokončené zmeny sú uložené ako Last-In-First-Out (Prvý dnu, posledný von) štruktúra, navrchu sa objavia najnovšie zmeny.
+
+```bash
+$ git stash list
+stash@{0}: WIP on master: 049d078 added the index file
+stash@{1}: WIP on master: c264051 Revert "added file_size"
+stash@{2}: WIP on master: 21d80a5 added number to log
+```
+
+Keď so zmenami budeš chcieť pracovať, odstráň ich zo stacku.
+
+```bash
+$ git stash pop
+# On branch master
+# Changes not staged for commit:
+# (use "git add <file>..." to update what will be committed)
+#
+# modified: index.html
+# modified: lib/simplegit.rb
+#
+```
+
+`git stash apply` urobí presne to isté
+
+Hotovo, môžeš pokračovať v práci!
+
+[Čítaj viac.](http://git-scm.com/book/en/v1/Git-Tools-Stashing)
+
+### rebase (pozor)
+
+Zober všetky zmeny commitnuté do vetvy a aplikuj ich na inú vetvu.
+*Tento príkaz nerob na verejných repozitároch*.
+
+```bash
+# Aplikuj commity z experimentálnej vetvy na master
+# git rebase <základnáVetva> <ináVetva>
+$ git rebase master experimentBranch
+```
+
+[Čítaj viac.](http://git-scm.com/book/en/Git-Branching-Rebasing)
+
+### reset (pozor)
+
+Resetni HEAD (ukazateľ na aktuálnu vetvu) do konrkétneho stavu. To ti umožní vziať späť zlúčenia, zverejnenia, commity, pridania atď. Je to užitočný, no nebezpečný príkaz, pokiaľ nevieš, čo robíš.
+
+```bash
+# Resetni index (vrstvu medzi pracovným stromom a Git repozitárom), aby odpovedal najnovšiemu commitu (adresár ostane nezmenený)
+$ git reset
+
+# Resetni index, aby odpovedal najnovšiemu commitu (adresár sa prepíše)
+$ git reset --hard
+
+# Presunie vrchol aktuálnuej vetvy do konkrétneho commitu (adresár ostane nezmenený)
+# všetky zmeny sú zachované v adresári.
+$ git reset 31f2bb1
+
+# Presunie vrchol aktuálnuej vetvy naopak do konkrétneho commitu
+# a zosúladí ju s pracovným adresárom (vymaže nekomitnuté zmeny).
+$ git reset --hard 31f2bb1
+```
+### revert
+
+Vezme naspäť ("od-urobí") commit. Nezamieňaj s resetom, ktorý obnoví stav
+projektu do predchádzajúceho bodu v čase. Revert pridá nový commit, inverzný tomu, ktorý chceš vymazať, tým ho od-urobí.
+
+```bash
+# Vezmi späť konkrétny commit
+$ git revert <commit>
+```
+
+### rm
+
+Opak od git add, rm odstráni súbory z aktuálneho pracovného stromu.
+
+```bash
+# odstráň HelloWorld.c
+$ git rm HelloWorld.c
+
+# Odstráň súbor z vnoreného adresára
+$ git rm /pather/to/the/file/HelloWorld.c
+```
+
+## Ďalšie informácie
+
+* [tryGit - Zábavný interaktívny spôsob, ako sa naučiť Git.](http://try.github.io/levels/1/challenges/1)
+
+* [Udemy Git Tutoriál: Kompletný návod](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/)
+
+* [Git Immersion - Návod, ktorý Ťa prevedie základmi Gitu](http://gitimmersion.com/)
+
+* [git-scm - Video Tutoriály](http://git-scm.com/videos)
+
+* [git-scm - Dokumentácia](http://git-scm.com/docs)
+
+* [Atlassian Git - Tutoriály & Postupy](https://www.atlassian.com/git/)
+
+* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
+
+* [GitGuys](http://www.gitguys.com/)
+
+* [Git - jednoducho](http://rogerdudler.github.io/git-guide/index.html)
+
+* [Pro Git](http://www.git-scm.com/book/en/v2)
+
+* [Úvod do Gitu a GitHubu pre začiatočníkov (Tutoriál)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners)
diff --git a/sk-sk/latex.html.markdown.tex b/sk-sk/latex.html.markdown.tex
new file mode 100644
index 00000000..5e2f9c7f
--- /dev/null
+++ b/sk-sk/latex.html.markdown.tex
@@ -0,0 +1,227 @@
+---
+language: latex
+contributors:
+ - ["Chaitanya Krishna Ande", "http://icymist.github.io"]
+ - ["Colton Kohnke", "http://github.com/voltnor"]
+ - ["Sricharan Chiruvolu", "http://sricharan.xyz"]
+translators:
+ - ["Terka Slanináková", "http://github.com/TerkaSlan"]
+filename: learn-latex-sk.tex
+---
+
+```tex
+% Všetky komentáre začínajú s %
+% Viac-riadkové komentáre sa nedajú urobiť
+
+% LaTeX NIE JE WYSIWY ("What You See Is What You Get") software ako MS Word, alebo OpenOffice Writer
+
+% Každý LaTeX príkaz začína s opačným lomítkom (\)
+
+% LaTeX dokumenty začínajú s definíciou typu kompilovaného dokumentu
+% Ostatné typy sú napríklad kniha (book), správa (report), prezentácia (presentation), atď.
+% Možnosti dokumentu sa píšu do [] zátvoriek. V tomto prípade tam upresňujeme veľkosť (12pt) fontu.
+\documentclass[12pt]{article}
+
+% Ďalej definujeme balíčky, ktoré dokuemnt používa.
+% Ak chceš zahrnúť grafiku, farebný text, či zdrojový kód iného jazyka, musíš rozšíriť možnosti LaTeXu dodatočnými balíčkami.
+% Zahŕňam float a caption. Na podporu slovenčiny treba zahrnúť aj utf8 balíček.
+\usepackage{caption}
+\usepackage{float}
+\usepackage[utf8]{inputenc}
+% Tu môžme definovať ostatné vlastnosti dokumentu!
+% Autori tohto dokumentu, "\\*" znamená "choď na nový riadok"
+\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu, \\*Preklad: Terka Slanináková}
+% Vygeneruje dnešný dátum
+\date{\today}
+\title{Nauč sa LaTeX za Y Minút!}
+% Teraz môžme začať pracovať na samotnom dokumente.
+% Všetko do tohto riadku sa nazýva "Preambula" ("The Preamble")
+\begin{document}
+% ak zadáme položky author, date a title, LaTeX vytvorí titulnú stranu.
+\maketitle
+
+% Väčšina odborných článkov má abstrakt, na jeho vytvorenie môžeš použiť preddefinované príkazy.
+% Ten by sa mal zobraziť v logickom poradí, teda po hlavičke,
+% no pred hlavnými sekciami tela..
+% Tento príkaz je tiež dostupný v triedach article a report.
+% Tzv. makro "abstract" je fixnou súčasťou LaTeXu, ak chceme použiť abstract
+% a napísať ho po slovensky, musíme ho redefinovať nasledujúcim príkazom
+\renewcommand\abstractname{Abstrakt}
+
+\begin{abstract}
+LaTeX dokumentácia v LaTeXe! Aké netradičné riešenie cudzieho nápadu!
+\end{abstract}
+
+% Príkazy pre sekciu sú intuitívne
+% Všetky nadpisy sekcií sú pridané automaticky do obsahu.
+\section{Úvod}
+Čaute, volám sa Colton a spoločne sa pustíme do skúmania LaTeXu (toho druhého)!
+
+\section{Ďalšia sekcia}
+Toto je text ďalšej sekcie. Myslím, že potrebuje podsekciu.
+
+\subsection{Toto je podsekcia} % Podsekcie sú tiež intuitívne.
+Zdá sa mi, že treba ďalšiu.
+
+\subsubsection{Pytagoras}
+To je ono!
+\label{subsec:pytagoras}
+
+% Použitím '*' môžeme potlačiť zabudované číslovanie LaTeXu.
+% Toto funguje aj na iné príkazy.
+\section*{Toto je nečíslovaná sekcia}
+Všetky číslované byť nemusia!
+
+\section{Nejaké poznámočky}
+Zarovnávať veci tam, kde ich chceš mať, je všeobecne ľahké. Ak
+potrebuješ \\ nový \\ riadok \\ pridaj \textbackslash\textbackslash do
+zdrojového kódu. \\
+
+\section{Zoznamy}
+Zoznamy sú jednou z najjednoduchších vecí vôbec! Treba mi zajtra nakúpiť, urobím si zoznam.
+\begin{enumerate} % "enumerate" spustí číslovanie prvkov.
+ % \item povie LaTeXu, ako že treba pripočítať 1
+ \item Vlašský šalát.
+ \item 5 rožkov.
+ \item 3 Horalky.
+ % číslovanie môžeme pozmeniť použitím []
+ \item[koľko?] Stredne veľkých guličkoviek.
+
+ Ja už nie som položka zoznamu, no stále som časť "enumerate".
+
+\end{enumerate} % Všetky prostredia končia s "end".
+
+\section{Matika}
+
+Jedným z primárnych použití LaTeXu je písanie akademických, či technických prác. Zvyčajne za použitia matematiky a vedy. Podpora špeciálnych symbolov preto nemôže chýbať!\\
+
+Matematika má veľa symbolov, omnoho viac, než by klávesnica mohla reprezentovať;
+Množinové a relačné symboly, šípky, operátory a Grécke písmená sú len malou ukážkou.\\
+
+Množiny a relácie hrajú hlavnú rolu v mnohých matematických článkoch.
+Takto napíšeš, že niečo platí pre všetky x patriace do X, $\forall$ x $\in$ X. \\
+% Všimni si, že som pridal $ pred a po symboloch. Je to
+% preto, lebo pri písaní sme v textovom móde,
+% no matematické symboly existujú len v matematickom.
+% Vstúpime doňho z textového práve '$' znamienkami.
+% Platí to aj opačne. Premenná môže byť zobrazená v matematickom móde takisto.
+% Do matematického módu sa dá dostať aj s \[\]
+
+\[a^2 + b^2 = c^2 \]
+
+Moje obľúbené Grécke písmeno je $\xi$. Tiež sa mi pozdávajú $\beta$, $\gamma$ a $\sigma$.
+Ešte som neprišiel na Grécke písmeno, ktoré by LaTeX nepoznal!
+
+Operátory sú dôležitou súčasťou matematických dokumentov:
+goniometrické funkcie ($\sin$, $\cos$, $\tan$),
+logaritmy and exponenciálne výrazy ($\log$, $\exp$),
+limity ($\lim$), atď.
+majú pred-definované LaTeXové príkazy.
+Napíšme si rovnicu, nech vidíme, ako to funguje: \\
+
+$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$
+
+Zlomky(Čitateľ-menovateľ) sa píšu v týchto formách:
+
+% 10 / 7
+$^{10}/_{7}$
+
+% Relatívne komplexné zlomky sa píšu ako
+% \frac{čitateľ}{menovateľ}
+$\frac{n!}{k!(n - k)!}$ \\
+
+Rovnice tiež môžeme zadať v "rovnicovom prostredí".
+
+% Takto funguje rovnicové prostredie
+\begin{equation} % vstúpi do matematického módu
+ c^2 = a^2 + b^2.
+ \label{eq:pythagoras} % na odkazovanie
+\end{equation} % všetky \begin príkazy musia mať konečný príkaz.
+
+Teraz môžeme odkázať na novovytvorenú rovnicu!
+Rovn.~\ref{eq:pythagoras} je tiež známa ako Pytagorova Veta, ktorá je tiež predmetom Sekc.~\ref{subsec:pytagoras}. Odkazovať môžme na veľa vecí, napr na: čísla, rovnice, či sekcie.
+
+Sumácie a Integrály sa píšu príkazmi sum a int:
+
+% Niektoré prekladače LaTeXu sa môžu sťažovať na prázdne riadky (ak tam sú)
+% v rovnicovom prostredí.
+\begin{equation}
+ \sum_{i=0}^{5} f_{i}
+\end{equation}
+\begin{equation}
+ \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
+\end{equation}
+
+\section{Obrázky}
+
+Vloženie obrázku môže byť zložitejšie. Ja si vždy možnosti vloženia pozerám pre každý obrázok.
+\renewcommand\figurename{Obrázok}
+\begin{figure}[H] % H značí možnosť zarovnania.
+ \centering % nacentruje obrázok na stránku
+ % Vloží obrázok na 80% šírky stránky.
+ %\includegraphics[width=0.8\linewidth]{right-triangle.png}
+ % Zakomentované kvôli kompilácií, použi svoju predstavivosť :).
+ \caption{Pravouhlý trojuholník so stranami $a$, $b$, $c$}
+ \label{fig:right-triangle}
+\end{figure}
+% Opäť, fixné makro "table" nahradíme slovenskou tabuľkou. Pokiaľ preferuješ table, nasledujúci riadok nepridávaj
+\renewcommand\tablename{Tabuľka}
+
+\subsection{Tabuľky}
+Tabuľky sa vkládajú podobne ako obrázky.
+
+\begin{table}[H]
+ \caption{Nadpis tabuľky.}
+ % zátvorky: {} hovoria ako sa vykreslí každý riadok.
+ % Toto si nikdy nepamätám a vždy to musím hľadať. Všetko. Každý. Jeden. Raz!
+ \begin{tabular}{c|cc}
+ Číslo & Priezvisko & Krstné meno \\ % Stĺpce sú rozdelené $
+ \hline % horizontálna čiara
+ 1 & Ladislav & Meliško \\
+ 2 & Eva & Máziková
+ \end{tabular}
+\end{table}
+
+% \section{Hyperlinks} % Už čoskoro :)
+
+\section{Prikáž LaTeXu nekompilovať (napr. Zdrojový Kód)}
+Povedzme, že chceme do dokumentu vložiť zdrojový kód, budeme musieť LaTeXu povedať, nech sa ho nesnaží skompilovať, ale nech s ním pracuje ako s textom.
+Toto sa robí vo verbatim prostredí.
+
+% Tiež sú na to špeciálne balíčky, (napr. minty, lstlisting, atď.)
+% ale verbatim je to najzákladnejšie, čo môžeš použiť.
+\begin{verbatim}
+ print("Hello World!")
+ a%b; pozri! Vo verbatime môžme použiť % znamienka.
+ random = 4; #priradené randomným hodom kockou
+\end{verbatim}
+
+\section{Kompilácia}
+
+Už by bolo načase túto nádheru skompilovať a zhliadnuť jej úžasnú úžasnosť v podobe LaTeX pdfka, čo povieš?
+(áno, tento dokument sa musí kompilovať). \\
+Cesta k finálnemu dokumentu pomocou LaTeXu pozostáva z nasledujúcich krokov:
+ \begin{enumerate}
+ \item Napíš dokument v čistom texte (v "zdrojáku").
+ \item Skompiluj zdroják na získanie pdfka.
+ Kompilácia by mala vyzerať nasledovne (v Linuxe): \\
+ \begin{verbatim}
+ $pdflatex learn-latex.tex learn-latex.pdf
+ \end{verbatim}
+ \end{enumerate}
+
+Mnoho LaTeX editorov kombinuje Krok 1 a Krok 2 v jednom prostredí. Krok 1 teda uvidíš, krok 2 už nie.
+Ten sa deje za oponou. Kompilácia v 2. kroku sa postará o produkciu dokumentu v tebou zadanom formáte.
+
+\section{Koniec}
+
+To je zatiaľ všetko!
+
+% koniec dokumentu
+\end{document}
+```
+
+## Viac o LaTeXe (anglicky)
+
+* Úžasná LaTeX wikikniha: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX)
+* Naozajstný tutoriál: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
diff --git a/sk-sk/learn-latex-sk.tex b/sk-sk/learn-latex-sk.tex
new file mode 100644
index 00000000..5cc7b11f
--- /dev/null
+++ b/sk-sk/learn-latex-sk.tex
@@ -0,0 +1,209 @@
+% Všetky komentáre začínajú s %
+% Viac-riadkové komentáre sa nedajú urobiť
+
+% LaTeX NIE JE WYSIWY ("What You See Is What You Get") software ako MS Word, alebo OpenOffice Writer
+
+% Každý LaTeX príkaz začína s opačným lomítkom (\)
+
+% LaTeX dokumenty začínajú s definíciou typu kompilovaného dokumentu
+% Ostatné typy sú napríklad kniha (book), správa (report), prezentácia (presentation), atď.
+% Možnosti dokumentu sa píšu do [] zátvoriek. V tomto prípade tam upresňujeme veľkosť (12pt) fontu.
+\documentclass[12pt]{article}
+
+% Ďalej definujeme balíčky, ktoré dokuemnt používa.
+% Ak chceš zahrnúť grafiku, farebný text, či zdrojový kód iného jazyka, musíš rozšíriť možnosti LaTeXu dodatočnými balíčkami.
+% Zahŕňam float a caption. Na podporu slovenčiny treba zahrnúť aj utf8 balíček.
+\usepackage{caption}
+\usepackage{float}
+\usepackage[utf8]{inputenc}
+% Tu môžme definovať ostatné vlastnosti dokumentu!
+% Autori tohto dokumentu, "\\*" znamená "choď na nový riadok"
+\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu, \\*Preklad: Terka Slanináková}
+% Vygeneruje dnešný dátum
+\date{\today}
+\title{Nauč sa LaTeX za Y Minút!}
+% Teraz môžme začať pracovať na samotnom dokumente.
+% Všetko do tohto riadku sa nazýva "Preambula" ("The Preamble")
+\begin{document}
+% ak zadáme položky author, date a title, LaTeX vytvorí titulnú stranu.
+\maketitle
+
+% Väčšina odborných článkov má abstrakt, na jeho vytvorenie môžeš použiť preddefinované príkazy.
+% Ten by sa mal zobraziť v logickom poradí, teda po hlavičke,
+% no pred hlavnými sekciami tela..
+% Tento príkaz je tiež dostupný v triedach article a report.
+% Tzv. makro "abstract" je fixnou súčasťou LaTeXu, ak chceme použiť abstract
+% a napísať ho po slovensky, musíme ho redefinovať nasledujúcim príkazom
+\renewcommand\abstractname{Abstrakt}
+
+\begin{abstract}
+LaTeX dokumentácia v LaTeXe! Aké netradičné riešenie cudzieho nápadu!
+\end{abstract}
+
+% Príkazy pre sekciu sú intuitívne
+% Všetky nadpisy sekcií sú pridané automaticky do obsahu.
+\section{Úvod}
+Čaute, volám sa Colton a spoločne sa pustíme do skúmania LaTeXu (toho druhého)!
+
+\section{Ďalšia sekcia}
+Toto je text ďalšej sekcie. Myslím, že potrebuje podsekciu.
+
+\subsection{Toto je podsekcia} % Podsekcie sú tiež intuitívne.
+Zdá sa mi, že treba ďalšiu.
+
+\subsubsection{Pytagoras}
+To je ono!
+\label{subsec:pytagoras}
+
+% Použitím '*' môžeme potlačiť zabudované číslovanie LaTeXu.
+% Toto funguje aj na iné príkazy.
+\section*{Toto je nečíslovaná sekcia}
+Všetky číslované byť nemusia!
+
+\section{Nejaké poznámočky}
+Zarovnávať veci tam, kde ich chceš mať, je všeobecne ľahké. Ak
+potrebuješ \\ nový \\ riadok \\ pridaj \textbackslash\textbackslash do
+zdrojového kódu. \\
+
+\section{Zoznamy}
+Zoznamy sú jednou z najjednoduchších vecí vôbec! Treba mi zajtra nakúpiť, urobím si zoznam.
+\begin{enumerate} % "enumerate" spustí číslovanie prvkov.
+ % \item povie LaTeXu, ako že treba pripočítať 1
+ \item Vlašský šalát.
+ \item 5 rožkov.
+ \item 3 Horalky.
+ % číslovanie môžeme pozmeniť použitím []
+ \item[koľko?] Stredne veľkých guličkoviek.
+
+ Ja už nie som položka zoznamu, no stále som časť "enumerate".
+
+\end{enumerate} % Všetky prostredia končia s "end".
+
+\section{Matika}
+
+Jedným z primárnych použití LaTeXu je písanie akademických, či technických prác. Zvyčajne za použitia matematiky a vedy. Podpora špeciálnych symbolov preto nemôže chýbať!\\
+
+Matematika má veľa symbolov, omnoho viac, než by klávesnica mohla reprezentovať;
+Množinové a relačné symboly, šípky, operátory a Grécke písmená sú len malou ukážkou.\\
+
+Množiny a relácie hrajú hlavnú rolu v mnohých matematických článkoch.
+Takto napíšeš, že niečo platí pre všetky x patriace do X, $\forall$ x $\in$ X. \\
+% Všimni si, že som pridal $ pred a po symboloch. Je to
+% preto, lebo pri písaní sme v textovom móde,
+% no matematické symboly existujú len v matematickom.
+% Vstúpime doňho z textového práve '$' znamienkami.
+% Platí to aj opačne. Premenná môže byť zobrazená v matematickom móde takisto.
+% Do matematického módu sa dá dostať aj s \[\]
+
+\[a^2 + b^2 = c^2 \]
+
+Moje obľúbené Grécke písmeno je $\xi$. Tiež sa mi pozdávajú $\beta$, $\gamma$ a $\sigma$.
+Ešte som neprišiel na Grécke písmeno, ktoré by LaTeX nepoznal!
+
+Operátory sú dôležitou súčasťou matematických dokumentov:
+goniometrické funkcie ($\sin$, $\cos$, $\tan$),
+logaritmy and exponenciálne výrazy ($\log$, $\exp$),
+limity ($\lim$), atď.
+majú pred-definované LaTeXové príkazy.
+Napíšme si rovnicu, nech vidíme, ako to funguje: \\
+
+$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$
+
+Zlomky(Čitateľ-menovateľ) sa píšu v týchto formách:
+
+% 10 / 7
+$^{10}/_{7}$
+
+% Relatívne komplexné zlomky sa píšu ako
+% \frac{čitateľ}{menovateľ}
+$\frac{n!}{k!(n - k)!}$ \\
+
+Rovnice tiež môžeme zadať v "rovnicovom prostredí".
+
+% Takto funguje rovnicové prostredie
+\begin{equation} % vstúpi do matematického módu
+ c^2 = a^2 + b^2.
+ \label{eq:pythagoras} % na odkazovanie
+\end{equation} % všetky \begin príkazy musia mať konečný príkaz.
+
+Teraz môžeme odkázať na novovytvorenú rovnicu!
+Rovn.~\ref{eq:pythagoras} je tiež známa ako Pytagorova Veta, ktorá je tiež predmetom Sekc.~\ref{subsec:pytagoras}. Odkazovať môžme na veľa vecí, napr na: čísla, rovnice, či sekcie.
+
+Sumácie a Integrály sa píšu príkazmi sum a int:
+
+% Niektoré prekladače LaTeXu sa môžu sťažovať na prázdne riadky (ak tam sú)
+% v rovnicovom prostredí.
+\begin{equation}
+ \sum_{i=0}^{5} f_{i}
+\end{equation}
+\begin{equation}
+ \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
+\end{equation}
+
+\section{Obrázky}
+
+Vloženie obrázku môže byť zložitejšie. Ja si vždy možnosti vloženia pozerám pre každý obrázok.
+\renewcommand\figurename{Obrázok}
+\begin{figure}[H] % H značí možnosť zarovnania.
+ \centering % nacentruje obrázok na stránku
+ % Vloží obrázok na 80% šírky stránky.
+ %\includegraphics[width=0.8\linewidth]{right-triangle.png}
+ % Zakomentované kvôli kompilácií, použi svoju predstavivosť :).
+ \caption{Pravouhlý trojuholník so stranami $a$, $b$, $c$}
+ \label{fig:right-triangle}
+\end{figure}
+% Opäť, fixné makro "table" nahradíme slovenskou tabuľkou. Pokiaľ preferuješ table, nasledujúci riadok nepridávaj
+\renewcommand\tablename{Tabuľka}
+
+\subsection{Tabuľky}
+Tabuľky sa vkládajú podobne ako obrázky.
+
+\begin{table}[H]
+ \caption{Nadpis tabuľky.}
+ % zátvorky: {} hovoria ako sa vykreslí každý riadok.
+ % Toto si nikdy nepamätám a vždy to musím hľadať. Všetko. Každý. Jeden. Raz!
+ \begin{tabular}{c|cc}
+ Číslo & Priezvisko & Krstné meno \\ % Stĺpce sú rozdelené $
+ \hline % horizontálna čiara
+ 1 & Ladislav & Meliško \\
+ 2 & Eva & Máziková
+ \end{tabular}
+\end{table}
+
+% \section{Hyperlinks} % Už čoskoro :)
+
+\section{Prikáž LaTeXu nekompilovať (napr. Zdrojový Kód)}
+Povedzme, že chceme do dokumentu vložiť zdrojový kód, budeme musieť LaTeXu povedať, nech sa ho nesnaží skompilovať, ale nech s ním pracuje ako s textom.
+Toto sa robí vo verbatim prostredí.
+
+% Tiež sú na to špeciálne balíčky, (napr. minty, lstlisting, atď.)
+% ale verbatim je to najzákladnejšie, čo môžeš použiť.
+\begin{verbatim}
+ print("Hello World!")
+ a%b; pozri! Vo verbatime môžme použiť % znamienka.
+ random = 4; #priradené randomným hodom kockou
+\end{verbatim}
+
+\section{Kompilácia}
+
+Už by bolo načase túto nádheru skompilovať a zhliadnuť jej úžasnú úžasnosť v podobe LaTeX pdfka, čo povieš?
+(áno, tento dokument sa musí kompilovať). \\
+Cesta k finálnemu dokumentu pomocou LaTeXu pozostáva z nasledujúcich krokov:
+ \begin{enumerate}
+ \item Napíš dokument v čistom texte (v "zdrojáku").
+ \item Skompiluj zdroják na získanie pdfka.
+ Kompilácia by mala vyzerať nasledovne (v Linuxe): \\
+ \begin{verbatim}
+ $pdflatex learn-latex.tex learn-latex.pdf
+ \end{verbatim}
+ \end{enumerate}
+
+Mnoho LaTeX editorov kombinuje Krok 1 a Krok 2 v jednom prostredí. Krok 1 teda uvidíš, krok 2 už nie.
+Ten sa deje za oponou. Kompilácia v 2. kroku sa postará o produkciu dokumentu v tebou zadanom formáte.
+
+\section{Koniec}
+
+To je zatiaľ všetko!
+
+% koniec dokumentu
+\end{document}
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 a40e86c8..e921e7ea 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -5,6 +5,8 @@ contributors:
- ["Christopher Bess", "http://github.com/cbess"]
- ["Joey Huang", "http://github.com/kamidox"]
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
+ - ["Clayton Walker", "https://github.com/cwalk"]
+ - ["Fernando Valverde", "http://visualcosita.xyz"]
filename: learnswift.swift
---
@@ -24,12 +26,13 @@ import UIKit
// Xcode supports landmarks to annotate your code and lists them in the jump bar
// MARK: Section mark
+// MARK: - Section mark with a separator line
// TODO: Do something soon
// FIXME: Fix this code
// In Swift 2, println and print were combined into one print method. Print automatically appends a new line.
print("Hello, world") // println is now print
-print("Hello, world", appendNewLine: false) // printing without appending a newline
+print("Hello, world", terminator: "") // printing without appending a newline
// variables (var) value can change after being set
// constants (let) value can NOT be changed after being set
@@ -43,7 +46,7 @@ let `class` = "keyword" // backticks allow keywords to be used as variable names
let explicitDouble: Double = 70
let intValue = 0007 // 7
let largeIntValue = 77_000 // 77000
-let label = "some text " + String(myVariable) // Casting
+let label = "some text " + String(myVariable) // String construction
let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation
// Build Specific values
@@ -57,13 +60,14 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation
print("Build value: \(buildValue)") // Build value: 7
/*
- Optionals are a Swift language feature that allows you to store a `Some` or
- `None` value.
+Optionals are a Swift language feature that either contains a value,
+or contains nil (no value) to indicate that a value is missing.
+A question mark (?) after the type marks the value as optional.
- Because Swift requires every property to have a value, even nil must be
- explicitly stored as an Optional value.
+Because Swift requires every property to have a value, even nil must be
+explicitly stored as an Optional value.
- Optional<T> is an enum.
+Optional<T> is an enum.
*/
var someOptionalString: String? = "optional" // Can be nil
// same as above, but ? is a postfix operator (syntax candy)
@@ -79,11 +83,19 @@ if someOptionalString != nil {
}
someOptionalString = nil
+/*
+Trying to use ! to access a non-existent optional value triggers a runtime
+error. Always make sure that an optional contains a non-nil value before
+using ! to force-unwrap its value.
+*/
+
// implicitly unwrapped optional
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") {
@@ -93,7 +105,7 @@ if let someOptionalStringConstant = someOptionalString {
// Swift has support for storing a value of any type.
// AnyObject == id
-// Unlike Objective-C `id`, AnyObject works with any value (Class, Int, struct, etc)
+// Unlike Objective-C `id`, AnyObject works with any value (Class, Int, struct, etc.)
var anyObjectVar: AnyObject = 7
anyObjectVar = "Changed value to a string, not good practice, but possible."
@@ -110,8 +122,8 @@ anyObjectVar = "Changed value to a string, not good practice, but possible."
//
/*
- Array and Dictionary types are structs. So `let` and `var` also indicate
- that they are mutable (var) or immutable (let) when declaring these types.
+Array and Dictionary types are structs. So `let` and `var` also indicate
+that they are mutable (var) or immutable (let) when declaring these types.
*/
// Array
@@ -120,6 +132,7 @@ shoppingList[1] = "bottle of water"
let emptyArray = [String]() // let == immutable
let emptyArray2 = Array<String>() // same as above
var emptyMutableArray = [String]() // var == mutable
+var explicitEmptyMutableStringArray: [String] = [] // same as above
// Dictionary
@@ -131,12 +144,21 @@ occupations["Jayne"] = "Public Relations"
let emptyDictionary = [String: Float]() // let == immutable
let emptyDictionary2 = Dictionary<String, Float>() // same as above
var emptyMutableDictionary = [String: Float]() // var == mutable
+var explicitEmptyMutableDictionary: [String: Float] = [:] // same as above
//
// MARK: Control Flow
//
+// Condition statements support "where" clauses, which can be used
+// to help provide conditions on optional values.
+// Both the assignment and the "where" clause must pass.
+let someNumber = Optional<Int>(7)
+if let num = someNumber where num > 3 {
+ print("num is greater than 3")
+}
+
// for loop (array)
let myArray = [1, 1, 2, 3, 5]
for value in myArray {
@@ -166,8 +188,8 @@ while i < 1000 {
i *= 2
}
-// do-while loop
-do {
+// repeat-while loop
+repeat {
print("hello")
} while 1 == 2
@@ -186,7 +208,6 @@ default: // required (in order to cover all possible input)
let vegetableComment = "Everything tastes good in soup."
}
-
//
// MARK: Functions
//
@@ -194,28 +215,28 @@ 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
+A greet operation
- - A bullet in docs
- - Another bullet in the docs
+- 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)."
}
-greet("Bob", "Tuesday")
+greet("Bob", day: "Tuesday")
// similar to above except for the function parameter behaviors
-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")
+greet2(requiredName: "John", externalParamName: "Sunday")
// Function that returns multiple items in a tuple
func getGasPrices() -> (Double, Double, Double) {
@@ -228,11 +249,33 @@ let (_, price1, _) = pricesTuple // price1 == 3.69
print(price1 == pricesTuple.1) // true
print("Gas price: \(price)")
+// Labeled/named tuple params
+func getGasPrices2() -> (lowestPrice: Double, highestPrice: Double, midPrice: Double) {
+ return (1.77, 37.70, 7.37)
+}
+let pricesTuple2 = getGasPrices2()
+let price2 = pricesTuple2.lowestPrice
+let (_, price3, _) = pricesTuple2
+print(pricesTuple2.highestPrice == pricesTuple2.1) // true
+print("Highest gas price: \(pricesTuple2.highestPrice)")
+
+// guard statements
+func testGuard() {
+ // guards provide early exits or breaks, placing the error handler code near the conditions.
+ // it places variables it declares in the same scope as the guard statement.
+ guard let aNumber = Optional<Int>(7) else {
+ return
+ }
+
+ print("number is \(aNumber)")
+}
+testGuard()
+
// Variadic Args
func setup(numbers: Int...) {
// its an array
- let number = numbers[0]
- let argCount = numbers.count
+ let _ = numbers[0]
+ let _ = numbers.count
}
// Passing and returning functions
@@ -253,7 +296,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
@@ -281,23 +324,17 @@ numbers = numbers.map({ number in 3 * number })
print(numbers) // [3, 6, 18]
// Trailing closure
-numbers = sorted(numbers) { $0 > $1 }
+numbers = numbers.sort { $0 > $1 }
print(numbers) // [18, 6, 3]
-// Super shorthand, since the < operator infers the types
-
-numbers = sorted(numbers, < )
-
-print(numbers) // [3, 6, 18]
-
//
// MARK: Structures
//
-// Structures and classes have very similar capabilites
+// Structures and classes have very similar capabilities
struct NamesTable {
- let names = [String]()
+ let names: [String]
// Custom subscript
subscript(index: Int) -> String {
@@ -311,6 +348,44 @@ let name = namesTable[1]
print("Name is \(name)") // Name is Them
//
+// MARK: Error Handling
+//
+
+// The `ErrorType` protocol is used when throwing errors to catch
+enum MyError: ErrorType {
+ case BadValue(msg: String)
+ case ReallyBadValue(msg: String)
+}
+
+// functions marked with `throws` must be called using `try`
+func fakeFetch(value: Int) throws -> String {
+ guard 7 == value else {
+ throw MyError.ReallyBadValue(msg: "Some really bad value")
+ }
+
+ return "test"
+}
+
+func testTryStuff() {
+ // assumes there will be no error thrown, otherwise a runtime exception is raised
+ let _ = try! fakeFetch(7)
+
+ // if an error is thrown, then it proceeds, but if the value is nil
+ // it also wraps every return value in an optional, even if its already optional
+ let _ = try? fakeFetch(7)
+
+ do {
+ // normal try operation that provides error handling via `catch` block
+ try fakeFetch(1)
+ } catch MyError.BadValue(let msg) {
+ print("Error message: \(msg)")
+ } catch {
+ // must be exhaustive
+ }
+}
+testTryStuff()
+
+//
// MARK: Classes
//
@@ -319,7 +394,7 @@ print("Name is \(name)") // Name is Them
public class Shape {
public func getArea() -> Int {
- return 0;
+ return 0
}
}
@@ -341,6 +416,11 @@ internal class Rect: Shape {
}
}
+ // Computed properties must be declared as `var`, you know, cause' they can change
+ var smallestSideLength: Int {
+ return self.sideLength - 1
+ }
+
// Lazily load a property
// subShape remains nil (uninitialized) until getter called
lazy var subShape = Rect(sideLength: 4)
@@ -445,9 +525,10 @@ enum Suit {
// when the variable is explicitly declared
var suitValue: Suit = .Hearts
-// Non-Integer enums require direct raw value assignments
+// String enums can have direct raw value assignments
+// or their raw values will be derived from the Enum field
enum BookName: String {
- case John = "John"
+ case John
case Luke = "Luke"
}
print("Name: \(BookName.John.rawValue)")
@@ -491,7 +572,7 @@ protocol ShapeGenerator {
// Protocols declared with @objc allow optional functions,
// which allow you to check for conformance
@objc protocol TransformShape {
- optional func reshaped()
+ optional func reshape()
optional func canReshape() -> Bool
}
@@ -504,9 +585,9 @@ class MyShape: Rect {
// Place a question mark after an optional property, method, or
// subscript to gracefully ignore a nil value and return nil
// instead of throwing a runtime error ("optional chaining").
- if let allow = self.delegate?.canReshape?() {
+ if let reshape = self.delegate?.canReshape?() where reshape {
// test for delegate then for method
- self.delegate?.reshaped?()
+ self.delegate?.reshape?()
}
}
}
@@ -518,8 +599,8 @@ class MyShape: Rect {
// `extension`s: Add extra functionality to an already existing type
-// Square now "conforms" to the `Printable` protocol
-extension Square: Printable {
+// Square now "conforms" to the `CustomStringConvertible` protocol
+extension Square: CustomStringConvertible {
var description: String {
return "Area: \(self.getArea()) - ID: \(self.identifier)"
}
@@ -544,8 +625,8 @@ print(14.multiplyBy(3)) // 42
// Generics: Similar to Java and C#. Use the `where` keyword to specify the
// requirements of the generics.
-func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
- for (index, value) in enumerate(array) {
+func findIndex<T: Equatable>(array: [T], _ valueToFind: T) -> Int? {
+ for (index, value) in array.enumerate() {
if value == valueToFind {
return index
}
@@ -574,4 +655,18 @@ print(mySquare.sideLength) // 4
// change side length using custom !!! operator, increases size by 3
!!!mySquare
print(mySquare.sideLength) // 12
+
+// Operators can also be generics
+infix operator <-> {}
+func <-><T: Equatable> (inout a: T, inout b: T) {
+ let c = a
+ a = b
+ b = c
+}
+
+var foo: Float = 10
+var bar: Float = 20
+
+foo <-> bar
+print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0"
```
diff --git a/ta_in/css-ta.html.markdown b/ta_in/css-ta.html.markdown
new file mode 100644
index 00000000..cbe88f1e
--- /dev/null
+++ b/ta_in/css-ta.html.markdown
@@ -0,0 +1,254 @@
+---
+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"]
+translators:
+ - ["Rasendran Kirushan", "https://github.com/kirushanr"]
+filename: learncss-ta.css
+lang: in-ta
+---
+
+
+இணையத்தின் ஆரம்ப காலத்தில் முழுமையாக உரைகளை மட்டுமே கொண்டிருந்தன.
+ஆனால் உலாவிகளில் கொண்டு வரப்பட்ட மாற்றங்களில் முழுமையான காட்சிபடுத்தல்களுடன்
+கூடிய இணையதளங்கள் உருவாகின.
+
+
+CSS ஆனது HTML மற்றும் அதன் அழகுபடுத்கூடிய காரணிகளையும் வேறுபடுத்த உதவியது.
+
+ஒரு html இல் உள்ள உறுப்புகளை(elements) வெவ்வேறு வகையான காட்சி பண்புகளை வழங்க உதவுகிறது.
+
+இந்த வழிகாட்டி CSS2 உக்கு எழுதப்பட்டுள்ளது, இருப்பினும் தற்போது CSS 3 வேகமாக பிரபல்யமாகி வருகிறது.
+
+**குறிப்பு:**
+CSS ஆனது முற்று முழுதாக visual(காட்சி) மாற்றங்களை தருவதால் அதை நீங்கள் முயற்சிக்க
+இதை உபயோகபடுத்தலாம் [dabblet](http://dabblet.com/).
+இந்த வழிகாட்டியின் பிரதான நோக்கம் CSS இன் syntax மற்றும் மேலும் சில வழிமுறைகளை
+உங்களுக்கு கற்று தருவதாகும்
+
+```css
+/* css இல் குறிப்புகளை இப்படி இடலாம் */
+
+/* ####################
+ ## SELECTORS
+ #################### */
+
+/* ஒரு HTML பக்கத்தில் இருக்கும் உறுப்பை நாம் selector மூலம் தெரிவு செய்யலாம்
+selector { property: value; /* more properties...*/ }
+
+/*
+கிழே ஒரு உதாரணம் காட்டப்பட்டுள்ளது:
+
+<div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' />
+*/
+
+/* நீங்கள் அந்த உறுப்பை அதன் CSS class மூலம் தெரியலாம் */
+.class1 { }
+
+/* அல்லது இவ்வாறு இரண்டு class மூலம் தெரியலாம்! */
+.class1.class2 { }
+
+/* அல்லது அதன் பெயரை பாவித்து தெரியலாம் */
+div { }
+
+/* அல்லது அதன் id ஐ பயன்படுத்தி தெரியலாம்*/
+#anID { }
+
+/* அல்லது ஒரு உறுப்பின் பண்பு ஒன்றின் மூலம்! */
+[attr] { font-size:smaller; }
+
+/* அல்லது அந்த பண்பு ஒரு குறிப்பிட்ட பெறுமானத்தை கொண்டு இருப்பின் */
+[attr='value'] { font-size:smaller; }
+
+/* ஒரு பெறுமதியுடன் ஆரம்பமாகும் போது (CSS 3) */
+[attr^='val'] { font-size:smaller; }
+
+/* அல்லது ஒரு பெறுமதியுடன் முடிவடையும் போது (CSS 3) */
+[attr$='ue'] { font-size:smaller; }
+
+/* அல்லது காற்புள்ளியால் பிரிக்கப்பட்ட பெறுமானங்களை கொண்டு இருப்பின் */
+[otherAttr~='foo'] { }
+[otherAttr~='bar'] { }
+
+/* அல்லது `-` பிரிக்கப்பட்ட பெறுமானங்களை கொண்டு இருப்பின், உ.ம்:-, "-" (U+002D) */
+[otherAttr|='en'] { font-size:smaller; }
+
+
+/* நாம் இரண்டு selectors ஐ ஒன்றாக உபயோகித்தும் ஒரு உறுப்பை அணுக முடியும் ,
+அவற்றுக்கு இடயே இடைவெளி காணப்படகூடாது
+ */
+div.some-class[attr$='ue'] { }
+
+/*அல்லது ஒரு உறுப்பினுள் இருக்கும் இன்னொரு உறுப்பை (child element) அணுக */
+div.some-parent > .class-name { }
+
+/* ஒரு ஒரு பிரதான உறுப்பில் உள்ள உப உறுப்புகளை அணுக*/
+div.some-parent .class-name { }
+
+/* மேலே குறிபிட்ட அணுகுமுறையில் இடைவெளி காணப்படாது விடின்
+ அந்த selector வேலை செய்யாது
+ */
+div.some-parent.class-name { }
+
+/* அல்லது ஒரு உறுப்புக்கு அடுத்துள்ள */
+.i-am-just-before + .this-element { }
+
+/* or அல்லது அதற்கு முந்தய உறுப்பின் மூலம் */
+.i-am-any-element-before ~ .this-element { }
+
+/*
+ சில selectors ஐ pseudo class மூலம் அணுக முடியும் , எப்போது எனில் அவை
+ குறித்த ஒரு நிலையில் இருக்கும் போது ஆகும்
+ */
+
+/* உதாரணமாக நாம் ஒரு உறுப்பின் மீதாக cursor ஐ நகர்த்தும் போது */
+selector:hover { }
+
+/* அல்லது ஒரு
+பார்வையிட்ட இணைப்பு */
+selector:visited { }
+
+/* அல்லது ஒரு பார்வையிடபடாத இணைப்பு */
+selected:link { }
+
+/* அல்லது ஒரு element ஐ focus செய்யும் போது */
+selected:focus { }
+
+/*
+ எல்லா elementகளையும் ஒரே நேரத்தில் அணுக `*`
+*/
+* { } /* all elements */
+.parent * { } /* all descendants */
+.parent > * { } /* all children */
+
+/* ####################
+ ## பண்புகள்
+ #################### */
+
+selector {
+
+ /* நீளத்தின் அலகுகள் absolute அல்லது relative ஆக இருக்கலாம். */
+
+ /* Relative units */
+ width: 50%; /* percentage of parent element width */
+ font-size: 2em; /* multiples of element's original font-size */
+ font-size: 2rem; /* or the root element's font-size */
+ font-size: 2vw; /* multiples of 1% of the viewport's width (CSS 3) */
+ 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 */
+ color: tomato; /* a named color */
+ color: rgb(255, 255, 255); /* as rgb values */
+ color: rgb(10%, 20%, 50%); /* as rgb percentages */
+ color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 < a < 1 */
+ color: transparent; /* equivalent to setting the alpha to 0 */
+ color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */
+ color: hsla(0, 100%, 50%, 0.3); /* as hsla percentages with alpha */
+
+ /* 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 */
+ font-family: "Courier New";
+ /* if the first one is not found, the browser uses the next, and so on */
+ font-family: "Courier New", Trebuchet, Arial, sans-serif;
+}
+```
+
+## Usage
+
+ஒரு css file ஐ save செய்ய `.css`.
+
+```xml
+<!-- உங்கள் css file ஐ <head>. உள் குறிப்பிட வேண்டும்
+ சரியான முறையை பார்க்க http://stackoverflow.com/questions/8284365 -->
+<link rel='stylesheet' type='text/css' href='path/to/style.css' />
+
+<!-- நீங்கள் css ஐ html உள்ளும் எழுத முடியும் -->
+<style>
+ a { color: purple; }
+</style>
+
+<!-- அல்லது css ஐ நேரடியாக அந்த element இல் எழுத முடியும் -->
+<div style="border: 1px solid red;">
+</div>
+```
+
+## Precedence அல்லது Cascade
+
+ஒரு element ஆனது ஒன்றுக்கு மேற்பட்ட selectors மூலம் அணுகபடலாம் ,இவ்வாறான சந்தர்பங்களில்
+ஒரு குறிபிட்ட விதிமுறையை பின்பற்றுகிறது இது cascading என அழைக்கபடுகிறது, அதனால் தன
+இது Cascading Style Sheets என அழைக்கபடுகிறது.
+
+
+கிழே தரப்பட்டுள்ள css இன் படி:
+
+```css
+/* A */
+p.class1[attr='value']
+
+/* B */
+p.class1 { }
+
+/* C */
+p.class2 { }
+
+/* D */
+p { }
+
+/* E */
+p { property: value !important; }
+```
+
+அத்துடன் கிழே தரப்பட்டுள்ள கட்டமைப்பின்படியும்:
+
+```xml
+<p style='/*F*/ property:value;' class='class1 class2' attr='value' />
+```
+
+
+css முன்னுரிமை பின்வருமாறு
+* `E` இதுவே அதிக முக்கியத்துவம் வாய்ந்தது காரணம் இது `!important` பயன்படுத்துகிறது. இதை பயன்படுத்துவதை தவிர்க்கவும்
+* `F` இது இரண்டாவது காரணம் இது inline style.
+* `A` இது மூன்றவதாக வருகிறது, காரணம் இது மூன்று காரணிகளை குறிக்கிறது : element(உறுப்பு) பெயர் `p`, அதன் class `class1`, an அதன் பண்பு(attribute) `attr='value'`.
+* `C` இது அடுத்த நிலையில் உள்ளது கடைசி.
+* `B` இது அடுத்தது.
+* `D` இதுவே கடைசி .
+
+## css அம்சங்களின் பொருந்தகூடிய தன்மை
+
+பெரும்பாலான css 2 வின் அம்சங்கள் எல்லா உலாவிகளிலும் , கருவிகளிலும் உள்ளன. ஆனால் முன்கூட்டியே அந்த அம்சங்களை பரிசோதிப்பது நல்லது.
+
+## வளங்கள்
+
+* To run a quick compatibility check, [CanIUse](http://caniuse.com).
+* CSS Playground [Dabblet](http://dabblet.com/).
+* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS)
+* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/)
+
+## மேலும் வாசிக்க
+
+* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
+* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/)
+* [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)
+* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing
+* [CSS-Tricks](https://css-tricks.com)
diff --git a/ta_in/javascript-ta.html.markdown b/ta_in/javascript-ta.html.markdown
new file mode 100644
index 00000000..d3fe5a85
--- /dev/null
+++ b/ta_in/javascript-ta.html.markdown
@@ -0,0 +1,594 @@
+---
+language: javascript
+contributors:
+ - ['Adam Brenecki', 'http://adam.brenecki.id.au']
+ - ['Ariel Krakowski', 'http://www.learneroo.com']
+translators:
+ - ["Rasendran Kirushan", "https://github.com/kirushanr"]
+filename: javascript-ta.js
+lang: in-ta
+---
+
+javascript 1995 ஆம் ஆண்டு Netscape இல் பணிபுரிந்த Brendan Eich
+என்பவரால் உருவாக்கபட்டது.ஆரம்பத்தில் மிகவும் எளிமையான
+ஸ்க்ரிப்டிங் மொழியாக இணையதளங்களில் பயன்படுத்தபட்டது.
+இது ஜாவா (java ) வில் உருவாக்கபட்ட மிகவும் சிக்கலான இணைய செயலிகளுக்கு
+உதவும் முகமாக உருவாக்கபட்டது. எனினும் இணையதள பக்கங்களில் இதன் முழுதான பயன்பாடு
+மற்றும் உலாவிகளில் பயன்படுத்த கூடிய வகையில் இருந்தமையாலும் Java வை விட
+இணையதளகளின் முகப்பு உருவாக்கத்தில் இன்றளவில் முன்னிலை பெற்றுள்ளது.
+
+உலாவிகளுக்கு மட்டும் மட்டுபடுத்தபடவில்லை , Node.js மூலமாக
+மிகவும் பிரபல்யமடைந்து வருகின்றது , உதாரணமாக கூகிள்க்ரோம் உலாவியின்
+V8 JavaScript engine Node .js உதவியுடன் இயங்குகிறது .
+
+உங்கள் கருத்துக்கள் மிகவும் வரவேற்கபடுகின்றன , என்னுடன் தொடர்புகொள்ள
+[@adambrenecki](https://twitter.com/adambrenecki), or
+[adam@brenecki.id.au](mailto:adam@brenecki.id.au).
+
+```js
+// குறிப்புக்கள் C நிரலாக்கத்தை ஒத்தது .ஒரு வரி குறிப்புக்கள் "//" குறியீடுடன் ஆரம்பமாகும்
+
+/* பலவரி குறிப்புக்கள் "/*" ஆரம்பமாகி "/*" இல் முடிவடையும் */
+
+// ஒரு கூற்று முற்றுபெற செய்ய ; இடல் வேண்டும் .
+doStuff();
+
+// ...ஆனால் அரைபுள்ளி இட வேண்டும் என்று அவசியம் இல்லை ஏன் எனில்
+// ஒரு வரி புதிதாக இடப்படும் போது அரைபுள்ளிகள் தானாகவே இடப்படும் ஆனால் சில தருணங்களை தவிர .
+doStuff()
+
+// ஆனால் அவ்வாறான தருணங்கள் எதிர்பாராத முடிவுகளை தரலாம்
+
+// எனவே நாம் தொடர்ந்து ஒரு கூற்று நிறைவடையும் போது அரைபுள்ளி ஒன்றை இடுவோம் .
+
+///////////////////////////////////
+// 1. எண்கள்(Number) ,சரம் (String),செயற்குறிகள்(Operators)
+
+// JavaScript ஒரே ஒரு எண்வகை காணப்படுகிறது தசமி (which is a 64-bit IEEE 754 double).
+// தசமி எண்வகை (Doubles) 2^ 52 வரை சேமிக்க கூடியது
+// முழு எண்வகையின் 9✕10¹⁵ சேமிக்க போதுமானது .
+3; // = 3
+1.5; // = 1.5
+
+// அடிப்படை கணித பொறிமுறைகள்
+1 + 1; // = 2
+0.1 + 0.2; // = 0.30000000000000004
+8 - 1; // = 7
+10 * 2; // = 20
+35 / 5; // = 7
+
+// வகுத்தல்
+5 / 2; // = 2.5
+
+
+//bitwise பொறிமுறையை உபயோகிக்கும் போது
+//உங்கள் தசம எண்ணின் பெறுமானமானது ஒரு நேர் அல்லது மறை அல்லது பூசியமாகவுள்ள முழு எண்ணாக
+//மாற்றம் பெறுகிறது இது 32 இருமம்(bit) வரை செல்லலாம்
+
+1 << 2; // = 4
+
+// நிரலாக்கத்தில் செயலியை அமுல்படுத்தும் வரிசைமுறையில் அடைப்பு குறிக்கு முன்னிலை வழங்கபடுகிறது
+(1 + 3) * 2; // = 8
+
+// மெய் எண் அல்லாத மூன்றுபெறுமானங்கள் உள்ளன :
+Infinity; // result of e.g. 1/0
+-Infinity; // result of e.g. -1/0
+NaN; // result of e.g. 0/0, இது எண் அல்ல என்பதை குறிக்கும்
+
+// தர்க ரீதியில் ஆன கட்டமைப்பு காணப்படுகிறது .
+true;
+false;
+
+// சரம் (string) ' அல்லது " குறியீட்டினால் உருவாக்கபடுகிறது
+'abc';
+"Hello, world";
+
+// ஒரு boolean பெறுமானத்தின் எதிர்மறை பெறுமானத்தை பெற ! குறியீடு பயன்படுத்தபடுகிறது
+!true; // = false
+!false; // = true
+
+// சமமா என பார்க்க ===
+1 === 1; // = true
+2 === 1; // = false
+
+// சமனற்றவையா என பார்க்க !==
+1 !== 1; // = false
+2 !== 1; // = true
+
+// மேலும் சில ஒப்பீடுகள்
+1 < 10; // = true
+1 > 10; // = false
+2 <= 2; // = true
+2 >= 2; // = true
+
+// இரண்டு சரங்களை(Strings) ஒன்றாக இணைப்பதற்கு +
+"Hello " + "world!"; // = "Hello world!"
+
+// இரண்டு மாறிகளை/பெறுமானங்களை ஒப்பிட < and >
+"a" < "b"; // = true
+
+// இரண்டு பெறுமானங்கள் / மாறிகள் ஒரேவகையை சேர்ந்தவையா என பார்க்க
+"5" == 5; // = true
+null == undefined; // = true
+
+// ...இல்லாவிடின் ===
+"5" === 5; // = false
+null === undefined; // = false
+
+// ...கிழே உள்ள கூற்றுகள் எதிர்பாராத
+வெளியீடுகளை தரலாம் ...
+13 + !0; // 14
+"13" + !0; // '13true'
+
+// ஒரு சரத்தில்(string ) உள்ள எழுத்தை பெற `charAt`
+"This is a string".charAt(0); // = 'T'
+
+
+//... ஒரு சரத்தை(string ) சொற்களாக பிரிக்க (substring) `substring
+"Hello world".substring(0, 5); // = "Hello"
+
+// `length` ஒரு சரத்தில்(string) உள்ள சொற்களின் எண்ணிக்கை அல்லது நீளத்தை(length)அறிய
+"Hello".length; // = 5
+
+// `null` மற்றும் `undefined` இரு பெறுமானங்கள் உள்ளன .
+null; // மதிப்பு அற்ற ஒரு பெறுமானத்தை குறிக்கும்
+undefined; // பெறுமானம் இன்னும் நிர்ணயிக்க படவில்லை என்பதை குறிக்கும் (
+ // `undefined` இருப்பினும் இதுவும் ஒரு பெறுமானமாக கருதபடுகிறது )
+
+// ஆகியன தர்க்க ரீதியாக பிழையானவை(false) , மற்றவை யாவும் சரியானவை (true).
+// 0 மானது பிழையை (false) குறிக்கும் "0" சரியை (true) குறிக்கும் எனினும் 0 == "0".
+
+///////////////////////////////////
+// 2. மாறிகள் (Variables),அணிகள் (Arrays) மற்றும் பொருட்கள் (Objects)
+
+// மாறிகளை உருவாக்க `var ` என்னும் குறியீட்டு சொல் (keyword ) பயன்படுகிறது .
+//உருவாக்கப்படும் மாறிகள் எந்த வகையை சார்ந்தன என்பதை JavaScript
+//தானாகவே நிர்ணயிக்கும் . மாறிக்கு ஒரு பெறுமானத்தை வழங்க `=` பாவிக்க
+var someVar = 5;
+
+// //நீங்கள் மாறிகளை நிறுவ 'var' குறியீட்டு சொல்லை பயன்படுத்தா விடினும்
+//அது தவறில்லை ...
+someOtherVar = 10;
+
+// ...ஆனால் நீங்கள் நிறுவிய மாறி(variable) எல்லா உங்கள் ப்ரோக்ராம் இன் சகல இடங்களிலும்
+//அணுக கூடியதாய் அமையும் , இல்லாவிடின் அது ஒரு குறிபிட்ட இடத்திற்கு மட்டும்
+//மட்டுபடுத்தபடும் .
+
+//பெறுமானம் வழங்கபடாத மாறிகளுக்கு ,இயல்பாக/தானாக undefined என்ற பெறுமானம்
+//வழங்கப்படும்
+var someThirdVar; // = undefined
+
+// மாறிகளில் கணித செயல்பாடுகளை நடத்த சுருக்கெழுத்து முறைகள் காணப்படுகின்றன :
+someVar += 5; // இது someVar = someVar + 5; ஐ ஒத்தது someVar இன் பெறுமானம் இப்போது 10
+someVar *= 10; // someVar இன் பெறுமானம் இப்போது 100
+
+//மிகவும் சுருக்கமான சுருகேழுத்து முறை கூட்டல் அல்லது கழித்தல் செயன்முறையை
+//மேற்கொள்ள
+someVar++; // someVar இன் பெறுமானம் இப்போது is 101
+someVar--; // someVar இன் பெறுமானம் இப்போது 100
+
+// அணிகள்(Arrays) எல்லாவகையான பெறுமானங்களையும் உள்ளடக்க கூடியது
+var myArray = ["Hello", 45, true];
+
+// அணிகள்(Arrays) உறுப்பினர்கள் சதுர அடைப்புக்குறிக்குள் அதன் தான இலக்கத்தை கொண்டு
+//அணுகமுடியும் .
+// அணிகளில் உள்ள உறுப்புகள் 0 இருந்து ஆரம்பமாகும் .
+myArray[1]; // = 45
+
+// அணிகள் உள்ள உறுப்புகளை மாற்றமுடியும் அத்துடன் உறுப்புகளின் எண்ணிக்கையும் மாறலாம் .
+myArray.push("World");
+myArray.length; // = 4
+
+// அணியில்(Array) ஒரு குறிப்பிட்ட இடத்தில உள்ள பெறுமானத்தை மாற்ற .
+myArray[3] = "Hello";
+
+// JavaScript's பொருள் (objects) அகராதியை ஒத்தன
+// ஒழுங்கு படுத்த படாத சேகரிப்பு (collection) ஆகும் இதில் ஒரு சாவியும்(key)
+//அதுக்குரிய பெறுமானமும்(value) காணப்படும் .
+var myObj = {key1: "Hello", key2: "World"};
+
+// விசைகள் சரங்களை, ஆனால் அவர்கள் சரியான என்றால் மேற்கோள் அவசியம் இல்லை
+//சாவிகளை உ.ம் : "key" என நிறுவலாம் ஆனால் , மேற்கோள் ஆனது சாவி முன்பே நிறுவபட்டிருப்பின்
+//அவசியம் இல்லை
+// சாவிகளுக்குரிய பெறுமானங்கள் எந்த வகையாகவும் இருக்கலாம்
+var myObj = {myKey: "myValue", "my other key": 4};
+
+//பொருள் பண்புகளை சதுர அடைப்புக்குறிக்குள் அதன் சாவியின் பெயரை (key) கொண்டு
+//அணுகமுடியும் ,
+myObj["my other key"]; // = 4
+
+// ... அல்லது புள்ளி குறியீட்டை பயன்படுத்தி ,சாவியின் (key is a valid identifier)
+//பெயர் மூலம் அணுக முடியும்
+myObj.myKey; // = "myValue"
+
+// பொருட்கள்(ஒப்ஜெக்ட்ஸ்) மாற்றபடகூடியான சாவிகளின் பெறுமதிகளை மாற்ற முடியும் அத்துடன் புதிய
+//சாவிகளை(keys) இடவும் முடியும்
+myObj.myThirdKey = true;
+
+//பெறுமதி வரையறுக்கபடாத ஒரு சாவியினை அணுகும் போது
+//அது வெளியிடும் பெறுமதி `undefined`.
+myObj.myFourthKey; // = undefined
+
+///////////////////////////////////
+// 3. தர்க்கம் மற்றும் கட்டுப்பாட்டு கட்டமைப்பு
+
+// கீழே காட்டப்பட்டுள்ள தொடரியல் ஜாவா வை ஒத்தது
+
+// The `if` ஒரு குறித்த தர்க்கம் சரியாயின்
+//அல்லது என்ற வடிவமைப்பை
+var count = 1;
+if (count == 3){
+ // count இன் பெறுமானம் 3 சமமா என பார்க்கபடுகிறது
+} else if (count == 4){
+ // count இன் பெறுமானம் 4க்கு சமமா என பார்க்கபடுகிறது
+} else {
+ // count ஆனது 3 அல்ல 4 அல்ல எனின்
+}
+
+// ஒரு குறிப்பிட்ட ஒப்பீடு உண்மையாக இருக்கும் வரை `while`.
+while (true){
+ // இந்த இருக்கும் கூற்றுகள் முடிவிலி தடவை மறுபடி செயற்படுத்தப்படும் !
+}
+
+// while போல் அல்லாது do-while ,அவை ஒரு தடவையேனும் அதனுள் உள்ள கூற்றுகள் செயற்படுத்தபடும்
+var input;
+do {
+ input = getInput();
+} while (!isValid(input))
+
+// for (loop /சுற்று ) C , ஜாவாவை ஒத்தது
+//மாறிக்கு பெறுமானத்தை வழங்கல் , மாறியானது தர்க்கத்தை பூர்த்தி செய்கிறதா என பார்த்தல் ,
+//சுற்றுக்குள் இருக்கும் கூற்றை செயற்படுதல்
+
+for (var i = 0; i < 5; i++){
+ // இந்த சுற்று 5 தடவைகள் தொடர்ந்து செயற்படுத்தபடும்
+}
+
+//for /In சுற்றுகள் prototype சங்கிலியில் உள்ள சகல காரணிகள் ஊடகவும் செல்லும்
+var description = "";
+var person = {fname:"Paul", lname:"Ken", age:18};
+for (var x in person){
+ description += person[x] + " ";
+}
+
+//ஒரு பொருளில் (Object) இடப்பட்ட பண்புகளை (properties) கருத்தில் கொள்ளும் போது
+//குறிப்பிட்ட பண்புகளை அந்த Object கொண்டுள்ளதா என பார்க்க
+var description = "";
+var person = {fname:"Paul", lname:"Ken", age:18};
+for (var x in person){
+ if (person.hasOwnProperty(x)){
+ description += person[x] + " ";
+ }
+}
+
+//for /in ஆனது அணியில் உள்ள பண்புகள் ஒழுங்குபடுத்தப்பட்டவிதம் முக்கியம்
+//ஆயின் பாவிப்பதை தவிர்க்கவும் ஏனெனில் அது சரியான ஒழுங்கில்
+//வெளியீட்டை தரும் என்பது ஐயம் ஆகும்
+
+// && is logical and, || is logical or
+if (house.size == "big" && house.colour == "blue"){
+ house.contains = "bear";
+}
+if (colour == "red" || colour == "blue"){
+ // colour is either red or blue
+}
+
+// && and || "short circuit", which is useful for setting default values.
+var name = otherName || "default";
+
+
+
+grade = 'B';
+switch (grade) {
+ case 'A':
+ console.log("Great job");
+ break;
+ case 'B':
+ console.log("OK job");
+ break;
+ case 'C':
+ console.log("You can do better");
+ break;
+ default:
+ console.log("Oy vey");
+ break;
+}
+
+
+///////////////////////////////////
+// 4. Functions, Scope and Closures
+
+// JavaScript இல் functions நிறுவ `function` keyword.பயன்படும்
+function myFunction(thing){
+ return thing.toUpperCase();
+}
+myFunction("foo"); // = "FOO"
+
+//ஒரு பெறுமானத்தை return செய்ய வேண்டும் எனின் இரண்டும் ஒரே வரியில்
+//இருக்க வேண்டும் இல்லாவிடின் return ஆனது `undefined ` return செய்யும்
+//காற் புள்ளி தானாகவே இடப்படும் , நீங்கள் Allman style உபயோகிக்கும் போது
+//அவதானமாக இருக்கவும்
+function myFunction()
+{
+ return // <- semicolon automatically inserted here
+ {
+ thisIsAn: 'object literal'
+ }
+}
+myFunction(); // = undefined
+
+// JavaScript functions ஆனது first class objects ஆகும் ,எனவே அவற்றை மாறிகளுக்கு
+//assign செய்ய முடியும் அதுமட்டும் அல்லது functions களில் arguments ஆக அனுப்பமுடியும்
+// உதாரணமாக ஒரு event handler:
+function myFunction(){
+ //இந்த code 5 செக்கன்களில் செயற்படுத்தப்படும்
+}
+setTimeout(myFunction, 5000);
+// Note: setTimeout ஆனது ஜாவஸ்க்ரிப்ட் சேர்ந்தது அன்று , ஆனால் அந்த வசதி
+//உலாவிகளிலும் ,Node .js காணப்படுகிறது
+
+// Function objects கட்டாயம் பெயரிடப்பட வீண்டும் என்று அவசியம் இல்லை
+// அவை anonymous(பெயரிடப்படாமல்) உருவாக்கபடலாம்
+setTimeout(function(){
+ //இந்த code 5 செக்கன்களில் செயற்படுத்தப்படும்
+}, 5000);
+
+// JavaScript function ஒரு குறிப்பிட்ட scope(எல்லை) கொண்டுள்ளது ;
+//functions தமக்கென ஒரு scope கொண்டுள்ளன .
+
+if (true){
+ var i = 5;
+}
+i; // = 5 - //இது undefined அல்ல
+
+// இதன் காரணமாக anonymous functions உடனடியாக செயற்படுத்தபடுகின்றன
+//இதன் மூலம் தற்காலிக மாறிகள்(variable) குளோபல் scope
+//இற்கு மாறுவதை தவிர்க்கலாம் .
+(function(){
+ var temporary = 5;
+ //நாங்கள் ஒரு மாறியை எங்கிருந்தும் அணுக (access) அதை "global object"
+ //ஒன்றுக்கு வழங்க வேண்டும் உலாவியில் அது எப்போதும் `window` ஆகும் .
+ //உலாவி அல்லாத சூழலில் (Node.js) வேறு பெயருடன் இருக்கும்
+ window.permanent = 10;
+})();
+temporary; // raises ReferenceError
+permanent; // = 10
+
+//JavaScript's மிகவும் சக்தி வாய்ந்த ஒரு வசதி closures ஆகும்
+//ஒரு function இன்னொரு function உள் உருவாக்கபடின்
+//அது உருவாகப்பட்ட function இன் மாறிகளை அணுக முடியும்
+function sayHelloInFiveSeconds(name){
+ var prompt = "Hello, " + name + "!";
+ // Inner functions ஆனது local scope இல் காணப்படும்
+ //அது `var ` என்ற குறியீட்டு சொல்லால் நிறுவப்படும்
+ function inner(){
+ alert(prompt);
+ }
+ setTimeout(inner, 5000);
+ //setTimeout ஆனது background இல் இயங்கும் , எனவே sayHelloInFiveSeconds function,
+ //செயற்பாடு முடிவடைய ,setTimeout ஆனது inner function call செய்யும்.
+
+}
+sayHelloInFiveSeconds("Adam"); // //இது ஒரு popup ஐ ஐந்து செக்கன்களில் காட்டும்
+
+///////////////////////////////////
+// 5. Objects; Constructors and Prototypes பற்றி மேலும்
+
+// Objects functions ஐ கொண்டிருக்கலாம்
+var myObj = {
+ myFunc: function(){
+ return "Hello world!";
+ }
+};
+myObj.myFunc(); // = "Hello world!"
+
+//functions ஆனது objects உடன் இணைக்கப்பட்டுள போது அவை object ஐ அணுக முடியும்
+//அவை this என்ற குறியீட்டு சொல்லை பயன்படுத்தி இணைக்கபடுகின்றன
+myObj = {
+ myString: "Hello world!",
+ myFunc: function(){
+ return this.myString;
+ }
+};
+myObj.myFunc(); // = "Hello world!"
+
+//எங்கள் function ஆனது தொழிற் படாமல் போகலாம் அது context(அமைப்பு ) of the object call செய்யபடவிடின்
+var myFunc = myObj.myFunc;
+myFunc(); // = undefined
+
+
+//function ஆனது ஒரு object உக்கு assign செய்யலாம் பிறகு அதை நாம் அணுகமுடியும்
+//`this` மூலம்
+var myOtherFunc = function(){
+ return this.myString.toUpperCase();
+}
+myObj.myOtherFunc = myOtherFunc;
+myObj.myOtherFunc(); // = "HELLO WORLD!"
+
+//ஒரு function ஒரு அமைப்பை நாம் உருவாக்க முடியும்
+//அதை நாம் `call` அல்லது `apply` மூலம் செயல்படுத்த முடியும்
+
+var anotherFunc = function(s){
+ return this.myString + s;
+}
+anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"
+
+//apply செயற்பாட்டளவில் ஒத்தன ,ஆனால் அது array (அணி) argument
+//ஆக எடுக்கிறது.
+
+anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!"
+
+//இது தொடர்ச்சியான arguments ஐ நாம் function ஒன்றுக்குள் pass பண்ண
+//வேண்டும் எனில் மிகவும் உபயோகமானது
+
+Math.min(42, 6, 27); // = 6
+Math.min([42, 6, 27]); // = NaN (uh-oh!)
+Math.min.apply(Math, [42, 6, 27]); // = 6
+
+//ஆனால் `call ` ,`apply ` இரண்டும் தற்காலிகமானவை
+//அவற்றை நிரந்தரமாக்க bind function ஐ பயன்படுத்தவும்
+
+var boundFunc = anotherFunc.bind(myObj);
+boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!"
+
+//`bind ` ஐ உபயோகித்து ஒரு function ஐ பகுதியாக apply செய்ய முடியும்
+
+var product = function(a, b){ return a * b; }
+var doubler = product.bind(this, 2);
+doubler(8); // = 16
+
+
+//ஒரு function ஐ நாம் new என்ற குறியீட்டு சொல்லை பயன்படுத்தி
+//அழைக்கும் போது புதிய object உருவாக்கப்படும் .இவ்வாறான functions
+//constructors என அழைக்கப்படும்
+
+var MyConstructor = function(){
+ this.myNumber = 5;
+}
+myNewObj = new MyConstructor(); // = {myNumber: 5}
+myNewObj.myNumber; // = 5
+
+//ஒவ்வொரு JavaScript object உம் ஒரு `prototype ` கொண்டுள்ளது
+//நீங்கள் object ஒன்றின் ஒரு property ஐ அணுகும் போது
+//அந்த property இல்லாவிடின் interpreter ஆனது
+//அதன் prototype உள்ளதா என பார்க்கும்
+
+//JS இன் சில செயலாக்கங்கள் ஒரு object இன் protoype ஐ
+//இலகுவாக `__proto__` மூலம் access செய்ய முடியும் .
+//இது prototype பாவணை யை இலகுவாக்கினாலும்
+//இது சரியான ஒரு முறை அல்ல
+var myObj = {
+ myString: "Hello world!"
+};
+var myPrototype = {
+ meaningOfLife: 42,
+ myFunc: function(){
+ return this.myString.toLowerCase()
+ }
+};
+
+myObj.__proto__ = myPrototype;
+myObj.meaningOfLife; // = 42
+
+// This works for functions, too.
+myObj.myFunc(); // = "hello world!"
+
+//உங்கள் property prototype இல் இல்லது இருப்பின் , protype இன்
+//prototype search செய்யப்படும்
+myPrototype.__proto__ = {
+ myBoolean: true
+};
+myObj.myBoolean; // = true
+
+//ஒவ்வொரு object உம் அதன் protype க்கும் reference (மேற்கோள் ) ஒன்றை வைத்திருக்கும்
+//நாம் ஒரு protype இணை மாற்றினால் அதன் மாற்றங்கள் எல்லா இடத்திலும் (program இல் )
+//பிரதிபலிக்கும்
+myPrototype.meaningOfLife = 43;
+myObj.meaningOfLife; // = 43
+
+
+//நாம் முன்பு கூறியது போல் `__proto__` பயன்படுத்துவது சரியான முறை அல்ல
+//எனவே நாம் ஒரு protype ஐ object இல் உருவாக்க இரண்டு வழிமுறைகள்
+//உள்ளன
+
+// முதல் முறை Object.create இது அண்மையில் அறிமுகம் செய்ய பட்ட ஒன்று
+//எனவே சில இடங்களில் இந்த முறை இன்னும் அறிமுகம் ஆகவில்லை
+
+var myObj = Object.create(myPrototype);
+myObj.meaningOfLife; // = 43
+
+
+// இரண்டாவது முறை , இது சகல இடங்களிலும் வேலைசெய்யும், இது constructors மூலம்.
+//constructors prototype என்னும் ஒரு காரணியை கொண்டுள்ளது , இது constructor function
+//இன் prototype அன்று. ,இது நாம் new என்ற குறியீட்டு சொல்லையும் அந்த constructor உபயோகித்து
+//உருவாக்கபடுகிறது
+
+MyConstructor.prototype = {
+ myNumber: 5,
+ getMyNumber: function(){
+ return this.myNumber;
+ }
+};
+var myNewObj2 = new MyConstructor();
+myNewObj2.getMyNumber(); // = 5
+myNewObj2.myNumber = 6
+myNewObj2.getMyNumber(); // = 6
+
+// Built-in types like strings and numbers also have constructors that create
+// equivalent wrapper objects.
+// JavaScript இல் உள்ள strings மற்றும் numbers வகைகளும் constructors கொண்டுள்ளன
+//இவை wrapper objects ஐ ஒத்தன
+
+var myNumber = 12;
+var myNumberObj = new Number(12);
+myNumber == myNumberObj; // = true
+
+
+//இவை மிக சிறிய அளவில் ஒத்தவை
+typeof myNumber; // = 'number'
+typeof myNumberObj; // = 'object'
+myNumber === myNumberObj; // = false
+if (0){
+ // இந்த கூற்றானது செயல்படுத்தபடாது ஏனெனில் ௦ false ஆகும்
+}
+
+// However, the wrapper objects and the regular builtins share a prototype, so
+// you can actually add functionality to a string, for instance.
+
+//இருப்பினும் wrapper objects மற்றும் regular builtins ஆகியன prototype ஒன்றை கொண்டுள்ளன
+String.prototype.firstCharacter = function(){
+ return this.charAt(0);
+}
+"abc".firstCharacter(); // = "a"
+
+// This fact is often used in "polyfilling", which is implementing newer
+// features of JavaScript in an older subset of JavaScript, so that they can be
+// used in older environments such as outdated browsers.
+
+//இந்த முறையானது "polyfilling" இல் உபயோகபடுத்தபடுகிறது.
+//புதிய சில வசதிகளை JavaScript பழைய JavaScript பிரதிகளில் இல் உருவாக்குகிறது.
+//இது பழைய சூழல்களில் உபயோகிகப்படும்.
+
+
+//நாங்கள் முன்பு கூறி இருந்தோம் Object.create சில இடங்களில் இந்த முறை இன்னும்
+//அறிமுகம் ஆகவில்லை என்று ஆனால் இதை polyfill ஐ பயன்படுத்தி உருவாக்க
+//முடியும்
+
+if (Object.create === undefined){ // don't overwrite it if it exists
+ Object.create = function(proto){
+ // make a temporary constructor with the right prototype
+ var Constructor = function(){};
+ Constructor.prototype = proto;
+ // then use it to create a new, appropriately-prototyped object
+ return new Constructor();
+ }
+}
+```
+
+## மேலும் JavaScript பற்றி கற்க
+
+The [Mozilla Developer
+Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides
+excellent documentation for JavaScript as it's used in browsers. Plus, it's a
+wiki, so as you learn more you can help others out by sharing your own
+knowledge.
+
+MDN's [A re-introduction to
+JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
+covers much of the concepts covered here in more detail. This guide has quite
+deliberately only covered the JavaScript language itself; if you want to learn
+more about how to use JavaScript in web pages, start by learning about the
+[Document Object
+Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)
+
+[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges.
+
+[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth
+guide of all the counter-intuitive parts of the language.
+
+[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book.
+
+In addition to direct contributors to this article, some content is adapted
+from Louie Dinh's Python tutorial on this site, and the [JS
+Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
+on the Mozilla Developer Network.
diff --git a/ta_in/json-ta.html.markdown b/ta_in/json-ta.html.markdown
new file mode 100644
index 00000000..d85e0d82
--- /dev/null
+++ b/ta_in/json-ta.html.markdown
@@ -0,0 +1,86 @@
+---
+language: json
+filename: learnjson.json
+contributors:
+ - ["Anna Harren", "https://github.com/iirelu"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["himanshu", "https://github.com/himanshu81494"]
+translators:
+ - ["Rasendran Kirushan", "https://github.com/kirushanr"]
+lang: ta-in
+---
+
+ஜேசன் ஒரு ஒரு மிக எளிய தரவு உள்மாற்றீட்டு வடிவம் ஆகும்.
+Learn X in Y Minutes இதுவே மிகவும் இலகுவான பகுதியாக அமைய போகிறது.
+
+
+ஜேசன் இன் எளிமையான கட்டமைப்பில் குறிப்புக்கள் (Comments) இல்லை , எனினும்
+பெரும்பாலான பாகுபடுத்திகளில் C - style முறையிலான (`//`, `/* */`) குறிப்புகளை இட முடியும்.
+சில பாகுபடுத்திகள்(interpreter) குறிப்புகளுக்கு (comments)தொடர்ச்சியாக வரும்
+ காற்புள்ளியை அனுமதிக்கின்றன (உதாரணமாக ஒரு அணியை (array) அடுத்துவரும் காற்புள்ளி
+ அல்லது ஒரு பொருளில் (object)உள்ள கடைசி உறுப்பை/சொத்தை( last property) அடுத்து வரும் காற்புள்ளி )
+எனினும் சகல இடங்களிலும் ஜேசன் பயன்படுத்த பட வேண்டும் எனில் மேற்கூறிய குறிப்புகளை தவிர்த்தல் நல்லது .\
+
+
+ஜேசன் 100% மிக சரியாக அமைவது மட்டும் இன்றி
+இலகுவாக புரியக் கூடிய எளிய தரவு உள்மாற்றீட்டு வடிவம் ஆகும்.
+
+
+ஜேசன் அனுமதிக்கும் தரவு வகைகள் : சரம் (string),முழு (int),பூலியன் (தர்க ரீதியில் ஆன கட்டமைப்பு),
+அணி (array ),கழி (null ),பொருள் (object).
+
+ஜேசன் அனுமதிக்கும் அல்லது பாவனைக்கு உட்படுத்த கூடிய உலாவிகள் (browsers):
+Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4.
+
+ஜேசனின் கோப்புவகை(filetype) ".json " ஆகும் .
+
+ஜேசன் உரைக்கான MIME வகை "application/json" ஆகும்.
+ஜேசன் இல் காணப்படும் பிரதான பின்னடைவு தரவு இனம் இதுவென்று வரையறுக்க
+படாமை ஆகும் .
+
+ஒரு ஜேசன் இன் எளிய கட்டமைப்பு கீழே காட்டப்பட்டுள்ளது
+
+```json
+{
+ "key": "ஒரு சாவிக்கு ஒரு பெறுமதி உள்ளது ",
+
+ "keys": "சாவிகள் , மற்றும் பெறுமானங்கள் மேற்கோள் குறிக்குள் இடல் வேண்டும்",
+ "numbers": 0,
+ "strings": "Hellø, wørld. எல்லாவகையான unicode உம் அனுமதிக்கப்படும், அத்துடன் \"escaping\".",
+ "has bools?": true,
+ "nothingness": null,
+
+ "big number": 1.2e+100,
+
+ "objects": {
+ "comment": "பெரும்பாலான கட்டமைப்புகள் objects இல் இருந்தே வருகின்றன",
+
+ "array": [0, 1, 2, 3, "array யானது எல்லாவகையான பெறுமானங்களையும் கொண்டிருக்கும்", 5],
+
+ "another object": {
+ "comment": "இவை ஒன்றுக்குள் இன்னொன்றை எழுத முடியும்"
+ }
+ },
+
+ "silliness": [
+ {
+ "sources of potassium": ["வாழைபழம்"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "neo"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "alternative style": {
+ "comment": "இதை பார்க்கவும்"
+ , "comma position": "doesn't matter - as long as it's before the value, then it's valid"
+ , "another comment": "how nice"
+ },
+
+ "that was short": "நீங்கள் ஜேசன் பற்றி யாவற்றையும் கற்றுள்ளீர்கள்"
+}
+```
+
diff --git a/ta_in/xml-ta.html.markdown b/ta_in/xml-ta.html.markdown
new file mode 100644
index 00000000..d782399d
--- /dev/null
+++ b/ta_in/xml-ta.html.markdown
@@ -0,0 +1,145 @@
+---
+language: xml
+filename: learnxml-ta.xml
+contributors:
+ - ["João Farias", "https://github.com/JoaoGFarias"]
+translators:
+ - ["Rasendran Kirushan", "https://github.com/kirushanr"]
+lang: in-ta
+---
+
+
+XML ஆனது ஒரு கட்டமைப்பு மொழி ஆகும் இது தகவலை சேமிக்கவும்
+தகவலை பரிமாறவும் உருவாக்கபட்டுள்ளது
+
+
+HTML போல் அன்றி , XML ஆனது தகவலை மட்டும் கொண்டு செல்ல்கிறது
+* XML வாக்கிய அமைப்பு
+
+
+```xml
+<!-- இது ஒரு XML குறிப்பு -->
+
+<?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>
+
+
+ <!--
+
+ மேல காட்டப்பட்டுள்ளது ஒரு xml file இன் உதாரணம் ஆகும்
+ அது metadata உடன் ஆரம்பமாகிறது
+ XML ஆனது ஒரு மரத்தை போன்ற கட்டமைப்பை ஒத்தது.
+ இங்கு root node (கொப்பு) `bookstore` இது மூன்று கிளைகள் (child nodes)
+ கொண்டுள்ளது. இந்த கிளைகள் மேலும் சில கிளைகளை கொண்டு இருக்கலாம்
+ ஒவொரு node கட்டமைப்பும் ஒரு `<` ஆரம்பாமாகி `>` முடிவடையும்
+ கிளைகள் இந்த கட்டமைப்புக்கு இடையில் நிறுவப்படும்
+ -->
+
+
+<!--
+XML இரண்டு வகையான தகவல்களை கொண்டு செல்லக்கூடியது
+1- Attributes -> ஒரு கணு(node) பற்றிய metadata
+பொதுவாக XML Parser இந்த தகவலை பயன்படுத்தியே தகவலை
+சரியான முறையில் சேமிக்க.
+இது xml கட்டமைப்பின் ஆரம்பத்தில் உள்ள name="value"
+தீர்மானிக்கபடுகிறது.
+
+2-Elements ->இவற்றில் முற்றிலும் தகவல்களே சேமிக்கபட்டு இருக்கும்
+Elements ஒரு `<` ஆரம்பாமாகி `>` முடிவடையும் காணப்படும்
+
+
+-->
+
+<!-- கிழே உள்ள element இரண்டு பெறுமானங்களை கொண்டுள்ளது -->
+<file type="gif" id="4293">computer.gif</file>
+
+
+```
+
+* சரியான முறையில் ஒழுகுபடுத்தபட்ட X document
+
+
+ஒரு XML document ஆனது சரியான முறையில் எழுத பட்டிருப்பின் மட்டுமே அது
+சிறந்த வகையில் வடிவமைக்கபட்டுள்ளது,எனினும் மேலும் பல கட்டுபாடுகளை
+நாம் ஒரு xml document உக்கு இட முடியும் உ.ம்:-DTD மற்றும் XML Schema.
+
+
+ஒரு xml document ஆனது ஒரு வரையறுக்கபட்டிருப்பின் மட்டுமே
+அது சரி என கொள்ளப்படும்
+
+
+With this tool, you can check the XML data outside the application logic.
+இந்த கருவியை உபயோகித்து xml தகவல்களை சோதிக்க முடியும்
+
+```xml
+
+<!-- கீழே bookstore html document இன் எளிமையான வடிவம்
+ 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 ஆனது பின்வருமாறு அமையும் :-->
+
+<!DOCTYPE note
+[
+<!ELEMENT bookstore (book+)>
+<!ELEMENT book (title,price)>
+<!ATTLIST book category CDATA "Literature">
+<!ELEMENT title (#PCDATA)>
+<!ELEMENT price (#PCDATA)>
+]>
+
+
+<!-- DTD ஆனது root node ஐ உருவாக்கிய பின் நிறுவ படுகிறது ,இது ஒன்று அல்லது
+ஒன்றிக்கு மேற்பட்ட child node களை எதிர்பார்க்கிறது.
+ ஒவ்வொரு 'book' உம் கட்டாயமாக ஒரு 'title' , 'price','category', with "Literature"
+ ஆகிய பெறுமானங்களை கொண்டிருத்தல் அவசியம்.
+-->
+
+<!-- DTD ஆனது xml file ஒன்றினுள் உருவாக்கபடுகிறது-->
+
+<?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/tmux.html.markdown b/tmux.html.markdown
index c11da5fc..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
@@ -38,7 +38,7 @@ then later reattached.
lsp # List panes
-a # List all panes
-s # List all panes in session
- -t # List app panes in target
+ -t # List all panes in target
kill-window # Kill current window
-t "#" # Kill target window
@@ -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)
@@ -249,3 +249,7 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] |
[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux)
[Display CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux)
+
+[tmuxinator - Manage complex tmux sessions](https://github.com/tmuxinator/tmuxinator)
+
+
diff --git a/tr-tr/brainfuck-tr.html.markdown b/tr-tr/bf-tr.html.markdown
index baca4217..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"]
@@ -19,7 +19,7 @@ gözardı edilir.
Brainfuck 30,000 hücresi olan ve ilk değerleri sıfır olarak atanmış bir
dizidir. İşaretçi ilk hücreyi işaret eder.
-Sekik komut vardır:
+Sekiz komut vardır:
+ : Geçerli hücrenin değerini bir artırır.
- : Geçerli hücrenin değerini bir azaltır.
> : Veri işaretçisini bir sonraki hücreye hareket ettirir(sağdaki hücreye).
diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown
index 128901de..2d4240ed 100644
--- a/tr-tr/c-tr.html.markdown
+++ b/tr-tr/c-tr.html.markdown
@@ -91,9 +91,9 @@ int main() {
// Örneğin,
printf("%lu\n", sizeof(int)); // => 4 (bir çok makinede 4-byte words)
- // If the argument of the `sizeof` operator an expression, then its argument
- // is not evaluated (except VLAs (see below)).
- // The value it yields in this case is a compile-time constant.
+ // Eger arguman düzenli ifae olan sizeof operatoru ise degerlendirilmez.
+ // VLAs hariç asagiya bakiniz).
+ // Bu durumda verimliligin degeri derleme-zamani sabitidir.
int a = 1;
// size_t bir objeyi temsil etmek için kullanılan 2 byte uzunluğundaki bir
@@ -101,7 +101,7 @@ int main() {
size_t size = sizeof(a++); // a++ is not evaluated
printf("sizeof(a++) = %zu where a = %d\n", size, a);
- // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture)
+ // yazdirilan "sizeof(a++) = 4 where a = 1" (32-bit mimaride)
// Diziler somut bir boyut ile oluşturulmalıdır.
char my_char_array[20]; // Bu dizi 1 * 20 = 20 byte alan kaplar
@@ -119,19 +119,19 @@ int main() {
my_array[1] = 2;
printf("%d\n", my_array[1]); // => 2
- // In C99 (and as an optional feature in C11), variable-length arrays (VLAs)
- // can be declared as well. The size of such an array need not be a compile
- // time constant:
- printf("Enter the array size: "); // ask the user for an array size
+ // C99'da (ve C11 istege bagli bir ozellik olarak), değidken-uzunluklu diziler (VLAs) bildirilebilirler.
+ // Böyle bir dizinin boyuunu derlenmesi gerekmez
+ // zaman sabiti:
+ printf("Enter the array size: "); // dizi boyutu kullaniciya soruluyor
char buf[0x100];
fgets(buf, sizeof buf, stdin);
- // strtoul parses a string to an unsigned integer
+ // strtoul isaretsiz integerlar icin string ayiricisidir.
size_t size = strtoul(buf, NULL, 10);
int var_length_array[size]; // declare the VLA
printf("sizeof array = %zu\n", sizeof var_length_array);
- // A possible outcome of this program may be:
+ // Bu programın olası bir sonucu olabilir:
// > Enter the array size: 10
// > sizeof array = 40
@@ -151,8 +151,8 @@ int main() {
printf("%d\n", a_string[16]); // => 0
// i.e., byte #17 is 0 (as are 18, 19, and 20)
- // If we have characters between single quotes, that's a character literal.
- // It's of type `int`, and *not* `char` (for historical reasons).
+ // Tek tirnak arasinda karakterlere sahipsek, bu karakterler degismezdir.
+ // Tip `int` ise, `char` *degildir* (tarihsel sebeplerle).
int cha = 'a'; // fine
char chb = 'a'; // fine too (implicit conversion from int to char)
@@ -201,10 +201,10 @@ int main() {
0x01 << 1; // => 0x02 (bitwise left shift (by 1))
0x02 >> 1; // => 0x01 (bitwise right shift (by 1))
- // Be careful when shifting signed integers - the following are undefined:
- // - shifting into the sign bit of a signed integer (int a = 1 << 32)
- // - left-shifting a negative number (int a = -1 << 2)
- // - shifting by an offset which is >= the width of the type of the LHS:
+ // Isaretli sayilari kaydirirken dikkatli olun - tanimsizlar sunlardir:
+ // - isaretli sayinin isaret bitinde yapilan kaydirma (int a = 1 << 32)
+ // - negatif sayilarda sol kaydirma (int a = -1 << 2)
+ // - LHS tipinde >= ile olan ofset genisletmelerde yapilan kaydirma:
// int a = 1 << 32; // UB if int is 32 bits wide
///////////////////////////////////////
@@ -485,4 +485,4 @@ Readable code is better than clever code and fast code. For a good, sane coding
Diğer taraftan google sizin için bir arkadaş olabilir.
-[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file
+[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member
diff --git a/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/objective-c-tr.html.markdown b/tr-tr/objective-c-tr.html.markdown
index f27cbf08..727f973e 100644
--- a/tr-tr/objective-c-tr.html.markdown
+++ b/tr-tr/objective-c-tr.html.markdown
@@ -14,7 +14,7 @@ kendi çatıları olan Cocoa ve Cocoa Touch için kullanılan bir programlama di
Genel açamlı, object-oriented bir yapıya sahip programlama dilidir. C
programlama diline Smalltalk stilinde mesajlaşma ekler.
-```objective_c
+```objective-c
// Tek satır yorum // işaretleri ile başlar
/*
diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown
index 2477c5da..c7de2922 100644
--- a/tr-tr/python3-tr.html.markdown
+++ b/tr-tr/python3-tr.html.markdown
@@ -538,7 +538,7 @@ Insan.grunt() # => "*grunt*"
# Modülleri içe aktarabilirsiniz
import math
-print(math.sqrt(16)) # => 4
+print(math.sqrt(16)) # => 4.0
# Modülden belirli bir fonksiyonları alabilirsiniz
from math import ceil, floor
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 e9135510..47e41405 100644
--- a/typescript.html.markdown
+++ b/typescript.html.markdown
@@ -83,23 +83,23 @@ mySearch = function(src: string, sub: string) {
// Classes - members are public by default
class Point {
// Properties
- x: number;
+ x: number;
- // Constructor - the public/private keywords in this context will generate
- // the boiler plate code for the property and the initialization in the
- // constructor.
- // In this example, "y" will be defined just like "x" is, but with less code
- // Default values are also supported
+ // Constructor - the public/private keywords in this context will generate
+ // the boiler plate code for the property and the initialization in the
+ // constructor.
+ // In this example, "y" will be defined just like "x" is, but with less code
+ // Default values are also supported
- constructor(x: number, public y: number = 0) {
- this.x = x;
- }
+ constructor(x: number, public y: number = 0) {
+ this.x = x;
+ }
- // Functions
- dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
+ // Functions
+ dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
- // Static members
- static origin = new Point(0, 0);
+ // Static members
+ static origin = new Point(0, 0);
}
var p1 = new Point(10 ,20);
@@ -107,15 +107,15 @@ var p2 = new Point(25); //y will be 0
// Inheritance
class Point3D extends Point {
- constructor(x: number, y: number, public z: number = 0) {
- super(x, y); // Explicit call to the super class constructor is mandatory
- }
+ constructor(x: number, y: number, public z: number = 0) {
+ super(x, y); // Explicit call to the super class constructor is mandatory
+ }
- // Overwrite
- dist() {
- var d = super.dist();
- return Math.sqrt(d * d + this.z * this.z);
- }
+ // Overwrite
+ dist() {
+ var d = super.dist();
+ return Math.sqrt(d * d + this.z * this.z);
+ }
}
// Modules, "." can be used as separator for sub modules
@@ -139,19 +139,19 @@ var s2 = new G.Square(10);
// Generics
// 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;
}
// And functions
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"});
@@ -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/uk-ua/bash-ua.html.markdown b/uk-ua/bash-ua.html.markdown
new file mode 100644
index 00000000..b7e4a5ba
--- /dev/null
+++ b/uk-ua/bash-ua.html.markdown
@@ -0,0 +1,296 @@
+---
+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: uk-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/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/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown
new file mode 100644
index 00000000..9614f9ca
--- /dev/null
+++ b/uk-ua/javascript-ua.html.markdown
@@ -0,0 +1,495 @@
+---
+language: javascript
+contributors:
+ - ["Adam Brenecki", "http://adam.brenecki.id.au"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
+filename: javascript-uk.js
+translators:
+ - ["Ivan", "https://github.com/IvanEh"]
+ - ["Serhii Maksymchuk", "https://github.com/Serg-Maximchuk"]
+lang: uk-ua
+---
+
+JavaScript було створено в 1995 році Бренданом Айком, який працював у копаніх Netscape.
+Він був задуманий як проста мова сценаріїв для веб-сайтів, який би доповнював Java
+для більш складних веб-застосунків. Але тісна інтеграція з веб-сторінками і
+вбудована підтримка браузерами призвела до того, що JavaScript став популярніший
+за власне Java.
+
+Зараз JavaScript не обмежується тільки веб-браузеорм. Наприклад, Node.js,
+програмна платформа, що дозволяє виконувати JavaScript код з використанням
+рушія V8 від браузера Google Chrome, стає все більш і більш популярною.
+
+```js
+// С-подібні коментарі. Однорядкові коментарі починаються з двох символів /(слеш)
+/* а багаторядкові коментарі починаються з послідовності слеша та зірочки і
+ закінчуються символами зірочка-слеш */
+
+//Інструкції можуть закінчуватися крапкою з комою ;
+doStuff();
+
+// ... але не обов’язково, тому що крапка з комою автоматично вставляється на
+// місці символу нового рядка, крім деяких випадків.
+doStuff()
+
+// Ми завжди будемо використовувати крапку з комою в цьому посібнику, тому що ці
+// винятки можуть призвести до неочікуваних результатів
+
+///////////////////////////////////
+// 1. Числа, Рядки і Оператори
+
+// В JavaScript числа зберігаються тільки в одному форматі (64-bit IEEE 754 double)
+// Цей тип має 52-бітну мантису, якої достатньо для збереження чисел з
+// точністю до 9✕10¹⁵.
+3; // = 3
+1.5; // = 1.5
+
+// Деякі прості арифметичні операції працють так, як ми очікуємо.
+1 + 1; // = 2
+0.1 + 0.2; // = 0.30000000000000004 (а деякі - ні)
+8 - 1; // = 7
+10 * 2; // = 20
+35 / 5; // = 7
+
+// В тому числі ділення з остачею
+5 / 2; // = 2.5
+
+// В JavaScript є побітові операції; коли ви виконуєте таку операцію,
+// число з плаваючою точкою переводиться в ціле зі знаком
+// довжиною *до* 32 розрядів.
+1 << 2; // = 4
+
+// Пріоритет у виразах можна задати явно круглими дужками
+(1 + 3) * 2; // = 8
+
+// Є три спеціальні значення, які не є реальними числами:
+Infinity; // "нескінченність", наприклад, як результат ділення на 0
+-Infinity; // "мінус нескінченність", як результат ділення від’ємного числа на 0
+NaN; // "не число", наприклад, ділення 0/0
+
+// Логічні типи
+true;
+false;
+
+// Рядки створюються за допомогою подвійних та одинарних лапок
+'абв';
+"Привіт, світе!";
+
+// Для логічного заперечення використовується знак оклику.
+!true; // = false
+!false; // = true
+
+// Строга рівність ===
+1 === 1; // = true
+2 === 1; // = false
+
+// Строга нерівність !==
+1 !== 1; // = false
+2 !== 1; // = true
+
+// Інші оператори порівняння
+1 < 10; // = true
+1 > 10; // = false
+2 <= 2; // = true
+2 >= 2; // = true
+
+// Рядки об’єднуються за допомогою оператора +
+"hello, " + "world!"; // = "hello, world!"
+
+// І порівнюються за допомогою > та <
+"a" < "b"; // = true
+
+// Перевірка на рівність з приведнням типів здійснюється оператором ==
+"5" == 5; // = true
+null == undefined; // = true
+
+// ... але приведення не виконується при ===
+"5" === 5; // = false
+null === undefined; // = false
+
+// ... приведення типів може призвести до дивних результатів
+13 + !0; // 14
+"13" + !0; // '13true'
+
+// Можна отримати доступ до будь-якого символа рядка за допомгою charAt
+"Це рядок".charAt(0); // = 'Ц'
+
+// ... або використати метод substring, щоб отримати більший кусок
+"Hello, world".substring(0, 5); // = "Hello"
+
+// length - це не метод, а поле
+"Hello".length; // = 5
+
+// Типи null и undefined
+null; // навмисна відсутність результату
+undefined; // використовується для позначення відсутності присвоєного значення
+
+// false, null, undefined, NaN, 0 та "" — хиба; все інше - істина.
+// Потрібно відмітити, що 0 — це хиба, а "0" — істина, не зважаючи на те що:
+// 0 == "0".
+
+///////////////////////////////////
+// 2. Змінні, Масиви, Об’єкти
+
+// Змінні оголошуються за допомогою ключового слова var. JavaScript — мова з
+// динамічною типізацією, тому не потрібно явно вказувати тип. Для присвоєння
+// значення змінної використовується символ =
+var someVar = 5;
+
+// якщо пропустити слово var, ви не отримаєте повідомлення про помилку, ...
+someOtherVar = 10;
+
+// ... але вашу змінну буде створено в глобальному контексті, а не там, де
+// ви її оголосили
+
+// Змінні, які оголошені без присвоєння, автоматично приймають значення undefined
+var someThirdVar; // = undefined
+
+// У математичних операцій є скорочені форми:
+someVar += 5; // як someVar = someVar + 5;
+someVar *= 10; // тепер someVar = 100
+
+// Інкремент і декремент
+someVar++; // тепер someVar дорівнює 101
+someVar--; // а зараз 100
+
+// Масиви — це нумеровані списки, які зберігають значення будь-якого типу.
+var myArray = ["Привіт", 45, true];
+
+// Доступ до елементів можна отримати за допомогою синтаксиса з квадратними дужками
+// Індексація починається з нуля
+myArray[1]; // = 45
+
+// Масиви в JavaScript змінюють свою довжину при додаванні нових елементів
+myArray.push("Привіт");
+myArray.length; // = 4
+
+// Додавання і редагування елементів
+myArray[3] = "світ";
+
+// Об’єкти в JavaScript схожі на словники або асоціативні масиви в інших мовах
+var myObj = {key1: "Hello", key2: "World"};
+
+// Ключі - це рядки, але лапки не обов’язкі, якщо ключ задовольняє
+// правилам формування назв змінних. Значення можуть бути будь-яких типів.
+var myObj = {myKey: "myValue", "my other key": 4};
+
+// Атрибути можна отримати використовуючи квадратні дужки
+myObj["my other key"]; // = 4
+
+// Або через точку, якщо ключ є правильним ідентифікатором
+myObj.myKey; // = "myValue"
+
+// Об’єкти можна динамічно змінювати й додавати нові поля
+myObj.myThirdKey = true;
+
+// Коли ви звертаєтесь до поля, що не існує, ви отримуєте значення undefined
+myObj.myFourthKey; // = undefined
+
+///////////////////////////////////
+// 3. Керуючі конструкції
+
+// Синтаксис для цього розділу майже такий самий, як у Java
+
+// Умовна конструкція
+var count = 1;
+if (count == 3) {
+ // виконується, якщо count дорівнює 3
+} else if (count == 4) {
+ // ..
+} else {
+ // ...
+}
+
+// ... цикл while.
+while (true){
+ // Нескінченний цикл!
+}
+
+// Цикл do-while такий самий, як while, але завжди виконується принаймні один раз.
+var input
+do {
+ input = getInput();
+} while (!isValid(input))
+
+// цикл for такий самий, як в C і Java:
+// ініціалізація; умова; крок.
+for (var i = 0; i < 5; i++) {
+ // виконається 5 разів
+}
+
+// && — логічне І, || — логічне АБО
+if (house.size == "big" && house.color == "blue") {
+ house.contains = "bear";
+}
+if (color == "red" || color == "blue") {
+ // колір червоний або синій
+}
+
+// && та || використовують скорочене обчислення
+// тому їх можна використовувати для задання значень за замовчуванням.
+var name = otherName || "default";
+
+// Оператор switch виконує перевірку на рівність за допомогою ===
+// використовуйте break, щоб призупити виконання наступного case,
+grade = 4;
+switch (grade) {
+ case 5:
+ console.log("Відмінно");
+ break;
+ case 4:
+ console.log("Добре");
+ break;
+ case 3:
+ console.log("Можна краще");
+ break;
+ default:
+ console.log("Погано!");
+ break;
+}
+
+
+///////////////////////////////////
+// 4. Функції, область видимості і замикання
+
+// Функції в JavaScript оголошуються за допомогою ключового слова function.
+function myFunction(thing) {
+ return thing.toUpperCase();
+}
+myFunction("foo"); // = "FOO"
+
+// Зверніть увагу, що значення яке буде повернено, повинно починатися на тому ж
+// рядку, що і ключове слово return, інакше завжди буде повертатися значення undefined
+// через автоматичну вставку крапки з комою
+function myFunction()
+{
+ return // <- крапка з комою вставляється автоматично
+ {
+ thisIsAn: 'object literal'
+ }
+}
+myFunction(); // = undefined
+
+// В JavaScript функції - це об`єкти першого класу, тому вони можуть присвоюватися
+// іншим змінним і передаватися іншим функціям, наприклад, щоб визначити обробник
+// події.
+function myFunction() {
+ // код буде виконано через 5 сек.
+}
+setTimeout(myFunction, 5000);
+// setTimeout не є частиною мови, але реалізований в браузерах і Node.js
+
+// Функції не обов’язково мають мати ім’я при оголошенні — ви можете написати
+// анонімну функцію як аргумент іншої функції
+setTimeout(function() {
+ // Цей код буде виконано через п’ять секунд
+}, 5000);
+
+// В JavaScript реалізована концепція області видимості; функції мають свою
+// область видимості, а інші блоки не мають
+if (true) {
+ var i = 5;
+}
+i; // = 5, а не undefined, як це звичайно буває в інших мовах
+
+// Така особливість призвела до шаблону "анонімних функцій, які викликають самих себе"
+// що дозволяє уникнути проникнення змінних в глобальну область видимості
+(function() {
+ var temporary = 5;
+ // об’єкт window зберігає глобальний контекст; таким чином ми можемо також додавати
+ // змінні до глобальної області
+ window.permanent = 10;
+})();
+temporary; // повідомлення про помилку ReferenceError
+permanent; // = 10
+
+// Замикання - один з найпотужніших інструментів JavaScript. Якщо функція визначена
+// всередині іншої функції, то внутрішня функція має доступ до змінних зовнішньої
+// функції навіть після того, як код буде виконуватися поза контекстом зовнішньої функції
+function sayHelloInFiveSeconds(name) {
+ var prompt = "Привіт, " + name + "!";
+ // Внутрішня функція зберігається в локальній області так,
+ // ніби функція була оголошена за допомогою ключового слова var
+ function inner() {
+ alert(prompt);
+ }
+ setTimeout(inner, 5000);
+ // setTimeout асинхронна, тому функція sayHelloInFiveSeconds одразу завершиться,
+ // після чого setTimeout викличе функцію inner. Але функція inner
+ // «замкнута» кругом sayHelloInFiveSeconds, вона все рівно має доступ до змінної prompt
+}
+sayHelloInFiveSeconds("Адам"); // Через 5 с відкриється вікно «Привіт, Адам!»
+
+///////////////////////////////////
+// 5. Об’єкти: конструктори і прототипи
+
+// Об’єкти можуть містити функції
+var myObj = {
+ myFunc: function() {
+ return "Hello, world!";
+ }
+};
+myObj.myFunc(); // = "Hello, world!"
+
+// Функції, що прикріплені до об’єктів мають доступ до поточного об’єкта за
+// допомогою ключового слова this.
+myObj = {
+ myString: "Hello, world!",
+ myFunc: function() {
+ return this.myString;
+ }
+};
+myObj.myFunc(); // = "Hello, world!"
+
+// Значення this залежить від того, як функція викликається
+// а не від того, де вона визначена. Таким чином наша функція не працює, якщо
+// вона викликана не в контексті об’єкта
+var myFunc = myObj.myFunc;
+myFunc(); // = undefined
+
+// Функція може бути присвоєна іншому об’єкту. Тоді вона матиме доступ до
+// цього об’єкта через this
+var myOtherFunc = function() {
+}
+myObj.myOtherFunc = myOtherFunc;
+myObj.myOtherFunc(); // = "HELLO, WORLD!"
+
+// Контекст виконання функції можна задати за допомогою сall або apply
+var anotherFunc = function(s) {
+ return this.myString + s;
+}
+anotherFunc.call(myObj, " Hello!"); // = "Hello, world! Hello!"
+
+// Функцiя apply приймає в якості аргументу масив
+anotherFunc.apply(myObj, [" Hello!"]); // = "Hello, world! Hello!"
+
+// apply можна використати, коли функція працює послідовністю аргументів, а
+// ви хочете передати масив
+Math.min(42, 6, 27); // = 6
+Math.min([42, 6, 27]); // = NaN (Ой-ой!)
+Math.min.apply(Math, [42, 6, 27]); // = 6
+
+// Але call і apply — тимчасові. Коли ми хочемо зв’язати функцію і об’єкт
+// використовують bind
+var boundFunc = anotherFunc.bind(myObj);
+boundFunc(" Hello!"); // = "Hello world, Hello!"
+
+// Bind можна використати для задання аргументів
+var product = function(a, b) { return a * b; }
+var doubler = product.bind(this, 2);
+doubler(8); // = 16
+
+// Коли ви викликаєте функцію за допомогою ключового слова new, створюється новий об’єкт,
+// доступний функції за допомогою this. Такі функції називають конструкторами.
+var MyConstructor = function() {
+ this.myNumber = 5;
+}
+myNewObj = new MyConstructor(); // = {myNumber: 5}
+myNewObj.myNumber; // = 5
+
+// У кожного об’єкта є прототип. Коли ви звертаєтесь до поля, яке не існує в цьому
+// об’єкті, інтерпретатор буде шукати поле в прототипі
+
+// Деякі реалізації мови дозволяють отримати доступ до прототипа об’єкта через
+// "магічну" властивість __proto__. Це поле не є частиною стандарта, але існують
+// стандартні способи використання прототипів, які ми побачимо пізніше
+var myObj = {
+ myString: "Hello, world!"
+};
+var myPrototype = {
+ meaningOfLife: 42,
+ myFunc: function() {
+ return this.myString.toLowerCase()
+ }
+};
+
+myObj.__proto__ = myPrototype;
+myObj.meaningOfLife; // = 42
+
+// Аналогічно для функцій
+myObj.myFunc(); // = "Hello, world!"
+
+// Якщо інтерпретатор не знайде властивості в прототипі, то він продовжить пошук
+// в прототипі прототипа і так далі
+myPrototype.__proto__ = {
+ myBoolean: true
+};
+myObj.myBoolean; // = true
+
+// Кожен об’єкт зберігає посилання на свій прототип. Це значить, що ми можемо змінити
+// наш прототип, і наші зміни будуть всюди відображені.
+myPrototype.meaningOfLife = 43;
+myObj.meaningOfLife; // = 43
+
+// Ми сказали, що властивість __proto__ нестандартна, і нема ніякого стандартного способу
+// змінити прототип об’єкта, що вже існує. Але є два способи створити новий об’єкт із заданим
+// прототипом
+
+// Перший спосіб — це Object.create, який з’явився в JavaScript недавно,
+// а тому в деяких реалізаціях може бути недоступним.
+var myObj = Object.create(myPrototype);
+myObj.meaningOfLife; // = 43
+
+// Другий спосіб: у конструкторів є властивість з іменем prototype. Це *не*
+// прототип функції-конструктора, це прототип для нових об’єктів, які будуть створені
+// цим конструктором і ключового слова new.
+MyConstructor.prototype = {
+ myNumber: 5,
+ getMyNumber: function() {
+ return this.myNumber;
+ }
+};
+var myNewObj2 = new MyConstructor();
+myNewObj2.getMyNumber(); // = 5
+myNewObj2.myNumber = 6
+myNewObj2.getMyNumber(); // = 6
+
+// У вбудованих типів(рядок, число) теж є конструктори, які створють еквівалентні
+// об’єкти-обгортки
+var myNumber = 12;
+var myNumberObj = new Number(12);
+myNumber == myNumberObj; // = true
+
+// Але вони не ідентичні
+typeof myNumber; // = 'number'
+typeof myNumberObj; // = 'object'
+myNumber === myNumberObj; // = false
+if (0) {
+ // Цей код не виконається, тому що 0 - це хиба.
+}
+
+// Об’єкти-обгортки і вбудовані типи мають спільні прототипи, тому
+// ви можете розширити функціонал рядків:
+String.prototype.firstCharacter = function() {
+ return this.charAt(0);
+}
+"abc".firstCharacter(); // = "a"
+
+// Такий прийом часто використовуються в поліфілах, які реалізують нові можливості
+// JavaScript в старій реалізації мови, так що вони можуть бути використані в старих
+// середовищах
+
+// Наприклад, Object.create доступний не у всіх реалізаціях, але ми можемо
+// використати функції за допомогою наступного поліфіла:
+if (Object.create === undefined) { // не перезаписуємо метод, якщо він існує
+ Object.create = function(proto) {
+ // Створюємо правильний конструктор з правильним прототипом
+ var Constructor = function(){};
+ Constructor.prototype = proto;
+
+ return new Constructor();
+ }
+}
+```
+
+## Що почитати
+
+[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript
+[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
+[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core
+[4]: http://www.learneroo.com/modules/64/nodes/350
+[5]: http://bonsaiden.github.io/JavaScript-Garden/
+[6]: http://www.amazon.com/gp/product/0596805527/
+[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
+[8]: http://eloquentjavascript.net/
+[9]: http://jstherightway.org/
diff --git a/uk-ua/json-ua.html.markdown b/uk-ua/json-ua.html.markdown
new file mode 100644
index 00000000..a860e9a7
--- /dev/null
+++ b/uk-ua/json-ua.html.markdown
@@ -0,0 +1,67 @@
+---
+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: uk-ua
+---
+
+JSON - це надзвичайно простий формат обміну даними. Це мабуть буде найлегшим курсом
+"Learn X in Y Minutes".
+
+В загальному випадку в JSON немає коментарів, але більшість парсерів дозволяють
+використовувати коментарі в С-стилі(//, /\* \*/). Можна залишити кому після останнього
+поля, але все-таки краще такого уникати для кращої сумісності
+
+```json
+{
+ "ключ": "значеннь",
+
+ "ключі": "завжди мають бути обгорнуті в подвійні лапки",
+ "числа": 0,
+ "рядки": "Пρивіт, світe. Допускаються всі 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/vi-vn/json-vi.html.markdown b/vi-vn/json-vi.html.markdown
new file mode 100644
index 00000000..257216ff
--- /dev/null
+++ b/vi-vn/json-vi.html.markdown
@@ -0,0 +1,76 @@
+---
+language: json
+filename: learnjson-vi.json
+contributors:
+ - ["Anna Harren", "https://github.com/iirelu"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["himanshu", "https://github.com/himanshu81494"]
+translators:
+ - ["Thanh Phan", "https://github.com/thanhpd"]
+lang: vi-vn
+---
+
+Do JSON là một ngôn ngữ trao đổi dữ liệu hết sức đơn giản, đây có thể sẽ là bài
+đơn giản nhất của Học X trong Y phút (Learn X in Y Minutes) từ trước tới nay.
+
+JSON ở dạng thuần túy nhất không có chú thích cho câu lệnh (comment) nào, nhưng
+hầu hết các trình phân tích cú pháp (parser) đều chấp nhận chú thích theo phong
+cách của ngôn ngữ C (`//`, `/* */`). Một số trình phân tích cú pháp còn chấp
+nhận dấu phẩy cuối cùng (vd: một dấu phẩy sau phần tử cuối cùng của một mảng
+hoặc sau thuộc tính cuối cùng của một object), nhưng những trường hợp này nên
+tránh để có sự tương thích tốt hơn.
+
+Để phục vụ cho mục đích bài học này, tất cả cú pháp JSON ở đây sẽ đều là 100% hợp lệ.
+May mắn thay, chúng cũng tự trình bày cho chính mình mà không cần thêm giải thích.
+
+Các kiểu dữ liệu được JSON hỗ trợ bao gồm: số (*numbers*), chuỗi kí tự
+(*string*), toán tử đúng/sai (*boolean*), mảng (*array*), *object* và *null*.
+Các trình duyệt hỗ trợ bao gồm: Mozilla Firefox phiên bản 3.5 trở lên,
+Internet Explorer 8 trở lên, Google Chrome, Opera 10 trở lên, Safari 4 trở lên.
+Kiểu tệp JSON có dạng ".json". Kiểu MIME (Multipurpose Internet Mail Extensions)
+cho JSON là "application/json". Điểm yếu của JSON đó là thiếu các định dạng cho
+kiểu dữ liệu cũng như quy chuẩn cú pháp chặt chẽ sử dụng DTD.
+
+```json
+{
+ "khóa": "dữ liệu",
+
+ "các khóa": "phải luôn được đặt trong dấu ngoặc kép",
+ "số": 0,
+ "chuỗi kí tự": "Xin chàø. Tất cả kí tự unicode đều được chấp nhận, sử dụng với dạng \"kí tự\"."
+ "có đúng không?": true,
+ "không có gì": null,
+
+ "số rất lớn": 1.2e+100,
+
+ "objects": {
+ "chú thích": "Hầu hết các cấu trúc dữ liệu bạn sẽ dùng sẽ sử dụng object.",
+
+ "mảng": [0, 1, 2, 3, "Mảng có thể chứa bất kì thứ gì bên trong.", 5],
+
+ "một object khác": {
+ "chú thích": "Những thứ này có thể lồng vào nhau, rất tiện."
+ }
+ },
+
+ "ngớ ngẩn": [
+ {
+ "nguồn cung cấp kali": ["chuối"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "neo"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "phong cách khác": {
+ "chú thích": "kiểm tra cái này xem!"
+ , "vị trí dấu phẩy": "không quan trọng - chỉ cần nó ở trước khóa tiếp theo là được"
+ , "chú thích khác": "tiện phải không"
+ },
+
+ "nó rất ngắn": "Và bạn đã xong rồi đấy. Bạn đã biết tất cả những thứ mà JSON có thể cung cấp."
+}
+```
diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown
index c97bb560..38e418e9 100644
--- a/vi-vn/objective-c-vi.html.markdown
+++ b/vi-vn/objective-c-vi.html.markdown
@@ -12,7 +12,7 @@ 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.
Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C.
-```objective_c
+```objective-c
// Chú thích dòng đơn bắt đầu với //
/*
diff --git a/vi-vn/ruby-vi.html.markdown b/vi-vn/ruby-vi.html.markdown
new file mode 100644
index 00000000..73382100
--- /dev/null
+++ b/vi-vn/ruby-vi.html.markdown
@@ -0,0 +1,549 @@
+---
+language: ruby
+filename: learnruby.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"]
+ - ["Vinh Nguyen", "http://rubydaily.net"]
+lang: vi-vn
+
+---
+
+```ruby
+# Đây là một comment
+
+=begin
+Đây là một comment nhiều dòng
+Không ai dùng cách này
+Bạn không nên dùng
+=end
+
+# Đầu tiên và quan trọng nhất: Mọi thứ là đối tượng.
+
+# Các con số là các đối tượng.
+
+3.class #=> Fixnum
+
+3.to_s #=> "3"
+
+
+# Một vài bài toán số học căn bản
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+2**5 #=> 32
+
+# Số học vừa là các cú pháp thân thiện cho việc gọi
+# một hàm trên một đối tượng
+1.+(3) #=> 4
+10.* 5 #=> 50
+
+# Các giá trị đặc biệt là các đối tượng
+nil # Ở đây không có gì để xem
+true # luôn đúng
+false # luôn sai
+
+nil.class #=> Lớp Nil
+true.class #=> Lớp True
+false.class #=> Lớp False
+
+# So sánh bằng
+1 == 1 #=> true
+2 == 1 #=> false
+
+# So sánh không bằng
+1 != 1 #=> false
+2 != 1 #=> true
+
+# Ngoài chính false, thì nil là một giá trị khác của false
+
+!nil #=> true
+!false #=> true
+!0 #=> false
+
+# Các loại so sánh khác
+1 < 10 #=> true
+1 > 10 #=> false
+2 <= 2 #=> true
+2 >= 2 #=> true
+
+# Các toán tử logic
+true && false #=> false
+true || false #=> true
+!true #=> false
+
+
+# Có các cách khác của các toán tử logic với mức thấp hơn
+# Chúng được sử dụng như các cấu trúc điều khiển luồng nối các mệnh đề
+# với nhau cho đến khi một trong số chúng trả về đúng hoặc sai.
+
+# `do_something_else` chỉ được gọi nếu như hàm `do_something` thành công.
+do_something() and do_something_else()
+# `log_error` chỉ được gọi nếu hàm `do_something` không thành công.
+do_something() or log_error()
+
+
+# Các chuỗi là các đối tượng
+
+'I am a string'.class #=> String
+"I am a string too".class #=> String
+
+placeholder = 'use string interpolation'
+"I can #{placeholder} when using double quoted strings"
+#=> "I can use string interpolation when using double quoted strings"
+
+# Nên đưa các chuỗi vào trong dấu nháy đơn
+# Ngoài ra dấu nháy kép được sử dụng trong tính toán.
+
+# Nối các chuỗi, nhưng không nối với các số.
+'hello ' + 'world' #=> "hello world"
+'hello ' + 3 #=> TypeError: can't convert Fixnum into String
+'hello ' + 3.to_s #=> "hello 3"
+
+# Xuất ra ngoài màn hình
+puts "I'm printing!"
+
+# Các biến
+x = 25 #=> 25
+x #=> 25
+
+# Chú ý về việc gán các giá trị được trả về vào biến.
+# Điều này có nghĩa là bạn có thể gán nhiều biến.
+
+x = y = 10 #=> 10
+x #=> 10
+y #=> 10
+
+# Theo quy ước, dùng snake_case cho các tên của biến.
+snake_case = true
+
+# Dùng để mô tả tên các biến
+path_to_project_root = '/good/name/'
+path = '/bad/name/'
+
+# Ký tự (là các đối tượng)
+# Các ký tự là bất biến, như các biến hằng số chỉ đến các số nguyên.
+# Chúng thường xuyên được sử dụng thay cho các chuỗi để chuyển đổi các giá
+# trị hiệu quả.
+
+:pending.class #=> Symbol
+
+status = :pending
+
+status == :pending #=> true
+
+status == 'pending' #=> false
+
+status == :approved #=> false
+
+# Các mảng
+
+# Đây là một mảng
+array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+
+# Các mảng có thể chứa nhiều phần tử khác nhau
+
+[1, 'hello', false] #=> [1, "hello", false]
+
+# Có thể truy cập các giá trị của mảng thông qua các chỉ mục
+array[0] #=> 1
+array[12] #=> nil
+
+# Giống như số học, sử dụng [biến] là một cú pháp thông dụng
+array.[] 0 #=> 1
+array.[] 12 #=> nil
+
+# Lấy phần tử cuối cùng
+array[-1] #=> 5
+
+# Bắt đầu từ chỉ mục và số phần tử cần lấy
+array[2, 3] #=> [3, 4, 5]
+
+# Đảo ngược một mảng
+a=[1,2,3]
+a.reverse! #=> [3,2,1]
+
+# Lấy một khoảng
+array[1..3] #=> [2, 3, 4]
+
+# Thêm phần tử vào mảng bằng cách này
+array << 6 #=> [1, 2, 3, 4, 5, 6]
+# Hoặc cách này
+array.push(6) #=> [1, 2, 3, 4, 5, 6]
+
+# Kiểm tra phần tử có tồn tại trong mảng
+array.include?(1) #=> true
+
+# Băm là phần chính của Ruby với các cặp khoá/giá trị
+# Băm được biểu thị bằng dấu ngoặc nhọn:
+hash = { 'color' => 'green', 'number' => 5 }
+
+hash.keys #=> ['color', 'number']
+
+# Băm có thể được truy cập nhanh chóng thông qua khoá
+hash['color'] #=> 'green'
+hash['number'] #=> 5
+
+# Khoá không tồn tại sẽ trả về nil
+hash['nothing here'] #=> nil
+
+# Kể từ Ruby bản 1.9, đây là một cú pháp đặc biệt, sử dụng symbol như khoá
+
+new_hash = { defcon: 3, action: true }
+
+new_hash.keys #=> [:defcon, :action]
+
+# Kiểm tra khoá hoặc giá trị có tồn tại hay không
+new_hash.has_key?(:defcon) #=> true
+new_hash.has_value?(3) #=> true
+
+# Mẹo: Cả Mảng và Băm đều là Enumberable
+# Chúng cùng chia sẻ rất nhiều phương thức hữu ích như each, map, count...
+
+# Cấu trúc điều khiển
+
+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
+
+# TUY NHIÊN, không ai sử dụng vòng lặp for.
+# Thay vào đó, ban nên dùng phương thức "each" và truyền vào đó một khối.
+# Một khối là một loạt các mã mà bạn có thể truyền
+# cho một phương thức giống như each.
+# Nó tương tự với lambda, các hàm ẩn danh hoặc closures trong các ngôn ngữ
+# lập trình khác.
+#
+# Phương thức "each" cho một khoản sẽ chạy qua từng phần tử của khoảng đó.
+# Khối được truyền vào là một số đếm như là tham số.
+# Gọi một method "each" với một khối sẽ trông như thế này:
+
+(1..5).each do |counter|
+ puts "iteration #{counter}"
+end
+#=> iteration 1
+#=> iteration 2
+#=> iteration 3
+#=> iteration 4
+#=> iteration 5
+
+# Bạn cũng có thể bao khối trong các dấu ngoặc nhọn.
+(1..5).each { |counter| puts "iteration #{counter}" }
+
+# Các nội dung của cấu trúc dữ liệu cũng có thể được lặp bằng each.
+array.each do |element|
+ puts "#{element} is part of the array"
+end
+hash.each do |key, value|
+ puts "#{key} is #{value}"
+end
+
+counter = 1
+while counter <= 5 do
+ puts "iteration #{counter}"
+ counter += 1
+end
+#=> iteration 1
+#=> iteration 2
+#=> iteration 3
+#=> iteration 4
+#=> iteration 5
+
+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"
+
+# Cases cũng được dùng cho các dãy
+grade = 82
+case grade
+when 90..100
+ puts 'Hooray!'
+when 80...90
+ puts 'OK job'
+else
+ puts 'You failed!'
+end
+#=> "OK job"
+
+# Xử lý ngoại lệ:
+begin
+ # Code ở đây có thể sẽ đưa ra một ngoại lệ.
+ 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
+
+# Hàm
+
+def double(x)
+ x * 2
+end
+
+# Hàm (và tất cả các khối) được mặc định giá trị trả về ở mệnh đề cuối.
+double(2) #=> 4
+
+# Dấu ngoặc là một tuỳ chọn cho một kết quả rõ ràng.
+double 3 #=> 6
+
+double double 3 #=> 12
+
+def sum(x, y)
+ x + y
+end
+
+# Các đối số được chia cắt bởi dấu phẩy.
+sum 3, 4 #=> 7
+
+sum sum(3, 4), 5 #=> 12
+
+# yield
+# Tất cả các hàm có thể có một tham số tuỳ chọn.
+# Nó có thể được gọi với từ khóa "yield".
+def surround
+ puts '{'
+ yield
+ puts '}'
+end
+
+surround { puts 'hello world' }
+
+# {
+# hello world
+# }
+
+
+# Bạn có thể truyền một khối đến một hàm
+# Dấu "&" được đánh dấu đến một khối
+def guests(&block)
+ block.call 'some_argument'
+end
+
+# Bạn có thể truyền một danh sách các tham số, nó sẽ được chuyển thành mảng.
+# Thông qua việc sử dụng dấu *.
+def guests(*array)
+ array.each { |guest| puts guest }
+end
+
+# Định nghĩ một lớp thông qua từ khoá class.
+class Human
+
+ # Một biến class. Nó được chia sẽ cho tất cả các instance của lớp này.
+ @@species = 'H. sapiens'
+
+ # Các khởi tạo căn bản
+ def initialize(name, age = 0)
+ # Gán đối số đến biến instance "name"
+ @name = name
+ # Nếu không có age, sẽ lấy giá trị mặc định trong danh sách đối số.
+ @age = age
+ end
+
+ # Hàm nhập giá trị căn bản
+ def name=(name)
+ @name = name
+ end
+
+ # Hàm lấy giá trị căn bản
+ def name
+ @name
+ end
+
+ # Các hàm trên có thể được gọn lại bằng cách dùng hàm attr_accessor
+ attr_accessor :name
+
+ # Các hàm nhận/lấy cũng có thể được tạo riêng như sau:
+ attr_reader :name
+ attr_writer :name
+
+ # Một hàm lớp dùng self để phân biệt với hàm instance.
+ # Nó chỉ có thể được gọi trên lớp.
+ def self.say(msg)
+ puts msg
+ end
+
+ def species
+ @@species
+ end
+end
+
+
+# Khởi tạo một lớp
+jim = Human.new('Jim Halpert')
+
+dwight = Human.new('Dwight K. Schrute')
+
+# Hãy gọi một cặp các hàm.
+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"
+
+# Gọi một hàm lớp
+Human.say('Hi') #=> "Hi"
+
+# Phạm vi của biến được định nghĩa bởi cách chúng ta đặt tên cho chúng.
+# Các biến bắt đầu với dấu $ là biến toàn cục.
+$var = "I'm a global var"
+defined? $var #=> "global-variable"
+
+# Các biến bắt đầu với dấu @ là biến phạm vi.
+@var = "I'm an instance var"
+defined? @var #=> "instance-variable"
+
+# Các biến bắt đầu với dấu @@ có pham vi là trong một lớp.
+@@var = "I'm a class var"
+defined? @@var #=> "class variable"
+
+# Các biến bắt đầu với ký tự viết hoa là biến hằng.
+Var = "I'm a constant"
+defined? Var #=> "constant"
+
+# Lớp cũng là một đối tượng trong Ruby. Bởi vậy lớp có các biến instance.
+# Biến lớp được chia sẽ trong lớp và các lớp kế thừa nó.
+
+# Lớp cơ sở
+class Human
+ @@foo = 0
+
+ def self.foo
+ @@foo
+ end
+
+ def self.foo=(value)
+ @@foo = value
+ end
+end
+
+# Lớp kế thừa
+class Worker < Human
+end
+
+Human.foo # 0
+Worker.foo # 0
+
+Human.foo = 2 # 2
+Worker.foo # 2
+
+# Các biến lớp instance không được chia sẽ trong lớp kế thừa.
+
+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
+
+# Include một module sẽ đưa các hàm của module thành instances của lớp.
+# Extend một module sẽ đưa các hàm của module thành các biến của lớp.
+
+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'
+
+# Hàm hồi quy được thực hiện khi include và extend một module.
+
+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'
+```
+
+## Các nguồn tham khảo thêm.
+
+- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.
+- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/)
+- [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.
diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown
index bdfdcc10..0371e6f6 100644
--- a/visualbasic.html.markdown
+++ b/visualbasic.html.markdown
@@ -9,13 +9,13 @@ filename: learnvisualbasic.vb
Module Module1
Sub Main()
- ' A Quick Overview of Visual Basic Console Applications before we dive
- ' in to the deep end.
- ' Apostrophe starts comments.
- ' To Navigate this tutorial within the Visual Basic Complier, I've put
- ' together a navigation system.
- ' This navigation system is explained however as we go deeper into this
- ' tutorial, you'll understand what it all means.
+ 'A Quick Overview of Visual Basic Console Applications before we dive
+ 'in to the deep end.
+ 'Apostrophe starts comments.
+ 'To Navigate this tutorial within the Visual Basic Complier, I've put
+ 'together a navigation system.
+ 'This navigation system is explained however as we go deeper into this
+ 'tutorial, you'll understand what it all means.
Console.Title = ("Learn X in Y Minutes")
Console.WriteLine("NAVIGATION") 'Display
Console.WriteLine("")
@@ -32,6 +32,9 @@ Module Module1
Console.WriteLine("50. About")
Console.WriteLine("Please Choose A Number From The Above List")
Dim selection As String = Console.ReadLine
+ 'The "Case" in the Select statement is optional.
+ 'For example, "Select selection" instead of "Select Case selection"
+ 'will also work.
Select Case selection
Case "1" 'HelloWorld Output
Console.Clear() 'Clears the application and opens the private sub
@@ -42,10 +45,10 @@ Module Module1
Case "3" 'Calculating Whole Numbers
Console.Clear()
CalculatingWholeNumbers()
- Case "4" 'Calculting Decimal Numbers
+ Case "4" 'Calculating Decimal Numbers
Console.Clear()
CalculatingDecimalNumbers()
- Case "5" 'Working Calcculator
+ Case "5" 'Working Calculator
Console.Clear()
WorkingCalculator()
Case "6" 'Using Do While Loops
@@ -74,10 +77,10 @@ Module Module1
'One - I'm using numbers to help with the above navigation when I come back
'later to build it.
- 'We use private subs to seperate different sections of the program.
+ 'We use private subs to separate different sections of the program.
Private Sub HelloWorldOutput()
'Title of Console Application
- Console.Title = "Hello World Ouput | Learn X in Y Minutes"
+ Console.Title = "Hello World Output | Learn X in Y Minutes"
'Use Console.Write("") or Console.WriteLine("") to print outputs.
'Followed by Console.Read() alternatively Console.Readline()
'Console.ReadLine() prints the output to the console.
@@ -88,18 +91,18 @@ Module Module1
'Two
Private Sub HelloWorldInput()
Console.Title = "Hello World YourName | Learn X in Y Minutes"
- ' Variables
- ' Data entered by a user needs to be stored.
- ' Variables also start with a Dim and end with an As VariableType.
+ 'Variables
+ 'Data entered by a user needs to be stored.
+ 'Variables also start with a Dim and end with an As VariableType.
- ' In this tutorial, we want to know what your name, and make the program
- ' respond to what is said.
+ 'In this tutorial, we want to know what your name, and make the program
+ 'respond to what is said.
Dim username As String
'We use string as string is a text based variable.
Console.WriteLine("Hello, What is your name? ") 'Ask the user their name.
username = Console.ReadLine() 'Stores the users name.
Console.WriteLine("Hello " + username) 'Output is Hello 'Their name'
- Console.ReadLine() 'Outsputs the above.
+ Console.ReadLine() 'Outputs the above.
'The above will ask you a question followed by printing your answer.
'Other variables include Integer and we use Integer for whole numbers.
End Sub
@@ -107,7 +110,7 @@ Module Module1
'Three
Private Sub CalculatingWholeNumbers()
Console.Title = "Calculating Whole Numbers | Learn X in Y Minutes"
- Console.Write("First number: ") 'Enter a whole number, 1, 2, 50, 104 ect
+ Console.Write("First number: ") 'Enter a whole number, 1, 2, 50, 104, etc
Dim a As Integer = Console.ReadLine()
Console.Write("Second number: ") 'Enter second whole number.
Dim b As Integer = Console.ReadLine()
@@ -123,10 +126,10 @@ Module Module1
'Of course we would like to be able to add up decimals.
'Therefore we could change the above from Integer to Double.
- 'Enter a whole number, 1.2, 2.4, 50.1, 104.9 ect
+ 'Enter a floating-point number, 1.2, 2.4, 50.1, 104.9, etc
Console.Write("First number: ")
Dim a As Double = Console.ReadLine
- Console.Write("Second number: ") 'Enter second whole number.
+ Console.Write("Second number: ") 'Enter second floating-point number.
Dim b As Double = Console.ReadLine
Dim c As Double = a + b
Console.WriteLine(c)
@@ -142,15 +145,15 @@ Module Module1
'Copy and paste the above again.
Console.Write("First number: ")
Dim a As Double = Console.ReadLine
- Console.Write("Second number: ") 'Enter second whole number.
- Dim b As Integer = Console.ReadLine
- Dim c As Integer = a + b
- Dim d As Integer = a * b
- Dim e As Integer = a - b
- Dim f As Integer = a / b
+ Console.Write("Second number: ") 'Enter second floating-point number.
+ Dim b As Double = Console.ReadLine
+ Dim c As Double = a + b
+ Dim d As Double = a * b
+ Dim e As Double = a - b
+ Dim f As Double = a / b
'By adding the below lines we are able to calculate the subtract,
- 'multply as well as divide the a and b values
+ 'multiply as well as divide the a and b values
Console.Write(a.ToString() + " + " + b.ToString())
'We want to pad the answers to the left by 3 spaces.
Console.WriteLine(" = " + c.ToString.PadLeft(3))
@@ -176,11 +179,11 @@ Module Module1
Console.Write("First number: ")
Dim a As Double = Console.ReadLine
Console.Write("Second number: ")
- Dim b As Integer = Console.ReadLine
- Dim c As Integer = a + b
- Dim d As Integer = a * b
- Dim e As Integer = a - b
- Dim f As Integer = a / b
+ Dim b As Double = Console.ReadLine
+ Dim c As Double = a + b
+ Dim d As Double = a * b
+ Dim e As Double = a - b
+ Dim f As Double = a / b
Console.Write(a.ToString() + " + " + b.ToString())
Console.WriteLine(" = " + c.ToString.PadLeft(3))
@@ -193,10 +196,10 @@ Module Module1
Console.ReadLine()
'Ask the question, does the user wish to continue? Unfortunately it
'is case sensitive.
- Console.Write("Would you like to continue? (yes / no)")
+ Console.Write("Would you like to continue? (yes / no) ")
'The program grabs the variable and prints and starts again.
answer = Console.ReadLine
- 'The command for the variable to work would be in this case "yes"
+ 'The command for the variable to work would be in this case "yes"
Loop While answer = "yes"
End Sub
@@ -208,7 +211,7 @@ Module Module1
Console.Title = "Using For Loops | Learn X in Y Minutes"
'Declare Variable and what number it should count down in Step -1,
- 'Step -2, Step -3 ect.
+ 'Step -2, Step -3, etc.
For i As Integer = 10 To 0 Step -1
Console.WriteLine(i.ToString) 'Print the value of the counter
Next i 'Calculate new value
@@ -219,7 +222,7 @@ Module Module1
'Eight
Private Sub ConditionalStatement()
Console.Title = "Conditional Statements | Learn X in Y Minutes"
- Dim userName As String = Console.ReadLine
+ Dim userName As String
Console.WriteLine("Hello, What is your name? ") 'Ask the user their name.
userName = Console.ReadLine() 'Stores the users name.
If userName = "Adam" Then
@@ -235,36 +238,34 @@ Module Module1
'Nine
Private Sub IfElseStatement()
- Console.Title = "If / Else Statement | Learn X in Y Minutes"
+ Console.Title = "If / Else Statement | Learn X in Y Minutes"
'Sometimes it is important to consider more than two alternatives.
'Sometimes there are a good few others.
'When this is the case, more than one if statement would be required.
'An if statement is great for vending machines. Where the user enters a code.
- 'A1, A2, A3, ect to select an item.
- 'All choices can be combined into a single if statement.
+ 'A1, A2, A3, etc to select an item.
+ 'All choices can be combined into a single if block.
- Dim selection As String = Console.ReadLine 'Value for selection
- Console.WriteLine("A1. for 7Up")
- Console.WriteLine("A2. for Fanta")
- Console.WriteLine("A3. for Dr. Pepper")
- Console.WriteLine("A4. for Diet Coke")
- Console.ReadLine()
- If selection = "A1" Then
- Console.WriteLine("7up")
- Console.ReadLine()
- ElseIf selection = "A2" Then
- Console.WriteLine("fanta")
- Console.ReadLine()
- ElseIf selection = "A3" Then
- Console.WriteLine("dr. pepper")
- Console.ReadLine()
- ElseIf selection = "A4" Then
- Console.WriteLine("diet coke")
- Console.ReadLine()
- Else
- Console.WriteLine("Please select a product")
- Console.ReadLine()
- End If
+ Dim selection As String 'Declare a variable for selection
+ Console.WriteLine("Please select a product form our lovely vending machine.")
+ Console.WriteLine("A1. for 7Up")
+ Console.WriteLine("A2. for Fanta")
+ Console.WriteLine("A3. for Dr. Pepper")
+ Console.WriteLine("A4. for Diet Coke")
+
+ selection = Console.ReadLine() 'Store a selection from the user
+ If selection = "A1" Then
+ Console.WriteLine("7up")
+ ElseIf selection = "A2" Then
+ Console.WriteLine("fanta")
+ ElseIf selection = "A3" Then
+ Console.WriteLine("dr. pepper")
+ ElseIf selection = "A4" Then
+ Console.WriteLine("diet coke")
+ Else
+ Console.WriteLine("Sorry, I don't have any " + selection)
+ End If
+ Console.ReadLine()
End Sub
diff --git a/whip.html.markdown b/whip.html.markdown
index 3faee98a..e7e5e427 100644
--- a/whip.html.markdown
+++ b/whip.html.markdown
@@ -2,13 +2,14 @@
language: whip
contributors:
- ["Tenor Biel", "http://github.com/L8D"]
+ - ["Saurabh Sandav", "http://github.com/SaurabhSandav"]
author: Tenor Biel
author_url: http://github.com/L8D
filename: whip.lisp
---
Whip is a LISP-dialect made for scripting and simplified concepts.
-It has also borrowed a lot of functions and syntax from Haskell(a non-related language).
+It has also borrowed a lot of functions and syntax from Haskell (a non-related language).
These docs were written by the creator of the language himself. So is this line.
@@ -93,13 +94,13 @@ null ; used to indicate a deliberate non-value
undefined ; user to indicate a value that hasn't been set
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-; 2. Vairbles, Lists, and Dicts
+; 2. Variables, Lists, and Dicts
; Variables are declared with the `def` or `let` functions.
; Variables that haven't been set will be `undefined`.
(def some_var 5)
; `def` will keep the variable in the global context.
-; `let` will only have the variable inside its context, and has a wierder syntax.
+; `let` will only have the variable inside its context, and has a weirder syntax.
(let ((a_var 5)) (+ a_var 5)) ; => 10
(+ a_var 5) ; = undefined + 5 => undefined
@@ -163,7 +164,7 @@ undefined ; user to indicate a value that hasn't been set
(my_function 10 10) ; = (+ (+ 10 10) 10) => 30
-; Obiously, all lambdas by definition are anonymous and
+; Obviously, all lambdas by definition are anonymous and
; technically always used anonymously. Redundancy.
((lambda (x) x) 10) ; => 10
@@ -171,12 +172,12 @@ undefined ; user to indicate a value that hasn't been set
; Comprehensions
; `range` or `..` generates a list of numbers for
-; each number between it's two args.
+; each number between its two args.
(range 1 5) ; => (1 2 3 4 5)
(.. 0 2) ; => (0 1 2)
-; `map` applies it's first arg(which should be a lambda/function)
-; to each item in the following arg(which should be a list)
+; `map` applies its first arg (which should be a lambda/function)
+; to each item in the following arg (which should be a list)
(map (-> (x) (+ x 1)) (1 2 3)) ; => (2 3 4)
; Reduce
@@ -191,7 +192,7 @@ undefined ; user to indicate a value that hasn't been set
(slice (.. 1 5) 2) ; => (3 4 5)
(\ (.. 0 100) -5) ; => (96 97 98 99 100)
-; `append` or `<<` is self expanatory
+; `append` or `<<` is self explanatory
(append 4 (1 2 3)) ; => (1 2 3 4)
(<< "bar" ("foo")) ; => ("foo" "bar")
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/xml.html.markdown b/xml.html.markdown
index d407512d..b4b54330 100644
--- a/xml.html.markdown
+++ b/xml.html.markdown
@@ -3,18 +3,77 @@ language: xml
filename: learnxml.xml
contributors:
- ["João Farias", "https://github.com/JoaoGFarias"]
+ - ["Rachel Stiyer", "https://github.com/rstiyer"]
+ - ["Deepanshu Utkarsh", "https://github.com/duci9y"]
---
-XML is a markup language designed to store and transport data.
+XML is a markup language designed to store and transport data. It is supposed to be both human readable and machine readable.
-Unlike HTML, XML does not specify how to display or to format data, just carry it.
+Unlike HTML, XML does not specify how to display or to format data, it just carries it.
-* XML Syntax
+Distinctions are made between the **content** and the **markup**. In short, content could be anything, markup is defined.
+
+## Some definitions and introductions
+
+XML Documents are basically made up of *elements* which can have *attributes* describing them and may contain some textual content or more elements as its children. All XML documents must have a root element, which is the ancestor of all the other elements in the document.
+
+XML Parsers are designed to be very strict, and will stop parsing malformed documents. Therefore it must be ensured that all XML documents follow the [XML Syntax Rules](http://www.w3schools.com/xml/xml_syntax.asp).
```xml
-<!-- Comments in XML are like this -->
+<!-- This is a comment. It must not contain two consecutive hyphens (-). -->
+<!-- Comments can span
+ multiple lines -->
+
+<!-- Elements -->
+<!-- An element is a basic XML component. There are two types, empty: -->
+<element1 attribute="value" /> <!-- Empty elements do not hold any content -->
+<!-- and non-empty: -->
+<element2 attribute="value">Content</element2>
+<!-- Element names may only contain alphabets and numbers. -->
+
+<empty /> <!-- An element either consists an empty element tag… -->
+<!-- …which does not hold any content and is pure markup. -->
+
+<notempty> <!-- Or, it consists of a start tag… -->
+ <!-- …some content… -->
+</notempty> <!-- and an end tag. -->
+
+<!-- Element names are case sensitive. -->
+<element />
+<!-- is not the same as -->
+<eLEMENT />
+
+<!-- Attributes -->
+<!-- An attribute is a key-value pair and exists within an element. -->
+<element attribute="value" another="anotherValue" many="space-separated list" />
+<!-- An attribute may appear only once in an element. It holds just one value.
+ Common workarounds to this involve the use of space-separated lists. -->
+
+<!-- Nesting elements -->
+<!-- An element's content may include other elements: -->
+<parent>
+ <child>Text</child>
+ <emptysibling />
+</parent>
+<!-- Standard tree nomenclature is followed. Each element being called a node.
+ An ancestor a level up is the parent, descendants a level down are children.
+ Elements within the same parent element are siblings. -->
+
+<!-- XML preserves whitespace. -->
+<child>
+ Text
+</child>
+<!-- is not the same as -->
+<child>Text</child>
+```
+## An XML document
+
+This is what makes XML versatile. It is human readable too. The following document tells us that it defines a bookstore which sells three books, one of which is Learning XML by Erik T. Ray. All this without having used an XML Parser yet.
+
+```xml
<?xml version="1.0" encoding="UTF-8"?>
+<!-- This is called an XML prolog. Optional, but recommended. -->
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
@@ -35,84 +94,49 @@ Unlike HTML, XML does not specify how to display or to format data, just carry i
<price>39.95</price>
</book>
</bookstore>
-
-<!-- Above is a typical XML file.
- It starts with a declaration, informing some metadata (optional).
-
- XML uses a tree structure. Above, the root node is 'bookstore', which has
- three child nodes, all 'books'. Those nodes has more child nodes, and so on...
-
- Nodes are created using open/close tags, and childs are just nodes between
- the open and close tags.-->
-
-
-<!-- XML carries two kind of data:
- 1 - Attributes -> That's metadata about a node.
- Usually, the XML parser uses this information to store the data properly.
- It is characterized by appearing with the format name="value" within the opening
- tag.
- 2 - Elements -> That's pure data.
- That's what the parser will retrieve from the XML file.
- Elements appear between the open and close tags. -->
-
-
-<!-- Below, an element with two attributes -->
-<file type="gif" id="4293">computer.gif</file>
-
-
```
-* Well-Formated Document x Validation
+## Well-formedness and Validation
-A XML document is well-formated if it is syntactically correct.
-However, it is possible to inject more constraints in the document,
-using document definitions, such as DTD and XML Schema.
-
-A XML document which follows a document definition is called valid,
-regarding that document.
-
-With this tool, you can check the XML data outside the application logic.
+A XML document is *well-formed* if it is syntactically correct. However, it is possible to add more constraints to the document, using Document Type Definitions (DTDs). A document whose elements are attributes are declared in a DTD and which follows the grammar specified in that DTD is called *valid* with respect to that DTD, in addition to being well-formed.
```xml
-
-<!-- Below, you can see an simplified version of bookstore document,
- with the addition of DTD definition.-->
-
+<!-- Declaring a DTD externally: -->
<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE note SYSTEM "Bookstore.dtd">
+<!DOCTYPE bookstore SYSTEM "Bookstore.dtd">
+<!-- Declares that bookstore is our root element and 'Bookstore.dtd' is the path
+ to our DTD file. -->
<bookstore>
<book category="COOKING">
- <title >Everyday Italian</title>
+ <title lang="en">Everyday Italian</title>
+ <author>Giada De Laurentiis</author>
+ <year>2005</year>
<price>30.00</price>
</book>
</bookstore>
-<!-- This DTD could be something like:-->
-
-<!DOCTYPE note
-[
+<!-- The DTD file: -->
<!ELEMENT bookstore (book+)>
-<!ELEMENT book (title,price)>
+<!-- The bookstore element may contain one or more child book elements. -->
+<!ELEMENT book (title, price)>
+<!-- Each book must have a title and a price as its children. -->
<!ATTLIST book category CDATA "Literature">
+<!-- A book should have a category attribute. If it doesn't, its default value
+ will be 'Literature'. -->
<!ELEMENT title (#PCDATA)>
+<!-- The element title must only contain parsed character data. That is, it may
+ only contain text which is read by the parser and must not contain children.
+ Compare with CDATA, or character data. -->
<!ELEMENT price (#PCDATA)>
]>
-
-<!-- The DTD starts with a declaration.
- Following, the root node is declared, requiring 1 or more child nodes 'book'.
- Each 'book' should contain exactly one 'title' and 'price' and an attribute
- called 'category', with "Literature" as its default value.
- The 'title' and 'price' nodes contain a parsed character data.-->
-
<!-- The DTD could be declared inside the XML file itself.-->
<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE note
-[
+<!DOCTYPE bookstore [
<!ELEMENT bookstore (book+)>
-<!ELEMENT book (title,price)>
+<!ELEMENT book (title, price)>
<!ATTLIST book category CDATA "Literature">
<!ELEMENT title (#PCDATA)>
<!ELEMENT price (#PCDATA)>
@@ -120,8 +144,23 @@ With this tool, you can check the XML data outside the application logic.
<bookstore>
<book category="COOKING">
- <title >Everyday Italian</title>
+ <title>Everyday Italian</title>
<price>30.00</price>
</book>
</bookstore>
```
+
+## DTD Compatibility and XML Schema Definitions
+
+Support for DTDs is ubiquitous because they are so old. Unfortunately, modern XML features like namespaces are not supported by DTDs. XML Schema Definitions (XSDs) are meant to replace DTDs for defining XML document grammar.
+
+## Resources
+
+* [Validate your XML](http://www.xmlvalidation.com)
+
+## Further Reading
+
+* [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/yaml.html.markdown b/yaml.html.markdown
index 6e3e2c94..507c4d1f 100644
--- a/yaml.html.markdown
+++ b/yaml.html.markdown
@@ -3,6 +3,7 @@ language: yaml
filename: learnyaml.yaml
contributors:
- ["Adam Brenecki", "https://github.com/adambrenecki"]
+ - ["Suhas SG", "https://github.com/jargnar"]
---
YAML is a data serialisation language designed to be directly writable and
@@ -24,6 +25,8 @@ YAML doesn't allow literal tab characters at all.
key: value
another_key: Another value goes here.
a_number_value: 100
+# If you want to use number 1 as a value, you have to enclose it in quotes,
+# otherwise, YAML parser will assume that it is a boolean value of true.
scientific_notation: 1e+12
boolean: true
null_value: null
@@ -66,14 +69,19 @@ a_nested_map:
# Maps don't have to have string keys.
0.25: a float key
-# Keys can also be multi-line objects, using ? to indicate the start of a key.
+# Keys can also be complex, like multi-line objects
+# We use ? followed by a space to indicate the start of a complex key.
? |
This is a key
that has multiple lines
: and this is its value
-# YAML also allows collection types in keys, but many programming languages
-# will complain.
+# YAML also allows mapping between sequences with the complex key syntax
+# Some language parsers might complain
+# An example
+? - Manchester United
+ - Real Madrid
+: [ 2001-01-01, 2002-02-02 ]
# Sequences (equivalent to lists or arrays) look like this:
a_sequence:
@@ -101,12 +109,31 @@ json_seq: [3, 2, 1, "takeoff"]
anchored_content: &anchor_name This string will appear as the value of two keys.
other_anchor: *anchor_name
+# Anchors can be used to duplicate/inherit properties
+base: &base
+ name: Everyone has same name
+
+foo: &foo
+ <<: *base
+ age: 10
+
+bar: &bar
+ <<: *base
+ age: 20
+
+# foo and bar would also have name: Everyone has same name
+
# YAML also has tags, which you can use to explicitly declare types.
explicit_string: !!str 0.5
# Some parsers implement language specific tags, like this one for Python's
# complex number type.
python_complex_number: !!python/complex 1+2j
+# We can also use yaml complex keys with language specific tags
+? !!python/tuple [5, 7]
+: Fifty Seven
+# Would be {(5, 7): 'Fifty Seven'} in python
+
####################
# EXTRA YAML TYPES #
####################
diff --git a/zfs.html.markdown b/zfs.html.markdown
new file mode 100644
index 00000000..39ff84cd
--- /dev/null
+++ b/zfs.html.markdown
@@ -0,0 +1,400 @@
+---
+category: tool
+tool: zfs
+contributors:
+ - ["sarlalian", "http://github.com/sarlalian"]
+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 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.
+
+
+## ZFS Concepts
+
+### Virtual Devices
+
+A VDEV is similar to a raid device presented by a RAID card, there are several different
+types of VDEV's that offer various advantages, including redundancy and speed. In general
+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
+* stripe (a single disk, no redundancy)
+* mirror (n-way mirrors supported)
+* raidz
+ * raidz1 (1-disk parity, similar to RAID 5)
+ * raidz2 (2-disk parity, similar to RAID 6)
+ * raidz3 (3-disk parity, no RAID analog)
+* disk
+* file (not recommended for production due to another filesystem adding unnecessary layering)
+
+Your data is striped across all the VDEV's present in your Storage Pool, so more VDEV's will
+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 visible file system from the physical layout.
+
+### ZFS Dataset
+
+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 de-duplication.
+
+
+### Limits
+
+One directory may contain up to 2^48 files, up to 16 exabytes each. A single storage pool
+can contain up to 256 zettabytes (2^78) of space, and can be striped across 2^64 devices. A
+single host can have 2^64 storage pools. The limits are huge.
+
+
+## Commands
+
+### Storage Pools
+
+Actions:
+* List
+* Status
+* Destroy
+* Get/Set properties
+
+List zpools
+
+```bash
+# Create a raidz zpool
+$ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2
+
+# List ZPools
+$ zpool list
+NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT
+zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE -
+
+# List detailed information about a specific zpool
+$ zpool list -v zroot
+NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT
+zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE -
+ gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 141G 106G 35.2G - 43% 75%
+```
+
+Status of zpools
+
+```bash
+# Get status information about zpools
+$ zpool status
+ pool: zroot
+ state: ONLINE
+ scan: scrub repaired 0 in 2h51m with 0 errors on Thu Oct 1 07:08:31 2015
+config:
+
+ NAME STATE READ WRITE CKSUM
+ zroot ONLINE 0 0 0
+ gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0
+
+errors: No known data errors
+
+# Scrubbing a zpool to correct any errors
+$ zpool scrub zroot
+$ zpool status -v zroot
+ pool: zroot
+ state: ONLINE
+ scan: scrub in progress since Thu Oct 15 16:59:14 2015
+ 39.1M scanned out of 106G at 1.45M/s, 20h47m to go
+ 0 repaired, 0.04% done
+config:
+
+ NAME STATE READ WRITE CKSUM
+ zroot ONLINE 0 0 0
+ gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0
+
+errors: No known data errors
+```
+
+Properties of zpools
+
+```bash
+
+# Getting properties from the pool properties can be user set or system provided.
+$ zpool get all zroot
+NAME PROPERTY VALUE SOURCE
+zroot size 141G -
+zroot capacity 75% -
+zroot altroot - default
+zroot health ONLINE -
+...
+
+# Setting a zpool property
+$ zpool set comment="Storage of mah stuff" zroot
+$ zpool get comment
+NAME PROPERTY VALUE SOURCE
+tank comment - default
+zroot comment Storage of mah stuff local
+```
+
+Remove zpool
+
+```bash
+$ zpool destroy test
+```
+
+
+### Datasets
+
+Actions:
+* Create
+* List
+* Rename
+* Delete
+* Get/Set properties
+
+Create datasets
+
+```bash
+# Create dataset
+$ zfs create tank/root/data
+$ mount | grep data
+tank/root/data on /data (zfs, local, nfsv4acls)
+
+# Create child dataset
+$ zfs create tank/root/data/stuff
+$ mount | grep data
+tank/root/data on /data (zfs, local, nfsv4acls)
+tank/root/data/stuff on /data/stuff (zfs, local, nfsv4acls)
+
+
+# Create Volume
+$ zfs create -V zroot/win_vm
+$ zfs list zroot/win_vm
+NAME USED AVAIL REFER MOUNTPOINT
+tank/win_vm 4.13G 17.9G 64K -
+```
+
+List datasets
+
+```bash
+# List all datasets
+$ zfs list
+NAME USED AVAIL REFER MOUNTPOINT
+zroot 106G 30.8G 144K none
+zroot/ROOT 18.5G 30.8G 144K none
+zroot/ROOT/10.1 8K 30.8G 9.63G /
+zroot/ROOT/default 18.5G 30.8G 11.2G /
+zroot/backup 5.23G 30.8G 144K none
+zroot/home 288K 30.8G 144K none
+...
+
+# List a specific dataset
+$ zfs list zroot/home
+NAME USED AVAIL REFER MOUNTPOINT
+zroot/home 288K 30.8G 144K none
+
+# List snapshots
+$ zfs list -t snapshot
+zroot@daily-2015-10-15 0 - 144K -
+zroot/ROOT@daily-2015-10-15 0 - 144K -
+zroot/ROOT/default@daily-2015-10-15 0 - 24.2G -
+zroot/tmp@daily-2015-10-15 124K - 708M -
+zroot/usr@daily-2015-10-15 0 - 144K -
+zroot/home@daily-2015-10-15 0 - 11.9G -
+zroot/var@daily-2015-10-15 704K - 1.42G -
+zroot/var/log@daily-2015-10-15 192K - 828K -
+zroot/var/tmp@daily-2015-10-15 0 - 152K -
+```
+
+Rename datasets
+
+```bash
+$ zfs rename tank/root/home tank/root/old_home
+$ zfs rename tank/root/new_home tank/root/home
+```
+
+Delete dataset
+
+```bash
+# Datasets cannot be deleted if they have any snapshots
+zfs destroy tank/root/home
+```
+
+Get / set properties of a dataset
+
+```bash
+# Get all properties
+$ zfs get all zroot/usr/home │157 # Create Volume
+NAME PROPERTY VALUE SOURCE │158 $ zfs create -V zroot/win_vm
+zroot/home type filesystem - │159 $ zfs list zroot/win_vm
+zroot/home creation Mon Oct 20 14:44 2014 - │160 NAME USED AVAIL REFER MOUNTPOINT
+zroot/home used 11.9G - │161 tank/win_vm 4.13G 17.9G 64K -
+zroot/home available 94.1G - │162 ```
+zroot/home referenced 11.9G - │163
+zroot/home mounted yes -
+...
+
+# Get property from dataset
+$ zfs get compression zroot/usr/home
+NAME PROPERTY VALUE SOURCE
+zroot/home compression off default
+
+# Set property on dataset
+$ zfs set compression=gzip-9 mypool/lamb
+
+# Get a set of properties from all datasets
+$ zfs list -o name,quota,reservation
+NAME QUOTA RESERV
+zroot none none
+zroot/ROOT none none
+zroot/ROOT/default none none
+zroot/tmp none none
+zroot/usr none none
+zroot/home none none
+zroot/var none none
+...
+```
+
+
+### Snapshots
+
+ZFS snapshots are one of the things about zfs that are a really big deal
+
+* The space they take up is equal to the difference in data between the filesystem and its snapshot
+* Creation time is only seconds
+* Recovery is as fast as you can write data.
+* They are easy to automate.
+
+Actions:
+* Create
+* Delete
+* Rename
+* Access snapshots
+* Send / Receive
+* Clone
+
+
+Create snapshots
+
+```bash
+# Create a snapshot of a single dataset
+zfs snapshot tank/home/sarlalian@now
+
+# Create a snapshot of a dataset and its children
+$ zfs snapshot -r tank/home@now
+$ zfs list -t snapshot
+NAME USED AVAIL REFER MOUNTPOINT
+tank/home@now 0 - 26K -
+tank/home/sarlalian@now 0 - 259M -
+tank/home/alice@now 0 - 156M -
+tank/home/bob@now 0 - 156M -
+...
+
+Destroy snapshots
+
+```bash
+# How to destroy a snapshot
+$ zfs destroy tank/home/sarlalian@now
+
+# Delete a snapshot on a parent dataset and its children
+$ zfs destroy -r tank/home/sarlalian@now
+
+```
+
+Renaming Snapshots
+
+```bash
+# Rename a snapshot
+$ zfs rename tank/home/sarlalian@now tank/home/sarlalian@today
+$ zfs rename tank/home/sarlalian@now today
+
+# zfs rename -r tank/home@now @yesterday
+```
+
+Accessing snapshots
+
+```bash
+# CD Into a snapshot directory
+$ cd /home/.zfs/snapshot/
+```
+
+Sending and Receiving
+
+```bash
+# Backup a snapshot to a file
+$ zfs send tank/home/sarlalian@now | gzip > backup_file.gz
+
+# Send a snapshot to another dataset
+$ zfs send tank/home/sarlalian@now | zfs recv backups/home/sarlalian
+
+# Send a snapshot to a remote host
+$ zfs send tank/home/sarlalian@now | ssh root@backup_server 'zfs recv tank/home/sarlalian'
+
+# Send full dataset with snapshos to new host
+$ zfs send -v -R tank/home@now | ssh root@backup_server 'zfs recv tank/home'
+```
+
+Cloneing Snapshots
+
+```bash
+# Clone a snapshot
+$ zfs clone tank/home/sarlalian@now tank/home/sarlalian_new
+
+# Promoting the clone so it is no longer dependent on the snapshot
+$ zfs promote tank/home/sarlalian_new
+```
+
+### Putting it all together
+
+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.
+
+```bash
+#!/bin/sh
+
+echo "==== Stopping the staging database server ===="
+jail -r staging
+
+echo "==== Cleaning up existing staging server and snapshot ===="
+zfs destroy -r zroot/jails/staging
+zfs destroy zroot/jails/slave@staging
+
+echo "==== Quiescing the slave database ===="
+echo "FLUSH TABLES WITH READ LOCK;" | /usr/local/bin/mysql -u root -pmyrootpassword -h slave
+
+echo "==== Snapshotting the slave db filesystem as zroot/jails/slave@staging ===="
+zfs snapshot zroot/jails/slave@staging
+
+echo "==== Starting the slave database server ===="
+jail -c slave
+
+echo "==== Cloning the slave snapshot to the staging server ===="
+zfs clone zroot/jails/slave@staging zroot/jails/staging
+
+echo "==== Installing the staging mysql config ===="
+mv /jails/staging/usr/local/etc/my.cnf /jails/staging/usr/local/etc/my.cnf.slave
+cp /jails/staging/usr/local/etc/my.cnf.staging /jails/staging/usr/local/etc/my.cnf
+
+echo "==== Setting up the staging rc.conf file ===="
+mv /jails/staging/etc/rc.conf.local /jails/staging/etc/rc.conf.slave
+mv /jails/staging/etc/rc.conf.staging /jails/staging/etc/rc.conf.local
+
+echo "==== Starting the staging db server ===="
+jail -c staging
+
+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
+```
+
+
+### 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)
+* [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)
+* [FreeBSD ZFS Tuning Guide](https://wiki.freebsd.org/ZFSTuningGuide)
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/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown
index 8904970f..b0b1183f 100644
--- a/zh-cn/haskell-cn.html.markdown
+++ b/zh-cn/haskell-cn.html.markdown
@@ -200,13 +200,13 @@ foo 5 -- 75
-- 你可以使用 `$` 来移除多余的括号。
-- 修改前
-(even (fib 7)) -- true
+(even (fib 7)) -- False
-- 修改后
-even . fib $ 7 -- true
+even . fib $ 7 -- False
-- 等价地
-even $ fib 7 -- true
+even $ fib 7 -- False
----------------------------------------------------
-- 5. 类型声明
diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown
index 12afa59a..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;
}
@@ -405,4 +405,4 @@ class PennyFarthing extends Bicycle {
* [泛型](http://docs.oracle.com/javase/tutorial/java/generics/index.html)
-* [Java代码规范](http://www.oracle.com/technetwork/java/codeconv-138413.html)
+* [Java代码规范](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html)
diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown
index 098d0ab5..f7065445 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.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/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown
index c223297c..76455a46 100644
--- a/zh-cn/python3-cn.html.markdown
+++ b/zh-cn/python3-cn.html.markdown
@@ -535,7 +535,7 @@ Human.grunt() # => "*grunt*"
# 用import导入模块
import math
-print(math.sqrt(16)) # => 4
+print(math.sqrt(16)) # => 4.0
# 也可以从模块中导入个别值
from math import ceil, floor
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 28001e3f..3efe4941 100644
--- a/zh-cn/swift-cn.html.markdown
+++ b/zh-cn/swift-cn.html.markdown
@@ -5,7 +5,8 @@ contributors:
- ["Grant Timmerman", "http://github.com/grant"]
translators:
- ["Xavier Yao", "http://github.com/xavieryao"]
- - ["Joey Huang", "http://github.com/kamidox"]
+ - ["Joey Huang", "http://github.com/kamidox"]
+ - ["CY Lim", "http://github.com/cylim"]
lang: zh-cn
---
@@ -13,13 +14,13 @@ Swift 是 Apple 开发的用于 iOS 和 OS X 开发的编程语言。Swift 于20
Swift 的官方语言教程 [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) 可以从 iBooks 免费下载.
-亦可参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html) ——一个完整的Swift 教程
+亦可参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/) ——一个完整的Swift 教程
```swift
// 导入外部模块
import UIKit
-//
+//
// MARK: 基础
//
@@ -28,12 +29,14 @@ import UIKit
// TODO: TODO 标记
// FIXME: FIXME 标记
-println("Hello, world")
+// Swift2.0 println() 及 print() 已经整合成 print()。
+print("Hello, world") // 这是原本的 println(),会自动进入下一行
+print("Hello, world", appendNewLine: false) // 如果不要自动进入下一行,需设定进入下一行为 false
// 变量 (var) 的值设置后可以随意改变
// 常量 (let) 的值设置后不能改变
var myVariable = 42
-let øπΩ = "value" // 可以支持 unicode 变量名
+let øπΩ = "value" // 可以支持 unicode 变量名
let π = 3.1415926
let myConstant = 3.1415926
let explicitDouble: Double = 70 // 明确指定变量类型为 Double ,否则编译器将自动推断变量类型
@@ -46,16 +49,17 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // 格式化字符串
// 条件编译
// 使用 -D 定义编译开关
#if false
- println("Not printed")
+ print("Not printed")
let buildValue = 3
#else
let buildValue = 7
#endif
-println("Build value: \(buildValue)") // Build value: 7
+print("Build value: \(buildValue)") // Build value: 7
/*
- Optionals 是 Swift 的新特性,它允许你存储两种状态的值给 Optional 变量:有效值或 None
-
+ Optionals 是 Swift 的新特性,它允许你存储两种状态的值给 Optional 变量:有效值或 None 。
+ 可在值名称后加个问号 (?) 来表示这个值是 Optional。
+
Swift 要求所有的 Optinal 属性都必须有明确的值,如果为空,则必须明确设定为 nil
Optional<T> 是个枚举类型
@@ -67,13 +71,17 @@ var someOptionalString2: Optional<String> = "optional"
if someOptionalString != nil {
// 变量不为空
if someOptionalString!.hasPrefix("opt") {
- println("has the prefix")
+ print("has the prefix")
}
-
+
let empty = someOptionalString?.isEmpty
}
someOptionalString = nil
+/*
+ 使用 (!) 可以解决无法访问optional值的运行错误。若要使用 (!)来强制解析,一定要确保 Optional 里不是 nil参数。
+*/
+
// 显式解包 optional 变量
var unwrappedString: String! = "Value is expected."
// 下面语句和上面完全等价,感叹号 (!) 是个后缀运算符,这也是个语法糖
@@ -94,7 +102,7 @@ anyObjectVar = "Changed value to a string, not good practice, but possible."
/*
这里是注释
-
+
/*
支持嵌套的注释
*/
@@ -116,6 +124,7 @@ shoppingList[1] = "bottle of water"
let emptyArray = [String]() // 使用 let 定义常量,此时 emptyArray 数组不能添加或删除内容
let emptyArray2 = Array<String>() // 与上一语句等价,上一语句更常用
var emptyMutableArray = [String]() // 使用 var 定义变量,可以向 emptyMutableArray 添加数组元素
+var explicitEmptyMutableStringArray: [String] = [] // 与上一语句等价
// 字典
var occupations = [
@@ -126,6 +135,7 @@ occupations["Jayne"] = "Public Relations" // 修改字典,如果 key 不存
let emptyDictionary = [String: Float]() // 使用 let 定义字典常量,字典常量不能修改里面的值
let emptyDictionary2 = Dictionary<String, Float>() // 与上一语句类型等价,上一语句更常用
var emptyMutableDictionary = [String: Float]() // 使用 var 定义字典变量
+var explicitEmptyMutableDictionary: [String: Float] = [:] // 与上一语句类型等价
//
@@ -136,21 +146,21 @@ var emptyMutableDictionary = [String: Float]() // 使用 var 定义字典变量
let myArray = [1, 1, 2, 3, 5]
for value in myArray {
if value == 1 {
- println("One!")
+ print("One!")
} else {
- println("Not one!")
+ print("Not one!")
}
}
// 字典的 for 循环
var dict = ["one": 1, "two": 2]
for (key, value) in dict {
- println("\(key): \(value)")
+ print("\(key): \(value)")
}
// 区间的 loop 循环:其中 `...` 表示闭环区间,即[-1, 3];`..<` 表示半开闭区间,即[-1,3)
for i in -1...shoppingList.count {
- println(i)
+ print(i)
}
shoppingList[1...2] = ["steak", "peacons"]
// 可以使用 `..<` 来去掉最后一个元素
@@ -163,7 +173,7 @@ while i < 1000 {
// do-while 循环
do {
- println("hello")
+ print("hello")
} while 1 == 2
// Switch 语句
@@ -177,7 +187,7 @@ case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
case let localScopeValue where localScopeValue.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(localScopeValue)?"
-default: // 在 Swift 里,switch 语句的 case 必须处理所有可能的情况,如果 case 无法全部处理,则必须包含 default语句
+default: // 在 Swift 里,switch 语句的 case 必须处理所有可能的情况,如果 case 无法全部处理,则必须包含 default语句
let vegetableComment = "Everything tastes good in soup."
}
@@ -219,8 +229,8 @@ let pricesTuple = getGasPrices()
let price = pricesTuple.2 // 3.79
// 通过下划线 (_) 来忽略不关心的值
let (_, price1, _) = pricesTuple // price1 == 3.69
-println(price1 == pricesTuple.1) // true
-println("Gas price: \(price)")
+print(price1 == pricesTuple.1) // true
+print("Gas price: \(price)")
// 可变参数
func setup(numbers: Int...) {
@@ -248,7 +258,7 @@ func swapTwoInts(inout a: Int, inout b: Int) {
var someIntA = 7
var someIntB = 3
swapTwoInts(&someIntA, &someIntB)
-println(someIntB) // 7
+print(someIntB) // 7
//
@@ -256,7 +266,7 @@ println(someIntB) // 7
//
var numbers = [1, 2, 6]
-// 函数是闭包的一个特例
+// 函数是闭包的一个特例 ({})
// 闭包实例
// `->` 分隔了闭包的参数和返回值
@@ -296,7 +306,7 @@ print(numbers) // [3, 6, 18]
struct NamesTable {
let names = [String]()
-
+
// 自定义下标运算符
subscript(index: Int) -> String {
return names[index]
@@ -306,7 +316,7 @@ struct NamesTable {
// 结构体有一个自动生成的隐含的命名构造函数
let namesTable = NamesTable(names: ["Me", "Them"])
let name = namesTable[1]
-println("Name is \(name)") // Name is Them
+print("Name is \(name)") // Name is Them
//
// MARK: 类
@@ -329,7 +339,7 @@ public class Shape {
internal class Rect: Shape {
// 值属性 (Stored properties)
var sideLength: Int = 1
-
+
// 计算属性 (Computed properties)
private var perimeter: Int {
get {
@@ -340,11 +350,11 @@ internal class Rect: Shape {
sideLength = newValue / 4
}
}
-
+
// 延时加载的属性,只有这个属性第一次被引用时才进行初始化,而不是定义时就初始化
// subShape 值为 nil ,直到 subShape 第一次被引用时才初始化为一个 Rect 实例
lazy var subShape = Rect(sideLength: 4)
-
+
// 监控属性值的变化。
// 当我们需要在属性值改变时做一些事情,可以使用 `willSet` 和 `didSet` 来设置监控函数
// `willSet`: 值改变之前被调用
@@ -352,14 +362,14 @@ internal class Rect: Shape {
var identifier: String = "defaultID" {
// `willSet` 的参数是即将设置的新值,参数名可以指定,如果没有指定,就是 `newValue`
willSet(someIdentifier) {
- println(someIdentifier)
+ print(someIdentifier)
}
// `didSet` 的参数是已经被覆盖掉的旧的值,参数名也可以指定,如果没有指定,就是 `oldValue`
didSet {
- println(oldValue)
+ print(oldValue)
}
}
-
+
// 命名构造函数 (designated inits),它必须初始化所有的成员变量,
// 然后调用父类的命名构造函数继续初始化父类的所有变量。
init(sideLength: Int) {
@@ -367,13 +377,13 @@ internal class Rect: Shape {
// 必须显式地在构造函数最后调用父类的构造函数 super.init
super.init()
}
-
+
func shrink() {
if sideLength > 0 {
--sideLength
}
}
-
+
// 函数重载使用 override 关键字
override func getArea() -> Int {
return sideLength * sideLength
@@ -394,16 +404,16 @@ class Square: Rect {
}
var mySquare = Square()
-println(mySquare.getArea()) // 25
+print(mySquare.getArea()) // 25
mySquare.shrink()
-println(mySquare.sideLength) // 4
+print(mySquare.sideLength) // 4
// 类型转换
let aShape = mySquare as Shape
// 使用三个等号来比较是不是同一个实例
if mySquare === aShape {
- println("Yep, it's mySquare")
+ print("Yep, it's mySquare")
}
class Circle: Shape {
@@ -411,12 +421,12 @@ class Circle: Shape {
override func getArea() -> Int {
return 3 * radius * radius
}
-
+
// optional 构造函数,可能会返回 nil
init?(radius: Int) {
self.radius = radius
super.init()
-
+
if radius <= 0 {
return nil
}
@@ -425,13 +435,13 @@ class Circle: Shape {
// 根据 Swift 类型推断,myCircle 是 Optional<Circle> 类型的变量
var myCircle = Circle(radius: 1)
-println(myCircle?.getArea()) // Optional(3)
-println(myCircle!.getArea()) // 3
+print(myCircle?.getArea()) // Optional(3)
+print(myCircle!.getArea()) // 3
var myEmptyCircle = Circle(radius: -1)
-println(myEmptyCircle?.getArea()) // "nil"
+print(myEmptyCircle?.getArea()) // "nil"
if let circle = myEmptyCircle {
// 此语句不会输出,因为 myEmptyCircle 变量值为 nil
- println("circle is not nil")
+ print("circle is not nil")
}
@@ -461,7 +471,7 @@ enum BookName: String {
case John = "John"
case Luke = "Luke"
}
-println("Name: \(BookName.John.rawValue)")
+print("Name: \(BookName.John.rawValue)")
// 与特定数据类型关联的枚举
enum Furniture {
@@ -469,7 +479,7 @@ enum Furniture {
case Desk(height: Int)
// 和 String, Int 关联的枚举记录
case Chair(brand: String, height: Int)
-
+
func description() -> String {
switch self {
case .Desk(let height):
@@ -481,9 +491,9 @@ enum Furniture {
}
var desk: Furniture = .Desk(height: 80)
-println(desk.description()) // "Desk with 80 cm"
+print(desk.description()) // "Desk with 80 cm"
var chair = Furniture.Chair(brand: "Foo", height: 40)
-println(chair.description()) // "Chair of Foo with 40 cm"
+print(chair.description()) // "Chair of Foo with 40 cm"
//
@@ -512,7 +522,7 @@ protocol ShapeGenerator {
class MyShape: Rect {
var delegate: TransformShape?
-
+
func grow() {
sideLength += 2
@@ -539,21 +549,21 @@ extension Square: Printable {
}
}
-println("Square: \(mySquare)") // Area: 16 - ID: defaultID
+print("Square: \(mySquare)") // Area: 16 - ID: defaultID
// 也可以给系统内置类型添加功能支持
extension Int {
var customProperty: String {
return "This is \(self)"
}
-
+
func multiplyBy(num: Int) -> Int {
return num * self
}
}
-println(7.customProperty) // "This is 7"
-println(14.multiplyBy(3)) // 42
+print(7.customProperty) // "This is 7"
+print(14.multiplyBy(3)) // 42
// 泛型: 和 Java 及 C# 的泛型类似,使用 `where` 关键字来限制类型。
// 如果只有一个类型限制,可以省略 `where` 关键字
@@ -566,7 +576,7 @@ func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
return nil
}
let foundAtIndex = findIndex([1, 2, 3, 4], 3)
-println(foundAtIndex == 2) // true
+print(foundAtIndex == 2) // true
// 自定义运算符:
// 自定义运算符可以以下面的字符打头:
@@ -581,11 +591,24 @@ prefix func !!! (inout shape: Square) -> Square {
}
// 当前值
-println(mySquare.sideLength) // 4
+print(mySquare.sideLength) // 4
// 使用自定义的 !!! 运算符来把矩形边长放大三倍
!!!mySquare
-println(mySquare.sideLength) // 12
+print(mySquare.sideLength) // 12
-```
+// 运算符也可以是泛型
+infix operator <-> {}
+func <-><T: Equatable> (inout a: T, inout b: T) {
+ let c = a
+ a = b
+ b = c
+}
+var foo: Float = 10
+var bar: Float = 20
+
+foo <-> bar
+print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0"
+
+```
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-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)