summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--.github/CODEOWNERS6
-rw-r--r--.github/ISSUE_TEMPLATE.md (renamed from ISSUE_TEMPLATE.md)0
-rw-r--r--.github/PULL_REQUEST_TEMPLATE.md (renamed from PULL_REQUEST_TEMPLATE.md)2
-rw-r--r--CHICKEN.html.markdown16
-rw-r--r--CONTRIBUTING.markdown4
-rw-r--r--bash.html.markdown64
-rw-r--r--c++.html.markdown26
-rw-r--r--c.html.markdown182
-rw-r--r--chapel.html.markdown2
-rw-r--r--clojure.html.markdown4
-rw-r--r--cobol.html.markdown6
-rw-r--r--coq.html.markdown8
-rw-r--r--crystal.html.markdown70
-rw-r--r--cs-cz/markdown.html.markdown342
-rw-r--r--csharp.html.markdown51
-rw-r--r--dart.html.markdown12
-rw-r--r--de-de/bash-de.html.markdown2
-rw-r--r--de-de/elixir-de.html.markdown4
-rw-r--r--de-de/nix-de.html.markdown3
-rw-r--r--de-de/ruby-de.html.markdown2
-rw-r--r--de-de/rust-de.html.markdown2
-rw-r--r--de-de/swift-de.html.markdown2
-rw-r--r--docker.html.markdown13
-rw-r--r--easylang.html.markdown221
-rw-r--r--el-gr/bash-gr.html.markdown2
-rw-r--r--el-gr/ocaml-gr.html.markdown381
-rw-r--r--el-gr/rust-gr.html.markdown2
-rw-r--r--el-gr/vim-gr.html.markdown2
-rw-r--r--elixir.html.markdown2
-rw-r--r--es-es/bash-es.html.markdown2
-rw-r--r--es-es/c++-es.html.markdown67
-rw-r--r--es-es/docker-es.html.markdown167
-rw-r--r--es-es/matlab-es.html.markdown2
-rw-r--r--es-es/objective-c-es.html.markdown2
-rw-r--r--es-es/rust-es.html.markdown2
-rw-r--r--es-es/swift-es.html.markdown2
-rw-r--r--es-es/typescript-es.html.markdown2
-rw-r--r--fi-fi/ruby-fi.html.markdown2
-rw-r--r--fish.html.markdown313
-rw-r--r--fortran95.html.markdown1
-rw-r--r--fr-fr/asymptotic-notation-fr.html.markdown14
-rw-r--r--fr-fr/bash-fr.html.markdown2
-rw-r--r--fr-fr/java-fr.html.markdown64
-rw-r--r--fr-fr/objective-c-fr.html.markdown4
-rw-r--r--fr-fr/rust-fr.html.markdown2
-rw-r--r--fr-fr/set-theory-fr.html.markdown134
-rw-r--r--fr-fr/typescript-fr.html.markdown2
-rw-r--r--gdscript.html.markdown322
-rw-r--r--go.html.markdown10
-rw-r--r--haskell.html.markdown2
-rw-r--r--hd-hd/json-hd.html.markdown86
-rw-r--r--hdl.html.markdown4
-rw-r--r--html.html.markdown12
-rw-r--r--id-id/ruby-id.html.markdown2
-rw-r--r--images/solidity/copy-address.pngbin0 -> 75859 bytes
-rw-r--r--images/solidity/metamask-kovan.pngbin0 -> 167647 bytes
-rw-r--r--images/solidity/remix-add-token.pngbin0 -> 94850 bytes
-rw-r--r--images/solidity/remix-choose-file.pngbin0 -> 474613 bytes
-rw-r--r--images/solidity/remix-compile.pngbin0 -> 757033 bytes
-rw-r--r--images/solidity/remix-deploy.pngbin0 -> 755589 bytes
-rw-r--r--images/solidity/remix-interact.pngbin0 -> 792300 bytes
-rw-r--r--images/solidity/remix-solidity.pngbin0 -> 343697 bytes
-rw-r--r--images/solidity/remix-testnet.pngbin0 -> 869929 bytes
-rw-r--r--images/solidity/send-link.pngbin0 -> 120488 bytes
-rw-r--r--it-it/bash-it.html.markdown2
-rw-r--r--it-it/ruby-it.html.markdown2
-rw-r--r--it-it/rust-it.html.markdown2
-rw-r--r--ja-jp/vim-jp.html.markdown275
-rw-r--r--janet.html.markdown2
-rw-r--r--java.html.markdown53
-rw-r--r--javascript.html.markdown2
-rw-r--r--jsonnet.html.markdown2
-rw-r--r--julia.html.markdown65
-rw-r--r--ko-kr/yaml-kr.html.markdown113
-rw-r--r--kotlin.html.markdown4
-rw-r--r--lambda-calculus.html.markdown2
-rw-r--r--latex.html.markdown59
-rw-r--r--lua.html.markdown13
-rw-r--r--markdown.html.markdown65
-rw-r--r--matlab.html.markdown2
-rw-r--r--mips.html.markdown8
-rw-r--r--mongodb.html.markdown405
-rw-r--r--ms-my/bash-my.html.markdown2
-rw-r--r--nix.html.markdown5
-rw-r--r--nl-nl/bash-nl.html.markdown2
-rw-r--r--no-nb/bash-no.html.markdown2
-rw-r--r--objective-c.html.markdown2
-rw-r--r--ocaml.html.markdown2
-rw-r--r--opencv.html.markdown1
-rw-r--r--pascal.html.markdown12
-rw-r--r--perl.html.markdown6
-rw-r--r--phel.html.markdown337
-rw-r--r--php.html.markdown6
-rw-r--r--pt-br/bash-pt.html.markdown2
-rw-r--r--pt-br/css-pt.html.markdown4
-rw-r--r--pt-br/r-pt.html.markdown786
-rw-r--r--pt-br/rust-pt.html.markdown3
-rw-r--r--pt-br/solidity-pt.html.markdown2
-rw-r--r--pt-br/swift-pt.html.markdown2
-rw-r--r--pt-br/typescript-pt.html.markdown2
-rw-r--r--pt-pt/swift-pt.html.markdown2
-rw-r--r--pug.html.markdown10
-rw-r--r--purescript.html.markdown119
-rw-r--r--python.html.markdown5
-rw-r--r--qsharp.html.markdown4
-rw-r--r--r.html.markdown297
-rw-r--r--racket.html.markdown27
-rw-r--r--raku.html.markdown945
-rw-r--r--ro-ro/bash-ro.html.markdown2
-rw-r--r--ru-ru/bash-ru.html.markdown2
-rw-r--r--ru-ru/c-ru.html.markdown2
-rw-r--r--ru-ru/forth-ru.html.markdown3
-rw-r--r--ru-ru/javascript-ru.html.markdown2
-rw-r--r--ru-ru/kotlin-ru.html.markdown2
-rw-r--r--ru-ru/lua-ru.html.markdown4
-rw-r--r--ru-ru/objective-c-ru.html.markdown6
-rw-r--r--ru-ru/rust-ru.html.markdown2
-rw-r--r--ru-ru/swift-ru.html.markdown4
-rw-r--r--ruby.html.markdown2
-rw-r--r--rust.html.markdown26
-rw-r--r--scala.html.markdown6
-rw-r--r--set-theory.html.markdown6
-rw-r--r--sing.html.markdown446
-rw-r--r--sk-sk/bash-sk.html.markdown2
-rw-r--r--solidity.html.markdown140
-rw-r--r--sv-se/nix-sv.html.markdown5
-rw-r--r--swift.html.markdown6
-rw-r--r--tcl.html.markdown2
-rw-r--r--texinfo.html.markdown183
-rwxr-xr-xtoml.html.markdown5
-rw-r--r--typescript.html.markdown11
-rw-r--r--uk-ua/c-ua.html.markdown860
-rw-r--r--uk-ua/mips-ua.html.markdown2
-rw-r--r--uk-ua/ruby-ua.html.markdown2
-rw-r--r--uk-ua/rust-ua.html.markdown2
-rw-r--r--uxntal.html.markdown174
-rwxr-xr-xvala.html.markdown12
-rw-r--r--vi-vn/objective-c-vi.html.markdown2
-rw-r--r--vim.html.markdown13
-rw-r--r--visualbasic.html.markdown3
-rw-r--r--wasm.html.markdown2
-rw-r--r--zh-cn/asciidoc-cn.html.markdown135
-rw-r--r--zh-cn/bash-cn.html.markdown2
-rw-r--r--zh-cn/c-cn.html.markdown2
-rw-r--r--zh-cn/cmake-cn.html.markdown168
-rw-r--r--zh-cn/docker-cn.html.markdown149
-rw-r--r--zh-cn/dynamic-programming-cn.html.markdown2
-rw-r--r--zh-cn/go-cn.html.markdown10
-rw-r--r--zh-cn/java-cn.html.markdown4
-rw-r--r--zh-cn/mips-cn.html.markdown334
-rw-r--r--zh-cn/nim-cn.html.markdown283
-rw-r--r--zh-cn/perl-cn.html.markdown8
-rw-r--r--zh-cn/python-cn.html.markdown740
-rw-r--r--zh-cn/qt-cn.html.markdown160
-rw-r--r--zh-cn/raylib-cn.html.markdown147
-rw-r--r--zh-cn/red-cn.html.markdown12
-rw-r--r--zh-cn/ruby-cn.html.markdown2
-rw-r--r--zh-cn/rust-cn.html.markdown2
-rw-r--r--zh-cn/set-theory-cn.html.markdown138
-rw-r--r--zh-cn/solidity-cn.html.markdown2
-rw-r--r--zh-cn/sql-cn.html.markdown (renamed from zh-cn/sql.html.markdown)0
-rw-r--r--zh-cn/swift-cn.html.markdown2
-rw-r--r--zh-cn/wolfram-cn.html.markdown140
-rw-r--r--zh-tw/bash-tw.html.markdown2
-rw-r--r--zh-tw/perl-tw.html.markdown328
165 files changed, 9512 insertions, 1519 deletions
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
new file mode 100644
index 00000000..6c1efe0d
--- /dev/null
+++ b/.github/CODEOWNERS
@@ -0,0 +1,6 @@
+/fr-fr/ @vendethiel
+/ru-ru/ @Menelion
+/uk-ua/ @Menelion
+/zh-cn/ @geoffliu @imba-tjd
+/zh-tw/ @geoffliu @imba-tjd
+/ko-kr/ @justin-themedium
diff --git a/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
index 96278da9..96278da9 100644
--- a/ISSUE_TEMPLATE.md
+++ b/.github/ISSUE_TEMPLATE.md
diff --git a/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index fd9d1b31..6a496409 100644
--- a/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -1,5 +1,5 @@
- [ ] I solemnly swear that this is all original content of which I am the original author
-- [ ] Pull request title is prepended with `[language/lang-code]`
+- [ ] Pull request title is prepended with `[language/lang-code]` (example `[python/fr-fr]` or `[java/en]`)
- [ ] Pull request 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)
- [ ] If you've changed any part of the YAML Frontmatter, make sure it is formatted according to [CONTRIBUTING.md](https://github.com/adambard/learnxinyminutes-docs/blob/master/CONTRIBUTING.markdown)
diff --git a/CHICKEN.html.markdown b/CHICKEN.html.markdown
index 3f7cc2db..4ae45cac 100644
--- a/CHICKEN.html.markdown
+++ b/CHICKEN.html.markdown
@@ -362,8 +362,6 @@ sqr ;; => #<procedure (sqr x)>
;; The CHICKEN core is very minimal, but additional features are provided by library extensions known as Eggs.
;; You can install Eggs with 'chicken-install <eggname>' command.
-;; 'numbers' egg provides support for full numeric tower.
-(require-extension numbers)
;; complex numbers
3+4i ;; => 3+2i
;; Supports fractions without falling back to inexact flonums
@@ -375,12 +373,12 @@ sqr ;; => #<procedure (sqr x)>
(numerator 2/3) ;; => 2
;; 'utf8' provides unicode support
-(require-extension utf8)
+(import utf8)
"\u03BBx:(\u03BC\u0251.\u0251\u2192\u0251).xx" ;; => "λx:(μɑ.ɑ→ɑ).xx"
;; 'posix' provides file I/O and lots of other services for unix-like operating systems
;; Some of the functions are not available in Windows system,
-;; See http://wiki.call-cc.org/man/4/Unit%20posix for more details
+;; See http://wiki.call-cc.org/man/5/Module%20(chicken%20file%20posix) for more details
;; Open a file to append, open "write only" and create file if it does not exist
(define outfn (file-open "chicken-hen.txt" (+ open/append open/wronly open/creat)))
@@ -396,14 +394,14 @@ sqr ;; => #<procedure (sqr x)>
;; CHICKEN also supports SRFI (Scheme Requests For Implementation) extensions
;; See 'http://srfi.schemers.org/srfi-implementers.html" to see srfi's supported by CHICKEN
-(require-extension srfi-1) ;; list library
+(import srfi-1) ;; list library
(filter odd? '(1 2 3 4 5 6 7)) ;; => (1 3 5 7)
(count even? '(1 2 3 4 5)) ;; => 2
(take '(12 24 36 48 60) 3) ;; => (12 24 36)
(drop '(12 24 36 48 60) 2) ;; => (36 48 60)
(circular-list 'z 'q) ;; => z q z q ...
-(require-extension srfi-13) ;; string library
+(import srfi-13) ;; string library
(string-reverse "pan") ;; => "nap"
(string-index "Turkey" #\k) ;; => 3
(string-every char-upper-case? "CHICKEN") ;; => #t
@@ -448,7 +446,7 @@ sqr ;; => #<procedure (sqr x)>
; 9. Modules
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;; Also See http://wiki.call-cc.org/man/4/Modules
+;; Also See http://wiki.call-cc.org/man/5/Modules
;; The 'test' module exports a value named 'hello' and a macro named 'greet'
(module test (hello greet)
@@ -509,11 +507,11 @@ sqr ;; => #<procedure (sqr x)>
```
## Further Reading
-* [CHICKEN User's Manual](http://wiki.call-cc.org/man/4/The%20User%27s%20Manual).
+* [CHICKEN User's Manual](https://wiki.call-cc.org/manual).
* [R5RS standards](http://www.schemers.org/Documents/Standards/R5RS)
## Extra Info
-* [For programmers of other languages](http://wiki.call-cc.org/chicken-for-programmers-of-other-languages)
+* [For programmers of other languages](https://wiki.call-cc.org/chicken-for-programmers-of-other-languages)
* [Compare CHICKEN syntax with other languages](http://plr.sourceforge.net/cgi-bin/plr/launch.py)
diff --git a/CONTRIBUTING.markdown b/CONTRIBUTING.markdown
index 3dfd38ce..8d2a8320 100644
--- a/CONTRIBUTING.markdown
+++ b/CONTRIBUTING.markdown
@@ -16,7 +16,7 @@ review them more effectively and/or individually.
## Style Guidelines
-- **Keep lines of under 80 chars**
+- **Keep lines 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**
@@ -78,7 +78,7 @@ lang: ep-ep
If you want to add yourself to contributors, keep in mind that contributors get
equal billing, and the first contributor usually wrote the whole article. Please
-use your judgement when deciding if your contribution constitutes a substantial
+use your judgment when deciding if your contribution constitutes a substantial
addition or not.
## Building the site locally
diff --git a/bash.html.markdown b/bash.html.markdown
index 7ca4285b..8fdfdf08 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -17,6 +17,7 @@ contributors:
- ["John Detter", "https://github.com/jdetter"]
- ["Harry Mumford-Turner", "https://github.com/harrymt"]
- ["Martin Nicholson", "https://github.com/mn113"]
+ - ["Mark Grimwood", "https://github.com/MarkGrimwood"]
filename: LearnBash.sh
translators:
- ["Dimitri Kokkonis", "https://github.com/kokkonisd"]
@@ -27,12 +28,12 @@ for the GNU operating system and as the default shell on most Linux distros.
Nearly all examples below can be a part of a shell script
or executed directly in the shell.
-[Read more here.](http://www.gnu.org/software/bash/manual/bashref.html)
+[Read more here.](https://www.gnu.org/software/bash/manual/bashref.html)
```bash
#!/usr/bin/env bash
# First line of the script is the shebang which tells the system how to execute
-# the script: http://en.wikipedia.org/wiki/Shebang_(Unix)
+# the script: https://en.wikipedia.org/wiki/Shebang_(Unix)
# As you already figured, comments start with #. Shebang is also a comment.
# Simple hello world example:
@@ -178,6 +179,19 @@ echo "Always executed" && echo "Only executed if first command does NOT fail"
# => Always executed
# => Only executed if first command does NOT fail
+# A single ampersand & after a command runs it in the background. A background command's
+# output is printed to the terminal, but it cannot read from the input.
+sleep 30 &
+# List background jobs
+jobs # => [1]+ Running sleep 30 &
+# Bring the background job to the foreground
+fg
+# Ctrl-C to kill the process, or Ctrl-Z to pause it
+# Resume a background process after it has been paused with Ctrl-Z
+bg
+# Kill job number 2
+kill %2
+# %1, %2, etc. can be used for fg and bg as well
# To use && and || with if statements, you need multiple pairs of square brackets:
if [ "$Name" == "Steve" ] && [ "$Age" -eq 15 ]
@@ -198,7 +212,7 @@ then
fi
# Note that =~ only works within double [[ ]] square brackets,
# which are subtly different from single [ ].
-# See http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs for more on this.
+# See https://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs for more on this.
# Redefine command `ping` as alias to send only 5 packets
alias ping='ping -c 5'
@@ -220,7 +234,8 @@ ls -l # Lists every file and directory on a separate line
ls -t # Sorts the directory contents by last-modified date (descending)
ls -R # Recursively `ls` this directory and all of its subdirectories
-# Results of the previous command can be passed to the next command as input.
+# Results (stdout) of the previous command can be passed as input (stdin) to the next command
+# using a pipe |. Commands chained in this way are called a "pipeline", and are run concurrently.
# The `grep` command filters the input with provided patterns.
# That's how we can list .txt files in the current directory:
ls -l | grep "\.txt"
@@ -260,7 +275,7 @@ cd # also goes to home directory
cd .. # go up one directory
# (^^say, from /home/username/Downloads to /home/username)
cd /home/username/Documents # change to specified directory
-cd ~/Documents/.. # still in home directory..isn't it??
+cd ~/Documents/.. # now in home directory (if ~/Documents exists)
cd - # change to last directory
# => /home/username/Documents
@@ -275,9 +290,13 @@ mkdir -p myNewDir/with/intermediate/directories
# if the intermediate directories didn't already exist, running the above
# command without the `-p` flag would return an error
-# You can redirect command input and output (stdin, stdout, and stderr).
+# You can redirect command input and output (stdin, stdout, and stderr)
+# using "redirection operators". Unlike a pipe, which passes output to a command,
+# a redirection operator has a command's input come from a file or stream, or
+# sends its output to a file or stream.
+
# Read from stdin until ^EOF$ and overwrite hello.py with the lines
-# between "EOF":
+# between "EOF" (which are called a "here document"):
cat > hello.py << EOF
#!/usr/bin/env python
from __future__ import print_function
@@ -299,6 +318,8 @@ python hello.py 2> "error.err" # redirect error output to error.err
python hello.py > "output-and-error.log" 2>&1
# redirect both output and errors to output-and-error.log
+# &1 means file descriptor 1 (stdout), so 2>&1 redirects stderr (2) to the current
+# destination of stdout (1), which has been redirected to output-and-error.log.
python hello.py > /dev/null 2>&1
# redirect all output and errors to the black hole, /dev/null, i.e., no output
@@ -325,6 +346,9 @@ echo "#helloworld" | tee output.out >/dev/null
# WARNING: `rm` commands cannot be undone
rm -v output.out error.err output-and-error.log
rm -r tempDir/ # recursively delete
+# You can install the `trash-cli` Python package to have `trash`
+# which puts files in the system trash and doesn't delete them directly
+# see https://pypi.org/project/trash-cli/ if you want to be careful
# Commands can be substituted within other commands using $( ):
# The following command displays the number of files and directories in the
@@ -332,15 +356,15 @@ rm -r tempDir/ # recursively delete
echo "There are $(ls | wc -l) items here."
# The same can be done using backticks `` but they can't be nested -
-#the preferred way is to use $( ).
+# the preferred way is to use $( ).
echo "There are `ls | wc -l` items here."
# Bash uses a `case` statement that works similarly to switch in Java and C++:
case "$Variable" in
- #List patterns for the conditions you want to meet
+ # List patterns for the conditions you want to meet
0) echo "There is a zero.";;
1) echo "There is a one.";;
- *) echo "It is not null.";;
+ *) echo "It is not null.";; # match everything
esac
# `for` loops iterate for as many arguments given:
@@ -377,6 +401,13 @@ do
cat "$Output"
done
+# Bash can also accept patterns, like this to `cat`
+# all the Markdown files in current directory
+for Output in ./*.markdown
+do
+ cat "$Output"
+done
+
# while loop:
while [ true ]
do
@@ -392,13 +423,17 @@ function foo ()
echo "Arguments work just like script arguments: $@"
echo "And: $1 $2..."
echo "This is a function"
- return 0
+ returnValue=0 # Variable values can be returned
+ return $returnValue
}
# Call the function `foo` with two arguments, arg1 and arg2:
foo arg1 arg2
# => Arguments work just like script arguments: arg1 arg2
# => And: arg1 arg2...
# => This is a function
+# Return values can be obtained with $?
+resultValue=$?
+# More than 9 arguments are also possible by using braces, e.g. ${10}, ${11}, ...
# or simply
bar ()
@@ -419,7 +454,7 @@ tail -n 10 file.txt
# prints first 10 lines of file.txt
head -n 10 file.txt
-# sort file.txt's lines
+# print file.txt's lines in sorted order
sort file.txt
# report or omit repeated lines, with -d it reports them
@@ -431,6 +466,8 @@ cut -d ',' -f 1 file.txt
# replaces every occurrence of 'okay' with 'great' in file.txt
# (regex compatible)
sed -i 's/okay/great/g' file.txt
+# be aware that this -i flag means that file.txt will be changed
+# -i or --in-place erase the input file (use --in-place=.backup to keep a back-up)
# print to stdout all lines of file.txt which match some regex
# The example prints lines which begin with "foo" and end in "bar"
@@ -448,7 +485,7 @@ grep -rI "^foo.*bar$" someDir/ # recursively `grep`, but ignore binary files
grep "^foo.*bar$" file.txt | grep -v "baz"
# if you literally want to search for the string,
-# and not the regex, use fgrep (or grep -F)
+# and not the regex, use `fgrep` (or `grep -F`)
fgrep "foobar" file.txt
# The `trap` command allows you to execute a command whenever your script
@@ -457,6 +494,7 @@ fgrep "foobar" file.txt
trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM
# `sudo` is used to perform commands as the superuser
+# usually it will ask interactively the password of superuser
NAME1=$(whoami)
NAME2=$(sudo whoami)
echo "Was $NAME1, then became more powerful $NAME2"
diff --git a/c++.html.markdown b/c++.html.markdown
index 948b52ec..038c3900 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -2,16 +2,16 @@
language: c++
filename: learncpp.cpp
contributors:
- - ["Steven Basart", "http://github.com/xksteven"]
+ - ["Steven Basart", "https://github.com/xksteven"]
- ["Matt Kline", "https://github.com/mrkline"]
- ["Geoff Liu", "http://geoffliu.me"]
- - ["Connor Waters", "http://github.com/connorwaters"]
- - ["Ankush Goyal", "http://github.com/ankushg07"]
+ - ["Connor Waters", "https://github.com/connorwaters"]
+ - ["Ankush Goyal", "https://github.com/ankushg07"]
- ["Jatin Dhankhar", "https://github.com/jatindhankhar"]
---
C++ is a systems programming language that,
-[according to its inventor Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote),
+[according to its inventor Bjarne Stroustrup](https://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote),
was designed to
- be a "better C"
@@ -37,7 +37,7 @@ one of the most widely-used programming languages.
// Just like in C, your program's entry point is a function called
// main with an integer return type.
// This value serves as the program's exit status.
-// See http://en.wikipedia.org/wiki/Exit_status for more information.
+// See https://en.wikipedia.org/wiki/Exit_status for more information.
int main(int argc, char** argv)
{
// Command line arguments are passed in by argc and argv in the same way
@@ -483,7 +483,7 @@ public:
void setOwner(const std::string& dogsOwner);
// Override the behavior of the print function for all OwnedDogs. See
- // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
+ // https://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
// for a more general introduction if you are unfamiliar with
// subtype polymorphism.
// The override keyword is optional but makes sure you are actually
@@ -616,7 +616,7 @@ boxOfBox.insert(intBox);
// template<typename T>
// instead. The 'class' keyword and 'typename' keywords are _mostly_
// interchangeable in this case. For the full explanation, see
-// http://en.wikipedia.org/wiki/Typename
+// https://en.wikipedia.org/wiki/Typename
// (yes, that keyword has its own Wikipedia page).
// Similarly, a template function:
@@ -660,7 +660,7 @@ printMessage<10>(); // Prints "Learn C++ faster in only 10 minutes!"
/////////////////////
// The standard library provides a few exception types
-// (see http://en.cppreference.com/w/cpp/error/exception)
+// (see https://en.cppreference.com/w/cpp/error/exception)
// but any type can be thrown as an exception
#include <exception>
#include <stdexcept>
@@ -946,7 +946,7 @@ mymap.insert(pair<char,int>('Z',26));
// To iterate
map<char,int>::iterator it;
for (it=mymap.begin(); it!=mymap.end(); ++it)
- std::cout << it->first << "->" << it->second << std::cout;
+ std::cout << it->first << "->" << it->second << std::endl;
// Output:
// A->1
// Z->26
@@ -1030,7 +1030,7 @@ 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
+// More on Lambdas in C++ : https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11
///////////////////////////////
// Range For (C++11 and above)
@@ -1106,7 +1106,8 @@ f1 = f2;
#include<tuple>
-// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members,
+// 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.
@@ -1195,5 +1196,6 @@ compl 4 // Performs a bitwise not
Further Reading:
* An up-to-date language reference can be found at [CPP Reference](http://cppreference.com/w/cpp).
-* Additional resources may be found at [CPlusPlus](http://cplusplus.com).
+* A tutorial for beginners or experts, covering many modern features and good practices: [LearnCpp.com](https://www.learncpp.com/)
* A tutorial covering basics of language and setting up coding environment is available at [TheChernoProject - C++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb).
+* Additional resources may be found at [CPlusPlus](http://cplusplus.com).
diff --git a/c.html.markdown b/c.html.markdown
index a57be1dc..90b5ed2d 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -46,31 +46,47 @@ Multi-line comments don't nest /* Be careful */ // comment ends on this line...
// Enumeration constants are also ways to declare constants.
// All statements must end with a semicolon
-enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT};
+enum days {SUN, MON, TUE, WED, THU, FRI, SAT};
+// SUN gets 0, MON gets 1, TUE gets 2, etc.
+
+// Enumeration values can also be specified
+enum days {SUN = 1, MON, TUE, WED = 99, THU, FRI, SAT};
// MON gets 2 automatically, TUE gets 3, etc.
+// WED get 99, THU gets 100, FRI gets 101, etc.
// Import headers with #include
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
-// (File names between <angle brackets> are headers from the C standard library.)
-// For your own headers, use double quotes instead of angle brackets:
-//#include "my_header.h"
+// File names between <angle brackets> tell the compiler to look in your system
+// libraries for the headers.
+// For your own headers, use double quotes instead of angle brackets, and
+// provide the path:
+#include "my_header.h" // local file
+#include "../my_lib/my_lib_header.h" //relative path
// Declare function signatures in advance in a .h file, or at the top of
// your .c file.
void function_1();
int function_2(void);
-// Must declare a 'function prototype' before main() when functions occur after
-// your main() function.
+// At a minimum, you must declare a 'function prototype' before its use in any function.
+// Normally, prototypes are placed at the top of a file before any function definition.
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.
+// Function prototypes are not necessary if the function definition comes before
+// any other function that calls that function. However, it's standard practice to
+// always add the function prototype to a header file (*.h) and then #include that
+// file at the top. This prevents any issues where a function might be called
+// before the compiler knows of its existence, while also giving the developer a
+// clean header file to share with the rest of the project.
+
+// Your program's entry point is a function called "main". The return type can
+// be anything, however most operating systems expect a return type of `int` for
+// error code processing.
int main(void) {
// your program
}
@@ -96,13 +112,14 @@ int main (int argc, char** argv)
// For the sake of the tutorial, variables are declared dynamically under
// C99-compliant standards.
- // ints are usually 4 bytes
+ // ints are usually 4 bytes (use the `sizeof` operator to check)
int x_int = 0;
- // shorts are usually 2 bytes
+ // shorts are usually 2 bytes (use the `sizeof` operator to check)
short x_short = 0;
- // chars are guaranteed to be 1 byte
+ // chars are defined as the smallest addressable unit for a processor.
+ // This is usually 1 byte, but for some systems it can be more (ex. for TMS320 from TI it's 2 bytes).
char x_char = 0;
char y_char = 'y'; // Char literals are quoted with ''
@@ -145,19 +162,25 @@ int main (int argc, char** argv)
int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes
// (assuming 4-byte words)
- // You can initialize an array to 0 thusly:
- char my_array[20] = {0};
+ // You can initialize an array of twenty ints that all equal 0 thusly:
+ int my_array[20] = {0};
// where the "{0}" part is called an "array initializer".
- // NOTE that you get away without explicitly declaring the size of the array,
- // IF you initialize the array on the same line. So, the following declaration
- // is equivalent:
- char my_array[] = {0};
- // BUT, then you have to evaluate the size of the array at run-time, like this:
+ // All elements (if any) past the ones in the initializer are initialized to 0:
+ int my_array[5] = {1, 2};
+ // So my_array now has five elements, all but the first two of which are 0:
+ // [1, 2, 0, 0, 0]
+ // NOTE that you get away without explicitly declaring the size
+ // of the array IF you initialize the array on the same line:
+ int my_array[] = {0};
+ // NOTE that, when not declaring the size, the size of the array is the number
+ // of elements in the initializer. With "{0}", my_array is now of size one: [0]
+ // To evaluate the size of the array at run-time, divide its byte size by the
+ // byte size of its element type:
size_t my_array_size = sizeof(my_array) / sizeof(my_array[0]);
- // WARNING If you adopt this approach, you should evaluate the size *before*
- // you begin passing the array to function (see later discussion), because
- // arrays get "downgraded" to raw pointers when they are passed to functions
- // (so the statement above will produce the wrong result inside the function).
+ // WARNING You should evaluate the size *before* you begin passing the array
+ // to functions (see later discussion) because arrays get "downgraded" to
+ // raw pointers when they are passed to functions (so the statement above
+ // will produce the wrong result inside the function).
// Indexing an array is like other languages -- or,
// rather, other languages are like C
@@ -224,24 +247,41 @@ int main (int argc, char** argv)
(float)i1 / i2; // => 0.5f
i1 / (double)i2; // => 0.5 // Same with double
f1 / f2; // => 0.5, plus or minus epsilon
- // Floating-point numbers and calculations are not exact
-
- // Modulo is there as well
- 11 % 3; // => 2
+
+ // Floating-point numbers are defined by IEEE 754, thus cannot store perfectly
+ // exact values. For instance, the following does not produce expected results
+ // because 0.1 might actually be 0.099999999999 insided the computer, and 0.3
+ // might be stored as 0.300000000001.
+ (0.1 + 0.1 + 0.1) != 0.3; // => 1 (true)
+ // and it is NOT associative due to reasons mentioned above.
+ 1 + (1e123 - 1e123) != (1 + 1e123) - 1e123; // => 1 (true)
+ // this notation is scientific notations for numbers: 1e123 = 1*10^123
+
+ // It is important to note that most all systems have used IEEE 754 to
+ // represent floating points. Even python, used for scientific computing,
+ // eventually calls C which uses IEEE 754. It is mentioned this way not to
+ // indicate that this is a poor implementation, but instead as a warning
+ // that when doing floating point comparisons, a little bit of error (epsilon)
+ // needs to be considered.
+
+ // Modulo is there as well, but be careful if arguments are negative
+ 11 % 3; // => 2 as 11 = 2 + 3*x (x=3)
+ (-11) % 3; // => -2, as one would expect
+ 11 % (-3); // => 2 and not -2, and it's quite counter intuitive
// Comparison operators are probably familiar, but
// there is no Boolean type in C. We use ints instead.
- // (Or _Bool or bool in C99.)
+ // (C99 introduced the _Bool type provided in stdbool.h)
// 0 is false, anything else is true. (The comparison
// operators always yield 0 or 1.)
3 == 2; // => 0 (false)
3 != 2; // => 1 (true)
- 3 > 2; // => 1
- 3 < 2; // => 0
+ 3 > 2; // => 1
+ 3 < 2; // => 0
2 <= 2; // => 1
2 >= 2; // => 1
- // C is not Python - comparisons don't chain.
+ // C is not Python - comparisons do NOT chain.
// Warning: The line below will compile, but it means `(0 < a) < 2`.
// This expression is always true, because (0 < a) could be either 1 or 0.
// In this case it's 1, because (0 < 1).
@@ -349,25 +389,30 @@ int main (int argc, char** argv)
break;
}
/*
- using "goto" in C
+ Using "goto" in C
*/
typedef enum { false, true } bool;
// for C don't have bool as data type before C99 :(
bool disaster = false;
int i, j;
- for(i=0;i<100;++i)
- for(j=0;j<100;++j)
+ for(i=0; i<100; ++i)
+ for(j=0; j<100; ++j)
{
if((i + j) >= 150)
disaster = true;
if(disaster)
- goto error;
+ goto error; // exit both for loops
}
- error :
+ error: // this is a label that you can "jump" to with "goto error;"
printf("Error occurred at i = %d & j = %d.\n", i, j);
/*
- https://ideone.com/GuPhd6
- this will print out "Error occurred at i = 51 & j = 99."
+ https://ideone.com/GuPhd6
+ this will print out "Error occurred at i = 51 & j = 99."
+ */
+ /*
+ it is generally considered bad practice to do so, except if
+ you really know what you are doing. See
+ https://en.wikipedia.org/wiki/Spaghetti_code#Meaning
*/
///////////////////////////////////////
@@ -378,13 +423,16 @@ int main (int argc, char** argv)
// if you want (with some constraints).
int x_hex = 0x01; // You can assign vars with hex literals
+ // binary is not in the standard, but allowed by some
+ // compilers (x_bin = 0b0010010110)
// Casting between types will attempt to preserve their numeric values
printf("%d\n", x_hex); // => Prints 1
printf("%d\n", (short) x_hex); // => Prints 1
printf("%d\n", (char) x_hex); // => Prints 1
- // Types will overflow without warning
+ // If you assign a value greater than a types max val, it will rollover
+ // without warning.
printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 if char is 8 bits long)
// For determining the max value of a `char`, a `signed char` and an `unsigned char`,
@@ -530,7 +578,8 @@ 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.
-Use pointers if you need to edit the original argument values.
+Use pointers if you need to edit the original argument values (arrays are always
+passed in as pointers).
Example: in-place string reversal
*/
@@ -541,9 +590,11 @@ void str_reverse(char *str_in)
char tmp;
size_t ii = 0;
size_t len = strlen(str_in); // `strlen()` is part of the c standard library
- // NOTE: length returned by `strlen` DOESN'T include the
- // terminating NULL byte ('\0')
- for (ii = 0; ii < len / 2; ii++) { // in C99 you can directly declare type of `ii` here
+ // NOTE: length returned by `strlen` DOESN'T
+ // include the terminating NULL byte ('\0')
+ // in C99 and newer versions, you can directly declare loop control variables
+ // in the loop's parentheses. e.g., `for (size_t ii = 0; ...`
+ for (ii = 0; ii < len / 2; ii++) {
tmp = str_in[ii];
str_in[ii] = str_in[len - ii - 1]; // ii-th char from end
str_in[len - ii - 1] = tmp;
@@ -575,6 +626,24 @@ printf("first: %d\nsecond: %d\n", first, second);
// values will be swapped
*/
+// Return multiple values.
+// C does not allow for returning multiple values with the return statement. If
+// you would like to return multiple values, then the caller must pass in the
+// variables where they would like the returned values to go. These variables must
+// be passed in as pointers such that the function can modify them.
+int return_multiple( int *array_of_3, int *ret1, int *ret2, int *ret3)
+{
+ if(array_of_3 == NULL)
+ return 0; //return error code (false)
+
+ //de-reference the pointer so we modify its value
+ *ret1 = array_of_3[0];
+ *ret2 = array_of_3[1];
+ *ret3 = array_of_3[2];
+
+ return 1; //return error code (true)
+}
+
/*
With regards to arrays, they will always be passed to functions
as pointers. Even if you statically allocate an array like `arr[10]`,
@@ -640,7 +709,7 @@ struct rectangle {
void function_1()
{
- struct rectangle my_rec;
+ struct rectangle my_rec = { 1, 2 }; // Fields can be initialized immediately
// Access struct members with .
my_rec.width = 10;
@@ -664,6 +733,16 @@ int area(rect r)
return r.width * r.height;
}
+// Typedefs can also be defined right during struct definition
+typedef struct {
+ int width;
+ int height;
+} rect;
+// Like before, doing this means one can type
+rect r;
+// instead of having to type
+struct rectangle r;
+
// if you have large structs, you can pass them "by pointer" to avoid copying
// the whole struct:
int areaptr(const rect *r)
@@ -703,6 +782,10 @@ typedef void (*my_fnp_type)(char *);
// my_fnp_type f;
+/////////////////////////////
+// Printing characters with printf()
+/////////////////////////////
+
//Special characters:
/*
'\a'; // alert (bell) character
@@ -741,11 +824,12 @@ typedef void (*my_fnp_type)(char *);
// Order of Evaluation
///////////////////////////////////////
+// From top to bottom, top has higher precedence
//---------------------------------------------------//
// Operators | Associativity //
//---------------------------------------------------//
// () [] -> . | left to right //
-// ! ~ ++ -- + = *(type)sizeof | right to left //
+// ! ~ ++ -- + = *(type) sizeof | right to left //
// * / % | left to right //
// + - | left to right //
// << >> | left to right //
@@ -783,8 +867,8 @@ as the C file.
/* 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. */
+/* Like for 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. */
@@ -811,7 +895,7 @@ enum traffic_light_state {GREEN, YELLOW, RED};
Node createLinkedList(int *vals, int len);
/* Beyond the above elements, other definitions should be left to a C source */
-/* file. Excessive includes or definitions should, also not be contained in */
+/* file. Excessive includes or definitions should also not be contained in */
/* a header file but instead put into separate headers or a C file. */
#endif /* End of the if precompiler directive. */
@@ -823,7 +907,7 @@ Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://
It is *the* book about C, written by Dennis Ritchie, the creator of C, and Brian Kernighan. Be careful, though - it's ancient and it contains some
inaccuracies (well, ideas that are not considered good anymore) or now-changed practices.
-Another good resource is [Learn C The Hard Way](http://learncodethehardway.org/c/).
+Another good resource is [Learn C The Hard Way](http://learncodethehardway.org/c/) (not free).
If you have a question, read the [compl.lang.c Frequently Asked Questions](http://c-faq.com).
@@ -833,4 +917,4 @@ Readable code is better than clever code and fast code. For a good, sane coding
Other than that, Google is your friend.
-[1] [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member)
+[1] [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member)
diff --git a/chapel.html.markdown b/chapel.html.markdown
index 7e8fc41a..cfab6f34 100644
--- a/chapel.html.markdown
+++ b/chapel.html.markdown
@@ -1171,7 +1171,7 @@ You will need to `source util/setchplenv.EXT` from within the Chapel directory
(`$CHPL_HOME`) every time your terminal starts so it's suggested that you drop
that command in a script that will get executed on startup (like .bashrc).
-Chapel is easily installed with Brew for OS X
+Chapel is easily installed with Brew for macOS
1. `brew update`
2. `brew install chapel`
diff --git a/clojure.html.markdown b/clojure.html.markdown
index 16771e25..20812a9b 100644
--- a/clojure.html.markdown
+++ b/clojure.html.markdown
@@ -298,8 +298,8 @@ keymap ; => {:a 1, :b 2, :c 3}
(as-> [1 2 3] input
(map inc input);=> You can use last transform's output at the last position
(nth input 2) ;=> and at the second position, in the same expression
- (conj [4 5 6] input [8 9 10])) ;=> or in the middle !
-
+ (conj [4 5 6] input 8 9 10)) ;=> or in the middle !
+ ; Result: [4 5 6 4 8 9 10]
; Modules
diff --git a/cobol.html.markdown b/cobol.html.markdown
index 22fcb6e0..1c858396 100644
--- a/cobol.html.markdown
+++ b/cobol.html.markdown
@@ -14,7 +14,7 @@ organizations.
*COBOL has significant differences between legacy (COBOL-85)
*and modern (COBOL-2002 and COBOL-2014) versions.
*Legacy versions require columns 1-6 to be blank (they are used
- *to store the index number of the punched card..)
+ *to store the index number of the punched card).
*A '*' in column 7 means a comment.
*In legacy COBOL, a comment can only be a full line.
*Modern COBOL doesn't require fixed columns and uses *> for
@@ -44,7 +44,7 @@ organizations.
*Let's declare some variables.
*We do this in the WORKING-STORAGE section within the DATA DIVISION.
- *Each data item (aka variable) with start with a level number,
+ *Each data item (aka variable) starts with a level number,
*then the name of the item, followed by a picture clause
*describing the type of data that the variable will contain.
*Almost every COBOL programmer will abbreviate PICTURE as PIC.
@@ -106,7 +106,7 @@ organizations.
PROCEDURE DIVISION.
FIRST-PARA.
DISPLAY 'THIS IS IN FIRST-PARA'.
- PERFORM THIRD-PARA THRU FOURTH-PARA. *>skip second-para and perfrom 3rd & 4th
+ PERFORM THIRD-PARA THRU FOURTH-PARA. *>skip second-para and perform 3rd & 4th
*> then after performing third and fourth,
*> return here and continue the program until STOP RUN.
diff --git a/coq.html.markdown b/coq.html.markdown
index 4c1ad690..3a924a19 100644
--- a/coq.html.markdown
+++ b/coq.html.markdown
@@ -61,8 +61,8 @@ Locate "+".
(* Calling a function with insufficient number of arguments does not cause
an error, it produces a new function. *)
-Definition make_inc x y := x + y. (* make_inc is int -> int -> int *)
-Definition inc_2 := make_inc 2. (* inc_2 is int -> int *)
+Definition make_inc x y := x + y. (* make_inc is nat -> nat -> nat *)
+Definition inc_2 := make_inc 2. (* inc_2 is nat -> nat *)
Compute inc_2 3. (* Evaluates to 5 *)
@@ -370,7 +370,7 @@ Close Scope string_scope.
power series and results,...)
• Relations : Relations (definitions and basic results)
• Sorting : Sorted list (basic definitions and heapsort correctness)
-• Strings : 8-bits characters and strings
+• Strings : 8-bit characters and strings
• Wellfounded : Well-founded relations (basic results)
*)
@@ -472,7 +472,7 @@ Proof.
intros A B ab. destruct ab as [ a b ]. apply a.
Qed.
-(* We can prove easily prove simple polynomial equalities using the
+(* We can easily prove simple polynomial equalities using the
automated tactic ring. *)
Require Import Ring.
diff --git a/crystal.html.markdown b/crystal.html.markdown
index ae027a8d..d32712ce 100644
--- a/crystal.html.markdown
+++ b/crystal.html.markdown
@@ -4,6 +4,7 @@ filename: learncrystal.cr
contributors:
- ["Vitalii Elenhaupt", "http://veelenga.com"]
- ["Arnaud Fernandés", "https://github.com/TechMagister/"]
+ - ["Valentin Baca", "https://github.com/valbaca/"]
---
@@ -64,24 +65,25 @@ true.class #=> Bool
1.5e10.class #=> Float64
1.5e-7.class #=> Float64
-# Chars
+# Chars use 'a' pair of single quotes
'a'.class #=> Char
-# Octal codepoint
-'\101' #=> 'A' : Char
+# Chars are 32-bit unicode
+'あ' #=> 'あ' : Char
# Unicode codepoint
'\u0041' #=> 'A' : Char
-# Strings
+# Strings use a "pair" of double quotes
"s".class #=> String
# Strings are immutable
s = "hello, " #=> "hello, " : String
s.object_id #=> 134667712 : UInt64
-s += "Crystal" #=> "hello, Crystal" : String
+s += "Crystal"
+s #=> "hello, Crystal" : String
s.object_id #=> 142528472 : UInt64
# Supports interpolation
@@ -89,7 +91,8 @@ s.object_id #=> 142528472 : UInt64
# Multiline string
"This is
- multiline string"
+ multiline string" #=> "This is\n multiline string"
+
# String with double quotes
%(hello "world") #=> "hello \"world\""
@@ -110,7 +113,7 @@ sentence == "question?" #=> false : Bool
# Arrays
[1, 2, 3].class #=> Array(Int32)
-[1, "hello", 'x'].class #=> Array(Int32 | String | Char)
+[1, "hello", 'x'].class #=> Array(Char | Int32 | String)
# Empty arrays should specify a type
[] # Syntax error: for empty arrays use '[] of ElementType'
@@ -154,24 +157,24 @@ array.includes? 3 #=> true
# There is a special array syntax with other types too, as long as
# they define a .new and a #<< method
-set = Set{1, 2, 3} #=> [1, 2, 3]
+set = Set{1, 2, 3} #=> Set{1, 2, 3}
set.class #=> Set(Int32)
# The above is equivalent to
-set = Set(typeof(1, 2, 3)).new
-set << 1
-set << 2
-set << 3
+set = Set(typeof(1, 2, 3)).new #=> Set{} : Set(Int32)
+set << 1 #=> Set{1} : Set(Int32)
+set << 2 #=> Set{1, 2} : Set(Int32)
+set << 3 #=> Set{1, 2, 3} : Set(Int32)
# Hashes
{1 => 2, 3 => 4}.class #=> Hash(Int32, Int32)
-{1 => 2, 'a' => 3}.class #=> Hash(Int32 | Char, Int32)
+{1 => 2, 'a' => 3}.class #=> Hash(Char| Int32, Int32)
-# Empty hashes should specify a type
-{} # Syntax error
-{} of Int32 => Int32 # {}
-Hash(Int32, Int32).new # {}
+# Empty hashes must specify a type
+{} # Syntax Error: for empty hashes use '{} of KeyType => ValueType'
+{} of Int32 => Int32 # {} : Hash(Int32, Int32)
+Hash(Int32, Int32).new # {} : Hash(Int32, Int32)
# Hashes can be quickly looked up by key
hash = {"color" => "green", "number" => 5}
@@ -179,6 +182,9 @@ hash["color"] #=> "green"
hash["no_such_key"] #=> Missing hash key: "no_such_key" (KeyError)
hash["no_such_key"]? #=> nil
+# The type of the returned value is based on all key types
+hash["number"] #=> 5 : (Int32 | String)
+
# Check existence of keys hash
hash.has_key? "color" #=> true
@@ -220,7 +226,7 @@ Range.new(1, 10).class #=> Range(Int32, Int32)
# Access tuple's value by its index
tuple = {:key1, :key2}
tuple[1] #=> :key2
-tuple[2] #=> syntax error : Index out of bound
+tuple[2] #=> Error: index out of bounds for Tuple(Symbol, Symbol) (2 not in -2..1)
# Can be expanded into multiple variables
a, b, c = {:a, 'b', "c"}
@@ -246,7 +252,7 @@ elsif false
"else-if, optional"
else
"else, also optional"
-end
+end
puts "if as a suffix" if true
@@ -314,7 +320,7 @@ if a < 3
else
a = true
end
-typeof a #=> (Bool | String)
+typeof(a) #=> (Bool | String)
if a && b
# here both a and b are guaranteed not to be Nil
@@ -388,15 +394,19 @@ dinner #=> "quesadilla"
5.even? # false
5.odd? # true
-# And if a method ends with an exclamation mark, it does something destructive
-# like mutate the receiver. Some methods have a ! version to make a change, and
+# Also by convention, if a method ends with an exclamation mark, it does
+# something destructive like mutate the receiver.
+# Some 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.gsub "Dunder", "Donald" #=> "Donald Mifflin"
-company_name #=> "Dunder Mifflin"
-company_name.gsub! "Dunder", "Donald"
-company_name #=> "Donald Mifflin"
+fruits = ["grapes", "apples", "bananas"]
+fruits.sort #=> ["apples", "bananas", "grapes"]
+fruits #=> ["grapes", "apples", "bananas"]
+fruits.sort! #=> ["apples", "bananas", "grapes"]
+fruits #=> ["apples", "bananas", "grapes"]
+# However, some mutating methods do not end in !
+fruits.shift #=> "apples"
+fruits #=> ["bananas", "grapes"]
# Define a class with the class keyword
class Human
@@ -404,7 +414,7 @@ class Human
# A class variable. It is shared by all instances of this class.
@@species = "H. sapiens"
- # type of name is String
+ # An instance variable. Type of name is String
@name : String
# Basic initializer
@@ -469,9 +479,9 @@ class TestClass
end
# Variables that start with a capital letter are constants
Var = "I'm a constant"
-Var = "can't be updated" # Already initialized constant Var
+Var = "can't be updated" # Error: already initialized constant Var
-# Class is also an object in crystal. So class can have instance variables.
+# Class is also an object in Crystal. So a class can have instance variables.
# Class variable is shared among the class and all of its descendants.
# base class
diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown
index 35becf94..50a69107 100644
--- a/cs-cz/markdown.html.markdown
+++ b/cs-cz/markdown.html.markdown
@@ -5,44 +5,87 @@ contributors:
- ["Dan Turkel", "http://danturkel.com/"]
translators:
- ["Michal Martinek", "https://github.com/MichalMartinek"]
+ - ["Tomáš Hartman", "https://github.com/tomas-hartman"]
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 byl vytvořen Johnem Gruberem v roce 2004 jako značkovací jazyk, který
+lze snadno číst a psát a který je možné jednoduše převést do HTML (a dnes i do
+mnoha dalších formátů).
+
+Implementace markdownu se v různých parserech (syntaktických analyzátorech,
+které markdown dále zpracovávají) mírně odlišuje. V této příručce se snažíme
+upozorňovat, kdy se jedná o obecnou vlastnost markdownu a kdy se jedná o
+specifickou vlastnost daného parseru.
+
+## Obsah
+
+- [Obsah](#obsah)
+- [HTML Elementy](#html-elementy)
+- [Nadpisy](#nadpisy)
+- [Jednoduché stylování textu](#jednoduché-stylování-textu)
+- [Odstavce](#odstavce)
+ - [Blokové citace](#blokové-citace)
+- [Seznamy](#seznamy)
+- [Bloky kódu](#bloky-kódu)
+- [Vodorovná čára (`<hr />`)](#vodorovná-čára-hr-)
+- [Odkazy](#odkazy)
+ - [Obsahy](#obsahy)
+- [Obrázky](#obrázky)
+- [Ostatní](#ostatní)
+ - [Automatické odkazy](#automatické-odkazy)
+ - [Automatické odkazy z emailů](#automatické-odkazy-z-emailů)
+ - [Escapování znaků](#escapování-znaků)
+ - [Klávesové zkratky](#klávesové-zkratky)
+ - [Tabulky](#tabulky)
+- [Markdownlint](#markdownlint)
+- [Reference](#reference)
+
+## HTML Elementy
+
+Markdown je nadstavba HTML. To znamená, že každý HTML kód je zároveň validním
+kódem v Markdownu.
+
+```md
+<!-- To znamená, že v Markdownu můžeme používat HTML elementy jako například
+komentáře, které nebudou ovlivněny parserem Markdownu. Na druhou stranu to také
+znamená, že pokud ve svém Markdown kódu vytvoříte HTML element, už v rámci
+tohoto elementu nelze použít Markdown.
+
+Markdown využívá i tato stránka, a tak by tento text, kdyby nebyl obalen v bloku
+kódu (viz níže), jako validní HTML komentář vůbec nebyl vidět. -->
+```
+
+## Nadpisy
+
+HTML elementy `<h1>` až `<h6>` vytvoříte jednoduše tak, že nadpisu předsadíte
+takový počet křížků (#), jaký odpovídá úrovni nadpisu.
```md
-<!-- 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 ještě dva další způsoby, jak vytvořit h1 a h2:
-<!-- Markdown obsahuje taky dvě další cesty, jak udělat h1 a h2 -->
+```md
Toto je h1
==========
Toto je h2
----------
+```
+
+## Jednoduché stylování textu
-<!-- Jednoduché stylování textu -->
-<!-- Pomocí markdownu můžete text jednoduše označit jako kurzívu či tučný -->
+Pomocí markdownu můžete text jednoduše označit jako kurzívu či tučný text.
+```md
*Tento text je kurzívou;*
_Stejně jako tento._
@@ -50,47 +93,62 @@ _Stejně jako tento._
__Stejně jako tento.__
***Tento text je obojí***
-**_Jako tento!_**
-*__A tento!__*
+**_Tak jako tento!_**
+*__Nebo tento!__*
+```
-<!-- Ve verzi Markdownu od GitHubu, máme k dispozici taky prošktrnutí: -->
+Ve verzi Markdownu od GitHubu máme k dispozici také přeškrtnutí:
-~~Tento text je prošktrnutý.~~
+```md
+~~Tento text je přeškrtnutý.~~
+```
-<!-- Odstavce jsou jedna nebo více řádek textu, oddělených jednou nebo více prázdnými řádky. -->
+## Odstavce
-Toto je odstavec. Píši odstavec, není to zábava?
+Odstavce tvoří jeden nebo více řádků textu, oddělených jedním nebo více
+prázdnými řádky.
-Teď jsem v odstavci 2.
-Jsem pořád v odstavci 2!
+```md
+Toto je odstavec. Zde jsem napsal odstavec a je to bezva!
+Teď jsem v odstavci 2.
+A tady jsem pořád v odstavci 2!
-Toto je odstavec 3.
+Ale tady už 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. -->
+Pokud byste chtěli vložit HTML element `<br />`, můžete na konec odstavce napsat
+dvě nebo více mezer a potom začít nový odstavec.
+```md
Tento odstavec končí dvěma mezerami.
-Nad tímto odstavcem je <br />!
+Nad tímto odstavcem je <br />!
+```
+
+### Blokové citace
-<!-- Blokové citace se dělají jednoduše pomocí znaku >. -->
+Blokové citace se dělají jednoduše uvozením řádku znakem >.
+```md
> 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 >.
+> manuálně rozdělit řádky, a před každý vložit >, nebo nechat vaše řádky
+> jakkoli dlouhé, ať se zarovnají samy.
+> Je to jedno, pokud vždy začínají symbolem `>`.
+
+> Použít můžu i více než jednu úroveň
+>> odsazení.
+> Co vy na to?
+```
-> Můžu použít více než jednu
->> odsazení?
-> Jak je to úhledné, že?
+## Seznamy
-<!-- Seznamy -->
-<!-- Nečíslovaný seznam můžete jednoduše udělat pomocí hvězdiček, plusů, nebo
- pomlček -->
+Nečíslovaný seznam můžete jednoduše udělat pomocí hvězdiček, plusů nebo pomlček:
+```md
* Položka
* Položka
-* Jinná položka
+* Jiná položka
nebo
@@ -103,158 +161,246 @@ nebo
- Položka
- Položka
- Další položka
+```
-<!-- Číslovaný seznam se dělají pomocí čísla a . -->
+Číslované seznamy se dělají pomocí číslice a `.`.
+```md
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 -->
+<!-- Čísla ani nemusíte psát popořadě. Markdown je umí zobrazit správně, jenom
+je třeba vždy překontrolovat, že číslování funguje správně. -->
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 -->
+<!-- (Toto zobrazí to samé, jako příklad nad tím.) -->
+```
+
+Můžete také tvořit podseznamy:
+```md
1. Položka jedna
2. Položka dvě
3. Položka tři
- * Podpoložka
- * Podpoložka
+ - Podpoložka
+ - Podpoložka
4. Položka čtyři
+```
-<!-- Existují i zašktávací seznamy. Toto vytvoří HTML checkboxy. -->
+Vytvořit lze i zaškrtávací seznamy. Takto lze vytvořit seznam s HTML checkboxy.
+(Boxy níže bez 'x' jsou nezaškrtnuté checkboxy.)
-Boxy níže bez 'x' jsou nezašktrnuté checkboxy.
-- [ ] První úkol
-- [ ] Druhý úkol
-Tento box bude zašktrnutý
+```md
+- [ ] První úkol, který je třeba dokončit
+- [ ] Druhý úkol na dodělání
+Tento box bude zaškrtnutý
- [x] Tento úkol byl dokončen
+```
+
+## Bloky kódu
-<!-- Bloky ködu -->
-<!-- Můžete označit kód bloku (který používá <code> element) odsazením pomocí 4
- mezer, nebo tabu -->
+Bloky kódu můžete označit tak, že řádek odsadíte čtyřmi mezerami nebo pomocí
+tabu. Pro interpretaci kódu parser používá `<code>` element.
+```md
Toto je kód
Stejně jako toto
+```
-<!-- Můžete dokonce přidat další 4 mezery nebo tab pro další odsazení -->
+Pro ještě hlubší odsazení můžete přidat další 4 mezery nebo další tab:
+```md
moje_pole.each do |i|
puts i
end
+```
-<!-- Kód na řádku může být označen pomocí zpětných apostrofů ` -->
+Jednořádkový kód můžete zabalit do dvou zpětných apostrofů (`) tak, jako
+kdybyste text normálně stylovali:
-Jan nevědel, jak se dělá `go_to()` funkce!
+```md
+Honza neměl tušení, co dělá funkce `go_to()`!
+```
-<!-- V Markdownu od GitHubu , můžete použít speciální syntaxi pro kód -->
+V Markdownu od GitHubu, můžete použít speciální syntaxi pro kód:
-\`\`\`ruby <!-- vyjma zpětných lomítek, jenom ```ruby ! -->
+<pre><code class="highlight">&#x60;&#x60;&#x60;ruby
def neco
puts "Ahoj světe!"
end
-\`\`\` <!-- zde taky, žádné zpětná lomítka, pouze ``` -->
+&#x60;&#x60;&#x60;</code></pre>
+
+Text výše nepotřebuje čtyřmezerové odsazení a parser navíc použije zvýraznění
+syntaxe pro zvolený jazyk.
-<!-- Text výše nepotřebuje odsazení a navíc GitHub použije zvýraznění označeného
- jazyka. -->
+## Vodorovná čára (`<hr />`)
-<!-- 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. -->
+Vodorovnou oddělovací čáru lze snadno přidat pomocí 3 nebo více hvězdiček (nebo
+pomlček), a to buď s mezerami mezi jednotlivými znaky, nebo bez nich.
+```md
***
---
- - -
****************
+```
+
+## Odkazy
-<!-- 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. -->
+```md
+<!-- Jedna z nejlepších vlastností Markdownu je, jak snadno lze s jeho pomocí
+vytvářet odkazy. Text odkazu, který chcete zobrazit vložte do [] a hned za něj
+v kulatých závorkách () připojte url adresu. -->
[Klikni na mě!](http://test.com/)
-<!-- Můžete také přidat jméno linku pomocí uvozovek -->
+
+<!-- V uvozovkách za url můžete přidat název odkazu -->
[Klikni na mě!](http://test.com/ "Odkaz na Test.com")
-<!-- Relativní cesty fungují taky -->
+
+<!-- Relativní cesty fungují také -->
[Jdi na hudbu](/hudba/).
-<!-- Markdown taktéž podporuje reference odkazů. -->
+
+<!-- Markdown taktéž podporuje referenční odkazy -->
[Klikni na tento odkaz][link1] pro více informací!
-[Taky zkontrolujte tento odkaz][neco], když chcete.
+[Taky zkontrolujte tento odkaz][neco], jestli tedy 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í.-->
+<!-- Titulek v tomto případě může být v jednoduchých uvozovkách, závorkách, nebo
+zcela vynechaný. Reference může být kdekoliv ve vašem dokumentu a identifikátory
+mohou být jakékoli, pokud jsou unikátní. -->
+
-<!-- Také existuje "implicitní pojmenování", které použije text jako id -->
+<!-- V markdownu existuje rovněž "implicitní pojmenování", které použije text
+odkazu jako své id -->
[Toto][] je odkaz..
[toto]: http://totojelink.cz/
-<!-- Ale toto není zrovna běžné užívané. -->
+<!-- Ale tento způsob se obvykle nepoužívá. -->
+```
-<!-- Obrázky -->
-<!-- Obrázky se dělají stejně jako odkazy, ale s vykřičníkem na začátku -->
+### Obsahy
+
+Kombinace seznamů, odkazů a nadpisů využívají také některé parsery pro
+generování obsahu Markdown souborů. Jako identifikátory slouží jména nadpisů
+psané malými písmeny, které jsou uvozené křížkem (`#`). Víceslovné nadpisy
+bývají propojeny pomlčkou (`-`), která někdy nahrazuje i speciální znaky. Jiné
+speciální znaky mohou být vynechány.
+
+```md
+- [Nadpis](#nadpis)
+- [Víceslovný text](#víceslovný-text)
+- [Odstavce](#odstavce)
+ - [Podkapitola <h3 />](#podkapitola-h3-)
+```
+
+V případě obsahů se v každém případě jedná o nadstavbu, která nemusí všude
+fungovat stejně.
+
+## Obrázky
+
+```md
+<!-- Obrázky se vytváří 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-->
+<!-- Reference fungují tak, jak bychom čekali -->
![Toto je atribut alt][mujobrazek]
[mujobrazek]: relativni/cesta/obrazek.jpg "a toto by byl titulek"
+```
+
+## Ostatní
+
+### Automatické odkazy
+
+```md
+<http://stranka.cz/>
-<!-- Ostatní -->
-<!-- Automatické odkazy -->
+je stejné jako
-<http://stranka.cz/> je stejná jako
[http://stranka.cz/](http://stranka.cz/)
+```
-<!-- Automatické odkazy pro emaily-->
+### Automatické odkazy z emailů
+```md
<jmeno@prijmeni.cz>
+```
-<!-- Escapování znaků -->
+### 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\*.
+```md
+Chci napsat *tento text obklopený hvězdičkami*, ale protože nechci, aby to bylo
+kurzívou, tak hvězdičky vyescapuji `\`: \*tento text bude 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 -->
+### Klávesové zkratky
+
+```md
+<!-- V Markdownu od GitHubu můžete použít tag <kbd> k označení kláves 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: -->
+### Tabulky
+Tabulky lze využít pouze v Markdownu od GitHubu a jejich syntax je trošku
+zvláštní. Kdybyste je chtěli použít, vytváří se takto:
+
+```md
| Sloupec1 | Sloupec2 | Sloupec3 |
| :----------- | :------: | ------------: |
| Vlevo zarovn.| Na střed | Vpravo zarovn.|
| blah | blah | blah |
-<!-- nebo, to jde i taky: -->
+<!-- nebo je jde taky zapsat takto: -->
Sloupec 1 | Sloupec2 | Sloupec3
:-- | :-: | --:
-Ohh toto je tak ošklivé | radši to | nedělejte
+Že se to nedá číst? | No tak to takhle | radši nedělejte.
+```
-<!-- Konec -->
+## Markdownlint
-```
+Pro usnadnění práce s Markdownem a s cílem sjednotit styl psaní jeho kódu vznikl
+nástroj `Markdownlint`. Tento nástroj je dostupný i jako plugin pro některé
+editory kódu (IDE) a lze jej použít jako nástroj pro vytváření a ověřování
+validity a čitelnosti Markdownu kódu.
+
+---
+
+## Reference
+
+Pro více informací doporučujeme 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).
+
+---
+
+> _Pozn. překladatele:_ Tento text vznikl jako překlad původního článku, který
+> pochází z roku 2013 a kombinace původního českého překladu z roku 2015.
+> Některé informace v tomto článku, zejména ty, týkající se specifických
+> vlastností parserů markdownu tak již dnes mohou být zastaralé.
+
+Aktuální informace o specifických vlastnostech různých implementací Markdownu
+můžete nalézt zde (v angličtině):
-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).
+- [Markdown pro GitHub](https://docs.github.com/en/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)
+- [Markdown pro GitLab](https://docs.gitlab.com/ee/user/markdown.html)
diff --git a/csharp.html.markdown b/csharp.html.markdown
index b965c2d4..c85acb1b 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -12,9 +12,9 @@ contributors:
filename: LearnCSharp.cs
---
-C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework.
+C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the cross-platform .NET framework.
-[Read more here.](https://docs.microsoft.com/dotnet/csharp/getting-started/introduction-to-the-csharp-language-and-the-net-framework)
+[Read more here.](https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/)
```c#
// Single-line comments start with //
@@ -29,7 +29,7 @@ Multi-line comments look like this
/// </summary>
/// <param name="firstParam">This is some parameter documentation for firstParam</param>
/// <returns>Information on the returned value of a function</returns>
-public void MethodOrClassOrOtherWithParsableHelp(string firstParam) {}
+public void MethodOrClassOrOtherWithParsableHelp(string firstParam) { }
// Specify the namespaces this source code will be using
// The namespaces below are all part of the standard .NET Framework Class Library
@@ -48,6 +48,10 @@ using System.Data.Entity;
// Namespaces define scope to organize code into "packages" or "modules"
// Using this code from another source file: using Learning.CSharp;
+
+// You can also do this in C# 10, it is called file-scoped namespaces.
+// namespace Learning.CSharp;
+
namespace Learning.CSharp
{
// Each .cs file should at least contain a class with the same name as the file.
@@ -341,8 +345,17 @@ on a new line! ""Wow!"", the masses cried";
// Convert Integer To String
// Convert class has a number of methods to facilitate conversions
+
+ // String to int
+
+ // Better
+ bool result = int.TryParse(string, out var integer)
+ int.Parse(string);
+
+ // Not recommended
Convert.ToString(123);
- // or
+
+ // Int to string
tryInt.ToString();
// Casting
@@ -375,6 +388,9 @@ on a new line! ""Wow!"", the masses cried";
Console.Read();
} // End main method
+ // Available in C# 9 and later, this is basically a syntactic sugar for a class. Records are immutable*.
+ public record ARecord(string Csharp);
+
// CONSOLE ENTRY - A console application must have a main method as an entry point
public static void Main(string[] args)
{
@@ -744,7 +760,7 @@ on a new line! ""Wow!"", the masses cried";
Gitane // 43
}
// We defined this type inside a Bicycle class, so it is a nested type
- // Code outside of this class should reference this type as Bicycle.Brand
+ // Code outside of this class should reference this type as Bicycle.BikeBrand
public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type
@@ -1299,16 +1315,27 @@ namespace Csharp7
```
## Topics Not Covered
+✨ New, 👍 Old, 🎈 LTS, 🔥 Cross-platform, 🎁 Windows-only
* Attributes
- * async/await
+
+ * Asynchronous Programming
+
* Web Development
- * ASP.NET MVC & WebApi (new)
- * ASP.NET Web Forms (old)
- * WebMatrix (tool)
+ * ASP.NET Core ✨
+
* Desktop Development
- * Windows Presentation Foundation (WPF) (new)
- * Winforms (old)
+ * Windows Presentation Foundation 👍 🎈 🎁
+ * Universal Windows Platform ✨ 🎁
+ * Uno Platform 🔥 ✨
+ * WinForms 👍 🎈 🎁
+ * Avalonia 🔥 ✨
+ * WinUI ✨ 🎁
+
+* Cross-platform Development
+ * Xamarin.Forms 👍
+ * MAUI ✨
+
## Further Reading
@@ -1321,4 +1348,4 @@ namespace Csharp7
* [LINQ Pocket Reference](http://shop.oreilly.com/product/9780596519254.do)
* [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208)
* [freeCodeCamp - C# Tutorial for Beginners](https://www.youtube.com/watch?v=GhQdlIFylQ8)
- \ No newline at end of file
+
diff --git a/dart.html.markdown b/dart.html.markdown
index b215474a..69e1623d 100644
--- a/dart.html.markdown
+++ b/dart.html.markdown
@@ -77,13 +77,11 @@ example1() {
nested1();
}
-/// Anonymous functions don't include a name but can take number of arguments
+/// Anonymous functions don't include a name
example2() {
- //// Explicit return type.
- nested1(Function<void> fn) {
+ nested1(fn) {
fn();
}
-
nested1(() => print("Example2 nested 1"));
}
@@ -717,6 +715,6 @@ main() {
## Further Reading
Dart has a comprehensive web-site. It covers API reference, tutorials, articles and more, including a
-useful Try Dart online.
-[https://www.dartlang.org](https://www.dartlang.org)
-[https://try.dartlang.org](https://try.dartlang.org)
+useful DartPad (a cloud-based Dart coding playground).
+[https://dart.dev/](https://dart.dev)
+[https://dartpad.dev/](https://dartpad.dev)
diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown
index 3a76708a..12da1df8 100644
--- a/de-de/bash-de.html.markdown
+++ b/de-de/bash-de.html.markdown
@@ -10,7 +10,7 @@ translators:
filename: LearnBash-de.sh
---
-Bash ist der Name der Unix-Shell, die als Shell des GNU-Betriebssystems und auch als Standard-Shell von Linux und Mac OS X ausgeliefert wurde.
+Bash ist der Name der Unix-Shell, die als Shell des GNU-Betriebssystems und auch als Standard-Shell von Linux und macOS ausgeliefert wurde.
Beinahe alle der folgenden Beispiele können als Teile eines Shell-Skripts oder direkt in der Shell ausgeführt werden.
[Weitere Informationen \(Englisch\)](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/de-de/elixir-de.html.markdown b/de-de/elixir-de.html.markdown
index 29d5132d..254cca51 100644
--- a/de-de/elixir-de.html.markdown
+++ b/de-de/elixir-de.html.markdown
@@ -35,6 +35,10 @@ viele Features mit.
0x1F # Integer
3.0 # Float
+# Für bessere Lesbarkeit des Codes können Unterstriche "_" als Trennzeichen verwendet werden
+1_000_000 == 1000000 # Integer
+1_000.567 == 1000.567 # Float
+
# Atome, das sind Literale, sind Konstanten mit Namen. Sie starten mit einem
# ':'.
:hello # Atom
diff --git a/de-de/nix-de.html.markdown b/de-de/nix-de.html.markdown
index ea02e81d..ffe8dffc 100644
--- a/de-de/nix-de.html.markdown
+++ b/de-de/nix-de.html.markdown
@@ -356,3 +356,6 @@ with builtins; [
* [Susan Potter - Nix Cookbook - Nix By Example]
(https://ops.functionalalgebra.com/nix-by-example/)
+
+* [Rommel Martinez - A Gentle Introduction to the Nix Family]
+ (https://web.archive.org/web/20210121042658/https://ebzzry.io/en/nix/#nix)
diff --git a/de-de/ruby-de.html.markdown b/de-de/ruby-de.html.markdown
index 8025a8c0..23571377 100644
--- a/de-de/ruby-de.html.markdown
+++ b/de-de/ruby-de.html.markdown
@@ -685,4 +685,4 @@ _(z.T. auf Englisch)_
- [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/) - Eine ältere [freie Ausgabe](http://ruby-doc.com/docs/ProgrammingRuby/) ist online verfügbar.
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Ein von der Community erstellter Ruby coding style guide.
-- [Try Ruby](http://tryruby.org) - Lerne die Grundlagen der Ruby Programmiersprache, interaktiv im Browser.
+- [Try Ruby](https://try.ruby-lang.org/) - Lerne die Grundlagen der Ruby Programmiersprache, interaktiv im Browser.
diff --git a/de-de/rust-de.html.markdown b/de-de/rust-de.html.markdown
index faa4ec2b..02bb460a 100644
--- a/de-de/rust-de.html.markdown
+++ b/de-de/rust-de.html.markdown
@@ -255,7 +255,7 @@ fn main() {
// `for` Schleife/Iterationen
let array = [1, 2, 3];
- for i in array.iter() {
+ for i in array {
println!("{}", i);
}
diff --git a/de-de/swift-de.html.markdown b/de-de/swift-de.html.markdown
index 08f72a35..5828b5d3 100644
--- a/de-de/swift-de.html.markdown
+++ b/de-de/swift-de.html.markdown
@@ -11,7 +11,7 @@ filename: learnswift-de.swift
lang: de-de
---
-Swift ist eine Programmiersprache von Apple für die Entwicklung von iOS und OS X Applikationen. Swift wurde 2014 zu Apples WWDC Entwicklerkonferenz vorgestellt und wurde mit dem Ziel entwickelt, fehlerträchtigen Code zu vermeiden sowie mit Objective-C zu koexistieren. Es wird mit dem LLVM Compiler gebaut und ist ab Xcode 6+ verfügbar.
+Swift ist eine Programmiersprache von Apple für die Entwicklung von iOS und macOS Applikationen. Swift wurde 2014 zu Apples WWDC Entwicklerkonferenz vorgestellt und wurde mit dem Ziel entwickelt, fehlerträchtigen Code zu vermeiden sowie mit Objective-C zu koexistieren. Es wird mit dem LLVM Compiler gebaut und ist ab Xcode 6+ verfügbar.
Das offizielle [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) Buch von Apple ist kostenlos via iBooks verfügbar.
diff --git a/docker.html.markdown b/docker.html.markdown
index 24f85247..1dad267a 100644
--- a/docker.html.markdown
+++ b/docker.html.markdown
@@ -3,9 +3,10 @@ language: docker
filename: docker.bat
contributors:
- ["Ruslan López", "http://javapro.org/"]
+ - ["Michael Chen", "https://github.com/ML-Chen"]
---
-```
+```bat
:: download, install and run hello-world image
docker run hello-world
@@ -37,12 +38,12 @@ docker run hello-world
:: For more examples and ideas, visit:
:: https://docs.docker.com/get-started/
-:: now lets see currently running images
+:: now let's see currently running images
docker ps
:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
:: NAMES
-:: lets see the images we have ran previously
+:: let's see the images we have ran previously
docker ps -a
:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
@@ -54,7 +55,7 @@ docker ps -a
:: let's remove our previously generated image
docker rm happy_poincare
-:: lets test if it was really deleted
+:: let's test if it was really deleted
docker ps -a
:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
:: NAMES
@@ -89,7 +90,7 @@ docker ps -a
:: test_container
:: as you can see the name is now what we have specified
-:: retireve logs from a named container
+:: retrieve logs from a named container
docker logs test_container
:: Hello from Docker!
:: This message shows that your installation appears to be working correctly.
@@ -143,4 +144,4 @@ docker ps -a
:: nifty_goldwasser
docker rm nifty_goldwasser
-``` \ No newline at end of file
+```
diff --git a/easylang.html.markdown b/easylang.html.markdown
new file mode 100644
index 00000000..ba33dbf2
--- /dev/null
+++ b/easylang.html.markdown
@@ -0,0 +1,221 @@
+---
+language: Easylang
+contributors:
+ - ["chkas", "https://github.com/chkas"]
+filename: easylang.el
+---
+
+**Easylang** is a simple programming language with built-in graphical functions and an easy-to-use and offline usable browser IDE. Its simple syntax and semantics make it well suited as a teaching and learning programming language. You can also use it to write graphical applications that you can embed in a web page.
+
+*Easylang* is statically typed and has as data types only strings and numbers (floating point), resizeable arrays of strings and numbers and arrays of arrays.
+
+[The browser IDE](https://easylang.online/ide/) includes various tutorials, including one for beginners.
+
+```
+print "Hello world"
+#
+# number variable (64 bit floating point)
+#
+h = 3.14
+print h
+#
+# string variable
+#
+str$ = "monkey"
+# strings can grow
+str$ &= " circus"
+print str$
+#
+# blocks end with 'end' or a dot, a newline has no
+# other meaning than a space
+#
+for i = 1 to 5
+ sum += i * i
+.
+print sum
+#
+# functions have value and reference
+# parameters, no return values
+#
+func gcd a b . res .
+ # a and b are value parameters
+ # res is a reference parameter
+ while b <> 0
+ # h is a local variable, because
+ # it is first used in the function
+ h = b
+ b = a mod b
+ a = h
+ .
+ res = a
+.
+call gcd 120 35 r
+print r
+#
+# strings can be concatenated and numbers are
+# automatically converted to strings
+#
+print "1 + 2 = " & 1 + 2
+#
+# array of numbers
+#
+a[] = [ 2.1 3.14 3 ]
+#
+# arrays can grow
+a[] &= 4
+print a[]
+#
+# arrays, strings and numbers are copied by value
+#
+b[] = a[]
+a[] &= 4
+print a[] ; print b[]
+#
+# array swapping ist fast
+#
+swap a[] b[]
+print a[] ; print b[]
+#
+# array of strings
+#
+fruits$[] = [ "apple" "banana" "orange" ]
+#
+# for-in iterates over the elements of an array
+#
+for fruit$ in fruits$[]
+ print fruit$
+.
+#
+# strings are also used for single characters
+#
+letters$[] = str_chars "ping"
+print letters$[]
+letters$[1] = "o"
+print str_join letters$[]
+#
+# 2-dimensional arrays are arrays of arrays
+# this defines 3 arrays with length 4
+#
+len a[][] 3
+for i range len a[][]
+ len a[i][] 4
+.
+a[1][2] = 99
+print a[][]
+#
+# builtin functions
+if sin 90 = 1
+ print "angles are in degree"
+.
+print pow 2 8
+# seconds since 1970
+print floor sys_time
+# random numbers
+print randomf
+print random 6 + 1
+#
+# hour and minutes
+print substr time_str sys_time 11 5
+#
+print str_ord "A"
+print str_chr 65
+#
+# set number format
+numfmt 0 4
+print sqrt 2
+print pi
+print logn 10
+#
+a$[] = str_split "10,15,22" ","
+print a$[]
+print 2 * number a$[0]
+print len a$[]
+print len "Hello"
+#
+# With 'break n' you can leave nested loops and a function
+#
+names$[] = [ ]
+func name2id name$ . id .
+ for id range len names$[]
+ if names$[id] = name$
+ # leave loop and function
+ break 2
+ .
+ .
+ names$[] &= name$
+.
+call name2id "alice" id ; print id
+call name2id "bob" id ; print id
+call name2id "alice" id ; print i
+#
+# with 'repeat' you can make loops, which you can leave
+# in the loop body using 'until'
+#
+sum = 0
+repeat
+ s$ = input
+ until s$ = ""
+ sum += number s$
+.
+print "sum: " & sum
+#
+# "input" reads a string from the "input_data" section,
+# if it exists, otherwise via a prompt.
+#
+input_data
+10
+-2
+6
+```
+
+Built-in graphic primitives and event-driven programming
+
+```
+# simple drawing with the mouse
+#
+set_linewidth 4
+set_color 900
+# the colors are coded from 0 to 999, with
+# the left digit specifying the red component,
+# the middle digit the green component and
+# the right digit the blue component.
+#
+on mouse_down
+ down = 1
+ move_pen mouse_x mouse_y
+ # moves the drawing pen to the actual mouse position
+ draw_circle 2
+.
+on mouse_up
+ down = 0
+.
+on mouse_move
+ if down = 1
+ draw_line mouse_x mouse_y
+ .
+.
+```
+
+```
+# an animated pendulum
+#
+on animate
+ # The animate event occurs after each screen refresh.
+ #
+ clear_screen
+ move_pen 50 50
+ draw_circle 1
+ x = 50 + 40 * sin ang
+ y = 50 - 40 * cos ang
+ draw_line x y
+ draw_circle 5
+ vel += sin ang / 5
+ ang += vel
+.
+ang = 10
+```
+
+* [More about Easylang](https://easylang.online/)
+
+* [Source code](https://github.com/chkas/easylang)
+
diff --git a/el-gr/bash-gr.html.markdown b/el-gr/bash-gr.html.markdown
index 2989969d..239beaa4 100644
--- a/el-gr/bash-gr.html.markdown
+++ b/el-gr/bash-gr.html.markdown
@@ -8,7 +8,7 @@ lang: el-gr
---
Η λέξη «bash» είναι ένα από τα ονόματα του unix shell (τερματικός), το οποίο
-διανέμεται επίσης ως προεπιλεγμένος τερματικός για το λειτουργικό σύστημα GNU, τα Linux και τα Mac OS X.
+διανέμεται επίσης ως προεπιλεγμένος τερματικός για το λειτουργικό σύστημα GNU, τα Linux και τα macOS.
Σχεδόν όλα τα παραδείγματα που ακολουθούν μπορούν να αποτελέσουν μέρος ενός
προγράμματος τερματικού (shell script) ή να εκτελεσθούν απευθείας από τον
τερματικό.
diff --git a/el-gr/ocaml-gr.html.markdown b/el-gr/ocaml-gr.html.markdown
new file mode 100644
index 00000000..9a15b2d3
--- /dev/null
+++ b/el-gr/ocaml-gr.html.markdown
@@ -0,0 +1,381 @@
+---
+language: OCaml
+filename: learnocaml-gr.ml
+contributors:
+ - ["Daniil Baturin", "http://baturin.org/"]
+translators:
+ - ["Chariton Charitonidis", "https://github.com/haritonch"]
+lang: el-gr
+---
+
+Η OCaml είναι μία strictly evaluated συναρτησιακή γλώσσα με κάποια στοιχεία
+προστακτικού προγραμματισμού.
+
+Μαζί με την StandardML και τις διαλέκτους της, ανήκει στην οικογένεια ML γλωσσών.
+Η F# είναι επίσης αρκετά επιρρεασμένη από την OCaml.
+
+Ακριβώς όπως η StandardML, η OCaml διαθέτει έναν interpreter, που μπορεί να
+χρησιμοποιηθεί διαδραστικά, αλλά και έναν compiler.
+Το εκτελέσιμο αρχείο του interpreter κανονικά έχει το όνομα "ocaml" και ο compiler
+έχει το όνομα "ocamlopt".
+Υπάρχει και ένας bytecode compiler "ocamlc", αλλά δεν υπάρχουν πολλοί λόγοι να το
+χρησιμοποιήσει κάποιος.
+
+Είναι ισχυρά και στατικά τυποποιημένη. Παρ'όλα αυτά , δεν χρειάζεται ο
+προγραμματιστής να δηλώνει τους τύπους, καθώς συμπερασμός τύπων γίνεται με τον
+αλγόριθμο του συστήματος τύπων Hindley-Milner. Αυτό κάνει τις δηλώσεις τύπων μη
+αναγκαίες στις περισσότερες περιπτώσεις, αλλά μπορεί να είναι δύσκολο στην αρχή.
+
+Όταν είμαστε στο toplevel της OCaml (read-eval-print-loop), η OCaml τυπώνει τον
+τύπο που συμπεραίνει όταν εισάγουμε μια έκφραση.
+
+```
+# let inc x = x + 1 ;;
+val inc : int -> int = <fun>
+# let a = 99 ;;
+val a : int = 99
+```
+Για ένα source αρχείο μπορούμε να χρησιμοποιούμε την εντολή
+"ocamlc -i /path/to/file.ml" στο terminal για να τυπώσει όλα τα ονόματα και
+τους τύπους.
+
+```
+$ cat sigtest.ml
+let inc x = x + 1
+let add x y = x + y
+
+let a = 1
+
+$ ocamlc -i ./sigtest.ml
+val inc : int -> int
+val add : int -> int -> int
+val a : int
+```
+
+Σημειώστε ότι τα type signatures των συναρτήσεων με πολλά ορίσματα είναι
+γραμμένα σε curried form. Μια συνάρτηση με πολλά ορίσματα μπορεί να
+αναπαρασταθεί ως σύνθεση συναρτήσεων με μόνο ένα όρισμα.
+Η "f(x,y) = x + y" από το παράδειγμα, όταν εφαρμόζεται στα ορίσματα 2 και 3
+είναι ισοδύναμη με την εφαρμογή της "f0(y) = 2 + y" στο 3. Γι' αυτό έχει τύπο
+"int -> int -> int".
+
+
+```ocaml
+(*** Comments ***)
+
+(* Τα σχόλια περικλείονται σε (* και *). Μπορούν να είναι και εμφωλευμένα *)
+
+(* Δεν υπάρχει ειδικό σύμβολο για σχόλια μιας γραμμής *)
+
+
+(*** Μεταβλητές και Συναρτήσεις ***)
+
+(* Οι εκφράσεις διαχωρίζονται από διπλό semicolon, ";;".
+ Σε πολλές περιπτώσεις είναι περιττό, αλλά εδώ θα το χρησιμοποιούμε σε
+ κάθε έκφραση για ευκολότερο copy-paste στο interpreter shell.
+ Το να χρησιμοποιούμε περιττά ;; σε αρχεία κώδικα θεωρείται συνήθως
+ κακό στυλιστικά. *)
+
+(* Οι δηλώσεις μεταβλητών και συναρτήσεων χρησιμοποιούν το keyword "let" *)
+let x = 10 ;;
+
+(* Η OCaml επιτρέπει χαρακτήρες μονών εισαγωγικών σε identifiers.
+ το μονό εισαγωγικό δεν έχει κάποια σημασία σε αυτή την περίπτωση,
+ χρησιμοποιείται συνήθως σε περιπτώσεις που σε άλλες γλώσσες χρησιμοποιούμε
+ ονόματα όπως "foo_tmp". *)
+let foo = 1 ;;
+let foo' = foo * 2 ;;
+
+(* Από τη στιγμή που ο compiler της OCaml συμπεραίνει τους τύπους αυτόματα,
+ κανονικά δεν χρειάζεται να δηλώνουμε ρητά τον τύπο ορισμάτων. Παρ'όλα αυτά
+ μπορούμε να το κάνουμε αν θέλουμε ή χρειάζεται *)
+let inc_int (x: int) : int = x + 1 ;;
+
+(* Μία από αυτές τις περιπτώσεις που είναι αναγκαίο να δηλώσουμε ρητά τύπους
+ είναι για να λύσουμε την αμφισημία μεταξύ δύο record types που έχουν πεδία με
+ όμοια ονόματα. Η εναλλακτική είναι να βάλουμε αυτούς τους τύπους σε modules,
+ αλλά και τα δύο αυτά θέματα είναι εκτός του σκοπού αυτού το μαθήματος. *)
+
+(* Πρέπει να δηλώνουμε ότι μία συνάρτηση είναι αναδρομική με "rec". *)
+let rec factorial n =
+ if n = 0 then 1
+ else n * factorial (n-1)
+;;
+
+(* H εφαρμογή συναρτήσεων συνήθως δεν χρειάζεται παρενθέσεις γύρω από ορίσματα *)
+let fact_5 = factorial 5 ;;
+
+(* ...εκτός αν τα ορίσματα είναι εκφράσεις *)
+let fact_4 = factorial (5-1) ;;
+let sqr2 = sqr (-2) ;;
+
+(* Κάθε συνάρητση πρέπει να έχει τουλάχιστον ένα όρισμα.
+ Από τη στιγμή που κάποιες συναρτήσεις, από τη φύση τους, δεν παίρνουν κάποιο
+ όρισμα, υπάρχει ο τύπος "unit" που έχει μόνο μία τιμή,
+ την οποία γράφουμε ως "()". *)
+let print_hello () = print_endline "hello world" ;;
+
+(* Προσέχετε ότι πρέπει να γράφουμε το "()" ως όρισμα και όταν την καλούμε. *)
+print_hello () ;;
+
+(* Το να καλούμε μια συνάρτηση με λιγότερα ορίσματα από όσα δέχεται
+ δεν προκαλεί πρόβλημα, απλά παράγει μια νέα συνάρτηση. *)
+let make_inc x y = x + y ;; (* make_inc is int -> int -> int *)
+let inc_2 = make_inc 2 ;; (* inc_2 is int -> int *)
+inc_2 3 ;; (* Αποτιμάται σε 5 *)
+
+(* Μπορούμε να χρησιμοποιούμε πολλές εκφράσεις στο σώμα μιας συνάρτησης.
+ Η αποτίμηση της τελευταίας έκφρασης είναι η τιμή που επιστρέφει η συνάρτηση.
+ Όλες οι ενδιάμεσες εκφράσεις πρέπει να είναι τύπου "unit".
+ Αυτό είναι ιδιαίτερα χρήσιμο όταν γράφουμε σε προστακτικό στυλ, η απλούστερη
+ μορφή αυτού είναι η εισαγωγή ενός debug print. *)
+let print_and_return x =
+ print_endline (string_of_int x);
+ x
+;;
+
+(* Ως συναρτησιακή γλώσσα η OCaml δεν έχει "procedures" (διαδικασίες).
+ Κάθε συνάρτηση πρέπει να επιστρέφει κάτι. Οπότε, συναρτήσεις που δεν
+ επιστρέφουν κάτι και καλούνται μόνο για τις παρενέργειες τους,
+ όπως η print_endline, επιστρέφουν τιμή τύπου "unit". *)
+
+
+(* Οι ορισμοί μπορούν να γίνουν αλυσιδωτά με τη δομή "let ... in".
+ Αυτό είναι περίπου το ίδιο με το να αναθέτουμε τιμές σε πολλές μεταβλητές
+ πριν τις χρησιμοποιήσουμε σε εκφράσεις σε προστακτικές γλώσσες. *)
+let x = 10 in
+let y = 20 in
+x + y ;;
+
+(* Εναλλακτικά μπορούμε να χρησιμποιούμε τη δομή "let ... and ... in".
+ Αυτό είναι εξαιρετικά χρήσιμο για αμοιβαία αποκλειόμενες συναρτήσεις,
+ όπυ με "let .. in", ο compiler θα παραπονιόταν για unbound values *)
+let rec
+ is_even = function
+ | 0 -> true
+ | n -> is_odd (n-1)
+and
+ is_odd = function
+ | 0 -> false
+ | n -> is_even (n-1)
+;;
+
+(* Οι ανώνυμες συναρτήσεις χρησιμοποιούν την εξής σύνταξη: *)
+let my_lambda = fun x -> x * x ;;
+
+(*** Τελεστές ***)
+
+(* Δεν υπάρχει ιδιαίτερη διάκριση ανάμεσα σε τελεστές και συναρτήσεις.
+ Κάθε τελεστής μπορεί να κληθεί ως συνάρτηση. *)
+
+(+) 3 4 (* Same as 3 + 4 *)
+
+(* Υπάρχει ένας αριθμός built-in τελεστών. Ένα ασυνήθιστο χαρακτηριστικό είναι
+ ότι η OCaml δεν μπορεί να κάνει έμμεση μετατροπή τύπων
+ ανάμεσα σε ακεραίους και floats, επίσης, χρησιμοποιεί διαφορετικούς τελεστές
+ για τους floats (αριθμούς κινητής υποδιαστολής) *)
+12 + 3 ;; (* Πρόσθεση ακεραίων. *)
+12.0 +. 3.0 ;; (* Πρόσθεση κινητής υποδιαστολής. *)
+
+12 / 3 ;; (* Διαίρεση ακεραίων. *)
+12.0 /. 3.0 ;; (* Διαίρεση κινητής υποδιαστολής. *)
+5 mod 2 ;; (* Υπόλοιπο. *)
+
+(* Το ενός-ορίσματος μείον είναι αξιοσημείωτη εξαίρεση, είναι πολυμορφικό.
+ Ωστόσο, έχει καθαρές μορφές ακεραίων και float. *)
+- 3 ;; (* Πολυμορφικό, ακέραιοι *)
+- 4.5 ;; (* Πολυμορφικό, float *)
+~- 3 (* Μόνο για integer *)
+~- 3.4 (* Type error *)
+~-. 3.4 (* Μόνο για float *)
+
+(* Μπορούμε να ορίζουμε δικούς μας τελεστές ή να ξανα-ορίσουμε υπάρχοντες.
+ Σε αντίθεση με την SML ή τη Haskell, μόνο ορισμένα σύμβολα μπορούν να
+ χρησιμοποιηθούν για ονόματα τελεστών και το πρώτο σύμβολο ορίζει την
+ επιμεριστικότητα και προτεραιότητα πράξεων. *)
+let (+) a b = a - b ;; (* και καλή τύχη στον επόμενο... *)
+
+(* Πιο χρήσιμο: ένας τελεστής αντιστρόφου για floats.
+ οι τελεστές ενός-ορίσματος πρέπει να ξεκινούν με "~". *)
+let (~/) x = 1.0 /. x ;;
+~/4.0 (* = 0.25 *)
+
+
+(*** Built-in δομές δεδομένων ***)
+
+(* Οι λίστες περικλείονται από αγκύλες και τα στοιχεία τους
+ διαχωρίζονται με semicolons. *)
+let my_list = [1; 2; 3] ;;
+
+(* Οι tuples (προαιρετικά) περικλείονται από παρενθέσεις, τα στοιχεία τους
+ διαχωρίζονται με κόμματα. *)
+let first_tuple = 3, 4 ;; (* Έχει τύπο "int * int". *)
+let second_tuple = (4, 5) ;;
+
+(* Συνέπεια: αν προσπαθήσεουμε να διαχωρίσουμε τα στοιχεία μιας λίστας
+ με κόμματα, θα πάρουμε μια λίστα με ένα tuple ως στοιχείο.
+ Μπορεί να την πατήσουμε εύκολα έτσι. *)
+let bad_list = [1, 2] ;; (* Becomes [(1, 2)] *)
+
+(* Μπρούμε να προσπελάσουμε στοιχεία μιας λίστας με τη συνάρτηση List.nth. *)
+List.nth my_list 1 ;;
+
+(* Yπάρχουν συναρτήσεις ανώτερης τάξης για λίστες, όπως οι map και filter. *)
+List.map (fun x -> x * 2) [1; 2; 3] ;;
+List.filter (fun x -> x mod 2 = 0) [1; 2; 3; 4] ;;
+
+(* Μπορούμε να προσθέτουμε στοιχεία στην αρχή μιας λίστας με τον
+ constructor "::", συνήθως αναφέρεται ως "cons". *)
+1 :: [2; 3] ;; (* Αποτέλεσμα: [1; 2; 3] *)
+
+(* Οι πίνακες Arrays περικλείονται από [| |] *)
+let my_array = [| 1; 2; 3 |] ;;
+
+(* Προσπελαύνουμε στοιχεία ενός πίνακα ως εξής: *)
+my_array.(0) ;;
+
+
+(*** Strings και Χαρακτήρες ***)
+
+(* Χρησιμοποιούμε διπλά εισαγωγικά για τα string literals. *)
+let my_str = "Hello world" ;;
+
+(* Μονά εισαγωγικά για τα literals χαρακτήρων. *)
+let my_char = 'a' ;;
+
+(* Τα μονά και τα διπλά εισαγωγικά δεν είναι ισοδύναμα. *)
+let bad_str = 'syntax error' ;; (* Syntax error. *)
+
+(* Αυτό μας δίνει ένα string με έναν χαρακτήρα και όχι εναν χαρακτήρα. *)
+let single_char_str = "w" ;;
+
+(* Τα strings παρατίθενται με τον τελεστή "^". *)
+let some_str = "hello" ^ "world" ;;
+
+(* Τα strings δεν είναι πίνακες από χαρακτήρες όπως στην C.
+ Δεν μπορούμε να ανακατεύουμε strings με χαρακτήρες σε εκφράσεις.
+ Μπορούμε να μετατρέπουμε χαρακτήρες σε strings με "String.make 1 my_char".
+ Υπάρχουν πιο βολικές συναρτήσεις για αυτό το σκοπό σε πρόσθετες βιβλιοθήκες,
+ όπως η Core.Std που μπορεί να μην έχουν εγκατασταθεί/φορτωθεί by default. *)
+let ocaml = (String.make 1 'O') ^ "Caml" ;;
+
+(* Υπάρχει και μια συνάρτηση printf. *)
+Printf.printf "%d %s" 99 "bottles of beer" ;;
+
+(* Υπάρχουν και συναρτήσεις read/write χωρίς μορφοποίηση. *)
+print_string "hello world\n" ;;
+print_endline "hello world" ;;
+let line = read_line () ;;
+
+
+(*** User-defined τύποι δεδομένων ***)
+
+(* Μπορούμε να ορίζουμε τύπους δεδομένων με τη δομή "type some_type".
+ Όπως σε αυτό τον άχρηστο τύπο που αντιγράφει τους ακεραίους: *)
+type my_int = int ;;
+
+(* Πιο ενδιαφέροντες τύποι περιλαμβάνουν τους λεγόμενους type constructors.
+ Αυτοί πρέπει να ξεκινούν με κεφαλαίο γράμμα. *)
+type ml = OCaml | StandardML ;;
+let lang = OCaml ;; (* Έχει τύπο "ml". *)
+
+(* Οι type constructors δε χρειάζεται να είναι κενοί. *)
+type my_number = PlusInfinity | MinusInfinity | Real of float ;;
+let r0 = Real (-3.4) ;; (* Έχει τύπο "my_number". *)
+
+(* Μπορούν να χρησιμοποιηθούν για πολυμορφική αριθμιτική *)
+type number = Int of int | Float of float ;;
+
+(* Σημείο στο επίπεδο, βασικά ένα tuple περιορισμένου συγκεκριμένου τύπου *)
+type point2d = Point of float * float ;;
+let my_point = Point (2.0, 3.0) ;;
+
+(* Οι τύποι μπορούν να είναι παραμετροποιημένοι, όπως σε αυτόν τον τύπο για
+ λίστες λίστών με οτιδήποτε τύπου στοιχεία. Το 'a μπορεί να αντικατασταθεί από
+ οποιονδήποτε τύπο. *)
+type 'a list_of_lists = 'a list list ;;
+type int_list_list = int list_of_lists ;;
+
+(* Οι τύποι μπορούν επίσης να ορίζονται αναδρομικά. Σαν αυτόν εδώ τον τύπο που
+ είναι ανάλογος της built in λίστας από ακεραίους. *)
+type my_int_list = EmptyList | IntList of int * my_int_list ;;
+let l = IntList (1, EmptyList) ;;
+
+
+(*** Ταίριασμα Προτύπων - Pattern Matching ***)
+
+(* Το ταίριασμα προτύπων είναι κάπως σαν το switch statement σε προστακτικές
+ γλώσσες προγραμματισμού, αλλά παρέχει πολύ μεγαλύτερη εκφραστική ισχύ.
+
+ Παρόλο που φαίνεται περίπλοκο, στην πραγματικότητα είναι απλώς ταίριασμα
+ ενός ορίσματος με μια συγκεκριμένη τιμή, ένα κατηγόρημα ή έναν type constructor
+ Το σύστημα τύπων είναι αυτό που το κάνει τόσο ισχυρό. *)
+
+(** Ταίριασμα με ακριβείς τιμές. **)
+
+let is_zero x =
+ match x with
+ | 0 -> true
+ | _ -> false (* Το "_" σημαίνει "οτιδήποτε άλλο". *)
+;;
+
+(* Εναλλακτικά μπορούμε να χρησιμοποιούμε το keyword "function". *)
+let is_one = function
+| 1 -> true
+| _ -> false
+;;
+
+(* Ταίριασμα με κατηγορήματα, γνωστό και ως "guarded pattern matching". *)
+let abs x =
+ match x with
+ | x when x < 0 -> -x
+ | _ -> x
+;;
+
+abs 5 ;; (* 5 *)
+abs (-5) ;; (* 5 πάλι *)
+
+(** Ταίριασμα με type constructors **)
+
+type animal = Dog of string | Cat of string ;;
+
+let say x =
+ match x with
+ | Dog x -> x ^ " says woof"
+ | Cat x -> x ^ " says meow"
+;;
+
+say (Cat "Fluffy") ;; (* "Fluffy says meow". *)
+
+(** Διάσχιση δομών δεδομένων με ταίριασμα προτύπων **)
+
+(* Οι αναδρομικοί τύποι μπορούν να διασχιστούν εύκολα με ταίριασμα προτύπων.
+ Ας δούμε πώς μπορούμε να διασχίσουμε μια λίστα.
+ Παρόλο που το built-in cons ("::") μοιάζει με infix τελεστή,
+ στην πραγματικότητα είναι ένας type constructor και μπορεί να
+ ταιριαστεί όπως όλοι οι type constructors. *)
+let rec sum_list l =
+ match l with
+ | [] -> 0
+ | head :: tail -> head + (sum_list tail)
+;;
+
+sum_list [1; 2; 3] ;; (* Αποτιμάται σε 6 *)
+
+(* Η built-in συνταξη των cons εμποδίζει τη δομή λίγο, γι αυτό θα φτιάξουμε
+ το δικό μας τύπο λίστας για την παρουσίαση. *)
+type int_list = Nil | Cons of int * int_list ;;
+let rec sum_int_list l =
+ match l with
+ | Nil -> 0
+ | Cons (head, tail) -> head + (sum_int_list tail)
+;;
+
+let t = Cons (1, Cons (2, Cons (3, Nil))) ;;
+sum_int_list t ;;
+```
+
+## Περισσότερα για την OCaml
+
+* Επισκεφθείτε την επίσημη σελίδα της OCaml για να κατεβάσετε τον compiler και να διαβάσετε το documentation: <http://ocaml.org/>
+* Δοκιμάστε διαδραστικά μαθήματα και έναν web-based interpreter από την OCaml Pro: <http://try.ocamlpro.com/>
diff --git a/el-gr/rust-gr.html.markdown b/el-gr/rust-gr.html.markdown
index 79f210ac..4da75b1d 100644
--- a/el-gr/rust-gr.html.markdown
+++ b/el-gr/rust-gr.html.markdown
@@ -242,7 +242,7 @@ fn main() {
// Βρόγχοι `for`
let array = [1, 2, 3];
- for i in array.iter() {
+ for i in array {
println!("{}", i);
}
diff --git a/el-gr/vim-gr.html.markdown b/el-gr/vim-gr.html.markdown
index 679a5488..b11b5c33 100644
--- a/el-gr/vim-gr.html.markdown
+++ b/el-gr/vim-gr.html.markdown
@@ -3,7 +3,7 @@ category: tool
tool: vim
contributors:
- ["RadhikaG", "https://github.com/RadhikaG"]
-filename: LearnVim.txt
+filename: LearnVim-gr.txt
lang: el-gr
---
diff --git a/elixir.html.markdown b/elixir.html.markdown
index 8b80c582..9f96be49 100644
--- a/elixir.html.markdown
+++ b/elixir.html.markdown
@@ -33,7 +33,7 @@ and many more features.
0x1F # integer
3.0 # float
-# Atoms, that are literals, a constant with name. They start with `:`.
+# Atoms are constants whose values are their own name. They start with `:`.
:hello # atom
# Tuples that are stored contiguously in memory.
diff --git a/es-es/bash-es.html.markdown b/es-es/bash-es.html.markdown
index fb89b2a0..27070e79 100644
--- a/es-es/bash-es.html.markdown
+++ b/es-es/bash-es.html.markdown
@@ -18,7 +18,7 @@ Tutorial de Shell en español.
Bash es el nombre del shell de unix, el cual también es distribuido como
el shell del sistema operativo GNU. También es el shell
-por defecto de Linux y Mac OS X. Casi todos los ejemplos abajo pueden
+por defecto de Linux y macOS. Casi todos los ejemplos abajo pueden
ser parte de un script shell o ser ejecutados directamente en la terminal.
[Leer más aquí.](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/es-es/c++-es.html.markdown b/es-es/c++-es.html.markdown
index 2c3762d5..9db2c802 100644
--- a/es-es/c++-es.html.markdown
+++ b/es-es/c++-es.html.markdown
@@ -8,6 +8,7 @@ contributors:
- ["Connor Waters", "http://github.com/connorwaters"]
translators:
- ["Gerson Lázaro", "https://gersonlazaro.com"]
+ - ["Diego Ramirez", "https://DiddiLeija.github.io"]
lang: es-es
---
@@ -101,8 +102,8 @@ void print(int myInt)
int main()
{
- print("Hello"); // Resolves to void print(const char*)
- print(15); // Resolves to void print(int)
+ print("Hello"); // Corresponde a void print(const char*)
+ print(15); // Corresponde a void print(int)
}
////////////////////////////////////
@@ -114,7 +115,7 @@ int main()
void doSomethingWithInts(int a = 1, int b = 4)
{
- // Hacer algo con los enteros aqui
+ // Hacer algo con los enteros aquí
}
int main()
@@ -134,7 +135,7 @@ void invalidDeclaration(int a = 1, int b) // Error!
// Espacios de nombre
/////////////////////
-// Espacios de nombres proporcionan ámbitos separados para variable, función y
+// Los espacios de nombres proporcionan ámbitos separados para variable, función y
// otras declaraciones.
// Los espacios de nombres se pueden anidar.
@@ -184,7 +185,7 @@ int main()
#include <iostream> // Incluir para el flujo de entrada/salida
-using namespace std; // Los streams estan en std namespace (libreria estandar)
+using namespace std; // Los streams estan en el espacio de nombre std (libreria estandar)
int main()
{
@@ -208,7 +209,7 @@ int main()
// Las cadenas en C++ son objetos y tienen muchas funciones
#include <string>
-using namespace std; // Strings también estan en namespace std
+using namespace std; // Las cadenas también estan en el nombre de espacio std
string myString = "Hola";
string myOtherString = " Mundo";
@@ -252,7 +253,7 @@ fooRef = bar;
const string& barRef = bar; // Crea una referencia constante a bar.
// Como en C, los valores constantes (y punteros y referencias) no pueden ser
// modificados.
-barRef += ". Hola!"; // Error, referencia constante no puede ser modificada.
+barRef += ". Hola!"; // Error, una referencia constante no puede ser modificada.
// Sidetrack: Antes de hablar más sobre referencias, hay que introducir un
// concepto llamado objeto temporal. Supongamos que tenemos el siguiente código:
@@ -264,7 +265,7 @@ string retVal = tempObjectFun();
// - Una nueva cadena se construye con el objeto devuelto como argumento al
// constructor
// - El objeto devuelto es destruido
-// El objeto devuelto se llama objeto temporal. Objetos temporales son
+// El objeto devuelto se llama objeto temporal. Los objetos temporales son
// creados cada vez que una función devuelve un objeto, y es destruido en el
// fin de la evaluación de la expresión que encierra (Bueno, esto es lo que la
// norma dice, pero los compiladores están autorizados a cambiar este
@@ -295,7 +296,7 @@ void someFun(string&& s) { ... } // Referencia a objeto temporal
string foo;
someFun(foo); // Llama la función con referencia regular
-someFun(tempObjectFun()); // Llama la versión con referencia temporal
+someFun(tempObjectFun()); // Llama la función con referencia temporal
// Por ejemplo, puedes ver estas dos versiones de constructores para
// std::basic_string:
@@ -305,7 +306,7 @@ basic_string(basic_string&& other);
// La idea es que si estamos construyendo una nueva cadena de un objeto temporal
// (que va a ser destruido pronto de todos modos), podemos tener un constructor
// mas eficiente que "rescata" partes de esa cadena temporal. Usted verá este
-// Concepto denominado "movimiento semántico".
+// concepto denominado "movimiento semántico".
////////////////////////////////////////////
// Clases y programación orientada a objetos
@@ -322,9 +323,7 @@ class Dog {
int weight;
// Todos los miembros siguientes de este son públicos
-// Hasta que se encuentre "private" o "protected".
-// All members following this are public
-// until "private:" or "protected:" is found.
+// hasta que se encuentre "private" o "protected".
public:
// Constructor por defecto
@@ -339,8 +338,8 @@ public:
void setWeight(int dogsWeight);
// Funciones que no modifican el estado del objeto
- // Deben marcarse como const.
- // Esto le permite llamarlas si se envia una referencia constante al objeto.
+ // deben marcarse como const.
+ // Esto le permite llamarlas si se envía una referencia constante al objeto.
// También tenga en cuenta que las funciones deben ser declaradas
// explícitamente como _virtual_ para que sea reemplazada en las clases
// derivadas.
@@ -357,8 +356,8 @@ public:
// Esto permite paradigmas potentes como RAII
// (mira abajo)
// El destructor debe ser virtual si una clase es dervada desde el;
- // Si no es virtual, entonces la clase derivada destructor
- // No será llamada si el objeto se destruye a través de una referencia de
+ // Si no es virtual, entonces la clase destructora derivada
+ // no será llamada si el objeto se destruye a través de una referencia de
// la clase base o puntero.
virtual ~Dog();
@@ -373,7 +372,7 @@ Dog::Dog()
}
// Objetos (tales como cadenas) deben ser pasados por referencia
-// Si los estas modificando o referencia constante en caso contrario.
+// si los estás modificando, o referencia constante en caso contrario.
void Dog::setName(const std::string& dogsName)
{
name = dogsName;
@@ -413,9 +412,9 @@ class OwnedDog : public Dog {
// Reemplaza el comportamiento de la función de impresión
// de todos los OwnedDogs. Mira
// http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
- // Para una introducción más general si no está familiarizado con el
+ // para una introducción más general si no está familiarizado con el
// polimorfismo de subtipo.
- // La palabra clave override es opcional, pero asegura que estás
+ // La palabra clave override es opcional, pero asegúrate de que estás
// reemplazando el método de una clase base.
void print() const override;
@@ -460,8 +459,8 @@ public:
// pero inicializa el punto al valor por defecto (0, 0)
Point() { };
- // The following syntax is known as an initialization list
- // and is the proper way to initialize class member values
+ // La siguiente sintaxis se conoce como lista de inicialización
+ // y es la forma correcta de inicializar los valores de los miembros de la clase
Point (double a, double b) :
x(a),
y(b)
@@ -474,7 +473,7 @@ public:
Point& operator+=(const Point& rhs);
// También tendría sentido añadir los operadores - y -=,
-    // Pero vamos a omitirlos por razones de brevedad.
+    // pero vamos a omitirlos por razones de brevedad.
};
Point Point::operator+(const Point& rhs) const
@@ -496,7 +495,7 @@ int main () {
// Llama al operador + de Point
// Point llama la función + con right como parámetro
Point result = up + right;
- // Prints "Result is upright (1,1)"
+ // Imprime "Result is upright (1,1)"
cout << "Result is upright (" << result.x << ',' << result.y << ")\n";
return 0;
}
@@ -525,7 +524,7 @@ public:
// plantilla con parámetros sustituidos, por lo que la definición completa
// de la clase debe estar presente en cada invocación.
// Es por esto que usted verá clases de plantilla definidas
-// Enteramente en archivos de cabecera.
+// enteramente en archivos de cabecera.
//Para crear una instancia de una clase de plantilla en la pila:
Box<int> intBox;
@@ -544,7 +543,7 @@ boxOfBox.insert(intBox);
// A veces verás
// template<typename T>
-// en su lugar. La palabra clave "class" y las palabras clave "typename" son
+// en su lugar. La palabra clave "class" y la palabra clave "typename" son
// mayormente intercambiables en este caso. Para la explicación completa, mira
// http://en.wikipedia.org/wiki/Typename
// (sí, esa palabra clave tiene su propia página de Wikipedia).
@@ -568,7 +567,7 @@ Dog fluffy;
fluffy.setName("Fluffy")
barkThreeTimes(fluffy); // Imprime "Fluffy barks" 3 veces.
-Los parámetros de la plantilla no tienen que ser las clases:
+// Los parámetros de la plantilla no tienen que ser las clases:
template<int Y>
void printMessage() {
cout << "Aprende C++ en " << Y << " minutos!" << endl;
@@ -604,7 +603,7 @@ printMessage<10>(); // Prints "Aprende C++ rapido en solo 10 minutos!"
//Todas las excepciones lanzadas dentro del bloque _try_ pueden ser
// capturados por los siguientes manejadores _catch_.
try {
- // No asignar excepciones en el heap usando _new_.
+ // No asigne excepciones en el heap usando _new_.
throw std::runtime_error("Ocurrió un problema");
}
@@ -629,10 +628,10 @@ catch (...)
// (Adquisición de recursos es inicialización).
// A menudo se considera el paradigma más poderoso en C++
// Y el concepto es simple: un constructor de un objeto
-// Adquiere recursos de ese objeto y el destructor les libera.
+// adquiere recursos de ese objeto y el destructor les libera.
// Para entender cómo esto es útil,
-// Considere una función que utiliza un identificador de archivo C:
+// considere una función que utiliza un identificador de archivo C:
void doSomethingWithAFile(const char* filename)
{
// Para empezar, asuma que nada puede fallar.
@@ -691,11 +690,11 @@ bool doSomethingWithAFile(const char* filename)
failure:
fclose(fh);
- return false; // Propagate el error
+ return false; // Propaga el error
}
// Si las funciones indican errores mediante excepciones,
-// Las cosas son un poco más claras, pero pueden optimizarse mas.
+// las cosas son un poco más claras, pero pueden optimizarse más.
void doSomethingWithAFile(const char* filename)
{
FILE* fh = fopen(filename, "r"); // Abrir el archivo en modo lectura
@@ -732,9 +731,9 @@ void doSomethingWithAFile(const std::string& filename)
// Esto tiene ventajas _enormes_:
// 1. No importa lo que pase,
-// El recurso (en este caso el manejador de archivo) será limpiado.
+// el recurso (en este caso el manejador de archivo) será limpiado.
// Una vez que escribes el destructor correctamente,
-// Es _imposible_ olvidar cerrar el identificador y permitir
+// es _imposible_ olvidar cerrar el identificador y permitir
// fugas del recurso.
// 2. Tenga en cuenta que el código es mucho más limpio.
// El destructor se encarga de cerrar el archivo detrás de cámaras
diff --git a/es-es/docker-es.html.markdown b/es-es/docker-es.html.markdown
new file mode 100644
index 00000000..93e17f02
--- /dev/null
+++ b/es-es/docker-es.html.markdown
@@ -0,0 +1,167 @@
+---
+language: docker
+filename: docker-es.bat
+contributors:
+ - ["Ruslan López", "http://javapro.org/"]
+ - ["Michael Chen", "https://github.com/ML-Chen"]
+lang: es-es
+---
+
+```bat
+:: descargar, instalar y ejecutar la imágen del hola mundo
+docker run hello-world
+
+:: Si esta es la primera vez, deberíais de poder ver el mensaje
+:: Unable to find image 'hello-world:latest' locally
+:: latest: Pulling from library/hello-world
+:: 1b930d010525: Pull complete
+:: Digest: sha256:4fe721ccc2e8dc7362278a29dc660d833570ec2682f4e4194f4ee23e415e1064
+:: Status: Downloaded newer image for hello-world:latest
+::
+:: Hello from Docker!
+:: This message shows that your installation appears to be working correctly.
+::
+:: To generate this message, Docker took the following steps:
+:: 1. The Docker client contacted the Docker daemon.
+:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
+:: (amd64)
+:: 3. The Docker daemon created a new container from that image which runs the
+:: executable that produces the output you are currently reading.
+:: 4. The Docker daemon streamed that output to the Docker client, which sent it
+:: to your terminal.
+::
+:: To try something more ambitious, you can run an Ubuntu container with:
+:: $ docker run -it ubuntu bash
+::
+:: Share images, automate workflows, and more with a free Docker ID:
+:: https://hub.docker.com/
+::
+:: For more examples and ideas, visit:
+:: https://docs.docker.com/get-started/
+:: El susodicho mensaje se podría traducir como:
+::
+:: Hola desde Docker!
+:: Este mensaje muestra que su instalación parece estar funcionando crrectamente.
+::
+:: Para generar este mensaje, Docker realizó los siguientes pasos:
+:: 1. El cliente de Docker contactó a Docker daemon.
+:: 2. El Docker daemon obtubo la imágen "hello-world" desde Docker Hub.
+:: (amd64)
+:: 3. El Docker daemon creó un nuevo contenedor a partir de esa imagen con la cual ejecuta el
+:: ejecutable que produce la salida que estás leyendo.
+:: 4. El Docker daemon transmitió dicha salida el cliente Docker, el cual
+:: la envió a tu terminal.
+::
+:: Para intentar algo más ambicioso, puede correr un contenedor Ubuntu mediante:
+:: $ docker run -it ubuntu bash
+::
+:: Comparte imágenes, automatice flujos y más con un Docker ID gratuito:
+:: https://hub.docker.com/
+
+:: ahora veamos las imágenes que se están ejecutando actualmente
+docker ps
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+
+:: veamos las imágenes que hemos ejecutado previamente
+docker ps -a
+
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+:: 4a76281f9c53 hello-world "/hello" 2 minutes ago Exited (0) 2 minutes ago
+:: happy_poincare
+:: la parte del nombre se genera automáticamente, así que probablemente sea diferente para vos
+
+:: eliminemos nuestra imagen previamente generada
+docker rm happy_poincare
+
+:: verifiquemos si realmente fue borrada
+docker ps -a
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+
+:: especifiquemos un nombre personalizado para el contenedor
+docker run --name test_container hello-world
+:: Hello from Docker!
+:: This message shows that your installation appears to be working correctly.
+::
+:: To generate this message, Docker took the following steps:
+:: 1. The Docker client contacted the Docker daemon.
+:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
+:: (amd64)
+:: 3. The Docker daemon created a new container from that image which runs the
+:: executable that produces the output you are currently reading.
+:: 4. The Docker daemon streamed that output to the Docker client, which sent it
+:: to your terminal.
+::
+:: To try something more ambitious, you can run an Ubuntu container with:
+:: $ docker run -it ubuntu bash
+::
+:: Share images, automate workflows, and more with a free Docker ID:
+:: https://hub.docker.com/
+::
+:: For more examples and ideas, visit:
+:: https://docs.docker.com/get-started/
+
+docker ps -a
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+:: d345fe1a4f41 hello-world "/hello" About a minute ago Exited (0) About a minute ago
+:: test_container
+:: tal como podeis ver el nombre es el que especificamos
+
+:: obtener los registros de un contenedor nombrado
+docker logs test_container
+:: Hello from Docker!
+:: This message shows that your installation appears to be working correctly.
+::
+:: To generate this message, Docker took the following steps:
+:: 1. The Docker client contacted the Docker daemon.
+:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
+:: (amd64)
+:: 3. The Docker daemon created a new container from that image which runs the
+:: executable that produces the output you are currently reading.
+:: 4. The Docker daemon streamed that output to the Docker client, which sent it
+:: to your terminal.
+::
+:: To try something more ambitious, you can run an Ubuntu container with:
+:: $ docker run -it ubuntu bash
+::
+:: Share images, automate workflows, and more with a free Docker ID:
+:: https://hub.docker.com/
+::
+:: For more examples and ideas, visit:
+:: https://docs.docker.com/get-started/
+
+docker rm test_container
+
+docker run ubuntu
+:: Unable to find image 'ubuntu:latest' locally
+:: latest: Pulling from library/ubuntu
+:: 2746a4a261c9: Pull complete
+:: 4c1d20cdee96: Pull complete 0d3160e1d0de: Pull complete c8e37668deea: Pull complete Digest: sha256:250cc6f3f3ffc5cdaa9d8f4946ac79821aafb4d3afc93928f0de9336eba21aa4
+:: Status: Downloaded newer image for ubuntu:latest
+
+docker ps -a
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+:: c19e9e5b000a ubuntu "/bin/bash" 5 seconds ago Exited (0) 4 seconds ago
+:: relaxed_nobel
+
+:: ejecutando un contenedor en modo interactivo
+docker run -it ubuntu
+:: root@e2cac48323d2:/# uname
+:: Linux
+:: root@e2cac48323d2:/# exit
+:: exit
+
+docker rm relaxed_nobel
+
+docker ps -a
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+:: e2cac48323d2 ubuntu "/bin/bash" 2 minutes ago Exited (0) About a minute ago
+:: nifty_goldwasser
+
+docker rm nifty_goldwasser
+```
diff --git a/es-es/matlab-es.html.markdown b/es-es/matlab-es.html.markdown
index 9f1656bb..faa3dead 100644
--- a/es-es/matlab-es.html.markdown
+++ b/es-es/matlab-es.html.markdown
@@ -31,7 +31,7 @@ esto
% Dos símbolos de porcentaje denotan el comienzo de una nueva sección de código.
% Secciones de código individuales pueden ser ejecutadas moviendo el cursor hacia la sección,
% seguida por un clic en el botón de “Ejecutar Sección”
-% o usando Ctrl+Shift+Enter (Windows) o Cmd+Shift+Return (OS X)
+% o usando Ctrl+Shift+Enter (Windows) o Cmd+Shift+Return (macOS)
%% Este es el comienzo de una sección de código
% Una forma de usar las secciones es separar un código de inicio costoso que no cambia, como cargar datos
diff --git a/es-es/objective-c-es.html.markdown b/es-es/objective-c-es.html.markdown
index 26cd14d9..28733cfb 100644
--- a/es-es/objective-c-es.html.markdown
+++ b/es-es/objective-c-es.html.markdown
@@ -9,7 +9,7 @@ translators:
lang: es-es
filename: LearnObjectiveC-es.m
---
-Objective C es el lenguaje de programación principal utilizado por Apple para los sistemas operativos OS X y iOS y sus respectivos frameworks, Cocoa y Cocoa Touch.
+Objective C es el lenguaje de programación principal utilizado por Apple para los sistemas operativos macOS y iOS y sus respectivos frameworks, Cocoa y Cocoa Touch.
Es un lenguaje de programación para propósito general que le agrega al lenguaje de programación C una mensajería estilo "Smalltalk".
diff --git a/es-es/rust-es.html.markdown b/es-es/rust-es.html.markdown
index b43cb815..dc48abf5 100644
--- a/es-es/rust-es.html.markdown
+++ b/es-es/rust-es.html.markdown
@@ -225,7 +225,7 @@ fn main() {
// bucles `for`
let array = [1, 2, 3];
- for i in array.iter() {
+ for i in array {
println!("{}", i);
}
diff --git a/es-es/swift-es.html.markdown b/es-es/swift-es.html.markdown
index 22e3c532..60af1913 100644
--- a/es-es/swift-es.html.markdown
+++ b/es-es/swift-es.html.markdown
@@ -11,7 +11,7 @@ lang: es-es
filename: learnswift-es.swift
---
-Swift es un lenguaje de programación para el desarrollo en iOS y OS X creado
+Swift es un lenguaje de programación para el desarrollo en iOS y macOS 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.
diff --git a/es-es/typescript-es.html.markdown b/es-es/typescript-es.html.markdown
index c42da4a4..fbe1290b 100644
--- a/es-es/typescript-es.html.markdown
+++ b/es-es/typescript-es.html.markdown
@@ -12,7 +12,7 @@ TypeScript es un lenguaje cuyo objetivo es facilitar el desarrollo de aplicacion
TypeScript añade conceptos comunes como clases, módulos, interfaces, genéricos y (opcionalmente) tipeo estático a JavaScript.
Es un superset de JavaScript: todo el código JavaScript es código válido en TypeScript de manera que se puede integrar fácilmente a cualquier proyecto . El compilador TypeScript emite JavaScript.
-Este artículo se enfocará solo en la sintáxis extra de TypeScript, y no en [JavaScript] (../javascript/).
+Este artículo se enfocará solo en la sintáxis extra de TypeScript, y no en [JavaScript] (../javascript-es/).
Para probar el compilador de TypeScript, diríjase al [Área de Pruebas] (http://www.typescriptlang.org/Playground) donde podrá tipear código, y ver como se auto-completa al tiempo que ve el código emitido JavaScript.
diff --git a/fi-fi/ruby-fi.html.markdown b/fi-fi/ruby-fi.html.markdown
index 52c60182..84a5844f 100644
--- a/fi-fi/ruby-fi.html.markdown
+++ b/fi-fi/ruby-fi.html.markdown
@@ -605,4 +605,4 @@ Something.new.qux # => 'qux'
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - 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
+- [Try Ruby](https://try.ruby-lang.org/) - Rubyn perusteet interaktiivisesti
diff --git a/fish.html.markdown b/fish.html.markdown
new file mode 100644
index 00000000..edbd8909
--- /dev/null
+++ b/fish.html.markdown
@@ -0,0 +1,313 @@
+---
+category: tool
+tool: fish
+contributors:
+ - ["MySurmise", "https://github.com/MySurmise"]
+filename: learn.fish
+---
+
+Fish (**f**riendly **i**nteractive **sh**ell) is the name of an exotic shell. That is a shell with a syntax that is derived from neither the Bourne-Shell nor the C-Shell.
+
+The advantage of fish is that many features that you want in a modern shell come out-of-the-box, so you don't have to install additional software like zsh and oh-my-zsh.
+
+Examples of these features are autosuggestions, 24-bit colors, Man Page Completions (meaning fish automatically parses your man pages and suggests additional options for your commands) or the ability to make options through a web page (when a GUI is installed).
+
+It was released in February 2005.
+
+[Read more](https://fishshell.com/docs/current/language.html)
+
+[Installation guide](https://github.com/fish-shell/fish-shell#getting-fish)
+
+
+# Guide
+
+Be sure you have the newest fish shell. This was made with version 3.3.0. To test, type:
+> fish -v
+
+To start the fish shell, type:
+> fish
+
+to exit, type:
+> exit
+
+or press <kbd>Ctrl + D</kbd>
+
+Now, right out of the gate, there's one annoying thing in fish. It's the welcome message. Who needs that, right? When your shell is started, just type:
+> set -U fish_greeting ""
+
+To set that to the wanted value,  .
+
+
+If you want to execute a single command written in bash, without switching to that shell, you can type:
+> bash -c 'echo "fish is better than bash"'
+
+In fish, you can use single or double quotes.
+The escape character is a `\`
+
+You can change your configuration of fish either by editing the config file
+> vim ~/.config/fish/config.fish
+
+or by opening the aforementioned web settings:
+
+>fish_config
+
+Adding something to your fish PATH Variable is easy:
+> fish_path_add ~/cowsay
+
+Can you do that with bash, huh? No, you always have to look it up... It's just that easy!
+
+But there's more. Most fish-specific commands start, you guessed it, with 'fish'. Just type in `fish` and press <kbd>TAB</kbd>. And there you have one of the many cool features of fish: The autocompletion that **just works.**
+Now you can navigate with <kbd>TAB</kbd>, <kbd>Shift + TAB</kbd> and your Arrow-Keys <kbd>←</kbd><kbd>↑</kbd><kbd>→</kbd><kbd>↓</kbd>.
+
+To get help, contact your local psychiatrist or type `man`. That will bring up the manual for that command, for example:
+> man set
+
+If you finally tried fish, you can see something other in fish that's really cool. Everything has cool colors, if you type in something wrong, it is red, without even executing, if you put something in quotes, you see where it ends and why that quote doesn't work, because there's another qoutation mark in the quote at position 26.
+
+fish has even more cool things, like wildcards.
+For example, type
+> ls *.fish
+
+That will list all fish files in your current directory.
+
+You can have multiple wildcards per command or even a recursive wildcard, `**`, which basically means it includes files and directories, that fit.
+For example the following command would return (in your case):
+> ls ~/images/**.jpg
+
+```
+~/images/nudes/pewdiepie.jpg
+~/images/nudes/peppa.jpg
+~/images/screenshots/2020-42-69.jpg
+~/images/omegalul.jpg
+```
+
+Of course, you can also pipe the output of a command to another command
+
+>echo sick egg, nadia. no u do really goofy shit. | grep [udense]
+
+write to a file:
+
+>echo This\ is\ text > file.txt
+
+(noticed the escape character?)
+Add to a file:
+
+>echo This\ is\ a\ line >> file.txt
+
+>echo This\ is\ a\ second\ line >> file.txt
+
+For Autocompletion, just always press <kbd>TAB</kbd>. You will be surprised how many things fish knows.
+
+To use variables, just type `$VAR`, like in bash.
+
+> echo "My home is $HOME"
+
+> My home is /home/myuser
+
+Here comes a difference between single and double quotes. If you use a variable in single quotes, it will not substitute it.
+
+> echo 'My home is $HOME'
+
+> My home is $HOME
+
+More on variables later.
+
+To execute two commands, separate them with `;`
+> echo Lol; echo this is fun
+
+The status code of the last command is stored in `$status`
+
+You can use && for two commands that depend on each other.
+
+> set var lol && echo $var
+
+You can also use and,
+which executes if the previous command was successful
+
+or
+which executes if the previous command was not successful
+
+and not
+which inverts the exit status of a command.
+
+For example:
+
+
+> if not echo It's very late I should not waste my time with this
+
+>> echo Nobody heard you
+
+>end
+
+(You can of course do all of that in the shell)
+
+
+---
+Now let's start with the scripting part of fish.
+
+As with every shell, you can not only execute commands in the shell, but also as files, saved as a `.fish` file.
+(You can also execute `.sh` files with fish syntax, but I always use `.fish` for fish-syntax scripts to distinguish them from bash script files)
+
+```bash
+# This is a comment in fish.
+#
+# If you execute a file without specifying an interpreter,
+# meaning the software that runs your script, you need to tell the shell,
+# where that interpreter is.
+# For fish you just add the following comment as the first line in your script:
+
+#!/bin/fish
+
+# When executing via e.g. fish /path/to/script.fish
+# you don't need that, because you specified fish as an interpreter
+
+# Let's start with variables.
+# for use inside a program, you can use the syntax
+set name = 'My Variable'
+
+
+# use
+set -x name value
+# to eXport
+set -e name
+# to Erase
+
+# a variable set with a space doesn't get sent as two arguments, but as one, as you would expect it.
+set turtlefolder 'Turtle Folder'
+mkdir $turtlefolder
+
+# This will create one folder, as expected, not two, like in bash...
+# Who would even want that? tHiS iS a fEaTurE, nOt a bUg...
+
+# you can even have lists as variables. This actually makes sense, because if you want to have a variable that would create two folders, you just give mkdir a list of your foldernames.
+
+# you can then count the entries in that list with:
+count $PATH
+
+# Not only is everything awesome, but in fish, everything is also a list.
+# So $PWD for example is a list of length 1.
+# To make a list, just give the set command multiple arguments:
+set list entry1 entry2 entry3
+# that way you can also append something to an existing variable:
+set PATH $PATH ~/cowsay/
+
+# But, as previously mentioned, we also have a simpler way to do that specifically in fish.
+# As with every Array/List, you can access it with
+$listvar[2]
+# there's also ranges with
+$listvar[1..5]
+# and you can use negative numbers like
+$listvar[-1]
+# e.g to access the last element.
+
+
+
+# You can also do fancy cartesian products when you combine two list variables:
+set a 1 2 3
+set 1 a b c
+echo $a$1
+# Will output : 1a 2a 3a 1b 2b 3b 1c 2c 3c
+
+# Of course, if you separate them, it will see them as two separate arguments and echo them one after the other. THAT is expected behavior @bash.
+
+# There are also other useful things, like command substitutions. For example, when you want to output the returns of two commands in one line. In bash you would do that with
+echo "`ls` is in $PWD"
+# or
+echo "$(ls) is in $PWD"
+
+# if you ask me, that's unnecessary. I always type in the wrong apostrophe. Why not just use two parenthesis, like in fish?
+echo (ls) is in $PWD
+
+# Yep, that easy. And thanks to fish's highlighting you can instantly see, if you typed it in correctly.
+
+# And, as you would expect, if you ask me, your commands don't work in quotes. I mean why bash? Ok I'll stop now. But in fish, just do:
+echo (ls)" is in $PWD"
+# or
+set myvar "The file"(ls -a)" is in the directory $PWD"
+# will make a List with the string and all files. Try it out. Isn't that cool?
+
+# And to separate these variables in separate arguments, just put a space between them:
+
+set myvar "The files" (ls -a) " are in the directory $PWD"
+
+# There's also if, else if, else
+if grep fish /etc/shells
+ echo Found fish
+else if grep bash /etc/shells
+ echo Found bash
+else
+ echo Got nothing
+end
+
+# A little weird is that you compare stuff with one = sign , of course because we don't need it to set variables, but still... and the keyword "test":
+if test $var = "test"
+ echo yes
+else
+ echo no
+end
+
+# Of course, there's also switch case with
+switch $OS
+case Linux
+ echo "you're good"
+case Windows
+ echo "install Gentoo"
+case Arch
+ echo "I use arch btw"
+case '*'
+ echo "what OS is $OS, please?"
+end
+
+
+# functions in fish get their arguments through the $argv variable. The syntax is following:
+
+function print
+ echo $argv
+end
+
+# There are also events, like the "fish_exit"-event (What may that be, hmm?).
+
+# You can use them by adding them to the function definition:
+
+function on_exit --on-event fish_exit
+ echo fish is now exiting
+end
+
+# find events with the command
+functions --handlers
+
+
+# You can use the functions command to learn more about, well, functions.
+# For example you can print the source code of every function:
+functions cd
+functions print
+# or get the names of all functions:
+functions
+
+# There's while Loops, of course
+while test $var = lol
+ echo lol
+end
+
+# for Loops (with wildcards, they are even cooler):
+for image in *.jpg
+ echo $image
+end
+
+# there's an equivalent to the range(0, 5) in Python, so you can also do the standard for loops with numbers:
+
+set files (ls)
+for number in (seq 10)
+ echo "$files[$number] is file number $number"
+end
+
+# Cool!
+
+# The bashrc equivalent is not fishrc, but the previously mentioned config.fish file in ~/.config/fish/
+
+# To add a function to fish, though, you should create a simple .fish file in that directory. Don't just paste that function in the config.fish. That's ugly.
+
+# If you have more, just add it, but those are the most important basics.
+
+```
+
diff --git a/fortran95.html.markdown b/fortran95.html.markdown
index c256bb38..5fa8ca88 100644
--- a/fortran95.html.markdown
+++ b/fortran95.html.markdown
@@ -443,6 +443,7 @@ end module fruity
For more information on Fortran:
+ [wikipedia](https://en.wikipedia.org/wiki/Fortran)
++ [Fortran-lang Organization](https://fortran-lang.org/)
+ [Fortran_95_language_features](https://en.wikipedia.org/wiki/Fortran_95_language_features)
+ [fortranwiki.org](http://fortranwiki.org)
+ [www.fortran90.org/](http://www.fortran90.org)
diff --git a/fr-fr/asymptotic-notation-fr.html.markdown b/fr-fr/asymptotic-notation-fr.html.markdown
index 491dc3c4..fb0a8220 100644
--- a/fr-fr/asymptotic-notation-fr.html.markdown
+++ b/fr-fr/asymptotic-notation-fr.html.markdown
@@ -67,21 +67,21 @@ f(n) = 3log n + 100
g(n) = log n
```
-Est-ce que `f(n)` O(g(n))?
-Est-ce que `3 log n + 100` O(log n)?
+Est-ce que `f(n)` est égal à O(g(n))?
+Est-ce que `3 log n + 100` est égal à O(log n)?
Regardons maintenant la définition de Big-O.
```
3log n + 100 <= c * log n
```
-Existe t-il une paire de constantes c, n<sub>0</sub> qui satisfait cela pour tout n > <sub>0</sub>?
+Existe t-il une paire de constantes c, n<sub>0</sub> qui satisfait cela pour tout n > n<sub>0</sub>?
```
3log n + 100 <= 150 * log n, n > 2 (Indéfini avec n = 1)
```
-Oui ! La définition de Big-O a été satisfaite, donc `f(n)` is O(g(n)).
+Oui ! La définition de Big-O a été satisfaite, donc `f(n)` est égal à O(g(n)).
*Exemple 2*
@@ -90,15 +90,15 @@ f(n) = 3*n^2
g(n) = n
```
-Est-ce que `f(n)` O(g(n))?
-Est-ce que `3 * n^2` O(n)?
+Est-ce que `f(n)` est égal à O(g(n))?
+Est-ce que `3 * n^2` est égal à O(n)?
Regardons de nouveau la définition de Big-O.
```
3 * n^2 <= c * n
```
-Existe t-il une paire de constantes c, n<sub>0</sub> qui satisfait cela pour tout n > <sub>0</sub>?
+Existe t-il une paire de constantes c, n<sub>0</sub> qui satisfait cela pour tout n > n<sub>0</sub>?
Non, il n'en existe pas. `f(n)` n'est pas égal à O(g(n)).
### Big-Omega
diff --git a/fr-fr/bash-fr.html.markdown b/fr-fr/bash-fr.html.markdown
index 0e764d7d..58d01e6a 100644
--- a/fr-fr/bash-fr.html.markdown
+++ b/fr-fr/bash-fr.html.markdown
@@ -17,7 +17,7 @@ lang: fr-fr
---
Bash est le nom du shell UNIX, qui était aussi distribué avec le système
-d’exploitation GNU et est le shell par défaut sur Linux et Mac OS X.
+d’exploitation GNU et est le shell par défaut sur Linux et macOS.
Presque tous les exemples ci-dessous peuvent être écrits dans un script shell
ou exécutés directement dans le terminal.
diff --git a/fr-fr/java-fr.html.markdown b/fr-fr/java-fr.html.markdown
index d6c68343..b72200d6 100644
--- a/fr-fr/java-fr.html.markdown
+++ b/fr-fr/java-fr.html.markdown
@@ -31,7 +31,7 @@ Les commentaires sur plusieurs lignes ressemblent à ceci.
/**
* Les commentaires de la JavaDoc ressemblent à ceci. Ils sont utilisés pour
* décrire la classe et ses différents attributs.
- * Attributs principaux:
+ * Attributs principaux :
*
* @author Nom (et information de contact comme l'email) de(s) auteur(s).
* @version Version actuelle du programme.
@@ -82,7 +82,7 @@ public class JavaFr {
*/
// Utilisez Scanner pour lire l'entrée
- // Nécessite: import java.util.Scanner;
+ // Nécessite : import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
// Lire une chaîne de caractères
@@ -160,7 +160,7 @@ public class JavaFr {
// L est utilisé pour indiquer que la variable est de type long;
// le nombre serait traité comme un int sans le L
- // Note: byte, short, int et long sont signés. Ils peuvent avoir des
+ // Note : byte, short, int et long sont signés. Ils peuvent avoir des
// valeurs positives et négatives.
// Il n'existe pas de variantes non-signées.
// char, toutefois, est non-signé sur 16 bits
@@ -203,7 +203,7 @@ public class JavaFr {
// BigDecimal - entier immuable et positif de taille arbitraire
//
- // BigDecimal comprend deux parties: une entier de taille arbitraire
+ // BigDecimal comprend deux parties : une entier de taille arbitraire
// (BigInteger) et un entier de 32 bits représantant la position de la
// virgule.
//
@@ -240,13 +240,13 @@ public class JavaFr {
// C'est la manière la plus simple et optimisé par le compilateur
String plusConcatenated = "Strings can " + "be concatenated " + "via + operator.";
System.out.println(plusConcatenated);
- // Affiche: Strings can be concatenated via + operator.
+ // Affiche : Strings can be concatenated via + operator.
// #2 - avec StringBuilder
// Cette méthode ne nécessite pas d'objet String intermédiaire. Elle
// stocke juste les différentes chaînes de caractères et les assemble
// lorsque la méthode toString() est appelée.
- // Attention: Cette classe n'est pas thread-safe (l'objet ne peut pas être partagé
+ // Attention : Cette classe n'est pas thread-safe (l'objet ne peut pas être partagé
// entre les threads). Une alternative
// (avec un impact sur les performances) thread-safe est d'utiliser la
// classe StringBuffer.
@@ -255,7 +255,7 @@ public class JavaFr {
builderConcatenated.append("can use ");
builderConcatenated.append("the StringBuilder class.");
System.out.println(builderConcatenated.toString()); // only now is the string built
- // Affiche: You can use the StringBuilder class.
+ // Affiche : You can use the StringBuilder class.
// StringBuffer est efficace quand la chaîne de caractères n'est pas
// utilisée avec la fin de sa construction.
@@ -276,7 +276,7 @@ public class JavaFr {
// #3 - avec la méthode format() de la classe String.
// Une autre alternative. Rapide et lisible.
String.format("%s may prefer %s.", "Or you", "String.format()");
- // Affiche: Or you may prefer String.format().
+ // Affiche : Or you may prefer String.format().
// Tableau
// La taille du tableau doit être précisée à l'instantiation
@@ -419,7 +419,7 @@ public class JavaFr {
System.out.println("fooFor Value: " + fooFor);
// Fin d'une boucle for avec un label
- outer:
+ outer :
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (i == 5 && j ==5) {
@@ -433,9 +433,9 @@ public class JavaFr {
// La boucle for est également capable d'itérer aussi bien sur un
// tableau que sur des objets qui implémentent l'interface Iterable.
int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9};
- // De la forme: for (<object> : <iterable>)
- // Lu comme: "Pour chaque élément du tableau"
- // note: le type doit correspondre à celui de l'objet itérable
+ // De la forme : for (<object> : <iterable>)
+ // Lu comme : "Pour chaque élément du tableau"
+ // note : le type doit correspondre à celui de l'objet itérable
for (int bar : fooList) {
System.out.println(bar);
//Itère 9 fois et affiche les chiffres de 1 à 9
@@ -511,7 +511,7 @@ public class JavaFr {
// Convert Integer To String
Integer.toString(123); // retourne un object String correspondant à"123"
- // Pour les autres conversions, référer vous aux classes suivantes:
+ // Pour les autres conversions, référer vous aux classes suivantes :
// Double
// Long
// String
@@ -537,7 +537,7 @@ public class JavaFr {
// Initialisation avec double accolades
// Le langage Java ne permet pas de créer des collections statiques d'une
- // manière simple. Généralement, on utilise la forme suivante:
+ // manière simple. Généralement, on utilise la forme suivante :
private static final Set<String> COUNTRIES = new HashSet<String>();
static {
COUNTRIES.add("DENMARK");
@@ -566,7 +566,7 @@ public class JavaFr {
// Cependant, il est préférable de séparer les
// classes dans des fichiers différents.
-// Syntaxe de déclaration des classes:
+// Syntaxe de déclaration des classes :
// <public/private/protected> class <Nom de la classe> {
// // Les attributs, les constructeurs et les méthodes de la classe vont ici.
// // Les functions de classes sont appelées méthode.
@@ -575,11 +575,11 @@ public class JavaFr {
class Bicycle {
// Attributs et variables de la classe Bicycle
- public int cadence; // Public: Peut être accesible depuis n'importe où
- private int speed; // Private: Accisible depuis la classe
- protected int gear; // Protected: Accisible depuis la classe et ses sous-
+ public int cadence; // Public : Peut être accesible depuis n'importe où
+ private int speed; // Private : Accisible depuis la classe
+ protected int gear; // Protected : Accisible depuis la classe et ses sous-
// classes
- String name; // default: Uniquement accesible depuis ce package
+ String name; // default : Uniquement accesible depuis ce package
static String className; // Variable de classe static
// Bloc static
@@ -595,7 +595,7 @@ class Bicycle {
// Ceci est le constructeur de la classe Bicycle
public Bicycle() {
// Vous pouvez aussie appeler un autre constructeur. Par exemple en
- // appelant le constructeur de la classe mère (voir héritage):
+ // appelant le constructeur de la classe mère (voir héritage) :
// this(1, 50, 5, "Bontrager");
gear = 1;
cadence = 50;
@@ -665,7 +665,7 @@ class PennyFarthing extends Bicycle {
// Ici nous modifions la méthode setGear() de la classe mère. Il faut donc
// utiliser l'annotation @Overide. Pour en savoir plus sur les annotations,
// consulter la documention officiel (en anglais) :
- // out: http://docs.oracle.com/javase/tutorial/java/annotations/
+ // out : http://docs.oracle.com/javase/tutorial/java/annotations/
@Override
public void setGear(int gear) {
this.gear = 0;
@@ -719,7 +719,7 @@ public class Fruit implements Edible, Digestible {
}
// En Java, on peut hériter uniquement d'une classe mais on peut implémenter
-// plusieurs interfaces:
+// plusieurs interfaces :
public class ExampleClass extends ExampleClassParent implements InterfaceOne,
InterfaceTwo {
@Override
@@ -734,7 +734,7 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
// Classes abstraites
-// Syntaxe de déclaration:
+// Syntaxe de déclaration :
// <niveau d'accès> abstract class <nom de la classe abstraite> extends <nom de la
// classe mère abstraite> {
// // Constantes et variables
@@ -758,7 +758,7 @@ public abstract class Animal
public void eat()
{
System.out.println("I am an animal and I am Eating.");
- // Note: On peut accéder à une variable privée ici.
+ // Note : On peut accéder à une variable privée ici.
age = 30;
}
@@ -790,7 +790,7 @@ class Dog extends Animal
// age = 30; ==> ERREUR! age est privé et n'est pas accesible.
}
- // NOTE: Vous obtiendrez une erreur si vous utilisé l'annotation @Override
+ // NOTE : Vous obtiendrez une erreur si vous utilisé l'annotation @Override
// ici car Java n'autorise pas la surcharge de méthodes statiques. Ce qui ce
// passe est appelé "method hiding". Si vous voulez en savoir plus,
// consultez cette discussion (en anglais) :
@@ -828,7 +828,7 @@ public final class SaberToothedCat extends Animal
// Méthodes final
public abstract class Mammal()
{
- // Syntaxe:
+ // Syntaxe :
// <niveau d'accès> final <type de retour> <nom de la fonction>(<arguments>)
// Les méthodes déclarées comme final ne peuvent pas être surchargées par
@@ -846,13 +846,13 @@ public abstract class Mammal()
// des valeurs pédéfinies pour celle-ci. En Java, les variables constantes sont
// notées en majuscules.
// On définie un type enum en utilisant le mot clé enum. Par exemple pour les
-// jours de l'année:
+// jours de la semaine :
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
-// On l'utilise ainsi:
+// On l'utilise ainsi :
public class EnumTest {
// On utilise notre énumération
Day day;
@@ -889,7 +889,7 @@ public class EnumTest {
// Le type enum permet de faire bien plus que ce qui est montré ici. Il ne se
// limite pas à une liste de constante mais peut inclure des champs et méthodes.
-// Vous pouvez en savoir plus ici (en anglais):
+// Vous pouvez en savoir plus ici (en anglais) :
//https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
```
@@ -899,7 +899,7 @@ public class EnumTest {
Les liens ci-dessous sont données si vous souhaitez approfondir sur le sujet,
n'hésitez pas à consulter Google pour trouver des exemples spécifiques.
-**Guides officiels d'Oracle**:
+**Guides officiels d'Oracle** :
* [Java Tutorial Trail from Sun / Oracle](https://docs.oracle.com/javase/tutorial/index.html)
@@ -918,7 +918,7 @@ n'hésitez pas à consulter Google pour trouver des exemples spécifiques.
* [Java Code Conventions](https://www.oracle.com/technetwork/java/codeconvtoc-136057.html)
-* Nouvelles fonctionnalités Java 8:
+* Nouvelles fonctionnalités Java 8 :
* [Lambda expressions (functional programming)](https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html)
* [Date and time API (java.time package)](http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html)
@@ -928,7 +928,7 @@ n'hésitez pas à consulter Google pour trouver des exemples spécifiques.
* [Codingbat.com](http://codingbat.com/java)
-**Livres**:
+**Livres** :
* [Head First Java](http://www.headfirstlabs.com/books/hfjava/)
diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown
index fbe1741e..191cdfb6 100644
--- a/fr-fr/objective-c-fr.html.markdown
+++ b/fr-fr/objective-c-fr.html.markdown
@@ -10,7 +10,7 @@ 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.
+L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations macOS et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch.
```objective-c
// Les commentaires sur une seule ligne commencent par //
@@ -30,7 +30,7 @@ ceci
#import <Foundation/Foundation.h>
#import "MaClasse.h"
-// Si vous activez les modules dans les projets iOS >= 7 ou Mac OS X >= 10.9
+// Si vous activez les modules dans les projets iOS >= 7 ou OS X >= 10.9
// dans Xcode 5, vous pouvez importer les frameworks comme cela :
@import Foundation;
diff --git a/fr-fr/rust-fr.html.markdown b/fr-fr/rust-fr.html.markdown
index b3675f5b..a61f78be 100644
--- a/fr-fr/rust-fr.html.markdown
+++ b/fr-fr/rust-fr.html.markdown
@@ -221,7 +221,7 @@ fn main() {
    // `for` boucles / itération
    let array = [1, 2, 3];
-    for i in array.iter() {
+    for i in array {
        println!("{}", i);
    }
diff --git a/fr-fr/set-theory-fr.html.markdown b/fr-fr/set-theory-fr.html.markdown
new file mode 100644
index 00000000..50a4ea30
--- /dev/null
+++ b/fr-fr/set-theory-fr.html.markdown
@@ -0,0 +1,134 @@
+```
+---
+category: tool
+lang: fr-fr
+name: Set theory
+contributors:
+ - ["kieutrang", "https://github.com/kieutrang1729"]
+---
+La théorie des ensembles est une branche des mathématiques qui étudie les ensembles, leurs opérations et leurs propriétés.
+
+* Un ensemble est une collection d'éléments disjoints.
+
+## Symboles de base
+
+### Opérateurs
+* l'opérateur réunion, `∪`, signifie "ou" ;
+* l'opérateur intersection, `∩`, signifie "et" ;
+* l'opérateur différence, `\`, signifie "sans", (lire "A moins B") ;
+* l'opérateur complémentaire, `'`, signifie "le complémentaire de" ;
+* l'opérateur croix, `×`, signifie "le produit cartésien de".
+
+### Autres symboles
+* le symbole deux-points, `:`, signifie "tel que" ;
+* le symbole d'appartenance, `∈`, signifie "appartient à" ;
+* le symbole sous-ensemble, `⊆`, signifie "est un sous-ensemble de" ;
+* le symbole sous-ensemble propre, `⊂`, signifie "est un sous-ensemble de mais n'est pas égal à".
+
+### Ensembles importants
+* `∅`, l'ensemble vide, c'est-à-dire l'ensemble ne contenant aucun élément ;
+* `ℕ`, l'ensemble des nombres naturels ;
+* `ℤ`, l'ensemble des entiers ;
+* `ℚ`, l'ensemble des nombres rationnels ;
+* `ℝ`, l'ensemble des nombres réels.
+
+Quelques mise en gardes sur les ensembles definis ci-dessus:
+1. Même si l'ensemble vide ne contient aucun élément, il est lui-même un sous-ensemble de n'importe quel ensemble.
+2. Il n'y a pas d'accord général sur l'appartenance de zéro dans l'ensemble des nombres naturels, et les livres indiquent explicitment si l'auteur considère le zéro comme nombre naturel ou pas.
+
+
+### Cardinalité
+
+La cardinalité, ou taille, d'un ensemble est déterminée par le nombre d'éléments dans l'ensemble. L'opérateur de cardinalité s'écrit, `| ... |`.
+Par exemple, si `S = { 1, 2, 4 }`, alors `|S| = 3`.
+
+### L'ensemble vide
+* L'ensemble vide peut se définir en comprehension à l'aide d'une propriété qui n'est satisfaite par nul élément, e.g. `∅ = { x : x ≠ x }`, ou `∅ = { x : x ∈ N, x < 0 }`.
+* il n'y a qu'un seul ensemble vide.
+* l'ensemble vide est sous-ensemble de tout ensemble.
+* la cardinalité de l'ensemble vide est 0, ou `|∅| = 0`.
+
+## Notation ensembliste
+
+### Définition par extension
+
+Un ensemble peut être defini en extension par une liste de tous les éléments qui sont contenus dans l'ensemble. Par exemple, `S = { a, b, c, d }`.
+
+Quand le contexte est clair, on peut raccourcir la liste en utilisant des points de suspension. Par exemple, `E = { 2, 4, 6, 8, ... }` est clairement l'ensemble de tous les nombres pairs, contenant un nombre infini des éléments, même si on a explicitement écrit seulement les quatres premiers.
+
+### Définition par comprehension
+
+C'est une notation plus descriptif qui permet de définir un ensemble à l'aide d'un sujet et d'une propriété, et il est noté `S = { sujet : propriété }`. Par exemple,
+
+```
+A = { x : x est une voyelle } = { a, e, i, o, u, y}
+B = { x : x ∈ N, x < 10 } = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
+C = { x : x = 2k, k ∈ N } = { 0, 2, 4, 6, 8, ... }
+```
+
+On peut même appliquer une fonction au sujet, e.g.
+
+```
+D = { 2x : x ∈ N } = { 0, 2, 4, 6, 8, ... }
+```
+
+## Relations
+
+### Appartenance
+
+* Si l'élement `a` est dans l'ensemble `A`, on dit que `a` appartient à `A` et on le note `a ∈ A`.
+* Si l'élement `a` n'est pas dans l'ensemble `A`, on dit que `a` n'appartient pas à `A` et on le note `a ∉ A`.
+
+### Égalité
+
+* On dit que deux ensembles `A` et `B` sont égaux s'ils contiennent les mêmes éléments, et on le note `A = B`.
+* Les ensembles n'ont pas de notion d'ordre, par exemple `{ 1, 2, 3, 4 } = { 2, 3, 1, 4 }`.
+* Un élément ne peut apparaître qu'au plus une seule fois - il n'y a jamais de répétition, e.g. `{ 1, 2, 2, 3, 4, 3, 4, 2 } = { 1, 2, 3, 4 }`.
+* Deux ensembles `A` and `B` sont égaux si et seulement si `A ⊆ B` and `B ⊆ A`.
+
+## Ensemble puissance
+* L'ensemble puissance d'un ensemble `A` est l'ensemble contenant tous les sous-ensembles de `A`. Il est noté `P(A)`. Si la cardinalité d'`A` est `n`, la cardinalité de `P(A)` est `2^n`.
+
+```
+P(A) = { x : x ⊆ A }
+```
+
+## Opérations ensemblistes
+### Réunion
+La réunion de deux ensembles `A` et `B` est l'ensemble contenant tous les éléments qui appartient à `A` ou à `B`.
+
+```
+A ∪ B = { x : x ∈ A ∪ x ∈ B }
+```
+
+### Intersection
+L'intersection de deux ensembles `A` et `B` est l'ensemble contenant tous les éléments qui appartient à la fois à `A` et à `B`.
+
+```
+A ∩ B = { x : x ∈ A, x ∈ B }
+```
+
+### Différence
+La différence de deux ensembles `A` et `B` est l'ensemble contenant tous les éléments de l'ensemble `A` qui n'appartient pas à `B`.
+
+```
+A \ B = { x : x ∈ A, x ∉ B }
+```
+
+### Différence symétrique
+Le différence symétrique de deux ensembles `A` et `B` est l'ensemble contenant tous les éléments de `A` et `B` qui n'apparaissent pas dans leur intersection.
+
+```
+A △ B = { x : ((x ∈ A) ∩ (x ∉ B)) ∪ ((x ∈ B) ∩ (x ∉ A)) }
+
+A △ B = (A \ B) ∪ (B \ A)
+```
+
+### Produit cartésien
+Le produit cartésien de deux ensembles `A` et `B` est l'ensemble contenant tous les couples dont la première élément appartient à `A` et la deuxième à `B`.
+
+```
+A × B = { (x, y) | x ∈ A, y ∈ B }
+```
+
+```
diff --git a/fr-fr/typescript-fr.html.markdown b/fr-fr/typescript-fr.html.markdown
index 52d34650..8a761f61 100644
--- a/fr-fr/typescript-fr.html.markdown
+++ b/fr-fr/typescript-fr.html.markdown
@@ -12,7 +12,7 @@ TypeScript est un langage visant à faciliter le développement d'applications l
TypeScript ajoute des concepts classiques comme les classes, les modules, les interfaces, les génériques et le typage statique (optionnel) à JavaScript.
C'est une surcouche de JavaScript : tout le code JavaScript est valide en TypeScript ce qui permet de l'ajouter de façon transparente à n'importe quel projet. Le code TypeScript est transcompilé en JavaScript par le compilateur.
-Cet article se concentrera seulement sur la syntaxe supplémentaire de TypeScript, plutôt que celle de [JavaScript] (../javascript/).
+Cet article se concentrera seulement sur la syntaxe supplémentaire de TypeScript, plutôt que celle de [JavaScript] (../javascript-fr/).
Pour tester le compilateur de TypeScript, rendez-vous au [Playground] (http://www.typescriptlang.org/Playground) où vous pourrez coder, profiter d'une autocomplétion et accéder directement au rendu JavaScript.
diff --git a/gdscript.html.markdown b/gdscript.html.markdown
new file mode 100644
index 00000000..25af0974
--- /dev/null
+++ b/gdscript.html.markdown
@@ -0,0 +1,322 @@
+---
+language: GDScript
+contributors:
+ - ["Wichamir", "https://github.com/Wichamir/"]
+filename: learngdscript.gd
+---
+
+GDScript is a dynamically typed scripting language made specifically for
+free and open source game engine Godot. GDScript's syntax is similar to
+Python's. Its main advantages are ease of use and tight integration with
+the engine. It's a perfect fit for game development.
+
+## Basics
+
+```nim
+# Single-line comments are written using hash symbol.
+"""
+ Multi-line
+ comments
+ are
+ written
+ using
+ docstrings.
+"""
+
+# Script file is a class in itself and you can optionally define a name for it.
+class_name MyClass
+
+# Inheritance
+extends Node2D
+
+# Member variables
+var x = 8 # int
+var y = 1.2 # float
+var b = true # bool
+var s = "Hello World!" # String
+var a = [1, false, "brown fox"] # Array - similar to list in Python,
+ # it can hold different types
+ # of variables at once.
+var d = {
+ "key" : "value",
+ 42 : true
+} # Dictionary holds key-value pairs.
+var p_arr = PoolStringArray(["Hi", "there", "!"]) # Pool arrays can
+ # only hold a certain type.
+
+# Built-in vector types:
+var v2 = Vector2(1, 2)
+var v3 = Vector3(1, 2, 3)
+
+# Constants
+const ANSWER_TO_EVERYTHING = 42
+const BREAKFAST = "Spam and eggs!"
+
+# Enums
+enum { ZERO, ONE , TWO, THREE }
+enum NamedEnum { ONE = 1, TWO, THREE }
+
+# Exported variables are visible in the inspector.
+export(int) var age
+export(float) var height
+export var person_name = "Bob" # Export type hints are unnecessary
+ # if you set a default value.
+
+# Functions
+func foo():
+ pass # pass keyword is a placeholder for future code
+
+func add(first, second):
+ return first + second
+
+# Printing values
+func printing():
+ print("GDScript ", "is ", " awesome.")
+ prints("These", "words", "are", "divided", "by", "spaces.")
+ printt("These", "words", "are", "divided", "by", "tabs.")
+ printraw("This gets printed to system console.")
+
+# Math
+func doing_math():
+ var first = 8
+ var second = 4
+ print(first + second) # 12
+ print(first - second) # 4
+ print(first * second) # 32
+ print(first / second) # 2
+ print(first % second) # 0
+ # There are also +=, -=, *=, /=, %= etc.,
+ # however no ++ or -- operators.
+ print(pow(first, 2)) # 64
+ print(sqrt(second)) # 2
+ printt(PI, TAU, INF, NAN) # built-in constants
+
+# Control flow
+func control_flow():
+ x = 8
+ y = 2 # y was originally a float,
+ # but we can change it's type to int
+ # using the power of dynamic typing!
+
+ if x < y:
+ print("x is smaller than y")
+ elif x > y:
+ print("x is bigger than y")
+ else:
+ print("x and y are equal")
+
+ var a = true
+ var b = false
+ var c = false
+ if a and b or not c: # alternatively you can use &&, || and !
+ print("This is true!")
+
+ for i in range(20): # GDScript's range is similar to Python's
+ print(i) # so this will print numbers from 0 to 19
+
+ for i in ["two", 3, 1.0]: # iterating over an array
+ print(i)
+
+ while x > y:
+ printt(x, y)
+ y += 1
+
+ x = 2
+ y = 10
+ while x < y:
+ x += 1
+ if x == 6:
+ continue # 6 won't get printed because of continue statement
+ prints("x is equal to:", x)
+ if x == 7:
+ break # loop will break on 7, so 8, 9 and 10 won't get printed
+
+ match x:
+ 1:
+ print("Match is similar to switch.")
+ 2:
+ print("However you don't need to put cases before each value.")
+ 3:
+ print("Furthermore each case breaks on default.")
+ break # ERROR! Break statement is unnecessary!
+ 4:
+ print("If you need fallthrough use continue.")
+ continue
+ _:
+ print("Underscore is a default case.")
+
+ # ternary operator (one line if-else statement)
+ prints("x is", "positive" if x >= 0 else "negative")
+
+# Casting
+func casting_examples():
+ var i = 42
+ var f = float(42) # cast using variables constructor
+ var b = i as bool # or using "as" keyword
+
+# Override functions
+# By a convention built-in overridable functions start with an underscore,
+# but in practice you can override virtually any function.
+
+# _init is called when object gets initialized
+# This is the object's constructor.
+func _init():
+ # Initialize object's internal stuff here.
+ pass
+
+# _ready gets called when script's node and
+# its children have entered the scene tree.
+func _ready():
+ pass
+
+# _process gets called on every frame.
+func _process(delta):
+ # The delta argument passed to this function is a number of seconds,
+ # which passed between the last frame and the current one.
+ print("Delta time equals: ", delta)
+
+# _physics_process gets called on every physics frame.
+# That means delta should be constant.
+func _physics_process(delta):
+ # Simple movement using vector addition and multiplication.
+ var direction = Vector2(1, 0) # or Vector2.RIGHT
+ var speed = 100.0
+ self.global_position += direction * speed * delta
+ # self refers to current class instance
+
+# When overriding you can call parent's function using the dot operator
+# like here:
+func get_children():
+ # Do some additional things here.
+ var r = .get_children() # call parent's implementation
+ return r
+
+# Inner class
+class InnerClass:
+ extends Object
+
+ func hello():
+ print("Hello from inner class!")
+
+func use_inner_class():
+ var ic = InnerClass.new()
+ ic.hello()
+ ic.free() # use free for memory cleanup
+```
+
+## Accessing other nodes in the scene tree
+
+```nim
+extends Node2D
+
+var sprite # This variable will hold the reference.
+
+# You can get references to other nodes in _ready.
+func _ready() -> void:
+ # NodePath is useful for accessing nodes.
+ # Create NodePath by passing String to its constructor:
+ var path1 = NodePath("path/to/something")
+ # Or by using NodePath literal:
+ var path2 = @"path/to/something"
+ # NodePath examples:
+ var path3 = @"Sprite" # relative path, immediate child of the current node
+ var path4 = @"Timers/Firerate" # relative path, child of the child
+ var path5 = @".." # current node's parent
+ var path6 = @"../Enemy" # current node's sibling
+ var path7 = @"/root" # absolute path, equivalent to get_tree().get_root()
+ var path8 = @"/root/Main/Player/Sprite" # absolute path to Player's Sprite
+ var path9 = @"Timers/Firerate:wait_time" # accessing properties
+ var path10 = @"Player:position:x" # accessing subproperties
+
+ # Finally, to get a reference use one of these:
+ sprite = get_node(@"Sprite") as Sprite # always cast to the type you expect
+ sprite = get_node("Sprite") as Sprite # here String gets
+ # implicitly casted to NodePath
+ sprite = get_node(path3) as Sprite
+ sprite = get_node_or_null("Sprite") as Sprite
+ sprite = $Sprite as Sprite
+
+func _process(delta):
+ # Now we can reuse the reference in other places.
+ prints("Sprite has global_position of", sprite.global_position)
+
+# Use onready keyword to assign a value to
+# a variable just before _ready executes.
+# This is a commonly used syntax sugar.
+onready var tween = $Tween as Tween
+
+# You can export NodePath, so you can assign it within the inspector.
+export var nodepath = @""
+onready var reference = get_node(nodepath) as Node
+```
+
+## Signals
+
+Signal system is Godot's implementation of the observer programming
+pattern. Here's an example:
+
+```nim
+class_name Player extends Node2D
+
+var hp = 10
+
+signal died() # define signal
+signal hurt(hp_old, hp_new) # signals can take arguments
+
+func apply_damage(dmg):
+ var hp_old = hp
+ hp -= dmg
+ emit_signal("hurt", hp_old, hp) # emit signal and pass arguments
+ if hp <= 0:
+ emit_signal("died")
+
+func _ready():
+ # connect signal "died" to function "_on_death" defined in self
+ self.connect("died", self, "_on_death")
+
+func _on_death():
+ self.queue_free() # destroy Player on death
+```
+
+## Type hints
+
+GDScript can optionally use static typing.
+
+```nim
+extends Node
+
+var x: int # define typed variable
+var y: float = 4.2
+var z := 1.0 # infer type based on default value using := operator
+
+onready var node_ref_typed := $Child as Node
+
+export var speed := 50.0
+
+const CONSTANT := "Typed constant."
+
+func _ready() -> void:
+ # function returns nothing
+ x = "string" # ERROR! Type can't be changed!
+ return
+
+func join(arg1: String, arg2: String) -> String:
+ # function takes two Strings and returns a String
+ return arg1 + arg2
+
+func get_child_at(index: int) -> Node:
+ # function takes an int and returns a Node
+ return get_children()[index]
+
+signal example(arg: int) # ERROR! Signals can't take typed arguments!
+```
+
+## Further Reading
+
+* [Godot's Website](https://godotengine.org/)
+* [Godot Docs](https://docs.godotengine.org/en/stable/)
+* [Getting started with GDScript](https://docs.godotengine.org/en/stable/getting_started/scripting/gdscript/index.html)
+* [NodePath](https://docs.godotengine.org/en/stable/classes/class_nodepath.html)
+* [Signals](https://docs.godotengine.org/en/stable/getting_started/step_by_step/signals.html)
+* [GDQuest](https://www.gdquest.com/)
+* [GDScript.com](https://gdscript.com/) \ No newline at end of file
diff --git a/go.html.markdown b/go.html.markdown
index 5a9214b0..39c8ac74 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -179,7 +179,7 @@ func learnNamedReturns(x, y int) (z int) {
// Go is fully garbage collected. It has pointers but no pointer arithmetic.
// You can make a mistake with a nil pointer, but not by incrementing a pointer.
-// Unlike in C/Cpp taking and returning an address of a local varible is also safe.
+// Unlike in C/Cpp taking and returning an address of a local variable is also safe.
func learnMemory() (p, q *int) {
// Named return values p and q have type pointer to int.
p = new(int) // Built-in function new allocates memory.
@@ -190,6 +190,7 @@ func learnMemory() (p, q *int) {
return &s[3], &r // & takes the address of an object.
}
+// Use the aliased math library (see imports, above)
func expensiveComputation() float64 {
return m.Exp(10)
}
@@ -474,8 +475,9 @@ documentation](http://golang.org/pkg/) and the source code comes up!
Another great resource to learn Go is [Go by example](https://gobyexample.com/).
There are many excellent conference talks and video tutorials on Go available on YouTube, and here are three playlists of the very best, tailored for beginners, intermediate, and advanced Gophers respectively:
-* [Golang University 101](https://www.youtube.com/playlist?list=PLEcwzBXTPUE9V1o8mZdC9tNnRZaTgI-1P) introduces fundamental Go concepts and shows you how to use the Go tools to create and manage Go code
-* [Golang University 201](https://www.youtube.com/playlist?list=PLEcwzBXTPUE_5m_JaMXmGEFgduH8EsuTs) steps it up a notch, explaining important techniques like testing, web services, and APIs
-* [Golang University 301](https://www.youtube.com/watch?v=YHRO5WQGh0k&list=PLEcwzBXTPUE8KvXRFmmfPEUmKoy9LfmAf) dives into more advanced topics like the Go scheduler, implementation of maps and channels, and optimisation techniques
+
+- [Golang University 101](https://www.youtube.com/playlist?list=PLEcwzBXTPUE9V1o8mZdC9tNnRZaTgI-1P) introduces fundamental Go concepts and shows you how to use the Go tools to create and manage Go code
+- [Golang University 201](https://www.youtube.com/playlist?list=PLEcwzBXTPUE_5m_JaMXmGEFgduH8EsuTs) steps it up a notch, explaining important techniques like testing, web services, and APIs
+- [Golang University 301](https://www.youtube.com/playlist?list=PLEcwzBXTPUE8KvXRFmmfPEUmKoy9LfmAf) dives into more advanced topics like the Go scheduler, implementation of maps and channels, and optimisation techniques
Go Mobile adds support for mobile platforms (Android and iOS). You can write all-Go native mobile apps or write a library that contains bindings from a Go package, which can be invoked via Java (Android) and Objective-C (iOS). Check out the [Go Mobile page](https://github.com/golang/go/wiki/Mobile) for more information.
diff --git a/haskell.html.markdown b/haskell.html.markdown
index 328da5c9..29712570 100644
--- a/haskell.html.markdown
+++ b/haskell.html.markdown
@@ -41,6 +41,8 @@ False
-- Boolean operations
not True -- False
not False -- True
+True && False -- False
+True || False -- True
1 == 1 -- True
1 /= 1 -- False
1 < 10 -- True
diff --git a/hd-hd/json-hd.html.markdown b/hd-hd/json-hd.html.markdown
new file mode 100644
index 00000000..dd1657cd
--- /dev/null
+++ b/hd-hd/json-hd.html.markdown
@@ -0,0 +1,86 @@
+---
+language: 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"]
+ - ["Athanasios Emmanouilidis", "https://github.com/athanasiosem"]
+translators:
+ - ["Namami Shanker", "https://github.com/NamamiShanker"]
+lang: hd-hd
+---
+
+जैसन(JSON) इस अत्यंत सरल डाटा-इंटरचेंज फॉर्मेट है| जैसा [json.org](https://json.org) कहती है, ये इंसानो के पढ़ने और लिखने के लिए भी आसान है और और मशीन के लिए इसे पार्स और उतपन्न करना भी बेहद सरल है|
+
+जैसन(JSON) के एक अंश को इनमे से किसी एक का प्रतिनिधित्व(represent) करना चाहिए:
+
+* एक नाम/वैल्यू जोड़े का कलेक्शन (`{ }`). कई दूसरी भाषाओ में इसे ऑब्जेक्ट, रिकॉर्ड, स्ट्रक्ट, डिक्शनरी, हैश टेबल, कीड लिस्ट, या असोसिएटिव ऐरे का भी नाम दिया जाता है|
+* वैल्यूज की एक व्यवस्थित लिस्ट(ordered list) (`[ ]`). कई दूसरी भाषाओ में इसे ऐरे, वेक्टर, लिस्ट, या सीक्वेंस भी कहा जाता है|
+
+जैसन(JSON) अपने शुद्धतम रूप में कमैंट्स सपोर्ट नहीं करता है, पर ज़्यादातर पारसर C स्टाइल की कमैंट्स (`//`, `/* */`) सपोर्ट करेंगे| कुछ पारसर्स अंतिम कॉमा भी स्वीकार करते हैं (जब आप किसी ऐरे के अंतिम एलिमेंट या किसी ऑब्जेक्ट की अंतिम प्रॉपर्टी के बार एक कॉमा छोड़ देते हैं), पर ऐसी गलतियों से बचना चाहिए बेहतर कम्पेटिबिलिटी के लिए|
+
+ ये उदाहरण १०० प्रतिशत मान्य जैसन(JSON) है| किस्मत से, जैसन(JSON) डॉक्यूमेंट को पढ़ के ही आप इसे समझ जायेंगे|
+
+समर्थित डाटा टाइप्स:
+
+* स्ट्रिंग्स(Strings): `"नमस्ते"`, `"\"एक उद्धरण\""`, `"\u0abe"`, `"नयी पंक्ति|\n"`
+* अंक(Numbers): `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4`
+* ऑब्जेक्ट्स(Objects): `{ "की": "मूल्य" }`
+* ऐरे(Arrays): `["बहुत सारे मूल्य"]`
+* विविध(Miscellaneous): `true`, `false`, `null`
+
+```json
+{
+ "की": "मूल्य",
+
+ "की": "हमेशा दोहरे उद्धरण चिह्नों में संलग्न होना चाहिए",
+ "अंक": 0,
+ "स्ट्रिंग्स": "नमस्ते| यूनिकोड और \"एस्केप\" सीक्वेंस की अनुमति है|",
+ "बूलियन है?": true,
+ "शून्यता ": null,
+
+ "बड़े अंक": 1.2e+100,
+
+ "ऑब्जेक्ट्स": {
+ "टिप्पणी": "आपके जैसन(JSON) ऑब्जेक्ट को ज़्यादातर ऑब्जेक्ट से ही ढांचा मिलेगा|",
+
+ "ऐरे": [0, 1, 2, 3, "ऐरे में आप कुछ भी रख सकते हैं|", 5],
+
+ "एक और ऑब्जेक्ट": {
+ "टिप्पणी": "आप एक ऑब्जेक्ट दूसरे ऑब्जेक्ट के अंदर रख सकते हैं| ये बहुत उपयोगी होता है|"
+ }
+ },
+
+ "फ़र्ज़ी": [
+ {
+ "पोटेशियम के स्रोत": ["केला"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "नव"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "वैकल्पिक शैली": {
+ "टिप्पणी": "ये देखिये!"
+ , "कॉमा के स्थान": "से फरक नहीं पड़ता, अगर आपने उसे अगली की से पहले लगाया है तो वो मान्य है|"
+ , "एक और टिप्पणी": "कितनी अच्छी बात है"
+ },
+
+
+
+ "खाली स्थान": "से फरक नहीं पड़ता",
+
+
+
+ "ये काफी छोटा था :>": "और ख़तम| अब आपको जैसन(JSON) के बारे में सब कुछ पता है|"
+}
+```
+
+## और जानकारी के लिए
+
+* [JSON.org](https://json.org) पूरा जैसन(JSON) फ्लोचार्ट के माध्यम से खूबसूरत तरह से दर्शित|
+* [JSON Tutorial](https://www.youtube.com/watch?v=wI1CWzNtE-M) जैसन(JSON) का एक संक्षिप्त परिचय|
diff --git a/hdl.html.markdown b/hdl.html.markdown
index cad07817..3c3aff66 100644
--- a/hdl.html.markdown
+++ b/hdl.html.markdown
@@ -123,7 +123,7 @@ CHIP And {
PARTS:
// Insert I and K into the nand gate and store the output in an internal
// wire called notOut.
- Nand(a=i,b=b,out=notOut);
+ Nand(a=i,b=k,out=notOut);
// Use the not gate we constructed to invert notOut and send to the AND
// output.
@@ -228,4 +228,4 @@ Good luck and happy coding!
* [Hardware Description Language](https://en.wikipedia.org/wiki/Hardware_description_language)
-* [HDL Programming Fundamentals](https://www.electronicdesign.com/products/hdl-programming-fundamentals) \ No newline at end of file
+* [HDL Programming Fundamentals](https://www.electronicdesign.com/products/hdl-programming-fundamentals)
diff --git a/html.html.markdown b/html.html.markdown
index b8212776..e9226a61 100644
--- a/html.html.markdown
+++ b/html.html.markdown
@@ -8,11 +8,11 @@ translators:
- ["Dimitri Kokkonis", "https://github.com/kokkonisd"]
---
-HTML stands for HyperText Markup Language.
+HTML stands for Hypertext Markup Language.
-It is a language which allows us to write pages for the world wide web.
+It is a language which allows us to write pages for the World Wide Web.
It is a markup language, it enables us to write webpages using code to indicate
-how text and data should be displayed. In fact, html files are simple text
+how text and data should be displayed. In fact, HTML files are simple text
files.
What is this markup? It is a method of organising the page's data by
@@ -171,6 +171,6 @@ HTML is written in files ending with `.html` or `.htm`. The mime type is
**HTML is NOT a programming language**
## To Learn More
-* [wikipedia](https://en.wikipedia.org/wiki/HTML)
-* [HTML tutorial](https://developer.mozilla.org/en-US/docs/Web/HTML)
-* [W3School](http://www.w3schools.com/html/html_intro.asp)
+* [Wikipedia](https://en.wikipedia.org/wiki/HTML)
+* [HTML Tutorial](https://developer.mozilla.org/en-US/docs/Web/HTML)
+* [W3Schools](http://www.w3schools.com/html/html_intro.asp)
diff --git a/id-id/ruby-id.html.markdown b/id-id/ruby-id.html.markdown
index 28135da1..a94aefb2 100644
--- a/id-id/ruby-id.html.markdown
+++ b/id-id/ruby-id.html.markdown
@@ -619,4 +619,4 @@ Sesuatu.new.qux # => 'qux'
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Edisi lama yang [gratis](http://ruby-doc.com/docs/ProgrammingRuby/) tersedia online.
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Panduan penulisan kode Ruby oleh komunitas.
-- [Try Ruby](http://tryruby.org) - Pelajari dasar bahasa pemrograman Ruby, secara interaktif di browser.
+- [Try Ruby](https://try.ruby-lang.org/) - Pelajari dasar bahasa pemrograman Ruby, secara interaktif di browser.
diff --git a/images/solidity/copy-address.png b/images/solidity/copy-address.png
new file mode 100644
index 00000000..b0a698ee
--- /dev/null
+++ b/images/solidity/copy-address.png
Binary files differ
diff --git a/images/solidity/metamask-kovan.png b/images/solidity/metamask-kovan.png
new file mode 100644
index 00000000..c5d5ae4b
--- /dev/null
+++ b/images/solidity/metamask-kovan.png
Binary files differ
diff --git a/images/solidity/remix-add-token.png b/images/solidity/remix-add-token.png
new file mode 100644
index 00000000..a1c2f1ac
--- /dev/null
+++ b/images/solidity/remix-add-token.png
Binary files differ
diff --git a/images/solidity/remix-choose-file.png b/images/solidity/remix-choose-file.png
new file mode 100644
index 00000000..6a16afc8
--- /dev/null
+++ b/images/solidity/remix-choose-file.png
Binary files differ
diff --git a/images/solidity/remix-compile.png b/images/solidity/remix-compile.png
new file mode 100644
index 00000000..7afd0d7c
--- /dev/null
+++ b/images/solidity/remix-compile.png
Binary files differ
diff --git a/images/solidity/remix-deploy.png b/images/solidity/remix-deploy.png
new file mode 100644
index 00000000..7f855f48
--- /dev/null
+++ b/images/solidity/remix-deploy.png
Binary files differ
diff --git a/images/solidity/remix-interact.png b/images/solidity/remix-interact.png
new file mode 100644
index 00000000..79f89ae9
--- /dev/null
+++ b/images/solidity/remix-interact.png
Binary files differ
diff --git a/images/solidity/remix-solidity.png b/images/solidity/remix-solidity.png
new file mode 100644
index 00000000..f4500967
--- /dev/null
+++ b/images/solidity/remix-solidity.png
Binary files differ
diff --git a/images/solidity/remix-testnet.png b/images/solidity/remix-testnet.png
new file mode 100644
index 00000000..6cc845ea
--- /dev/null
+++ b/images/solidity/remix-testnet.png
Binary files differ
diff --git a/images/solidity/send-link.png b/images/solidity/send-link.png
new file mode 100644
index 00000000..1cd9188e
--- /dev/null
+++ b/images/solidity/send-link.png
Binary files differ
diff --git a/it-it/bash-it.html.markdown b/it-it/bash-it.html.markdown
index cfe58f30..dd55b84c 100644
--- a/it-it/bash-it.html.markdown
+++ b/it-it/bash-it.html.markdown
@@ -22,7 +22,7 @@ translators:
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.
+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 macOS.
Quasi tutti gli esempi sottostanti possono fare parte di uno shell script o eseguiti direttamente nella shell.
[Per saperne di più.](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/it-it/ruby-it.html.markdown b/it-it/ruby-it.html.markdown
index 295bf28a..1f466cce 100644
--- a/it-it/ruby-it.html.markdown
+++ b/it-it/ruby-it.html.markdown
@@ -650,4 +650,4 @@ Something.new.qux #=> 'qux'
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Una passata [edizione libera](http://ruby-doc.com/docs/ProgrammingRuby/) è disponibile online.
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
-- [Try Ruby](http://tryruby.org) - Imparare le basi del linguaggio di programmazion Ruby, interattivamente nel browser.
+- [Try Ruby](https://try.ruby-lang.org/) - Imparare le basi del linguaggio di programmazion Ruby, interattivamente nel browser.
diff --git a/it-it/rust-it.html.markdown b/it-it/rust-it.html.markdown
index e4b7c33f..df4d6279 100644
--- a/it-it/rust-it.html.markdown
+++ b/it-it/rust-it.html.markdown
@@ -229,7 +229,7 @@ fn main() {
// Ciclo/iterazione con `for`
let array = [1, 2, 3];
- for i in array.iter() {
+ for i in array {
println!("{}", i);
}
diff --git a/ja-jp/vim-jp.html.markdown b/ja-jp/vim-jp.html.markdown
new file mode 100644
index 00000000..1d9867ca
--- /dev/null
+++ b/ja-jp/vim-jp.html.markdown
@@ -0,0 +1,275 @@
+---
+category: tool
+tool: vim
+contributors:
+ - ["RadhikaG", "https://github.com/RadhikaG"]
+translators:
+ - ["Kota Kato", "https://github.com/kato-k"]
+filename: LearnVim-jp.txt
+lang: ja-jp
+---
+
+
+[Vim](http://www.vim.org)
+(Vi IMproved) は、Unix用の人気なエディタである vi のクローンです。
+これは、速度と生産性を高めることを目的に設計されたエディタであり、
+ほとんどのUnix互換のシステムに組込まれています。
+ファイル内の特定の位置に移動したり、素早く編集したりするための多数のキーバインドを持ちます。
+
+`vimtutor`はあなたに`Vim`の使い方を教える素晴しいアプリケーションです。
+Vimパッケージのインストール時に一緒に付属しますので、
+コマンドラインで「vimtutor」を実行するだけで、このチュートリアルを開けるはずです。
+これは、`vim`の全ての主要機能を説明します。
+
+訳注) 日本語で`vimtutor`を利用するには、「vimtutor ja」を実行しなければならない場合があります。
+
+## 基本のVim操作
+
+```
+ vim <filename> # <filename>をVimで開く
+ :help <topic> # <topic>についての組み込みドキュメントが存在する場合、
+ # それを開く
+ :q # Vimを終了する
+ :w # 編集中のファイルを保存する
+ :wq # ファイルを保存して、Vimを終了する
+ ZZ # ファイルを保存して、Vimを終了する。:xと同様
+ :q! # ファイルを保存せずにVimを終了する
+ # :q を ! *強制的に* 実行するため保存せずにVimが終了します
+ ZQ # ファイルを保存せずにVimを終了する
+ :x # 変更点がある時、ファイルを保存してVimを終了する
+
+ u # Undo
+ CTRL+R # Redo
+
+ h # 左に一文字移動
+ j # 一行下に移動
+ k # 一行上に移動
+ l # 右に一文字移動
+
+ Ctrl+B # ウィンドウを一画面上に移動
+ Ctrl+F # ウィンドウを一画面下に移動
+ Ctrl+D # ウィンドウを半画面上に移動
+ Ctrl+U # ウィンドウを半画面下に移動
+
+ # 行内を移動する
+
+ 0 # 行頭に移動
+ $ # 行末に移動
+ ^ # 行の初めの非空白文字に移動
+
+ # テキストの検索
+
+ /word # カーソル以降に出現する全ての一致をハイライト
+ ?word # カーソル以前に出現する全ての一致をハイライト
+ n # カーソルを次の一致に移動
+ N # カーソルを前の一致に移動
+
+ :%s/foo/bar/g # 全ての行について「foo」を「bar」に置換
+ :s/foo/bar/g # 現在の行について「foo」を「bar」に置換
+ :%s/\n/\r/g # 改行文字の置換
+
+ # 文字への移動
+
+ f<character> # 前方の<character>に移動する
+ t<character> # 前方の<character>の一文字前に移動する
+
+ # 例
+ f< # 前方の < に移動
+ t< # 前方の < の一文字前に移動
+
+ # 単語ごとの移動
+
+ w # 一単語前に移動
+ b # 一単語後ろに移動
+ e # 現在の単語の後部に移動
+
+ # 移動のためのキーバインド
+
+ gg # ファイルの先頭に移動
+ G # ファイルの最後に移動
+ :NUM # ファイルのNUM行に移動(NUMは任意の行数)
+ H # カーソルをウィンドウ上部に移動
+ M # カーソルをウィンドウ中央に移動
+ L # カーソルをウィンドウ下部に移動
+```
+
+## ヘルプドキュメント:
+
+Vimには`:help <topic>`でアクセスできるヘルプドキュメントが組込まれています。
+例えば、`:help navigation`はカーソルを移動する方法についてのドキュメントを開きます。
+
+`:help`はオプション無しでも利用できます。
+これにより、Vimにより親しみやすくすることを目的としたデフォルトのヘルプダイアログが開かれます。
+
+## モード:
+
+Vimは**モード**の概念に基づいています。
+
+- Command Mode - Vimはこのモードで起動し、移動とコマンドの実行に使われます
+- Insert Mode - ファイルに変更を加えるのに使われます
+- Visual Mode - テキストをハイライトしてオペレータを適用するために使われます
+- Ex Mode - コマンドを入力するための「:」プロンプトで使われます
+
+```
+ i # カーソル位置の前からInsert Modeに入る
+ a # カーソル位置の後ろからInsert Modeに入る
+ v # Visual Modeに入る
+ : # Ex Modeに入る
+ <esc> # 現在のモードからコマンドモードに「脱出」
+
+ # テキストのコピーと貼り付け
+
+ y # 選択された対象をヤンクする
+ yy # 現在の行をヤンクする
+ d # 選択された対象を削除する
+ dd # 現在の行を削除する
+ p # ヤンクされたテキストをカーソルの後ろに貼り付ける
+ P # ヤンクされたテキストをのカーソルの前に貼り付ける
+ x # カーソル位置の文字を削除
+```
+
+## Vimの「文法」
+
+Vimの操作は「動詞・修飾子・名詞」形式のコマンドとして考えることができます。
+
+- 動詞 - 動作
+- 修飾子 - 動作の実行方法
+- 名詞 - 動作が作用するオブジェクト
+
+「動詞・修飾子・名詞」関するいくつかの重要な例:
+
+```
+ # '動詞'
+
+ d # 削除
+ c # 変更
+ y # ヤンク (コピー)
+ v # ビジュアル選択
+
+ # '修飾子'
+
+ i # 内部
+ a # 周り
+ NUM # 回数 (NUMは任意の番号)
+ f # 任意の一文字まで
+ t # 任意の一文字の手前まで
+ / # カーソル以降の任意の文字列まで
+ ? # カーソル以前の任意の文字列まで
+
+ # '名詞'
+
+ w # 単語
+ s # 文
+ p # 段落
+ b # ブロック
+
+ # 「文」の例
+
+ d2w # 削除 2 単語 (2単語を削除)
+ cis # 変更 内部 文 (文の内部を変更)
+ yip # ヤンク 内部 段落 (段落の内部をヤンク)
+ ct< # 変更 手前 < (<の手前まで変更)
+ d$ # 削除 行末まで (行末まで削除)
+```
+
+## いくつかのショートカットと小技
+
+ <!--TODO: Add more!-->
+```
+ > # 選択部を1ブロックインデント
+ < # 選択部を1ブロックデインデント
+ :earlier 15m # ファイルを15分前の状態に戻す
+ :later 15m # 上記のコマンドの逆
+ ddp # 連続する行を入れ替え
+ . # 前回の動作を繰り返す
+ :w !sudo tee % # 編集中のファイルを管理者として保存
+ :set syntax=c # 「C言語」のシンタックスハイライトを利用する
+ :sort # 全ての行をソートする
+ :sort! # 全ての行を降順にソートする
+ :sort u # 全ての行をソートして重複を削除する
+ ~ # 選択部分の大文字小文字を入れ替える
+ u # 選択部分を小文字にする
+ U # 選択部分を大文字にする
+ J # 現在の行と次の行を結合する
+
+ # テキストの折り畳み
+ zf # 選択したテキストを折り畳む
+ zo # 折り畳みを開く
+ zc # 折り畳みを閉じる
+ zR # 全ての折り畳みを開く
+ zM # 全ての折り畳みを閉じる
+```
+
+## マクロ
+
+マクロは基本的に記録可能なアクションです。
+マクロの記録を開始すると、記録を停止するまで**全て**の操作とコマンドが記録されます。
+マクロを呼びだすと、まったく同じ一連の操作とコマンドが文書に再度適用されます。
+
+```
+ qa # 「a」という名前のマクロの記録を開始する
+ q # 記録を停止する
+ @a # 「a」マクロを再生する
+```
+
+### ~/.vimrc の設定
+
+ファイル.vimrcは起動時にVimの設定として利用されます
+
+次は~/.vimrcファイルのサンプルです
+
+```
+" Example ~/.vimrc
+" 2015.10
+
+" Required for vim to be iMproved
+set nocompatible
+
+" 自動インデントなどを利用するために、ファイル名からファイルタイプを決定する
+filetype indent plugin on
+
+" シンタックスハイライトを利用する
+syntax on
+
+" より良いコマンドライン補完
+set wildmenu
+
+" 大文字を利用しない場合、検索で大文字・小文字を区別しない
+set ignorecase
+set smartcase
+
+" ファイル固有のインデントが有効でない場合、現在行のインデントを継続する
+set autoindent
+
+" 行番号の表示
+set number
+
+" インデントに関するオプション
+
+" TAB文字の幅
+set tabstop=4
+
+" 編集中TABキーを押した際の挙動
+set softtabstop=4
+
+" << >> を利用した再インデント時のスペースの数
+set shiftwidth=4
+
+" TABキーをスペースに変換する
+set expandtab
+
+" 賢いTAB機能を有効にする
+set smarttab
+```
+
+### 参考文献
+
+[Vim | Home](http://www.vim.org/index.php)
+
+`$ vimtutor`
+
+[A vim Tutorial and Primer](https://danielmiessler.com/study/vim/)
+
+[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about)
+
+[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim)
diff --git a/janet.html.markdown b/janet.html.markdown
index ec53b018..7b2912c2 100644
--- a/janet.html.markdown
+++ b/janet.html.markdown
@@ -18,7 +18,7 @@ As we only have a scant *y* minutes, we'll survey the basics here and
leave the remaining details for the manual. So please, keep your arms and
legs inside the vehicle at all times, and on with the scenic tour!
-```janet
+```python
# A comment.
# Some literal values.
diff --git a/java.html.markdown b/java.html.markdown
index 79769352..4be940be 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -510,10 +510,12 @@ public class LearnJava {
// toString returns this Object's string representation.
System.out.println("trek info: " + trek.toString());
+ } // End main method
+ private static class TestInitialization {
// Double Brace Initialization
- // The Java Language has no syntax for how to create static Collections
- // in an easy way. Usually you end up in the following way:
+ // Before Java 11, the Java Language had no syntax for how to create
+ // static Collections in an easy way. Usually you end up like this:
private static final Set<String> COUNTRIES = new HashSet<String>();
static {
COUNTRIES.add("DENMARK");
@@ -521,10 +523,10 @@ public class LearnJava {
COUNTRIES.add("FINLAND");
}
- // But there's a nifty way to achieve the same thing in an
- // easier way, by using something that is called Double Brace
- // Initialization.
- private static final Set<String> COUNTRIES = new HashSet<String>() {{
+ // There's a nifty way to achieve the same thing,
+ // by using something that is called Double Brace Initialization.
+ private static final Set<String> COUNTRIES_DOUBLE_BRACE =
+ new HashSet<String>() {{
add("DENMARK");
add("SWEDEN");
add("FINLAND");
@@ -535,8 +537,45 @@ public class LearnJava {
// is called when the anonymous inner class is created.
// This does not only work for Collections, it works for all
// non-final classes.
+
+
+ // Another option was to initialize the Collection from an array,
+ // using Arrays.asList() method:
+ private static final List<String> COUNTRIES_AS_LIST =
+ Arrays.asList("SWEDEN", "DENMARK", "NORWAY");
+ // This has one catch: the list we get is internally backed by the array,
+ // and since arrays can't change their size, the list backed by the array
+ // is not resizeable, which means we can't add new elements to it:
+ public static void main(String[] args) {
+ COUNTRIES.add("FINLAND"); // throws UnsupportedOperationException!
+ // However, we can replace elements by index, just like in array:
+ COUNTRIES.set(1, "FINLAND");
+ System.out.println(COUNTRIES); // prints [SWEDEN, FINLAND, NORWAY]
+ }
+ // The resizing problem can be circumvented
+ // by creating another Collection from the List:
+ private static final Set<String> COUNTRIES_SET =
+ new HashSet<>(Arrays.asList("SWEDEN", "DENMARK", "NORWAY"));
+ // It's perfectly fine to add anything to the Set of COUNTRIES now.
+ } // End TestInitialization class
+
+ private static class TestJava11Initialization {
+ // Since Java 11, there is a convenient option to initialize Collections:
+ // Set.of() and List.of() methods.
+ private static final Set<String> COUNTRIES =
+ Set.of("SWEDEN", "DENMARK", "NORWAY");
+ // There is a massive catch, though: Lists and Sets initialized like this
+ // 1) are immutable
+ // 2) can't contain null elements (even check for null elements fails)!
+ public static void main(String[] args) {
+ COUNTRIES.add("FINLAND"); // throws UnsupportedOperationException
+ COUNTRIES.remove("NORWAY"); // throws UnsupportedOperationException
+ COUNTRIES.contains(null); // throws NullPointerException
+ }
+ private static final Set<String> COUNTRIES_WITH_NULL =
+ Set.of("SWEDEN", null, "NORWAY"); // throws NullPointerException
- } // End main method
+ } // End TestJava11Initialization class
} // End LearnJava class
// You can include other, non-public outer-level classes in a .java file,
diff --git a/javascript.html.markdown b/javascript.html.markdown
index 3c0e6d4f..b290b553 100644
--- a/javascript.html.markdown
+++ b/javascript.html.markdown
@@ -590,7 +590,7 @@ if (Object.create === undefined){ // don't overwrite it if it exists
// ES6 Additions
// The "let" keyword allows you to define variables in a lexical scope,
-// as opposed to a block scope like the var keyword does.
+// as opposed to a function scope like the var keyword does.
let name = "Billy";
// Variables defined with let can be reassigned new values.
diff --git a/jsonnet.html.markdown b/jsonnet.html.markdown
index 9fe4edbe..241caf5f 100644
--- a/jsonnet.html.markdown
+++ b/jsonnet.html.markdown
@@ -124,7 +124,7 @@ local obj5 = {
};
assert obj5 == {};
-# a jsonnet doucment have to evaluate to something
+# a jsonnet document has to evaluate to something
# be it an object, list, number or just string literal
"FIN"
diff --git a/julia.html.markdown b/julia.html.markdown
index 5e9ef1b8..4d8eb497 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -11,7 +11,7 @@ Julia is a new homoiconic functional language focused on technical computing.
While having the full power of homoiconic macros, first-class functions,
and low-level control, Julia is as easy to learn and use as Python.
-This is based on Julia 1.0.0
+This is based on Julia version 1.0.0.
```julia
# Single line comments start with a hash (pound) symbol.
@@ -83,7 +83,7 @@ false
1 > 10 # => false
2 <= 2 # => true
2 >= 2 # => true
-# Comparisons can be chained
+# Comparisons can be chained, like in Python but unlike many other languages
1 < 2 < 3 # => true
2 < 3 < 2 # => false
@@ -93,28 +93,29 @@ false
# Character literals are written with '
'a'
-# Strings are UTF8 encoded. Only if they contain only ASCII characters can
-# they be safely indexed.
-ascii("This is a string")[1]
+# Strings are UTF8 encoded, so strings like "π" or "☃" are not directly equivalent
+# to an array of single characters.
+# Only if they contain only ASCII characters can they be safely indexed.
+ascii("This is a string")[1] # => 'T'
# => 'T': ASCII/Unicode U+0054 (category Lu: Letter, uppercase)
-# Julia indexes from 1
+# Beware, Julia indexes everything from 1 (like MATLAB), not 0 (like most languages).
# Otherwise, iterating over strings is recommended (map, for loops, etc).
-# String can be compared lexicographically
-"good" > "bye" # => true
+# String can be compared lexicographically, in dictionnary order:
+"good" > "bye" # => true
"good" == "good" # => true
"1 + 2 = 3" == "1 + 2 = $(1 + 2)" # => true
-# $ can be used for string interpolation:
+# $(..) can be used for string interpolation:
"2 + 2 = $(2 + 2)" # => "2 + 2 = 4"
# You can put any Julia expression inside the parentheses.
# Printing is easy
-println("I'm Julia. Nice to meet you!") # => I'm Julia. Nice to meet you!
+println("I'm Julia. Nice to meet you!") # => I'm Julia. Nice to meet you!
# Another way to format strings is the printf macro from the stdlib Printf.
-using Printf
-@printf "%d is less than %f\n" 4.5 5.3 # => 5 is less than 5.300000
+using Printf # this is how you load (or import) a module
+@printf "%d is less than %f\n" 4.5 5.3 # => 5 is less than 5.300000
####################################################
@@ -123,7 +124,7 @@ using Printf
# You don't declare variables before assigning to them.
someVar = 5 # => 5
-someVar # => 5
+someVar # => 5
# Accessing a previously unassigned variable is an error
try
@@ -137,9 +138,10 @@ end
SomeOtherVar123! = 6 # => 6
# You can also use certain unicode characters
+# here ☃ is a Unicode 'snowman' characters, see http://emojipedia.org/%E2%98%83%EF%B8%8F if it displays wrongly here
☃ = 8 # => 8
-# These are especially handy for mathematical notation
-2 * π # => 6.283185307179586
+# These are especially handy for mathematical notation, like the constant π
+2 * π # => 6.283185307179586
# A note on naming conventions in Julia:
#
@@ -171,7 +173,7 @@ matrix = [1 2; 3 4] # => 2×2 Array{Int64,2}: [1 2; 3 4]
b = Int8[4, 5, 6] # => 3-element Array{Int8,1}: [4, 5, 6]
# Add stuff to the end of a list with push! and append!
-# By convention, the exclamation mark '!'' is appended to names of functions
+# By convention, the exclamation mark '!' is appended to names of functions
# that modify their arguments
push!(a, 1) # => [1]
push!(a, 2) # => [1,2]
@@ -202,10 +204,10 @@ a # => [7,2,4,3,4,5,6]
# Function names that end in exclamations points indicate that they modify
# their argument.
arr = [5,4,6] # => 3-element Array{Int64,1}: [5,4,6]
-sort(arr) # => [4,5,6]
-arr # => [5,4,6]
-sort!(arr) # => [4,5,6]
-arr # => [4,5,6]
+sort(arr) # => [4,5,6]
+arr # => [5,4,6]
+sort!(arr) # => [4,5,6]
+arr # => [4,5,6]
# Looking out of bounds is a BoundsError
try
@@ -238,7 +240,7 @@ a = [1:5;] # => 5-element Array{Int64,1}: [1,2,3,4,5]
a2 = [1:5] # => 1-element Array{UnitRange{Int64},1}: [1:5]
# You can look at ranges with slice syntax.
-a[1:3] # => [1, 2, 3]
+a[1:3] # => [1, 2, 3]
a[2:end] # => [2, 3, 4, 5]
# Remove elements from an array by index with splice!
@@ -276,15 +278,15 @@ in(2, tup) # => true
# You can unpack tuples into variables
a, b, c = (1, 2, 3) # => (1,2,3)
-a # => 1
-b # => 2
-c # => 3
+a # => 1
+b # => 2
+c # => 3
# Tuples are created even if you leave out the parentheses
d, e, f = 4, 5, 6 # => (4,5,6)
-d # => 4
-e # => 5
-f # => 6
+d # => 4
+e # => 5
+f # => 6
# A 1-element tuple is distinct from the value it contains
(1,) == 1 # => false
@@ -292,8 +294,8 @@ f # => 6
# Look how easy it is to swap two values
e, d = d, e # => (5,4)
-d # => 5
-e # => 4
+d # => 5
+e # => 4
# Dictionaries store mappings
emptyDict = Dict() # => Dict{Any,Any} with 0 entries
@@ -375,7 +377,8 @@ end
# 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
+ # You can use $ to interpolate variables or expression into strings.
+ # In this special case, no need for parenthesis: $animal and $(animal) give the same
end
# => dog is a mammal
# => cat is a mammal
@@ -408,7 +411,7 @@ end
let x = 0
while x < 4
println(x)
- x += 1 # Shorthand for x = x + 1
+ x += 1 # Shorthand for in place increment: x = x + 1
end
end
# => 0
diff --git a/ko-kr/yaml-kr.html.markdown b/ko-kr/yaml-kr.html.markdown
index 4b1b29d2..c275c47f 100644
--- a/ko-kr/yaml-kr.html.markdown
+++ b/ko-kr/yaml-kr.html.markdown
@@ -2,19 +2,22 @@
language: yaml
filename: learnyaml-kr.yaml
contributors:
- - ["Leigh Brenecki", "https://github.com/adambrenecki"]
- - ["Suhas SG", "https://github.com/jargnar"]
+- ["Leigh Brenecki", "https://github.com/adambrenecki"]
+- ["Suhas SG", "https://github.com/jargnar"]
translators:
- - ["Wooseop Kim", "https://github.com/linterpreteur"]
+- ["Wooseop Kim", "https://github.com/linterpreteur"]
+- ["Justin Yang", "https://github.com/justin-themedium"]
lang: ko-kr
---
YAML은 인간이 직접 쓰고 읽을 수 있도록 설계된 데이터 직렬화 언어입니다.
YAML은 마치 파이썬처럼 개행과 들여쓰기에 문법적으로 의미를 준 JSON의 엄격한 수퍼셋입니다.
-하지만 파이썬과는 달리 YAML은 탭 문자를 전혀 허용하지 않습니다.
+하지만 파이썬과는 달리 YAML은 탭 문자를 들여쓰기에 사용하지 않습니다.
```yaml
+--- # 문서 시작
+
# YAML의 주석은 이런 식입니다.
############
@@ -22,19 +25,23 @@ YAML은 마치 파이썬처럼 개행과 들여쓰기에 문법적으로 의미
############
# 문서 내내 이어질 루트 객체는 맵입니다.
-# 맵은 다른 언어의 딕셔너리, 해시, 혹은 객체에 해당됩니다.
+# 맵은 다른 언어의 딕셔너리, 해시, 혹은 객체에 해당합니다.
키: 값
다른_키: 다른 값이 여기 옵니다.
숫자_값: 100
-# 숫자 1을 값으로 가지기 위해서는 따옴표에 담아야 합니다.
-# 그러지 않는다면 YAML 파서는 그것을 참 값을 가지는 불리언으로 해석할 것입니다.
과학적_표기법: 1e+12
+# 숫자 1은 불리언이 아닌 값으로 처리됩니다. 불리언으로 처리하고 싶다면
+# true를 사용하세요.
불리언: true
널_값: null
띄어서 쓴 키: 값
# 문자열에 따옴표를 칠 필요는 없습니다. 하지만 칠 수도 있습니다.
-하지만: "따옴표에 담은 문자열"
-"키도 따옴표에 담을 수 있습니다.": "키에 ':'을 넣고 싶다면 유용합니다."
+하지만: '따옴표에 담은 문자열'
+'키도 따옴표에 담을 수 있습니다.': "키에 ':'을 넣고 싶다면 유용합니다."
+작은 따옴표: '는 ''하나''의 이스케이프 패턴을 갖습니다'
+큰 따옴표: "는 많이 갖습니다. \", \0, \t, \u263A, \x0d\x0a == \r\n, 그리고 더."
+# UTF-8/16/32 문자는 인코딩되어야 합니다.
+첨자 2: \u00B2
# 여러 줄의 문자열은 (|을 이용한) '리터럴 블락' 혹은 (>을 이용한) '접은 블락'으로
# 쓸 수 있습니다.
@@ -59,12 +66,12 @@ YAML은 마치 파이썬처럼 개행과 들여쓰기에 문법적으로 의미
# 모임 형 #
##########
-# 중첩은 들여쓰기로 가능합니다.
+# 중첩은 들여쓰기를 사용합니다. 2칸 띄어쓰기가 많이 쓰입니다(필수는 아닙니다).
중첩된_맵:
- 키: 값
- 다른_키: 다른 값
- 다른_중첩된_맵:
- 안녕: 안녕
+ 키: 값
+ 다른_키: 다른 값
+ 다른_중첩된_맵:
+ 안녕: 안녕
# 맵은 반드시 문자열 키를 가지는 것은 아닙니다.
0.25: 실수형 키
@@ -72,28 +79,31 @@ YAML은 마치 파이썬처럼 개행과 들여쓰기에 문법적으로 의미
# 키는 여러 줄에 걸친 객체와 같이 복합적일 수도 있습니다.
# ?와 그 뒤의 띄어쓰기로 복합 키의 시작을 나타냅니다.
? |
- 여러 줄짜리
- 키
+ 여러 줄짜리
+ 키
: 그리고 그 값
-# YAML은 복합 키 문법으로 연속열 간의 매핑을 지원합니다.
+# YAML은 복합 키 문법으로 연속열 간의 매핑도 지원합니다.
# 일부 파서는 지원하지 않을 수 있습니다.
# 예시
? - 맨체스터 유나이티드
- 레알 마드리드
-: [ 2001-01-01, 2002-02-02 ]
+: [2001-01-01, 2002-02-02]
# 리스트 혹은 배열에 대응되는 연속열은 다음과 같습니다.
+# (들여쓰기처럼 '-'를 세는 것에 주의하세요)
연속열:
- - 하나
- - 둘
- - 0.5 # 연속열은 다른 형을 포함 가능
- - 넷
- - 키: 값
- 다른_키: 다른_값
- -
- - 연속열 안의
- - 또 다른 연속열
+ - 하나
+ - 둘
+ - 0.5 # 연속열은 다른 형을 포함 가능
+ - 넷
+ - 키: 값
+ 다른_키: 다른_값
+ -
+ - 연속열 안의
+ - 또 다른 연속열
+ - - - 중첩된 연속열 지시자
+ - 접힘 가능
# YAML은 JSON의 수퍼셋이기 때문에, JSON식으로 맵과 연속열을 작성할 수도
# 있습니다.
@@ -111,17 +121,19 @@ YAML은 마치 파이썬처럼 개행과 들여쓰기에 문법적으로 의미
# 앵커는 속성을 복제하거나 상속할 수 있습니다.
기반: &기반
- 이름: 모두 이름이 같다
+ 이름: 모두 이름이 같다
-멍멍: &멍멍
- <<: *기반
- 나이: 10
+# 정규식 << 는 병합 키 언어-비종속 타입으로 불립니다. 이는 하나
+# 이상 지정된 맵의 모든 키가 현재 맵 안으로 삽입됨을 나타냅니다.
+멍멍:
+ <<: *기반
+ 나이: 10
-야옹: &야옹
- <<: *기반
- 나이: 20
+야옹:
+ <<: *기반
+ 나이: 20
-# 멍멍이와 야옹이는 같은 이름, '모두 이름이 같다'를 같습니다.
+# 멍멍이와 야옹이도 '이름: 모두 이름이 같다'를 갖습니다.
# 또한 YAML에는 명시적으로 형을 선언할 수 있는 태그가 있습니다.
명시적_문자열: !!str 0.5
@@ -138,8 +150,7 @@ YAML은 마치 파이썬처럼 개행과 들여쓰기에 문법적으로 의미
# 기타 YAML 형 #
###############
-# Strings and numbers aren't the only scalars that YAML can understand.
-# YAML이 이해할 수 있는 스칼라는 문자열과 수만 있는 것은 아닙니다.
+# YAML이 이해할 수 있는 스칼라가 문자열과 수만 있는 것은 아닙니다.
# ISO 형식 날짜와 시간 리터럴 또한 해석됩니다.
시간: 2001-12-15T02:59:43.1Z
띄어쓰기_한_시간: 2001-12-14 21:59:43.10 -5
@@ -148,25 +159,27 @@ YAML은 마치 파이썬처럼 개행과 들여쓰기에 문법적으로 의미
# !!binary 태그는 문자열이 실제로는 base64로 인코딩된
# 이진수 객체(BLOB)라는 것을 나타냅니다.
이미지_파일: !!binary |
- R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
- OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
- +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
- AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
+ R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
+ OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+ +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
+ AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
# YAML에는 다음과 같은 집합도 있습니다.
집합:
- ? 하나
- ? 둘
- ? 셋
+ ? 하나
+ ? 둘
+ ? 셋
-# 파이썬과 마찬가지로 집합은 단지 널 값을 갖는 맵입니다. 위는 다음과 같습니다.
+# 집합은 단지 널 값을 갖는 맵입니다. 위는 다음과 같습니다.
집합2:
- 하나: null
- 둘: null
- 셋: null
+ 하나: null
+ 둘: null
+ 셋: null
+
+... # 문서 끝
```
### 더 읽기
-+ [(영어) YAML 공식 사이트](http://yaml.org/)
-+ [(영어) 온라인 YAML 검사기](http://codebeautify.org/yaml-validator)
++ [(영어) YAML 공식 사이트](https://yaml.org/)
++ [(영어) 온라인 YAML 검사기](http://www.yamllint.com/)
diff --git a/kotlin.html.markdown b/kotlin.html.markdown
index 5bbf6847..12008074 100644
--- a/kotlin.html.markdown
+++ b/kotlin.html.markdown
@@ -180,7 +180,7 @@ fun helloWorld(val name : String) {
// destructuring in "for" loop
for ((a, b, c) in listOf(fooData)) {
- println("$a $b $c") // => 1 100 4
+ println("$a $b $c") // => 1 2 4
}
val mapData = mapOf("a" to 1, "b" to 2)
@@ -426,7 +426,7 @@ data class Counter(var value: Int) {
operator fun invoke() = println("The value of the counter is $value")
}
-/* You can also overload operators through an extension methods */
+/* You can also overload operators through extension methods */
// overload -Counter
operator fun Counter.unaryMinus() = Counter(-this.value)
diff --git a/lambda-calculus.html.markdown b/lambda-calculus.html.markdown
index 53a7a7cd..958dd746 100644
--- a/lambda-calculus.html.markdown
+++ b/lambda-calculus.html.markdown
@@ -131,7 +131,7 @@ We can convert an expression in the lambda calculus to an expression
in the SKI combinator calculus:
1. `λx.x = I`
-2. `λx.c = Kc`
+2. `λx.c = Kc` provided that `x` does not occur free in `c`
3. `λx.(y z) = S (λx.y) (λx.z)`
Take the church number 2 for example:
diff --git a/latex.html.markdown b/latex.html.markdown
index 49200968..34c4b78d 100644
--- a/latex.html.markdown
+++ b/latex.html.markdown
@@ -2,7 +2,7 @@
language: latex
contributors:
- ["Chaitanya Krishna Ande", "http://icymist.github.io"]
- - ["Colton Kohnke", "http://github.com/voltnor"]
+ - ["Colton Kohnke", "https://github.com/voltnor"]
- ["Sricharan Chiruvolu", "http://sricharan.xyz"]
- ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"]
- ["Svetlana Golubeva", "https://attillax.github.io/"]
@@ -95,8 +95,9 @@ to the source code.
Separate paragraphs by empty lines.
-You need to add a backslash after abbreviations (if not followed by a comma), because otherwise the spacing after the dot is too large:
-E.g., i.e., etc.\ are are such abbreviations.
+You need to add a tilde after abbreviations (if not followed by a comma) for a
+non-breaking space, because otherwise the spacing after the dot is too large:
+E.g., i.e., etc.~are are such abbreviations.
\section{Lists}
Lists are one of the easiest things to create in \LaTeX! I need to go shopping
@@ -140,8 +141,7 @@ about!
Operators are essential parts of a mathematical document:
trigonometric functions ($\sin$, $\cos$, $\tan$),
logarithms and exponentials ($\log$, $\exp$),
-limits ($\lim$), etc.\
-have pre-defined LaTeX commands.
+limits ($\lim$), etc.~have pre-defined LaTeX commands.
Let's write an equation to see how it's done:
$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$
@@ -181,7 +181,9 @@ Summations and Integrals are written with sum and int commands:
\section{Figures}
Let's insert a figure. Figure placement can get a little tricky.
+Basic options are [t] for top, [b] for bottom, [h] for here (approximately).
I definitely have to lookup the placement options each time.
+% See https://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions for more details
\begin{figure}[H] % H here denoted the placement option.
\centering % centers the figure on the page
@@ -198,16 +200,24 @@ 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 &
+ % The basics are simple: one letter for each column, to control alignment:
+ % basic options are: c, l, r and p for centered, left, right and paragraph
+ % optionally, you can add a | for a vertical line
+ % See https://en.wikibooks.org/wiki/LaTeX/Tables for more details
+ \begin{tabular}{c|cc} % here it means "centered | vertical line, centered centered"
+ Number & First Name & Last Name \\ % Column rows are separated by &
\hline % a horizontal line
1 & Biggus & Dickus \\
2 & Monty & Python
\end{tabular}
+ % it will approximately be displayed like this
+ % Number | First Name Last Name
+ % -------|--------------------------- % because of \hline
+ % 1 | Biggus Dickus
+ % 2 | Monty Python
\end{table}
-\section{Getting \LaTeX{} to not compile something (i.e.\ Source Code)}
+\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 with a verbatim
@@ -218,14 +228,15 @@ environment.
\begin{verbatim}
print("Hello World!")
a%b; % look! We can use % signs in verbatim.
- random = 4; #decided by fair random dice roll
+ random = 4; #decided by fair random dice roll, https://www.xkcd.com/221/
+ See https://www.explainxkcd.com/wiki/index.php/221:_Random_Number
\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).
+(Yes, this document actually does compile).
Getting to the final document using \LaTeX{} consists of the following
steps:
@@ -244,6 +255,7 @@ Step 2 is still happening behind the scenes\footnote{In cases, where you use
references (like Eqn.~\ref{eq:pythagoras}), you may need to run Step 2
multiple times, to generate an intermediary *.aux file.}.
% Also, this is how you add footnotes to your document!
+% with a simple \footnote{...} command. They are numbered ¹, ², ... by default.
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
@@ -262,9 +274,30 @@ There exists two main types of links: visible URL \\
% You can not add extra-spaces or special symbols into shadowing text since it
% will cause mistakes during the compilation
-This package also produces list of thumbnails in the output pdf document and
+This package also produces list of thumbnails in the output PDF document and
active links in the table of contents.
+\section{Writing in ASCII or other encodings}
+
+By default, historically LaTeX accepts inputs which are pure ASCII (128),
+but not extended ASCII, meaning without accents (à, è etc.) and non-Latin symbols.
+
+It is easy to insert accents and basic Latin symbols, with backslash shortcuts
+Like \,c, \'e, \`A, \ae and \oe etc. % for ç, é, À, etc
+% See https://en.wikibooks.org/wiki/LaTeX/Special_Characters#Escaped_codes for more
+
+To write directly in UTF-8, when compiling with pdflatex, use
+\begin{verbatim}
+ \usepackage[utf8]{inputenc}
+\end{verbatim}
+The selected font has to support the glyphs used for your document, you have to add
+\begin{verbatim}
+ \usepackage[T1]{fontenc}
+\end{verbatim}
+
+Since LuaTeX and XeLaTeX were designed with built-in support for UTF-8, making
+life easier for writing in non-Latin alphabets.
+
\section{End}
That's all for now!
@@ -284,6 +317,6 @@ That's all for now!
## More on LaTeX
-* The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX)
+* The amazing LaTeX Wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX)
* An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
* A quick guide for learning LaTeX: [Learn LaTeX in 30 minutes](https://www.overleaf.com/learn/latex/Learn_LaTeX_in_30_minutes)
diff --git a/lua.html.markdown b/lua.html.markdown
index 53e396be..ac7883b2 100644
--- a/lua.html.markdown
+++ b/lua.html.markdown
@@ -383,19 +383,26 @@ dofile('mod2.lua') --> Hi! (runs it again)
-- loadfile loads a lua file but doesn't run it yet.
f = loadfile('mod2.lua') -- Call f() to run it.
--- loadstring is loadfile for strings.
-g = loadstring('print(343)') -- Returns a function.
+-- load is loadfile for strings.
+-- (loadstring is deprecated, use load instead)
+g = load('print(343)') -- Returns a function.
g() -- Prints out 343; nothing printed before now.
--]]
```
+
+## Community
+
+If you need support join the official Lua [mailing list](https://www.lua.org/lua-l.html), [irc channel](http://lua-users.org/wiki/IrcChannel), or [forum](https://luaforum.com).
+
+
## References
I was excited to learn Lua so I could make games
with the <a href="http://love2d.org/">Love 2D game engine</a>. That's the why.
-I started with <a href="http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/">BlackBulletIV's Lua for programmers</a>.
+I started with <a href="https://ebens.me/post/lua-for-programmers-part-1/">BlackBulletIV's Lua for programmers</a>.
Next I read the official <a href="http://www.lua.org/pil/contents.html">Programming in Lua</a> book.
That's the how.
diff --git a/markdown.html.markdown b/markdown.html.markdown
index cf4286e2..60ca1323 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -3,12 +3,13 @@ language: markdown
contributors:
- ["Dan Turkel", "http://danturkel.com/"]
- ["Jacob Ward", "http://github.com/JacobCWard/"]
+ - ["Tomáš Hartman", "https://github.com/tomas-hartman"]
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
+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
@@ -17,16 +18,25 @@ specific to a certain parser.
- [HTML Elements](#html-elements)
- [Headings](#headings)
-- [Simple Text Styles](#simple-text-styles)
+- [Simple text styles](#simple-text-styles)
- [Paragraphs](#paragraphs)
- [Lists](#lists)
- [Code blocks](#code-blocks)
- [Horizontal rule](#horizontal-rule)
- [Links](#links)
+ - [Table of contents](#table-of-contents)
- [Images](#images)
- [Miscellany](#miscellany)
+ - [Auto-links](#auto-links)
+ - [Auto-links for emails](#auto-links-for-emails)
+ - [Escaping characters](#escaping-characters)
+ - [Keyboard keys](#keyboard-keys)
+ - [Tables](#tables)
+- [Markdownlint](#markdownlint)
+- [Further reading](#further-reading)
## HTML Elements
+
Markdown is a superset of HTML, so any HTML file is valid Markdown.
```md
@@ -49,6 +59,7 @@ text you want to be in that element by a number of hashes (#).
##### This is an <h5>
###### This is an <h6>
```
+
Markdown also provides us with two alternative ways of indicating h1 and h2.
```md
@@ -81,6 +92,7 @@ GitHub, we also have strikethrough:
```md
~~This text is rendered with strikethrough.~~
```
+
## Paragraphs
Paragraphs are a one or multiple adjacent lines of text separated by one or
@@ -119,6 +131,7 @@ Block quotes are easy and done with the > character.
```
## Lists
+
Unordered lists can be made using asterisks, pluses, or hyphens.
```md
@@ -155,6 +168,7 @@ render the numbers in order, but this may not be a good idea.
1. Item two
1. Item three
```
+
(This renders the same as the above example)
You can also use sublists
@@ -217,7 +231,7 @@ highlighting of the language you specify after the \`\`\`
## Horizontal rule
-Horizontal rules (`<hr/>`) are easily added with three or more asterisks or
+Horizontal rules (`<hr/>`) are easily added with three or more asterisks or
hyphens, with or without spaces.
```md
@@ -235,11 +249,13 @@ the text to display in hard brackets [] followed by the url in parentheses ()
```md
[Click me!](http://test.com/)
```
+
You can also add a link title using quotes inside the parentheses.
```md
[Click me!](http://test.com/ "Link to Test.com")
```
+
Relative paths work too.
```md
@@ -266,7 +282,27 @@ There is also "implicit naming" which lets you use the link text as the id.
But it's not that commonly used.
+### Table of contents
+
+Some Markdown flavors even make use of the combination of lists, links and
+headings in order to create tables of contents. In this case, heading titles in
+lowercase are prepended with hash (`#`) and are used as link ids. Should the
+heading have multiple words, they will be connected with a hyphen (`-`), that
+also replaces some special characters. (Some other special characters are
+omitted though.)
+
+```md
+- [Heading](#heading)
+- [Another heading](#another-heading)
+- [Chapter](#chapter)
+ - [Subchapter <h3 />](#subchapter-h3-)
+```
+
+Nontheless, this is a feature that might not be working in all Markdown
+implementations the same way.
+
## Images
+
Images are done the same way as links but with an exclamation point in front!
```md
@@ -278,7 +314,9 @@ And reference style works as expected.
<pre><code class="highlight">!&#x5b;<span class="nv">This is the alt-attribute.</span>][<span class="ss">myimage</span>]
&#x5b;<span class="nv">myimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"if you need a title, it's here"</span></code></pre>
+
## Miscellany
+
### Auto-links
```md
@@ -301,13 +339,14 @@ 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
+In GitHub Flavored Markdown, you can use a `<kbd>` tag to represent keyboard
keys.
```md
Your computer crashed? Try sending a
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
```
+
### Tables
Tables are only available in GitHub Flavored Markdown and are slightly
@@ -319,6 +358,7 @@ cumbersome, but if you really want it:
| Left-aligned | Centered | Right-aligned |
| blah | blah | blah |
```
+
or, for the same results
```md
@@ -327,5 +367,20 @@ Col 1 | Col2 | Col3
Ugh this is so ugly | make it | stop
```
+## Markdownlint
+
+In order to simplify work with Markdown and to unify its coding style,
+`Markdownlint` has been created. This tool is available also as a plugin for
+some IDEs and can be used as an utility to ensure validity and readability of
+Markdown.
+
---
+
+## Further reading
+
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).
+
+If you want to learn more on some major Markdown flavors' features, see:
+
+- [GitHub flavored Markdown](https://docs.github.com/en/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)
+- [GitLab flavored Markdown](https://docs.gitlab.com/ee/user/markdown.html)
diff --git a/matlab.html.markdown b/matlab.html.markdown
index 4ca31857..ecf2fc96 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -28,7 +28,7 @@ this
% Two percent signs denote the start of a new code section
% Individual code sections can be run by moving the cursor to the section followed by
% either clicking the "Run Section" button
-% or using Ctrl+Shift+Enter (Windows) or Cmd+Shift+Return (OS X)
+% or using Ctrl+Shift+Enter (Windows) or Cmd+Shift+Return (macOS)
%% This is the start of a code section
% One way of using sections is to separate expensive but unchanging start-up code like loading data
diff --git a/mips.html.markdown b/mips.html.markdown
index 33d4f87c..0e7a7d0c 100644
--- a/mips.html.markdown
+++ b/mips.html.markdown
@@ -193,7 +193,7 @@ gateways and routers.
# Let $s0 = a, $s1 = b, $s2 = c, $v0 = return register
ble $s0, $s1, a_LTE_b # if(a <= b) branch(a_LTE_b)
ble $s0, $s2, max_C # if(a > b && a <=c) branch(max_C)
- move $v0, $s1 # else [a > b && a > c] max = a
+ move $v0, $s0 # else [a > b && a > c] max = a
j done # Jump to the end of the program
a_LTE_b: # Label for when a <= b
@@ -242,7 +242,7 @@ gateways and routers.
## FUNCTIONS ##
_functions:
# Functions are callable procedures that can accept arguments and return
- values all denoted with labels, like above
+ # values all denoted with labels, like above
main: # Programs begin with main func
jal return_1 # jal will store the current PC in $ra
@@ -293,7 +293,7 @@ gateways and routers.
fact_done:
lw $s0, ($sp)
- lw $ra, ($sp) # Restore the PC
+ lw $ra, 4($sp) # Restore the PC
addi $sp, $sp, 8
jr $ra
@@ -357,7 +357,7 @@ gateways and routers.
li $t1, 5 # Length of the list
loop:
- bgt $t0, $t1, end_loop
+ bge $t0, $t1, end_loop
lw $a0, ($s0)
li $v0, 1
diff --git a/mongodb.html.markdown b/mongodb.html.markdown
new file mode 100644
index 00000000..959b57d0
--- /dev/null
+++ b/mongodb.html.markdown
@@ -0,0 +1,405 @@
+---
+language: MongoDB
+filename: mongo.js
+contributors:
+ - ["Raj Piskala", "https://www.rajpiskala.ml/"]
+---
+
+MongoDB is a NoSQL document database for high volume data storage.
+
+MongoDB uses collections and documents for its storage. Each document consists
+of key-value pairs using JSON-like syntax, similar to a dictionary or JavaScript
+object.
+
+Likewise, as MongoDB is a NoSQL database, it uses its own query language, Mongo
+Query Language (MQL) which uses JSON for querying.
+
+## Getting Started
+
+### Installation
+
+MongoDB can either be installed locally following the instructions
+[here](https://docs.mongodb.com/manual/installation/) or you can create a
+remotely-hosted free 512 MB cluster
+[here](https://www.mongodb.com/cloud/atlas/register). Links to videos with
+instructions on setup are at the bottom.
+
+This tutorial assumes that you have the MongoDB Shell from
+[here](https://www.mongodb.com/try/download/shell). You can also download the
+graphical tool, MongoDB Compass, down below from the same link.
+
+### Components
+
+After installing MongoDB, you will notice there are multiple command line tools.
+The three most important of which are:
+
+- `mongod` - The database server which is responsible for managing data and
+ handling queries
+- `mongos` - The sharding router, which is needed if data will be distributed
+ across multiple machines
+- `mongo` - The database shell (using JavaScript) through which we can configure
+ our database
+
+Usually we start the `mongod` process and then use a separate terminal with
+`mongo` to access and modify our collections.
+
+### JSON & BSON
+
+While queries in MongoDB are made using a JSON-like\* format, MongoDB stores its
+documents internally in the Binary JSON (BSON format). BSON is not human
+readable like JSON as it's a binary encoding. However, this allows for end users
+to have access to more types than regular JSON, such as an integer or float
+type. Many other types, such as regular expressions, dates, or raw binary are
+supported too.
+
+[Here](https://docs.mongodb.com/manual/reference/bson-types/) is the full list
+of all types that are supported.
+
+- We refer JSON-like to mean JSON but with these extended types. For example,
+ you can make queries directly with a regular expression or timestamp in
+ MongoDB and you can receive data that has those types too.
+
+```js
+/////////////////////////////////////////////////////////
+/////////////////// Getting Started /////////////////////
+/////////////////////////////////////////////////////////
+
+// Start up the mongo database server
+// NOTE - You will need to do this in a separate terminal as the process will
+// take over the terminal. You may want to use the --fork option
+mongod // --fork
+
+// Connecting to a remote Mongo server
+// mongo "mongodb+srv://host.ip.address/admin" --username your-username
+
+// Mongoshell has a proper JavaScript interpreter built in
+3 + 2 // 5
+
+// Show available databases
+// MongoDB comes with the following databases built-in: admin, config, local
+show dbs
+
+// Switch to a new database (pre-existing or about to exist)
+// NOTE: There is no "create" command for a database in MongoDB.
+// The database is created upon data being inserted into a collection
+use employees
+
+// Create a new collection
+// NOTE: Inserting a document will implicitly create a collection anyways,
+// so this is not required
+db.createCollection('engineers')
+db.createCollection('doctors')
+
+// See what collections exist under employees
+show collections
+
+/////////////////////////////////////////////////////////
+// Basic Create/Read/Update/Delete (CRUD) Operations: ///
+/////////////////////////////////////////////////////////
+
+/////////////// Insert (Create) /////////////////////////
+
+// Insert one employee into the database
+// Each insertion returns acknowledged true or false
+// Every document has a unique _id value assigned to it automatically
+db.engineers.insertOne({ name: "Jane Doe", age: 21, gender: 'Female' })
+
+// Insert a list of employees into the `engineers` collection
+// Can insert as an array of objects
+db.engineers.insert([
+ { name: "Foo Bar", age: 25, gender: 'Male' },
+ { name: "Baz Qux", age: 27, gender: 'Other' },
+])
+
+// MongoDB does not enforce a schema or structure for objects
+// Insert an empty object into the `engineers` collection
+db.engineers.insertOne({})
+
+// Fields are optional and do not have to match rest of documents
+db.engineers.insertOne({ name: "Your Name", gender: "Male" })
+
+// Types can vary and are preserved on insertion
+// This can require additional validation in some languages to prevent problems
+db.engineers.insert({ name: ['Foo', 'Bar'], age: 3.14, gender: true })
+
+// Objects or arrays can be nested inside a document
+db.engineers.insertOne({
+ name: "Your Name",
+ gender: "Female",
+ skilledIn: [
+ "MongoDB",
+ "NoSQL",
+ ],
+ "date-of-birth": {
+ "date": 1993-07-20T09:44:18.674Z,
+ "age": 26
+ },
+})
+
+// We can override the _id field
+// Works fine
+db.engineers.insertOne({
+ _id: 1,
+ name: "An Engineer",
+ age: 25,
+ gender: "Female",
+})
+
+// Be careful, as _id must ALWAYS be unique for the collection otherwise
+// the insertion will fail
+// Fails with a WriteError indicating _id is a duplicate value
+db.engineers.insertOne({
+ _id: 1,
+ name: "Another Engineer",
+ age: 25,
+ gender: "Male",
+})
+
+// Works fine as this is a different collection
+db.doctors.insertOne({
+ _id: 1,
+ name: "Some Doctor",
+ age: 26,
+ gender: "Other",
+})
+
+/////////////////// Find (Read) ////////////////////////
+// Queries are in the form of db.collectionName.find(<filter>)
+// Where <filter> is an object
+
+// Show everything in our database so far, limited to a
+// maximum of 20 documents at a time
+// Press i to iterate this cursor to the next 20 documents
+db.engineers.find({})
+
+// We can pretty print the result of any find() query
+db.engineers.find({}).pretty()
+
+// MongoDB queries take in a JS object and search for documents with matching
+// key-value pairs
+// Returns the first document matching query
+// NOTE: Order of insertion is not preserved in the database, output can vary
+db.engineers.findOne({ name: 'Foo Bar' })
+
+// Returns all documents with the matching key-value properties as a cursor
+// (which can be converted to an array)
+db.engineers.find({ age: 25 })
+
+// Type matters when it comes to queries
+// Returns nothing as all ages above are integer type
+db.engineers.find({ age: '25' })
+
+// find() supports nested objects and arrays just like create()
+db.engineers.find({
+ name: "Your Name",
+ gender: "Female",
+ skilledIn: [
+ "MongoDB",
+ "NoSQL",
+ ],
+ "date-of-birth": {
+ "date": 1993-07-20T09:44:18.674Z,
+ "age": 26
+ },
+})
+
+///////////////////////// Update ////////////////////////
+// Queries are in the form of db.collectionName.update(<filter>, <update>)
+// NOTE: <update> will always use the $set operator.
+// Several operators are covered later on in the tutorial.
+
+// We can update a single object
+db.engineers.updateOne({ name: 'Foo Bar' }, { $set: { name: 'John Doe', age: 100 }})
+
+// Or update many objects at the same time
+db.engineers.update({ age: 25 }, { $set: { age: 26 }})
+
+// We can use { upsert: true } if we would like it to insert if the document doesn't already exist,
+// or to update if it does
+// Returns matched, upserted, modified count
+db.engineers.update({ name: 'Foo Baz' },
+ { $set:
+ {
+ age: 26,
+ gender: 'Other'
+ }
+ },
+ { upsert: true }
+)
+
+/////////////////////// Delete /////////////////////////
+// Queries are in the form of db.collectionName.find(<filter>)
+
+// Delete first document matching query, always returns deletedCount
+db.engineers.deleteOne({ name: 'Foo Baz' })
+
+// Delete many documents at once
+db.engineers.deleteMany({ gender: 'Male' })
+
+// NOTE: There are two methods db.collection.removeOne(<filter>) and
+// db.collection.removeMany(<filter>) that also delete objects but have a
+// slightly different return value.
+// They are not included here as they have been deprecated in the NodeJS driver.
+
+/////////////////////////////////////////////////////////
+//////////////////// Operators //////////////////////////
+/////////////////////////////////////////////////////////
+
+// Operators in MongoDB have a $ prefix. For this tutorial, we are only looking
+// at comparison and logical operators, but there are many other types of
+// operators
+
+//////////////// Comparison Operators ///////////////////
+
+// Find all greater than or greater than equal to some condition
+db.engineers.find({ $gt: { age: 25 }})
+db.engineers.find({ $gte: { age: 25 }})
+
+// Find all less than or less than equal to some condition
+db.engineers.find({ $lte: { age: 25 }})
+db.engineers.find({ $lte: { age: 25 }})
+
+// Find all equal or not equal to
+// Note: the $eq operator is added implicitly in most queries
+db.engineers.find({ $eq: { age: 25 }})
+db.engineers.find({ $ne: { age: 25 }})
+
+// Find all that match any element in the array
+db.engineers.find({ age: ${ in: [ 20, 23, 24, 25 ]}})
+
+//////////////// Logical Operators ///////////////////
+
+// Join two query clauses together
+// NOTE: MongoDB does this implicitly for most queries
+db.engineers.find({ $and: [
+ gender: 'Female',
+ age: {
+ $gte: 18
+ }
+]})
+
+// Match either query condition
+db.engineers.find({ $or: [
+ gender: 'Female',
+ age: {
+ $gte: 18
+ }
+]})
+
+// Negates the query
+db.engineers.find({ $not: {
+ gender: 'Female'
+}})
+
+// Must match none of the query conditions
+db.engineers.find({ $nor [
+ gender: 'Female,
+ age: {
+ $gte: 18
+ }
+]})
+
+/////////////////////////////////////////////////////////
+//////////////// Database Operations: ///////////////////
+/////////////////////////////////////////////////////////
+
+// Delete (drop) the employees database
+// THIS WILL DELETE ALL DOCUMENTS IN THE DATABASE!
+db.dropDatabase()
+
+// Create a new database with some data
+use example
+db.test.insertOne({ name: "Testing data, please ignore!", type: "Test" })
+
+// Quit Mongo shell
+exit
+
+// Import/export database as BSON:
+
+// Mongodump to export data as BSON for all databases
+// Exported data is found in under "MongoDB Database Tools/bin/dump"
+// NOTE: If the command is not found, navigate to "MongoDB Database Tools/bin"
+// and use the executable from there mongodump
+
+// Mongorestore to restore data from BSON
+mongorestore dump
+
+// Import/export database as JSON:
+// Mongoexport to export data as JSON for all databases
+mongoexport --collection=example
+
+// Mongoimport to export data as JSON for all databases
+mongoimport --collection=example
+```
+
+## Further Reading
+
+### Setup Videos
+
+- [Install MongoDB - Windows 10](https://www.youtube.com/watch?v=85A6m1soKww)
+- [Install MongoDB - Mac](https://www.youtube.com/watch?v=DX15WbKidXY)
+- [Install MongoDB - Linux
+ (Ubuntu)](https://www.youtube.com/watch?v=wD_2pojFWoE)
+
+### Input Validation
+
+From the examples above, if input validation or structure is a concern, I would
+take a look at the following ORMs:
+
+- [Mongoose (Node.js)](https://mongoosejs.com/docs/) - Input validation through
+ schemas that support types, required values, minimum and maximum values.
+- [MongoEngine (Python)](http://mongoengine.org/) - Similar to Mongoose, but I
+ found it somewhat limited in my experience
+- [MongoKit (Python)](https://github.com/namlook/mongokit) - Another great
+ alternative to MongoEngine that I find easier to use than MongoEngine
+
+For statically strongly typed languages (e.g. Java, C++, Rust), input validation
+usually doesn't require a library as they define types and structure at compile
+time.
+
+### Resources
+
+If you have the time to spare, I would strongly recommend the courses on
+[MongoDB University](https://university.mongodb.com/). They're by MongoDB
+themselves and go into much more detail while still being concise. They're a mix
+of videos and quiz questions and this was how I gained my knowledge of MongoDB.
+
+I would recommend the following video series for learning MongoDB:
+
+- [MongoDB Crash Course - Traversy
+ Media](https://www.youtube.com/watch?v=-56x56UppqQ)
+- [MongoDB Tutorial for Beginners -
+ Amigoscode](https://www.youtube.com/watch?v=Www6cTUymCY)
+
+Language-specific ones that I used before:
+
+- [Build A REST API With Node.js, Express, & MongoDB - Web Dev
+ Simplified](https://www.youtube.com/watch?v=fgTGADljAeg)
+- [MongoDB with Python Crash Course - Tutorial for Beginners -
+ FreeCodeCamp](https://www.youtube.com/watch?v=E-1xI85Zog8)
+- [How to Use MongoDB with Java - Random
+ Coder](https://www.youtube.com/watch?v=reYPUvu2Giw)
+- [An Introduction to Using MongoDB with Rust -
+ MongoDB](https://www.youtube.com/watch?v=qFlftfLGwPM)
+
+Most of the information above was cross-referenced with the [MongoDB
+docs](https://www.mongodb.com/). Here are the docs for each section:
+
+- [MongoDB Types](https://docs.mongodb.com/manual/reference/bson-types/) - List
+ of all types that MongoDB supports natively
+- [MongoDB Operators](https://docs.mongodb.com/manual/reference/operator/) -
+ List of operators MongoDB supports natively
+- [MongoDB CRUD](https://docs.mongodb.com/manual/reference/command/nav-crud/) -
+ Commands for create, read, update, delete
+
+If you've been enjoying MongoDB so far and want to explore intermediate
+features, I would look at
+[aggregation](https://docs.mongodb.com/manual/reference/command/nav-aggregation/),
+[indexing](https://docs.mongodb.com/manual/indexes/), and
+[sharding](https://docs.mongodb.com/manual/sharding/).
+
+- Aggregation - useful for creating advanced queries to be executed by the
+ database
+- Idexing allows for caching, which allows for much faster execution of queries
+- Sharding allows for horizontal data scaling and distribution between multiple
+ machines.
diff --git a/ms-my/bash-my.html.markdown b/ms-my/bash-my.html.markdown
index e4e55b2c..a97e651c 100644
--- a/ms-my/bash-my.html.markdown
+++ b/ms-my/bash-my.html.markdown
@@ -17,7 +17,7 @@ translators:
lang: ms-my
---
-Bash adalah nama daripada unix shell, yang mana telah diagihkan sebagai shell untuk sistem operasi GNU dan sebagai shell lalai pada Linux dan Mac OS X. Hampir semua contoh di bawah boleh menjadi sebahagian daripada skrip shell atau dijalankan terus dalam shell.
+Bash adalah nama daripada unix shell, yang mana telah diagihkan sebagai shell untuk sistem operasi GNU dan sebagai shell lalai pada Linux dan macOS. Hampir semua contoh di bawah boleh menjadi sebahagian daripada skrip shell atau dijalankan terus dalam shell.
[Baca lebih lanjut di sini.](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/nix.html.markdown b/nix.html.markdown
index dde5dbec..1d5a7778 100644
--- a/nix.html.markdown
+++ b/nix.html.markdown
@@ -373,5 +373,8 @@ with builtins; [
* [James Fisher - Nix by example - Part 1: The Nix expression language]
(https://medium.com/@MrJamesFisher/nix-by-example-a0063a1a4c55)
+* [Susan Potter - Nix Cookbook - Nix By Example]
+ (https://ops.functionalalgebra.com/nix-by-example/)
+
* [Rommel Martinez - A Gentle Introduction to the Nix Family]
- (https://ebzzry.io/en/nix/#nix)
+ (https://web.archive.org/web/20210121042658/https://ebzzry.io/en/nix/#nix)
diff --git a/nl-nl/bash-nl.html.markdown b/nl-nl/bash-nl.html.markdown
index af4a8cc8..8d127c57 100644
--- a/nl-nl/bash-nl.html.markdown
+++ b/nl-nl/bash-nl.html.markdown
@@ -17,7 +17,7 @@ lang: nl-nl
filename: LearnBash-nl.sh
---
-Bash is de naam van de unix shell, deze wordt gebruikt voor het GNU operating system en is de standaard shell op Linux en Mac OS X.
+Bash is de naam van de unix shell, deze wordt gebruikt voor het GNU operating system en is de standaard shell op Linux en macOS.
Bijna alle voorbeelden hieronder kunnen deel uitmaken van een shell script of kunnen uitgevoerd worden in de shell.
[Lees er meer over hier.](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/no-nb/bash-no.html.markdown b/no-nb/bash-no.html.markdown
index 481aecbd..9affaa21 100644
--- a/no-nb/bash-no.html.markdown
+++ b/no-nb/bash-no.html.markdown
@@ -17,7 +17,7 @@ lang: no-nb
---
Bash er navnet på unix skallet, som også var distribuert som skallet for GNU
operativsystemet og som standard skall på de fleste Linux distribusjoner og
-Mac OS X.
+macOS.
[Les mer her.](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/objective-c.html.markdown b/objective-c.html.markdown
index de3884af..c029c5fb 100644
--- a/objective-c.html.markdown
+++ b/objective-c.html.markdown
@@ -9,7 +9,7 @@ contributors:
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.
+Objective-C is the main programming language used by Apple for the macOS 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
diff --git a/ocaml.html.markdown b/ocaml.html.markdown
index b631df0a..70668611 100644
--- a/ocaml.html.markdown
+++ b/ocaml.html.markdown
@@ -201,7 +201,7 @@ let (~/) x = 1.0 /. x ;;
(* Lists are enclosed in square brackets, items are separated by
semicolons. *)
-let my_list = [1; 2; 3] ;;
+let my_list = [1; 2; 3] ;; (* Has type "int list". *)
(* Tuples are (optionally) enclosed in parentheses, items are separated
by commas. *)
diff --git a/opencv.html.markdown b/opencv.html.markdown
index d1f7ec51..5d860eca 100644
--- a/opencv.html.markdown
+++ b/opencv.html.markdown
@@ -138,7 +138,6 @@ cv2.destroyAllWindows()
* An up-to-date language reference can be found at [https://opencv.org](https://opencv.org)
* Additional resources may be found at [https://en.wikipedia.org/wiki/OpenCV](https://en.wikipedia.org/wiki/OpenCV)
* Good OpenCv Tutorials
- * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html)
* [https://realpython.com/python-opencv-color-spaces](https://realpython.com/python-opencv-color-spaces)
* [https://pyimagesearch.com](https://pyimagesearch.com)
* [https://www.learnopencv.com](https://www.learnopencv.com)
diff --git a/pascal.html.markdown b/pascal.html.markdown
index a505a38f..9c73c456 100644
--- a/pascal.html.markdown
+++ b/pascal.html.markdown
@@ -12,7 +12,7 @@ source : [wikipedia](https://en.wikipedia.org/wiki/Pascal_(programming_language)
-to compile and run a pascal program you could use a free pascal compiler. [Download Here](https://www.freepascal.org/)
+To compile and run a pascal program you could use a free pascal compiler. [Download Here](https://www.freepascal.org/)
```pascal
//Anatomy of a Pascal Program
@@ -23,7 +23,7 @@ to compile and run a pascal program you could use a free pascal compiler. [Downl
}
//name of the program
-program learn_pascal; //<-- dont forget a semicolon
+program learn_pascal; //<-- don't forget a semicolon
const
{
@@ -31,7 +31,7 @@ const
}
type
{
- this is where you should delcare a custom
+ this is where you should declare custom
data-types
}
var
@@ -44,11 +44,11 @@ begin
{
area to declare your instruction
}
-end. // End of a main program area should required a "." symbol
+end. // End of a main program area should require a "." symbol
```
```pascal
-//declaring variable
+//When declaring variables
//you can do this
var a:integer;
var b:integer;
@@ -62,7 +62,7 @@ var a,b : integer;
```pascal
program Learn_More;
-//Lets learn about data types and their operations
+//Let's learn about data types and their operations
const
PI = 3.141592654;
diff --git a/perl.html.markdown b/perl.html.markdown
index 8811dd08..88185e9d 100644
--- a/perl.html.markdown
+++ b/perl.html.markdown
@@ -217,6 +217,12 @@ open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
my $line = <$in>;
my @lines = <$in>;
+# You can iterate through the lines in a file one at a time with a while loop:
+
+while (my $line = <$in>) {
+ print "Found apples\n" if $line =~ m/apples/;
+}
+
# You can write to an open filehandle using the standard "print"
# function.
diff --git a/phel.html.markdown b/phel.html.markdown
new file mode 100644
index 00000000..4dc030fa
--- /dev/null
+++ b/phel.html.markdown
@@ -0,0 +1,337 @@
+---
+language: phel
+filename: learnphel.phel
+contributors:
+ - ["Chemaclass", "https://github.com/Chemaclass"]
+---
+
+[Phel](https://phel-lang.org/) is a functional programming language that compiles to PHP.
+It is a dialect of Lisp inspired by Clojure and Janet.
+
+## Features
+- Built on PHP's ecosystem
+- Good error reporting
+- Persistent Datastructures (Lists, Vectors, Maps and Sets)
+- Macros
+- Recursive functions
+- Powerful but simple Syntax
+- REPL
+
+```newlisp
+# Comments begin with a # character and continue until the end of the line. There are no multi-line comments.
+
+# Phel is written in "forms", which are just
+# lists of things inside parentheses, separated by whitespace.
+
+# The first call in a file should be ns, to set the namespace
+(ns learn-phel)
+
+# More basic examples:
+
+# str will create a string out of all its arguments
+(str "Hello" " " "World") #=> "Hello World"
+
+# Math is straightforward
+(+ 1 1) #=> 2
+(- 2 1) #=> 1
+(* 1 2) #=> 2
+(/ 2 1) #=> 2
+
+# Equality is =
+(= 1 1) #=> true
+(= 2 1) #=> false
+
+# You need not for logic, too
+(not true) #=> false
+
+# Nesting forms works as you expect
+(+ 1 (- 3 2)) # = 1 + (3 - 2) => 2
+
+# Phel inherits PHP under the hood, so it can use native PHP (functions and classes) without
+# any additional cost by using the `php/` prefix to all PHP native functions.
+
+# Types
+#############
+
+# Booleans are similar as the native PHP ones
+
+nil
+true
+false
+
+# Symbols are used to name functions and variables in Phel
+# For example: symbol, snake_case_symbol, my-module/my-function
+
+# Keywords are like symbols that begin with a colon character. However, they are used as constants rather than a name for something.
+
+:keyword
+:0x0x0x
+::
+
+# Numbers in Phel are equivalent to numbers in PHP
+
+1337 # integer
++1337 # positive integer
+-1337 # negative integer
+
+1.234 # float
++1.234 # positive float
+-1.234 # negative float
+1.2e3 # float
+7E-10 # float
+
+# Strings are surrounded by double quotes. They almost work the same as PHP double quoted strings.
+# A string can be written in multiple lines. The line break character is then ignored by the reader.
+
+"hello world"
+
+"this is\na\nstring"
+
+"this
+is
+a
+string."
+
+"use backslack to escape \" string"
+
+"the dollar must not be escaped: $ or $abc just works"
+
+
+# Collections & Sequences
+#############
+
+# Lists are linked-list data structures, while vectors are array-backed
+(type '(1 2 3)) #=> :list
+(type [1 2 3]) #=> :vector
+
+# A list would be written as just (1 2 3), but we have to quote
+# it to stop the reader thinking it's a function.
+# Also, (list 1 2 3) is the same as '(1 2 3)
+
+# You can produce a (non-lazy) sequence between a range.
+(range 1 10 2) #=> (range from to step)
+(take 4 (range 10))
+
+# Use cons to add an item to the beginning of a list
+(cons 4 '(1 2 3)) #=> (4 1 2 3)
+
+# Use push to add, and put to replace an item in a vector
+(push [1 2 3] 4) #=> (1 2 3 4)
+(put [1 2 3] 1 4) #=> (1 4 3)
+
+# Use concat to add lists or vectors together
+(concat [1 2] '(3 4)) #=> [1 2 3 4]
+
+# Use filter, map to interact with collections
+(map inc [1 2 3]) #=> [2 3 4]
+(filter even? [1 2 3]) #=> [2]
+
+# Use reduce to reduce them. The initial-value is mandatory
+(reduce + 0 [1 2 3 4])
+#=> (+ (+ (+ 1 2) 3) 4)
+#=> 10
+
+(reduce push [] '(3 2 1))
+#=> (push (push (push [] 3) 2) 1)
+#=> [3 2 1]
+
+# Functions
+#############
+
+# Use fn to create new functions
+# A function always returns its last statement
+(fn [] "Hello World") #=> <function>
+
+# You need extra parens to call it
+((fn [] "Hello World")) #=> "Hello World"
+
+# You can bind a value to a symbol using def for definition
+(def x 1)
+x #=> 1
+
+# Variables provide a way to manage mutable state
+(def foo (var 10)) # Define a variable with value 10
+
+# Assign a function to a definition
+(def hello-world (fn [] "Hello World"))
+(hello-world) #=> "Hello World"
+
+# You can shorten this process by using defn
+(defn hello-world [] "Hello World")
+
+# The [] is the list of arguments for the function
+(defn hello [name]
+ (str "Hello " name))
+(hello "Jens") #=> "Hello Jens"
+
+# You can also use this shorthand to create functions
+(def hello2 |(str "Hello " $1))
+(hello2 "Anna") #=> "Hello Anna"
+
+# Functions can pack extra arguments up in a seq for you
+(defn count-args [& args]
+ (str "You passed " (count args) " args: " args))
+(count-args 1 2 3) #=> "You passed 3 args: @[1 2 3]"
+
+# You can mix regular and packed arguments
+(defn hello-count [name & args]
+ (str "Hello " name ", you passed " (count args) " extra args"))
+(hello-count "Jesus" 1 2) #=> "Hello Jesus, you passed 2 extra args"
+
+
+# Maps
+#############
+
+# Hash maps have faster lookups but don't retain key order
+(type {:a 1 :b 2 :c 3}) #=> :hash-map
+(type (hash-map :a 1 :b 2 :c 3)) #=> :hash-map
+
+# Maps can use any hashable type as a key, but usually keywords are best
+# Keywords are like strings with some efficiency bonuses and they start with `:`
+(type :a) #=> :keyword
+
+(def stringmap {"a" 1 "b" 2 "c" 3})
+stringmap #=> {"a" 1 "b" 2 "c" 3}
+
+(def keymap {:a 1 :b 2 :c 3})
+keymap #=> {:a 1 :c 3 :b 2}
+
+# Retrieve a value from a map by calling it as a function
+(stringmap "a") #=> 1
+(keymap :a) #=> 1
+
+# Keywords can be used to retrieve their value from a map, too!
+(:b keymap) #=> 2
+
+# Don't try this with strings
+# ("a" stringmap)
+# ...Exception: Call to undefined function a()
+
+# Retrieving a non-present key returns nil
+(stringmap "d") #=> nil
+
+# Use put to add new keys to hash-maps
+(def newkeymap (put keymap :d 4))
+newkeymap #=> {:a 1 :b 2 :c 3 :d 4}
+
+# But remember, phel types are immutable!
+keymap #=> {:a 1 :b 2 :c 3}
+
+# Use unset to remove keys
+(unset keymap :a) #=> {:b 2 :c 3}
+
+# Sets
+#############
+
+# A Set contains unique values in random order
+
+(type (set 1 2 3)) #=> :set
+(set 1 2 3 1 2 3 3 2 1 3 2 1) #=> (set 1 2 3)
+
+# Add a member with push
+(push (set 1 2 3) 4) #=> (set 1 2 3 4)
+
+# Remove one with unset
+(unset (set 1 2 3) 1) #=> (set 2 3)
+
+# Test for existence by using the set as a function
+((set 1 2 3) 1) #=> 1
+((set 1 2 3) 4) #=> nil
+
+# There are more functions like: count, union, intersection, difference, etc
+
+
+# Useful forms
+#############
+
+# `If` conditionals in phel are special forms
+(if false "a" "b") #=> "b"
+(if false "a") #=> nil
+
+# Use let to create temporary bindings
+(let [a 1 b 2]
+ (> a b)) #=> false
+
+# Group statements together with do
+(do
+ (print "Hello")
+ "World") #=> "World" (prints "Hello")
+
+# Functions have an implicit do
+(defn print-and-say-hello [name]
+ (print "Saying hello to " name)
+ (str "Hello " name))
+(print-and-say-hello "Jeff") #=> "Hello Jeff" (prints "Saying hello to Jeff")
+
+# So does let
+(let [name "Urkel"]
+ (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}
+ (put :c 3) #=> (put {:a 1 :b 2} :c 3)
+ (unset :b)) #=> (unset (put {:a 1 :b 2} :c 3) :b)
+
+
+# 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)))
+ # Result: [1 3 5 7 9]
+
+
+# When you are in a situation where you want more freedom as where to
+# put the result of previous data transformations in an
+# expression, you can use the as-> macro. With it, you can assign a
+# specific name to transformations' output and use it as a
+# placeholder in your chained expressions:
+
+(as-> [1 2 3] input
+ (map inc input) #=> You can use last transform's output at the last position
+ (get input 2) #=> and at the second position, in the same expression
+ (push [4 5 6] input 8 9 10)) #=> or in the middle !
+ # Result: [4 5 6 4 8 9 10]
+
+# PHP
+#################
+
+# PHP has a huge and useful standard library, and you're able to use
+# all native functions with the prefix `php/`.
+(php/+ 1 2 3)
+
+# With :use you can use different namespaces. Similar as `use` in PHP
+(ns my\module
+ (:use \DateTimeImmutable))
+
+# You can import functions from other phel files with :require
+(ns my\module
+ (:require phel\test :refer [deftest is]))
+
+# Use the class name with a "php/new" to make a new instance
+(php/new \DateTime) # <a date-time object>
+
+# Use php/-> to call methods of an object
+(def d (php/new \DateTime))
+(php/-> d (getTimestamp)) # <a timestamp>
+
+# you can do it in one line too
+(php/-> (php/new \DateTime) (getTimestamp))
+
+# Use php/:: to call static methods
+(php/:: \DateTimeImmutable ATOM) # <a timestamp>
+```
+
+### Further Reading
+
+This is far from exhaustive, but hopefully it's enough to get you on your feet.
+
+Read the full documentation in the website: [https://phel-lang.org/](https://phel-lang.org/documentation/getting-started/)
diff --git a/php.html.markdown b/php.html.markdown
index 57ba29c4..821bde8f 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -591,6 +591,12 @@ echo $my_class->property; // => "public"
echo $my_class->instanceProp; // => "An instance property"
$my_class->myMethod(); // => "MyClass"
+// Nullsafe operators since PHP 8
+// You can use this when you're unsure if the abstraction of $my_class contains has a property/method
+// it can be used in conjunction with the nullish coalesce operator to ensure proper value
+echo $my_class->invalid_property // An error is thrown
+echo $my_class?->invalid_property // => NULL
+echo $my_class?->invalid_property ?? "public" // => "public"
// Extend classes using "extends"
class MyOtherClass extends MyClass
diff --git a/pt-br/bash-pt.html.markdown b/pt-br/bash-pt.html.markdown
index 988e8e7d..ab003a18 100644
--- a/pt-br/bash-pt.html.markdown
+++ b/pt-br/bash-pt.html.markdown
@@ -17,7 +17,7 @@ lang: pt-br
Tutorial de shell em português
Bash é o nome do shell do Unix, que também é distribuído como shell do sistema
-operacional GNU e como shell padrão para Linux e Mac OS X. Praticamente todos
+operacional GNU e como shell padrão para Linux e macOS. Praticamente todos
os exemplos abaixo podem fazer parte de um shell script e pode ser executados
diretamente no shell.
diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown
index e6dea5b8..e4f55276 100644
--- a/pt-br/css-pt.html.markdown
+++ b/pt-br/css-pt.html.markdown
@@ -290,9 +290,9 @@ A maior parte dos recursos do CSS 2 (e muitos em CSS 3) estão disponíveis em t
## Leitura adicional
-* [Entendendo Estilo Precedência em CSS: Especificidade, Herança, eo Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
+* [Entendendo Estilo Precedência em CSS: Especificidade, Herança, e o 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
+* [SASS](http://sass-lang.com/) e [Less](http://lesscss.org/) para CSS pré-processamento
* [CSS-Tricks](https://css-tricks.com)
diff --git a/pt-br/r-pt.html.markdown b/pt-br/r-pt.html.markdown
new file mode 100644
index 00000000..eeaa4eab
--- /dev/null
+++ b/pt-br/r-pt.html.markdown
@@ -0,0 +1,786 @@
+---
+language: R
+contributors:
+ - ["e99n09", "http://github.com/e99n09"]
+ - ["isomorphismes", "http://twitter.com/isomorphisms"]
+ - ["kalinn", "http://github.com/kalinn"]
+translators:
+ - ["Marcel Ribeiro-Dantas", "http://github.com/mribeirodantas"]
+lang: pt-br
+filename: learnr.r
+---
+
+R é uma linguagem de programação estatística. Ela tem muitas bibliotecas para carregar e limpar conjuntos de dados, executar análises estatísticas e produzir gráficos. Você também pode executar comandos do `R` dentro de um documento LaTeX.
+
+```r
+
+# Comentários começam com o símbolo de Cerquilha, também conhecido como
+# jogo da velha
+
+# Não existe um símbolo especial para comentários em várias linhas
+# mas você pode escrever várias linhas de comentários adicionando a
+# cerquilha (#) ao início de cada uma delas.
+
+# No Windows e Linux, você pode usar CTRL-ENTER para executar uma linha.
+# No MacOS, o equivalente é COMMAND-ENTER
+
+
+
+#############################################################################
+# Coisas que você pode fazer sem entender nada sobre programação
+#############################################################################
+
+# Nesta seção, mostramos algumas das coisas legais que você pode fazer em
+# R sem entender nada de programação. Não se preocupe em entender tudo o
+# que o código faz. Apenas aproveite!
+
+data() # navegue pelos conjuntos de dados pré-carregados
+data(rivers) # carregue este: "Comprimentos dos principais rios norte-americanos"
+ls() # observe que "rivers" apareceu na área de trabalho (workspace)
+head(rivers) # dê uma espiada no conjunto de dados
+# 735 320 325 392 524 450
+
+length(rivers) # quantos rios foram medidos?
+# 141
+summary(rivers) # consulte um sumário de estatísticas básicas
+# Min. 1st Qu. Median Mean 3rd Qu. Max.
+# 135.0 310.0 425.0 591.2 680.0 3710.0
+
+# faça um diagrama de ramos e folhas (uma visualização de dados semelhante a um histograma)
+stem(rivers)
+
+# A vírgula está 2 dígito(s) à direita do símbolo |
+#
+# 0 | 4
+# 2 | 011223334555566667778888899900001111223333344455555666688888999
+# 4 | 111222333445566779001233344567
+# 6 | 000112233578012234468
+# 8 | 045790018
+# 10 | 04507
+# 12 | 1471
+# 14 | 56
+# 16 | 7
+# 18 | 9
+# 20 |
+# 22 | 25
+# 24 | 3
+# 26 |
+# 28 |
+# 30 |
+# 32 |
+# 34 |
+# 36 | 1
+
+stem(log(rivers)) # Observe que os dados não são normais nem log-normais!
+# Tome isso, fundamentalistas da curva normal!
+
+# O ponto decimal está 1 dígito(s) à esquerda do símbolo |
+#
+# 48 | 1
+# 50 |
+# 52 | 15578
+# 54 | 44571222466689
+# 56 | 023334677000124455789
+# 58 | 00122366666999933445777
+# 60 | 122445567800133459
+# 62 | 112666799035
+# 64 | 00011334581257889
+# 66 | 003683579
+# 68 | 0019156
+# 70 | 079357
+# 72 | 89
+# 74 | 84
+# 76 | 56
+# 78 | 4
+# 80 |
+# 82 | 2
+
+# faça um histograma:
+hist(rivers, col="#333333", border="white", breaks=25) # brinque com estes parâmetros
+hist(log(rivers), col="#333333", border="white", breaks=25) # você fará mais gráficos mais tarde
+
+# Aqui está outro conjunto de dados que vem pré-carregado. O R tem toneladas deles.
+data(discoveries)
+plot(discoveries, col="#333333", lwd=3, xlab="Ano",
+ main="Número de descobertas importantes por ano")
+plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Ano",
+ main="Número de descobertas importantes por ano")
+
+# Em vez de deixar a ordenação padrão (por ano),
+# também podemos ordenar para ver o que é mais comum:
+sort(discoveries)
+# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2
+# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3
+# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4
+# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12
+
+stem(discoveries, scale=2)
+#
+# O ponto decimal está no símbolo |
+#
+# 0 | 000000000
+# 1 | 000000000000
+# 2 | 00000000000000000000000000
+# 3 | 00000000000000000000
+# 4 | 000000000000
+# 5 | 0000000
+# 6 | 000000
+# 7 | 0000
+# 8 | 0
+# 9 | 0
+# 10 | 0
+# 11 |
+# 12 | 0
+
+max(discoveries)
+# 12
+summary(discoveries)
+# Min. 1st Qu. Median Mean 3rd Qu. Max.
+# 0.0 2.0 3.0 3.1 4.0 12.0
+
+# Role um dado algumas vezes
+round(runif(7, min=.5, max=6.5))
+# 1 4 6 1 4 6 4
+# Seus números serão diferentes dos meus, a menos que definamos a mesma semente aleatória com o set.seed
+
+# Obtenha 9 números de forma aleatória a partir de uma distribuição normal
+rnorm(9)
+# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271
+# [7] -0.59975593 0.57629164 1.08455362
+
+
+
+##################################################
+# Tipos de dados e aritmética básica
+##################################################
+
+# Agora para a parte orientada a programação do tutorial.
+# Nesta seção você conhecerá os tipos de dados importantes do R:
+# integers, numerics, characters, logicals, e factors.
+# Existem outros, mas estes são o mínimo que você precisa para
+# iniciar.
+
+# INTEGERS
+# Os inteiros de armazenamento longo são escritos com L
+5L # 5
+class(5L) # "integer"
+# (Experimente ?class para obter mais informações sobre a função class().)
+# Em R, todo e qualquer valor, como 5L, é considerado um vetor de comprimento 1
+length(5L) # 1
+# Você pode ter um vetor inteiro com comprimento > 1 também:
+c(4L, 5L, 8L, 3L) # 4 5 8 3
+length(c(4L, 5L, 8L, 3L)) # 4
+class(c(4L, 5L, 8L, 3L)) # "integer"
+
+# NUMERICS
+# Um "numeric" é um número de ponto flutuante de precisão dupla
+5 # 5
+class(5) # "numeric"
+# De novo, tudo em R é um vetor;
+# você pode fazer um vetor numérico com mais de um elemento
+c(3,3,3,2,2,1) # 3 3 3 2 2 1
+# Você também pode usar a notação científica
+5e4 # 50000
+6.02e23 # Número de Avogadro
+1.6e-35 # Comprimento de Planck
+# Você também pode ter números infinitamente grandes ou pequenos
+class(Inf) # "numeric"
+class(-Inf) # "numeric"
+# Você pode usar "Inf", por exemplo, em integrate(dnorm, 3, Inf)
+# isso evita as tabelas de escores-Z.
+
+# ARITMÉTICA BÁSICA
+# Você pode fazer aritmética com números
+# Fazer aritmética com uma mistura de números inteiros (integers) e com
+# ponto flutuante (numeric) resulta em um numeric
+10L + 66L # 76 # integer mais integer resulta em integer
+53.2 - 4 # 49.2 # numeric menos numeric resulta em numeric
+2.0 * 2L # 4 # numeric vezes integer resulta em numeric
+3L / 4 # 0.75 # integer dividido por numeric resulta em numeric
+3 %% 2 # 1 # o resto de dois numeric é um outro numeric
+# Aritmética ilegal produz um "não-é-um-número" (do inglês Not-a-Number):
+0 / 0 # NaN
+class(NaN) # "numeric"
+# Você pode fazer aritmética em dois vetores com comprimento maior que 1,
+# desde que o comprimento do vetor maior seja um múltiplo inteiro do menor
+c(1,2,3) + c(1,2,3) # 2 4 6
+# Como um único número é um vetor de comprimento um, escalares são aplicados
+# elemento a elemento com relação a vetores
+(4 * c(1,2,3) - 2) / 2 # 1 3 5
+# Exceto para escalares, tenha cuidado ao realizar aritmética em vetores com
+# comprimentos diferentes. Embora possa ser feito,
+c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6
+# ter comprimentos iguais é uma prática melhor e mais fácil de ler
+c(1,2,3,1,2,3) * c(1,2,1,2,1,2)
+
+# CHARACTERS
+# Não há diferença entre strings e caracteres em R
+"Horatio" # "Horatio"
+class("Horatio") # "character"
+class('H') # "character"
+# São ambos vetores de caracteres de comprimento 1
+# Aqui está um mais longo:
+c('alef', 'bet', 'gimmel', 'dalet', 'he')
+# "alef" "bet" "gimmel" "dalet" "he"
+length(c("Call","me","Ishmael")) # 3
+# Você pode utilizar expressões regulares (regex) em vetores de caracteres:
+substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis "
+gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis."
+# R tem vários vetores de caracteres embutidos:
+letters
+# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
+# [20] "t" "u" "v" "w" "x" "y" "z"
+month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
+
+# LOGICALS
+# Em R, um "logical" é um booleano
+class(TRUE) # "logical"
+class(FALSE) # "logical"
+# O comportamento deles é normal
+TRUE == TRUE # TRUE
+TRUE == FALSE # FALSE
+FALSE != FALSE # FALSE
+FALSE != TRUE # TRUE
+# Dados ausentes (NA) são logical, também
+class(NA) # "logical"
+# Use | e & para operações lógicas.
+# OR
+TRUE | FALSE # TRUE
+# AND
+TRUE & FALSE # FALSE
+# Aplicar | e & a vetores retorna operações lógicas elemento a elemento
+c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE
+c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE
+# Você pode testar se x é TRUE
+isTRUE(TRUE) # TRUE
+# Aqui obtemos um vetor logical com muitos elementos:
+c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE
+c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE
+
+# FACTORS
+# A classe factor é para dados categóricos
+# Os fatores podem ser ordenados (como as avaliações de crianças) ou
+# não ordenados (como as cores)
+factor(c("azul", "azul", "verde", NA, "azul"))
+# azul azul verde <NA> azul
+# Levels: azul verde
+# Os "levels" são os valores que os dados categóricos podem assumir
+# Observe que os dados ausentes não entram nos levels
+levels(factor(c("verde", "verde", "azul", NA, "azul"))) # "azul" "verde"
+# Se um vetor de factor tem comprimento 1, seus levels também terão comprimento 1
+length(factor("green")) # 1
+length(levels(factor("green"))) # 1
+# Os fatores são comumente vistos em data frames, uma estrutura de dados que abordaremos
+# mais tarde
+data(infert) # "Infertilidade após aborto espontâneo e induzido"
+levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs"
+
+# NULL
+# "NULL" é um valor estranho; use-o para "apagar" um vetor
+class(NULL) # NULL
+parakeet = c("bico", "penas", "asas", "olhos")
+parakeet
+# [1] "bico" "penas" "asas" "olhos"
+parakeet <- NULL
+parakeet
+# NULL
+
+# COERÇÃO DE TIPO
+# Coerção de tipo é quando você força um valor a assumir um tipo diferente
+as.character(c(6, 8)) # "6" "8"
+as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE
+# Se você colocar elementos de diferentes tipos em um vetor, coerções estranhas acontecem:
+c(TRUE, 4) # 1 4
+c("cachorro", TRUE, 4) # "cachorro" "TRUE" "4"
+as.numeric("Bilbo")
+# [1] NA
+# Warning message:
+# NAs introduced by coercion
+
+# Observe também: esses são apenas os tipos de dados básicos
+# Existem muitos outros tipos de dados, como datas, séries temporais, etc.
+
+
+
+##################################################
+# Variáveis, laços, expressões condicionais
+##################################################
+
+# Uma variável é como uma caixa na qual você armazena um valor para uso posterior.
+# Chamamos isso de "atribuir" o valor à variável.
+# Ter variáveis nos permite escrever laços, funções e instruções com condição
+
+# VARIÁVEIS
+# Existem muitas maneiras de atribuir valores:
+x = 5 # é possível fazer assim
+y <- "1" # mas é preferível fazer assim
+TRUE -> z # isso funciona, mas é estranho
+
+# LAÇOS
+# Nós temos laços com for
+for (i in 1:4) {
+ print(i)
+}
+# [1] 1
+# [1] 2
+# [1] 3
+# [1] 4
+# Nós temos laços com while
+a <- 10
+while (a > 4) {
+ cat(a, "...", sep = "")
+ a <- a - 1
+}
+# 10...9...8...7...6...5...
+# Tenha em mente que os laços for e while são executados lentamente em R
+# Operações em vetores inteiros (por exemplo, uma linha inteira, uma coluna inteira)
+# ou funções do tipo apply() (discutiremos mais tarde) são mais indicadas
+
+# IF/ELSE
+# Novamente, bastante padrão
+if (4 > 3) {
+ print("4 é maior que 3")
+} else {
+ print("4 não é maior que 3")
+}
+# [1] "4 é maior que 3"
+
+# FUNÇÕES
+# Definidas assim:
+jiggle <- function(x) {
+ x = x + rnorm(1, sd=.1) # adicione um pouco de ruído (controlado)
+ return(x)
+}
+# Chamada como qualquer outra função R:
+jiggle(5) # 5±ε. Após set.seed(2716057), jiggle(5)==5.005043
+
+
+
+###########################################################################
+# Estruturas de dados: Vetores, matrizes, data frames e arranjos (arrays)
+###########################################################################
+
+# UNIDIMENSIONAL
+
+# Vamos começar do início, e com algo que você já sabe: vetores.
+vec <- c(8, 9, 10, 11)
+vec # 8 9 10 11
+# Consultamos elementos específicos utilizando colchetes
+# (Observe que R começa a contar a partir de 1)
+vec[1] # 8
+letters[18] # "r"
+LETTERS[13] # "M"
+month.name[9] # "September"
+c(6, 8, 7, 5, 3, 0, 9)[3] # 7
+# Também podemos pesquisar os índices de componentes específicos,
+which(vec %% 2 == 0) # 1 3
+# pegue apenas as primeiras ou últimas entradas no vetor,
+head(vec, 1) # 8
+tail(vec, 2) # 10 11
+# ou descubra se um determinado valor está no vetor
+any(vec == 10) # TRUE
+# Se um índice for além do comprimento de um vetor, você obterá NA:
+vec[6] # NA
+# Você pode encontrar o comprimento do seu vetor com length()
+length(vec) # 4
+# Você pode realizar operações em vetores inteiros ou subconjuntos de vetores
+vec * 4 # 32 36 40 44
+vec[2:3] * 5 # 45 50
+any(vec[2:3] == 8) # FALSE
+# e R tem muitas funções internas para sumarizar vetores
+mean(vec) # 9.5
+var(vec) # 1.666667
+sd(vec) # 1.290994
+max(vec) # 11
+min(vec) # 8
+sum(vec) # 38
+# Mais alguns recursos embutidos:
+5:15 # 5 6 7 8 9 10 11 12 13 14 15
+seq(from=0, to=31337, by=1337)
+# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707
+# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751
+
+# BIDIMENSIONAL (ELEMENTOS DA MESMA CLASSE)
+
+# Você pode fazer uma matriz com entradas do mesmo tipo assim:
+mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6))
+mat
+# [,1] [,2]
+# [1,] 1 4
+# [2,] 2 5
+# [3,] 3 6
+# Ao contrário de um vetor, a classe de uma matriz é "matrix" independente do que ela contém
+class(mat) # "matrix"
+# Consulte a primeira linha
+mat[1,] # 1 4
+# Execute uma operação na primeira coluna
+3 * mat[,1] # 3 6 9
+# Consulte uma célula específica
+mat[3,2] # 6
+
+# Transponha toda a matriz
+t(mat)
+# [,1] [,2] [,3]
+# [1,] 1 2 3
+# [2,] 4 5 6
+
+# Multiplicação de matrizes
+mat %*% t(mat)
+# [,1] [,2] [,3]
+# [1,] 17 22 27
+# [2,] 22 29 36
+# [3,] 27 36 45
+
+# cbind() une vetores em colunas para formar uma matriz
+mat2 <- cbind(1:4, c("cachorro", "gato", "passaro", "cachorro"))
+mat2
+# [,1] [,2]
+# [1,] "1" "cachorro"
+# [2,] "2" "gato"
+# [3,] "3" "passaro"
+# [4,] "4" "cachorro"
+class(mat2) # matrix
+# Mais uma vez, observe o que aconteceu!
+# Como as matrizes devem conter todas as entradas da mesma classe,
+# tudo foi convertido para a classe character
+c(class(mat2[,1]), class(mat2[,2]))
+
+# rbind() une vetores linha a linha para fazer uma matriz
+mat3 <- rbind(c(1,2,4,5), c(6,7,0,4))
+mat3
+# [,1] [,2] [,3] [,4]
+# [1,] 1 2 4 5
+# [2,] 6 7 0 4
+# Ah, tudo da mesma classe. Sem coerções. Muito melhor.
+
+# BIDIMENSIONAL (CLASSES DIFERENTES)
+
+# Para colunas de tipos diferentes, use um data frame
+# Esta estrutura de dados é tão útil para programação estatística,
+# que uma versão dela foi adicionada ao Python através do pacote "pandas".
+
+estudantes <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"),
+ c(3,2,2,1,0,-1),
+ c("H", "G", "G", "R", "S", "G"))
+names(estudantes) <- c("nome", "ano", "casa") # nomeie as colunas
+class(estudantes) # "data.frame"
+estudantes
+# nome ano casa
+# 1 Cedric 3 H
+# 2 Fred 2 G
+# 3 George 2 G
+# 4 Cho 1 R
+# 5 Draco 0 S
+# 6 Ginny -1 G
+class(estudantes$ano) # "numeric"
+class(estudantes[,3]) # "factor"
+# encontre as dimensões
+nrow(estudantes) # 6
+ncol(estudantes) # 3
+dim(estudantes) # 6 3
+# A função data.frame() converte vetores de caracteres em vetores de fator
+# por padrão; desligue isso definindo stringsAsFactors = FALSE quando
+# você criar um data frame
+?data.frame
+
+# Existem muitas maneiras particulares de consultar partes de um data frame,
+# todas sutilmente diferentes
+estudantes$ano # 3 2 2 1 0 -1
+estudantes[,2] # 3 2 2 1 0 -1
+estudantes[,"ano"] # 3 2 2 1 0 -1
+
+# Uma versão extendida da estrutura data.frame é a data.table
+# Se você estiver trabalhando com dados enormes ou em painel, ou precisar mesclar
+# alguns conjuntos de dados, data.table pode ser uma boa escolha. Aqui está um tour
+# relâmpago:
+install.packages("data.table") # baixe o pacote a partir do CRAN
+require(data.table) # carregue ele
+estudantes <- as.data.table(estudantes)
+estudantes # observe a saída ligeiramente diferente
+# nome ano casa
+# 1: Cedric 3 H
+# 2: Fred 2 G
+# 3: George 2 G
+# 4: Cho 1 R
+# 5: Draco 0 S
+# 6: Ginny -1 G
+estudantes[nome=="Ginny"] # Consulte estudantes com o nome == "Ginny"
+# nome ano casa
+# 1: Ginny -1 G
+estudantes[ano==2] # Consulte estudantes com o ano == 2
+# nome ano casa
+# 1: Fred 2 G
+# 2: George 2 G
+# data.table facilita a fusão de dois conjuntos de dados
+# vamos fazer outro data.table para mesclar com os alunos
+fundadores <- data.table(casa=c("G","H","R","S"),
+ fundador=c("Godric","Helga","Rowena","Salazar"))
+fundadores
+# casa fundador
+# 1: G Godric
+# 2: H Helga
+# 3: R Rowena
+# 4: S Salazar
+setkey(estudantes, casa)
+setkey(fundadores, casa)
+estudantes <- fundadores[estudantes] # mescle os dois conjuntos de dados com base na "casa"
+setnames(estudantes, c("casa","nomeFundadorCasa","nomeEstudante","ano"))
+estudantes[,order(c("nome","ano","casa","nomeFundadorCasa")), with=F]
+# nomeEstudante ano casa nomeFundadorCasa
+# 1: Fred 2 G Godric
+# 2: George 2 G Godric
+# 3: Ginny -1 G Godric
+# 4: Cedric 3 H Helga
+# 5: Cho 1 R Rowena
+# 6: Draco 0 S Salazar
+
+# O data.table torna as tabelas de sumário fáceis
+estudantes[,sum(ano),by=casa]
+# casa V1
+# 1: G 3
+# 2: H 3
+# 3: R 1
+# 4: S 0
+
+# Para remover uma coluna de um data.frame ou data.table,
+# atribua a ela o valor NULL
+estudantes$nomeFundadorCasa <- NULL
+estudantes
+# nomeEstudante ano casa
+# 1: Fred 2 G
+# 2: George 2 G
+# 3: Ginny -1 G
+# 4: Cedric 3 H
+# 5: Cho 1 R
+# 6: Draco 0 S
+
+# Remova uma linha consultando parte dos dados
+# Usando data.table:
+estudantes[nomeEstudante != "Draco"]
+# casa estudanteNome ano
+# 1: G Fred 2
+# 2: G George 2
+# 3: G Ginny -1
+# 4: H Cedric 3
+# 5: R Cho 1
+# Usando data.frame:
+estudantes <- as.data.frame(estudantes)
+estudantes[estudantes$casa != "G",]
+# casa nomeFundadorCasa nomeEstudante ano
+# 4 H Helga Cedric 3
+# 5 R Rowena Cho 1
+# 6 S Salazar Draco 0
+
+# MULTIDIMENSIONAL (TODOS OS ELEMENTOS DE UM TIPO)
+
+# Arranjos (arrays) criam tabelas n-dimensionais
+# Todos os elementos devem ser do mesmo tipo
+# Você pode fazer uma tabela bidimensional (como uma matriz)
+array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4))
+# [,1] [,2] [,3] [,4]
+# [1,] 1 4 8 3
+# [2,] 2 5 9 6
+# Você pode usar array para fazer matrizes tridimensionais também
+array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2))
+# , , 1
+#
+# [,1] [,2]
+# [1,] 2 8
+# [2,] 300 9
+# [3,] 4 0
+#
+# , , 2
+#
+# [,1] [,2]
+# [1,] 5 66
+# [2,] 60 7
+# [3,] 0 847
+
+# LISTAS (MULTIDIMENSIONAIS, POSSIVELMENTE IMPERFEITAS, DE DIFERENTES TIPOS)
+
+# Finalmente, R tem listas (de vetores)
+lista1 <- list(tempo = 1:40)
+lista1$preco = c(rnorm(40,.5*lista1$tempo,4)) # aleatória
+lista1
+# Você pode obter itens na lista assim
+lista1$tempo # um modo
+lista1[["tempo"]] # um outro modo
+lista1[[1]] # e ainda um outro modo
+# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
+# [34] 34 35 36 37 38 39 40
+# Você pode obter itens de uma lista como qualquer outro vetor
+lista1$preco[4]
+
+# Listas não são a estrutura de dados mais eficiente para se trabalhar em R;
+# a menos que você tenha um bom motivo, você deve se ater a data.frames
+# As listas geralmente são retornadas por funções que realizam regressões lineares
+
+##################################################
+# A família de funções apply()
+##################################################
+
+# Lembra de mat?
+mat
+# [,1] [,2]
+# [1,] 1 4
+# [2,] 2 5
+# [3,] 3 6
+# Use apply(X, MARGIN, FUN) para aplicar a função FUN a uma matriz X
+# sobre linhas (MARGIN = 1) ou colunas (MARGIN = 2)
+# Ou seja, R faz FUN para cada linha (ou coluna) de X, muito mais rápido que um
+# laço for ou while faria
+apply(mat, MAR = 2, jiggle)
+# [,1] [,2]
+# [1,] 3 15
+# [2,] 7 19
+# [3,] 11 23
+# Outras funções: ?lappy, ?sapply
+
+# Não as deixe te intimidar; todos concordam que essas funções são bem confusas
+
+# O pacote plyr visa substituir (e melhorar!) a família *apply().
+install.packages("plyr")
+require(plyr)
+?plyr
+
+
+
+#########################
+# Carregando dados
+#########################
+
+# "pets.csv" é um arquivo hospedado na internet
+# (mas também poderia tranquilamente ser um arquivo no seu computador)
+require(RCurl)
+pets <- read.csv(textConnection(getURL("https://learnxinyminutes.com/docs/pets.csv")))
+pets
+head(pets, 2) # primeiras duas linhas
+tail(pets, 1) # última linha
+
+# Para salvar um data frame ou matriz como um arquivo .csv:
+write.csv(pets, "pets2.csv") # para criar um novo arquivo .csv
+# Define o diretório de trabalho com setwd(), confirme em qual você está com getwd()
+
+# Experimente ?read.csv e ?write.csv para obter mais informações
+
+
+
+#########################
+# Análise estatística
+#########################
+
+# Regressão linear!
+modeloLinear <- lm(preco ~ tempo, data = lista1)
+modeloLinear # imprime na tela o resultado da regressão
+# Call:
+# lm(formula = preco ~ tempo, data = lista1)
+#
+# Coefficients:
+# (Intercept) tempo
+# 0.1453 0.4943
+summary(modeloLinear) # saída mais detalhada da regressão
+# Call:
+# lm(formula = preco ~ tempo, data = lista1)
+#
+# Residuals:
+# Min 1Q Median 3Q Max
+# -8.3134 -3.0131 -0.3606 2.8016 10.3992
+#
+# Coefficients:
+# Estimate Std. Error t value Pr(>|t|)
+# (Intercept) 0.14527 1.50084 0.097 0.923
+# tempo 0.49435 0.06379 7.749 2.44e-09 ***
+# ---
+# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
+#
+# Residual standard error: 4.657 on 38 degrees of freedom
+# Multiple R-squared: 0.6124, Adjusted R-squared: 0.6022
+# F-statistic: 60.05 on 1 and 38 DF, p-value: 2.44e-09
+coef(modeloLinear) # extrai os parâmetros estimados
+# (Intercept) tempo
+# 0.1452662 0.4943490
+summary(modeloLinear)$coefficients # um outro meio de extrair os resultados
+# Estimate Std. Error t value Pr(>|t|)
+# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01
+# tempo 0.4943490 0.06379348 7.74920901 2.440008e-09
+summary(modeloLinear)$coefficients[,4] # the p-values
+# (Intercept) tempo
+# 9.234021e-01 2.440008e-09
+
+# MODELOS LINEARES GERAIS
+# Regressão logística
+set.seed(1)
+lista1$sucesso = rbinom(length(lista1$tempo), 1, .5) # binário aleatório
+modeloLg <- glm(sucesso ~ tempo, data = lista1,
+ family=binomial(link="logit"))
+modeloLg # imprime na tela o resultado da regressão logística
+# Call: glm(formula = sucesso ~ tempo,
+# family = binomial(link = "logit"), data = lista1)
+#
+# Coefficients:
+# (Intercept) tempo
+# 0.17018 -0.01321
+#
+# Degrees of Freedom: 39 Total (i.e. Null); 38 Residual
+# Null Deviance: 55.35
+# Residual Deviance: 55.12 AIC: 59.12
+summary(modeloLg) # saída mais detalhada da regressão
+# Call:
+# glm(formula = sucesso ~ tempo,
+# family = binomial(link = "logit"), data = lista1)
+
+# Deviance Residuals:
+# Min 1Q Median 3Q Max
+# -1.245 -1.118 -1.035 1.202 1.327
+#
+# Coefficients:
+# Estimate Std. Error z value Pr(>|z|)
+# (Intercept) 0.17018 0.64621 0.263 0.792
+# tempo -0.01321 0.02757 -0.479 0.632
+#
+# (Dispersion parameter for binomial family taken to be 1)
+#
+# Null deviance: 55.352 on 39 degrees of freedom
+# Residual deviance: 55.121 on 38 degrees of freedom
+# AIC: 59.121
+#
+# Number of Fisher Scoring iterations: 3
+
+
+#########################
+# Gráficos
+#########################
+
+# FUNÇÕES DE PLOTAGEM INTEGRADAS
+# Gráficos de dispersão!
+plot(lista1$tempo, lista1$preco, main = "dados falsos")
+# Trace a linha de regressão em um gráfico existente!
+abline(modeloLinear, col = "red")
+# Obtenha uma variedade de diagnósticos legais
+plot(modeloLinear)
+# Histogramas!
+hist(rpois(n = 10000, lambda = 5), col = "thistle")
+# Gráficos de barras!
+barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow"))
+
+# GGPLOT2
+# Mas estes não são nem os mais bonitos dos gráficos no R
+# Experimente o pacote ggplot2 para gráficos diferentes e mais bonitos
+install.packages("ggplot2")
+require(ggplot2)
+?ggplot2
+pp <- ggplot(estudantes, aes(x=casa))
+pp + geom_bar()
+ll <- as.data.table(lista1)
+pp <- ggplot(ll, aes(x=tempo,preco))
+pp + geom_point()
+# ggplot2 tem uma excelente documentação (disponível em http://docs.ggplot2.org/current/)
+
+
+
+```
+
+## Como faço para obter R?
+
+* Obtenha o R e uma interface gráfica para o R em [http://www.r-project.org/](http://www.r-project.org/)
+* [RStudio](http://www.rstudio.com/ide/) é uma outra interface gráfica
diff --git a/pt-br/rust-pt.html.markdown b/pt-br/rust-pt.html.markdown
index b2bab214..3dd4a8d5 100644
--- a/pt-br/rust-pt.html.markdown
+++ b/pt-br/rust-pt.html.markdown
@@ -234,7 +234,7 @@ fn main() {
// `for` laços de repetição/iteração
let array = [1, 2, 3];
- for i in array.iter() {
+ for i in array {
println!("{}", i);
}
@@ -329,4 +329,3 @@ mais na página oficial [Rust website](http://rust-lang.org).
No Brasil acompanhe os encontros do [Meetup Rust São Paulo]
(http://www.meetup.com/pt-BR/Rust-Sao-Paulo-Meetup/).
-
diff --git a/pt-br/solidity-pt.html.markdown b/pt-br/solidity-pt.html.markdown
index d4555fa7..c77ff298 100644
--- a/pt-br/solidity-pt.html.markdown
+++ b/pt-br/solidity-pt.html.markdown
@@ -259,7 +259,7 @@ nomes.length; // pega o tamanho
nomes.length = 1; // tamanhos pode ser alterados (para arrays dinâmicos)
// arrays multidimensionais
-uint x[][5]; // array com 5 arrays dinâmicos como elementos (ordem da maioria
+uint[][5] x; // array com 5 arrays dinâmicos como elementos (ordem da maioria
// das linguagens)
// Dicionários (qualquer tipo para qualquer tipo)
diff --git a/pt-br/swift-pt.html.markdown b/pt-br/swift-pt.html.markdown
index bf410352..96b96427 100644
--- a/pt-br/swift-pt.html.markdown
+++ b/pt-br/swift-pt.html.markdown
@@ -10,7 +10,7 @@ lang: pt-br
---
-Swift é uma linguagem de programação para desenvolvimento de aplicações no iOS e OS X criada pela Apple. Criada para
+Swift é uma linguagem de programação para desenvolvimento de aplicações no iOS e macOS criada pela Apple. Criada para
coexistir com Objective-C e para ser mais resiliente a código com erros, Swift foi apresentada em 2014 na Apple's
developer conference WWDC. Foi construída com o compilador LLVM já incluído no Xcode 6 beta.
diff --git a/pt-br/typescript-pt.html.markdown b/pt-br/typescript-pt.html.markdown
index ed76959c..7d28bf53 100644
--- a/pt-br/typescript-pt.html.markdown
+++ b/pt-br/typescript-pt.html.markdown
@@ -12,7 +12,7 @@ Typescript é uma linguagem que visa facilitar o desenvolvimento de aplicações
Typescript acrescenta conceitos comuns como classes, módulos, interfaces, genéricos e (opcional) tipagem estática para JavaScript.
É um super conjunto de JavaScript: todo o código JavaScript é TypeScript válido então ele pode ser adicionado diretamente a qualquer projeto. O compilador emite TypeScript JavaScript.
-Este artigo irá se concentrar apenas na sintaxe extra do TypeScript, ao contrário de [JavaScript](javascript-pt.html.markdown).
+Este artigo irá se concentrar apenas na sintaxe extra do TypeScript, ao contrário de [JavaScript](../javascript-pt/).
Para testar o compilador TypeScript, vá para o [Playground](http://www.typescriptlang.org/Playground), onde você vai ser capaz de escrever código, ter auto conclusão e ver diretamente o JavaScript emitido.
diff --git a/pt-pt/swift-pt.html.markdown b/pt-pt/swift-pt.html.markdown
index 6b263942..a8d3e1ab 100644
--- a/pt-pt/swift-pt.html.markdown
+++ b/pt-pt/swift-pt.html.markdown
@@ -12,7 +12,7 @@ translators:
lang: pt-pt
---
-Swift é uma linguagem de programação criada pela Apple para o desenvolvimento em iOS e OS X.
+Swift é uma linguagem de programação criada pela Apple para o desenvolvimento em iOS e macOS.
Desenhada de forma a coexistir com Objective-C e ser mais resiliente contra código errôneo, a linguagem Swift foi introduzida em 2014 na conferência para desenvolvedores WWDC da Apple.
Swift usa o compilador LLVM incluido no XCode 6+.
diff --git a/pug.html.markdown b/pug.html.markdown
index 0187f1e0..1bc49f64 100644
--- a/pug.html.markdown
+++ b/pug.html.markdown
@@ -183,9 +183,9 @@ style
include styles/theme.css
//- ---MIXIN---
-mixin basic()
+mixin basic
div Hello
-+basic("Bob")
++basic
//- <div>Hello</div>
mixin comment(name, comment)
@@ -193,7 +193,11 @@ mixin comment(name, comment)
span.comment-name= name
div.comment-text= comment
+comment("Bob", "This is Awesome")
-//- <div>Hello</div>
+//-
+ <div>
+ <span class="comment-name">Bob</span>
+ <div class="comment-text">This is Awesome</div>
+ </div>
```
diff --git a/purescript.html.markdown b/purescript.html.markdown
index 6b74ac64..8cf1c1dd 100644
--- a/purescript.html.markdown
+++ b/purescript.html.markdown
@@ -1,24 +1,25 @@
---
-language: purescript
+language: PureScript
filename: purescript.purs
contributors:
- ["Fredrik Dyrkell", "http://www.lexicallyscoped.com"]
- ["Thimoteus", "https://github.com/Thimoteus"]
---
-PureScript is a small strongly, statically typed language compiling to Javascript.
+PureScript is a small strongly, statically typed language compiling to JavaScript.
-* Learn more at [http://www.purescript.org/](http://www.purescript.org/)
-* Documentation: [http://pursuit.purescript.org/](http://pursuit.purescript.org/)
-* Book: Purescript by Example, [https://leanpub.com/purescript/](https://leanpub.com/purescript/)
+* Learn more at [https://www.purescript.org/](https://www.purescript.org/)
+* Documentation: [https://pursuit.purescript.org/](https://pursuit.purescript.org/)
+* Book: Purescript by Example, [https://book.purescript.org/](https://book.purescript.org/)
-All the noncommented lines of code can be run in the PSCI REPL, though some will
-require the `--multi-line-mode` flag.
+All the noncommented lines of code can be run in the PSCi REPL, though some
+will require "paste" mode (`:paste` followed by multiple lines, terminated by
+^D).
```haskell
--
--- 1. Primitive datatypes that corresponds to their Javascript
+-- 1. Primitive datatypes that corresponds to their JavaScript
-- equivalents at runtime.
import Prelude
@@ -39,7 +40,7 @@ import Prelude
3.0 % 2.0 -- 1.0
4.0 % 2.0 -- 0.0
-- Inspect the type of an expression in psci
-:t 9.5/2.5 + 4.4 -- Prim.Number
+:t 9.5/2.5 + 4.4 -- Number
-- Booleans
true :: Boolean -- true
@@ -59,7 +60,7 @@ true && (9 >= 19 || 1 < 2) -- true
-- Strings
"Hellow" :: String -- "Hellow"
--- Multiline string without newlines, to run in psci use the --multi-line-mode flag
+-- Multiline string without newlines, to run in PSCi use "paste" mode.
"Hellow\
\orld" -- "Helloworld"
-- Multiline string with newlines
@@ -69,26 +70,26 @@ world""" -- "Hello\nworld"
"such " <> "amaze" -- "such amaze"
--
--- 2. Arrays are Javascript arrays, but must be homogeneous
+-- 2. Arrays are JavaScript arrays, but must be homogeneous
[1,1,2,3,5,8] :: Array Int -- [1,1,2,3,5,8]
[1.2,2.0,3.14] :: Array Number -- [1.2,2.0,3.14]
[true, true, false] :: Array Boolean -- [true,true,false]
-- [1,2, true, "false"] won't work
--- `Cannot unify Prim.Int with Prim.Boolean`
+-- `Cannot unify Int with Boolean`
+
+-- Requires purescript-arrays (Data.Array)
-- Cons (prepend)
1 : [2,4,3] -- [1,2,4,3]
--- Requires purescript-arrays (Data.Array)
-- and purescript-maybe (Data.Maybe)
-
-- Safe access return Maybe a
-head [1,2,3] -- Just (1)
-tail [3,2,1] -- Just ([2,1])
-init [1,2,3] -- Just ([1,2])
-last [3,2,1] -- Just (1)
+head [1,2,3] -- (Just 1)
+tail [3,2,1] -- (Just [2,1])
+init [1,2,3] -- (Just [1,2])
+last [3,2,1] -- (Just 1)
-- Array access - indexing
-[3,4,5,6,7] !! 2 -- Just (5)
+[3,4,5,6,7] !! 2 -- (Just 5)
-- Range
1..5 -- [1,2,3,4,5]
length [2,2,2] -- 3
@@ -97,31 +98,30 @@ take 3 [5,4,3,2,1] -- [5,4,3]
append [1,2,3] [4,5,6] -- [1,2,3,4,5,6]
--
--- 3. Records are Javascript objects, with zero or more fields, which
+-- 3. Records are JavaScript objects, with zero or more fields, which
-- 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"}
+book = {title: "Foucault's pendulum", author: "Umberto Eco"}
-- Access properties
book.title -- "Foucault's pendulum"
-let getTitle b = b.title
+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
-let changeTitle b t = b {title = t}
+changeTitle b t = b {title = t}
getTitle (changeTitle book "Ill nome della rosa") -- "Ill nome della rosa"
--
-- 4. Functions
--- In psci's multiline mode
-let sumOfSquares :: Int -> Int -> Int
- sumOfSquares x y = x*x + y*y
+-- In PSCi's paste mode
+sumOfSquares :: Int -> Int -> Int
+sumOfSquares x y = x*x + y*y
sumOfSquares 3 4 -- 25
-let myMod x y = x % y
+
+myMod x y = x % y
myMod 3.0 2.0 -- 1.0
-- Infix application of function
3 `mod` 2 -- 1
@@ -131,48 +131,47 @@ myMod 3.0 2.0 -- 1.0
sumOfSquares 3 4 * sumOfSquares 4 5 -- 1025
-- Conditional
-let abs' n = if n>=0 then n else -n
+abs' n = if n>=0 then n else -n
abs' (-3) -- 3
-- Guarded equations
-let abs'' n | n >= 0 = n
- | otherwise = -n
+-- In PSCi's paste mode
+abs'' n | n >= 0 = n
+ | otherwise = -n
-- Pattern matching
-- 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
+-- Requires purescript-lists (Data.List) and purescript-maybe (Data.Maybe)
+first :: forall a. List a -> Maybe a
+first (x : _) = Just x
+first Nil = Nothing
+first (fromFoldable [3,4,5]) -- (Just 3)
+
+second :: forall a. List a -> Maybe a
+second Nil = Nothing
+second (_ : Nil) = Nothing
+second (_ : (y : _)) = Just y
+second (fromFoldable [3,4,5]) -- (Just 4)
-- Complementing patterns to match
-- Good ol' Fibonacci
-let fib 1 = 1
- fib 2 = 2
- fib x = fib (x-1) + fib (x-2)
+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
-let isZero 0 = true
- isZero _ = false
+isZero 0 = true
+isZero _ = false
+isZero 9 -- false
-- Pattern matching on records
-let ecoTitle {author = "Umberto Eco", title = t} = Just t
- ecoTitle _ = Nothing
+ecoTitle {author: "Umberto Eco", title: t} = Just t
+ecoTitle _ = Nothing
-ecoTitle book -- Just ("Foucault's pendulum")
+ecoTitle {title: "Foucault's pendulum", author: "Umberto Eco"} -- (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 lacks required property "author"
@@ -180,13 +179,13 @@ 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
-let sqr = \x -> x*x
+sqr = \x -> x*x
-- Currying
-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
+myAdd x y = x + y -- is equivalent with
+myAdd' = \x -> \y -> x + y
+add3 = myAdd 3
+:t add3 -- Int -> Int
-- Forward and backward function composition
-- drop 3 followed by taking 5
@@ -195,7 +194,7 @@ let add3 = myAdd 3
(drop 3 <<< take 5) (1..20) -- [4,5]
-- Operations using higher order functions
-let even x = x `mod` 2 == 0
+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]
diff --git a/python.html.markdown b/python.html.markdown
index e21d7dde..0bd16a80 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -482,7 +482,7 @@ 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
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
@@ -735,7 +735,7 @@ class Human:
return "*grunt*"
# A property is just like a getter.
- # It turns the method age() into an read-only attribute of the same name.
+ # It turns the method age() into a read-only attribute of the same name.
# There's no need to write trivial getters and setters in Python, though.
@property
def age(self):
@@ -1032,6 +1032,7 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
* [The Official Docs](https://docs.python.org/3/)
* [Hitchhiker's Guide to Python](https://docs.python-guide.org/en/latest/)
* [Python Course](https://www.python-course.eu)
+* [Free Interactive Python Course](http://www.Kikodo.io)
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
* [30 Python Language Features and Tricks You May Not Know About](https://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
diff --git a/qsharp.html.markdown b/qsharp.html.markdown
index b256043c..10015d7f 100644
--- a/qsharp.html.markdown
+++ b/qsharp.html.markdown
@@ -29,10 +29,10 @@ using (qs = Qubit[2]) {
// If you want to change the state of a qubit
// you have to do this by applying quantum gates to the qubit.
- H(q[0]); // This changes the state of the first qubit
+ H(qs[0]); // This changes the state of the first qubit
// from |0⟩ (the initial state of allocated qubits)
// to (|0⟩ + |1⟩) / sqrt(2).
- // q[1] = |1⟩; - this does NOT work, you have to manipulate a qubit by using gates.
+ // qs[1] = |1⟩; - this does NOT work, you have to manipulate a qubit by using gates.
// You can apply multi-qubit gates to several qubits.
CNOT(qs[0], qs[1]);
diff --git a/r.html.markdown b/r.html.markdown
index 2aedf625..2746d1eb 100644
--- a/r.html.markdown
+++ b/r.html.markdown
@@ -4,6 +4,7 @@ contributors:
- ["e99n09", "http://github.com/e99n09"]
- ["isomorphismes", "http://twitter.com/isomorphisms"]
- ["kalinn", "http://github.com/kalinn"]
+ - ["mribeirodantas", "http://github.com/mribeirodantas"]
filename: learnr.r
---
@@ -29,13 +30,13 @@ R is a statistical computing language. It has lots of libraries for uploading an
# R without understanding anything about programming. Do not worry
# about understanding everything the code does. Just enjoy!
-data() # browse pre-loaded data sets
-data(rivers) # get this one: "Lengths of Major North American Rivers"
-ls() # notice that "rivers" now appears in the workspace
-head(rivers) # peek at the data set
+data() # browse pre-loaded data sets
+data(rivers) # get this one: "Lengths of Major North American Rivers"
+ls() # notice that "rivers" now appears in the workspace
+head(rivers) # peek at the data set
# 735 320 325 392 524 450
-length(rivers) # how many rivers were measured?
+length(rivers) # how many rivers were measured?
# 141
summary(rivers) # what are some summary statistics?
# Min. 1st Qu. Median Mean 3rd Qu. Max.
@@ -91,14 +92,15 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
# 82 | 2
# make a histogram:
-hist(rivers, col="#333333", border="white", breaks=25) # play around with these parameters
-hist(log(rivers), col="#333333", border="white", breaks=25) # you'll do more plotting later
+hist(rivers, col = "#333333", border = "white", breaks = 25)
+hist(log(rivers), col = "#333333", border = "white", breaks = 25)
+# play around with these parameters, you'll do more plotting later
# Here's another neat data set that comes pre-loaded. R has tons of these.
data(discoveries)
-plot(discoveries, col="#333333", lwd=3, xlab="Year",
+plot(discoveries, col = "#333333", lwd = 3, xlab = "Year",
main="Number of important discoveries per year")
-plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year",
+plot(discoveries, col = "#333333", lwd = 3, type = "h", xlab = "Year",
main="Number of important discoveries per year")
# Rather than leaving the default ordering (by year),
@@ -109,7 +111,7 @@ sort(discoveries)
# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4
# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12
-stem(discoveries, scale=2)
+stem(discoveries, scale = 2)
#
# The decimal point is at the |
#
@@ -134,7 +136,7 @@ summary(discoveries)
# 0.0 2.0 3.0 3.1 4.0 12.0
# Roll a die a few times
-round(runif(7, min=.5, max=6.5))
+round(runif(7, min = .5, max = 6.5))
# 1 4 6 1 4 6 4
# Your numbers will differ from mine unless we set the same random.seed(31337)
@@ -157,69 +159,68 @@ rnorm(9)
# INTEGERS
# Long-storage integers are written with L
-5L # 5
-class(5L) # "integer"
+5L # 5
+class(5L) # "integer"
# (Try ?class for more information on the class() function.)
# In R, every single value, like 5L, is considered a vector of length 1
-length(5L) # 1
+length(5L) # 1
# You can have an integer vector with length > 1 too:
-c(4L, 5L, 8L, 3L) # 4 5 8 3
-length(c(4L, 5L, 8L, 3L)) # 4
-class(c(4L, 5L, 8L, 3L)) # "integer"
+c(4L, 5L, 8L, 3L) # 4 5 8 3
+length(c(4L, 5L, 8L, 3L)) # 4
+class(c(4L, 5L, 8L, 3L)) # "integer"
# NUMERICS
# A "numeric" is a double-precision floating-point number
-5 # 5
-class(5) # "numeric"
+5 # 5
+class(5) # "numeric"
# Again, everything in R is a vector;
# you can make a numeric vector with more than one element
-c(3,3,3,2,2,1) # 3 3 3 2 2 1
+c(3, 3, 3, 2, 2, 1) # 3 3 3 2 2 1
# You can use scientific notation too
-5e4 # 50000
-6.02e23 # Avogadro's number
-1.6e-35 # Planck length
+5e4 # 50000
+6.02e23 # Avogadro's number
+1.6e-35 # Planck length
# You can also have infinitely large or small numbers
-class(Inf) # "numeric"
-class(-Inf) # "numeric"
+class(Inf) # "numeric"
+class(-Inf) # "numeric"
# You might use "Inf", for example, in integrate(dnorm, 3, Inf);
# this obviates Z-score tables.
# BASIC ARITHMETIC
# You can do arithmetic with numbers
# Doing arithmetic on a mix of integers and numerics gives you another numeric
-10L + 66L # 76 # integer plus integer gives integer
-53.2 - 4 # 49.2 # numeric minus numeric gives numeric
-2.0 * 2L # 4 # numeric times integer gives numeric
-3L / 4 # 0.75 # integer over numeric gives numeric
-3 %% 2 # 1 # the remainder of two numerics is another numeric
+10L + 66L # 76 # integer plus integer gives integer
+53.2 - 4 # 49.2 # numeric minus numeric gives numeric
+2.0 * 2L # 4 # numeric times integer gives numeric
+3L / 4 # 0.75 # integer over numeric gives numeric
+3 %% 2 # 1 # the remainder of two numerics is another numeric
# Illegal arithmetic yields you a "not-a-number":
-0 / 0 # NaN
-class(NaN) # "numeric"
+0 / 0 # NaN
+class(NaN) # "numeric"
# You can do arithmetic on two vectors with length greater than 1,
# so long as the larger vector's length is an integer multiple of the smaller
-c(1,2,3) + c(1,2,3) # 2 4 6
+c(1, 2, 3) + c(1, 2, 3) # 2 4 6
# Since a single number is a vector of length one, scalars are applied
# elementwise to vectors
-(4 * c(1,2,3) - 2) / 2 # 1 3 5
+(4 * c(1, 2, 3) - 2) / 2 # 1 3 5
# Except for scalars, use caution when performing arithmetic on vectors with
# different lengths. Although it can be done,
-c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6
-# Matching lengths is better practice and easier to read
-c(1,2,3,1,2,3) * c(1,2,1,2,1,2)
+c(1, 2, 3, 1, 2, 3) * c(1, 2) # 1 4 3 2 2 6
+# Matching lengths is better practice and easier to read most times
+c(1, 2, 3, 1, 2, 3) * c(1, 2, 1, 2, 1, 2) # 1 4 3 2 2 6
# CHARACTERS
# There's no difference between strings and characters in R
-"Horatio" # "Horatio"
-class("Horatio") # "character"
-class("H") # "character"
+"Horatio" # "Horatio"
+class("Horatio") # "character"
+class("H") # "character"
# Those were both character vectors of length 1
# Here is a longer one:
c("alef", "bet", "gimmel", "dalet", "he")
-# =>
-# "alef" "bet" "gimmel" "dalet" "he"
+# => "alef" "bet" "gimmel" "dalet" "he"
length(c("Call","me","Ishmael")) # 3
# You can do regex operations on character vectors:
-substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis "
+substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis "
gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis."
# R has several built-in character vectors:
letters
@@ -230,64 +231,61 @@ month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "D
# LOGICALS
# In R, a "logical" is a boolean
-class(TRUE) # "logical"
-class(FALSE) # "logical"
+
+class(TRUE) # "logical"
+class(FALSE) # "logical"
# Their behavior is normal
-TRUE == TRUE # TRUE
-TRUE == FALSE # FALSE
-FALSE != FALSE # FALSE
-FALSE != TRUE # TRUE
+TRUE == TRUE # TRUE
+TRUE == FALSE # FALSE
+FALSE != FALSE # FALSE
+FALSE != TRUE # TRUE
# Missing data (NA) is logical, too
-class(NA) # "logical"
+class(NA) # "logical"
# Use | and & for logic operations.
# OR
-TRUE | FALSE # TRUE
+TRUE | FALSE # TRUE
# AND
-TRUE & FALSE # FALSE
+TRUE & FALSE # FALSE
# Applying | and & to vectors returns elementwise logic operations
-c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE
-c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE
+c(TRUE, FALSE, FALSE) | c(FALSE, TRUE, FALSE) # TRUE TRUE FALSE
+c(TRUE, FALSE, TRUE) & c(FALSE, TRUE, TRUE) # FALSE FALSE TRUE
# You can test if x is TRUE
-isTRUE(TRUE) # TRUE
+isTRUE(TRUE) # TRUE
# Here we get a logical vector with many elements:
-c("Z", "o", "r", "r", "o") == "Zorro" # FALSE FALSE FALSE FALSE FALSE
-c("Z", "o", "r", "r", "o") == "Z" # TRUE FALSE FALSE FALSE FALSE
+c("Z", "o", "r", "r", "o") == "Zorro" # FALSE FALSE FALSE FALSE FALSE
+c("Z", "o", "r", "r", "o") == "Z" # TRUE FALSE FALSE FALSE FALSE
# FACTORS
# The factor class is for categorical data
-# Factors can be ordered (like childrens' grade levels) or unordered (like gender)
-factor(c("female", "female", "male", NA, "female"))
-# female female male <NA> female
-# Levels: female male
+# Factors can be ordered (like grade levels) or unordered (like colors)
+factor(c("blue", "blue", "green", NA, "blue"))
+# blue blue green <NA> blue
+# Levels: blue green
# The "levels" are the values the categorical data can take
# Note that missing data does not enter the levels
-levels(factor(c("male", "male", "female", NA, "female"))) # "female" "male"
+levels(factor(c("green", "green", "blue", NA, "blue"))) # "blue" "green"
# If a factor vector has length 1, its levels will have length 1, too
-length(factor("male")) # 1
-length(levels(factor("male"))) # 1
+length(factor("green")) # 1
+length(levels(factor("green"))) # 1
# Factors are commonly seen in data frames, a data structure we will cover later
-data(infert) # "Infertility after Spontaneous and Induced Abortion"
+data(infert) # "Infertility after Spontaneous and Induced Abortion"
levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs"
# NULL
# "NULL" is a weird one; use it to "blank out" a vector
-class(NULL) # NULL
+class(NULL) # NULL
parakeet = c("beak", "feathers", "wings", "eyes")
-parakeet
-# =>
-# [1] "beak" "feathers" "wings" "eyes"
+parakeet # "beak" "feathers" "wings" "eyes"
parakeet <- NULL
-parakeet
-# =>
-# NULL
+parakeet # NULL
# TYPE COERCION
# Type-coercion is when you force a value to take on a different type
-as.character(c(6, 8)) # "6" "8"
-as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE
+as.character(c(6, 8)) # "6" "8"
+as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE
# If you put elements of different types into a vector, weird coercions happen:
-c(TRUE, 4) # 1 4
-c("dog", TRUE, 4) # "dog" "TRUE" "4"
+c(TRUE, 4) # 1 4
+c("dog", TRUE, 4) # "dog" "TRUE" "4"
as.numeric("Bilbo")
# =>
# [1] NA
@@ -309,14 +307,15 @@ as.numeric("Bilbo")
# VARIABLES
# Lots of way to assign stuff:
-x = 5 # this is possible
-y <- "1" # this is preferred
-TRUE -> z # this works but is weird
+x = 5 # this is possible
+y <- "1" # this is preferred traditionally
+TRUE -> z # this works but is weird
+# Refer to the Internet for the behaviors and preferences about them.
# LOOPS
# We've got for loops
for (i in 1:4) {
- print(i)
+ print(i)
}
# We've got while loops
a <- 10
@@ -341,11 +340,11 @@ if (4 > 3) {
# FUNCTIONS
# Defined like so:
jiggle <- function(x) {
- x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise
+ x = x + rnorm(1, sd=.1) # add in a bit of (controlled) noise
return(x)
}
# Called like any other R function:
-jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043
+jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043
@@ -357,39 +356,39 @@ jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043
# Let's start from the very beginning, and with something you already know: vectors.
vec <- c(8, 9, 10, 11)
-vec # 8 9 10 11
+vec # 8 9 10 11
# We ask for specific elements by subsetting with square brackets
# (Note that R starts counting from 1)
-vec[1] # 8
-letters[18] # "r"
-LETTERS[13] # "M"
-month.name[9] # "September"
-c(6, 8, 7, 5, 3, 0, 9)[3] # 7
+vec[1] # 8
+letters[18] # "r"
+LETTERS[13] # "M"
+month.name[9] # "September"
+c(6, 8, 7, 5, 3, 0, 9)[3] # 7
# We can also search for the indices of specific components,
-which(vec %% 2 == 0) # 1 3
+which(vec %% 2 == 0) # 1 3
# grab just the first or last few entries in the vector,
-head(vec, 1) # 8
-tail(vec, 2) # 10 11
+head(vec, 1) # 8
+tail(vec, 2) # 10 11
# or figure out if a certain value is in the vector
-any(vec == 10) # TRUE
+any(vec == 10) # TRUE
# If an index "goes over" you'll get NA:
-vec[6] # NA
+vec[6] # NA
# You can find the length of your vector with length()
-length(vec) # 4
+length(vec) # 4
# You can perform operations on entire vectors or subsets of vectors
-vec * 4 # 16 20 24 28
-vec[2:3] * 5 # 25 30
-any(vec[2:3] == 8) # FALSE
+vec * 4 # 32 36 40 44
+vec[2:3] * 5 # 45 50
+any(vec[2:3] == 8) # FALSE
# and R has many built-in functions to summarize vectors
-mean(vec) # 9.5
-var(vec) # 1.666667
-sd(vec) # 1.290994
-max(vec) # 11
-min(vec) # 8
-sum(vec) # 38
+mean(vec) # 9.5
+var(vec) # 1.666667
+sd(vec) # 1.290994
+max(vec) # 11
+min(vec) # 8
+sum(vec) # 38
# Some more nice built-ins:
-5:15 # 5 6 7 8 9 10 11 12 13 14 15
-seq(from=0, to=31337, by=1337)
+5:15 # 5 6 7 8 9 10 11 12 13 14 15
+seq(from = 0, to = 31337, by = 1337)
# =>
# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707
# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751
@@ -397,7 +396,7 @@ seq(from=0, to=31337, by=1337)
# TWO-DIMENSIONAL (ALL ONE CLASS)
# You can make a matrix out of entries all of the same type like so:
-mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6))
+mat <- matrix(nrow = 3, ncol = 2, c(1, 2, 3, 4, 5, 6))
mat
# =>
# [,1] [,2]
@@ -405,13 +404,13 @@ mat
# [2,] 2 5
# [3,] 3 6
# Unlike a vector, the class of a matrix is "matrix", no matter what's in it
-class(mat) # => "matrix"
+class(mat) # "matrix" "array"
# Ask for the first row
-mat[1,] # 1 4
+mat[1, ] # 1 4
# Perform operation on the first column
-3 * mat[,1] # 3 6 9
+3 * mat[, 1] # 3 6 9
# Ask for a specific cell
-mat[3,2] # 6
+mat[3, 2] # 6
# Transpose the whole matrix
t(mat)
@@ -437,14 +436,14 @@ mat2
# [2,] "2" "cat"
# [3,] "3" "bird"
# [4,] "4" "dog"
-class(mat2) # matrix
+class(mat2) # matrix
# Again, note what happened!
# Because matrices must contain entries all of the same class,
# everything got converted to the character class
-c(class(mat2[,1]), class(mat2[,2]))
+c(class(mat2[, 1]), class(mat2[, 2]))
# rbind() sticks vectors together row-wise to make a matrix
-mat3 <- rbind(c(1,2,4,5), c(6,7,0,4))
+mat3 <- rbind(c(1, 2, 4, 5), c(6, 7, 0, 4))
mat3
# =>
# [,1] [,2] [,3] [,4]
@@ -458,11 +457,11 @@ mat3
# This data structure is so useful for statistical programming,
# a version of it was added to Python in the package "pandas".
-students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"),
- c(3,2,2,1,0,-1),
- c("H", "G", "G", "R", "S", "G"))
+students <- data.frame(c("Cedric", "Fred", "George", "Cho", "Draco", "Ginny"),
+ c( 3, 2, 2, 1, 0, -1),
+ c( "H", "G", "G", "R", "S", "G"))
names(students) <- c("name", "year", "house") # name the columns
-class(students) # "data.frame"
+class(students) # "data.frame"
students
# =>
# name year house
@@ -472,21 +471,22 @@ students
# 4 Cho 1 R
# 5 Draco 0 S
# 6 Ginny -1 G
-class(students$year) # "numeric"
-class(students[,3]) # "factor"
+class(students$year) # "numeric"
+class(students[,3]) # "factor"
# find the dimensions
-nrow(students) # 6
-ncol(students) # 3
-dim(students) # 6 3
-# The data.frame() function converts character vectors to factor vectors
-# by default; turn this off by setting stringsAsFactors = FALSE when
-# you create the data.frame
+nrow(students) # 6
+ncol(students) # 3
+dim(students) # 6 3
+# The data.frame() function used to convert character vectors to factor
+# vectors by default; This has changed in R 4.0.0. If your R version is
+# older, turn this off by setting stringsAsFactors = FALSE when you
+# create the data.frame
?data.frame
# There are many twisty ways to subset data frames, all subtly unalike
-students$year # 3 2 2 1 0 -1
-students[,2] # 3 2 2 1 0 -1
-students[,"year"] # 3 2 2 1 0 -1
+students$year # 3 2 2 1 0 -1
+students[, 2] # 3 2 2 1 0 -1
+students[, "year"] # 3 2 2 1 0 -1
# An augmented version of the data.frame structure is the data.table
# If you're working with huge or panel data, or need to merge a few data
@@ -503,19 +503,19 @@ students # note the slightly different print-out
# 4: Cho 1 R
# 5: Draco 0 S
# 6: Ginny -1 G
-students[name=="Ginny"] # get rows with name == "Ginny"
+students[name == "Ginny"] # get rows with name == "Ginny"
# =>
# name year house
# 1: Ginny -1 G
-students[year==2] # get rows with year == 2
+students[year == 2] # get rows with year == 2
# =>
# name year house
# 1: Fred 2 G
# 2: George 2 G
# data.table makes merging two data sets easy
# let's make another data.table to merge with students
-founders <- data.table(house=c("G","H","R","S"),
- founder=c("Godric","Helga","Rowena","Salazar"))
+founders <- data.table(house = c("G" , "H" , "R" , "S"),
+ founder = c("Godric", "Helga", "Rowena", "Salazar"))
founders
# =>
# house founder
@@ -526,8 +526,8 @@ founders
setkey(students, house)
setkey(founders, house)
students <- founders[students] # merge the two data sets by matching "house"
-setnames(students, c("house","houseFounderName","studentName","year"))
-students[,order(c("name","year","house","houseFounderName")), with=F]
+setnames(students, c("house", "houseFounderName", "studentName", "year"))
+students[, order(c("name", "year", "house", "houseFounderName")), with = F]
# =>
# studentName year house houseFounderName
# 1: Fred 2 G Godric
@@ -538,7 +538,7 @@ students[,order(c("name","year","house","houseFounderName")), with=F]
# 6: Draco 0 S Salazar
# data.table makes summary tables easy
-students[,sum(year),by=house]
+students[, sum(year), by = house]
# =>
# house V1
# 1: G 3
@@ -571,7 +571,7 @@ students[studentName != "Draco"]
# 5: R Cho 1
# Using data.frame:
students <- as.data.frame(students)
-students[students$house != "G",]
+students[students$house != "G", ]
# =>
# house houseFounderName studentName year
# 4 H Helga Cedric 3
@@ -583,13 +583,13 @@ students[students$house != "G",]
# Arrays creates n-dimensional tables
# All elements must be of the same type
# You can make a two-dimensional table (sort of like a matrix)
-array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4))
+array(c(c(1, 2, 4, 5), c(8, 9, 3, 6)), dim = c(2, 4))
# =>
# [,1] [,2] [,3] [,4]
# [1,] 1 4 8 3
# [2,] 2 5 9 6
# You can use array to make three-dimensional matrices too
-array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2))
+array(c(c(c(2, 300, 4), c(8, 9, 0)), c(c(5, 60, 0), c(66, 7, 847))), dim = c(3, 2, 2))
# =>
# , , 1
#
@@ -609,7 +609,7 @@ array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2))
# Finally, R has lists (of vectors)
list1 <- list(time = 1:40)
-list1$price = c(rnorm(40,.5*list1$time,4)) # random
+list1$price = c(rnorm(40, .5*list1$time, 4)) # random
list1
# You can get items in the list like so
list1$time # one way
@@ -682,7 +682,7 @@ write.csv(pets, "pets2.csv") # to make a new .csv file
#########################
# Linear regression!
-linearModel <- lm(price ~ time, data = list1)
+linearModel <- lm(price ~ time, data = list1)
linearModel # outputs result of regression
# =>
# Call:
@@ -719,7 +719,7 @@ summary(linearModel)$coefficients # another way to extract results
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01
# time 0.4943490 0.06379348 7.74920901 2.440008e-09
-summary(linearModel)$coefficients[,4] # the p-values
+summary(linearModel)$coefficients[, 4] # the p-values
# =>
# (Intercept) time
# 9.234021e-01 2.440008e-09
@@ -728,8 +728,7 @@ summary(linearModel)$coefficients[,4] # the p-values
# Logistic regression
set.seed(1)
list1$success = rbinom(length(list1$time), 1, .5) # random binary
-glModel <- glm(success ~ time, data = list1,
- family=binomial(link="logit"))
+glModel <- glm(success ~ time, data = list1, family=binomial(link="logit"))
glModel # outputs result of logistic regression
# =>
# Call: glm(formula = success ~ time,
@@ -745,8 +744,10 @@ glModel # outputs result of logistic regression
summary(glModel) # more verbose output from the regression
# =>
# Call:
-# glm(formula = success ~ time,
-# family = binomial(link = "logit"), data = list1)
+# glm(
+# formula = success ~ time,
+# family = binomial(link = "logit"),
+# data = list1)
# Deviance Residuals:
# Min 1Q Median 3Q Max
@@ -780,7 +781,7 @@ plot(linearModel)
# Histograms!
hist(rpois(n = 10000, lambda = 5), col = "thistle")
# Barplots!
-barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow"))
+barplot(c(1, 4, 5, 1, 2), names.arg = c("red", "blue", "purple", "green", "yellow"))
# GGPLOT2
# But these are not even the prettiest of R's plots
@@ -788,10 +789,10 @@ barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow"))
install.packages("ggplot2")
require(ggplot2)
?ggplot2
-pp <- ggplot(students, aes(x=house))
+pp <- ggplot(students, aes(x = house))
pp + geom_bar()
ll <- as.data.table(list1)
-pp <- ggplot(ll, aes(x=time,price))
+pp <- ggplot(ll, aes(x = time, price))
pp + geom_point()
# ggplot2 has excellent documentation (available http://docs.ggplot2.org/current/)
diff --git a/racket.html.markdown b/racket.html.markdown
index 60a895e0..6c40c3c8 100644
--- a/racket.html.markdown
+++ b/racket.html.markdown
@@ -117,16 +117,16 @@ some-var ; => 5
;; let* is like let, but allows you to use previous bindings in creating later bindings
(let* ([x 1]
[y (+ x 1)])
- (* x y))
+ (* x y))
;; finally, letrec allows you to define recursive and mutually recursive functions
(letrec ([is-even? (lambda (n)
- (or (zero? n)
- (is-odd? (sub1 n))))]
- [is-odd? (lambda (n)
- (and (not (zero? n))
- (is-even? (sub1 n))))])
- (is-odd? 11))
+ (or (zero? n)
+ (is-odd? (sub1 n))))]
+ [is-odd? (lambda (n)
+ (and (not (zero? n))
+ (is-even? (sub1 n))))])
+ (is-odd? 11))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 3. Structs and Collections
@@ -413,7 +413,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d'
(loop 5) ; => i=5, i=6, ...
;; Similarly, with a named let
-(let loop ((i 0))
+(let loop ([i 0])
(when (< i 10)
(printf "i=~a\n" i)
(loop (add1 i)))) ; => i=0, i=1, ...
@@ -441,17 +441,19 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d'
(for ([i (in-set (set 'x 'y 'z))])
(displayln i))
-(for ([(k v) (in-hash (hash 'a 1 'b 2 'c 3 ))])
+(for ([(k v) (in-hash (hash 'a 1 'b 2 'c 3))])
(printf "key:~a value:~a\n" k v))
;;; More Complex Iterations
;; Parallel scan of multiple sequences (stops on shortest)
-(for ([i 10] [j '(x y z)]) (printf "~a:~a\n" i j))
+(for ([i 10] [j '(x y z)])
+ (printf "~a:~a\n" i j))
; => 0:x 1:y 2:z
;; Nested loops
-(for* ([i 2] [j '(x y z)]) (printf "~a:~a\n" i j))
+(for* ([i 2] [j '(x y z)])
+ (printf "~a:~a\n" i j))
; => 0:x, 0:y, 0:z, 1:x, 1:y, 1:z
;; Conditions
@@ -663,8 +665,7 @@ vec ; => #(1 2 3 4)
(define amount 0)
(define (deposit a) (set! amount (+ amount a)))
- (define (balance) amount)
- )
+ (define (balance) amount))
(require 'bank-account)
(deposit 5)
diff --git a/raku.html.markdown b/raku.html.markdown
index 16035615..a8059791 100644
--- a/raku.html.markdown
+++ b/raku.html.markdown
@@ -116,12 +116,10 @@ say @array; # OUTPUT: «a 6 b␤»
# 1.3 Hashes, or key-value Pairs.
#
-=begin comment
-Hashes are pairs of keys and values. You can construct a `Pair` object
-using the syntax `key => value`. Hash tables are very fast for lookup,
-and are stored unordered. Keep in mind that keys get "flattened" in hash
-context, and any duplicated keys are deduplicated.
-=end comment
+# Hashes are pairs of keys and values. You can construct a `Pair` object
+# using the syntax `key => value`. Hash tables are very fast for lookup,
+# and are stored unordered. Keep in mind that keys get "flattened" in hash
+# context, and any duplicated keys are deduplicated.
my %hash = 'a' => 1, 'b' => 2;
# Keys get auto-quoted when the fat comman (`=>`) is used. Trailing commas are
@@ -144,12 +142,10 @@ my %hash = 'a' => 1, 'b' => 2;
# The `:` (as in `:is-even`) and `:!` (as `:!is-odd`) constructs are known
# as the `True` and `False` shortcuts respectively.
-=begin comment
-As demonstrated in the example below, you can use {} to get the value from a key.
-If it's a string without spaces, you can actually use the quote-words operator
-(`<>`). Since Raku doesn't have barewords, as Perl does, `{key1}` doesn't work
-though.
-=end comment
+# As demonstrated in the example below, you can use {} to get the value from a key.
+# If it's a string without spaces, you can actually use the quote-words operator
+# (`<>`). Since Raku doesn't have barewords, as Perl does, `{key1}` doesn't work
+# though.
say %hash{'n'}; # OUTPUT: «2␤», gets value associated to key 'n'
say %hash<is-even>; # OUTPUT: «True␤», gets value associated to key 'is-even'
@@ -187,13 +183,11 @@ sub return-for {
}
say return-for; # OUTPUT: «Nil␤»
-=begin comment
-Positional arguments are required by default. To make them optional, use
-the `?` after the parameters' names.
+# Positional arguments are required by default. To make them optional, use
+# the `?` after the parameters' names.
-In the following example, the sub `with-optional` returns `(Any)` (Perl's
-null-like value) if no argument is passed. Otherwise, it returns its argument.
-=end comment
+# In the following example, the sub `with-optional` returns `(Any)` (Perl's
+# null-like value) if no argument is passed. Otherwise, it returns its argument.
sub with-optional( $arg? ) {
$arg;
}
@@ -201,13 +195,11 @@ with-optional; # returns Any
with-optional(); # returns Any
with-optional(1); # returns 1
-=begin comment
-You can also give provide a default value when they're not passed. Doing
-this make said parameter optional. Required parameters must come before
-optional ones.
+# You can also give provide a default value when they're not passed. Doing
+# this make said parameter optional. Required parameters must come before
+# optional ones.
-In the sub `greeting`, the parameter `$type` is optional.
-=end comment
+# In the sub `greeting`, the parameter `$type` is optional.
sub greeting( $name, $type = "Hello" ) {
say "$type, $name!";
}
@@ -215,22 +207,18 @@ sub greeting( $name, $type = "Hello" ) {
greeting("Althea"); # OUTPUT: «Hello, Althea!␤»
greeting("Arthur", "Good morning"); # OUTPUT: «Good morning, Arthur!␤»
-=begin comment
-You can also, by using a syntax akin to the one of hashes (yay unified syntax!),
-declared named parameters and thus pass named arguments to a subroutine.
-By default, named parameter are optional and will default to `Any`.
-=end comment
+# You can also, by using a syntax akin to the one of hashes (yay unified syntax!),
+# declared named parameters and thus pass named arguments to a subroutine.
+# By default, named parameter are optional and will default to `Any`.
sub with-named( $normal-arg, :$named ) {
say $normal-arg + $named;
}
with-named(1, named => 6); # OUTPUT: «7␤»
-=begin comment
-There's one gotcha to be aware of, here: If you quote your key, Raku
-won't be able to see it at compile time, and you'll have a single `Pair`
-object as a positional parameter, which means the function subroutine
-`with-named(1, 'named' => 6);` fails.
-=end comment
+# There's one gotcha to be aware of, here: If you quote your key, Raku
+# won't be able to see it at compile time, and you'll have a single `Pair`
+# object as a positional parameter, which means the function subroutine
+# `with-named(1, 'named' => 6);` fails.
with-named(2, :named(5)); # OUTPUT: «7␤»
# Similar to positional parameters, you can provide your named arguments with
@@ -241,11 +229,9 @@ sub named-def( :$def = 5 ) {
named-def; # OUTPUT: «5»
named-def(def => 15); # OUTPUT: «15»
-=begin comment
-In order to make a named parameter mandatory, you can append `!` to the
-parameter. This is the inverse of `?`, which makes a required parameter
-optional.
-=end comment
+# In order to make a named parameter mandatory, you can append `!` to the
+# parameter. This is the inverse of `?`, which makes a required parameter
+# optional.
sub with-mandatory-named( :$str! ) {
say "$str!";
@@ -254,33 +240,27 @@ with-mandatory-named(str => "My String"); # OUTPUT: «My String!␤»
# with-mandatory-named; # runtime error: "Required named parameter not passed"
# with-mandatory-named(3);# runtime error: "Too many positional parameters passed"
-=begin comment
-If a sub takes a named boolean argument, you can use the same "short boolean"
-hash syntax we discussed earlier.
-=end comment
+# If a sub takes a named boolean argument, you can use the same "short boolean"
+# hash syntax we discussed earlier.
sub takes-a-bool( $name, :$bool ) {
say "$name takes $bool";
}
takes-a-bool('config', :bool); # OUTPUT: «config takes True␤»
takes-a-bool('config', :!bool); # OUTPUT: «config takes False␤»
-=begin comment
-Since parenthesis can be omitted when calling a subroutine, you need to use
-`&` in order to distinguish between a call to a sub with no arguments and
-the code object.
+# Since parenthesis can be omitted when calling a subroutine, you need to use
+# `&` in order to distinguish between a call to a sub with no arguments and
+# the code object.
-For instance, in this example we must use `&` to store the sub `say-hello`
-(i.e., the sub's code object) in a variable, not a subroutine call.
-=end comment
+# For instance, in this example we must use `&` to store the sub `say-hello`
+# (i.e., the sub's code object) in a variable, not a subroutine call.
my &s = &say-hello;
my &other-s = sub { say "Anonymous function!" }
-=begin comment
-A sub can have a "slurpy" parameter, or what one'd call a
-"doesn't-matter-how-many" parameter. This is Raku's way of supporting variadic
-functions. For this, you must use `*@` (slurpy) which will "take everything
-else". You can have as many parameters *before* a slurpy one, but not *after*.
-=end comment
+# A sub can have a "slurpy" parameter, or what one'd call a
+# "doesn't-matter-how-many" parameter. This is Raku's way of supporting variadic
+# functions. For this, you must use `*@` (slurpy) which will "take everything
+# else". You can have as many parameters *before* a slurpy one, but not *after*.
sub as-many($head, *@rest) {
@rest.join(' / ') ~ " !";
}
@@ -289,35 +269,29 @@ say as-many('Happy', ['Happy', 'Birthday'], 'Day'); # OUTPUT: «Happy / Birthday
# Note that the splat (the *) did not consume the parameter before it.
-=begin comment
-There are other two variations of slurpy parameters in Raku. The previous one
-(namely, `*@`), known as flattened slurpy, flattens passed arguments. The other
-two are `**@` and `+@` known as unflattened slurpy and "single argument rule"
-slurpy respectively. The unflattened slurpy doesn't flatten its listy
-arguments (or Iterable ones).
-=end comment
+# There are other two variations of slurpy parameters in Raku. The previous one
+# (namely, `*@`), known as flattened slurpy, flattens passed arguments. The other
+# two are `**@` and `+@` known as unflattened slurpy and "single argument rule"
+# slurpy respectively. The unflattened slurpy doesn't flatten its listy
+# arguments (or Iterable ones).
sub b(**@arr) { @arr.perl.say };
b(['a', 'b', 'c']); # OUTPUT: «[["a", "b", "c"],]»
b(1, $('d', 'e', 'f'), [2, 3]); # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]»
b(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤»
-=begin comment
-On the other hand, the "single argument rule" slurpy follows the "single argument
-rule" which dictates how to handle the slurpy argument based upon context and
-roughly states that if only a single argument is passed and that argument is
-Iterable, that argument is used to fill the slurpy parameter array. In any
-other case, `+@` works like `**@`.
-=end comment
+# On the other hand, the "single argument rule" slurpy follows the "single argument
+# rule" which dictates how to handle the slurpy argument based upon context and
+# roughly states that if only a single argument is passed and that argument is
+# Iterable, that argument is used to fill the slurpy parameter array. In any
+# other case, `+@` works like `**@`.
sub c(+@arr) { @arr.perl.say };
c(['a', 'b', 'c']); # OUTPUT: «["a", "b", "c"]␤»
c(1, $('d', 'e', 'f'), [2, 3]); # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]␤»
c(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤»
-=begin comment
-You can call a function with an array using the "argument list flattening"
-operator `|` (it's not actually the only role of this operator,
-but it's one of them).
-=end comment
+# You can call a function with an array using the "argument list flattening"
+# operator `|` (it's not actually the only role of this operator,
+# but it's one of them).
sub concat3($a, $b, $c) {
say "$a, $b, $c";
}
@@ -328,14 +302,12 @@ concat3(|@array); # OUTPUT: «a, b, c␤»
# 3. Containers
####################################################
-=begin comment
-In Raku, values are actually stored in "containers". The assignment
-operator asks the container on the left to store the value on its right.
-When passed around, containers are marked as immutable which means that,
-in a function, you'll get an error if you try to mutate one of your
-arguments. If you really need to, you can ask for a mutable container by
-using the `is rw` trait.
-=end comment
+# In Raku, values are actually stored in "containers". The assignment
+# operator asks the container on the left to store the value on its right.
+# When passed around, containers are marked as immutable which means that,
+# in a function, you'll get an error if you try to mutate one of your
+# arguments. If you really need to, you can ask for a mutable container by
+# using the `is rw` trait.
sub mutate( $n is rw ) {
$n++; # postfix ++ operator increments its argument but returns its old value
}
@@ -343,32 +315,26 @@ my $m = 42;
mutate $m; #=> 42, the value is incremented but the old value is returned
say $m; # OUTPUT: «43␤»
-=begin comment
-This works because we are passing the container $m to the `mutate` sub.
-If we try to just pass a number instead of passing a variable, it won't work
-because there is no container being passed and integers are immutable by
-themselves:
+# This works because we are passing the container $m to the `mutate` sub.
+# If we try to just pass a number instead of passing a variable, it won't work
+# because there is no container being passed and integers are immutable by
+# themselves:
-mutate 42; # Parameter '$n' expected a writable container, but got Int value
-=end comment
+# mutate 42; # Parameter '$n' expected a writable container, but got Int value
-=begin comment
-Similar error would be obtained, if a bound variable is passed to
-to the subroutine. In Raku, you bind a value to a variable using the binding
-operator `:=`.
-=end comment
+# Similar error would be obtained, if a bound variable is passed to
+# to the subroutine. In Raku, you bind a value to a variable using the binding
+# operator `:=`.
my $v := 50; # binding 50 to the variable $v
# mutate $v; # Parameter '$n' expected a writable container, but got Int value
-=begin comment
-If what you want is a copy instead, use the `is copy` trait which will
-cause the argument to be copied and allow you to modify the argument
-inside the routine without modifying the passed argument.
+# If what you want is a copy instead, use the `is copy` trait which will
+# cause the argument to be copied and allow you to modify the argument
+# inside the routine without modifying the passed argument.
-A sub itself returns a container, which means it can be marked as `rw`.
-Alternatively, you can explicitly mark the returned container as mutable
-by using `return-rw` instead of `return`.
-=end comment
+# A sub itself returns a container, which means it can be marked as `rw`.
+# Alternatively, you can explicitly mark the returned container as mutable
+# by using `return-rw` instead of `return`.
my $x = 42;
my $y = 45;
sub x-store is rw { $x }
@@ -390,12 +356,10 @@ say $y; # OUTPUT: «90␤»
# 4.1 if/if-else/if-elsif-else/unless
#
-=begin comment
-Before talking about `if`, we need to know which values are "truthy"
-(represent `True`), and which are "falsey" (represent `False`). Only these
-values are falsey: 0, (), {}, "", Nil, a type (like `Str`, `Int`, etc.) and
-of course, `False` itself. Any other value is truthy.
-=end comment
+# Before talking about `if`, we need to know which values are "truthy"
+# (represent `True`), and which are "falsey" (represent `False`). Only these
+# values are falsey: 0, (), {}, "", Nil, a type (like `Str`, `Int`, etc.) and
+# of course, `False` itself. Any other value is truthy.
my $number = 5;
if $number < 5 {
say "Number is less than 5"
@@ -422,11 +386,9 @@ unless False {
say "Quite truthy" if True; # OUTPUT: «Quite truthy␤»
say "Quite falsey" unless False; # OUTPUT: «Quite falsey␤»
-=begin comment
-The ternary operator (`??..!!`) is structured as follows `condition ??
-expression1 !! expression2` and it returns expression1 if the condition is
-true. Otherwise, it returns expression2.
-=end comment
+# The ternary operator (`??..!!`) is structured as follows `condition ??
+# expression1 !! expression2` and it returns expression1 if the condition is
+# true. Otherwise, it returns expression2.
my $age = 30;
say $age > 18 ?? "You are an adult" !! "You are under 18";
# OUTPUT: «You are an adult␤»
@@ -435,11 +397,9 @@ say $age > 18 ?? "You are an adult" !! "You are under 18";
# 4.2 with/with-else/with-orwith-else/without
#
-=begin comment
-The `with` statement is like `if`, but it tests for definedness rather than
-truth, and it topicalizes on the condition, much like `given` which will
-be discussed later.
-=end comment
+# The `with` statement is like `if`, but it tests for definedness rather than
+# truth, and it topicalizes on the condition, much like `given` which will
+# be discussed later.
my $s = "raku";
with $s.index("r") { say "Found a at $_" }
orwith $s.index("k") { say "Found c at $_" }
@@ -475,6 +435,7 @@ current iteration (unless explicitly named), etc.
Since other Raku constructs use this variable (as said before, like `for`,
blocks, `with` statement etc), this means the powerful `when` is not only
applicable along with a `given`, but instead anywhere a `$_` exists.
+
=end comment
given "foo bar" {
@@ -589,6 +550,7 @@ The categories are:
The associativity and precedence list are explained below.
Alright, you're set to go!
+
=end comment
#
@@ -680,11 +642,9 @@ my @natural = 1..*; # 1 to Infinite! Equivalent to `1..Inf`.
# You can pass ranges as subscripts and it'll return an array of results.
say @natural[^10]; # OUTPUT: «1 2 3 4 5 6 7 8 9 10␤», doesn't run out of memory!
-=begin comment
-NOTE: when reading an infinite list, Raku will "reify" the elements
-it needs, then keep them in memory. They won't be calculated more than once.
-It also will never calculate more elements that are needed.
-=end comment
+# NOTE: when reading an infinite list, Raku will "reify" the elements
+# it needs, then keep them in memory. They won't be calculated more than once.
+# It also will never calculate more elements than that are needed.
# An array subscript can also be a closure. It'll be called with the array's
# length as the argument. The following two examples are equivalent:
@@ -784,7 +744,7 @@ first-of-array(@small); #=> 1
# Here, `@rest` is `(3,)`, since `$fst` holds the `2`. This results
# since the length (.elems) of `@rest` is 1.
sub slurp-in-array(@ [$fst, *@rest]) {
- say $fst + @rest.elems;
+ say $fst + @rest.elems;
}
slurp-in-array(@tail); # OUTPUT: «3␤»
@@ -798,16 +758,14 @@ fst(1); # OUTPUT: «1␤»
# passed") though. After all, the `fst` sub declares only a single positional
# parameter.
-=begin comment
-You can also destructure hashes (and classes, which you'll learn about later).
-The syntax is basically the same as
-`%hash-name (:key($variable-to-store-value-in))`.
-The hash can stay anonymous if you only need the values you extracted.
-
-In order to call the function, you must supply a hash wither created with
-curly braces or with `%()` (recommended). Alternatively, you can pass
-a variable that contains a hash.
-=end comment
+# You can also destructure hashes (and classes, which you'll learn about later).
+# The syntax is basically the same as
+# `%hash-name (:key($variable-to-store-value-in))`.
+# The hash can stay anonymous if you only need the values you extracted.
+
+# In order to call the function, you must supply a hash wither created with
+# curly braces or with `%()` (recommended). Alternatively, you can pass
+# a variable that contains a hash.
sub key-of( % (:value($val), :qua($qua)) ) {
say "Got value $val, $qua time" ~~
@@ -826,12 +784,10 @@ sub next-index( $n ) {
}
my $new-n = next-index(3); # $new-n is now 4
-=begin comment
-This is true for everything, except for the looping constructs (due to
-performance reasons): there's no reason to build a list if we're just going to
-discard all the results. If you still want to build one, you can use the
-`do` statement prefix or the `gather` prefix, which we'll see later:
-=end comment
+# This is true for everything, except for the looping constructs (due to
+# performance reasons): there's no reason to build a list if we're just going to
+# discard all the results. If you still want to build one, you can use the
+# `do` statement prefix or the `gather` prefix, which we'll see later:
sub list-of( $n ) {
do for ^$n { $_ }
@@ -857,13 +813,11 @@ my &lambda3 = sub ($argument) {
"The argument passed to this lambda is $argument"
}
-=begin comment
-Both pointy blocks and blocks are pretty much the same thing, except that
-the former can take arguments, and that the latter can be mistaken as
-a hash by the parser. That being said, blocks can declare what's known
-as placeholders parameters through the twigils `$^` (for positional
-parameters) and `$:` (for named parameters). More on them later on.
-=end comment
+# Both pointy blocks and blocks are pretty much the same thing, except that
+# the former can take arguments, and that the latter can be mistaken as
+# a hash by the parser. That being said, blocks can declare what's known
+# as placeholders parameters through the twigils `$^` (for positional
+# parameters) and `$:` (for named parameters). More on them later on.
my &mult = { $^numbers * $:times }
say mult 4, :times(6); #=> «24␤»
@@ -876,12 +830,10 @@ my @res1 = map -> $v { $v + 3 }, @nums; # pointy block, explicit parameter
my @res2 = map { $_ + 3 }, @nums; # block using an implicit parameter
my @res3 = map { $^val + 3 }, @nums; # block with placeholder parameter
-=begin comment
-A sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`):
-A block doesn't have a "function context" (though it can have arguments),
-which means that if you return from it, you're going to return from the
-parent function.
-=end comment
+# A sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`):
+# A block doesn't have a "function context" (though it can have arguments),
+# which means that if you return from it, you're going to return from the
+# parent function.
# Compare:
sub is-in( @array, $elem ) {
@@ -895,23 +847,19 @@ sub truthy-array( @array ) {
say 'Hi';
}
-=begin comment
-In the `is-in` sub, the block will `return` out of the `is-in` sub once the
-condition evaluates to `True`, the loop won't be run anymore and the
-following statement won't be executed. The last statement is only executed
-if the block never returns.
-
-On the contrary, the `truthy-array` sub will produce an array of `True` and
-`False`, which will printed, and always execute the last execute statement.
-Thus, the `return` only returns from the anonymous `sub`
-=end comment
+# In the `is-in` sub, the block will `return` out of the `is-in` sub once the
+# condition evaluates to `True`, the loop won't be run anymore and the
+# following statement won't be executed. The last statement is only executed
+# if the block never returns.
-=begin comment
-The `anon` declarator can be used to create an anonymous sub from a
-regular subroutine. The regular sub knows its name but its symbol is
-prevented from getting installed in the lexical scope, the method table
-and everywhere else.
-=end comment
+# On the contrary, the `truthy-array` sub will produce an array of `True` and
+# `False`, which will printed, and always execute the last execute statement.
+# Thus, the `return` only returns from the anonymous `sub`
+
+# The `anon` declarator can be used to create an anonymous sub from a
+# regular subroutine. The regular sub knows its name but its symbol is
+# prevented from getting installed in the lexical scope, the method table
+# and everywhere else.
my $anon-sum = anon sub summation(*@a) { [+] @a }
say $anon-sum.name; # OUTPUT: «summation␤»
say $anon-sum(2, 3, 5); # OUTPUT: «10␤»
@@ -983,31 +931,27 @@ multi with-or-without-you {
say "Definitely can't live.";
}
-=begin comment
-This is very, very useful for many purposes, like `MAIN` subs (covered
-later), and even the language itself uses it in several places.
+# This is very, very useful for many purposes, like `MAIN` subs (covered
+# later), and even the language itself uses it in several places.
-For example, the `is` trait is actually a `multi sub` named `trait_mod:<is>`,
-and it works off that. Thus, `is rw`, is simply a dispatch to a function with
-this signature `sub trait_mod:<is>(Routine $r, :$rw!) {}`
-=end comment
+# For example, the `is` trait is actually a `multi sub` named `trait_mod:<is>`,
+# and it works off that. Thus, `is rw`, is simply a dispatch to a function with
+# this signature `sub trait_mod:<is>(Routine $r, :$rw!) {}`
####################################################
# 7. About types...
####################################################
-=begin comment
-Raku is gradually typed. This means you can specify the type of your
-variables/arguments/return types, or you can omit the type annotations in
-in which case they'll default to `Any`. Obviously you get access to a few
-base types, like `Int` and `Str`. The constructs for declaring types are
-`subset`, `class`, `role`, etc. which you'll see later.
-
-For now, let us examine `subset` which 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`), and add
-additional checks with the `where` clause.
-=end comment
+# Raku is gradually typed. This means you can specify the type of your
+# variables/arguments/return types, or you can omit the type annotations in
+# in which case they'll default to `Any`. Obviously you get access to a few
+# base types, like `Int` and `Str`. The constructs for declaring types are
+# `subset`, `class`, `role`, etc. which you'll see later.
+
+# For now, let us examine `subset` which 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`), and add
+# additional checks with the `where` clause.
subset VeryBigInteger of Int where * > 500;
# Or the set of the whole numbers:
@@ -1025,14 +969,12 @@ my PENFO $yes-penfo = 36; # OK
# 8. Scoping
####################################################
-=begin comment
-In Raku, unlike many scripting languages, (such as Python, Ruby, PHP),
-you must declare your variables before using them. The `my` declarator
-we've used so far uses "lexical scoping". There are a few other declarators,
-(`our`, `state`, ..., ) which we'll see later. This is called
-"lexical scoping", where in inner blocks, you can access variables from
-outer blocks.
-=end comment
+# In Raku, unlike many scripting languages, (such as Python, Ruby, PHP),
+# you must declare your variables before using them. The `my` declarator
+# we've used so far uses "lexical scoping". There are a few other declarators,
+# (`our`, `state`, ..., ) which we'll see later. This is called
+# "lexical scoping", where in inner blocks, you can access variables from
+# outer blocks.
my $file_scoped = 'Foo';
sub outer {
@@ -1052,17 +994,15 @@ outer()(); # OUTPUT: «Foo Bar␤»
# 9. Twigils
####################################################
-=begin comment
-There are many special `twigils` (composed sigils) in Raku. Twigils
-define a variable's scope.
-The `*` and `?` twigils work on standard variables:
- * for dynamic variables
- ? for compile-time variables
-
-The `!` and the `.` twigils are used with Raku's objects:
- ! for attributes (instance attribute)
- . for methods (not really a variable)
-=end comment
+# There are many special `twigils` (composed sigils) in Raku. Twigils
+# define a variable's scope.
+# The `*` and `?` twigils work on standard variables:
+# * for dynamic variables
+# ? for compile-time variables
+#
+# The `!` and the `.` twigils are used with Raku's objects:
+# ! for attributes (instance attribute)
+# . for methods (not really a variable)
#
# `*` twigil: Dynamic Scope
@@ -1084,14 +1024,14 @@ sub call_say_dyn {
my $*dyn_scoped_1 = 25;
# Will change the value of the file scoped variable.
- $*dyn_scoped_2 = 100;
+ $*dyn_scoped_2 = 100;
# $*dyn_scoped 1 and 2 will be looked for in the call.
say_dyn(); # OUTPUT: «25 100␤»
# The call to `say_dyn` uses the value of $*dyn_scoped_1 from inside
# this sub's lexical scope even though the blocks aren't nested (they're
- # call-nested).
+ # call-nested).
}
say_dyn(); # OUTPUT: «1 10␤»
@@ -1109,26 +1049,24 @@ say_dyn(); # OUTPUT: «1 100␤»
# 10. Object Model
####################################################
-=begin comment
-To call a method on an object, add a dot followed by the method name:
-`$object.method`
-
-Classes are declared with the `class` keyword. Attributes are declared
-with the `has` keyword, and methods declared with the `method` keyword.
-
-Every attribute that is private uses the `!` twigil. For example: `$!attr`.
-Immutable public attributes use the `.` twigil which creates a read-only
-method named after the attribute. In fact, declaring an attribute with `.`
-is equivalent to declaring the same attribute with `!` and then creating
-a read-only method with the attribute's name. However, this is done for us
-by Raku automatically. The easiest way to remember the `$.` twigil is
-by comparing it to how methods are called.
-
-Raku's object model ("SixModel") is very flexible, and allows you to
-dynamically add methods, change semantics, etc... Unfortunately, these will
-not all be covered here, and you should refer to:
-https://docs.raku.org/language/objects.html.
-=end comment
+# To call a method on an object, add a dot followed by the method name:
+# `$object.method`
+
+# Classes are declared with the `class` keyword. Attributes are declared
+# with the `has` keyword, and methods declared with the `method` keyword.
+
+# Every attribute that is private uses the `!` twigil. For example: `$!attr`.
+# Immutable public attributes use the `.` twigil which creates a read-only
+# method named after the attribute. In fact, declaring an attribute with `.`
+# is equivalent to declaring the same attribute with `!` and then creating
+# a read-only method with the attribute's name. However, this is done for us
+# by Raku automatically. The easiest way to remember the `$.` twigil is
+# by comparing it to how methods are called.
+
+# Raku's object model ("SixModel") is very flexible, and allows you to
+# dynamically add methods, change semantics, etc... Unfortunately, these will
+# not all be covered here, and you should refer to:
+# https://docs.raku.org/language/objects.html.
class Human {
has Str $.name; # `$.name` is immutable but with an accessor method.
@@ -1196,12 +1134,10 @@ $person1.get-info; #=> Jord born in Togo and now lives in France. Age: 10
# 10.1 Object Inheritance
#
-=begin comment
-Raku also has inheritance (along with multiple inheritance). While
-methods are inherited, submethods are not. Submethods are useful for
-object construction and destruction tasks, such as `BUILD`, or methods that
-must be overridden by subtypes. We will learn about `BUILD` later on.
-=end comment
+# Raku also has inheritance (along with multiple inheritance). While
+# methods are inherited, submethods are not. Submethods are useful for
+# object construction and destruction tasks, such as `BUILD`, or methods that
+# must be overridden by subtypes. We will learn about `BUILD` later on.
class Parent {
has $.age;
@@ -1232,13 +1168,11 @@ my Child $Madison .= new(age => 1, name => 'Madison');
$Madison.talk; # OUTPUT: «Goo goo ga ga␤», due to the overridden method.
# $Madison.favorite-color # does not work since it is not inherited.
-=begin comment
-When you use `my T $var`, `$var` starts off with `T` itself in it, so you can
-call `new` on it. (`.=` is just the dot-call and the assignment operator).
-Thus, `$a .= b` is the same as `$a = $a.b`. Also note that `BUILD` (the method
-called inside `new`) will set parent's properties too, so you can pass `val =>
-5`.
-=end comment
+# When you use `my T $var`, `$var` starts off with `T` itself in it, so you can
+# call `new` on it. (`.=` is just the dot-call and the assignment operator).
+# Thus, `$a .= b` is the same as `$a = $a.b`. Also note that `BUILD` (the method
+# called inside `new`) will set parent's properties too, so you can pass `val =>
+# 5`.
#
# 10.2 Roles, or Mixins
@@ -1281,15 +1215,13 @@ class Item does PrintableVal {
# 11. Exceptions
####################################################
-=begin comment
-Exceptions are built on top of classes, in the package `X` (like `X::IO`).
-In Raku, exceptions are automatically 'thrown':
+# Exceptions are built on top of classes, in the package `X` (like `X::IO`).
+# In Raku, exceptions are automatically 'thrown':
-open 'foo'; # OUTPUT: «Failed to open file foo: no such file or directory␤»
+# open 'foo'; # OUTPUT: «Failed to open file foo: no such file or directory␤»
-It will also print out what line the error was thrown at
-and other error info.
-=end comment
+# It will also print out what line the error was thrown at
+# and other error info.
# You can throw an exception using `die`. Here it's been commented out to
# avoid stopping the program's execution:
@@ -1298,58 +1230,48 @@ and other error info.
# Or more explicitly (commented out too):
# X::AdHoc.new(payload => 'Error!').throw; # OUTPUT: «Error!␤»
-=begin comment
-In Raku, `orelse` is similar to the `or` operator, except it only matches
-undefined variables instead of anything evaluating as `False`.
-Undefined values include: `Nil`, `Mu` and `Failure` as well as `Int`, `Str`
-and other types that have not been initialized to any value yet.
-You can check if something is defined or not using the defined method:
-=end comment
+# In Raku, `orelse` is similar to the `or` operator, except it only matches
+# undefined variables instead of anything evaluating as `False`.
+# Undefined values include: `Nil`, `Mu` and `Failure` as well as `Int`, `Str`
+# and other types that have not been initialized to any value yet.
+# You can check if something is defined or not using the defined method:
my $uninitialized;
say $uninitialized.defined; # OUTPUT: «False␤»
-=begin comment
-When using `orelse` it will disarm the exception and alias $_ to that
-failure. This will prevent it to being automatically handled and printing
-lots of scary error messages to the screen. We can use the `exception`
-method on the `$_` variable to access the exception
-=end comment
+# When using `orelse` it will disarm the exception and alias $_ to that
+# failure. This will prevent it to being automatically handled and printing
+# lots of scary error messages to the screen. We can use the `exception`
+# method on the `$_` variable to access the exception
open 'foo' orelse say "Something happened {.exception}";
# This also works:
open 'foo' orelse say "Something happened $_";
# OUTPUT: «Something happened Failed to open file foo: no such file or directory␤»
-=begin comment
-Both of those above work but in case we get an object from the left side
-that is not a failure we will probably get a warning. We see below how we
-can use try` and `CATCH` to be more specific with the exceptions we catch.
-=end comment
+# Both of those above work but in case we get an object from the left side
+# that is not a failure we will probably get a warning. We see below how we
+# can use try` and `CATCH` to be more specific with the exceptions we catch.
#
# 11.1 Using `try` and `CATCH`
#
-=begin comment
-By using `try` and `CATCH` you can contain and handle exceptions without
-disrupting the rest of the program. The `try` block will set the last
-exception to the special variable `$!` (known as the error variable).
-NOTE: This has no relation to $!variables seen inside class definitions.
-=end comment
+# By using `try` and `CATCH` you can contain and handle exceptions without
+# disrupting the rest of the program. The `try` block will set the last
+# exception to the special variable `$!` (known as the error variable).
+# NOTE: This has no relation to $!variables seen inside class definitions.
try open 'foo';
say "Well, I tried! $!" if defined $!;
# OUTPUT: «Well, I tried! Failed to open file foo: no such file or directory␤»
-=begin comment
-Now, what if we want more control over handling the exception?
-Unlike many other languages, in Raku, you put the `CATCH` block *within*
-the block to `try`. Similar to how the `$_` variable was set when we
-'disarmed' the exception with `orelse`, we also use `$_` in the CATCH block.
-NOTE: The `$!` variable is only set *after* the `try` block has caught an
-exception. By default, a `try` block has a `CATCH` block of its own that
-catches any exception (`CATCH { default {} }`).
-=end comment
+# Now, what if we want more control over handling the exception?
+# Unlike many other languages, in Raku, you put the `CATCH` block *within*
+# the block to `try`. Similar to how the `$_` variable was set when we
+# 'disarmed' the exception with `orelse`, we also use `$_` in the CATCH block.
+# NOTE: The `$!` variable is only set *after* the `try` block has caught an
+# exception. By default, a `try` block has a `CATCH` block of its own that
+# catches any exception (`CATCH { default {} }`).
try {
my $a = (0 %% 0);
@@ -1387,15 +1309,13 @@ try {
}
# OUTPUT: «Failed to open file /dir/foo: no such file or directory␤»
-=begin comment
-There are also some subtleties to exceptions. Some Raku subs return a
-`Failure`, which is a wrapper around an `Exception` object which is
-"unthrown". They're not thrown until you try to use the variables containing
-them unless you call `.Bool`/`.defined` on them - then they're handled.
-(the `.handled` method is `rw`, so you can mark it as `False` back yourself)
-You can throw a `Failure` using `fail`. Note that if the pragma `use fatal`
-is on, `fail` will throw an exception (like `die`).
-=end comment
+# There are also some subtleties to exceptions. Some Raku subs return a
+# `Failure`, which is a wrapper around an `Exception` object which is
+# "unthrown". They're not thrown until you try to use the variables containing
+# them unless you call `.Bool`/`.defined` on them - then they're handled.
+# (the `.handled` method is `rw`, so you can mark it as `False` back yourself)
+# You can throw a `Failure` using `fail`. Note that if the pragma `use fatal`
+# is on, `fail` will throw an exception (like `die`).
my $value = 0/0; # We're not trying to access the value, so no problem.
try {
@@ -1407,34 +1327,28 @@ try {
}
}
-=begin comment
-There is also another kind of exception: Control exceptions. Those are "good"
-exceptions, which happen when you change your program's flow, using operators
-like `return`, `next` or `last`. You can "catch" those with `CONTROL` (not 100%
-working in Rakudo yet).
-=end comment
+# There is also another kind of exception: Control exceptions. Those are "good"
+# exceptions, which happen when you change your program's flow, using operators
+# like `return`, `next` or `last`. You can "catch" those with `CONTROL` (not 100%
+# working in Rakudo yet).
####################################################
# 12. Packages
####################################################
-=begin comment
-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 denominator)
-Packages are important - especially as Perl is well-known for CPAN,
-the Comprehensive Perl Archive Network.
-=end comment
+# 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 denominator)
+# Packages are important - especially as Perl is well-known for CPAN,
+# the Comprehensive Perl Archive Network.
# 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; # OUTPUT: «[1]␤»
-=begin comment
-You should not declare packages using the `package` keyword (unlike Perl).
-Instead, use `class Package::Name::Here;` to declare a class, or if you only
-want to export variables/subs, you can use `module` instead.
-=end comment
+# You should not declare packages using the `package` keyword (unlike Perl).
+# Instead, use `class Package::Name::Here;` to declare a class, or if you only
+# want to export variables/subs, you can use `module` instead.
# If `Hello` doesn't exist yet, it'll just be a "stub", that can be redeclared
# as something else later.
@@ -1460,14 +1374,12 @@ my $actions = JSON::Tiny::Actions.new;
# 13. Declarators
####################################################
-=begin comment
-In Raku, you get different behaviors based on how you declare a variable.
-You've already seen `my` and `has`, we'll now explore the others.
+# In Raku, you get different behaviors based on how you declare a variable.
+# You've already seen `my` and `has`, we'll now explore the others.
-`our` - these declarations happen at `INIT` time -- (see "Phasers" below).
-It's like `my`, but it also creates a package variable. All packagish
-things such as `class`, `role`, etc. are `our` by default.
-=end comment
+# `our` - these declarations happen at `INIT` time -- (see "Phasers" below).
+# It's like `my`, but it also creates a package variable. All packagish
+# things such as `class`, `role`, etc. are `our` by default.
module Var::Increment {
# NOTE: `our`-declared variables cannot be typed.
@@ -1533,15 +1445,13 @@ for ^5 -> $a {
# 14. Phasers
####################################################
-=begin comment
-Phasers in Raku are blocks that happen at determined points of time in
-your program. They are called phasers because they mark a change in the
-phase of a program. For example, when the program is compiled, a for loop
-runs, you leave a block, or an exception gets thrown (The `CATCH` block is
-actually a phaser!). Some of them can be used for their return values,
-some of them can't (those that can have a "[*]" in the beginning of their
-explanation text). Let's have a look!
-=end comment
+# Phasers in Raku are blocks that happen at determined points of time in
+# your program. They are called phasers because they mark a change in the
+# phase of a program. For example, when the program is compiled, a for loop
+# runs, you leave a block, or an exception gets thrown (The `CATCH` block is
+# actually a phaser!). Some of them can be used for their return values,
+# some of them can't (those that can have a "[*]" in the beginning of their
+# explanation text). Let's have a look!
#
# 14.1 Compile-time phasers
@@ -1637,14 +1547,11 @@ do-db-stuff();
# 15. Statement prefixes
####################################################
-=begin comment
-Those act a bit like phasers: they affect the behavior of the following
-code. Though, they run in-line with the executable code, so they're in
-lowercase. (`try` and `start` are theoretically in that list, but explained
-elsewhere) NOTE: all of these (except start) don't need explicit curly
-braces `{` and `}`.
-
-=end comment
+# Those act a bit like phasers: they affect the behavior of the following
+# code. Though, they run in-line with the executable code, so they're in
+# lowercase. (`try` and `start` are theoretically in that list, but explained
+# elsewhere) NOTE: all of these (except start) don't need explicit curly
+# braces `{` and `}`.
#
# 15.1 `do` - It runs a block or a statement as a term.
@@ -1757,40 +1664,34 @@ quietly { warn 'This is a warning!' }; # No output
my ($p, $q, $r) = (1, 2, 3);
-=begin comment
-Given some binary operator § (not a Raku-supported operator), then:
+# Given some binary operator § (not a Raku-supported operator), then:
-$p § $q § $r; # with a left-associative §, this is ($p § $q) § $r
-$p § $q § $r; # with a right-associative §, this is $p § ($q § $r)
-$p § $q § $r; # with a non-associative §, this is illegal
-$p § $q § $r; # with a chain-associative §, this is ($p § $q) and ($q § $r)§
-$p § $q § $r; # with a list-associative §, this is `infix:<>`
-=end comment
+# $p § $q § $r; # with a left-associative §, this is ($p § $q) § $r
+# $p § $q § $r; # with a right-associative §, this is $p § ($q § $r)
+# $p § $q § $r; # with a non-associative §, this is illegal
+# $p § $q § $r; # with a chain-associative §, this is ($p § $q) and ($q § $r)§
+# $p § $q § $r; # with a list-associative §, this is `infix:<>`
#
# 17.2 Unary operators
#
-=begin comment
-Given some unary operator § (not a Raku-supported operator), then:
-§$p§ # with left-associative §, this is (§$p)§
-§$p§ # with right-associative §, this is §($p§)
-§$p§ # with non-associative §, this is illegal
-=end comment
+# Given some unary operator § (not a Raku-supported operator), then:
+# §$p§ # with left-associative §, this is (§$p)§
+# §$p§ # with right-associative §, this is §($p§)
+# §$p§ # with non-associative §, this is illegal
#
# 17.3 Create your own operators!
#
-=begin comment
-Okay, you've been reading all of that, so you might want to try something
-more exciting?! I'll tell you a little secret (or not-so-secret):
-In Raku, all operators are actually just funny-looking subroutines.
+# Okay, you've been reading all of that, so you might want to try something
+# more exciting?! I'll tell you a little secret (or not-so-secret):
+# In Raku, all operators are actually just funny-looking subroutines.
-You can declare an operator just like you declare a sub. In the following
-example, `prefix` refers to the operator categories (prefix, infix, postfix,
-circumfix, and post-circumfix).
-=end comment
+# You can declare an operator just like you declare a sub. In the following
+# example, `prefix` refers to the operator categories (prefix, infix, postfix,
+# circumfix, and post-circumfix).
sub prefix:<win>( $winner ) {
say "$winner Won!";
}
@@ -1834,12 +1735,10 @@ say "abc"{1}; # OUTPUT: «b␤», after the term `"abc"`, and around the index (
# Post-circumfix is 'after a term, around something'
-=begin comment
-This really means a lot -- because everything in Raku uses this.
-For example, to delete a key from a hash, you use the `:delete` adverb
-(a simple named argument underneath). For instance, the following statements
-are equivalent.
-=end comment
+# This really means a lot -- because everything in Raku uses this.
+# For example, to delete a key from a hash, you use the `:delete` adverb
+# (a simple named argument underneath). For instance, the following statements
+# are equivalent.
my %person-stans =
'Giorno Giovanna' => 'Gold Experience',
'Bruno Bucciarati' => 'Sticky Fingers';
@@ -1848,34 +1747,30 @@ my $key = 'Bruno Bucciarati';
postcircumfix:<{ }>( %person-stans, 'Giorno Giovanna', :delete );
# (you can call operators like this)
-=begin comment
-It's *all* using the same building blocks! Syntactic categories
-(prefix infix ...), named arguments (adverbs), ..., etc. used to build
-the language - are available to you. Obviously, you're advised against
-making an operator out of *everything* -- with great power comes great
-responsibility.
-=end comment
+# It's *all* using the same building blocks! Syntactic categories
+# (prefix infix ...), named arguments (adverbs), ..., etc. used to build
+# the language - are available to you. Obviously, you're advised against
+# making an operator out of *everything* -- with great power comes great
+# responsibility.
#
# 17.4 Meta operators!
#
-=begin comment
-Oh boy, get ready!. Get ready, because we're delving deep into the rabbit's
-hole, and you probably won't want to go back to other languages after
-reading this. (I'm guessing you don't want to go back at this point but
-let's continue, for the journey is long and enjoyable!).
-
-Meta-operators, as their name suggests, are *composed* operators. Basically,
-they're operators that act on another operators.
-
-The reduce meta-operator is a prefix meta-operator that takes a binary
-function and one or many lists. If it doesn't get passed any argument,
-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 the binary function to the last
-result (or the first element of a list) and the popped element.
-=end comment
+# Oh boy, get ready!. Get ready, because we're delving deep into the rabbit's
+# hole, and you probably won't want to go back to other languages after
+# reading this. (I'm guessing you don't want to go back at this point but
+# let's continue, for the journey is long and enjoyable!).
+
+# Meta-operators, as their name suggests, are *composed* operators. Basically,
+# they're operators that act on another operators.
+
+# The reduce meta-operator is a prefix meta-operator that takes a binary
+# function and one or many lists. If it doesn't get passed any argument,
+# 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 the binary function to the last
+# result (or the first element of a list) and the popped element.
# To sum a list, you could use the reduce meta-operator with `+`, i.e.:
say [+] 1, 2, 3; # OUTPUT: «6␤», equivalent to (1+2)+3.
@@ -1903,13 +1798,11 @@ say [//]; # OUTPUT: «(Any)␤»
sub add($a, $b) { $a + $b }
say [[&add]] 1, 2, 3; # OUTPUT: «6␤»
-=begin comment
-The zip meta-operator is an infix meta-operator that also can be used as a
-"normal" operator. It takes an optional binary function (by default, it
-just creates a pair), and will pop one value off of each array and call
-its binary function on these until it runs out of elements. It returns an
-array with all of these new elements.
-=end comment
+# The zip meta-operator is an infix meta-operator that also can be used as a
+# "normal" operator. It takes an optional binary function (by default, it
+# just creates a pair), and will pop one value off of each array and call
+# its binary function on these until it runs out of elements. It returns an
+# array with all of these new elements.
say (1, 2) Z (3, 4); # OUTPUT: «((1, 3), (2, 4))␤»
say 1..3 Z+ 4..6; # OUTPUT: «(5, 7, 9)␤»
@@ -1922,12 +1815,10 @@ say 1..3 Z+ 4..6; # OUTPUT: «(5, 7, 9)␤»
# And to end the operator list:
-=begin comment
-The sequence operator (`...`) is one of Raku's most powerful features:
-It's composed by the list (which might include a closure) you want Raku to
-deduce from on the left and a value (or either a predicate or a Whatever Star
-for a lazy infinite list) on the right that states when to stop.
-=end comment
+# The sequence operator (`...`) is one of Raku's most powerful features:
+# It's composed by the list (which might include a closure) you want Raku to
+# deduce from on the left and a value (or either a predicate or a Whatever Star
+# for a lazy infinite list) on the right that states when to stop.
# Basic arithmetic sequence
my @listv0 = 1, 2, 3...10;
@@ -1954,68 +1845,60 @@ my @fibv1 = 1, 1, -> $a, $b { $a + $b } ... *;
# Equivalent to the above example but using a block with placeholder parameters.
my @fibv2 = 1, 1, { $^a + $^b } ... *;
-=begin comment
-In the examples with explicit parameters (i.e., $a and $b), $a and $b
-will always take the previous values, meaning that for the Fibonacci sequence,
-they'll start with $a = 1 and $b = 1 (values we set by hand), then $a = 1
-and $b = 2 (result from previous $a + $b), and so on.
-=end comment
+# In the examples with explicit parameters (i.e., $a and $b), $a and $b
+# will always take the previous values, meaning that for the Fibonacci sequence,
+# they'll start with $a = 1 and $b = 1 (values we set by hand), then $a = 1
+# and $b = 2 (result from previous $a + $b), and so on.
-=begin comment
# In the example we use a range as an index to access the sequence. However,
# it's worth noting that for ranges, once reified, elements aren't re-calculated.
# That's why, for instance, `@primes[^100]` will take a long time the first
-# time you print it but then it will be instateneous.
-=end comment
+# time you print it but then it will be instantaneous.
say @fibv0[^10]; # OUTPUT: «1 1 2 3 5 8 13 21 34 55␤»
####################################################
# 18. Regular Expressions
####################################################
-=begin comment
-I'm sure a lot of you have been waiting for this one. Well, now that you know
-a good deal of Raku already, we can get started. First off, you'll have to
-forget about "PCRE regexps" (perl-compatible regexps).
-
-IMPORTANT: Don't skip them because you know PCRE. They're different. Some
-things are the same (like `?`, `+`, and `*`), but sometimes the semantics
-change (`|`). Make sure you read carefully, because you might trip over a
-new behavior.
-
-Raku has many features related to RegExps. After all, Rakudo parses itself.
-We're first going to look at the syntax itself, then talk about grammars
-(PEG-like), differences between `token`, `regex` and `rule` declarators,
-and some more. Side note: you still have access to PCRE regexps using the
-`:P5` modifier which we won't be discussing this in this tutorial, though.
-
-In essence, Raku natively implements PEG ("Parsing Expression Grammars").
-The pecking order for ambiguous parses is determined by a multi-level
-tie-breaking test:
- - Longest token matching: `foo\s+` beats `foo` (by 2 or more positions)
- - Longest literal prefix: `food\w*` beats `foo\w*` (by 1)
- - Declaration from most-derived to less derived grammars
- (grammars are actually classes)
- - Earliest declaration wins
-=end comment
+# I'm sure a lot of you have been waiting for this one. Well, now that you know
+# a good deal of Raku already, we can get started. First off, you'll have to
+# forget about "PCRE regexps" (perl-compatible regexps).
+
+# IMPORTANT: Don't skip them because you know PCRE. They're different. Some
+# things are the same (like `?`, `+`, and `*`), but sometimes the semantics
+# change (`|`). Make sure you read carefully, because you might trip over a
+# new behavior.
+
+# Raku has many features related to RegExps. After all, Rakudo parses itself.
+# We're first going to look at the syntax itself, then talk about grammars
+# (PEG-like), differences between `token`, `regex` and `rule` declarators,
+# and some more. Side note: you still have access to PCRE regexps using the
+# `:P5` modifier which we won't be discussing this in this tutorial, though.
+
+# In essence, Raku natively implements PEG ("Parsing Expression Grammars").
+# The pecking order for ambiguous parses is determined by a multi-level
+# tie-breaking test:
+# - Longest token matching: `foo\s+` beats `foo` (by 2 or more positions)
+# - Longest literal prefix: `food\w*` beats `foo\w*` (by 1)
+# - Declaration from most-derived to less derived grammars
+# (grammars are actually classes)
+# - Earliest declaration wins
say so 'a' ~~ /a/; # OUTPUT: «True␤»
say so 'a' ~~ / a /; # OUTPUT: «True␤», more readable with some spaces!
-=begin comment
-In all our examples, we're going to use the smart-matching operator against
-a regexp. We're converting the result using `so` to a Boolean value because,
-in fact, it's returning a `Match` object. They know how to respond to list
-indexing, hash indexing, and return the matched string. The results of the
-match are available in the `$/` variable (implicitly lexically-scoped). You
-can also use the capture variables which start at 0: `$0`, `$1', `$2`...
-
-You can also note that `~~` does not perform start/end checking, meaning
-the regexp can be matched with just one character of the string. We'll
-explain later how you can do it.
-
-In Raku, you can have any alphanumeric as a literal, everything else has
-to be escaped by using a backslash or quotes.
-=end comment
+# In all our examples, we're going to use the smart-matching operator against
+# a regexp. We're converting the result using `so` to a Boolean value because,
+# in fact, it's returning a `Match` object. They know how to respond to list
+# indexing, hash indexing, and return the matched string. The results of the
+# match are available in the `$/` variable (implicitly lexically-scoped). You
+# can also use the capture variables which start at 0: `$0`, `$1', `$2`...
+
+# You can also note that `~~` does not perform start/end checking, meaning
+# the regexp can be matched with just one character of the string. We'll
+# explain later how you can do it.
+
+# In Raku, you can have any alphanumeric as a literal, everything else has
+# to be escaped by using a backslash or quotes.
say so 'a|b' ~~ / a '|' b /; # OUTPUT: «True␤», it wouldn't mean the same
# thing if `|` wasn't escaped.
say so 'a|b' ~~ / a \| b /; # OUTPUT: «True␤», another way to escape it.
@@ -2030,12 +1913,10 @@ say so 'a b c' ~~ /:s a b c /; #=> `True`, we added the modifier `:s` here.
say so 'a b c' ~~ / a b c /; # OUTPUT: «False␤»
say so 'a b c' ~~ / a b c /; # OUTPUT: «False»
-=begin comment
-NOTE: Please use quotes or `:s` (`:sigspace`) modifier (or, to suppress this
-warning, omit the space, or otherwise change the spacing). To fix this and make
-the spaces less ambiguous, either use at least two spaces between strings
-or use the `:s` adverb.
-=end comment
+# NOTE: Please use quotes or `:s` (`:sigspace`) modifier (or, to suppress this
+# warning, omit the space, or otherwise change the spacing). To fix this and make
+# the spaces less ambiguous, either use at least two spaces between strings
+# or use the `:s` adverb.
# As we saw before, we can embed the `:s` inside the slash delimiters, but we
# can also put it outside of them if we specify `m` for 'match':
@@ -2157,18 +2038,16 @@ say $/[0]; # OUTPUT: «「ABC」 「ABC」␤»,
say $0; # The same as above.
-=begin comment
-Our capture is `$0` because it's the first and only one capture in the
-regexp. You might be wondering why it's an array, and the answer is simple:
-Some captures (indexed using `$0`, `$/[0]` or a named one) will be an array
-if and only if they can have more than one element. Thus any capture with
-`*`, `+` and `**` (whatever the operands), but not with `?`.
-Let's use examples to see that:
-
-NOTE: We quoted A B C to demonstrate that the whitespace between them isn't
-significant. If we want the whitespace to *be* significant there, we can use the
-`:sigspace` modifier.
-=end comment
+# Our capture is `$0` because it's the first and only one capture in the
+# regexp. You might be wondering why it's an array, and the answer is simple:
+# Some captures (indexed using `$0`, `$/[0]` or a named one) will be an array
+# if and only if they can have more than one element. Thus any capture with
+# `*`, `+` and `**` (whatever the operands), but not with `?`.
+# Let's use examples to see that:
+
+# NOTE: We quoted A B C to demonstrate that the whitespace between them isn't
+# significant. If we want the whitespace to *be* significant there, we can use the
+# `:sigspace` modifier.
say so 'fooABCbar' ~~ / foo ( "A" "B" "C" )? bar /; # OUTPUT: «True␤»
say $/[0]; # OUTPUT: «「ABC」␤»
say $0.WHAT; # OUTPUT: «(Match)␤»
@@ -2187,17 +2066,15 @@ say $0.WHAT; # OUTPUT: «(Array)␤», A specific quantifier will always capture
say $/[0].Str; # OUTPUT: «hello~␤»
say $/[0][0].Str; # OUTPUT: «~␤»
-=begin comment
-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.
-
-In the following example, we can see `$_` is a list of `Match` objects.
-Each of them contain a wealth of information: where the match started/ended,
-the "ast" (see actions later), etc. You'll see named capture below with
-grammars.
-=end comment
+# 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.
+
+# In the following example, we can see `$_` is a list of `Match` objects.
+# Each of them contain a wealth of information: where the match started/ended,
+# the "ast" (see actions later), etc. You'll see named capture below with
+# grammars.
say $/[0].list.perl; # OUTPUT: «(Match.new(...),).list␤»
# Alternation - the `or` of regexes
@@ -2210,19 +2087,17 @@ say so 'ayc' ~~ / a [ b | y ] c /; # OUTPUT: «True␤», Obviously enough...
# always try to match as much as possible in the string.
say 'foo' ~~ / fo | foo /; # OUTPUT: «foo», instead of `fo`, because it's longer.
-=begin comment
-To decide which part is the "longest", it first splits the regex in two parts:
-
- * The "declarative prefix" (the part that can be statically analyzed)
- which includes alternations (`|`), conjunctions (`&`), sub-rule calls (not
- yet introduced), literals, characters classes and quantifiers.
+# To decide which part is the "longest", it first splits the regex in two parts:
+#
+# * The "declarative prefix" (the part that can be statically analyzed)
+# which includes alternations (`|`), conjunctions (`&`), sub-rule calls (not
+# yet introduced), literals, characters classes and quantifiers.
+#
+# * The "procedural part" includes everything else: back-references,
+# code assertions, and other things that can't traditionally be represented
+# by normal regexps.
- * The "procedural part" includes everything else: back-references,
- code assertions, and other things that can't traditionally be represented
- by normal regexps.
-
-Then, all the alternatives are tried at once, and the longest wins.
-=end comment
+# Then, all the alternatives are tried at once, and the longest wins.
# Examples:
# DECLARATIVE | PROCEDURAL
@@ -2243,55 +2118,49 @@ say 'foo' ~~ / fo || foo /; # OUTPUT: «fo␤», in this case.
# 19. Extra: the MAIN subroutine
####################################################
-=begin comment
-The `MAIN` subroutine is called when you run a Raku file directly. It's
-very powerful, because Raku 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` flag.
-=end comment
+# The `MAIN` subroutine is called when you run a Raku file directly. It's
+# very powerful, because Raku 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` flag.
sub MAIN($name) {
say "Hello, $name!";
}
-=begin comment
-Supposing the code above is in file named cli.raku, then running in the command
-line (e.g., $ raku cli.raku) produces:
-Usage:
- cli.raku <name>
-=end comment
+# Supposing the code above is in file named cli.raku, then running in the command
+# line (e.g., $ raku cli.raku) produces:
+# Usage:
+# cli.raku <name>
-=begin comment
-And since MAIN is a regular Raku sub, you can have multi-dispatch:
-(using a `Bool` for the named argument so that we can do `--replace`
-instead of `--replace=1`. The presence of `--replace` indicates truthness
-while its absence falseness). For example:
+# And since MAIN is a regular Raku sub, you can have multi-dispatch:
+# (using a `Bool` for the named argument so that we can do `--replace`
+# instead of `--replace=1`. The presence of `--replace` indicates truthness
+# while its absence falseness). For example:
# convert to IO object to check the file exists
+ =begin comment
subset File of Str where *.IO.d;
multi MAIN('add', $key, $value, Bool :$replace) { ... }
multi MAIN('remove', $key) { ... }
multi MAIN('import', File, Str :$as) { ... } # omitting parameter name
+ =end comment
-Thus $ raku cli.raku produces:
-Usage:
- cli.raku [--replace] add <key> <value>
- cli.raku remove <key>
- cli.raku [--as=<Str>] import <File>
+# Thus $ raku cli.raku produces:
+# Usage:
+# cli.raku [--replace] add <key> <value>
+# cli.raku remove <key>
+# cli.raku [--as=<Str>] import <File>
-As you can see, this is *very* powerful. It even went as far as to show inline
-the constants (the type is only displayed if the argument is `$`/is named).
-=end comment
+# As you can see, this is *very* powerful. It even went as far as to show inline
+# the constants (the type is only displayed if the argument is `$`/is named).
####################################################
# 20. APPENDIX A:
####################################################
-=begin comment
-It's assumed by now you know the Raku basics. This section is just here to
-list some common operations, but which are not in the "main part" of the
-tutorial to avoid bloating it up.
-=end comment
+# It's assumed by now you know the Raku basics. This section is just here to
+# list some common operations, but which are not in the "main part" of the
+# tutorial to avoid bloating it up.
#
# 20.1 Operators
@@ -2316,14 +2185,12 @@ say Any // Nil // 0 // 5; # OUTPUT: «0␤»
# its arguments is true
say True ^^ False; # OUTPUT: «True␤»
-=begin comment
-Flip flops. These operators (`ff` and `fff`, equivalent to P5's `..`
-and `...`) are operators that take two predicates to test: They are `False`
-until their left side returns `True`, then are `True` until their right
-side returns `True`. Similar to ranges, you can exclude the iteration when
-it become `True`/`False` by using `^` on either side. Let's start with an
-example :
-=end comment
+# Flip flops. These operators (`ff` and `fff`, equivalent to P5's `..`
+# and `...`) are operators that take two predicates to test: They are `False`
+# until their left side returns `True`, then are `True` until their right
+# side returns `True`. Similar to ranges, you can exclude the iteration when
+# it become `True`/`False` by using `^` on either side. Let's start with an
+# example :
for <well met young hero we shall meet later> {
# by default, `ff`/`fff` smart-match (`~~`) against `$_`:
@@ -2336,20 +2203,16 @@ for <well met young hero we shall meet later> {
}
}
-=begin comment
-This will print "young hero we shall meet" (excluding "met"): the flip-flop
-will start returning `True` when it first encounters "met" (but will still
-return `False` for "met" itself, due to the leading `^` on `ff`), until it
-sees "meet", which is when it'll start returning `False`.
-=end comment
+# This will print "young hero we shall meet" (excluding "met"): the flip-flop
+# will start returning `True` when it first encounters "met" (but will still
+# return `False` for "met" itself, due to the leading `^` on `ff`), until it
+# sees "meet", which is when it'll start returning `False`.
-=begin comment
-The difference between `ff` (awk-style) and `fff` (sed-style) is that `ff`
-will test its right side right when its left side changes to `True`, and can
-get back to `False` right away (*except* it'll be `True` for the iteration
-that matched) while `fff` will wait for the next iteration to try its right
-side, once its left side changed:
-=end comment
+# The difference between `ff` (awk-style) and `fff` (sed-style) is that `ff`
+# will test its right side right when its left side changes to `True`, and can
+# get back to `False` right away (*except* it'll be `True` for the iteration
+# that matched) while `fff` will wait for the next iteration to try its right
+# side, once its left side changed:
# The output is due to the right-hand-side being tested directly (and returning
# `True`). "B"s are printed since it matched that time (it just went back to
@@ -2399,7 +2262,7 @@ This information may be a bit older but there are many great examples and
explanations. Posts stopped at the end of 2015 when the language was declared
stable and `Raku v6.c` was released.
-- Come along on `#raku` at [`irc.freenode.net`](https://webchat.freenode.net/?channels=#raku). The folks here are
+- Come along on `#raku` at [`irc.libera.chat`](https://web.libera.chat/?channel=#raku). The folks here are
always helpful.
- Check the [source of Raku's functions and
diff --git a/ro-ro/bash-ro.html.markdown b/ro-ro/bash-ro.html.markdown
index 32a878b2..de946861 100644
--- a/ro-ro/bash-ro.html.markdown
+++ b/ro-ro/bash-ro.html.markdown
@@ -12,7 +12,7 @@ lang: ro-ro
filename: LearnBash-ro.sh
---
-Bash este numele shell-ului UNIX, care a fost de asemenea distribuit drept shell pentru sistemul de operare GNU și ca shell implicit pentru Linux si Mac OS X.
+Bash este numele shell-ului UNIX, care a fost de asemenea distribuit drept shell pentru sistemul de operare GNU și ca shell implicit pentru Linux si macOS.
Aproape toate exemplele de mai jos pot fi parte dintr-un script sau pot fi executate direct in linia de comanda.
[Citește mai multe:](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/ru-ru/bash-ru.html.markdown b/ru-ru/bash-ru.html.markdown
index ce918340..9978380a 100644
--- a/ru-ru/bash-ru.html.markdown
+++ b/ru-ru/bash-ru.html.markdown
@@ -26,7 +26,7 @@ lang: ru-ru
Bash — это командная оболочка unix, которая распространялась как оболочка
для операционной системы GNU и используется в качестве оболочки по умолчанию
-для Linux и Mac OS X.
+для Linux и macOS.
Почти все нижеприведённые примеры могут быть частью shell-скриптов
или исполнены напрямую в shell.
diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown
index ba3c19ee..cc68d620 100644
--- a/ru-ru/c-ru.html.markdown
+++ b/ru-ru/c-ru.html.markdown
@@ -353,7 +353,7 @@ int main() {
// Это не работает, если строка является массивом
// (потенциально задаваемой с помощью строкового литерала)
- // который находиться в перезаписываемой части памяти:
+ // который находится в перезаписываемой части памяти:
char foo[] = "foo";
foo[0] = 'a'; // это выполнится и строка теперь "aoo"
diff --git a/ru-ru/forth-ru.html.markdown b/ru-ru/forth-ru.html.markdown
index 05316578..2fc4ad7c 100644
--- a/ru-ru/forth-ru.html.markdown
+++ b/ru-ru/forth-ru.html.markdown
@@ -12,9 +12,10 @@ lang: ru-ru
Внимание: эта материал использует реализацию Форта - Gforth, но большая часть написанного будет работать в других средах.
+
```
\ Это комментарий
-( Это тоже комментарий, но использыется для предоределённых слов )
+( Это тоже комментарий, но используется для предоределённых слов )
\ --------------------------------- Прекурсор --------------------------------
diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown
index c31c6994..4556b425 100644
--- a/ru-ru/javascript-ru.html.markdown
+++ b/ru-ru/javascript-ru.html.markdown
@@ -473,7 +473,7 @@ if (0) {
}
// Впрочем, объекты-обёртки и встроенные типы имеют общие прототипы,
-// поэтому вы можете расширить функционал строк, например:
+// поэтому вы можете расширить функциональность строк, например:
String.prototype.firstCharacter = function() {
return this.charAt(0);
}
diff --git a/ru-ru/kotlin-ru.html.markdown b/ru-ru/kotlin-ru.html.markdown
index 85f44c96..6ec52927 100644
--- a/ru-ru/kotlin-ru.html.markdown
+++ b/ru-ru/kotlin-ru.html.markdown
@@ -333,7 +333,7 @@ fun helloWorld(val name : String) {
}
/*
- Расширения - это способ добавить новый функционал к классу.
+ Расширения - это способ добавить новую функциональность к классу.
Это то же самое, что методы расширений в C#.
*/
fun String.remove(c: Char): String {
diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown
index da9ced6a..6bfea4bb 100644
--- a/ru-ru/lua-ru.html.markdown
+++ b/ru-ru/lua-ru.html.markdown
@@ -98,7 +98,7 @@ end
-- Вложенные и анонимные функции являются нормой:
function adder(x)
- -- Возращаемая функция создаётся, когда вызывается функция adder,
+ -- Возвращаемая функция создаётся, когда вызывается функция adder,
-- и запоминает значение переменной x:
return function (y) return x + y end
end
@@ -363,7 +363,7 @@ end
return M
--- Другой файл может использовать функционал mod.lua:
+-- Другой файл может использовать функциональность mod.lua:
local mod = require('mod') -- Запустим файл mod.lua.
-- require - стандартный способ подключения модулей.
diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown
index 3baa15f8..6c7d9f6c 100644
--- a/ru-ru/objective-c-ru.html.markdown
+++ b/ru-ru/objective-c-ru.html.markdown
@@ -12,7 +12,7 @@ lang: ru-ru
---
Objective-C — основной язык программирования, используемый корпорацией Apple
-для операционных систем OS X и iOS и их соответствующих фреймворках Cocoa и
+для операционных систем macOS и iOS и их соответствующих фреймворках Cocoa и
Cocoa Touch.
Он является объектно-ориентированным языком программирования общего назначения,
который добавляет обмен сообщениями в Smalltalk-стиле к языку программирования C.
@@ -507,8 +507,8 @@ distance = 18; // Ссылается на "long distance" из реализац
@end
// Теперь, если мы хотим создать объект Truck - грузовик, мы должны создать подкласс класса Car, что
-// изменит функционал Car и позволит вести себя подобно грузовику. Но что, если мы хотим только добавить
-// определенный функционал в уже существующий класс Car? Например - чистка автомобиля. Мы просто создадим
+// изменит функциональность Car и позволит вести себя подобно грузовику. Но что, если мы хотим только добавить
+// определенную функциональность в уже существующий класс Car? Например - чистка автомобиля. Мы просто создадим
// категорию, которая добавит несколько методов для чистки автомобиля в класс Car:
// @interface ИмяФайла: Car+Clean.h (ИмяБазовогоКласса+ИмяКатегории.h)
#import "Car.h" // Убедитесь в том, что базовый класс импортирован для расширения.
diff --git a/ru-ru/rust-ru.html.markdown b/ru-ru/rust-ru.html.markdown
index 9293a40e..d46d301c 100644
--- a/ru-ru/rust-ru.html.markdown
+++ b/ru-ru/rust-ru.html.markdown
@@ -226,7 +226,7 @@ fn main() {
// `for` loops/iteration
let array = [1, 2, 3];
- for i in array.iter() {
+ for i in array {
println!("{}", i);
}
diff --git a/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown
index f2b1fd36..bd2d23a0 100644
--- a/ru-ru/swift-ru.html.markdown
+++ b/ru-ru/swift-ru.html.markdown
@@ -13,7 +13,7 @@ lang: ru-ru
---
Swift - это язык программирования, созданный компанией Apple, для приложений
-под iOS и OS X. Разработанный, чтобы сосуществовать с Objective-C и
+под iOS и macOS. Разработанный, чтобы сосуществовать с Objective-C и
быть более устойчивым к ошибочному коду, Swift был представлен в 2014 году на
конференции разработчиков Apple, WWDC. Приложения на Swift собираются
с помощью LLVM-компилятора, включенного в Xcode 6+.
@@ -622,7 +622,7 @@ class MyShape: Rect {
// MARK: Прочее
//
-// `extension`s: Добавляет расширенный функционал к существующему типу
+// `extension`s: Добавляет расширенную функциональность к существующему типу
// Класс Square теперь "соответствует" протоколу `CustomStringConvertible`
extension Square: CustomStringConvertible {
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 4b96b71c..8e5f924a 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -670,4 +670,4 @@ Something.new.qux #=> "qux"
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
-- [Try Ruby](http://tryruby.org) - Learn the basic of Ruby programming language, interactive in the browser.
+- [Try Ruby](https://try.ruby-lang.org/) - Learn the basic of Ruby programming language, interactive in the browser.
diff --git a/rust.html.markdown b/rust.html.markdown
index e835de12..9e07e005 100644
--- a/rust.html.markdown
+++ b/rust.html.markdown
@@ -89,11 +89,16 @@ fn main() {
println!("{} {}", f, x); // 1.3 hello world
// A `String` – a heap-allocated string
+ // Stored as a `Vec<u8>` and always hold a valid UTF-8 sequence,
+ // which is not null terminated.
let s: String = "hello world".to_string();
// A string slice – an immutable view into another string
- // The string buffer can be statically allocated like in a string literal
- // or contained in another object (in this case, `s`)
+ // This is basically an immutable pair of pointers to a string – it doesn’t
+ // actually contain the contents of a string, just a pointer to
+ // the begin and a pointer to the end of a string buffer,
+ // statically allocated or contained in another object (in this case, `s`).
+ // The string slice is like a view `&[u8]` into `Vec<T>`.
let s_slice: &str = &s;
println!("{} {}", s, s_slice); // hello world hello world
@@ -205,6 +210,21 @@ fn main() {
let another_foo = Foo { bar: 1 };
println!("{:?}", another_foo.frobnicate()); // Some(1)
+ // Function pointer types //
+
+ fn fibonacci(n: u32) -> u32 {
+ match n {
+ 0 => 1,
+ 1 => 1,
+ _ => fibonacci(n - 1) + fibonacci(n - 2),
+ }
+ }
+
+ type FunctionPointer = fn(u32) -> u32;
+
+ let fib : FunctionPointer = fibonacci;
+ println!("Fib: {}", fib(4));
+
/////////////////////////
// 3. Pattern matching //
/////////////////////////
@@ -236,7 +256,7 @@ fn main() {
// `for` loops/iteration
let array = [1, 2, 3];
- for i in array.iter() {
+ for i in array {
println!("{}", i);
}
diff --git a/scala.html.markdown b/scala.html.markdown
index 08fd37e4..d2d45dc9 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -481,7 +481,7 @@ class SaintBernard extends Dog {
def bite = false
}
-scala> b
+scala> val b = new SaintBernard
res0: SaintBernard = SaintBernard@3e57cd70
scala> b.breed
res1: String = Saint Bernard
@@ -599,7 +599,7 @@ List("Dom", "Bob", "Natalia") foreach println
s.map(sq)
-val sSquared = s. map(sq)
+val sSquared = s.map(sq)
sSquared.filter(_ < 10)
@@ -717,7 +717,7 @@ 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 a scala file using an object, with a
+// Your program's entry point is defined in a scala file using an object, with a
// single method, main:
object Application {
def main(args: Array[String]): Unit = {
diff --git a/set-theory.html.markdown b/set-theory.html.markdown
index 6be7aa00..d55ab7d5 100644
--- a/set-theory.html.markdown
+++ b/set-theory.html.markdown
@@ -13,7 +13,7 @@ Set theory is a branch of mathematics that studies sets, their operations, and t
* the union operator, `∪`, pronounced "cup", means "or";
* the intersection operator, `∩`, pronounced "cap", means "and";
* the exclusion operator, `\`, means "without";
-* the compliment operator, `'`, means "the inverse of";
+* the complement operator, `'`, means "the inverse of";
* the cross operator, `×`, means "the Cartesian product of".
### Qualifiers
@@ -41,7 +41,7 @@ The cardinality, or size, of a set is determined by the number of items in the s
For example, if `S = { 1, 2, 4 }`, then `|S| = 3`.
### The Empty Set
-* The empty set can be constructed in set builder notation using impossible conditions, e.g. `∅ = { x : x =/= x }`, or `∅ = { x : x ∈ N, x < 0 }`;
+* The empty set can be constructed in set builder notation using impossible conditions, e.g. `∅ = { x : x ≠ x }`, or `∅ = { x : x ∈ N, x < 0 }`;
* the empty set is always unique (i.e. there is one and only one empty set);
* the empty set is a subset of all sets;
* the cardinality of the empty set is 0, i.e. `|∅| = 0`.
@@ -87,7 +87,7 @@ D = { 2x : x ∈ N } = { 0, 2, 4, 6, 8, ... }
## Special Sets
### The Power Set
-* Let `A` be any set. The set that contains all possible subsets of `A` is called a "power set" and is written as `P(A)`. If the set `A` contains `n` elements, then `P(A)` contains `2^N` elements.
+* Let `A` be any set. The set that contains all possible subsets of `A` is called a "power set" and is written as `P(A)`. If the set `A` contains `n` elements, then `P(A)` contains `2^n` elements.
```
P(A) = { x : x ⊆ A }
diff --git a/sing.html.markdown b/sing.html.markdown
new file mode 100644
index 00000000..2e439800
--- /dev/null
+++ b/sing.html.markdown
@@ -0,0 +1,446 @@
+---
+name: Sing
+category: language
+language: Sing
+filename: learnsing.sing
+contributors:
+ - ["Maurizio De Girolami", "https://github.com/mdegirolami"]
+---
+
+The purpose of sing is to provide a simple, safe, fast language that
+can be a good replacement for c++ for high performance applications.
+
+Sing is an easy choice because it compiles to human-quality readable c++.
+
+Because of that, if you work for a while with Sing and, at any time, you discover you don't like Sing anymore, you lose nothing of your work
+because you are left with nice and clean c++ code.
+
+In some way you can also think Sing as a tool to write c++ in a way that enforces some best practices.
+
+```go
+/* Multi- line comment.
+ /* It can be nested */
+ Use it to remark-out part of the code.
+ It leaves no trace in the intermediate c++ code.
+ (sing translates into nice human readable c++)
+*/
+
+// Single line comment, can be placed only before a statement or declaration...
+// ...or at the right of the first line of a statement or declaration.
+// single line comments are kept into c++.
+//
+// here we declare if we need to use public declarations from other files.
+// (in this case from files 'sio', 'sys')
+requires "sio";
+requires "sys";
+
+//
+// A sing function declaration.
+// All the declarations can be made public with the 'public' keyword.
+// All the declarations start with a keyword specifying the type of declaration
+// (in this case fn for function) then follows the name, the arguments and the
+// return type.
+//
+// Each argument starts with a direction qualifyer (in, out, io) which tells if
+// the argument is an input, an output or both...
+// ...then follows the argument name and the type.
+public fn singmain(in argv [*]string) i32
+{
+ // print is from the sio file and sends a string to the console
+ sio.print("Hello World\n");
+
+ // type conversions are allowed in the form of <newtype>(expression).
+ sio.print(string(sum(5, 10)) + "\n");
+
+ // For clarity you can specify after an argument its name separated by ':'.
+ var result i32;
+ recursive_power(10:base, 3:exponent, result);
+
+ // referred here to avoid a 'not used' error.
+ learnTypes();
+
+ // functions can only return a single value of some basic type.
+ return(0);
+}
+
+// You can have as many arguments as you want, comma separated.
+// You can also omit the 'in' direction qualifyer (it is the default).
+fn sum(arg1 i32, arg2 i32) i32
+{
+ // as 'fn' declares a function, 'let' declares a constant.
+ // With constants, if you place an initializer, you can omit the type.
+ let the_sum = arg1 + arg2;
+
+ return(the_sum);
+}
+
+// Arguments are passed by reference, which means that in the function body you
+// use the argument names to refer to the passed variables.
+// Example: all the functions in the recursion stack access the same 'result'
+// variable, supplied by the singmain function.
+fn recursive_power(base i32, exponent i32, out result i32) void
+{
+ if (exponent == 0) {
+ result = 1;
+ } else {
+ recursive_power(base, exponent - 1, result);
+ result *= base;
+ }
+}
+
+//**********************************************************
+//
+// TYPES
+//
+//**********************************************************
+fn learnTypes() void
+{
+ // the var keyword declares mutable variables
+ // in this case an UTF-8 encoded string
+ var my_name string;
+
+ // ints of 8..64 bits size
+ var int0 i8;
+ var int1 i16;
+ var int2 i32;
+ var int3 i64;
+
+ // uints
+ var uint0 u8;
+ var uint1 u16;
+ var uint2 u32;
+ var uint3 u64;
+
+ // floats
+ var float0 f32;
+ var float1 f64;
+
+ // complex
+ var cmplx0 c64;
+ var cmplx1 c128;
+
+ cmplx0 = 0;
+ cmplx1 = 0;
+
+ // and of course...
+ var bool0 bool;
+
+ // type inference: by default constants are i32, f32, c64
+ let an_int32 = 15;
+ let a_float32 = 15.0;
+ let a_complex = 15.0 + 3i;
+ let a_string = "Hello !";
+ let a_bool = false;
+
+ // To create constant of different types use a conversion-like syntax:
+ // NOTE: this is NOT a conversion. Just a type specification
+ let a_float64 = f64(5.6);
+
+ // in a type definition [] reads as "array of"
+ // in the example []i32 => array of i32.
+ var intarray []i32 = {1, 2, 3};
+
+ // You can specify a length, else the length is given by the initializer
+ // the last initializer is replicated on the extra items
+ var sizedarray [10]i32 = {1, 2, 3};
+
+ // Specify * as the size to get a dynamic array (can change its length)
+ var dyna_array [*]i32;
+
+ // you can append items to a vector invoking a method-like function on it.
+ dyna_array.push_back(an_int32);
+
+ // getting the size of the array. sys.validate() is like assert in c
+ sys.validate(dyna_array.size() == 1);
+
+ // a map that associates a number to a string.
+ // "map(x)..." reads "map with key of type x and vaue of type..."
+ var a_map map(string)i32;
+
+ a_map.insert("one", 1);
+ a_map.insert("two", 2);
+ a_map.insert("three", 3);
+ let key = "two";
+
+ // note: the second argument of get_safe is the value to be returned
+ // when the key is not found.
+ sio.print("\nAnd the value is...: " + string(a_map.get_safe(key, -1)));
+
+ // string concatenation
+ my_name = "a" + "b";
+}
+
+// an enum type can only have a value from a discrete set.
+// can't be converted to/from int !
+enum Stages {first, second, last}
+
+// you can refer to enum values (to assign/compare them)
+// specifying both the typename and tagname separated with the '.' operator
+var current_stage = Stages.first;
+
+
+//**********************************************************
+//
+// POINTERS
+//
+//**********************************************************
+
+// This is a factory for a dynamic vector.
+// In a type declaration '*' reads 'pointer to..'
+// so the return type is 'pointer to a vector of i32'
+fn vectorFactory(first i32, last i32) *[*]i32
+{
+ var buffer [*]i32;
+
+ // fill
+ for (value in first : last) {
+ buffer.push_back(value);
+ }
+
+ // The & operator returns the address of the buffer.
+ // You can only use & on local variables
+ // As you use & on a variable, that variable is allocated on the HEAP.
+ return(&buffer);
+}
+
+fn usePointers() void
+{
+ var bufferptr = vectorFactory(0, 100);
+
+ // you don't need to use the factory pattern to use pointers.
+ var another_buffer [*]i32;
+ var another_bufferptr = &another_buffer;
+
+ // you can dereference a pointer with the * operator
+ // sys.validate is an assertion (causes a signal if the argument is false)
+ sys.validate((*bufferptr)[0] == 0);
+
+ /*
+ // as all the pointers to a variable exit their scope the variable is
+ // no more accessible and is deleted (freed)
+ */
+}
+
+//**********************************************************
+//
+// CLASSES
+//
+//**********************************************************
+
+// This is a Class. The member variables can be directly initialized here
+class AClass {
+public:
+ var public_var = 100; // same as any other variable declaration
+ fn is_ready() bool; // same as any other function declaration
+ fn mut finalize() void; // destructor (called on object deletion)
+private:
+ var private_var string;
+
+ // Changes the member variables and must be marked as 'mut' (mutable)
+ fn mut private_fun(errmsg string) void;
+}
+
+// How to declare a member function
+fn AClass.is_ready() bool
+{
+ // inside a member function, members can be accessed thrugh the
+ // this keyword and the field selector '.'
+ return(this.public_var > 10);
+}
+
+fn AClass.private_fun(errmsg string) void
+{
+ this.private_var = errmsg;
+}
+
+// using a class
+fn useAClass() void
+{
+ // in this way you create a variable of type AClass.
+ var instance AClass;
+
+ // then you can access its members through the '.' operator.
+ if (instance.is_ready()) {
+ instance.public_var = 0;
+ }
+}
+
+//**********************************************************
+//
+// INTERFACES
+//
+//**********************************************************
+
+// You can use polymorphism in sing defining an interface...
+interface ExampleInterface {
+ fn mut eraseAll() void;
+ fn identify_myself() void;
+}
+
+// and then creating classes which implement the interface
+// NOTE: you don't need (and cannot) re-declare the interface functions
+class Implementer1 : ExampleInterface {
+private:
+ var to_be_erased i32 = 3;
+public:
+ var only_on_impl1 = 0;
+}
+
+class Implementer2 : ExampleInterface {
+private:
+ var to_be_erased f32 = 3;
+}
+
+fn Implementer1.eraseAll() void
+{
+ this.to_be_erased = 0;
+}
+
+fn Implementer1.identify_myself() void
+{
+ sio.print("\nI'm the terrible int eraser !!\n");
+}
+
+fn Implementer2.eraseAll() void
+{
+ this.to_be_erased = 0;
+}
+
+fn Implementer2.identify_myself() void
+{
+ sio.print("\nI'm the terrible float eraser !!\n");
+}
+
+fn interface_casting() i32
+{
+ // upcasting is automatic (es: *Implementer1 to *ExampleInterface)
+ var concrete Implementer1;
+ var if_ptr *ExampleInterface = &concrete;
+
+ // you can access interface members with (guess what ?) '.'
+ if_ptr.identify_myself();
+
+ // downcasting requires a special construct
+ // (see also below the conditional structures)
+ typeswitch(ref = if_ptr) {
+ case *Implementer1: return(ref.only_on_impl1);
+ case *Implementer2: {}
+ default: return(0);
+ }
+
+ return(1);
+}
+
+// All the loop types
+fn loops() void
+{
+ // while: the condition must be strictly of boolean type
+ var idx = 0;
+ while (idx < 10) {
+ ++idx;
+ }
+
+ // for in an integer range. The last value is excluded
+ // 'it' is local to the loop and must not be previously declared
+ for (it in 0 : 10) {
+ }
+
+ // reverse direction
+ for (it in 10 : 0) {
+ }
+
+ // configurable step. The loop stops when it's >= the final value
+ for (it in 0 : 100 step 3) {
+ }
+
+ // with an auxiliary counter.
+ // The counter start always at 0 and increments by one at each iteration
+ for (counter, it in 3450 : 100 step -22) {
+ }
+
+ // value assumes in turn all the values from array
+ var array [*]i32 = {0, 10, 100, 1000};
+ for (value in array) {
+ }
+
+ // as before with auxiliary counter
+ for (counter, value in array) {
+ }
+}
+
+// All the conditional structures
+interface intface {}
+class c0_test : intface {public: fn c0stuff() void;}
+class delegating : intface {}
+
+fn conditionals(in object intface, in objptr *intface) void
+{
+ let condition1 = true;
+ let condition2 = true;
+ let condition3 = true;
+ var value = 30;
+
+ // condition1 must be a boolean.
+ if (condition1) {
+ ++value; // conditioned statement
+ }
+
+ // you can chain conditions with else if
+ if (condition1) {
+ ++value;
+ } else if (condition2) {
+ --value;
+ }
+
+ // a final else runs if any other condition is false
+ if (condition1) {
+ ++value;
+ } else if (condition2) {
+ --value;
+ } else {
+ value = 0;
+ }
+
+ // based on the switch value selects a case statement
+ switch (value) {
+ case 0: sio.print("value is zero"); // a single statement !
+ case 1: {} // do nothing
+ case 2: // falls through
+ case 3: sio.print("value is more than one");
+ case 4: { // a block is a single statement !
+ value = 0;
+ sio.print("how big !!");
+ }
+ default: return; // if no one else matches
+ }
+
+ // similar to a switch but selects a case based on argument type.
+ // - object must be a function argument of type interface.
+ // - the case types must be classes implementing the object interface.
+ // - in each case statement, ref assumes the class type of that case.
+ typeswitch(ref = object) {
+ case c0_test: ref.c0stuff();
+ case delegating: {}
+ default: return;
+ }
+
+ // - object must be an interface pointer.
+ // - the case types must be pointers to classes implementing the objptr interface.
+ // - in each case statement, ref assumes the class pointer type of that case.
+ typeswitch(ref = objptr) {
+ case *c0_test: {
+ ref.c0stuff();
+ return;
+ }
+ case *delegating: {}
+ default: sio.print("unknown pointer type !!");
+ }
+}
+```
+
+## Further Reading
+
+[official Sing web site](https://mdegirolami.wixsite.com/singlang).
+
+If you want to play with sing you are recommended to download the vscode plugin. Please
+follow the instructions at [Getting Started](https://mdegirolami.wixsite.com/singlang/copy-of-interfacing-sing-and-c-2)
diff --git a/sk-sk/bash-sk.html.markdown b/sk-sk/bash-sk.html.markdown
index e9d1490c..1b0f48d4 100644
--- a/sk-sk/bash-sk.html.markdown
+++ b/sk-sk/bash-sk.html.markdown
@@ -19,7 +19,7 @@ filename: LearnBash-sk.sh
Bash je pomenovanie pre unix shell (príkazový interpreter), ktorý bol
tiež distribuovaný ako shell pre GNU operačné systémy a ako predvolený
-shell pre Linux a Mac OS X.
+shell pre Linux a macOS.
Takmer všetky príklady uvedené nižšie môžu byť súčasťou shell skriptu alebo
vykonané priamo v shelli.
diff --git a/solidity.html.markdown b/solidity.html.markdown
index cc719ec7..5f8ef407 100644
--- a/solidity.html.markdown
+++ b/solidity.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Joseph Chow", ""]
- ["Bhoomtawath Plinsut", "https://github.com/varshard"]
- ["Shooter", "https://github.com/liushooter"]
+ - ["Patrick Collins", "https://gist.github.com/PatrickAlphaC"]
---
Solidity lets you program on [Ethereum](https://www.ethereum.org/), a
@@ -18,7 +19,7 @@ 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.
+Some Ethereum contract examples include crowdfunding, voting, [decentralized finance](https://defipulse.com/), and blind auctions.
There is a high risk and high cost of errors in Solidity code, so you must be very careful to test
and slowly rollout. WITH THE RAPID CHANGES IN ETHEREUM, THIS DOCUMENT IS UNLIKELY TO STAY UP TO
@@ -32,6 +33,66 @@ popular design patterns.
As Solidity and Ethereum are under active development, experimental or beta
features are typically marked, and subject to change. Pull requests welcome.
+# Working with Remix and Metamask
+
+One of the easiest ways to build, deploy, and test solidity code is by using the:
+
+1. [Remix Web IDE](https://remix.ethereum.org/)
+2. [Metamask wallet](https://metamask.io/).
+
+To get started, [download the Metamask Browser Extension](https://metamask.io/).
+
+Once installed, we will be working with Remix. The below code will be pre-loaded, but before we head over there, let's look at a few tips to get started with remix. Load it all by [hitting this link](https://remix.ethereum.org/#version=soljson-v0.6.6+commit.6c089d02.js&optimize=false&evmVersion=null&gist=f490c0d51141dd0515244db40bbd0c17&runs=200).
+
+1. Choose the Solidity compiler
+
+![Solidity-in-remix](images/solidity/remix-solidity.png)
+
+2. Open the file loaded by that link
+
+![Solidity-choose-file](images/solidity/remix-choose-file.png)
+
+3. Compile the file
+
+![Solidity-compile](images/solidity/remix-compile.png)
+
+4. Deploy
+
+![Solidity-deploy](images/solidity/remix-deploy.png)
+
+5. Play with contracts
+
+![Solidity-deploy](images/solidity/remix-interact.png)
+
+You've deployed your first contract! Congrats!
+
+You can test out and play with the functions defined. Check out the comments to learn about what each does.
+
+
+## Working on a testnet
+
+Deploying and testing on a testnet is the most accurate way to test your smart contracts in solidity.
+To do this let's first get some testnet ETH from the Kovan testnet.
+
+[Pop into this Gitter Channel](https://gitter.im/kovan-testnet/faucet) and drop your metamask address in.
+
+In your metamask, you'll want to change to the `Kovan` testnet.
+
+![Solidity-in-remix](images/solidity/metamask-kovan.png)
+
+You'll be given some free test Ethereum. Ethereum is needed to deploy smart contracts when working with a testnet.
+
+In the previous example, we didn't use a testnet, we deployed to a fake virtual environment.
+When working with a testnet, we can actually see and interact with our contracts in a persistent manner.
+
+To deploy to a testnet, on the `#4 Deploy` step, change your `environment` to `injected web3`.
+This will use whatever network is currently selected in your metamask as the network to deploy to.
+
+![Solidity-in-remix](images/solidity/remix-testnet.png)
+
+For now, please continue to use the `Javascript VM` unless instructed otherwise. When you deploy to a testnet, metamask will pop up to ask you to "confirm" the transaction. Hit yes, and after a delay, you'll get the same contract interface at the bottom of your screen.
+
+
```javascript
// First, a simple Bank contract
// Allows deposits, withdrawals, and balance checks
@@ -40,7 +101,7 @@ features are typically marked, and subject to change. Pull requests welcome.
/* **** START EXAMPLE **** */
// Declare the source file compiler version
-pragma solidity ^0.4.19;
+pragma solidity ^0.6.6;
// Start with Natspec comment (the three slashes)
// used for documentation - and as descriptive data for UI elements/actions
@@ -67,7 +128,7 @@ contract SimpleBank { // CapWords
event LogDepositMade(address accountAddress, uint amount);
// Constructor, can receive one or many variables here; only one allowed
- function SimpleBank() public {
+ constructor() public {
// msg provides details about the message that's sent to the contract
// msg.sender is contract caller (address of contract creator)
owner = msg.sender;
@@ -84,7 +145,7 @@ contract SimpleBank { // CapWords
// no "this." or "self." required with state variable
// all values set to data type's initial value by default
- LogDepositMade(msg.sender, msg.value); // fire event
+ emit LogDepositMade(msg.sender, msg.value); // fire event
return balances[msg.sender];
}
@@ -92,7 +153,7 @@ contract SimpleBank { // CapWords
/// @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
+ /// @return remainingBal
function withdraw(uint withdrawAmount) public returns (uint remainingBal) {
require(withdrawAmount <= balances[msg.sender]);
@@ -153,7 +214,8 @@ assert(c >= a); // assert tests for internal invariants; require is used for use
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
-// No random functions built in, use other contracts for randomness
+// No random functions built in, you can get a pseduo-random number by hashing the current blockhash, or get a truely random number using something like Chainlink VRF.
+// https://docs.chain.link/docs/get-a-random-number
// Type casting
int x = int(b);
@@ -233,7 +295,7 @@ 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)
+uint[][5] x; // arr with 5 dynamic array elements (opp order of most languages)
// Dictionaries (any type to any other type)
mapping (string => uint) public balances;
@@ -584,9 +646,35 @@ reveal(100, "mySecret");
// All data to start of time is stored in blockchain, so
// anyone can observe all previous data and changes
+// E. Oracles and External Data
+// Oracles are ways to interact with your smart contracts outside the blockchain.
+// They are used to get data from the real world, send post requests, to the real world
+// or vise versa.
+
+// Time-based implementations of contracts are also done through oracles, as
+// contracts need to be directly called and can not "subscribe" to a time.
+// Due to smart contracts being decentralized, you also want to get your data
+// in a decentralized manner, other your run into the centralized risk that
+// smart contract design matter prevents.
+
+// To easiest way get and use pre-boxed decentralized data is with Chainlink Data Feeds
+// https://docs.chain.link/docs/get-the-latest-price
+// We can reference on-chain reference points that have already been aggregated by
+// multiple sources and delivered on-chain, and we can use it as a "data bank"
+// of sources.
+
+// You can see other examples making API calls here:
+// https://docs.chain.link/docs/make-a-http-get-request
+
+// And you can of course build your own oracle network, just be sure to know
+// how centralized vs decentralized your application is.
+
+// Setting up oracle networks yourself
+
// 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
@@ -628,23 +716,26 @@ contract SomeOracle {
// F. State machines
// see example below for State enum and inState modifier
+```
+Work with the full example below using the [`Javascript VM` in remix here.](https://remix.ethereum.org/#version=soljson-v0.6.6+commit.6c089d02.js&optimize=false&evmVersion=null&gist=3d12cd503dcedfcdd715ef61f786be0b&runs=200)
+```javascript
// *** EXAMPLE: A crowdfunding example (broadly similar to Kickstarter) ***
// ** START EXAMPLE **
// CrowdFunder.sol
-pragma solidity ^0.4.19;
+pragma solidity ^0.6.6;
/// @title CrowdFunder
/// @author nemild
contract CrowdFunder {
// Variables set on create by creator
address public creator;
- address public fundRecipient; // creator may be different than recipient
+ address payable public fundRecipient; // creator may be different than recipient, and must be payable
uint public minimumToRaise; // required to tip, else everyone gets refund
string campaignUrl;
- byte constant version = 1;
+ byte version = "1";
// Data structures
enum State {
@@ -654,7 +745,7 @@ contract CrowdFunder {
}
struct Contribution {
uint amount;
- address contributor;
+ address payable contributor;
}
// State variables
@@ -684,10 +775,10 @@ contract CrowdFunder {
_;
}
- function CrowdFunder(
+ function crowdFund(
uint timeInHoursForFundraising,
- string _campaignUrl,
- address _fundRecipient,
+ string memory _campaignUrl,
+ address payable _fundRecipient,
uint _minimumToRaise)
public
{
@@ -712,7 +803,7 @@ contract CrowdFunder {
);
totalRaised += msg.value;
- LogFundingReceived(msg.sender, msg.value, totalRaised);
+ emit LogFundingReceived(msg.sender, msg.value, totalRaised);
checkIfFundingCompleteOrExpired();
return contributions.length - 1; // return id
@@ -736,7 +827,7 @@ contract CrowdFunder {
public
inState(State.Successful)
{
- fundRecipient.transfer(this.balance);
+ fundRecipient.transfer(address(this).balance);
LogWinnerPaid(fundRecipient);
}
@@ -766,6 +857,11 @@ contract CrowdFunder {
}
// ** END EXAMPLE **
+```
+
+Some more functions.
+
+```javascript
// 10. OTHER NATIVE FUNCTIONS
// Currency units
@@ -837,18 +933,27 @@ someContractAddress.callcode('function_name');
## Additional resources
- [Solidity Docs](https://solidity.readthedocs.org/en/latest/)
+- [Chainlink Beginner Tutorials](https://docs.chain.link/docs/beginners-tutorial)
- [Smart Contract Best Practices](https://github.com/ConsenSys/smart-contract-best-practices)
- [Superblocks Lab - Browser based IDE for Solidity](https://lab.superblocks.com/)
- [EthFiddle - The JsFiddle for Solidity](https://ethfiddle.com/)
- [Browser-based Solidity Editor](https://remix.ethereum.org/)
- [Gitter Solidity Chat room](https://gitter.im/ethereum/solidity)
- [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/)
+- [Chainlink Documentation](https://docs.chain.link/docs/getting-started)
+
+## Smart Contract Development Frameworks
+- [Hardhat](https://hardhat.org/)
+- [Brownie](https://github.com/eth-brownie/brownie)
+- [Truffle](https://www.trufflesuite.com/)
## Important libraries
-- [Zeppelin](https://github.com/OpenZeppelin/zeppelin-solidity/): Libraries that provide common contract patterns (crowdfuding, safemath, etc)
+- [Zeppelin](https://github.com/OpenZeppelin/openzeppelin-contracts): Libraries that provide common contract patterns (crowdfuding, safemath, etc)
+- [Chainlink](https://github.com/smartcontractkit/chainlink): Code that allows you to interact with external data
## Sample contracts
- [Dapp Bin](https://github.com/ethereum/dapp-bin)
+- [Defi Example](https://github.com/PatrickAlphaC/chainlink_defi)
- [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/)
@@ -862,6 +967,7 @@ someContractAddress.callcode('function_name');
- [Solidity Style Guide](http://solidity.readthedocs.io/en/latest/style-guide.html): Ethereum's style guide is heavily derived from Python's [PEP 8](https://www.python.org/dev/peps/pep-0008/) style guide.
## Editors
+- [Remix](https://remix.ethereum.org/)
- [Emacs Solidity Mode](https://github.com/ethereum/emacs-solidity)
- [Vim Solidity](https://github.com/tomlion/vim-solidity)
- Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc))
diff --git a/sv-se/nix-sv.html.markdown b/sv-se/nix-sv.html.markdown
index 15d9456b..647575fe 100644
--- a/sv-se/nix-sv.html.markdown
+++ b/sv-se/nix-sv.html.markdown
@@ -365,4 +365,7 @@ with builtins; [
(https://medium.com/@MrJamesFisher/nix-by-example-a0063a1a4c55)
* [Susan Potter - Nix Cookbook - Nix By Example]
- (http://funops.co/nix-cookbook/nix-by-example/)
+ (https://ops.functionalalgebra.com/nix-by-example/)
+
+* [Rommel Martinez - A Gentle Introduction to the Nix Family]
+ (https://web.archive.org/web/20210121042658/https://ebzzry.io/en/nix/#nix)
diff --git a/swift.html.markdown b/swift.html.markdown
index 3981a4ce..e46dcc75 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -12,7 +12,7 @@ contributors:
filename: learnswift.swift
---
-Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6+.
+Swift is a programming language for iOS and macOS development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6+.
The official _[Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329)_ book from Apple is now available via iBooks. It goes into much more detail than this guide, and if you have the time and patience to read it, it's recommended. Some of these examples are from that book.
@@ -334,7 +334,7 @@ repeat {
} while i < 5
// The continue statement continues executing a loop at the next iteration
-// The break statement ends a swift or loop immediately
+// The break statement ends a loop immediately
// MARK: - Functions
@@ -654,7 +654,7 @@ class Rect: Shape {
// but still want to run code before and after getting or setting
// a property, you can use `willSet` and `didSet`
var identifier: String = "defaultID" {
- // the `willSet` arg will be the variable name for the new value
+ // the `someIdentifier` arg will be the variable name for the new value
willSet(someIdentifier) {
print(someIdentifier)
}
diff --git a/tcl.html.markdown b/tcl.html.markdown
index 1b577b49..51e8651c 100644
--- a/tcl.html.markdown
+++ b/tcl.html.markdown
@@ -308,7 +308,7 @@ set result [+ 5 3]
set name Neo
expr {{Bob} eq $name}
-# The general operators fall back to string string comparison if numeric
+# The general operators fall back to string comparison if numeric
# operation isn't feasible:
expr {{Bob} == $name}
diff --git a/texinfo.html.markdown b/texinfo.html.markdown
new file mode 100644
index 00000000..1b3ed9e2
--- /dev/null
+++ b/texinfo.html.markdown
@@ -0,0 +1,183 @@
+---
+language: Texinfo
+contributors:
+ - ["Julien Lepiller", "https://github.com/roptat"]
+filename: learntexinfo.texi
+---
+
+Texinfo is a documentation format you can use to create various types of
+documents from the same source. Its main usage is to create documentation
+manuals and info pages for GNU projects.
+
+Texinfo is a markup language that contains text and *@-commands* that specify
+what the generator should do.
+
+## Initial File
+
+A simple example of a simple manual:
+
+```
+\input texinfo
+@setfilename simple-document.info
+@documentencoding UTF-8
+@settitle simple-document
+@c This is a comment
+@c Replace simple-document above (twice) with the actual document title
+
+@c Automake will take care of version.texi
+@include version.texi
+
+@copying
+Copyright @copyright{} YEAR MY NAME
+
+@c GFDL is common for GNU projects
+@quotation
+Permission is granted to copy, distribute and/or modify this document
+under the terms of the GNU Free Documentation License, Version 1.3 or
+any later version published by the Free Software Foundation; with no
+Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A
+copy of the license is included in the section entitled ``GNU Free
+Documentation License''.
+@end quotation
+@end copying
+
+@titlepage
+@end titlepage
+
+@c Now starts the actual content
+@contents
+
+@c The first node must always be Top
+@node Top
+@c And we give it a title
+@top simple-document
+
+This document quickly describes Texinfo features.
+
+@c This is the ToC:
+@menu
+* Introduction:: A short summary of the chapter
+
+@detailmenu
+--- The Detailed Node Listing ---
+
+Introduction
+
+* Formatting:: How to format text nicely
+* Links:: Linking to other resources, pages, or manuals
+
+@end detailmenu
+@end menu
+
+@node Introduction
+@chapter Introduction
+
+Each node must have the same name as the menu item that was defined in the ToC.
+
+@node Formatting
+@section Formatting
+@c Add something to the content index, so people can get here when searching
+@c for something else
+@cindex bold text
+@cindex titles
+
+Similar to chapters, sections must have the same name and appear in the same order.
+
+@subsection This is a subsection title
+@subsubsection This is a sub-subsection title
+
+Each block of text is a paragraph. You can use multiple lines for the paragraph
+like so, only empty lines separate paragraphs.
+
+Common formatting include @emph{emphasis}, @code{inline code}. Specific type of
+text can be marked as well: @file{file.txt}, @option{--learn-fast},
+@command{ls} or @var{variable}. You can escape the command character like
+so: @@, and a newline with a single @@ at the end of the line.
+
+You can add different types of blocks:
+
+@example
+Here is an example
+@end example
+
+@lisp
+'(this is lisp code)
+@end lisp
+
+@itemize
+@item An element in an unordered list
+@item A second element in the same list
+@end itemize
+
+@enumerate
+@item This list is similar
+@item But ordered
+@end enumerate
+
+@quotation
+A quotation block, by someone famous maybe
+@end quotation
+
+@table @asis
+@item element title
+element description
+
+@item second element title
+second element description. Note that the description part can span multiple
+paragraphs, contain other blocks etc. This is usually used as a definition
+list.
+
+@code{@@asis} wraps the element title, and tells Texinfo to use them as-is.
+@end table
+
+@table @code
+@item do-x
+This item title is now wrapped in a code block, as in @code{@@code{do-x}}
+@end table
+
+@c content index can appear at any place in the document, not necessarily after
+@c titles.
+@cindex function definition
+@deffn {Kind of Function} function_name @var{arg1} @var{arg2} @
+ @var{arg3} @var{arg4} [@var{optional5}]
+This text describes the function. Note how we could use multiple lines for the
+function synopsis by escaping the line with a single @@.
+
+This again can contain multiple paragraphs or blocks.
+@end deffn
+
+@node Links
+@section Links
+
+There are various types of links you can use. A simple link to a URL with
+@uref{https://github.com} and optionally with it a title:
+@uref{https://github.com, GitHub}. An email address @email{me@@me.me}.
+A node in this document, @xref{Introduction}. Always use the exact node name
+for that one. @code{xref} will include the text ``see'' before the link. To
+insert something different, use @pxref{Introduction} (``See'') or
+@xref{Introduction} (nothing is inserted). With an additional argument, you
+can change the text of the link, @xref{Introduction, this introduction}.
+
+It is possible to link to external manuals with these commands by adding
+more arguments, as in @code{@@xref{Node name,,, manual-name, link text}},
+@xref{Overview,,, texinfo, Texinfo's manual} for the complete reference
+on Texinfo!
+
+@bye
+```
+
+## How to Use It
+
+With `automake`, all you need to do is to give it the path to your manual
+in `Makefile.am`:
+
+```
+info_TEXINFOS= doc/simple-manual.texi
+```
+
+Then, get your info manual with `make doc/simple-manual.info` or in other formats,
+e.g. HTML with `make doc/simple-manual.html`.
+
+## Readings
+
+- [Official manual](https://www.gnu.org/software/texinfo/manual/texinfo/html_node/)
diff --git a/toml.html.markdown b/toml.html.markdown
index 2b234965..79aa544c 100755
--- a/toml.html.markdown
+++ b/toml.html.markdown
@@ -225,6 +225,7 @@ sku = 284758393
color = "gray"
```
The equivalent in JSON would be:
+
```json
{
"products": [
@@ -270,8 +271,10 @@ The equivalent in JSON would be:
note = "I am an array item in banana fruit's table/map"
```
+
The equivalent in JSON would be:
-```json
+
+```
{
"fruit": [
diff --git a/typescript.html.markdown b/typescript.html.markdown
index f7a41ce1..74cd15c6 100644
--- a/typescript.html.markdown
+++ b/typescript.html.markdown
@@ -48,6 +48,7 @@ let list: Array<number> = [1, 2, 3];
// For enumerations:
enum Color { Red, Green, Blue };
let c: Color = Color.Green;
+console.log(Color[c]); // "Green"
// Lastly, "void" is used in the special case of a function returning nothing
function bigHorribleAlert(): void {
@@ -237,6 +238,16 @@ if (state.type === "success") {
console.error(state.message);
}
+// Template Literal Types
+// Use to create complex string types
+type OrderSize = "regular" | "large";
+type OrderItem = "Espresso" | "Cappuccino";
+type Order = `A ${OrderSize} ${OrderItem}`;
+
+let order1: Order = "A regular Cappuccino";
+let order2: Order = "A large Espresso";
+let order3: Order = "A small Espresso"; // Error
+
// Iterators and Generators
// for..of statement
diff --git a/uk-ua/c-ua.html.markdown b/uk-ua/c-ua.html.markdown
new file mode 100644
index 00000000..c4dac75f
--- /dev/null
+++ b/uk-ua/c-ua.html.markdown
@@ -0,0 +1,860 @@
+---
+language: c
+filename: learnc-ua.c
+contributors:
+ - ["Adam Bard", "http://adambard.com/"]
+ - ["Á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"]
+ - ["Joshua Li", "https://github.com/JoshuaRLi"]
+ - ["Dragos B. Chirila", "https://github.com/dchirila"]
+translators:
+ - ["AstiaSun", "https://github.com/AstiaSun"]
+lang: uk-ua
+---
+
+О, C! Досі мова для сучасних обчислень у високопродуктивних продуктах.
+
+C це імовірно найбільш низькорівнева мова, яку будуть використовувати більшість програмістів. Проте, вона компенсує це не тільки швидкістю виконання. Як тільки ви оціните її можливість ручного управління пам'яттю, С зможе відвести саме в ті місця, в які вам потрібно було потрапити.
+
+> **Дещо про прапори компілятора**
+>
+> За замовчуванням, gcc та clang досить тихо інформують про попередження та помилки
+> при компіляції, хоч це і може бути дуже корисною інформацією. Тому рекомендується
+> використовувати більш вимогливий компілятор. Ось кілька рекомендацій:
+>
+> `-Wall -Wextra -Werror -O2 -std=c99 -pedantic`
+>
+> За інформацією про ці та інші прапори зверніться до головної сторінки man вашого
+> компілятора C (наприклад, `man 1 gcc`) або ж просто заґуґліть.
+
+
+```c
+// Однорядкові коментарі починаються з //
+// Проте вони з'явились тільки після С99.
+
+/*
+Багаторядкові коментарі мають такий вигляд. І працюють в C89.
+*/
+
+/*
+Багаторядкові коментарі не можуть вкладатись один в одний.
+/* Будьте обережними */ // коментар закінчується на цьому рядку...
+*/ // ...а не на цьому!
+
+// Константа: #define <keyword>
+// Назви констант, як правило, пишуться великими літерами, проте це не вимога
+#define DAYS_IN_YEAR 365
+
+// Ще одним способом оголосити константи є перелічення констант.
+// До речі, всі вирази мають закінчуватись крапкою з комою.
+enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT};
+// MON отримає значення 2 автоматично, TUE дорівнюватиме 3 і т.д.
+
+// Імпортувати заголовки можна за допомогою #include
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+// (Заголовки із стандартної бібліотеки С вказуються між <кутовими дужками>.)
+// Щоб додати власні заголовки, потрібно використовувати "подвійні лапки"
+// замість кутових:
+//#include "my_header.h"
+
+// Сигнатури функцій попередньо оголошуються в .h файлах або на початку .с файлів.
+void function_1();
+int function_2(void);
+
+// Потрібно оголосити 'прототип функції' перед main(), реалізація функцій
+// відбувається після функції main().
+int add_two_ints(int x1, int x2); // прототип функції
+// Варіант `int add_two_ints(int, int);` теж правильний (не потрібно називати
+// аргументи). Рекомендується також називати аргументи в прототипі для
+// кращого розуміння.
+
+// Вхідною точкою програми є функція під назвою main. Вона повертає чисельний тип.
+int main(void) {
+ // реалізація програми
+}
+
+// Аргументи командного рядка, вказані при запуску програми, також передаються
+// у функцію main.
+// argc - це кількість переданих аргументів
+// argv — це масив масивів символів, що містить самі аргументи
+// argv[0] - назва програми, argv[1] - перший аргумент, і т.д.
+int main (int argc, char** argv)
+{
+ // printf дозволяє вивести на екран значення, вивід - це форматований рядок,
+ // в даному випадку %d позначає чисельне значення, \n — це новий рядок
+ printf("%d\n", 0); // => Виводить 0
+
+ ///////////////////////////////////////
+ // Типи
+ ///////////////////////////////////////
+
+ // Всі змінні повинні бути оголошені на початку поточного блоку області видимості.
+ // В цьому коді вони оголошуються динамічно. С99-сумісні компілятори
+ // дозволяють оголошення близько до місця, де значення використовується.
+
+ // int (цілочисельний знаковий тип) зазвичай займає 4 байти
+ int x_int = 0;
+
+ // short (цілочисельний знаковий тип) зазвичай займає 2 байти
+ //
+ short x_short = 0;
+
+ // Символьний тип char гарантовано займає 1 байт
+ char x_char = 0;
+ char y_char = 'y'; // Символьні літерали позначаються ''
+
+ // long (цілочисельний знаковий тип) має розмір від 4 до 8 байтів; великі значення
+ // типу long гарантовано займають 8 байтів
+ long x_long = 0;
+ long long x_long_long = 0;
+
+ // Тип float - це зазвичай 32-бітове число з плаваючою крапкою
+ float x_float = 0.0f; // Суфікс 'f' позначає літерал з плаваючою крапкою
+
+ // Тип double - це зазвийчай 64-бітове число з плаваючою крапкою
+ double x_double = 0.0; // дійсне число без суфіксів має тип double
+
+ // Цілочисельні типи можуть не мати знаку (бути більше, або ж рівними нулю)
+ unsigned short ux_short;
+ unsigned int ux_int;
+ unsigned long long ux_long_long;
+
+ // Char всередині одинарних лапок інтерпретуються як числа в наборі
+ // символів комп'ютера.
+ '0'; // => 48 в таблиці ASCII.
+ 'A'; // => 65 в таблиці ASCII.
+
+ // sizeof(T) повертає розмір змінної типу Т в байтах
+ // sizeof(obj) віддає розмір виразу (змінна, літерал, і т.п.)
+ printf("%zu\n", sizeof(int)); // => 4 (на більшості пристроїв з 4-байтним словом)
+
+ // Якщо аргумент оператора `sizeof` — це вираз, тоді його аргументи не оцінюються
+ // (крім масивів, розмір яких залежить від змінної).
+ // Значення, що повертається в цьому випадку, - це константа часу компіляції.
+ int a = 1;
+ // size_t - беззнаковий чисельний тип розміром щонайменше 2 байти, який
+ // використовується для відображення розміру об'єкта.
+ size_t size = sizeof(a++); // a++ не оцінюється
+ printf("sizeof(a++) = %zu where a = %d\n", size, a);
+ // Виводить "sizeof(a++) = 4 where a = 1" (на 32-бітній архітектурі)
+
+ // Масиви повинні бути проініціалізовані з конкретним розміром.
+ char my_char_array[20]; // Цей масив займає 1 * 20 = 20 байтів
+ int my_int_array[20]; // Цей масив займає 4 * 20 = 80 байтів
+ // (припускаючи 4-байтні числа)
+
+ // Таким чином можна проініціалізувати масив нулем:
+ char my_array[20] = {0};
+ // де "{0}" називається "ініціалізатором масиву".
+
+ // Зазначте, можна явно не оголошувати розмір масиву, ЯКЩО ви проініціалізуєте
+ // масив у тому ж рядку. Тому, наступне оголошення еквівалентне:
+ char my_array[] = {0};
+ // АЛЕ, потрібно визначити розмір масиву під час виконання, як тут:
+ size_t my_array_size = sizeof(my_array) / sizeof(my_array[0]);
+
+ // ПОПЕРЕДЖЕННЯ якщо ви вирішили використовувати даний підхід, потрібно
+ // визначити розмір **перед тим**, як ви почнете передавати масив у функцію
+ // (побачите дискусію пізніше). Масиви перетворюються на вказівники при
+ // передачі як аргументи у функцію, тому попереднє твердження буде видавати
+ // хибний результат всередині функції.
+
+ // Індексація по масиву така ж сама, як і в інших мовах програмування або,
+ // скоріше, як у інших с-подібних мовах.
+ my_array[0]; // => 0
+
+ // Масиви незмінні, це просто частина пам'яті!
+ my_array[1] = 2;
+ printf("%d\n", my_array[1]); // => 2
+
+ // Масиви, розмір яких залежить від змінної, в С99 (та в С11 як вибірковий
+ // функціонал) можуть бути оголошені також. Розмір такого масиву не має бути
+ // константою під час компіляції:
+ printf("Enter the array size: "); // спитати користувача розмір масиву
+ int array_size;
+ fscanf(stdin, "%d", &array_size);
+ int var_length_array[array_size]; // оголосити масив
+ printf("sizeof array = %zu\n", sizeof var_length_array);
+
+ // Приклад:
+ // > Enter the array size: 10
+ // > sizeof array = 40
+
+ // Рядки - це просто масиви символьних літералів (char), що закінчуються NULL
+ // (0x00) байтом, представленим у рядках як спеціальний символ '\0'.
+ // (Не потрібно включати байт NULL в рядкові літерали; компілятор сам вставляє
+ // його наприкінці масиву.)
+ char a_string[20] = "This is a string";
+ printf("%s\n", a_string); // %s форматує рядок
+
+ printf("%d\n", a_string[16]); // => 0
+ // тобто, байт #17 - це 0 (так само, як і 18-ий, 19-ий, та 20-ий)
+
+ // Якщо між одинарними лапками є букви, тоді це символьний літерал.
+ // Він має тип `int`, а не `char` (так історично склалось).
+ int cha = 'a'; // добре
+ char chb = 'a'; // також добре (неявне перетворення з int на char)
+
+ // Багатовимірні масиви:
+ int multi_array[2][5] = {
+ {1, 2, 3, 4, 5},
+ {6, 7, 8, 9, 0}
+ };
+ // Доступ до елементів:
+ int array_int = multi_array[0][2]; // => 3
+
+ ///////////////////////////////////////
+ // Оператори
+ ///////////////////////////////////////
+
+ // Скорочення для багатьох оголошень:
+ int i1 = 1, i2 = 2;
+ float f1 = 1.0, f2 = 2.0;
+
+ int b, c;
+ b = c = 0;
+
+ // Арифметичні операції
+ i1 + i2; // => 3
+ i2 - i1; // => 1
+ i2 * i1; // => 2
+ i1 / i2; // => 0 (0.5 округлено до 0)
+
+ // Потрібно перетворити хоча б одну з цілочисельних змінних на float, щоб
+ // отримати результат з плаваючою крапкою
+ (float)i1 / i2; // => 0.5f
+ i1 / (double)i2; // => 0.5 // Так само і для типу double
+ f1 / f2; // => 0.5, з певною точністю
+ // Такі обчислення не є точними
+
+ // Ділення за модулем також є
+ 11 % 3; // => 2, остача від ділення
+
+ // Оператори порівняння ймовірно схожі, проте в С немає логічного типу.
+ // Натомість використовується int.
+ // (Або _Bool або bool в C99.)
+ // 0 - хибно (false), всі інші значення - правда (true). Оператори
+ // порівняння завжди повертають 0 або 1.
+ 3 == 2; // => 0 (false)
+ 3 != 2; // => 1 (true)
+ 3 > 2; // => 1
+ 3 < 2; // => 0
+ 2 <= 2; // => 1
+ 2 >= 2; // => 1
+
+ // C - це не Python, порівняння не утворюють ланцюги.
+ // Попередження: Рядок нижче скомпілюється, але він означає `(0 < a) < 2`.
+ // В даному випадку, це 1, тому що (0 < 1).
+ int between_0_and_2 = 0 < a < 2;
+ // Натомість потрібно використати:
+ int between_0_and_2 = 0 < a && a < 2;
+
+ // Логічні оператори з числами
+ !3; // => 0 (Логічне НЕ)
+ !0; // => 1
+ 1 && 1; // => 1 (Логічне І)
+ 0 && 1; // => 0
+ 0 || 1; // => 1 (Логічне АБО)
+ 0 || 0; // => 0
+
+ // Тернарний вираз з умовою ( ? : )
+ int e = 5;
+ int f = 10;
+ int z;
+ z = (e > f) ? e : f; // => 10 "if e > f return e, else return f."
+
+ // Оператори збільшення та зменшення на 1:
+ int j = 0;
+ int s = j++; // Повернути j ПОТІМ збільшити j. (s = 0, j = 1)
+ s = ++j; // Збільшити j ПОТІМ повернути j. (s = 2, j = 2)
+ // так само і для j-- та --j
+
+ // Побітові операції!
+ ~0x0F; // => 0xFFFFFFF0 (побітове заперечення, "перше доповнення", результат
+ // для 32-бітного int)
+ 0x0F & 0xF0; // => 0x00 (побітове І)
+ 0x0F | 0xF0; // => 0xFF (побітове АБО)
+ 0x04 ^ 0x0F; // => 0x0B (побітове XOR)
+ 0x01 << 1; // => 0x02 (побітовий зсув вліво (на 1))
+ 0x02 >> 1; // => 0x01 (побітовий зсув вправо (на 1))
+
+ // Будьте обережними при зсуві цілочисельних значень зі знаком.
+ // Наступні дії дають невизначений результат:
+ // - зсув на біт, що зберігає знак числа (int a = 1 << 31)
+ // - зсув вліво на від'ємне число (int a = -1 << 2)
+ // - зсув на число, що більше за ширину типу
+ // TODO: LHS
+ // - зсув на зміщення, що >= ширині типу в лівій частині виразу:
+ // int a = 1 << 32; // Невизначена поведінка, якщо ширина int 32 біти.
+
+ ///////////////////////////////////////
+ // Структури розгалуження
+ ///////////////////////////////////////
+
+ // Оператор умови
+ if (0) {
+ printf("I am never run\n"); // ніколи не буде виконано
+ } else if (0) {
+ printf("I am also never run\n"); // теж ніколи не буде виконано
+ } else {
+ printf("I print\n"); // це буде надруковано
+ }
+
+ // Цикл з передумовою
+ int ii = 0;
+ while (ii < 10) { // БУДЬ-ЯКЕ значення, що менше 10 - правда.
+ printf("%d, ", ii++); // ii++ збільшує ii на 1 ПІСЛЯ передачі поточного значення.
+ } // => надрукує "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
+
+ printf("\n");
+
+ // Цикл з післяумовою
+ int kk = 0;
+ do {
+ printf("%d, ", kk);
+ } while (++kk < 10); // ++kk збільшує kk на 1 ПЕРЕД передачою поточного значення.
+ // => надрукує "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
+
+ printf("\n");
+
+ // Цикл з лічильником
+ int jj;
+ for (jj=0; jj < 10; jj++) {
+ printf("%d, ", jj);
+ } // => виводить "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
+
+ printf("\n");
+
+ // *****Додатково*****:
+ // Цикли та функції обов'язково повинні мати тіло. Якщо тіло не потрібно:
+ int i;
+ for (i = 0; i <= 5; i++) {
+ ; // використовуйте крапку з комою, щоб симулювати тіло (пусте твердження)
+ }
+ // Або
+ for (i = 0; i <= 5; i++);
+
+ // Розгалуження з множинним вибором: switch()
+ switch (a) {
+ case 0: // значення повинні бути *константними* виразами і мати вбудований тип
+ //(наприклад, перелічення)
+ printf("Hey, 'a' equals 0!\n");
+ break; // якщо не використати break, то управління буде передано наступному блоку
+ case 1:
+ printf("Huh, 'a' equals 1!\n");
+ break;
+ // Будьте обережними, виконання продовжиться до тих пір, поки
+ // не зустрінеться наступний "break".
+ case 3:
+ case 4:
+ printf("Look at that.. 'a' is either 3, or 4\n");
+ break;
+ default:
+ // якщо вираз a не співпадає з описаними значеннями, то виконується
+ // блок default
+ fputs("Error!\n", stderr);
+ exit(-1);
+ break;
+ }
+ /*
+ Використання "goto" в С
+ */
+ typedef enum { false, true } bool;
+ // вводимо таке перелічення, оскільки С не має логічного типу до С99
+ 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 occurred at i = %d & j = %d.\n", i, j);
+ /*
+ https://ideone.com/GuPhd6
+ Даний приклад виведе "Error occurred at i = 51 & j = 99."
+ */
+
+ ///////////////////////////////////////
+ // Приведення до типів
+ ///////////////////////////////////////
+
+ // Кожне значенння в С має тип, але можна перевести значення з одного типу в
+ // інший, якщо потрібно (із деякими обмеженнями).
+
+ int x_hex = 0x01; // Змінним можна присвоювати літерали в шістнадцятковій
+ // системі числення
+
+ // Приведення до типу призведе до спроби зберегти чисельне значення
+ printf("%d\n", x_hex); // => Виводить 1
+ printf("%d\n", (short) x_hex); // => Виводить 1
+ printf("%d\n", (char) x_hex); // => Виводить 1
+
+ // В данному випадку попередження не виникатиме, якщо значення виходить за межі
+ // значення типу
+ printf("%d\n", (unsigned char) 257); // => 1 (максимальне значення char = 255,
+ // якщо char має довжину 8 біт)
+
+ // Для того, щоб дізнатись максимальний розмір `char`, `signed char` або ж
+ // `unsigned char`, потрібно використати макроси CHAR_MAX, SCHAR_MAX та UCHAR_MAX
+ // відповідно з <limits.h>.
+
+ // Вбудовані типи можуть бути приведені до типу із плаваючою крапкою і навпаки.
+ printf("%f\n", (double) 100); // %f завжди перетворює число на double...
+ printf("%f\n", (float) 100); // ...навіть, якщо це float.
+ printf("%d\n", (char)100.0);
+
+ ///////////////////////////////////////
+ // Вказівники
+ ///////////////////////////////////////
+
+ // Вказівник - це змінна, що зберігає адресу у пам'яті. Оголошення вказівника
+ // також потребує інформації про тип об'єкта, на який він вказує. Можна
+ // отримати адресу пам'яті будь-якої змінної, а потім працювати з нею.
+
+ int x = 0;
+ printf("%p\n", (void *)&x); // Оператор & повертає адресу змінної у пам'яті
+ // (%p форматує об'єкт вказівника типу void *)
+ // => Виводить деяку адресу в пам'яті
+
+ // Для оголошення вказівника потрібно поставити * перед його назвою.
+ int *px, not_a_pointer; // px - це вказівник на цілочисельне значення (int)
+ px = &x; // Зберігає адресу змінної x в px
+ printf("%p\n", (void *)px); // => Виводить адресу в пам'яті
+ printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer));
+ // => Виводить "8, 4" на звичайній 64-бітній системі
+
+ // Щоб прочитати значення, яке зберігається за адресою, на яку вказує вказівник,
+ // потрібно поставити знак * перед назвою змінної.
+ // Так, * використовується одночасно і для оголошення вказівника, і для отримання
+ // значення за адресою. Звучить заплутано, проте тільки спочатку.
+ printf("%d\n", *px); // => Виводить 0, значення x
+
+ // Можна також змінити значення, на яке посилається вказівник.
+ // Тут звернення до адреси обернене у круглі дужки, тому що
+ // ++ має вищий пріоритет виконання, ніж *.
+ (*px)++; // Збільшити значення, на яке вказує px, на 1
+ printf("%d\n", *px); // => Виводить 1
+ printf("%d\n", x); // => Виводить 1
+
+ // Масиви зручно використовувати для виділення неперервного блоку пам'яті.
+ int x_array[20]; // оголошує масив з 20 елементів (розмір можна задати лише один раз)
+ int xx;
+ for (xx = 0; xx < 20; xx++) {
+ x_array[xx] = 20 - xx;
+ } // Ініціалізує x_array значеннями 20, 19, 18,... 2, 1
+
+ // Оголосити вказівник типу int, який посилається на масив x_array
+ int* x_ptr = x_array;
+ // x_ptr тепер вказує на перший елемент масиву (число 20).
+ //
+ // Це працює, тому що при зверненні до імені масиву повертається вказівник
+ // на перший елемент. Наприклад, коли масив передається у функцію або присвоюється
+ // вказівнику, він неявно приводиться до вказівника.
+ // Виключення:
+ // - коли вказівник передається як аргумент із оператором `&`:
+ int arr[10];
+ int (*ptr_to_arr)[10] = &arr; // &arr НЕ має тип `int *`!
+ // Він має тип "вказівник на масив" (з 10 чисел).
+ // - коли масив - це рядковий літерал, що використовується для ініціалізації
+ // масив символів:
+ char otherarr[] = "foobarbazquirk";
+ // - коли масив - це аргумент операторів `sizeof` або `alignof`:
+ int arraythethird[10];
+ int *ptr = arraythethird; // те ж саме, що з int *ptr = &arr[0];
+ printf("%zu, %zu\n", sizeof(arraythethird), sizeof(ptr));
+ // Ймовірно, виводить "40, 4" або "40, 8"
+
+ // Інкрементація та декрементація вказівника залежить від його типу.
+ // (так звана арифметика вказівників)
+ printf("%d\n", *(x_ptr + 1)); // => Виводить 19
+ printf("%d\n", x_array[1]); // => Виводить 19
+
+ // Можна також динамічно виділити послідовні блоки в пам'яті за допомогою
+ // функції malloc зі стандартної бібліотеки. malloc приймає один аргумент типу
+ // size_t, що описує кількість байтів для виділення (зазвичай із купи, проте це
+ // може бути неправдою на вбудованих системах - стандарт С нічого про це не повідомляє).
+ int *my_ptr = malloc(sizeof(*my_ptr) * 20);
+ for (xx = 0; xx < 20; xx++) {
+ *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx
+ } // Проініціалізувати пам'ять значеннями 20, 19, 18, 17... 2, 1 (як int)
+
+ // Будьте обережними із передачею значень, що надаються користувачем, в malloc!
+ // Про всяк випадок, використовуйте calloc в таких ситуаціях (який, на відміну від
+ // malloc, також заповнює пам'ять нулями).
+ int* my_other_ptr = calloc(20, sizeof(int));
+
+ // Немає стандартного способу визначити розмір динамічно виділеного масиву в С.
+ // Через це, якщо масиви будуть часто передаватись в програмі, потрібна інша змінна,
+ // яка буде відслідковувати кількість елементів в масиві. Детальніше в розділі
+ // про функції.
+ size_t size = 10;
+ int *my_arr = calloc(size, sizeof(int));
+ // Додати елемент до масиву.
+ size++;
+ my_arr = realloc(my_arr, sizeof(int) * size);
+ if (my_arr == NULL) {
+ // Не забувайте перевіряти результат виконання realloc на помилки!
+ return
+ }
+ my_arr[10] = 5;
+
+ // Робота з вказівниками може призводити до неочікуваних і непрогнозованих
+ // результатів, якщо звернутись до пам'яті, що не була виділена вами.
+ printf("%d\n", *(my_ptr + 21)); // => Хто зна, що буде виведено.
+ // Може навіть вилетіти з помилкою.
+
+ // Після закінчення роботи із виділеною за допомогою malloc пам'яттю, її обов'язково
+ // потрібно звільнити. Інакше ніхто не зможе нею скористатися, аж поки програма не
+ // завершить свою роботу (така ситуація називається "витоком пам'яті").
+ free(my_ptr);
+
+ // Рядки - це масиви символів, проте вони найчастіше представлені як
+ // вказівник на символ (тобто, вказівник на перший елемент масиву). Вважається
+ // хорошим підходом використовувати `const char *', посилаючись на об'єкт
+ // рядка, оскільки його не можна змінити ("foo"[0] = 'a' ЗАБОРОНЕНО).
+ const char *my_str = "This is my very own string literal";
+ printf("%c\n", *my_str); // => 'T'
+
+ // Це не працюватиме, якщо рядок - це масив (потенційно створений за допомогою
+ // рядкового літерала), що зберігається у частині пам'яті, яку можна перезаписувати:
+ char foo[] = "foo";
+ foo[0] = 'a'; // Дозволяється, foo тепер містить "aoo"
+
+ function_1();
+} // Кінець функції main
+
+///////////////////////////////////////
+// Функції
+///////////////////////////////////////
+
+// Синтаксис оголошення функції:
+// <тип повернення> <назва функції>(<аргументи>)
+
+int add_two_ints(int x1, int x2)
+{
+ return x1 + x2; // Використовуйте return, щоб повернути значення
+}
+
+/*
+Дані у функцію передають за значенням. Коли функція викликається, аргументи, що
+передаються у функцію, копіюються з оригіналів (окрім масивів). Всі зміни над
+значенням аргументів всередині функції не впливають на значення оригіналів.
+
+Використовуйте вказівники, якщо потрібно редагувати безпосередньо оригінальні
+значення аргументів.
+
+Приклад: замінити рядок на обернений.
+*/
+
+// void означає, що функція нічого не повертає
+void str_reverse(char *str_in)
+{
+ char tmp;
+ size_t ii = 0;
+ size_t len = strlen(str_in); // `strlen()` це частина стандартної бібліотеки С
+ // Зауважте: довжина, яку повертає `strlen`, не включає
+ // термінальний NULL байт ('\0')
+ for (ii = 0; ii < len / 2; ii++) { // в C99 можна напряму оголошувати тип `ii` в циклі
+ tmp = str_in[ii];
+ str_in[ii] = str_in[len - ii - 1]; // ii-й символ з кінця
+ str_in[len - ii - 1] = tmp;
+ }
+}
+// Зауважте: для використання strlen() потрібно завантажити файл заголовку string.h
+
+/*
+char c[] = "This is a test.";
+str_reverse(c);
+printf("%s\n", c); // => ".tset a si sihT"
+*/
+/*
+Оскільки можна повертати тільки одну змінну, для зміни значення більшої
+кількості змінних можна використовувати виклик за посиланням
+*/
+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);
+// змінні обмінюються значеннями
+*/
+
+/*
+Масиви завжди передаються у функції як вказівники, не зважаючи на тип масиву
+(статичний чи динамічний). Тому всередині функція не знає про розмір масиву.
+*/
+// Розмір масиву завжди має передаватись разом із масивом!
+void printIntArray(int *arr, size_t 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);
+// виведе "arr[0] is: 1" і т.д.
+*/
+
+// Ключове слово extern використовується, якщо всередині функції потрібно звернутись
+// до змінної, що була оголошена поза функцією.
+int i = 0;
+void testFunc() {
+ extern int i; // використовуємо зовнішню змінну i
+}
+
+// Зробити зовнішню змінну приватною у вихідному файлі за допомогою static:
+static int j = 0; // інші файли, що використовують testFunc2(),
+ // не матимуть доступу до змінної j
+void testFunc2() {
+ extern int j;
+}
+// Ключове слово static робить змінну недоступною для коду поза даною одиницею
+// компіляції. (На більшості систем, одиниця компіляції - це файл).
+// static можна використовувати до глобальних змінних, функцій, локальних
+// змінних у функціях. Локальні змінні, проініціалізовані static, поводять
+// себе як глобальні змінні, проте тільки в межах даного файлу. Статичні
+// змінні ініціалізуються 0, якщо інше значення не було вказане.
+// **Як варіант, функції можна зробити приватними оголосивши їх як static**
+
+///////////////////////////////////////
+// Користувацькі типи та структури
+///////////////////////////////////////
+
+// Ключове слово typedef використовується, щоб створити псевдонім типу
+typedef int my_type;
+my_type my_type_var = 0;
+
+// Структури - це такі собі колекції з даними. Пам'ять для полів виділяється
+// послідовно, в порядку їх написання:
+struct rectangle {
+ int width;
+ int height;
+};
+
+// Проте це не означає, що
+// sizeof(struct rectangle) == sizeof(int) + sizeof(int)
+// в зв'язку з вирівнюванням пам'яті [1]
+
+void function_1()
+{
+ struct rectangle my_rec;
+
+ // Доступ до полів структури відбувається через .
+ my_rec.width = 10;
+ my_rec.height = 20;
+
+ // Можна створити вказівники на структуру
+ struct rectangle *my_rec_ptr = &my_rec;
+
+ // Звернення до структури через вказівник та зміна значень поля:
+ (*my_rec_ptr).width = 30;
+
+ // Але є й альтернативний спосіб звернутись до поля через вказівник, використовуючи
+ // оператор -> (краще читається)
+ my_rec_ptr->height = 10; // Те ж саме, що (*my_rec_ptr).height = 10;
+}
+
+// Можна використати typedef перед struct
+typedef struct rectangle rect;
+
+int area(rect r)
+{
+ return r.width * r.height;
+}
+
+// Якщо ваша структура доволі громіздка, можна звертатись до неї через вказівник,
+// щоб уникнути копіювання всієї структури:
+int areaptr(const rect *r)
+{
+ return r->width * r->height;
+}
+
+///////////////////////////////////////
+// Вказівники на функції
+///////////////////////////////////////
+/*
+Під час виконання функції знаходяться за відомими адресами в пам'яті. Вказівники
+на функції - це ті ж самі вказівники, що зберігають адресу у пам'яті, проте можуть
+використовуватись, щоб викликати функції напряму і передавати обробники (або функції зі
+зворотнім зв'язком). Хоча, синтаксис спочатку може бути доволі незрозумілим.
+
+Приклад: use str_reverse from a pointer
+*/
+void str_reverse_through_pointer(char *str_in) {
+ // Оголосити вказівник на функцію під назвою f.
+ void (*f)(char *); // Сигнатура повинна точно співпадати із цільовою функцією.
+ f = &str_reverse; // Присвойте адресу певної функції (визначається під час виконання)
+ // f = str_reverse; повинно працювати також
+ (*f)(str_in); // Виклик функції через вказівник
+ // f(str_in); // Це альтернативний, але теж вірний синтаксис виклику функції.
+}
+
+/*
+Якщо сигнатури функцій співпадають, можна присвоїти будь-яку функцію тому ж
+самому вказівнику. Вказівники на функції зазвичай використовуються як псевдоніми
+для спрощення та покращення читабельності коду. Приклад:
+*/
+
+typedef void (*my_fnp_type)(char *);
+
+// Використання при оголошенні змінної вказівника:
+// ...
+// my_fnp_type f;
+
+
+// Спеціальні символи:
+/*
+'\a'; // символ попередження (дзвінок)
+'\n'; // символ нового рядка
+'\t'; // символ табуляції (вирівнювання по лівому краю)
+'\v'; // вертикальна табуляція
+'\f'; // нова сторінка
+'\r'; // повернення каретки
+'\b'; // стирання останнього символу
+'\0'; // нульовий символ. Зазвичай розташовується в кінці рядка.
+// hello\n\0. \0 використовується для позначення кінця рядка.
+'\\'; // зворотній слеш
+'\?'; // знак питання
+'\''; // одинарні лапки
+'\"'; // подвійні лапки
+'\xhh'; // шістнадцяткове число. Наприклад: '\xb' = символ вертикальної табуляції
+'\0oo'; // вісімкове число. Наприклад: '\013' = символ вертикальної табуляції
+
+// форматування виводу:
+"%d"; // ціле число (int)
+"%3d"; // ціле число, щонайменше 3 символи (вирівнювання по правому краю)
+"%s"; // рядок
+"%f"; // число з плаваючою крапкою (float)
+"%ld"; // велике ціле число (long)
+"%3.2f"; // число з плаваючою крапкою, щонайменше 3 цифри зліва і 2 цифри справа
+"%7.4s"; // (аналогічно для рядків)
+"%c"; // символ
+"%p"; // вказівник. Зазначте: потребує перетворення типу на (void *) перед
+ // використанням у `printf`.
+"%x"; // шістнадцяткове число
+"%o"; // вісімкове число
+"%%"; // друкує %
+*/
+
+///////////////////////////////////////
+// Порядок виконання
+///////////////////////////////////////
+
+//---------------------------------------------------//
+// Оператори | Асоціативність//
+//---------------------------------------------------//
+// () [] -> . | зліва направо //
+// ! ~ ++ -- + = *(type)sizeof | справа наліво //
+// * / % | зліва направо //
+// + - | зліва направо //
+// << >> | зліва направо //
+// < <= > >= | зліва направо //
+// == != | зліва направо //
+// & | зліва направо //
+// ^ | зліва направо //
+// | | зліва направо //
+// && | зліва направо //
+// || | зліва направо //
+// ?: | справа наліво //
+// = += -= *= /= %= &= ^= |= <<= >>= | справа наліво //
+// , | зліва направо //
+//---------------------------------------------------//
+
+/****************************** Файли заголовків *********************************
+
+Файли заголовків важливі в С. Вони розділяють вихідний код та визначення на різні
+файли, що робить їх кращими для розуміння.
+
+Файли заголовків синтаксично подібні до вихідних файлів С, проте описуються у".h"
+файлах. Їх можна додати в код за допомогою директиви #include "example.h", якщо
+example.h існує в тому ж каталозі, що і файл С.
+*/
+
+/*
+Так можна запобігти тому, що заголовок буде оголошений кілька разів. Така ситуація
+виникає у випадку циклічної залежності, тобто коли вміст заголовку вже було
+оголошено.
+*/
+#ifndef EXAMPLE_H /* якщо EXAMPLE_H ще не оголошено. */
+#define EXAMPLE_H /* Визначити макрос EXAMPLE_H. */
+
+/*
+Заголовки можна додавати в інші заголовки, таким чином вони разом додаються
+у подальшому.
+*/
+#include <string.h>
+
+/*
+Макроси можуть бути визначені також у заголовку та використовуватись у файлах,
+що містять цей заголовок.
+*/
+#define EXAMPLE_NAME "Dennis Ritchie"
+
+/* Макроси функції також можна визначити. */
+#define ADD(a, b) ((a) + (b))
+/*
+Зверніть увагу на круглі дужки навколо аргументів! Важливо переконатись, що
+a та b не можна проінтерпретувати інакше. Наприклад:
+MUL(x, y) (x * y);
+MUL(1 + 2, 3) -> (1 + 2 * 3), що є помилкою
+*/
+
+/* Struct та typedef можуть використовуватись для узгодженості між файлами. */
+typedef struct Node
+{
+ int val;
+ struct Node *next;
+} Node;
+
+/* Так само і перелічення. */
+enum traffic_light_state {GREEN, YELLOW, RED};
+
+/*
+Прототипи функцій також можна оголосити так, щоб використовувати у кількох
+файлах. Але так робити не варто. Краще оголосити їх у С файлі.
+*/
+Node createLinkedList(int *vals, int len);
+
+/*
+Окрім вище згаданих випадків, всі інші визначення мають описуватись у С файлах.
+*/
+
+#endif /* Кінець директиви передкомпіляції if. */
+
+```
+## Додаткові матеріали
+
+Кращим посібником для вивчення С буде книга авторства Деніса Рітчі (творець С) та Браяна Кернігана,
+[K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language).
+Але обережно з нею, книга старезна і містить неточності (ідеї, що вже вважаються не надто прийнятними).
+
+Ще одним хорошим ресурсом є книга "Learn C The Hard Way" (наявна тільки англійською).
+
+На деякі часті запитання дасть відповідь англомовний ресурс [compl.lang.c Frequently Asked Questions](http://c-faq.com).
+
+Нагадаю, що важливо використовувати правильні інтервали, відступи та загалом мати узгоджений стиль коду.
+Зручний для читання код краще, ніж складний код або зроблений нашвидкоруч. За прикладом можна звернутись до
+[Linux kernel coding style](https://www.kernel.org/doc/Documentation/process/coding-style.rst).
+
+Щодо всього іншого, Ґуґл на допомогу!
+
+[1] [Чому розмір структури не дорівнює сумі розмірів її полів? (англ.)](http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member)
diff --git a/uk-ua/mips-ua.html.markdown b/uk-ua/mips-ua.html.markdown
index 8d4517fe..2d42e85d 100644
--- a/uk-ua/mips-ua.html.markdown
+++ b/uk-ua/mips-ua.html.markdown
@@ -188,7 +188,7 @@ lang: uk-ua
# Нехай $s0 = a, $s1 = b, $s2 = c, $v0 = повернути регістр
ble $s0, $s1, a_LTE_b # якщо (a <= b) розгалуження(a_LTE_b)
ble $s0, $s2, max_C # якщо (a > b && a <=c) розгалуження(max_C)
- move $v0, $s1 # інакше [a > b && a > c] max = a
+ move $v0, $s0 # інакше [a > b && a > c] max = a
j done # Перейти в кінець програми
a_LTE_b: # Мітка розгалуження, коли a <= b
diff --git a/uk-ua/ruby-ua.html.markdown b/uk-ua/ruby-ua.html.markdown
index 74346dfe..a71c30bc 100644
--- a/uk-ua/ruby-ua.html.markdown
+++ b/uk-ua/ruby-ua.html.markdown
@@ -622,4 +622,4 @@ Something.new.qux # => 'qux'
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
-- [Try Ruby](http://tryruby.org) - Learn the basic of Ruby programming language, interactive in the browser.
+- [Try Ruby](https://try.ruby-lang.org/) - Learn the basic of Ruby programming language, interactive in the browser.
diff --git a/uk-ua/rust-ua.html.markdown b/uk-ua/rust-ua.html.markdown
index 4ec2b7c9..422de371 100644
--- a/uk-ua/rust-ua.html.markdown
+++ b/uk-ua/rust-ua.html.markdown
@@ -233,7 +233,7 @@ fn main() {
// Цикл `for`
let array = [1, 2, 3];
- for i in array.iter() {
+ for i in array {
println!("{}", i);
}
diff --git a/uxntal.html.markdown b/uxntal.html.markdown
new file mode 100644
index 00000000..c56e158a
--- /dev/null
+++ b/uxntal.html.markdown
@@ -0,0 +1,174 @@
+---
+language: uxntal
+contributors:
+ - ["Devine Lu Linvega", "https://wiki.xxiivv.com"]
+filename: learnuxn.tal
+---
+
+Uxntal is a stack-machine assembly language targeting the [Uxn virtual machine](https://wiki.xxiivv.com/site/uxn.html).
+
+Stack machine programming might look at bit odd, as it uses a postfix notation,
+which means that operators are always found at the end of an operation. For
+instance, one would write 3 4 + instead of 3 + 4.
+
+The expression written (5 + 10) * 3 in conventional notation would be
+written 10 5 + 3 * in reverse Polish notation.
+
+```forth
+( This is a comment )
+
+( All programming in Unxtal is done by manipulating the stack )
+
+#12 ( push a byte )
+#3456 ( push a short )
+
+( Uxn has 32 opcodes, each opcode has 3 possible modes )
+
+POP ( pop a byte )
+POP2 ( pop a short )
+
+( The modes are:
+ [2] The short mode consumes two bytes from the stack.
+ [k] The keep mode does not consume items from the stack.
+ [r] The return mode makes the operator operate on the return-stack. )
+
+#12 #34 ADD ( 46 )
+#12 #34 ADDk ( 12 34 46 )
+
+( The modes can be combined )
+
+#1234 #5678 ADD2k ( 12 34 56 78 68 ac )
+
+( The arithmetic/bitwise opcodes are:
+ ADD SUB MUL DIV
+ AND ORA EOR SFT )
+
+( New opcodes can be created using macros )
+
+%MOD2 { DIV2k MUL2 SUB2 }
+
+#1234 #0421 MOD2 ( 01 b0 )
+
+( ---------------------------------------------------------------------------- )
+
+( A short is simply two bytes, each byte can be manipulated )
+
+#1234 SWP ( 34 12 )
+#1234 #5678 SWP2 ( 56 78 12 34 )
+#1234 #5678 SWP ( 12 34 78 56 )
+
+( Individual bytes of a short can be removed from the stack )
+
+#1234 POP ( 12 )
+#1234 NIP ( 34 )
+
+( The stack opcodes are:
+ POP DUP NIP SWP OVR ROT )
+
+( ---------------------------------------------------------------------------- )
+
+( To compare values on the stack with each other )
+
+#12 #34 EQU ( 00 )
+#12 #12 EQU ( 01 )
+
+( Logic opcodes will put a flag with a value of either 00 or 01 )
+
+#12 #34 LTH
+#78 #56 GTH
+ #0101 EQU2 ( 01 )
+
+( The logic opcodes are:
+ EQU NEQ GTH LTH )
+
+( ---------------------------------------------------------------------------- )
+
+( Uxn's accessible memory is as follows:
+ 256 bytes of working stack
+ 256 bytes of return stack
+ 65536 bytes of memory
+ 256 bytes of IO memory )
+
+( The addressable memory is between 0000-ffff )
+
+#12 #0200 STA ( stored 12 at 0200 in memory )
+#3456 #0201 STA2 ( stored 3456 at 0201 in memory )
+#0200 LDA2 ( 12 34 )
+
+( The zero-page can be addressed with a single byte )
+
+#1234 #80 STZ2 ( stored 12 at 0080, and 34 at 0081 )
+#80 LDZ2 ( 12 34 )
+
+( Devices are ways for Uxn to communicate with the outside world
+ There is a maximum of 16 devices connected to Uxn at once
+ Device bytes are called ports, the Console device uses the 10-1f ports
+ The console's port 18 is called /write )
+
+%EMIT { #18 DEO }
+
+#31 EMIT ( print "1" to console )
+
+( A label is equal to a position in the program )
+@parent ( defines a label "parent" )
+ &child ( defines a sublabel "parent/child" )
+
+( Label positions can be pushed on stack )
+;parent ( push the absolute position, 2 bytes )
+,parent ( push the relative position, 1 byte )
+.parent ( push the zero-page position, 1 byte )
+
+( The memory opcodes are:
+ LDZ STZ LDR STR
+ LDA STA DEI DEO )
+
+( ---------------------------------------------------------------------------- )
+
+( Logic allows to create conditionals )
+
+#12 #34 NEQ ,skip JCN
+ #31 EMIT
+ @skip
+
+( Logic also allows to create for-loops )
+
+#3a #30
+@loop
+ DUP EMIT ( print "123456789" to console )
+ INC GTHk ,loop JCN
+POP2
+
+( Logic also allows to create while-loops )
+
+;word
+@while
+ LDAk EMIT
+ INC2 LDAk ,while JCN
+POP2
+BRK
+
+@word "vermillion $1
+
+( Subroutines can be jumped to with JSR, and returned from with JMP2r )
+
+;word ,print-word JSR
+BRK
+
+@print-word ( word* -- )
+ @while
+ LDAk EMIT
+ INC2 LDAk ,while JCN
+ POP2
+JMP2r
+
+@word "cerulean
+
+( The jump opcodes are:
+ JMP JCN JSR )
+```
+
+## Ready For More?
+
+* [Uxntal Lessons](https://compudanzas.net/uxn_tutorial.html)
+* [Uxntal Assembly](https://wiki.xxiivv.com/site/uxntal.html)
+* [Uxntal Resources](https://github.com/hundredrabbits/awesome-uxn)
diff --git a/vala.html.markdown b/vala.html.markdown
index 393578b0..06d6dedc 100755
--- a/vala.html.markdown
+++ b/vala.html.markdown
@@ -483,7 +483,7 @@ pointer_obj->some_data; // Returns some_data
delete pointer_obj;
int more = 57;
-int* more_pointer = &i; // & = address-of
+int* more_pointer = &more; // & = address-of
int indirection_demo = more_pointer*; // indirection
// Profiles: affect which Vala features are avaliable and which libraries the
@@ -494,10 +494,10 @@ int indirection_demo = more_pointer*; // indirection
// Use "--profile=whatever" when compiling.
```
-* More Vala documentation can be found [here](https://valadoc.org/).
+* More [Vala documentation](https://valadoc.org/).
* [Alternate construction syntax](https://wiki.gnome.org/Projects/Vala/Tutorial#GObject-Style_Construction) similar to GObject
-* More on contract programming [here](http://en.wikipedia.org/wiki/Contract_programming)
-* Collections library can be found [here](https://wiki.gnome.org/Projects/Vala/Tutorial#Collections)
+* More on [contract programming](http://en.wikipedia.org/wiki/Contract_programming)
+* [Collections library](https://wiki.gnome.org/Projects/Vala/Tutorial#Collections)
* [Multithreading](https://wiki.gnome.org/Projects/Vala/Tutorial#Multi-Threading)
-* Read about building GUIs with GTK+ and Vala [here](http://archive.is/7C7bw).
-* D-Bus [integration](https://wiki.gnome.org/Projects/Vala/Tutorial#D-Bus_Integration)
+* Read about [building GUIs with GTK+ and Vala](http://archive.is/7C7bw).
+* [D-Bus integration](https://wiki.gnome.org/Projects/Vala/Tutorial#D-Bus_Integration)
diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown
index 8bc334ab..4656cf38 100644
--- a/vi-vn/objective-c-vi.html.markdown
+++ b/vi-vn/objective-c-vi.html.markdown
@@ -7,7 +7,7 @@ lang: vi-vn
filename: LearnObjectiveC-vi.m
---
-Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch.
+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 macOS, 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
diff --git a/vim.html.markdown b/vim.html.markdown
index 55649cb2..00a44807 100644
--- a/vim.html.markdown
+++ b/vim.html.markdown
@@ -111,14 +111,21 @@ Vim is based on the concept on **modes**.
<esc> # 'Escapes' from whichever mode you're in, into Command mode
# Copying and pasting text
+ # Operations use the vim register by default
+ # Think of it as vim's private clipboard
+ # Yank ~ copy text into vim register
y # Yank whatever is selected
yy # Yank the current line
+
+ # Delete ~ yank text and delete from file
d # Delete whatever is selected
dd # Delete the current line
- p # Paste the copied text after the current cursor position
- P # Paste the copied text before the current cursor position
- x # Deleting character under current cursor position
+
+ p # Paste text in vim register after the current cursor position
+ P # Paste text in vim register before the current cursor position
+
+ x # Delete character under current cursor position
```
## The 'Grammar' of vim
diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown
index 221c1eb3..a253af48 100644
--- a/visualbasic.html.markdown
+++ b/visualbasic.html.markdown
@@ -102,7 +102,8 @@ Module Module1
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() 'Outputs the above.
+ Console.ReadLine() 'Pauses the execution for user to read
+
'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
diff --git a/wasm.html.markdown b/wasm.html.markdown
index 81344abe..4de7107f 100644
--- a/wasm.html.markdown
+++ b/wasm.html.markdown
@@ -42,7 +42,7 @@ contributors:
;; To set them to a value, we can use <type>.const:
(local.set $int_32 (i32.const 16))
- (local.set $int_32 (i64.const 128))
+ (local.set $int_64 (i64.const 128))
(local.set $float_32 (f32.const 3.14))
(local.set $float_64 (f64.const 1.28))
)
diff --git a/zh-cn/asciidoc-cn.html.markdown b/zh-cn/asciidoc-cn.html.markdown
new file mode 100644
index 00000000..74eed445
--- /dev/null
+++ b/zh-cn/asciidoc-cn.html.markdown
@@ -0,0 +1,135 @@
+---
+language: asciidoc
+filename: asciidoc-cn.md
+contributors:
+ - ["Ryan Mavilia", "http://unoriginality.rocks/"]
+ - ["Abel Salgado Romero", "https://twitter.com/abelsromero"]
+translators:
+ - ["Liu Yihua", "https://github.com/yihuajack"]
+lang: zh-cn
+---
+
+AsciiDoc 是一种类似于 Markdown 的标记语言,它可以用来写从书到博客的任何东西。它由 Stuart Rackham 在 2002 年发明,它的语言很简单,但同时也可以有丰富的定制。
+
+文档标题
+
+标题是可选的,且不可以包含空行。它必须离正文空出至少一个空行。
+
+仅标题
+
+```
+= 文档标题
+
+文档的第一句话。
+```
+
+标题和作者
+
+```
+= 文档标题
+张三 <san.zhang@learnxinyminutes.com>
+
+文档开始。
+```
+
+多名作者的情形
+
+```
+= 文档标题
+李四 <si@go.com>; 王五 <wu@yo.com>; 赵六 <xzhao@pirate.com>
+
+有多名作者的文档开始。
+```
+
+版本行(需要作者行)
+
+```
+= 文档标题(第一版)
+土豆人 <chip@crunchy.com>
+v1.0, 2016-01-13
+
+这篇关于炸薯条的文章会很有趣。
+```
+
+段落
+
+```
+段落不需要什么特别操作。
+
+在两段之间用一个空行隔开。
+
+当你需要换行时,添加一个 +
+你就会得到一个换行符!
+```
+
+文本格式化
+
+```
+_用下划线创建斜体_
+*用星号加粗*
+*_组合起来用更有趣_*
+`用重音符显示等宽字体`
+`*加粗等宽字体*`
+```
+
+节标题
+
+```
+= 第 0 级 (一般只用于文档标题)
+
+== 第 1 级 <h2>
+
+=== 第 2 级 <h3>
+
+==== 第 3 级 <h4>
+
+===== 第 4 级 <h5>
+
+```
+
+列表
+
+用星号创建无序列表。
+
+```
+* 甲
+* 乙
+* 丙
+```
+
+用句点创建有序列表。
+
+```
+. 项目 1
+. 项目 2
+. 项目 3
+```
+
+你可以用额外的星号或句点来嵌套最多五次列表。
+
+```
+* 甲 1
+** 甲 2
+*** 甲 3
+**** 甲 4
+***** 甲 5
+
+. 甲 1
+.. 甲 2
+... 甲 3
+.... 甲 4
+..... 甲 5
+```
+
+## 补充材料
+
+处理 AsciiDoc 文档有两种工具:
+
+1. [AsciiDoc](http://asciidoc.org/): 原版的 Python 实现,在主流 Linux 发行版中已附带,目前处于稳定版本维护模式。
+2. [Asciidoctor](http://asciidoctor.org/): 使用 Ruby 的另一种实现,也可以从 Java 和 JavaScript 中使用。它处于积极的开发中,目标是用新特性和输出格式扩展 AsciiDoc 的语法。
+
+以下是 `Asciidoctor` 实现的相关链接:
+
+* [Markdown - AsciiDoc 语法比较](http://asciidoctor.org/docs/user-manual/#comparison-by-example):并列比较一般 Markdown 和 AsciiDoc 的元素。
+* [入门](http://asciidoctor.org/docs/#get-started-with-asciidoctor):安装和快速启动指南,帮助构建简单的文档。
+* [Asciidoctor 用户手册](http://asciidoctor.org/docs/user-manual/): 完整的单文档指南,包含语法参考、示例、渲染工具等。
diff --git a/zh-cn/bash-cn.html.markdown b/zh-cn/bash-cn.html.markdown
index d85e5b8f..225df06b 100644
--- a/zh-cn/bash-cn.html.markdown
+++ b/zh-cn/bash-cn.html.markdown
@@ -18,7 +18,7 @@ filename: LearnBash-cn.sh
lang: zh-cn
---
-Bash 是一个为 GNU 计划编写的 Unix shell,是 Linux 和 Mac OS X 下的默认 shell。
+Bash 是一个为 GNU 计划编写的 Unix shell,是 Linux 和 macOS 下的默认 shell。
以下大多数例子可以作为脚本的一部分运行,也可直接在 shell 下交互执行。
[更多信息](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown
index 7286fa9f..dbad5030 100644
--- a/zh-cn/c-cn.html.markdown
+++ b/zh-cn/c-cn.html.markdown
@@ -616,7 +616,7 @@ typedef void (*my_fnp_type)(char *);
如果你有问题,请阅读[compl.lang.c Frequently Asked Questions](http://c-faq.com/)。
-使用合适的空格、缩进,保持一致的代码风格非常重要。可读性强的代码比聪明的代码、高速的代码更重要。可以参考下[Linux内核编码风格](https://www.kernel.org/doc/Documentation/CodingStyle)
+使用合适的空格、缩进,保持一致的代码风格非常重要。可读性强的代码比聪明的代码、高速的代码更重要。可以参考下[Linux内核编码风格](https://www.kernel.org/doc/Documentation/process/coding-style.rst)
除了这些,多多Google吧
diff --git a/zh-cn/cmake-cn.html.markdown b/zh-cn/cmake-cn.html.markdown
new file mode 100644
index 00000000..dd9961ca
--- /dev/null
+++ b/zh-cn/cmake-cn.html.markdown
@@ -0,0 +1,168 @@
+---
+category: tool
+tool: cmake
+contributors:
+ - ["Bruno Alano", "https://github.com/brunoalano"]
+translators:
+ - ["tx23", "https://github.com/tx23"]
+filename: CMake-cn
+lang: zh-cn
+---
+
+CMake 是一个跨平台且开源的自动化构建系统工具。通过该工具你可以对你的源代码进行测试、编译或创建安装包。
+
+CMake 试图去解决Makefile 跨平台的自动配置问题(不同的make解释器有不同的命令),以及链接第三方库时的易用性问题。
+
+CMake是一个可扩展的开源系统,它以操作系统和与编译器无关的方式管理构建过程。与其他许多跨平台系统不同的是,
+CMake被设计为与本机的构建环境结合使用。它通过被放置于每个源文件目录下的简单配置文件(名为 CMakeLists.txt 的文件)
+来生成常规使用的标准构建文件(比如:Unix 下的 makefiles 文件或 Windows MSVC 中的 projects/workspaces)。
+
+```cmake
+# 在 CMake 中, 这是一条命令
+
+# 要运行我们的代码,请执行以下命令:
+# - mkdir build && cd build
+# - cmake ..
+# - make
+#
+# 通过上述命令,我们将遵循最佳实践在子目录中进行编译
+# 在第二行命令中我们请求Cmake 生成新的依赖于系统的Makefile文件。
+# 最后,我们运行本地的make 命令。
+
+#------------------------------------------------------------------------------
+# 基础部分
+#------------------------------------------------------------------------------
+#
+# Cmake文件必须被命令为 “CMakeLists.txt” 。
+
+# 设置生成Makefile的CMake所需最低版本要求
+cmake_minimum_required (VERSION 2.8)
+
+# 当版本小于2.8时,需要加入关键字 FATAL_ERROR。
+cmake_minimum_required (VERSION 2.8 FATAL_ERROR)
+
+# 在这里定义了项目的名称,同时会影响Cmake 生成的目录命名约定。
+# 我们可以将代码的语言作为第二个参数传入。
+project (learncmake C)
+
+# 设置项目的源目录(仅仅是由于惯例)
+set( LEARN_CMAKE_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} )
+set( LEARN_CMAKE_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR} )
+
+# 在构建系统中用“semver”风格为我们代码设置当前版本是很有用的。
+set (LEARN_CMAKE_VERSION_MAJOR 1)
+set (LEARN_CMAKE_VERSION_MINOR 0)
+set (LEARN_CMAKE_VERSION_PATCH 0)
+
+# 将变量(版本号)发送到源代码头
+configure_file (
+ "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
+ "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+)
+
+# 包含目录
+# 在 GCC中, 该语句等同于 "-I" 命令
+include_directories( include )
+
+# 在哪里安装其他库?注意:在此处提供includes路径,后续检查将解决所有其他问题
+set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMake/modules/" )
+
+# 条件
+if ( CONDITION )
+ # 输出!
+
+ # 附带信息
+ message(STATUS "My message")
+
+ # CMake 警告,继续处理
+ message(WARNING "My message")
+
+ # CMake 警告 (dev),继续处理
+ message(AUTHOR_WARNING "My message")
+
+ # CMake 错误,继续处理但是会跳过生成
+ message(SEND_ERROR "My message")
+
+ # CMake 错误,停止处理和生成
+ message(FATAL_ERROR "My message")
+endif()
+
+if( CONDITION )
+
+elseif( CONDITION )
+
+else( CONDITION )
+
+endif( CONDITION )
+
+# 循环
+foreach(loop_var arg1 arg2 ...)
+ COMMAND1(ARGS ...)
+ COMMAND2(ARGS ...)
+ ...
+endforeach(loop_var)
+
+foreach(loop_var RANGE total)
+foreach(loop_var RANGE start stop [step])
+
+foreach(loop_var IN [LISTS [list1 [...]]]
+ [ITEMS [item1 [...]]])
+
+while(condition)
+ COMMAND1(ARGS ...)
+ COMMAND2(ARGS ...)
+ ...
+endwhile(condition)
+
+
+# 逻辑运算
+if(FALSE AND (FALSE OR TRUE))
+ message("Don't display!")
+endif()
+
+# 将常规,缓存或环境变量设置为给定值。
+# 如果指定了PARENT_SCOPE选项,则将在当前作用域上的作用域中设置变量
+# `set(<variable> <value>... [PARENT_SCOPE])`
+
+# 如何在带引号和不带引号的参数中引用变量?How to reference variables inside quoted and unquoted arguments?
+# 如果未设置变量,变量引用由变量值或空字符串替换。
+${variable_name}
+
+# 清单
+# 设置源文件列表
+set( LEARN_CMAKE_SOURCES
+ src/main.c
+ src/imagem.c
+ src/pather.c
+)
+
+# 调用编译器
+#
+# ${PROJECT_NAME} 即 Learn_CMake
+add_executable( ${PROJECT_NAME} ${LEARN_CMAKE_SOURCES} )
+
+# 链接库
+target_link_libraries( ${PROJECT_NAME} ${LIBS} m )
+
+# 在哪里安装其他库?注意:在此处提供includes路径,后续检查将解决所有其他问题
+set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMake/modules/" )
+
+# 编译条件 (gcc ; g++)
+if ( "${CMAKE_C_COMPILER_ID}" STREQUAL "GNU" )
+ message( STATUS "Setting the flags for ${CMAKE_C_COMPILER_ID} compiler" )
+ add_definitions( --std=c99 )
+endif()
+
+# 检查 OS
+if( UNIX )
+ set( LEARN_CMAKE_DEFINITIONS
+ "${LEARN_CMAKE_DEFINITIONS} -Wall -Wextra -Werror -Wno-deprecated-declarations -Wno-unused-parameter -Wno-comment" )
+endif()
+```
+
+### 资源
+
++ [CMake tutorial](https://cmake.org/cmake-tutorial/)
++ [CMake documentation](https://cmake.org/documentation/)
++ [Mastering CMake](http://amzn.com/1930934319/)
++ [An Introduction to Modern CMake](https://cliutils.gitlab.io/modern-cmake/)
diff --git a/zh-cn/docker-cn.html.markdown b/zh-cn/docker-cn.html.markdown
new file mode 100644
index 00000000..f55e805a
--- /dev/null
+++ b/zh-cn/docker-cn.html.markdown
@@ -0,0 +1,149 @@
+---
+language: docker
+lang: zh-cn
+filename: docker-cn.bat
+contributors:
+ - ["Ruslan López", "http://javapro.org/"]
+translators:
+ - ["imba-tjd", "https://github.com/imba-tjd/"]
+---
+
+```bat
+:: 下载、安装、运行 hello-world 镜像(image)
+docker run hello-world
+
+:: :: 如果这是第一次运行,你应该能见到这些信息
+:: Unable to find image 'hello-world:latest' locally # 在本地找不到镜像xxx
+:: latest: Pulling from library/hello-world
+:: 1b930d010525: Pull complete
+:: Digest: sha256:4fe721ccc2e8dc7362278a29dc660d833570ec2682f4e4194f4ee23e415e1064
+:: Status: Downloaded newer image for hello-world:latest
+::
+:: Hello from Docker! # 来自Docker的欢迎
+:: This message shows that your installation appears to be working correctly. # 此信息表明你的安装似乎成功了
+::
+:: To generate this message, Docker took the following steps: # Docker进行了如下步骤来产生此信息
+:: 1. The Docker client contacted the Docker daemon. # Docker客户端联系Docker守护程序
+:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. # Docker守护程序从Docker Hub拉取镜像
+:: (amd64)
+:: 3. The Docker daemon created a new container from that image which runs the # Docker守护程序从镜像中创建了一个容器
+:: executable that produces the output you are currently reading. # 运行了产生你正在读的输出的可执行文件
+:: 4. The Docker daemon streamed that output to the Docker client, which sent it # Docker守护程序把输出流式传输给Docker客户端,后者发送到你的终端上
+:: to your terminal.
+::
+:: To try something more ambitious, you can run an Ubuntu container with: # 若要尝试更强大的东西,你可以用该命令运行Ubuntu容器
+:: $ docker run -it ubuntu bash
+::
+:: Share images, automate workflows, and more with a free Docker ID: # 使用免费的Docker ID来分享镜像,自动化工作流等
+:: https://hub.docker.com/
+::
+:: For more examples and ideas, visit: # 欲获取更多例子和想法,访问
+:: https://docs.docker.com/get-started/
+
+:: 现在来看看当前正运行的镜像
+docker ps
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+
+:: 看看之前运行过的镜像
+docker ps -a
+
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+:: 4a76281f9c53 hello-world "/hello" 2 minutes ago Exited (0) 2 minutes ago
+:: happy_poincare
+:: 名字(name)是自动生成的,因此它会和你的不同
+
+:: 移除(remove)我们之前生成的镜像
+docker rm happy_poincare
+
+:: 测试是否真的删除了
+docker ps -a
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+
+:: 为容器(container)指定自定义名字
+docker run --name test_container hello-world
+:: Hello from Docker!
+:: This message shows that your installation appears to be working correctly.
+::
+:: To generate this message, Docker took the following steps:
+:: 1. The Docker client contacted the Docker daemon.
+:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
+:: (amd64)
+:: 3. The Docker daemon created a new container from that image which runs the
+:: executable that produces the output you are currently reading.
+:: 4. The Docker daemon streamed that output to the Docker client, which sent it
+:: to your terminal.
+::
+:: To try something more ambitious, you can run an Ubuntu container with:
+:: $ docker run -it ubuntu bash
+::
+:: Share images, automate workflows, and more with a free Docker ID:
+:: https://hub.docker.com/
+::
+:: For more examples and ideas, visit:
+:: https://docs.docker.com/get-started/
+
+docker ps -a
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+:: d345fe1a4f41 hello-world "/hello" About a minute ago Exited (0) About a minute ago
+:: test_container
+:: 如你所见,名字现在是我们指定的了
+
+:: 从命名过的容器中获取日志(logs)
+docker logs test_container
+:: Hello from Docker!
+:: This message shows that your installation appears to be working correctly.
+::
+:: To generate this message, Docker took the following steps:
+:: 1. The Docker client contacted the Docker daemon.
+:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
+:: (amd64)
+:: 3. The Docker daemon created a new container from that image which runs the
+:: executable that produces the output you are currently reading.
+:: 4. The Docker daemon streamed that output to the Docker client, which sent it
+:: to your terminal.
+::
+:: To try something more ambitious, you can run an Ubuntu container with:
+:: $ docker run -it ubuntu bash
+::
+:: Share images, automate workflows, and more with a free Docker ID:
+:: https://hub.docker.com/
+::
+:: For more examples and ideas, visit:
+:: https://docs.docker.com/get-started/
+
+docker rm test_container
+
+docker run ubuntu
+:: Unable to find image 'ubuntu:latest' locally
+:: latest: Pulling from library/ubuntu
+:: 2746a4a261c9: Pull complete
+:: 4c1d20cdee96: Pull complete 0d3160e1d0de: Pull complete c8e37668deea: Pull complete Digest: sha256:250cc6f3f3ffc5cdaa9d8f4946ac79821aafb4d3afc93928f0de9336eba21aa4
+:: Status: Downloaded newer image for ubuntu:latest
+
+docker ps -a
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+:: c19e9e5b000a ubuntu "/bin/bash" 5 seconds ago Exited (0) 4 seconds ago
+:: relaxed_nobel
+
+:: 在交互模式(interactive mode)下运行容器
+docker run -it ubuntu
+:: root@e2cac48323d2:/# uname
+:: Linux
+:: root@e2cac48323d2:/# exit
+:: exit
+
+docker rm relaxed_nobel
+
+docker ps -a
+:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
+:: NAMES
+:: e2cac48323d2 ubuntu "/bin/bash" 2 minutes ago Exited (0) About a minute ago
+:: nifty_goldwasser
+
+docker rm nifty_goldwasser
+```
diff --git a/zh-cn/dynamic-programming-cn.html.markdown b/zh-cn/dynamic-programming-cn.html.markdown
index b75c5404..7864c22a 100644
--- a/zh-cn/dynamic-programming-cn.html.markdown
+++ b/zh-cn/dynamic-programming-cn.html.markdown
@@ -15,7 +15,7 @@ translators:
动态规划是一种实用的技巧,它可以用来解决一系列特定问题。它的思路很简单,如果你对某个给定的输入解决了一个问题,那么你可以保存已有信息,以避免重复计算,节约计算时间。
-记住,只有那些没有办法记住历史的才被迫做更多的苦力。(Fibonacci就是一个显然的例子)
+记住,如果忘记历史,就要被迫做更多的苦力。斐波那契数列就是一个显然的例子。
## 解决问题的方式
diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown
index 37b4b137..dd52d187 100644
--- a/zh-cn/go-cn.html.markdown
+++ b/zh-cn/go-cn.html.markdown
@@ -35,12 +35,12 @@ import (
"strconv" // 字符串转换
)
-// 函数声明:Main是程序执行的入口。
+// 函数声明:main是程序执行的入口。
// 不管你喜欢还是不喜欢,反正Go就用了花括号来包住函数体。
func main() {
// 往标准输出打印一行。
// 用包名fmt限制打印函数。
- fmt.Println("天坑欢迎你!")
+ fmt.Println("你好世界")
// 调用当前包的另一个函数。
beyondHello()
@@ -81,7 +81,7 @@ func learnTypes() {
f := 3.14195 // float64类型,IEEE-754 64位浮点数
c := 3 + 4i // complex128类型,内部使用两个float64表示
- // Var变量可以直接初始化。
+ // var变量可以直接初始化。
var u uint = 7 // unsigned 无符号变量,但是实现依赖int型变量的长度
var pi float32 = 22. / 7
@@ -141,7 +141,7 @@ func learnTypes() {
// 只用写return一个词就能将函数内指定名称的变量返回
func learnNamedReturns(x, y int) (z int) {
z = x * y
- return // z is implicit here, because we named it earlier.
+ return // 隐式返回z,因为前面指定了它。
}
// Go全面支持垃圾回收。Go有指针,但是不支持指针运算。
@@ -161,7 +161,7 @@ func expensiveComputation() int {
}
func learnFlowControl() {
- // If需要花括号,括号就免了
+ // if需要花括号,括号就免了
if true {
fmt.Println("这句话肯定被执行")
}
diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown
index 27003f3e..1de7f3e6 100644
--- a/zh-cn/java-cn.html.markdown
+++ b/zh-cn/java-cn.html.markdown
@@ -297,8 +297,8 @@ class Bicycle {
// Bicycle 类的成员变量和方法
public int cadence; // Public: 任意位置均可访问
private int speed; // Private: 只在同类中可以访问
- protected int gear; // Protected: 可以在同类与子类中可以访问
- String name; // default: 可以在包内中可以访问
+ protected int gear; // Protected: 可以在同类与子类中访问
+ String name; // default: 可以在包内访问
// 构造函数是初始化一个对象的方式
// 以下是一个默认构造函数
diff --git a/zh-cn/mips-cn.html.markdown b/zh-cn/mips-cn.html.markdown
new file mode 100644
index 00000000..4f9ea7da
--- /dev/null
+++ b/zh-cn/mips-cn.html.markdown
@@ -0,0 +1,334 @@
+---
+language: "MIPS Assembly"
+filename: MIPS-cn.asm
+contributors:
+ - ["Stanley Lim", "https://github.com/Spiderpig86"]
+translators:
+ - ["Liu Yihua", "https://github.com/yihuajack"]
+lang: zh-cn
+---
+
+MIPS(Microprocessor without Interlocked Pipeline Stages)汇编语言是为了配合约翰·雷洛伊·亨尼西于1981年设计的 MIPS 微处理器范式而设计的,这些 RISC 处理器用于嵌入式系统,例如网关和路由器。
+
+[阅读更多](https://en.wikipedia.org/wiki/MIPS_architecture)
+
+```asm
+# 注释用一个 '#' 表示
+
+# 一行中 '#' 之后的所有文本都会被汇编器的词法分析器忽略
+
+# 程序通常包含 .data 和 .text 部分
+
+.data # 数据存储在内存中(在RAM中分配)
+ # 类似于高级语言中的变量
+
+ # 声明遵循( 标签: .类型 值 )的声明形式
+ hello_world: .asciiz "Hello World\n" # 声明一个 null 结束的字符串
+ num1: .word 42 # 整数被视为字
+ # (32位值)
+
+ arr1: .word 1, 2, 3, 4, 5 # 字数组
+ arr2: .byte 'a', 'b' # 字符数组(每个1字节)
+ buffer: .space 60 # 在 RAM 中分配空间
+ # (不清除为0)
+
+ # 数据类型的大小
+ _byte: .byte 'a' # 1字节
+ _halfword: .half 53 # 2字节
+ _word: .word 3 # 4字节
+ _float: .float 3.14 # 4字节
+ _double: .double 7.0 # 8字节
+
+ .align 2 # 数据的内存对齐
+ # 其中数字(应是2的幂)表示几字节对齐
+ # .align 2 表示字对齐(因为 2^2 = 4 字节)
+
+.text # 这部分包括指令和程序逻辑
+.globl _main # 声明一个全局指令标签
+ # 其他文件都可以访问
+
+ _main: # MIPS 程序按顺序执行指令
+ # 这条标签下的代码将首先执行
+
+ # 打印 "hello world"
+ la $a0, hello_world # 加载存储在内存中的字符串地址
+ li $v0, 4 # 加载 syscall 的值
+ # (数字代表要执行哪个 syscall)
+ syscall # 使用给定的参数($a0)执行指定的 syscall
+
+ # 寄存器(用于在程序执行期间保存数据)
+ # $t0 - $t9 # 临时寄存器,用于过程内部的中间计算
+ # (过程调用时不保存)
+
+ # $s0 - $s7 # 保留寄存器(被保留的寄存器,过程调用时保存)
+ # 通常保存在栈中
+
+ # $a0 - $a3 # 参数寄存器,用于传递过程的参数
+ # $v0 - $v1 # 返回寄存器,用于向调用过程返回值
+
+ # 存取指令
+ la $t0, label # 将内存中由 label 指定的值的地址复制到寄存器 $t0 中
+ lw $t0, label # 从内存中复制一个字
+ lw $t1, 4($s0) # 从寄存器中存储的地址复制一个字
+ # 偏移量为4字节(地址 + 4)
+ lb $t2, label # 把一个字节复制到寄存器 $t2 的低阶部分
+ lb $t2, 0($s0) # 从 $s0 的源地址复制一个字节
+ # 偏移量为0
+ # 同理也适用于 'lh' (取半字)
+
+ sw $t0, label # 将字存储到由 label 映射的内存地址中
+ sw $t0, 8($s0) # 将字存储到 $s0 指定的地址中
+ # 偏移量为8字节
+ # 同理也适用于 'sb' (存字)和 'sh' (存半字)。'sa'不存在
+
+### 数学 ###
+ _math:
+ # 记住要将值加载到寄存器中
+ lw $t0, num # 从数据部分
+ li $t0, 5 # 或者从一个立即数(常数)
+ li $t1, 6
+ add $t2, $t0, $t1 # $t2 = $t0 + $t1
+ sub $t2, $t0, $t1 # $t2 = $t0 - $t1
+ mul $t2, $t0, $t1 # $t2 = $t0 * $t1
+ div $t2, $t0, $t1 # $t2 = $t0 / $t1
+ # (MARS 的某些版本可能不支持)
+ div $t0, $t1 # 执行 $t0 / $t1。
+ # 用 'mflo' 得商,用 'mfhi' 得余数
+
+ # 移位
+ sll $t0, $t0, 2 # 按位左移立即数(常数值)2
+ sllv $t0, $t1, $t2 # 根据一个寄存器中的变量值左移相应位
+ srl $t0, $t0, 5 # 按位右移
+ # (不保留符号,用0符号扩展)
+ srlv $t0, $t1, $t2 # 根据一个寄存器中的变量值右移相应位
+ sra $t0, $t0, 7 # 按算术位右移(保留符号)
+ srav $t0, $t1, $t2 # 根据一个寄存器中的变量值右移相应算数位
+
+ # 按位运算符
+ and $t0, $t1, $t2 # 按位与
+ andi $t0, $t1, 0xFFF # 用立即数按位与
+ or $t0, $t1, $t2 # 按位或
+ ori $t0, $t1, 0xFFF # 用立即数按位或
+ xor $t0, $t1, $t2 # 按位异或
+ xori $t0, $t1, 0xFFF # 用立即数按位异或
+ nor $t0, $t1, $t2 # 按位或非
+
+## 分支 ##
+ _branching:
+ # 分支指令的基本格式通常遵循 <指令> <寄存器1> <寄存器2> <标签>
+ # 如果给定的条件求值为真,则跳转到标签
+ # 有时向后编写条件逻辑更容易,如下面的简单的 if 语句示例所示
+
+ beq $t0, $t1, reg_eq # 如果 $t0 == $t1,则跳转到 reg_eq
+ # 否则执行下一行
+ bne $t0, $t1, reg_neq # 当 $t0 != $t1 时跳转
+ b branch_target # 非条件分支,总会执行
+ beqz $t0, req_eq_zero # 当 $t0 == 0 时跳转
+ bnez $t0, req_neq_zero # 当 $t0 != 0 时跳转
+ bgt $t0, $t1, t0_gt_t1 # 当 $t0 > $t1 时跳转
+ bge $t0, $t1, t0_gte_t1 # 当 $t0 >= $t1 时跳转
+ bgtz $t0, t0_gt0 # 当 $t0 > 0 时跳转
+ blt $t0, $t1, t0_gt_t1 # 当 $t0 < $t1 时跳转
+ ble $t0, $t1, t0_gte_t1 # 当 $t0 <= $t1 时跳转
+ bltz $t0, t0_lt0 # 当 $t0 < 0 时跳转
+ slt $s0, $t0, $t1 # 当 $t0 < $t1 时结果为 $s0 (1为真)
+
+ # 简单的 if 语句
+ # if (i == j)
+ # f = g + h;
+ # f = f - i;
+
+ # 让 $s0 = f, $s1 = g, $s2 = h, $s3 = i, $s4 = j
+ bne $s3, $s4, L1 # if (i !=j)
+ add $s0, $s1, $s2 # f = g + h
+
+ L1:
+ sub $s0, $s0, $s3 # f = f - i
+
+ # 下面是一个求3个数的最大值的例子
+ # 从 Java 到 MIPS 逻辑的直接翻译:
+ # if (a > b)
+ # if (a > c)
+ # max = a;
+ # else
+ # max = c;
+ # else
+ # max = b;
+ # else
+ # max = c;
+
+ # 让 $s0 = a, $s1 = b, $s2 = c, $v0 = 返回寄存器
+ ble $s0, $s1, a_LTE_b # 如果 (a <= b) 跳转到 (a_LTE_b)
+ ble $s0, $s2, max_C # 如果 (a > b && a <= c) 跳转到 (max_C)
+ move $v0, $s0 # 否则 [a > b && a > c] max = a
+ j done # 跳转到程序结束
+
+ a_LTE_b: # 当 a <= b 时的标签
+ ble $s1, $s2, max_C # 如果 (a <= b && b <= c) 跳转到 (max_C)
+ move $v0, $s1 # 如果 (a <= b && b > c) max = b
+ j done # 跳转到 done
+
+ max_C:
+ move $v0, $s2 # max = c
+
+ done: # 程序结束
+
+## 循环 ##
+ _loops:
+ # 循环的基本结构是一个退出条件和一个继续执行的跳转指令
+ li $t0, 0
+ while:
+ bgt $t0, 10, end_while # 当 $t0 小于 10,不停迭代
+ addi $t0, $t0, 1 # 累加值
+ j while # 跳转回循环开始
+ end_while:
+
+ # 二维矩阵遍历
+ # 假设 $a0 存储整数 3 × 3 矩阵的地址
+ li $t0, 0 # 计数器 i
+ li $t1, 0 # 计数器 j
+ matrix_row:
+ bgt $t0, 3, matrix_row_end
+
+ matrix_col:
+ bgt $t1, 3, matrix_col_end
+
+ # 执行一些东西
+
+ addi $t1, $t1, 1 # 累加列计数器
+ matrix_col_end:
+
+ # 执行一些东西
+
+ addi $t0, $t0, 1
+ matrix_row_end:
+
+## 函数 ##
+ _functions:
+ # 函数是可调用的过程,可以接受参数并返回所有用标签表示的值,如前所示
+
+ main: # 程序以 main 函数开始
+ jal return_1 # jal 会把当前程序计数器(PC)存储在 $ra
+ # 并跳转到 return_1
+
+ # 如果我们想传入参数呢?
+ # 首先,我们必须将形参传递给参数寄存器
+ li $a0, 1
+ li $a1, 2
+ jal sum # 现在我们可以调用函数了
+
+ # 递归怎么样?
+ # 这需要更多的工作
+ # 由于 jal 会自动覆盖每次调用,我们需要确保在 $ra 中保存并恢复之前的程序计数器
+ li $a0, 3
+ jal fact
+
+ li $v0, 10
+ syscall
+
+ # 这个函数返回1
+ return_1:
+ li $v0, 1 # 将值取到返回寄存器 $v0 中
+ jr $ra # 跳转回原先的程序计数器继续执行
+
+
+ # 有2个参数的函数
+ sum:
+ add $v0, $a0, $a1
+ jr $ra # 返回
+
+ # 求阶乘的递归函数
+ fact:
+ addi $sp, $sp, -8 # 在栈中分配空间
+ sw $s0, ($sp) # 存储保存当前数字的寄存器
+ sw $ra, 4($sp) # 存储先前的程序计数器
+
+ li $v0, 1 # 初始化返回值
+ beq $a0, 0, fact_done # 如果参数为0则完成
+
+ # 否则继续递归
+ move $s0, $a0 # 复制 $a0 到 $s0
+ sub $a0, $a0, 1
+ jal fact
+
+ mul $v0, $s0, $v0 # 做乘法
+
+ fact_done:
+ lw $s0, ($sp)
+ lw $ra, ($sp) # 恢复程序计数器
+ addi $sp, $sp, 8
+
+ jr $ra
+
+## 宏 ##
+ _macros:
+ # 宏可以实现用单个标签替换重复的代码块,这可以增强程序的可读性
+ # 它们绝不是函数的替代品
+ # 它们必须在使用之前声明
+
+ # 用于打印换行符的宏(这可以被多次重用)
+ .macro println()
+ la $a0, newline # 存储在这里的新行字符串
+ li $v0, 4
+ syscall
+ .end_macro
+
+ println() # 汇编器会在运行前复制此代码块
+
+ # 参数可以通过宏传入。
+ # 它们由 '%' 符号表示,可以选择起任意名字
+ .macro print_int(%num)
+ li $v0, 1
+ lw $a0, %num
+ syscall
+ .end_macro
+
+ li $t0, 1
+ print_int($t0)
+
+ # 我们也可以给宏传递立即数
+ .macro immediates(%a, %b)
+ add $t0, %a, %b
+ .end_macro
+
+ immediates(3, 5)
+
+ # 以及标签
+ .macro print(%string)
+ la $a0, %string
+ li $v0, 4
+ syscall
+ .end_macro
+
+ print(hello_world)
+
+## 数组 ##
+.data
+ list: .word 3, 0, 1, 2, 6 # 这是一个字数组
+ char_arr: .asciiz "hello" # 这是一个字符数组
+ buffer: .space 128 # 在内存中分配块,不会自动清除
+ # 这些内存块彼此对齐
+
+.text
+ la $s0, list # 取 list 的地址
+ li $t0, 0 # 计数器
+ li $t1, 5 # list 的长度
+
+ loop:
+ bgt $t0, $t1, end_loop
+
+ lw $a0, ($s0)
+ li $v0, 1
+ syscall # 打印数字
+
+ addi $s0, $s0, 4 # 字的大小为4字节
+ addi $t0, $t0, 1 # 累加
+ j loop
+ end_loop:
+
+## INCLUDE ##
+# 使用 include 语句可以将外部文件导入到程序中
+# (它只是将文件中的代码放入 include 语句的位置)
+.include "somefile.asm"
+
+```
diff --git a/zh-cn/nim-cn.html.markdown b/zh-cn/nim-cn.html.markdown
new file mode 100644
index 00000000..dc662b1e
--- /dev/null
+++ b/zh-cn/nim-cn.html.markdown
@@ -0,0 +1,283 @@
+---
+language: Nim
+filename: learnNim-cn.nim
+contributors:
+ - ["Jason J. Ayala P.", "http://JasonAyala.com"]
+ - ["Dennis Felsing", "http://felsin9.de/nnis/"]
+translators:
+ - ["lzw-723", "https://github.com/lzw-723"]
+lang: zh-cn
+---
+
+Nim(原名Nimrod)是一种静态类型的命令式编程语言,
+它能在不影响运行时效率的情况下为程序员提供强大的功能。
+
+Nim语言高效、有表现力、优雅。
+
+```nim
+# 单行注释以一个#开头
+
+#[
+ 这是多行注释
+ 在Nim语言中,多行注释可以嵌套,以#[开头,以]#结尾
+]#
+
+discard """
+这也可以作为多行注释使用。
+或者用于无法解析、损坏的代码
+"""
+
+var # 声明(和赋值)变量
+ letter: char = 'n' # 带或不带类型批注
+ lang = "N" & "im"
+ nLength: int = len(lang)
+ boat: float
+ truth: bool = false
+
+ let # 使用let*一次性*声明和绑定变量。
+ legs = 400 # legs是不可改变的。
+ arms = 2_000 # _会被忽略,对long类型非常有用。
+ aboutPi = 3.15
+
+const # 常量在编译时计算。这确保了
+ debug = true # 性能,在编译时表达式中很有用。
+ compileBadCode = false
+
+when compileBadCode: # `when`是编译时的`if`
+ legs = legs + 1 # 这个错误永远不会被编译。
+ const input = readline(stdin) # const在编译时必须是已知的。
+
+discard 1 > 2 # 注意:如果表达式的结果未使用,
+ # 编译器会发出警告。`discard`绕过了这一点。
+
+
+#
+# 数据结构
+#
+
+# 元组(Tuple)
+
+var
+ child: tuple[name: string, age: int] # 元组有*字段名*
+ today: tuple[sun: string, temp: float] # 和*顺序*
+
+
+child = (name: "Rudiger", age: 2) # 使用字面值()一次性赋值全部
+today.sun = "Overcast" # 也可以单独赋值
+today.temp = 70.1
+
+# 序列(Sequence)
+
+var
+ drinks: seq[string]
+
+drinks = @["Water", "Juice", "Chocolate"] # @[V1,..,Vn] 是序列的字面值
+
+drinks.add("Milk")
+
+if "Milk" in drinks:
+ echo "We have Milk and ", drinks.len - 1, " other drinks"
+
+let myDrink = drinks[2]
+
+#
+# 自定义类型
+#
+
+# 定义你自己的类型使得编译器为你工作。
+# 这使得静态类型变得强大和有用。
+
+type
+ Name = string # 类型别名为你提供一个新类型,
+ Age = int # 该类型可与旧类型互换,但更具描述性。
+ Person = tuple[name: Name, age: Age] # 也可以定义数据结构。
+ AnotherSyntax = tuple
+ fieldOne: string
+ secondField: int
+
+var
+ john: Person = (name: "John B.", age: 17)
+ newage: int = 18 # 在这里使用Age比int要好
+
+john.age = newage # 仍然有效,因为int和Age同义
+
+type
+ Cash = distinct int # `distinct`使一个新类型与它的基本类型不兼容。
+ Desc = distinct string
+
+var
+ money: Cash = 100.Cash # `.Cash`把int转换成我们的类型
+ description: Desc = "Interesting".Desc
+
+when compileBadCode:
+ john.age = money # 错误!age是int类型、money是Cash类型
+ john.name = description # 编译器说:“没门!”
+
+#
+# 更多类型和数据结构
+#
+
+# 枚举类型只能具有有限数量的值之一
+
+type
+ Color = enum cRed, cBlue, cGreen
+ Direction = enum # 可选格式
+ dNorth
+ dWest
+ dEast
+ dSouth
+var
+ orient = dNorth # `orient`的类型是Direction,值是`dNorth`
+ pixel = cGreen # `pixel`的类型是Color,值是`cGreen`
+
+discard dNorth > dEast # Enum通常是“序数”类型
+
+# 子范围指定有限的有效范围
+
+type
+ DieFaces = range[1..20] # 只有从1到20的int才是有效值
+var
+ my_roll: DieFaces = 13
+
+when compileBadCode:
+ my_roll = 23 # 错误!
+
+# 数组(Array)
+
+type
+ RollCounter = array[DieFaces, int] # 数组长度固定
+ DirNames = array[Direction, string] # 以任意有序类型索引
+ Truths = array[42..44, bool]
+var
+ counter: RollCounter
+ directions: DirNames
+ possible: Truths
+
+possible = [false, false, false] # 数组字面以[V1,..,Vn]表示
+possible[42] = true
+
+directions[dNorth] = "Ahh. The Great White North!"
+directions[dWest] = "No, don't go there."
+
+my_roll = 13
+counter[my_roll] += 1
+counter[my_roll] += 1
+
+var anotherArray = ["Default index", "starts at", "0"]
+
+# 可用的数据结构包括表、集合、列表、队列、压缩前缀树。
+# http://nim-lang.org/docs/lib.html#collections-and-algorithms
+
+#
+# IO和控制流
+#
+
+# `case`, `readLine()`
+
+echo "Read any good books lately?"
+case readLine(stdin)
+of "no", "No":
+ echo "Go to your local library."
+of "yes", "Yes":
+ echo "Carry on, then."
+else:
+ echo "That's great; I assume."
+
+# `while`, `if`, `continue`, `break`
+
+import strutils as str # http://nim-lang.org/docs/strutils.html
+echo "I'm thinking of a number between 41 and 43. Guess which!"
+let number: int = 42
+var
+ raw_guess: string
+ guess: int
+while guess != number:
+ raw_guess = readLine(stdin)
+ if raw_guess == "": continue # 跳出循环
+ guess = str.parseInt(raw_guess)
+ if guess == 1001:
+ echo("AAAAAAGGG!")
+ break
+ elif guess > number:
+ echo("Nope. Too high.")
+ elif guess < number:
+ echo(guess, " is too low")
+ else:
+ echo("Yeeeeeehaw!")
+
+#
+# 循环(Iteration)
+#
+
+for i, elem in ["Yes", "No", "Maybe so"]: # 也可以是`for elem in`
+ echo(elem, " is at index: ", i)
+
+for k, v in items(@[(person: "You", power: 100), (person: "Me", power: 9000)]):
+ echo v
+
+let myString = """
+an <example>
+`string` to
+play with
+""" # 多行字符串
+
+for line in splitLines(myString):
+ echo(line)
+
+for i, c in myString: # 索引和字符。或使用'for j in'只有字符
+ if i mod 2 == 0: continue # 紧凑的'if'形式
+ elif c == 'X': break
+ else: echo(c)
+
+#
+# 过程(Procedure)
+#
+
+type Answer = enum aYes, aNo
+
+proc ask(question: string): Answer =
+ echo(question, " (y/n)")
+ while true:
+ case readLine(stdin)
+ of "y", "Y", "yes", "Yes":
+ return Answer.aYes # 枚举类型可以
+ of "n", "N", "no", "No":
+ return Answer.aNo
+ else: echo("Please be clear: yes or no")
+
+proc addSugar(amount: int = 2) = # amount默认是2,不返回任何值
+ assert(amount > 0 and amount < 9000, "Crazy Sugar")
+ for a in 1..amount:
+ echo(a, " sugar...")
+
+case ask("Would you like sugar in your tea?")
+of aYes:
+ addSugar(3)
+of aNo:
+ echo "Oh do take a little!"
+ addSugar()
+# 这里不需要使用`else` 。只能是`yes`和`no`。
+
+#
+# 外部函数接口(FFI)
+#
+
+# 因为Nim可以编译为C,使用外部函数接口(FFI)很简单:
+
+proc strcmp(a, b: cstring): cint {.importc: "strcmp", nodecl.}
+
+let cmp = strcmp("C?", "Easy!")
+```
+
+除此以外,Nim通过元编程、性能和编译时特性将自己与其他同类分离开来。
+
+## 进阶阅读
+
+* [主页](http://nim-lang.org)
+* [下载](http://nim-lang.org/download.html)
+* [社区](http://nim-lang.org/community.html)
+* [常见问题](http://nim-lang.org/question.html)
+* [文档](http://nim-lang.org/documentation.html)
+* [参考手册](http://nim-lang.org/docs/manual.html)
+* [标准库](http://nim-lang.org/docs/lib.html)
+* [Rosetta Code](http://rosettacode.org/wiki/Category:Nim)
diff --git a/zh-cn/perl-cn.html.markdown b/zh-cn/perl-cn.html.markdown
index 4421da6e..46c54618 100644
--- a/zh-cn/perl-cn.html.markdown
+++ b/zh-cn/perl-cn.html.markdown
@@ -146,7 +146,7 @@ perlfaq有很多常见问题和相应回答,也经常有对优秀CPAN模块的
#### 深入阅读
- - [perl-tutorial](http://perl-tutorial.org/)
- - [www.perl.com的learn站点](http://www.perl.org/learn.html)
- - [perldoc](http://perldoc.perl.org/)
- - 以及 perl 内置的: `perldoc perlintro`
+- [perl-tutorial](http://perl-tutorial.org/)
+- [www.perl.com的learn站点](http://www.perl.org/learn.html)
+- [perldoc](http://perldoc.perl.org/)
+- 以及 perl 内置的: `perldoc perlintro`
diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown
index 6c5556fc..a4e53c1b 100644
--- a/zh-cn/python-cn.html.markdown
+++ b/zh-cn/python-cn.html.markdown
@@ -6,8 +6,10 @@ contributors:
- ["Andre Polykanine", "https://github.com/Oire"]
translators:
- ["Geoff Liu", "http://geoffliu.me"]
+ - ["Maple", "https://github.com/mapleincode"]
filename: learnpython-cn.py
lang: zh-cn
+
---
Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。
@@ -19,7 +21,6 @@ Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。
注意:这篇教程是基于 Python 3 写的。如果你想学旧版 Python 2,我们特别有[另一篇教程](http://learnxinyminutes.com/docs/pythonlegacy/)。
```python
-
# 用井字符开头的是单行注释
""" 多行字符串用三个引号
@@ -35,50 +36,66 @@ Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。
3 # => 3
# 算术没有什么出乎意料的
-1 + 1 # => 2
-8 - 1 # => 7
+1 + 1 # => 2
+8 - 1 # => 7
10 * 2 # => 20
# 但是除法例外,会自动转换成浮点数
35 / 5 # => 7.0
-5 / 3 # => 1.6666666666666667
+10.0 / 3 # => 3.3333333333333335
# 整数除法的结果都是向下取整
-5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # 浮点数也可以
--5 // 3 # => -2
--5.0 // 3.0 # => -2.0
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # 浮点数也可以
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
# 浮点数的运算结果也是浮点数
3 * 2.0 # => 6.0
# 模除
7 % 3 # => 1
+# i % j 结果的正负符号会和 j 相同,而不是和 i 相同
+-7 % 3 # => 2
-# x的y次方
+# x 的 y 次方
2**4 # => 16
# 用括号决定优先级
+1 + 3 * 2 # => 7
(1 + 3) * 2 # => 8
-# 布尔值
-True
-False
+# 布尔值 (注意: 首字母大写)
+True # => True
+False # => False
-# 用not取非
-not True # => False
+# 用 not 取非
+not True # => False
not False # => True
-# 逻辑运算符,注意and和or都是小写
+# 逻辑运算符,注意 and 和 or 都是小写
True and False # => False
False or True # => True
-# 整数也可以当作布尔值
-0 and 2 # => 0
--5 or 0 # => -5
+# True 和 False 实质上就是数字 1 和0
+True + True # => 2
+True * 8 # => 8
+False - 5 # => -5
+
+# 数值与 True 和 False 之间的比较运算
0 == False # => True
2 == True # => False
1 == True # => True
+-5 != False # => True
+
+# 使用布尔逻辑运算符对数字类型的值进行运算时,会把数值强制转换为布尔值进行运算
+# 但计算结果会返回它们的强制转换前的值
+# 注意不要把 bool(ints) 与位运算的 "按位与"、"按位或" (&, |) 混淆
+bool(0) # => False
+bool(4) # => True
+bool(-6) # => True
+0 and 2 # => 0
+-5 or 0 # => -5
# 用==判断相等
1 == 1 # => True
@@ -94,47 +111,71 @@ False or True # => True
2 <= 2 # => True
2 >= 2 # => True
+# 判断一个值是否在范围里
+1 < 2 and 2 < 3 # => True
+2 < 3 and 3 < 2 # => False
# 大小比较可以连起来!
1 < 2 < 3 # => True
2 < 3 < 2 # => False
-# 字符串用单引双引都可以
+# (is 对比 ==) is 判断两个变量是否引用同一个对象,
+# 而 == 判断两个对象是否含有相同的值
+a = [1, 2, 3, 4] # 变量 a 是一个新的列表, [1, 2, 3, 4]
+b = a # 变量 b 赋值了变量 a 的值
+b is a # => True, a 和 b 引用的是同一个对象
+b == a # => True, a 和 b 的对象的值相同
+b = [1, 2, 3, 4] # 变量 b 赋值了一个新的列表, [1, 2, 3, 4]
+b is a # => False, a 和 b 引用的不是同一个对象
+b == a # => True, a 和 b 的对象的值相同
+
+
+# 创建字符串可以使用单引号(')或者双引号(")
"这是个字符串"
'这也是个字符串'
-# 用加号连接字符串
+# 字符串可以使用加号连接成新的字符串
"Hello " + "world!" # => "Hello world!"
+# 非变量形式的字符串甚至可以在没有加号的情况下连接
+"Hello " "world!" # => "Hello world!"
# 字符串可以被当作字符列表
-"This is a string"[0] # => 'T'
+"Hello world!"[0] # => 'H'
-# 用.format来格式化字符串
-"{} can be {}".format("strings", "interpolated")
+# 你可以获得字符串的长度
+len("This is a string") # => 16
+# 你可以使用 f-strings 格式化字符串(python3.6+)
+name = "Reiko"
+f"She said her name is {name}." # => "She said her name is Reiko"
+# 你可以在大括号内几乎加入任何 python 表达式,表达式的结果会以字符串的形式返回
+f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long."
+
+# 用 .format 来格式化字符串
+"{} can be {}".format("strings", "interpolated")
# 可以重复参数以节省时间
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
# => "Jack be nimble, Jack be quick, Jack jump over the candle stick"
-
# 如果不想数参数,可以用关键字
"{name} wants to eat {food}".format(name="Bob", food="lasagna")
# => "Bob wants to eat lasagna"
-# 如果你的Python3程序也要在Python2.5以下环境运行,也可以用老式的格式化语法
+# 如果你的 Python3 程序也要在 Python2.5 以下环境运行,也可以用老式的格式化语法
"%s can be %s the %s way" % ("strings", "interpolated", "old")
# None是一个对象
None # => None
-# 当与None进行比较时不要用 ==,要用is。is是用来比较两个变量是否指向同一个对象。
+# 当与 None 进行比较时不要用 ==,要用 is。is 是用来比较两个变量是否指向同一个对象。
"etc" is None # => False
None is None # => True
-# None,0,空字符串,空列表,空字典都算是False
-# 所有其他值都是True
+# None,0,空字符串,空列表,空字典,空元组都算是 False
+# 所有其他值都是 True
bool(0) # => False
bool("") # => False
bool([]) # => False
bool({}) # => False
+bool(()) # => False
####################################################
@@ -144,16 +185,26 @@ bool({}) # => False
# print是内置的打印函数
print("I'm Python. Nice to meet you!")
+# 默认情况下,print 函数会在输出结果后加入一个空行作为结尾
+# 可以使用附加参数改变输出结尾
+print("Hello, World", end="!") # => Hello, World!
+
+# 可以很简单的从终端获得输入数据
+input_string_var = input("Enter some data: ") # 返回字符串数值
+
# 在给变量赋值前不用提前声明
-# 传统的变量命名是小写,用下划线分隔单词
+# 习惯上变量命名是小写,用下划线分隔单词
some_var = 5
some_var # => 5
# 访问未赋值的变量会抛出异常
# 参考流程控制一段来学习异常处理
-some_unknown_var # 抛出NameError
+some_unknown_var # 抛出 NameError
+
+# "if" 可以用作表达式,它的作用等同于 C 语言的三元运算符 "?:"
+"yay!" if 0 > 1 else "nay!" # => "nay!"
-# 用列表(list)储存序列
+# 用列表 (list) 储存序列
li = []
# 创建列表时也可以同时赋给元素
other_li = [4, 5, 6]
@@ -173,128 +224,177 @@ li[0] # => 1
# 取出最后一个元素
li[-1] # => 3
-# 越界存取会造成IndexError
-li[4] # 抛出IndexError
+# 越界存取会造成 IndexError
+li[4] # 抛出 IndexError
# 列表有切割语法
-li[1:3] # => [2, 4]
+li[1:3] # => [2, 4]
# 取尾
-li[2:] # => [4, 3]
+li[2:] # => [4, 3]
# 取头
-li[:3] # => [1, 2, 4]
+li[:3] # => [1, 2, 4]
# 隔一个取一个
-li[::2] # =>[1, 4]
+li[::2] # =>[1, 4]
# 倒排列表
li[::-1] # => [3, 4, 2, 1]
# 可以用三个参数的任何组合来构建切割
# li[始:终:步伐]
-# 用del删除任何一个元素
-del li[2] # li is now [1, 2, 3]
+# 简单的实现了单层数组的深度复制
+li2 = li[:] # => li2 = [1, 2, 4, 3] ,但 (li2 is li) 会返回 False
+
+# 用 del 删除任何一个元素
+del li[2] # li 现在为 [1, 2, 3]
+
+# 删除第一个匹配的元素
+li.remove(2) # li 现在为 [1, 3]
+li.remove(2) # 抛出错误 ValueError: 2 is not in the list
+
+# 在指定索引处插入一个新的元素
+li.insert(1, 2) # li is now [1, 2, 3] again
+
+# 获得列表第一个匹配的值的索引
+li.index(2) # => 1
+li.index(4) # 抛出一个 ValueError: 4 is not in the list
# 列表可以相加
-# 注意:li和other_li的值都不变
+# 注意:li 和 other_li 的值都不变
li + other_li # => [1, 2, 3, 4, 5, 6]
-# 用extend拼接列表
-li.extend(other_li) # li现在是[1, 2, 3, 4, 5, 6]
+# 用 "extend()" 拼接列表
+li.extend(other_li) # li 现在是[1, 2, 3, 4, 5, 6]
-# 用in测试列表是否包含值
+# 用 "in" 测试列表是否包含值
1 in li # => True
-# 用len取列表长度
+# 用 "len()" 取列表长度
len(li) # => 6
-# 元组是不可改变的序列
+# 元组类似列表,但是不允许修改
tup = (1, 2, 3)
tup[0] # => 1
-tup[0] = 3 # 抛出TypeError
+tup[0] = 3 # 抛出 TypeError
+
+# 如果元素数量为 1 的元组必须在元素之后加一个逗号
+# 其他元素数量的元组,包括空元组,都不需要
+type((1)) # => <class 'int'>
+type((1,)) # => <class 'tuple'>
+type(()) # => <class 'tuple'>
-# 列表允许的操作元组大都可以
+# 列表允许的操作元组大多都可以
len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
tup[:2] # => (1, 2)
2 in tup # => True
# 可以把元组合列表解包,赋值给变量
-a, b, c = (1, 2, 3) # 现在a是1,b是2,c是3
+a, b, c = (1, 2, 3) # 现在 a 是 1,b 是 2,c 是 3
+# 也可以做扩展解包
+a, *b, c = (1, 2, 3, 4) # 现在 a 是 1, b 是 [2, 3], c 是 4
# 元组周围的括号是可以省略的
-d, e, f = 4, 5, 6
+d, e, f = 4, 5, 6 # 元组 4, 5, 6 通过解包被赋值给变量 d, e, f
# 交换两个变量的值就这么简单
-e, d = d, e # 现在d是5,e是4
+e, d = d, e # 现在 d 是 5,e 是 4
-# 用字典表达映射关系
+# 字典用来存储 key 到 value 的映射关系
empty_dict = {}
# 初始化的字典
filled_dict = {"one": 1, "two": 2, "three": 3}
+# 字典的 key 必须为不可变类型。 这是为了确保 key 被转换为唯一的哈希值以用于快速查询
+# 不可变类型包括整数、浮点、字符串、元组
+invalid_dict = {[1,2,3]: "123"} # => 抛出 TypeError: unhashable type: 'list'
+valid_dict = {(1,2,3):[1,2,3]} # 然而 value 可以是任何类型
+
# 用[]取值
filled_dict["one"] # => 1
-
# 用 keys 获得所有的键。
-# 因为 keys 返回一个可迭代对象,所以在这里把结果包在 list 里。我们下面会详细介绍可迭代。
-# 注意:字典键的顺序是不定的,你得到的结果可能和以下不同。
-list(filled_dict.keys()) # => ["three", "two", "one"]
+# 因为 keys 返回一个可迭代对象,所以我们需要把它包在 "list()" 里才能转换为列表。
+# 我们下面会详细介绍可迭代。
+# 注意: 对于版本 < 3.7 的 python, 字典的 key 的排序是无序的。你的运行结果
+# 可能与下面的例子不符,但是在 3.7 版本,字典中的项会按照他们被插入到字典的顺序进行排序
+list(filled_dict.keys()) # => ["three", "two", "one"] Python 版本 <3.7
+list(filled_dict.keys()) # => ["one", "two", "three"] Python 版本 3.7+
+# 用 "values()" 获得所有的值。跟 keys 一样也是可迭代对象,要使用 "list()" 才能转换为列表。
+# 注意: 排序顺序和 keys 的情况相同。
-# 用values获得所有的值。跟keys一样,要用list包起来,顺序也可能不同。
-list(filled_dict.values()) # => [3, 2, 1]
+list(filled_dict.values()) # => [3, 2, 1] Python 版本 < 3.7
+list(filled_dict.values()) # => [1, 2, 3] Python 版本 3.7+
# 用in测试一个字典是否包含一个键
"one" in filled_dict # => True
1 in filled_dict # => False
-# 访问不存在的键会导致KeyError
+# 访问不存在的键会导致 KeyError
filled_dict["four"] # KeyError
-# 用get来避免KeyError
-filled_dict.get("one") # => 1
-filled_dict.get("four") # => None
-# 当键不存在的时候get方法可以返回默认值
+# 用 "get()" 来避免KeyError
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
+# 当键不存在的时候 "get()" 方法可以返回默认值
filled_dict.get("one", 4) # => 1
-filled_dict.get("four", 4) # => 4
+filled_dict.get("four", 4) # => 4
-# setdefault方法只有当键不存在的时候插入新值
-filled_dict.setdefault("five", 5) # filled_dict["five"]设为5
-filled_dict.setdefault("five", 6) # filled_dict["five"]还是5
+# "setdefault()" 方法只有当键不存在的时候插入新值
+filled_dict.setdefault("five", 5) # filled_dict["five"] 设为5
+filled_dict.setdefault("five", 6) # filled_dict["five"] 还是5
# 字典赋值
filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
-filled_dict["four"] = 4 # 另一种赋值方法
+filled_dict["four"] = 4 # 另一种赋值方法
-# 用del删除
-del filled_dict["one"] # 从filled_dict中把one删除
+# 用 del 删除项
+del filled_dict["one"] # 从 filled_dict 中把 one 删除
-# 用set表达集合
+# 用 set 表达集合
empty_set = set()
# 初始化一个集合,语法跟字典相似。
-some_set = {1, 1, 2, 2, 3, 4} # some_set现在是{1, 2, 3, 4}
+some_set = {1, 1, 2, 2, 3, 4} # some_set现在是 {1, 2, 3, 4}
+
+# 类似字典的 keys,set 的元素也必须是不可变类型
+invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list'
+valid_set = {(1,), 1}
# 可以把集合赋值于变量
filled_set = some_set
# 为集合添加元素
-filled_set.add(5) # filled_set现在是{1, 2, 3, 4, 5}
+filled_set.add(5) # filled_set 现在是 {1, 2, 3, 4, 5}
+# set 没有重复的元素
+filled_set.add(5) # filled_set 依然是 {1, 2, 3, 4, 5}
-# & 取交集
+# "&" 取交集
other_set = {3, 4, 5, 6}
filled_set & other_set # => {3, 4, 5}
-# | 取并集
+# "|" 取并集
filled_set | other_set # => {1, 2, 3, 4, 5, 6}
-# - 取补集
+# "-" 取补集
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+# "^" 取异或集(对称差)
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# 判断左边的集合是否是右边集合的超集
+{1, 2} >= {1, 2, 3} # => False
+
+# 判断左边的集合是否是右边集合的子集
+{1, 2} <= {1, 2, 3} # => True
+
# in 测试集合是否包含元素
2 in filled_set # => True
10 in filled_set # => False
+# 单层集合的深度复制
+filled_set = some_set.copy() # filled_set 是 {1, 2, 3, 4, 5}
+filled_set is some_set # => False
####################################################
## 3. 流程控制和迭代器
@@ -303,28 +403,30 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# 先随便定义一个变量
some_var = 5
-# 这是个if语句。注意缩进在Python里是有意义的
-# 印出"some_var比10小"
+# 这是个if语句。注意缩进在Python里是有意义的!
+# 缩进要使用 4 个空格而不是 tabs。
+# 这段代码会打印 "some_var is smaller than 10"
if some_var > 10:
- print("some_var比10大")
-elif some_var < 10: # elif句是可选的
- print("some_var比10小")
-else: # else也是可选的
- print("some_var就是10")
+ print("some_var is totally bigger than 10.")
+elif some_var < 10: # elif 语句是可选的
+ print("some_var is smaller than 10.")
+else: # else 也是可选的
+ print("some_var is indeed 10.")
"""
-用for循环语句遍历列表
+用 for 循环语句遍历列表
打印:
dog is a mammal
cat is a mammal
mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
+ # 你可以使用 format() 格式化字符串并插入值
print("{} is a mammal".format(animal))
"""
-"range(number)"返回数字列表从0到给的数字
+"range(number)" 返回数字列表从 0 到 number 的数字
打印:
0
1
@@ -333,9 +435,41 @@ for animal in ["dog", "cat", "mouse"]:
"""
for i in range(4):
print(i)
+
+"""
+"range(lower, upper)" 会返回一个包含从 lower 到 upper 的数字迭代器
+prints:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print(i)
"""
-while循环直到条件不满足
+"range(lower, upper, step)" 会返回一个,从 lower 到 upper、并且间隔值为 step 的迭代器。
+如果 step 未传入则会使用默认值 1
+prints:
+ 4
+ 6
+"""
+for i in range(4, 8, 2):
+ print(i)
+
+"""
+遍历列表,并且同时返回列表里的每一个元素的索引和数值。
+prints:
+ 0 dog
+ 1 cat
+ 2 mouse
+"""
+animals = ["dog", "cat", "mouse"]
+for i, value in enumerate(animals):
+ print(i, value)
+
+"""
+while 循环直到条件不满足
打印:
0
1
@@ -347,20 +481,51 @@ while x < 4:
print(x)
x += 1 # x = x + 1 的简写
-# 用try/except块处理异常状况
+
+# 用 try/except 块处理异常状况
try:
- # 用raise抛出异常
+ # 用 raise 抛出异常
raise IndexError("This is an index error")
except IndexError as e:
- pass # pass是无操作,但是应该在这里处理错误
+ pass # pass 是无操作,但是应该在这里处理错误
except (TypeError, NameError):
- pass # 可以同时处理不同类的错误
-else: # else语句是可选的,必须在所有的except之后
+ pass # 可以同时处理不同类的错误
+else: # else语句是可选的,必须在所有的except之后
print("All good!") # 只有当try运行完没有错误的时候这句才会运行
+finally: # 在任何情况下都会执行
+ print("We can clean up resources here")
+
+# 你可以使用 with 语句来代替 try/finally 对操作进行结束的操作
+with open("myfile.txt") as f:
+ for line in f:
+ print(line)
+
+# 写入文件
+contents = {"aa": 12, "bb": 21}
+with open("myfile1.txt", "w+") as file:
+ file.write(str(contents)) # 写入字符串到文件
+
+with open("myfile2.txt", "w+") as file:
+ file.write(json.dumps(contents)) # 写入对象到文件
+
+# Reading from a file
+with open("myfile1.txt", "r+") as file:
+ contents = file.read() # 从文件读取字符串
+print(contents)
+# print: {"aa": 12, "bb": 21}
+
+with open("myfile2.txt", "r+") as file:
+ contents = json.load(file) # 从文件读取 json 对象
+print(contents)
+# print: {"aa": 12, "bb": 21}
+
+# Windows 环境调用 open() 读取文件的默认编码为 ANSI,如果需要读取 utf-8 编码的文件,
+# 需要指定 encoding 参数:
+# open("myfile3.txt", "r+", encoding = "utf-8")
-# Python提供一个叫做可迭代(iterable)的基本抽象。一个可迭代对象是可以被当作序列
-# 的对象。比如说上面range返回的对象就是可迭代的。
+# Python 提供一个叫做可迭代 (iterable) 的基本抽象。一个可迭代对象是可以被当作序列
+# 的对象。比如说上面 range 返回的对象就是可迭代的。
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
@@ -377,19 +542,24 @@ our_iterable[1] # 抛出TypeError
our_iterator = iter(our_iterable)
# 迭代器是一个可以记住遍历的位置的对象
-# 用__next__可以取得下一个元素
-our_iterator.__next__() # => "one"
+# 用 "next()" 获得下一个对象
+next(our_iterator) # => "one"
-# 再一次调取__next__时会记得位置
-our_iterator.__next__() # => "two"
-our_iterator.__next__() # => "three"
+# 再一次调取 "next()" 时会记得位置
+next(our_iterator) # => "two"
+next(our_iterator) # => "three"
-# 当迭代器所有元素都取出后,会抛出StopIteration
-our_iterator.__next__() # 抛出StopIteration
+# 当迭代器所有元素都取出后,会抛出 StopIteration
+next(our_iterator) # 抛出 StopIteration
-# 可以用list一次取出迭代器所有的元素
-list(filled_dict.keys()) # => Returns ["one", "two", "three"]
+# 我们可以通过遍历还访问所有的值,实际上,for 内部实现了迭代
+our_iterator = iter(our_iterable)
+for i in our_iterator:
+ print(i) # 依次打印 one, two, three
+# 可以用 list 一次取出迭代器或者可迭代对象所有的元素
+list(filled_dict.keys()) # => 返回 ["one", "two", "three"]
+list(our_iterator) # => 返回 [] 因为迭代的位置被保存了
####################################################
@@ -399,10 +569,10 @@ list(filled_dict.keys()) # => Returns ["one", "two", "three"]
# 用def定义新函数
def add(x, y):
print("x is {} and y is {}".format(x, y))
- return x + y # 用return语句返回
+ return x + y # 用 return 语句返回
# 调用函数
-add(5, 6) # => 印出"x is 5 and y is 6"并且返回11
+add(5, 6) # => 打印 "x is 5 and y is 6" 并且返回 11
# 也可以用关键字参数来调用函数
add(y=6, x=5) # 关键字参数可以用任何顺序
@@ -433,33 +603,43 @@ all_the_args(1, 2, a=3, b=4) prints:
{"a": 3, "b": 4}
"""
-# 调用可变参数函数时可以做跟上面相反的,用*展开序列,用**展开字典。
+# 调用可变参数函数时可以做跟上面相反的,用 * 展开元组,用 ** 展开字典。
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args) # 相当于 all_the_args(1, 2, 3, 4)
all_the_args(**kwargs) # 相当于 all_the_args(a=3, b=4)
all_the_args(*args, **kwargs) # 相当于 all_the_args(1, 2, 3, 4, a=3, b=4)
+# 使用返回多个数值(返回值为元组类型)
+def swap(x, y):
+ return y, x # 用不带括号的元组的格式来返回多个数值
+ # (注意: 括号不需要加,但是也可以加)
+
+x = 1
+y = 2
+x, y = swap(x, y) # => x = 2, y = 1
+# (x, y) = swap(x,y) # 同上,括号不需要加,但是也可以加
+
# 函数作用域
x = 5
def setX(num):
- # 局部作用域的x和全局域的x是不同的
+ # 局部作用域的 x 和全局域的 x 是不同的
x = num # => 43
print (x) # => 43
def setGlobalX(num):
global x
print (x) # => 5
- x = num # 现在全局域的x被赋值
+ x = num # 现在全局域的 x 被赋值
print (x) # => 6
setX(43)
setGlobalX(6)
-# 函数在Python是一等公民
+# 函数在 Python 是一等公民
def create_adder(x):
def adder(y):
return x + y
@@ -469,39 +649,90 @@ add_10 = create_adder(10)
add_10(3) # => 13
# 也有匿名函数
-(lambda x: x > 2)(3) # => True
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
# 内置的高阶函数
-map(add_10, [1, 2, 3]) # => [11, 12, 13]
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+list(map(add_10, [1, 2, 3])) # => [11, 12, 13]
+list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3]
+
+list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7]
# 用列表推导式可以简化映射和过滤。列表推导式的返回值是另一个列表。
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
+# 你也可以用这种方式实现对集合和字典的构建
+{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'}
+{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
+
+
####################################################
-## 5. 类
+## 5. 模块
####################################################
+# 导入模块
+import math
+print(math.sqrt(16)) # => 4.0
+
+# 你可以导入模块中具体的函数
+from math import ceil, floor
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
+
+# 你可以导入模块中的所有的函数
+# 警告: 此操作不推荐
+from math import *
+
+# 你可以对模块名进行简化
+import math as m
+math.sqrt(16) == m.sqrt(16) # => True
+
+# Python 模块实质上是 Python 文件
+# 你可以自己编写自己的模块,然后导入
+# 模块的名称和文件名相同
+
+# 你可以用 "dir()" 查看模块中定义的函数和字段
+import math
+dir(math)
+
+# 当你的脚本文件所在的文件夹也包含了一个名为 math.py 的 Python 文件
+# 这个 math.p 文件会被代替引入,而不是引入 Python 內建模块中的 math
+# 出现这个情况的原因是本地文件夹的引入优先级要比 Python 內建库引入优先级要高
+
+
+####################################################
+## 6. 类
+####################################################
-# 定义一个继承object的类
-class Human(object):
+# 我们使用 "class" 语句来创建类
+class Human:
- # 类属性,被所有此类的实例共用。
+ # 一个类的字段。 这个字段共享给这个类的所有实例。
species = "H. sapiens"
- # 构造方法,当实例被初始化时被调用。注意名字前后的双下划线,这是表明这个属
- # 性或方法对Python有特殊意义,但是允许用户自行定义。你自己取名时不应该用这
- # 种格式。
+ # 构造方法,当实例被初始化时被调用。注意名字前后的双下划线,这是表明这个属性
+ # 或方法对 Python 有特殊意义,但是允许用户自行定义。
+ # 方法(可能是对象或者属性) 类似: __init__, __str__,__repr__ etc
+ # 都是特殊的方法
+ # 你自己取名时不应该用这种格式
def __init__(self, name):
- # Assign the argument to the instance's name attribute
+ # 将参数赋值给实例的 name 字段
self.name = name
- # 实例方法,第一个参数总是self,就是这个实例对象
+ # 初始化属性
+ self._age = 0
+
+ # 实例方法,第一个参数总是self,也就是这个实例对象
def say(self, msg):
- return "{name}: {message}".format(name=self.name, message=msg)
+ print("{name}: {message}".format(name=self.name, message=msg))
+
+ # 另一个实例方法
+ def sing(self):
+ return 'yo... yo... microphone check... one two... one two...'
- # 类方法,被所有此类的实例共用。第一个参数是这个类对象。
+ # 类方法,被所有此类的实例共用。
+ # 第一个参数是这个类对象。
@classmethod
def get_species(cls):
return cls.species
@@ -511,53 +742,225 @@ class Human(object):
def grunt():
return "*grunt*"
+ # property 有点类似 getter
+ # 它把方法 age() 转换为同名并且只读的属性
+ # 通常情况下,可以不需要编写复杂的 getter 和 setter。
+ @property
+ def age(self):
+ return self._age
+
+ # 允许属性被修改
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # 允许属性被删除
+ @age.deleter
+ def age(self):
+ del self._age
+
+# 当 Python 解释器在读取源文件的时候,就会执行文件中所有的代码
+# 对 __name__ 的检查可以保证这块代码只会在执行这个模块是住程序情况下被运行(而不是在引用时运行)
+if __name__ == '__main__':
+ #
+ i = Human(name="Ian")
+ i.say("hi") # "Ian: hi"
+ j = Human("Joel")
+ j.say("hello") # "Joel: hello"
+ # i 和 j 都是 Human 实例化后的对象,换一句话说,它们都是 Human 实例
+
+ # 运行类方法 (classmethod)
+ i.say(i.get_species()) # "Ian: H. sapiens"
+ # 修改共享的类属性
+ Human.species = "H. neanderthalensis"
+ i.say(i.get_species()) # => "Ian: H. neanderthalensis"
+ j.say(j.get_species()) # => "Joel: H. neanderthalensis"
+
+ # 运行静态方法 (staticmethod)
+ print(Human.grunt()) # => "*grunt*"
+
+ # 实例上也可以执行静态方法
+ print(i.grunt()) # => "*grunt*"
+
+ # 更新实例的属性
+ i.age = 42
+ # 访问实例的属性
+ i.say(i.age) # => "Ian: 42"
+ j.say(j.age) # => "Joel: 0"
+ # 删除实例的属性
+ del i.age
+ # i.age # => 这会抛出一个错误: AttributeError
+
+
+####################################################
+## 6.1 类的继承
+####################################################
+
+# 继承机制允许子类可以继承父类上的方法和变量。
+# 我们可以把 Human 类作为一个基础类或者说叫做父类,
+# 然后定义一个名为 Superhero 的子类来继承父类上的比如 "species"、 "name"、 "age" 的属性
+# 和比如 "sing" 、"grunt" 这样的方法,同时,也可以定义它自己独有的属性
+
+# 基于 Python 文件模块化的特点,你可以把这个类放在独立的文件中,比如说,human.py。
+
+# 要从别的文件导入函数,需要使用以下的语句
+# from "filename-without-extension" import "function-or-class"
+
+from human import Human
+
+# 指定父类作为类初始化的参数
+class Superhero(Human):
+
+ # 如果子类需要继承所有父类的定义,并且不需要做任何的修改,
+ # 你可以直接使用 "pass" 关键字(并且不需要其他任何语句)
+ # 但是在这个例子中会被注释掉,以用来生成不一样的子类。
+ # pass
+
+ # 子类可以重写父类定义的字段
+ species = 'Superhuman'
+
+ # 子类会自动的继承父类的构造函数包括它的参数,但同时,子类也可以新增额外的参数或者定义,
+ # 甚至去覆盖父类的方法比如说构造函数。
+ # 这个构造函数从父类 "Human" 上继承了 "name" 参数,同时又新增了 "superpower" 和
+ # "movie" 参数:
+ def __init__(self, name, movie=False,
+ superpowers=["super strength", "bulletproofing"]):
+
+ # 新增额外类的参数
+ self.fictional = True
+ self.movie = movie
+ # 注意可变的默认值,因为默认值是共享的
+ self.superpowers = superpowers
+
+ # "super" 函数让你可以访问父类中被子类重写的方法
+ # 在这个例子中,被重写的是 __init__ 方法
+ # 这个语句是用来运行父类的构造函数:
+ super().__init__(name)
+
+ # 重写父类中的 sing 方法
+ def sing(self):
+ return 'Dun, dun, DUN!'
+
+ # 新增一个额外的方法
+ def boast(self):
+ for power in self.superpowers:
+ print("I wield the power of {pow}!".format(pow=power))
+
+
+if __name__ == '__main__':
+ sup = Superhero(name="Tick")
+
+ # 检查实例类型
+ if isinstance(sup, Human):
+ print('I am human')
+ if type(sup) is Superhero:
+ print('I am a superhero')
-# 构造一个实例
-i = Human(name="Ian")
-print(i.say("hi")) # 印出 "Ian: hi"
+ # 获取方法解析顺序 MRO,MRO 被用于 getattr() 和 super()
+ # 这个字段是动态的,并且可以被修改
+ print(Superhero.__mro__) # => (<class '__main__.Superhero'>,
+ # => <class 'human.Human'>, <class 'object'>)
-j = Human("Joel")
-print(j.say("hello")) # 印出 "Joel: hello"
+ # 调用父类的方法并且使用子类的属性
+ print(sup.get_species()) # => Superhuman
-# 调用一个类方法
-i.get_species() # => "H. sapiens"
+ # 调用被重写的方法
+ print(sup.sing()) # => Dun, dun, DUN!
-# 改一个共用的类属性
-Human.species = "H. neanderthalensis"
-i.get_species() # => "H. neanderthalensis"
-j.get_species() # => "H. neanderthalensis"
+ # 调用 Human 的方法
+ sup.say('Spoon') # => Tick: Spoon
-# 调用静态方法
-Human.grunt() # => "*grunt*"
+ # 调用 Superhero 独有的方法
+ sup.boast() # => I wield the power of super strength!
+ # => I wield the power of bulletproofing!
+
+ # 继承类的字段
+ sup.age = 31
+ print(sup.age) # => 31
+
+ # Superhero 独有的字段
+ print('Am I Oscar eligible? ' + str(sup.movie))
####################################################
-## 6. 模块
+## 6.2 多重继承
####################################################
-# 用import导入模块
-import math
-print(math.sqrt(16)) # => 4.0
+# 定义另一个类
+# bat.py
+class Bat:
-# 也可以从模块中导入个别值
-from math import ceil, floor
-print(ceil(3.7)) # => 4.0
-print(floor(3.7)) # => 3.0
+ species = 'Baty'
-# 可以导入一个模块中所有值
-# 警告:不建议这么做
-from math import *
+ def __init__(self, can_fly=True):
+ self.fly = can_fly
-# 如此缩写模块名字
-import math as m
-math.sqrt(16) == m.sqrt(16) # => True
+ # 这个类同样有 say 的方法
+ def say(self, msg):
+ msg = '... ... ...'
+ return msg
-# Python模块其实就是普通的Python文件。你可以自己写,然后导入,
-# 模块的名字就是文件的名字。
+ # 新增一个独有的方法
+ def sonar(self):
+ return '))) ... ((('
-# 你可以这样列出一个模块里所有的值
-import math
-dir(math)
+if __name__ == '__main__':
+ b = Bat()
+ print(b.say('hello'))
+ print(b.fly)
+
+# 现在我们来定义一个类来同时继承 Superhero 和 Bat
+# superhero.py
+from superhero import Superhero
+from bat import Bat
+
+# 定义 Batman 作为子类,来同时继承 SuperHero 和 Bat
+class Batman(Superhero, Bat):
+
+ def __init__(self, *args, **kwargs):
+ # 通常要继承属性,你必须调用 super:
+ # super(Batman, self).__init__(*args, **kwargs)
+ # 然而在这里我们处理的是多重继承,而 super() 只会返回 MRO 列表的下一个基础类。
+ # 因此,我们需要显式调用初始类的 __init__
+ # *args 和 **kwargs 传递参数时更加清晰整洁,而对于父类而言像是 “剥了一层洋葱”
+ Superhero.__init__(self, 'anonymous', movie=True,
+ superpowers=['Wealthy'], *args, **kwargs)
+ Bat.__init__(self, *args, can_fly=False, **kwargs)
+ # 重写了 name 字段
+ self.name = 'Sad Affleck'
+
+ def sing(self):
+ return 'nan nan nan nan nan batman!'
+
+
+if __name__ == '__main__':
+ sup = Batman()
+
+ # 获取方法解析顺序 MRO,MRO 被用于 getattr() 和 super()
+ # 这个字段是动态的,并且可以被修改
+ print(Batman.__mro__) # => (<class '__main__.Batman'>,
+ # => <class 'superhero.Superhero'>,
+ # => <class 'human.Human'>,
+ # => <class 'bat.Bat'>, <class 'object'>)
+
+ # 调用父类的方法并且使用子类的属性
+ print(sup.get_species()) # => Superhuman
+
+ # 调用被重写的类
+ print(sup.sing()) # => nan nan nan nan nan batman!
+
+ # 调用 Human 上的方法,(之所以是 Human 而不是 Bat),是因为继承顺序起了作用
+ sup.say('I agree') # => Sad Affleck: I agree
+
+ # 调用仅存在于第二个继承的父类的方法
+ print(sup.sonar()) # => ))) ... (((
+
+ # 继承类的属性
+ sup.age = 100
+ print(sup.age) # => 100
+
+ # 从第二个类上继承字段,并且其默认值被重写
+ print('Can I fly? ' + str(sup.fly)) # => Can I fly? False
####################################################
@@ -582,6 +985,10 @@ for i in double_numbers(range_):
print(i)
if i >= 30:
break
+# 你也可以把一个生成器推导直接转换为列表
+values = (-x for x in [1,2,3,4,5])
+gen_to_list = list(values)
+print(gen_to_list) # => [-1, -2, -3, -4, -5]
# 装饰器(decorators)
@@ -611,18 +1018,27 @@ print(say()) # Can you buy me a beer?
print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
```
-## 想继续学吗?
-### 线上免费材料(英文)
-* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
-* [Dive Into Python](http://www.diveintopython.net/)
-* [Ideas for Python Projects](http://pythonpracticeprojects.com)
+## 想继续学吗?
-* [The Official Docs](http://docs.python.org/3/)
-* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Module of the Week](http://pymotw.com/3/)
-* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+### 在线免费材料(英文)
+
+* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com/)
+* [Ideas for Python Projects](http://pythonpracticeprojects.com/)
+* [The Official Docs](https://docs.python.org/3/)
+* [Hitchhiker’s Guide to Python](https://docs.python-guide.org/en/latest/)
+* [Python Course](https://www.python-course.eu/)
+* [Free Interactive Python Course](http://www.kikodo.io/)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
+* [30 Python Language Features and Tricks You May Not Know About](https://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
+* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/)
+* [Python 3 Computer Science Circles](https://cscircles.cemc.uwaterloo.ca/)
+* [Dive Into Python 3](https://www.diveintopython3.net/index.html)
+* [A Crash Course in Python for Scientists](https://nbviewer.jupyter.org/gist/anonymous/5924718)
+* [Python Tutorial for Intermediates](https://pythonbasics.org/)
+* [Build a Desktop App with Python](https://pythonpyqt.com/)
### 书籍(也是英文)
diff --git a/zh-cn/qt-cn.html.markdown b/zh-cn/qt-cn.html.markdown
new file mode 100644
index 00000000..8681c85b
--- /dev/null
+++ b/zh-cn/qt-cn.html.markdown
@@ -0,0 +1,160 @@
+---
+category: tool
+tool: Qt Framework
+language: c++
+filename: learnqt-cn.cpp
+contributors:
+ - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"]
+translators:
+ - ["GengchenXU", "https://github.com/GengchenXU"]
+lang: zh-cn
+
+---
+
+**Qt** Qt是一个广为人知的框架,用于开发跨平台软件,该软件可以在各种软件和硬件平台上运行,代码几乎没有变化,同时具有本机应用程序的能力和速度。虽然**Qt**最初是用*C*++,但也有其他语言的端口: *[PyQt](https://learnxinyminutes.com/docs/pyqt/)*, *QtRuby*, *PHP-Qt*, 等等.
+
+**Qt** 非常适合使用图形用户界面 (GUI) 创建应用程序。本教程是关于如何用*C++*去实现。
+
+```c++
+/*
+ * 让我们从最经典的开始
+ */
+
+// Qt框架的所有标头均以大写字母'Q'开头
+#include <QApplication>
+#include <QLineEdit>
+
+int main(int argc, char *argv[]) {
+ // 创建一个对象来管理应用程序范围内的资源
+ QApplication app(argc, argv);
+
+ // 创建行编辑widgets并在屏幕上显示
+ QLineEdit lineEdit("Hello world!");
+ lineEdit.show();
+
+ // 启动应用程序的事件循环
+ return app.exec();
+}
+```
+
+**Qt**与 GUI 相关的部分与*widgets*及其之间的*connection*有关。
+
+[阅读更多有关widgets的信息](http://doc.qt.io/qt-5/qtwidgets-index.html)
+
+```c++
+/*
+ * 让我们创建一个标签和一个按钮。
+ * 按下按钮时应显示一个标签。
+ * Qt代码本身就可以说明问题。
+ */
+
+#include <QApplication>
+#include <QDialog>
+#include <QVBoxLayout>
+#include <QPushButton>
+#include <QLabel>
+
+int main(int argc, char *argv[]) {
+ QApplication app(argc, argv);
+
+ QDialog dialogWindow;
+ dialogWindow.show();
+
+ // 添加垂直布局
+ QVBoxLayout layout;
+ dialogWindow.setLayout(&layout);
+
+ QLabel textLabel("Thanks for pressing that button");
+ layout.addWidget(&textLabel);
+ textLabel.hide();
+
+ QPushButton button("Press me");
+ layout.addWidget(&button);
+
+ // 按下按钮时显示隐藏标签
+ QObject::connect(&button, &QPushButton::pressed,
+ &textLabel, &QLabel::show);
+
+ return app.exec();
+}
+```
+
+注意,*QObject :: connect*部分。 此方法用于将一个对象的*SIGNAL*连接到另一个对象的*SLOTS*。
+
+**Signals** 会被发出当对象发生某些事情时,例如当用户按下QPushButton对象时会发出*push*的信号。
+
+**Slots** 是可以响应于接收到的信号而执行的*action*。
+
+[阅读有关SLOTS和SIGNALS的更多信息](http://doc.qt.io/qt-5/signalsandslots.html)
+
+
+接下来,让我们了解到我们不仅可以使用标准的wigets,而且可以通过继承扩展其行为。 让我们创建一个按钮并计算其被按下的次数。 为此,我们定义了自己的类* CounterLabel *。 由于特定的Qt体系结构,必须在单独的文件中声明它。
+
+```c++
+// counterlabel.hpp
+
+#ifndef COUNTERLABEL
+#define COUNTERLABEL
+
+#include <QLabel>
+
+class CounterLabel : public QLabel {
+ Q_OBJECT // 在每个自定义wiget中必须存在的Qt定义的宏
+
+public:
+ CounterLabel() : counter(0) {
+ setText("Counter has not been increased yet"); // QLabel方法
+ }
+
+public slots:
+ // 将响应按钮按下而调用的操作
+ void increaseCounter() {
+ setText(QString("Counter value: %1").arg(QString::number(++counter)));
+ }
+
+private:
+ int counter;
+};
+
+#endif // COUNTERLABEL
+```
+
+```c++
+// main.cpp
+// 与前面的示例几乎相同
+
+#include <QApplication>
+#include <QDialog>
+#include <QVBoxLayout>
+#include <QPushButton>
+#include <QString>
+#include "counterlabel.hpp"
+
+int main(int argc, char *argv[]) {
+ QApplication app(argc, argv);
+
+ QDialog dialogWindow;
+ dialogWindow.show();
+
+ QVBoxLayout layout;
+ dialogWindow.setLayout(&layout);
+
+ CounterLabel counterLabel;
+ layout.addWidget(&counterLabel);
+
+ QPushButton button("Push me once more");
+ layout.addWidget(&button);
+ QObject::connect(&button, &QPushButton::pressed,
+ &counterLabel, &CounterLabel::increaseCounter);
+
+ return app.exec();
+}
+```
+
+当然,Qt框架比本教程介绍的部分要复杂得多,因此请仔细阅读和练习。
+
+## 进一步阅读
+- [Qt 4.8 tutorials](http://doc.qt.io/qt-4.8/tutorials.html)
+- [Qt 5 tutorials](http://doc.qt.io/qt-5/qtexamplesandtutorials.html)
+
+祝你好运,生活愉快!
diff --git a/zh-cn/raylib-cn.html.markdown b/zh-cn/raylib-cn.html.markdown
new file mode 100644
index 00000000..c88aa91e
--- /dev/null
+++ b/zh-cn/raylib-cn.html.markdown
@@ -0,0 +1,147 @@
+---
+category: tool
+tool: raylib
+lang: zh-cn
+filename: learnraylib-cn.c
+contributors:
+ - ["Nikolas Wipper", "https://notnik.cc"]
+translators:
+ - ["lzw-723", "https://github.com/lzw-723"]
+---
+
+**raylib** 是一个跨平台、易用的图形库,围绕OpenGL 1.1、2.1、3.3和OpenGL ES 2.0构建。
+虽然它是用C语言编写的,却有超过50种不同语言的绑定。本教程将使用C语言。
+更确切地说,是C99。
+
+```c
+#include <raylib.h>
+
+int main(void)
+{
+ const int screenWidth = 800;
+ const int screenHeight = 450;
+
+ // 在初始化raylib之前,可以设置标志位
+ SetConfigFlags(FLAG_MSAA_4X_HINT | FLAG_VSYNC_HINT);
+
+ // raylib并不要求我们存储任何实例结构
+ // 目前raylib一次只能处理一个窗口
+ InitWindow(screenWidth, screenHeight, "MyWindow");
+
+ // 设置我们的游戏以每秒60帧的速度运行
+ SetTargetFPS(60);
+
+ // 设置一个关闭窗口的键。
+ //可以是0,表示没有键
+ SetExitKey(KEY_DELETE);
+
+ // raylib定义了两种类型的相机。Camera3D和Camera2D
+ // Camera是Camera3D的一个类型化定义
+ Camera camera = {
+ .position = {0.0f, 0.0f, 0.0f},
+ .target = {0.0f, 0.0f, 1.0f},
+ .up = {0.0f, 1.0f, 0.0f},
+ .fovy = 70.0f,
+ .type = CAMERA_PERSPECTIVE
+ };
+
+
+ // raylib支持加载各种不同的文件格式的模型、动画、图像和声音。
+ Model myModel = LoadModel("my_model.obj");
+ Font someFont = LoadFont("some_font.ttf");
+
+ // 创建一个100x100的渲染纹理
+ RenderTexture renderTexture = LoadRenderTexture(100, 100);
+
+ // WindowShouldClose方法检查用户是否正在关闭窗口。
+ // 可能用的是快捷方式、窗口控制或之前设置的关闭窗口键
+ while (!WindowShouldClose())
+ {
+
+ // BeginDrawing方法要在任何绘图操作之前被调用。
+ BeginDrawing();
+ {
+
+ // 为背景设定某种颜色
+ ClearBackground(BLACK);
+
+ if (IsKeyDown(KEY_SPACE))
+ DrawCircle(400, 400, 30, GREEN);
+
+ // 简单地绘制文本
+ DrawText("Congrats! You created your first window!",
+ 190, // x
+ 200, // y
+ 20, // 字体大小
+ LIGHTGRAY
+ );
+
+ // 大多数函数都有几个版本
+ // 通常后缀为Ex, Pro, V
+ // 或者是Rec、Wires(仅适用于3D)、Lines(仅适用于2D)。
+ DrawTextEx(someFont,
+ "Text in another font",
+ (Vector2) {10, 10},
+ 20, // 字体大小
+ 2, // 间距
+ LIGHTGRAY);
+
+ // 绘制3D时需要,有2D的等价方法
+ BeginMode3D(camera);
+ {
+
+ DrawCube((Vector3) {0.0f, 0.0f, 3.0f},
+ 1.0f, 1.0f, 1.0f, RED);
+
+ // 绘图时的白色色调将保持原来的颜色
+ DrawModel(myModel, (Vector3) {0.0f, 0.0f, 3.0f},
+ 1.0f, // 缩放
+ WHITE);
+
+ }
+ // 结束3D模式,这样就可以再次普通绘图
+ EndMode3D();
+
+ // 开始在渲染纹理上绘图
+ BeginTextureMode(renderTexture);
+ {
+
+ // 它的行为与刚才调用的`BeginDrawing()`方法相同
+
+ ClearBackground(RAYWHITE);
+
+ BeginMode3D(camera);
+ {
+
+ DrawGrid(10, // Slices
+ 1.0f // 间距
+ );
+
+ }
+ EndMode3D();
+
+ }
+ EndTextureMode();
+
+ // 渲染有Texture2D字段的纹理
+ DrawTexture(renderTexture.texture, 40, 378, BLUE);
+
+ }
+ EndDrawing();
+ }
+
+ // 卸载已载入的对象
+ UnloadFont(someFont);
+ UnloadModel(myModel);
+
+ // 关闭窗口和OpenGL上下文
+ CloseWindow();
+
+ return 0;
+}
+
+```
+
+## 延伸阅读
+raylib有一些[不错的例子](https://www.raylib.com/examples.html)
+如果你不喜欢C语言你也可以看看[raylib的其他语言绑定](https://github.com/raysan5/raylib/blob/master/BINDINGS.md)
diff --git a/zh-cn/red-cn.html.markdown b/zh-cn/red-cn.html.markdown
index 85812990..7fee007e 100644
--- a/zh-cn/red-cn.html.markdown
+++ b/zh-cn/red-cn.html.markdown
@@ -150,11 +150,11 @@ msg: either a > 0 [
]
print ["a 是 " msg lf]
-; util
+; until
; 循环执行一段代码块,直到满足给定的条件为止。
-; util 没有返回值,所以它不能用在表示式中。
+; UNTIL 在最后一次循环执行完最后一个表达式后,总是返回真值 'true'。
c: 5
-util [
+until [
prin "o"
c: c - 1
c = 0 ; 终止循环的条件
@@ -193,15 +193,15 @@ print twice b ; 输出 6
## 更进一步
-Red 相关的源码信息在 [Red 语言主页](http://www.red-lang.org)。
+Red 相关的源码信息在 [Red 语言主页](https://www.red-lang.org)。
源代码的 [github 库](https://github.com/red/red)。
-Red/System 特性在 [这里](http://static.red-lang.org/red-system-specs-light.html)。
+Red/System 特性在 [这里](https://static.red-lang.org/red-system-specs-light.html)。
想要了解更多关于 Rebol 和 Red 的信息,加入 [Gitter 聊天室](https://gitter.im/red/red)。如果你无法加入,也可以给我们发[邮件](mailto:red-langNO_SPAM@googlegroups.com)。
-也可以在 [Stack Overflow](stackoverflow.com/questions/tagged/red) 上查阅、提交问题。
+也可以在 [Stack Overflow](https://stackoverflow.com/questions/tagged/red) 上查阅、提交问题。
也许你现在就要试一试 Red ?可以在线尝试 [try Rebol and Red site](http://tryrebol.esperconsultancy.nl)。
diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown
index 9918c022..63adab64 100644
--- a/zh-cn/ruby-cn.html.markdown
+++ b/zh-cn/ruby-cn.html.markdown
@@ -657,4 +657,4 @@ Something.new.qux # => 'qux'
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
-- [Try Ruby](http://tryruby.org) - Learn the basic of Ruby programming language, interactive in the browser.
+- [Try Ruby](https://try.ruby-lang.org/) - Learn the basic of Ruby programming language, interactive in the browser.
diff --git a/zh-cn/rust-cn.html.markdown b/zh-cn/rust-cn.html.markdown
index 5d3fc693..b77c9c38 100644
--- a/zh-cn/rust-cn.html.markdown
+++ b/zh-cn/rust-cn.html.markdown
@@ -211,7 +211,7 @@ fn main() {
// `for` 循环
let array = [1, 2, 3];
- for i in array.iter() {
+ for i in array {
println!("{}", i);
}
diff --git a/zh-cn/set-theory-cn.html.markdown b/zh-cn/set-theory-cn.html.markdown
new file mode 100644
index 00000000..13ba2c80
--- /dev/null
+++ b/zh-cn/set-theory-cn.html.markdown
@@ -0,0 +1,138 @@
+---
+category: Algorithms & Data Structures
+name: Set theory
+contributors:
+translators:
+ - ["Tianchen Xu", "https://github.com/lo0b0o"]
+lang: zh-cn
+---
+集合论是数学的一个分支,研究集合、它们的运算和它们的性质。
+
+* 集合由不重复的项组成。
+
+## 基本符号
+
+### 运算符
+* 并运算符,`∪`,表示“或”;
+* 交运算符,`∩`,表示“且”;
+* 差运算符,`\`,表示“不包括”;
+* 补运算符,`'`,表示补集;
+* 叉积运算符,`×`,表示笛卡尔积。
+
+### 限定词
+* 冒号限定词,`:`,表示“使得”;
+* 从属限定词,`∈`,表示“属于”;
+* 子集限定词,`⊆`,表示“是……的子集”;
+* 真子集限定词,`⊂`,表示“是……的真子集”。
+
+### 重要的集合
+* `∅`,空集,即不包含任何元素的集合;
+* `ℕ`,自然数集;
+* `ℤ`,整数集;
+* `ℚ`,有理数集;
+* `ℝ`,实数集。
+
+关于以上集合,有如下几点需要注意:
+1. 空集是其本身的子集(并且也是任何其他集合的子集),即便空集不包含任何项;
+2. 数学家们对于零是否为自然数的看法通常并不统一,教科书一般会明确说明作者是否认为零是自然数。
+
+### 基数
+
+集合的基数,或者说大小,由该集合中的项目数量决定。基数运算符为 `|...|`。
+
+例如,若 `S = { 1, 2, 4 }`,则 `|S| = 3`。
+
+### 空集
+
+* 可以在集合符号中使用不成立的条件来构造空集,例如,`∅ = { x : x ≠ x }`,或 `∅ = { x : x ∈ N, x < 0 }`;
+* 空集总是唯一的(即,有且只有一个空集);
+* 空集是所有集合的子集;
+* 空集的基数为 0,即 `|∅| = 0`。
+
+## 集合的表示
+
+### 集合的逐项构造
+
+集合可以通过包含其全部项的列表逐项生成。例如,`S = { a, b, c, d }`。
+
+只要构成集合的项清楚,长列表可以用省略号缩短。例如,`E = { 2, 4, 6, 8, ... }` 显然为所有偶数构成的集合,它包含无穷多项,虽然我们只显式写出了其中四项。
+
+### 集合构造器
+
+集合构造器符号是构造集合的一种更具描述性的方式。它依赖于一个主语和一个谓词,使得 `S = { 主语 : 谓词 }`。 例如,
+
+```
+A = { x : x 是元音字母 } = { a, e, i, o, u, y}
+B = { x : x ∈ N, x < 10 } = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
+C = { x : x = 2k, k ∈ N } = { 0, 2, 4, 6, 8, ... }
+```
+
+有时,谓词可能会 "漏 "到主语中,例如,
+
+```
+D = { 2x : x ∈ N } = { 0, 2, 4, 6, 8, ... }
+```
+
+## 关系
+
+### 从属关系
+
+* 如果值 `a` 包含在集合 `A` 中,那么我们说 `a` 属于 `A`,并用符号表示为 `a ∈ A`。
+* 如果值 `a` 不包含于集合 `A` 中,那么我们说 `a` 不属于 `A`,并用符号表示为 `a ∉ A`。
+
+### 相等关系
+
+* 如果两个集合包括相同的项,那么我们说这两个集合相等,例如,`A = B`。
+* 集合的相等关系于顺序无关,例如 `{ 1, 2, 3, 4 } = { 2, 3, 1, 4 }`。
+* 集合中的元素不能重复,例如 `{ 1, 2, 2, 3, 4, 3, 4, 2 } = { 1, 2, 3, 4 }`。
+* 集合 `A` 与 `B` 相等当且仅当 `A ⊆ B` 且 `B ⊆ A`。
+
+## 特殊集合
+
+### 幂集
+
+* 令 `A` 为任意集合。幂集指的是包括了 `A` 的所有子集的集合,记作 `P(A)`。如果集合 `A` 由 `2n` 个元素组成,那么 `P(A)` 中有 `2^n` 个元素。
+
+```
+P(A) = { x : x ⊆ A }
+```
+
+## 两个集合的运算
+### 并
+
+给定集合 `A` 和 `B`,两个集合的并由出现在 `A` 或 `B` 中的项构成,记作 `A ∪ B`。
+
+```
+A ∪ B = { x : x ∈ A ∪ x ∈ B }
+```
+
+### 交
+
+给定集合 `A` 和 `B`,两个集合的交由出现在 `A` 和 `B` 中的项构成,记作 `A ∩ B`。
+
+```
+A ∩ B = { x : x ∈ A, x ∈ B }
+```
+
+### 差
+给定集合 `A` 和 `B`,`A` 对于 `B` 的集合差指的是属于 `A` 但不属于 `B` 的每一项。
+
+```
+A \ B = { x : x ∈ A, x ∉ B }
+```
+
+### 对称差
+给定集合 `A` 和 `B`,对称差指的是属于 `A` 或 `B` 但不属于它们交集的所有项。
+
+```
+A △ B = { x : ((x ∈ A) ∩ (x ∉ B)) ∪ ((x ∈ B) ∩ (x ∉ A)) }
+
+A △ B = (A \ B) ∪ (B \ A)
+```
+
+### 笛卡尔积
+给定集合 `A` 和 `B`,`A` 和 `B` 的笛卡尔积由 `A` 和 `B` 的项的所有组合构成。
+
+```
+A × B = { (x, y) | x ∈ A, y ∈ B }
+```
diff --git a/zh-cn/solidity-cn.html.markdown b/zh-cn/solidity-cn.html.markdown
index ec684997..12a532bc 100644
--- a/zh-cn/solidity-cn.html.markdown
+++ b/zh-cn/solidity-cn.html.markdown
@@ -213,7 +213,7 @@ names.length; // 获得数组长度
names.length = 1; // 可以设定长度(仅针对 storage 中的动态数组)
// 多维数组
-uint x[][5]; // 5个动态数组元素的数组(和多数语言的顺序相反)
+uint[][5] x; // 5个动态数组元素的数组(和多数语言的顺序相反)
// 字典类型 (任一类型到其他类型的映射)
mapping (string => uint) public balances;
diff --git a/zh-cn/sql.html.markdown b/zh-cn/sql-cn.html.markdown
index 9d430bd1..9d430bd1 100644
--- a/zh-cn/sql.html.markdown
+++ b/zh-cn/sql-cn.html.markdown
diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown
index 18bc52ed..c56a0d33 100644
--- a/zh-cn/swift-cn.html.markdown
+++ b/zh-cn/swift-cn.html.markdown
@@ -10,7 +10,7 @@ translators:
lang: zh-cn
---
-Swift 是 Apple 开发的用于 iOS 和 OS X 开发的编程语言。Swift 于2014年 Apple WWDC (全球开发者大会)中被引入,用以与 Objective-C 共存,同时对错误代码更具弹性。Swift 由 Xcode 6 beta 中包含的 LLVM 编译器编译。
+Swift 是 Apple 开发的用于 iOS 和 macOS 开发的编程语言。Swift 于2014年 Apple WWDC (全球开发者大会)中被引入,用以与 Objective-C 共存,同时对错误代码更具弹性。Swift 由 Xcode 6 beta 中包含的 LLVM 编译器编译。
Swift 的官方语言教程 [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) 可以从 iBooks 免费下载.
diff --git a/zh-cn/wolfram-cn.html.markdown b/zh-cn/wolfram-cn.html.markdown
new file mode 100644
index 00000000..9d6ef54f
--- /dev/null
+++ b/zh-cn/wolfram-cn.html.markdown
@@ -0,0 +1,140 @@
+---
+language: wolfram
+contributors:
+ - ["hyphz", "http://github.com/hyphz/"]
+translators:
+ - ["wuyudi", "http://github.com/wuyudi/"]
+filename: learnwolfram-cn.nb
+lang: zh-cn
+---
+
+Wolfram 语言是最初在 Mathematica 中使用的底层语言,但现在可用于多种场合。
+
+Wolfram 语言有几个界面。
+
+- Raspberry Pi 上的命令行内核界面(就叫 _The Wolfram Language_),它是交互式运行的,不能产生图形输入。
+- _Mathematica_ 是一个丰富的文本/数学编辑器,内置交互式的 Wolfram: 在 "代码单元 "上按 shift+Return 键可以创建一个输出单元,输出结果,这不是动态的。
+- _Wolfram Workbench_,这是 Eclipse 与 Wolfram 语言后端的界面。
+
+本例中的代码可以在任何界面中输入,并使用 Wolfram Workbench 进行编辑。直接加载到 Mathematica 中可能会很不方便,因为该文件不包含单元格格式化信息(这将使该文件作为文本阅读时变得一团糟)--它可以被查看/编辑,但可能需要一些设置。
+
+```mma
+(* 这是一个注释 *)
+
+(* 在Mathematica中,您可以创建一个文本单元格,用排版好的文本和图像来注释您的代码,而不是使用这些注释 *)
+
+(* 输入一个表达式返回结果 *)
+2*2 (* 4 *)
+5+8 (* 13 *)
+
+(* 调用函数 *)
+(* 注意,函数名(和其他所有东西)是区分大小写的 *)
+Sin[Pi/2] (* 1 *)
+
+(* 带有一个参数的函数调用的替代语法 *)
+Sin@(Pi/2) (* 1 *)
+(Pi/2) // Sin (* 1 *)
+
+(* WL 中的每一种语法都有一些等价的函数调用,即万物皆函数 *)
+Times[2, 2] (* 4 *)
+Plus[5, 8] (* 13 *)
+
+(* 第一次使用一个变量定义它,并使其成为全局变量 *)
+x = 5 (* 5 *)
+x == 5 (* 返回真,C-style 的赋值和相等测试 *)
+x (* 5 *)
+x = x + 5 (* 10 *)
+x (* 10 *)
+Set[x, 20] (* 当我说万物皆函数时 我是认真的 *)
+x (* 20 *)
+
+(* 因为WL是基于计算机代数系统的, *)
+(* 可以使用未定义的变量,它们只是阻碍了计算 *)
+cow + 5 (* 5 + cow, cow 是未定义的,所以无法进一步计算 *)
+cow + 5 + 10 (* 15 + cow, 它将尽力计算 *)
+% (* 15 + cow, % 获取最后一次返回的内容 *)
+% - cow (* 15, 未定义的变量cow被消去 *)
+moo = cow + 5 (* 小心,moo 现在是一个表达式,不是一个数字! *)
+
+(* 定义一个函数 *)
+Double[x_] := x * 2 (* 注意 := 防止对RHS进行即时计算。
+ 而 x 后面的 _ 表示没有模式匹配的约束条件*)
+Double[10] (* 20 *)
+Double[Sin[Pi/2]] (* 2 *)
+Double @ Sin @ (Pi/2) (* 2, @-syntax 避免了闭括号的队列 *)
+(Pi/2) // Sin // Double(* 2, //-syntax 按执行顺序列举了函数 *)
+
+(* 对于命令式编程,使用 ; 来分隔语句。 *)
+(* 丢弃 LHS 的任何输出并运行 RHS *)
+MyFirst[] := (Print@"Hello"; Print@"World") (* 请注意,外侧的小括号是关键
+ ;的优先级低于:= *)
+MyFirst[] (* 你好,世界 *)
+
+(* C-Style 的 For 循环,注:在 Mathematica 中使用 For 循环是低效的 *)
+PrintTo[x_] := For[y=0, y<x, y++, (Print[y])] (* 开始,测试,自增,循环体 *)
+PrintTo[5] (* 0 1 2 3 4 *)
+
+(* While 循环 *)
+x = 0; While[x < 2, (Print@x; x++)] (* 带测试和程序体的 while 循环 *)
+
+(* If 和 条件 *)
+x = 8; If[x==8, Print@"Yes", Print@"No"] (* Condition, true case, else case *)
+Switch[x, 2, Print@"Two", 8, Print@"Yes"] (* 值匹配风格切换 *)
+Which[x==2, Print@"No", x==8, Print@"Yes"] (* Elif风格切换 *)
+
+(* 除参数外的变量默认为全局变量,即使在函数内部也是如此 *)
+y = 10 (* 10, 全局变量 y *)
+PrintTo[5] (* 0 1 2 3 4 *)
+y (* 5, 全局的 y 被 PrintTo 内的循环计数器所占用 *)
+x = 20 (* 20, 全局变量 x *)
+PrintTo[5] (* 0 1 2 3 4 *)
+x (* 20, PrintTo 中的 x 是一个参数,并自动局部化 *)
+
+(* 局部变量使用 Module 元函数声明 *)
+(* 带本地变量的版本 *)
+BetterPrintTo[x_] := Module[{y}, (For[y=0, y<x, y++, (Print@y)])]
+y = 20 (* 全局变量 y *)
+BetterPrintTo[5] (* 0 1 2 3 4 *)
+y (* 20, 那更好 *)
+
+(* 实际上,模块允许我们声明任何我们喜欢的作用域 *)
+Module[{count}, count=0; (* 声明这个变量count的作用域 *)
+ (IncCount[] := ++count); (* 这些函数都在该作用域内 *)
+ (DecCount[] := --count)]
+count (* count - 全局变量 count 未定义 *)
+IncCount[] (* 1, 使用作用域内的counter变量 *)
+IncCount[] (* 2, incCount 升级了它 *)
+DecCount[] (* 1, decCount 也是 *)
+count (* count - 这个名字依旧不是全局变量 *)
+
+(* Lists *)
+myList = {1, 2, 3, 4} (* {1, 2, 3, 4} *)
+myList[[1]] (* 1 - 注意列表索引从 1 开始,而不是从 0 开始。 *)
+Map[Double, myList] (* {2, 4, 6, 8} - 函数式列表的 map 函数 *)
+Double /@ myList (* {2, 4, 6, 8} - 以上的缩略语法 *)
+Scan[Print, myList] (* 1 2 3 4 - 命令式循环 *)
+Fold[Plus, 0, myList] (* 10 (0+1+2+3+4) *)
+FoldList[Plus, 0, myList] (* {0, 1, 3, 6, 10} - 存值的 Fold *)
+Append[myList, 5] (* {1, 2, 3, 4, 5} - 注意 myList 没有更新 *)
+Prepend[myList, 5] (* {5, 1, 2, 3, 4} - 如果想让 myList 更新,就加上 "myList = " *)
+Join[myList, {3, 4}] (* {1, 2, 3, 4, 3, 4} *)
+myList[[2]] = 5 (* {1, 5, 3, 4} - 这确实更新了myList *)
+
+(* 关联,又称字典/哈希值 *)
+myHash = <|"Green" -> 2, "Red" -> 1|> (* 创建一个关联 *)
+myHash[["Green"]] (* 2, 使用 *)
+myHash[["Green"]] := 5 (* 5, 更新 *)
+myHash[["Puce"]] := 3.5 (* 3.5, 扩展 *)
+KeyDropFrom[myHash, "Green"] (* 抹去绿色的键 *)
+Keys[myHash] (* {Red, Puce} *)
+Values[myHash] (* {1, 3.5} *)
+
+(* 做 Wolfram 的演示时 你不能不展示这个 *)
+Manipulate[y^2, {y, 0, 20}] (* 返回一个反应式的用户界面,显示y^2
+ 并允许通过滑块在 0-20 之间调整y。
+ 只适用于图形前端 *)
+```
+
+## 想多来点?
+
+- [Wolfram Language Documentation Center](http://reference.wolfram.com/language/)
diff --git a/zh-tw/bash-tw.html.markdown b/zh-tw/bash-tw.html.markdown
index 78b39f2d..5136d513 100644
--- a/zh-tw/bash-tw.html.markdown
+++ b/zh-tw/bash-tw.html.markdown
@@ -23,7 +23,7 @@ filename: LearnBash-tw.sh
lang: zh-tw
---
-Bash 是一個爲 GNU 計劃編寫的 Unix shell,是 Linux 和 Mac OS X 下預設的 shell。
+Bash 是一個爲 GNU 計劃編寫的 Unix shell,是 Linux 和 macOS 下預設的 shell。
以下大多數例子可以作爲腳本的一部分運行,也可直接在 shell 下互動執行。
[更多資訊](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/zh-tw/perl-tw.html.markdown b/zh-tw/perl-tw.html.markdown
new file mode 100644
index 00000000..55876e2a
--- /dev/null
+++ b/zh-tw/perl-tw.html.markdown
@@ -0,0 +1,328 @@
+---
+name: perl
+category: language
+language: perl
+filename: learnperl-tw.pl
+contributors:
+ - ["Korjavin Ivan", "http://github.com/korjavin"]
+ - ["Dan Book", "http://github.com/Grinnz"]
+translators:
+ - ["Kang-min Liu", "https://gugod.org"]
+ - ["Shih-Kai Chiu", "https://twitter.com/zard1989"]
+lang: zh-tw
+---
+
+Perl 5 是一款強大且功能豐富的程式語言,已經持續發展超過 25 年。
+
+從大型主機到行動裝置,Perl 5 能在上百種平台執行,適合快速打造產品原型,也適合大
+型專案開發。
+
+```perl
+# 註解列皆以井字號為開頭
+
+#### 嚴謹度
+
+use strict;
+use warnings;
+
+# 所有的 perl 程式檔案都應當包含此兩列程式碼。在如變數名稱有拼寫錯誤之時,
+# strict 能使編譯過程失敗。而對於像是將未定義值接到字串中等等易犯之錯誤,
+# warnings 則能提供適當的警告訊息。
+
+#### Perl 變數與其型別
+
+# 變數的開頭皆為一印記(sigil),是為一符號,用以標示其型別。
+# 變數名稱唯有以字母或底線開頭,後接字母、數字、底線若干,方為有效。
+
+### 在 Perl 語言中,主要的變數型別有三種:$純量、@陣列、%雜湊。
+
+## 純量
+# 一個純量變數,只能裝一個值:
+my $animal = "camel";
+my $answer = 42;
+my $display = "You have $answer ${animal}s.\n";
+
+# 純量值可為字串、整數、浮點數。Perl 會自動地在需要之時進行轉換。
+
+# 以單引號括住的字串內容與其字面之值完全相同。而以雙引號括住的字串,
+# 其中則能內插變數與像是這種表示換列字符 "\n" 的控制碼。
+
+## 陣列
+# 一個陣列,可以裝下很多值:
+my @animals = ("camel", "llama", "owl");
+my @numbers = (23, 42, 69);
+my @mixed = ("camel", 42, 1.23);
+
+# 陣列元素的存取,需要角括號。前方的印記為 $ 符號,表示只取一個值。
+my $second = $animals[1];
+
+# 欲知陣列之大小,在純量語境之下使用陣列便可。例如,將陣列裝到一個純量變數中。
+# 又或者是使用 "scalar" 算符。
+
+my $num_animals = @animals;
+print "Number of numbers: ", scalar(@numbers), "\n";
+
+# 陣列也能夠被安插在雙引號字串之內。各內容元素間隔,預設是一個空白字符。
+
+print "We have these numbers: @numbers\n";
+
+# 雙引號字串中,若有像電子郵件地址的部分,會被視為是在內插某個陣列的內容物。
+# 請稍加留意。
+
+my @example = ('secret', 'array');
+my $oops_email = "foo@example.com"; # 'foosecret array.com'
+my $ok_email = 'foo@example.com';
+
+## 雜湊
+# 一個雜湊,能裝下許多對的鍵與值:
+
+my %fruit_color = ("apple", "red", "banana", "yellow");
+
+# 善用空白與 "=>" 算符,就能將其排得得好看一些:
+
+my %fruit_color = (
+ apple => "red",
+ banana => "yellow",
+);
+
+# 雜湊元素的存取,需要大括號。前方的印記仍為 $ 符號,表示只取一個值。
+my $color = $fruit_color{apple};
+
+# 以 "keys" 與 "values" 兩個函數,則可一次取得雜湊中的所有鍵、所有值。
+my @fruits = keys %fruit_color;
+my @colors = values %fruit_color;
+
+# 關於純量、陣列、雜湊,在 perldata 文件之中,有更完整的描述。
+# (perldoc perldata)
+
+#### 參照
+
+# 以參照能組出結構更為複雜的資料型別。
+# 像是在陣列中放入雜湊、或是在雜湊裡放入陣列的雜湊。
+
+my $array_ref = \@array;
+my $hash_ref = \%hash;
+my @array_of_arrays = (\@array1, \@array2, \@array3);
+
+# 匿名陣列與匿名雜湊也是參照
+
+my $fruits = ["apple", "banana"];
+my $colors = {apple => "red", banana => "yellow"};
+
+# 在參照之前補上適當的印記,是為解參照。
+
+my @fruits_array = @$fruits;
+my %colors_hash = %$colors;
+
+# 以箭頭算符,便可在解參照同時存取其中一值。
+
+my $first = $array_ref->[0];
+my $value = $hash_ref->{banana};
+
+# 欲深入了解參照,詳見 perlreftut 與 perlref 兩份文件
+
+#### 條件結構與迴圈結構
+
+# 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) {
+ ...
+}
+
+my $max = 5;
+# 以 for 迴圈,$i 為迭代變數
+for my $i (0 .. $max) {
+ print "index is $i";
+}
+
+for my $element (@elements) {
+ print $element;
+}
+
+map {print} @elements;
+
+# 迭代變數為 $_
+for (@elements) {
+ print;
+}
+
+# 對雜湊進行迭代(for 與 foreach 完全相同)
+
+foreach my $key (keys %hash) {
+ print $key, ': ', $hash{$key}, "\n";
+}
+
+# 又是「很 Perl 的」倒裝句法
+print for @elements;
+
+# 對一雜湊參照之中迭代,逐一走過其鍵與值
+print $hash_ref->{$_} for keys %$hash_ref;
+
+#### 正規表示式
+
+# Perl 中,對正規表示式的支援既廣亦深,在 perlrequick、perlretut 等各處文件中
+# 都有更加完整的文件。不過,簡而言之:
+
+# 簡易比對
+if (/foo/) { ... } # 若 $_ 內含 "foo" 則為真
+if ($x =~ /foo/) { ... } # 若 $x 內含 "foo" 則為真
+
+# 簡易取代
+$x =~ s/foo/bar/; # 將 $x 中第一個出現的 foo 換為 bar
+$x =~ s/foo/bar/g; # 將 $x 中所有出現的 foo 換為 bar
+
+#### 檔案與輸出入
+
+# 以 "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>;
+
+# 以 "print" 函式,則可對檔案代號進行輸出。
+
+print $out @lines;
+print $log $msg, "\n";
+
+#### 函式之撰寫
+
+# 撰寫函式很是容易:
+
+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 程式碼來利用。
+# 為了讓 perl 能找至,通常模組之副檔名 .pm 。
+
+package MyModule;
+use strict;
+use warnings;
+
+sub trim {
+ my $string = shift;
+ $string =~ s/^\s+//;
+ $string =~ s/\s+$//;
+ return $string;
+}
+
+1;
+
+# 自他處利用:
+
+use MyModule;
+MyModule::trim($string);
+
+# Exporter 模組能將函式出口,好讓它們能被這樣利用:
+
+use MyModule 'trim';
+trim($string);
+
+# 有許多 Perl 模組能從 CPAN (https://www.cpan.org) 下載下來,各式各樣的機能讓你
+# 能免於重新發明輪子。不少高人氣模組,如 Exporter,則是與 Perl 一同釋出、散佈。
+# 更多關於 Perl 模組的細節,詳見 perlmod 文件。
+
+#### 物件
+
+# Perl 中的物件,只是個參照,但同時又知道自己屬於哪個類別(package),於是對自身
+# 調用方法(函式)時方知去何處尋找函式本體。在建構子(通常是 "new")中,都是以
+# "bless" 函式來標記參照與其類別。只不過,若你使用像 Moose 或 Moo 模組的話,這些
+# 都不必自己來(總之請繼續往下讀)。
+
+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;
+
+# 以箭頭運算符,便可對某類別或某物件呼叫某方法:
+use MyCounter;
+my $counter = MyCounter->new;
+print $counter->count, "\n"; # 0
+$counter->increment;
+print $counter->count, "\n"; # 1
+
+# CPAN 上的 Moose 與 Moo 模組能助你撰寫類別本體。它們提供了建構子,與簡單易懂的
+# 語法能來宣告屬性。前述的類別改寫之後,如下:
+
+package MyCounter;
+use Moo; # 同時也啟用 strict 與 warnings
+
+has 'count' => (is => 'rwp', default => 0, init_arg => undef);
+
+sub increment {
+ my $self = shift;
+ $self->_set_count($self->count + 1);
+}
+
+1;
+
+# 物件導向程式設計於 perlootut 文件中有詳盡的說明。
+# 此外,perlobj 文件中更涵蓋了底層實做之細節。
+```
+
+#### 常見問答集
+
+perlfaq 是問與答,涵蓋許多常見問題和解法,常常對該用哪些 CPAN 模組有很好的建議。
+
+#### 延伸閱讀
+
+ - [perl-tutorial](http://perl-tutorial.org/)
+ - [Learn Perl](https://www.perl.org/learn.html)
+ - [perldoc](http://perldoc.perl.org/)
+ - 內建函式 : `perldoc perlintro`