summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--.github/CODEOWNERS5
-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--bash.html.markdown27
-rw-r--r--c++.html.markdown45
-rw-r--r--c.html.markdown48
-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--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/swift-de.html.markdown2
-rw-r--r--docker.html.markdown13
-rw-r--r--el-gr/bash-gr.html.markdown2
-rw-r--r--el-gr/rust-gr.html.markdown339
-rw-r--r--es-es/bash-es.html.markdown2
-rw-r--r--es-es/matlab-es.html.markdown2
-rw-r--r--es-es/objective-c-es.html.markdown2
-rw-r--r--es-es/swift-es.html.markdown2
-rw-r--r--es-es/typescript-es.html.markdown2
-rw-r--r--fr-fr/asymptotic-notation-fr.html.markdown14
-rw-r--r--fr-fr/bash-fr.html.markdown2
-rw-r--r--fr-fr/c++-fr.html.markdown6
-rw-r--r--fr-fr/java-fr.html.markdown64
-rw-r--r--fr-fr/markdown-fr.html.markdown34
-rw-r--r--fr-fr/objective-c-fr.html.markdown4
-rw-r--r--fr-fr/set-theory-fr.html.markdown134
-rw-r--r--fr-fr/typescript-fr.html.markdown2
-rw-r--r--go.html.markdown2
-rw-r--r--haskell.html.markdown2
-rw-r--r--hd-hd/json-hd.html.markdown86
-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--ja-jp/vim-jp.html.markdown275
-rw-r--r--jquery.html.markdown2
-rw-r--r--json.html.markdown5
-rw-r--r--jsonnet.html.markdown2
-rw-r--r--julia.html.markdown65
-rw-r--r--kotlin.html.markdown4
-rw-r--r--latex.html.markdown43
-rw-r--r--lua.html.markdown2
-rw-r--r--matlab.html.markdown2
-rw-r--r--ms-my/bash-my.html.markdown2
-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--powershell.html.markdown974
-rw-r--r--pt-br/awk-pt.html.markdown4
-rw-r--r--pt-br/bash-pt.html.markdown10
-rw-r--r--pt-br/css-pt.html.markdown10
-rw-r--r--pt-br/elixir-pt.html.markdown2
-rw-r--r--pt-br/fsharp-pt.html.markdown639
-rw-r--r--pt-br/groovy-pt.html.markdown14
-rw-r--r--pt-br/julia-pt.html.markdown2
-rw-r--r--pt-br/kotlin-pt.html.markdown4
-rw-r--r--pt-br/lua-pt.html.markdown423
-rw-r--r--pt-br/matlab-pt.html.markdown2
-rw-r--r--pt-br/self-pt.html.markdown2
-rw-r--r--pt-br/swift-pt.html.markdown2
-rw-r--r--pt-br/typescript-pt.html.markdown16
-rw-r--r--pt-pt/swift-pt.html.markdown2
-rw-r--r--purescript.html.markdown117
-rw-r--r--python.html.markdown41
-rw-r--r--r.html.markdown14
-rw-r--r--ro-ro/bash-ro.html.markdown2
-rw-r--r--rst.html.markdown12
-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/nim-ru.html.markdown254
-rw-r--r--ru-ru/objective-c-ru.html.markdown2
-rw-r--r--ru-ru/python-ru.html.markdown963
-rw-r--r--ru-ru/swift-ru.html.markdown2
-rw-r--r--set-theory.html.markdown8
-rw-r--r--sk-sk/bash-sk.html.markdown2
-rw-r--r--smalltalk.html.markdown4
-rw-r--r--solidity.html.markdown138
-rw-r--r--sql.html.markdown2
-rw-r--r--sv-se/nix-sv.html.markdown5
-rw-r--r--swift.html.markdown13
-rw-r--r--tcl.html.markdown2
-rw-r--r--tr-tr/jquery-tr.html.markdown338
-rw-r--r--tr-tr/ruby-tr.html.markdown1598
-rw-r--r--vi-vn/objective-c-vi.html.markdown2
-rw-r--r--xml.html.markdown13
-rw-r--r--yaml.html.markdown6
-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/go-cn.html.markdown2
-rw-r--r--zh-cn/haskell-cn.html.markdown2
-rw-r--r--zh-cn/java-cn.html.markdown4
-rw-r--r--zh-cn/mips-cn.html.markdown334
-rw-r--r--zh-cn/perl-cn.html.markdown8
-rw-r--r--zh-cn/qt-cn.html.markdown160
-rw-r--r--zh-cn/set-theory-cn.html.markdown138
-rw-r--r--zh-cn/swift-cn.html.markdown2
-rw-r--r--zh-tw/bash-tw.html.markdown2
-rw-r--r--zh-tw/perl-tw.html.markdown328
110 files changed, 7055 insertions, 1030 deletions
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
new file mode 100644
index 00000000..7bc9d01b
--- /dev/null
+++ b/.github/CODEOWNERS
@@ -0,0 +1,5 @@
+/fr-fr/ @vendethiel
+/ru-ru/ @Menelion
+/uk-ua/ @Menelion
+/zh-cn/ @geoffliu
+/zh-tw/ @geoffliu
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/bash.html.markdown b/bash.html.markdown
index 7ca4285b..11ce4e74 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -27,12 +27,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:
@@ -198,7 +198,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'
@@ -325,6 +325,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 +335,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 +380,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
@@ -431,6 +441,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 +460,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 +469,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 59aad210..6e94e03e 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
@@ -199,7 +199,7 @@ int main()
cin >> myInt;
// cout can also be formatted
- cout << "Your favorite number is " << myInt << "\n";
+ cout << "Your favorite number is " << myInt << '\n';
// prints "Your favorite number is <myInt>"
cerr << "Used for error messages";
@@ -461,7 +461,7 @@ void Dog::print() const
Dog::~Dog()
{
- std::cout << "Goodbye " << name << "\n";
+ std::cout << "Goodbye " << name << '\n';
}
int main() {
@@ -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
@@ -504,7 +504,7 @@ void OwnedDog::setOwner(const std::string& dogsOwner)
void OwnedDog::print() const
{
Dog::print(); // Call the print function in the base Dog class
- std::cout << "Dog is owned by " << owner << "\n";
+ std::cout << "Dog is owned by " << owner << '\n';
// Prints "Dog is <name> and weights <weight>"
// "Dog is owned by <owner>"
}
@@ -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>
@@ -915,7 +915,7 @@ ST.erase(20); // Will erase element with value 20
// Set ST: 10 30
// To iterate through Set we use iterators
set<int>::iterator it;
-for(it=ST.begin();it<ST.end();it++) {
+for(it=ST.begin();it!=ST.end();it++) {
cout << *it << endl;
}
// Output:
@@ -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 << '\n';
+ std::cout << it->first << "->" << it->second << std::cout;
// 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.
@@ -1117,33 +1118,33 @@ const int maxL = 15;
auto second = make_tuple(maxN, maxL);
// Printing elements of 'first' tuple
-cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A
+cout << get<0>(first) << " " << get<1>(first) << '\n'; //prints : 10 A
// Printing elements of 'second' tuple
-cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 15
+cout << get<0>(second) << " " << get<1>(second) << '\n'; // prints: 1000000000 15
// Unpacking tuple into variables
int first_int;
char first_char;
tie(first_int, first_char) = first;
-cout << first_int << " " << first_char << "\n"; // prints : 10 A
+cout << first_int << " " << first_char << '\n'; // prints : 10 A
// We can also create tuple like this.
tuple<int, char, double> third(11, 'A', 3.14141);
// tuple_size returns number of elements in a tuple (as a constexpr)
-cout << tuple_size<decltype(third)>::value << "\n"; // prints: 3
+cout << tuple_size<decltype(third)>::value << '\n'; // prints: 3
// tuple_cat concatenates the elements of all the tuples in the same order.
auto concatenated_tuple = tuple_cat(first, second, third);
// concatenated_tuple becomes = (10, 'A', 1e9, 15, 11, 'A', 3.14141)
-cout << get<0>(concatenated_tuple) << "\n"; // prints: 10
-cout << get<3>(concatenated_tuple) << "\n"; // prints: 15
-cout << get<5>(concatenated_tuple) << "\n"; // prints: 'A'
+cout << get<0>(concatenated_tuple) << '\n'; // prints: 10
+cout << get<3>(concatenated_tuple) << '\n'; // prints: 15
+cout << get<5>(concatenated_tuple) << '\n'; // prints: 'A'
///////////////////////////////////
diff --git a/c.html.markdown b/c.html.markdown
index a57be1dc..ff396d21 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -224,10 +224,18 @@ 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
+ // for instance it is not giving mathematically correct results
+ (0.1 + 0.1 + 0.1) != 0.3; // => 1 (true)
+ // and it is NOT associative
+ 1 + (1e123 - 1e123) != (1 + 1e123) - 1e123; // => 1 (true)
+ // this notation is scientific notations for numbers: 1e123 = 1*10^123
- // Modulo is there as well
- 11 % 3; // => 2
+ // 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.
@@ -236,12 +244,12 @@ int main (int argc, char** argv)
// 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 +357,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
*/
///////////////////////////////////////
@@ -741,11 +754,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 +797,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. */
@@ -823,7 +837,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 +847,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 7d94d8c9..1b33f9cc 100644
--- a/cobol.html.markdown
+++ b/cobol.html.markdown
@@ -29,7 +29,7 @@ organizations.
*COBOL code is broken up into 4 divisions.
*Those divisions, in order, are:
- *IDENTIFICATION DIVSION.
+ *IDENTIFICATION DIVISION.
*ENVIRONMENT DIVISION.
*DATA DIVISION.
*PROCEDURE DIVISION.
@@ -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.
@@ -75,7 +75,7 @@ organizations.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 THE-MESSAGE PIC X(20).
- PROCEDURE DIVSION.
+ PROCEDURE DIVISION.
DISPLAY "STARTING PROGRAM".
MOVE "HELLO WORLD" TO THE-MESSAGE.
DISPLAY THE-MESSAGE.
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/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/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/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/rust-gr.html.markdown b/el-gr/rust-gr.html.markdown
new file mode 100644
index 00000000..79f210ac
--- /dev/null
+++ b/el-gr/rust-gr.html.markdown
@@ -0,0 +1,339 @@
+---
+language: Rust
+contributors:
+ - ["P1start", "http://p1start.github.io/"]
+ - ["Dimitri Kokkonis", "https://github.com/kokkonisd"]
+filename: learnrust-gr.rs
+lang: el-gr
+---
+
+_[ΣτΜ.: οι όροι "χαμηλό/υψηλό επίπεδο" αναφέρονται στην εγγύτητα μιας γλώσσας προγραμματισμού ή γενικότερα ενός
+στοιχείου στην "μηχανή", ή το υλικό του υπολογιστή. Για παράδειγμα, η φράση "η C είναι μια γλώσσα χαμηλού επιπέδου"
+αναφέρεται στο γεγονός ότι η C επιτρέπει άμεση και λεπτομερή διαχείρηση μνήμης, και πιο άμεσο έλεγχο του επεξεργαστή·
+σε καμία περίπτωση δεν σημαίνει ότι η C έχει λιγότερες δυνατότητες, και γενικότερα δεν φέρει αρνητική σημασία.]_
+
+Η Rust είναι μια γλώσσα προγραμματισμού ανεπτυγμένη από την Mozilla Research.
+Συνδυάζει τον έλεγχο της απόδοσης χαμηλού επιπέδου με διευκολύνσεις και ασφάλεια υψηλού επιπέδου.
+
+Πετυχαίνει αυτούς τους στόχους χωρίς να χρειάζεται garbage collector ή runtime, το οποίο καθιστά δυνατή τη χρήση
+βιβλιοθηκών της Rust ως αντικατάσταση της C.
+
+Η έκδοση 0.1 (η πρώτη της Rust) δημοσιεύθηκε τον Ιανουάριο του 2012, και για τα επόμενα 3 χρόνια η ανάπτυξή της
+εξελίχθηκε τόσο γρήγορα που, μέχρι πρότινος, προτείνονταν η χρήση μη-σταθερών εκδόσεων (nightly builds) αντί σταθερών
+εκδόσεων.
+
+Τις 15 Μαΐου 2015 δημοσιεύτηκε η εκδοχή 1.0 της Rust, με πλήρη εγγύηση συμβατότητας με προηγούμενες εκδοχές. Οι
+μη-σταθερές εκδόσεις συνήθως περιλαμβάνουν γρηγορότερους χρόνους μεταγλώττισης και γενικότερες βελτιώσεις όσον αφορά
+τον μεταγλωττιστή. Η μέθοδος [train release](https://www.plutora.com/blog/agile-release-train) χρησιμοποιείται, με
+συστηματικές εκδόσεις να δημοσιεύονται κάθε έξι εβδομάδες. Η beta έκδοση της Rust 1.1 δημοσιεύθηκε ταυτοχρόνως με την
+σταθερή έκδοση 1.0.
+
+Αν και η Rust είναι μια γλώσσα σχετικά χαμηλού επιπέδου, ο σχεδιασμός της περιλαμβάνει κάποιες έννοιες που συναντώνται
+συνχότερα σε γλώσσες υψηλού επιπέδου. Αυτό καθιστά την Rust γρήγορη και αποδοτική αλλά επίσης εύκολη και προσβάσιμη.
+
+
+```rust
+// Αυτό είναι ένα σχόλιο. Τα σχόλια μίας γραμμής γράφονται έτσι...
+// Και επεκτείνονται σε περισσότερες από μία γραμμές έτσι.
+
+/// Τα σχόλια documentation γράφονται έτσι, και υποστηρίζουν markdown.
+/// # Παράδειγμα
+///
+/// ```
+/// let five = 5
+/// ```
+
+//////////////////////
+// 1. Βασικές αρχές //
+//////////////////////
+
+#[allow(dead_code)]
+// Συναρτήσεις
+// `i32` είναι ο τύπος που αντιστοιχεί στους 32-bit signed ακέραιους
+fn add2(x: i32, y: i32) -> i32 {
+ // Έμεσα εννοούμενη επιστροφή του αποτελέσματος, χωρίς semicolon (;)
+ x + y
+}
+
+#[allow(unused_variables)]
+#[allow(unused_assignments)]
+#[allow(dead_code)]
+// Συνάρτηση main
+fn main() {
+ // Αριθμοί //
+
+ // Αμετάβλητη σύνδεση
+ let x: i32 = 1;
+
+ // Καταλήξεις integer/float
+ let y: i32 = 13i32;
+ let f: f64 = 1.3f64;
+
+ // Εξακρίβωση τύπου (type inference)
+ // Τις περισσότερες φορες ο μεταγλωττιστής της Rust μπορεί να εξακριβώσει τον τύπο μιας μεταβλητής, επομένως δεν
+ // χρειάζεται ο προγραμματιστής να τον δηλώνει ρητά.
+ // Σε αυτό το tutorial, οι τύποι δηλώνονται ρητά σε διάφορα σημεία, αλλά μόνο προκειμένου να είναι πιο ευανάγνωστος
+ // ο κώδικας. Ο μεταγλωττιστής μπορεί να το διαχειριστεί αυτόματα στις περισσότερες περιπτώσεις.
+ let implicit_x = 1;
+ let implicit_f = 1.3;
+
+ // Πράξεις
+ let sum = x + y + 13;
+
+ // Μη-αμετάβλητη αξία (με την έννοια ότι μπορεί να αλλάξει)
+ let mut mutable = 1;
+ mutable = 4;
+ mutable += 2;
+
+ // Αλφαριθμητικά //
+
+ // Σταθερά αλφαριθμητικά
+ let x: &str = "καλημέρα κόσμε!";
+
+ // Εκτύπωση αλφαριθμητικών
+ println!("{} {}", f, x); // 1.3 καλημέρα κόσμε!
+
+ // A `String` – a heap-allocated string
+ let s: String = "καλημέρα κόσμε".to_string();
+
+ // Ένα κομμάτι αλφαριθμητικού (string slice) – μια μη-μεταβλητή οπτική γωνία προς ένα άλλο αλφαριθμητικό
+ // Το αλφαριθμητικό μπορεί να είναι στατικό όπως τα σταθερά αλφαριθμητικά, ή να περιλαμβάνεται σε ένα άλλο,
+ // δυναμικό αντικείμενο (σε αυτή την περίπτωση τη μεταβλητή `s`)
+ let s_slice: &str = &s;
+
+ println!("{} {}", s, s_slice); // καλημέρα κόσμε καλημέρα κόσμε
+
+ // Διανύσματα/πίνακες //
+
+ // Πίνακας σταθερού μεγέθους
+ let four_ints: [i32; 4] = [1, 2, 3, 4];
+
+ // Δυναμικός πίνακας (διάνυσμα)
+ let mut vector: Vec<i32> = vec![1, 2, 3, 4];
+ vector.push(5);
+
+ // Ένα κομμάτι – μια μη-μεταβλητή οπτική γωνία προς ένα διάνυσμα ή πίνακα
+ // Είναι παρόμοιο με το κομμάτι αλφαριθμητικού που είδαμε προηγουμένως
+ let slice: &[i32] = &vector;
+
+ // Μπορούμε να χρησιμοποιήσουμε το `{:?}` για να εκτυπώσουμε κάτι σε στυλ debug
+ println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
+
+ // Tuples (πλειάδες) //
+
+ // Ένα tuple είναι μια σταθερού μεγέθους σειρά από αξίες (πιθανά διαφορετικού τύπου)
+ let x: (i32, &str, f64) = (1, "καλημέρα", 3.4);
+
+ // Μπορούμε να χρησιμοποιήσουμε το `let` και ένα tuple για να δώσουμε πολλές αξίες σε πολλές μεταβλητές ταυτόχρονα
+ // (destructuring `let`)
+ let (a, b, c) = x;
+ println!("{} {} {}", a, b, c); // 1 καλημέρα 3.4
+
+ // Μπορούμε επίσης να επιλέξουμε ένα συγκεκριμένο στοιχείο από ένα tuple
+ println!("{}", x.1); // καλημέρα
+
+ //////////////
+ // 2. Τύποι //
+ //////////////
+
+ // Δομή
+ struct Point {
+ x: i32,
+ y: i32,
+ }
+
+ let origin: Point = Point { x: 0, y: 0 };
+
+ // Μια δομή με ανώνυμα πεδία, ή αλλιώς μια `δομή tuple` (`tuple struct`)
+ struct Point2(i32, i32);
+
+ let origin2 = Point2(0, 0);
+
+ // Enum, όπως στην C
+ enum Direction {
+ Left,
+ Right,
+ Up,
+ Down,
+ }
+
+ let up = Direction::Up;
+
+ // Enum με πεδία
+ enum OptionalI32 {
+ AnI32(i32),
+ Nothing,
+ }
+
+ let two: OptionalI32 = OptionalI32::AnI32(2);
+ let nothing = OptionalI32::Nothing;
+
+ // Γενικότητα (genericity) //
+
+ struct Foo<T> { bar: T }
+
+ // Αυτό ορίζεται στην standard library ως `Option`
+ enum Optional<T> {
+ SomeVal(T),
+ NoVal,
+ }
+
+ // Μέθοδοι //
+
+ impl<T> Foo<T> {
+ // Οι μέθοδοι παίρνουν πάντα μια ρητή παράμετρο `self`
+ fn bar(&self) -> &T { // Δανειζόμαστε το self
+ &self.bar
+ }
+ fn bar_mut(&mut self) -> &mut T { // Δανειζόμαστε το self ως μη-αμετάβλητη αξία
+ &mut self.bar
+ }
+ fn into_bar(self) -> T { // Εδώ το self καταναλώνεται
+ self.bar
+ }
+ }
+
+ let a_foo = Foo { bar: 1 };
+ println!("{}", a_foo.bar()); // 1
+
+ // Χαρακτηρηστικά (traits) (γνωστά ως interfaces ή typeclasses σε άλλες γλώσσες) //
+
+ trait Frobnicate<T> {
+ fn frobnicate(self) -> Option<T>;
+ }
+
+ impl<T> Frobnicate<T> for Foo<T> {
+ fn frobnicate(self) -> Option<T> {
+ Some(self.bar)
+ }
+ }
+
+ let another_foo = Foo { bar: 1 };
+ println!("{:?}", another_foo.frobnicate()); // Some(1)
+
+ //////////////////////////////////////////////////
+ // 3. Αντιστοιχίσεις Μοτίβων (Pattern Matching) //
+ //////////////////////////////////////////////////
+
+ let foo = OptionalI32::AnI32(1);
+ match foo {
+ OptionalI32::AnI32(n) => println!("Είναι ένα i32: {}", n),
+ OptionalI32::Nothing => println!("Δεν είναι τίποτα!"),
+ }
+
+ // Προχωρημένο pattern matching
+ struct FooBar { x: i32, y: OptionalI32 }
+ let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) };
+
+ match bar {
+ FooBar { x: 0, y: OptionalI32::AnI32(0) } =>
+ println!("Οι αριθμοί είναι μηδέν!"),
+ FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m =>
+ println!("Οι αριθμοί είναι οι ίδιοι"),
+ FooBar { x: n, y: OptionalI32::AnI32(m) } =>
+ println!("Διαφορετικοί αριθμοί: {} {}", n, m),
+ FooBar { x: _, y: OptionalI32::Nothing } =>
+ println!("Ο δεύτερος αριθμός δεν είναι τίποτα!"),
+ }
+
+ /////////////////////
+ // 4. Έλεγχος ροής //
+ /////////////////////
+
+ // Βρόγχοι `for`
+ let array = [1, 2, 3];
+ for i in array.iter() {
+ println!("{}", i);
+ }
+
+ // Διαστήματα
+ for i in 0u32..10 {
+ print!("{} ", i);
+ }
+ println!("");
+ // Τυπώνει `0 1 2 3 4 5 6 7 8 9 `
+
+ // Βρόγχοι `if`
+ if 1 == 1 {
+ println!("Τα μαθηματικά δουλεύουν!");
+ } else {
+ println!("Ωχ όχι...");
+ }
+
+ // `if` ως έκφραση
+ let value = if true {
+ "καλό"
+ } else {
+ "κακό"
+ };
+
+ // Βρόγχοι `while`
+ while 1 == 1 {
+ println!("Το σύμπαν λειτουργεί κανονικά.");
+ // Μπορούμε να βγούμε από το βρόγχο με το `break`
+ break
+ }
+
+ // Ατέρμονος βρόχγος
+ loop {
+ println!("Καλημέρα!");
+ // Μπορούμε να βγούμε από το βρόγχο με το `break`
+ break
+ }
+
+ //////////////////////////////////
+ // 5. Ασφάλεια μνήμης & δείκτες //
+ //////////////////////////////////
+
+ // Δείκτης με ιδιοκτήτη – μόνο ένα αντικείμενο μπορεί να είναι ο "ιδιοκτήτης" αυτού του δείκτη ανά πάσα στιγμή
+ // Αυτό σημαίνει ότι μόλις το `Box` βγει εκτός πλαισίου (out of scope), ο δείκτης μπορεί να ελευθερωθεί με ασφάλεια
+ let mut mine: Box<i32> = Box::new(3);
+ *mine = 5; // Dereference του δείκτη
+ // Εδώ, το `now_its_mine` γίνεται ιδιοκτήτης του `mine`. Δηλαδή, το `mine` μετακινείται.
+ let mut now_its_mine = mine;
+ *now_its_mine += 2;
+
+ println!("{}", now_its_mine); // 7
+ // println!("{}", mine); // Αυτό παράγει λάθος κατά τη μεταγλώττιση διότι τώρα ο δείκτης ανοίκει στο `now_its_mine`
+
+ // Reference (αναφορά) – ένας αμετάβλητος δείκτης που αναφέρεται σε άλλα δεδομένα
+ // Όταν μια αναφορά δίνεται σε μια αξία, λέμε πως η αξία έχει "δανειστεί".
+ // Όταν μια αξία δανείζεται αμετάβλητα, δεν μπορεί να είναι mutated (να μεταβληθεί) ή να μετακινηθεί.
+ // Ένας "δανεισμός" παραμένει ενεργός μέχρι την τελευταία χρήση της μεταβλητής που δανείζεται.
+ let mut var = 4;
+ var = 3;
+ let ref_var: &i32 = &var;
+
+ println!("{}", var); // Αντίθετα με το `mine` προηγουμένως, η μεταβλητή `var` μπορεί ακόμα να χρησιμοποιηθεί
+ println!("{}", *ref_var);
+ // var = 5; // Αυτό παράγει λάθος κατά τη μεταγλώττιση γιατί η μεταβλητή `var` είναι δανεισμένη
+ // *ref_var = 6; // Το ίδιο εδώ, γιατί η `ref_var` αποτελεί αμετάβλητη αναφορά
+ ref_var; // Εντολή no-op (τίποτα δεν εκτελείται από τον επεξεργαστή), η οποία όμως μετράει ως χρήση και κρατά τον
+ // "δανεισμό" ενεργό
+ var = 2; // Η `ref_var` δεν χρησιμοποιείται από εδώ και στο εξής, άρα ο "δανεισμός" τελειώνει
+
+ // Μεταβλητή αναφορά
+ // Όσο μια αξία είναι μεταβλητά δανεισμένη, παραμένει τελείως απροσβάσιμη.
+ let mut var2 = 4;
+ let ref_var2: &mut i32 = &mut var2;
+ *ref_var2 += 2; // Ο αστερίσκος (*) χρησιμοποιείται ως δείκτης προς την μεταβλητά δανεισμένη `var2`
+
+ println!("{}", *ref_var2); // 6 , // Αν είχαμε `var2` εδώ θα προκαλούνταν λάθος μεταγλώττισης.
+ // O τύπος της `ref_var2` είναι &mut i32, άρα αποθηκεύει μια αναφορά προς μια αξία i32, όχι την αξία την ίδια.
+ // var2 = 2; // Λάθος μεταγλώττισης, γιατί η `var2` είναι δανεισμένη.
+ ref_var2; // Εντολή no-op (τίποτα δεν εκτελείται από τον επεξεργαστή), η οποία όμως μετράει ως χρήση και κρατά τον
+ // "δανεισμό" ενεργό
+}
+```
+
+## Μάθετε περισσότερα
+
+Υπάρχουν πολλά ακόμα πράγματα να μάθει κανείς· αυτά είναι μόνο τα βασικά της Rust, που επιτρέπουν να καταλάβουμε το
+βασικό τρόπο λειτουργίας της. Για να μάθετε περισσότερα για τη Rust, διαβάστε το [The Rust Programming
+Language](http://doc.rust-lang.org/book/index.html) και επισκεφθείτε το subreddit [/r/rust](http://reddit.com/r/rust).
+Οι άνθρωποι πίσω από το κανάλι #rust στο irc.mozilla.org είναι επίσης πάντα πρόθυμοι να βοηθήσουν τους αρχάριους.
+
+Μπορείτε επίσης να παίξετε με τη Rust χρησιμοποιώντας τους εξής online μεταγλωττιστές:
+
+- [Rust playpen](http://play.rust-lang.org)
+- [Rust website](http://rust-lang.org)
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/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/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/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/c++-fr.html.markdown b/fr-fr/c++-fr.html.markdown
index 863162f7..c8603756 100644
--- a/fr-fr/c++-fr.html.markdown
+++ b/fr-fr/c++-fr.html.markdown
@@ -69,11 +69,11 @@ void func(); // fonction qui ne prend aucun argument
// En C
void func(); // fonction qui peut prendre n'importe quel nombre d'arguments
-// Utilise nullptr au lieu de NULL in C++
+// Utilise nullptr au lieu de NULL en C++
int* ip = nullptr;
// Les en-têtes standards du C sont disponibles en C++,
-// mais son préfixés avec "c" et n'ont pas de suffixe .h
+// mais sont préfixés avec "c" et n'ont pas de suffixe .h
#include <cstdio>
int main()
@@ -722,7 +722,7 @@ catch (...)
// gestion d'un fichier C :
void faireQuelqueChoseAvecUnFichier(const char* nomDuFichier)
{
- // Pour commencer, supposns que rien ne peut échouer.
+ // Pour commencer, supposons que rien ne peut échouer.
FILE* fh = fopen(nomDuFichier, "r"); // Ouvre le fichier en lecture
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/markdown-fr.html.markdown b/fr-fr/markdown-fr.html.markdown
index 26c2546a..1fd22883 100644
--- a/fr-fr/markdown-fr.html.markdown
+++ b/fr-fr/markdown-fr.html.markdown
@@ -178,8 +178,8 @@ Vous pouvez également utiliser des sous-listes.
1. Item un
2. Item deux
3. Item trois
-* Sub-item
-* Sub-item
+ * Sub-item
+ * Sub-item
4. Item quatre
```
@@ -230,7 +230,7 @@ En Markdown GitHub, vous pouvez utiliser des syntaxes spécifiques.
```
Pas besoin d'indentation pour le code juste au-dessus, de plus, GitHub
-va utiliser une coloration syntaxique pour le langage indiqué après les ```.
+va utiliser une coloration syntaxique pour le langage indiqué après les <code>```</code>.
## Ligne Horizontale
@@ -267,13 +267,13 @@ Markdown supporte aussi les liens relatifs.
Les liens de références sont eux aussi disponibles en Markdown.
-```md
-[Cliquez ici][link1] pour plus d'information!
-[Regardez aussi par ici][foobar] si vous voulez.
+<div class="highlight"><code><pre>
+[<span class="nv">Cliquez ici</span>][<span class="ss">link1</span>] pour plus d'information!
+[<span class="nv">Regardez aussi par ici</span>][<span class="ss">foobar</span>] si vous voulez.
-[link1]: http://test.com/ "Cool!"
-[foobar]: http://foobar.biz/ "Génial!"
-```
+[<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Cool!"</span>
+[<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Génial!"</span>
+</pre></code></div>
Le titre peut aussi être entouré de guillemets simples, ou de parenthèses, ou
absent. Les références peuvent être placées où vous voulez dans le document et
@@ -282,11 +282,11 @@ les identifiants peuvent être n'importe quoi tant qu'ils sont uniques.
Il y a également le nommage implicite qui transforme le texte du lien en
identifiant.
-```md
-[Ceci][] est un lien.
+<div class="highlight"><code><pre>
+[<span class="nv">Ceci</span>][] est un lien.
-[ceci]: http://ceciestunlien.com/
-```
+[<span class="nv">Ceci</span>]:<span class="sx">http://ceciestunlien.com/</span>
+</pre></code></div>
Mais ce n'est pas beaucoup utilisé.
@@ -302,11 +302,11 @@ d'un point d'exclamation!
Là aussi, on peut utiliser le mode "références".
-```md
-![Ceci est l'attribut ALT de l'image][monimage]
+<div class="highlight"><code><pre>
+![<span class="nv">Ceci est l'attribut ALT de l'image</span>][<span class="ss">monimage</span>]
-[monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici."
-```
+[<span class="nv">monimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"si vous voulez un titre, c'est ici."</span>
+</pre></code></div>
## Divers
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/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/go.html.markdown b/go.html.markdown
index b727e59d..5a9214b0 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -33,7 +33,7 @@ Go comes with a good standard library and a sizeable community.
line comment */
/* A build tag is a line comment starting with // +build
- and can be execute by go build -tags="foo bar" command.
+ and can be executed by go build -tags="foo bar" command.
Build tags are placed before the package clause near or at the top of the file
followed by a blank line or other line comments. */
// +build prod, dev, test
diff --git a/haskell.html.markdown b/haskell.html.markdown
index 1cc79ec9..328da5c9 100644
--- a/haskell.html.markdown
+++ b/haskell.html.markdown
@@ -61,6 +61,8 @@ not False -- True
-- A string is a list of characters
['H', 'e', 'l', 'l', 'o'] -- "Hello"
+
+-- Lists can be indexed with the `!!` operator followed by an index
"This is a string" !! 0 -- 'T'
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/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/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/jquery.html.markdown b/jquery.html.markdown
index a1673c10..18077dca 100644
--- a/jquery.html.markdown
+++ b/jquery.html.markdown
@@ -3,6 +3,7 @@ category: tool
tool: jquery
contributors:
- ["Sawyer Charles", "https://github.com/xssc"]
+ - ["Devansh Patil", "https://github.com/subtra3t"]
filename: jquery.js
---
@@ -10,6 +11,7 @@ jQuery is a JavaScript library that helps you "do more, write less". It makes ma
Because jQuery is a JavaScript library you should [learn JavaScript first](https://learnxinyminutes.com/docs/javascript/)
+**NOTE**: jQuery has fallen out of the limelight in recent years, since you can achieve the same thing with the vanilla DOM (Document Object Model) API. So the only thing it is used for is a couple of handy features, such as the [jQuery date picker](https://api.jqueryui.com/datepicker) (which actually has a standard, unlike the `<input type="date">` HTML element), and the obvious decrease in the code length.
```js
diff --git a/json.html.markdown b/json.html.markdown
index 3ec7a3af..1ccdb5cf 100644
--- a/json.html.markdown
+++ b/json.html.markdown
@@ -9,7 +9,7 @@ contributors:
- ["Athanasios Emmanouilidis", "https://github.com/athanasiosem"]
---
-JSON is an extremely simple data-interchange format. As [json.org](http://json.org) says, it is easy for humans to read and write and for machines to parse and generate.
+JSON is an extremely simple data-interchange format. As [json.org](https://json.org) says, it is easy for humans to read and write and for machines to parse and generate.
A piece of JSON must represent either:
@@ -80,6 +80,5 @@ Supported data types:
## Further Reading
-* [JSON.org](http://json.org) All of JSON beautifully explained using flowchart-like graphics.
-
+* [JSON.org](https://json.org) All of JSON beautifully explained using flowchart-like graphics.
* [JSON Tutorial](https://www.youtube.com/watch?v=wI1CWzNtE-M) A concise introduction to JSON.
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/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/latex.html.markdown b/latex.html.markdown
index e8bc6064..29a9f638 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/"]
@@ -123,7 +123,7 @@ Math has many symbols, far beyond what you can find on a keyboard;
Set and relation symbols, arrows, operators, and Greek letters to name a few.
Sets and relations play a vital role in many mathematical research papers.
-Here's how you state all x that belong to X, $\forall$ x $\in$ X.
+Here's how you state all x that belong to X, $\forall x \in X$.
% Notice how I needed to add $ signs before and after the symbols. This is
% because when writing, we are in text-mode.
% However, the math symbols only exist in math-mode.
@@ -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,13 +200,21 @@ 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}
+ % The basic is simple: one letter for each column, to control alignment:
+ % basic options are: c, l, r and p for centered, left, right and paragraph
+ % optionnally, 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 & Last Name & First 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 | Last Name First Name
+ % -------|--------------------------- % because of \hline
+ % 1 | Biggus Dickus
+ % 2 | Monty Python
\end{table}
\section{Getting \LaTeX{} to not compile something (i.e.\ Source Code)}
@@ -218,7 +228,8 @@ 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}
@@ -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
@@ -265,6 +277,27 @@ There exists two main types of links: visible URL \\
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),
+not even extened 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}
+
+Not that there also exists LuaTeX and XeLaTeX that were designed to have builtin
+support for UTF-8 and case ease your life if you don't write in a latin alphabet.
+
\section{End}
That's all for now!
diff --git a/lua.html.markdown b/lua.html.markdown
index 53e396be..4a470623 100644
--- a/lua.html.markdown
+++ b/lua.html.markdown
@@ -395,7 +395,7 @@ g() -- Prints out 343; nothing printed before now.
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/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/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/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/powershell.html.markdown b/powershell.html.markdown
index 6efd984c..318bf043 100644
--- a/powershell.html.markdown
+++ b/powershell.html.markdown
@@ -3,6 +3,7 @@ category: tool
tool: powershell
contributors:
- ["Wouter Van Schandevijl", "https://github.com/laoujin"]
+ - ["Andrew Ryan Davis", "https://github.com/AndrewDavis1191"]
filename: LearnPowershell.ps1
---
@@ -13,116 +14,374 @@ Nearly all examples below can be a part of a shell script or executed directly
in the shell.
A key difference with Bash is that it is mostly objects that you manipulate
-rather than plain text.
+rather than plain text. After years of evolving, it resembles Python a bit.
[Read more here.](https://docs.microsoft.com/powershell/scripting/overview)
-If you are uncertain about your environment:
+Powershell as a Language:
```powershell
-Get-ExecutionPolicy -List
-Set-ExecutionPolicy AllSigned
-# Execution policies include:
-# - Restricted: Scripts won't run.
-# - RemoteSigned: Downloaded scripts run only if signed by a trusted publisher.
-# - AllSigned: Scripts need to be signed by a trusted publisher.
-# - Unrestricted: Run all scripts.
-help about_Execution_Policies # for more info
-# Current PowerShell version:
-$PSVersionTable
-```
+# Single line comments start with a number symbol.
-Getting help:
+<#
+ Multi-line comments
+ like so
+#>
-```powershell
-# Find commands
-Get-Command about_* # alias: gcm
-Get-Command -Verb Add
-Get-Alias ps
-Get-Alias -Definition Get-Process
-Get-Help ps | less # alias: help
-ps | Get-Member # alias: gm
+####################################################
+## 1. Primitive Datatypes and Operators
+####################################################
+
+# Numbers
+3 # => 3
+
+# Math
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+35 / 5 # => 7.0
+
+# Powershell uses banker's rounding,
+# meaning [int]1.5 would round to 2 but so would [int]2.5
+# Division always returns a float.
+# You must cast result to [int] to round.
+[int]5 / [int]3 # => 1.66666666666667
+[int]-5 / [int]3 # => -1.66666666666667
+5.0 / 3.0 # => 1.66666666666667
+-5.0 / 3.0 # => -1.66666666666667
+[int]$result = 5 / 3
+$result # => 2
+
+# Modulo operation
+7 % 3 # => 1
+
+# Exponentiation requires longform or the built-in [Math] class.
+[Math]::Pow(2,3) # => 8
+
+# Enforce order of operations with parentheses.
+1 + 3 * 2 # => 7
+(1 + 3) * 2 # => 8
+
+# Boolean values are primitives (Note: the $)
+$True # => True
+$False # => False
+
+# negate with !
+!$True # => False
+!$False # => True
+
+# Boolean Operators
+# Note "-and" and "-or" usage
+$True -and $False # => False
+$False -or $True # => True
+
+# True and False are actually 1 and 0 but only support limited arithmetic.
+# However, casting the bool to int resolves this.
+$True + $True # => 2
+$True * 8 # => '[System.Boolean] * [System.Int32]' is undefined
+[int]$True * 8 # => 8
+$False - 5 # => -5
+
+# Comparison operators look at the numerical value of True and False.
+0 -eq $False # => True
+1 -eq $True # => True
+2 -eq $True # => False
+-5 -ne $False # => True
+
+# Using boolean logical operators on ints casts to booleans for evaluation.
+# but their non-cast value is returned
+# Don't mix up with bool(ints) and bitwise -band/-bor
+[bool](0) # => False
+[bool](4) # => True
+[bool](-6) # => True
+0 -band 2 # => 0
+-5 -bor 0 # => -5
+
+# Equality is -eq (equals)
+1 -eq 1 # => True
+2 -eq 1 # => False
+
+# Inequality is -ne (notequals)
+1 -ne 1 # => False
+2 -ne 1 # => True
+
+# More comparisons
+1 -lt 10 # => True
+1 -gt 10 # => False
+2 -le 2 # => True
+2 -ge 2 # => True
+
+# Seeing whether a value is in a range
+1 -lt 2 -and 2 -lt 3 # => True
+2 -lt 3 -and 3 -lt 2 # => False
+
+# (-is vs. -eq) -is checks if two objects are the same type.
+# -eq checks if the objects have the same values.
+# Note: we called '[Math]' from .NET previously without the preceeding
+# namespaces. We can do the same with [Collections.ArrayList] if preferred.
+[System.Collections.ArrayList]$a = @() # Point a at a new list
+$a = (1,2,3,4)
+$b = $a # => Point b at what a is pointing to
+$b -is $a.GetType() # => True, a and b equal same type
+$b -eq $a # => True, a and b values are equal
+[System.Collections.Hashtable]$b = @{} # => Point a at a new hash table
+$b = @{'one' = 1
+ 'two' = 2}
+$b -is $a.GetType() # => False, a and b types not equal
+
+# Strings are created with " or ' but " is required for string interpolation
+"This is a string."
+'This is also a string.'
+
+# Strings can be added too! But try not to do this.
+"Hello " + "world!" # => "Hello world!"
+
+# A string can be treated like a list of characters
+"Hello world!"[0] # => 'H'
+
+# You can find the length of a string
+("This is a string").Length # => 16
+
+# You can also format using f-strings or formatted string literals.
+$name = "Steve"
+$age = 22
+"He said his name is $name."
+# => "He said his name is Steve"
+"{0} said he is {1} years old." -f $name, $age
+# => "Steve said he is 22 years old"
+"$name's name is $($name.Length) characters long."
+# => "Steve's name is 5 characters long."
+
+# Escape Characters in Powershell
+# Many languages use the '\', but Windows uses this character for
+# file paths. Powershell thus uses '`' to escape characters
+# Take caution when working with files, as '`' is a
+# valid character in NTFS filenames.
+"Showing`nEscape Chars" # => new line between Showing and Escape
+"Making`tTables`tWith`tTabs" # => Format things with tabs
+
+# Negate pound sign to prevent comment
+# Note that the function of '#' is removed, but '#' is still present
+`#Get-Process # => Fail: not a recognized cmdlet
+
+# $null is not an object
+$null # => None
+
+# $null, 0, and empty strings and arrays all evaluate to False.
+# All other values are True
+function Test-Value ($value) {
+ if ($value) {
+ Write-Output 'True'
+ }
+ else {
+ Write-Output 'False'
+ }
+}
-Show-Command Get-EventLog # Display GUI to fill in the parameters
+Test-Value ($null) # => False
+Test-Value (0) # => False
+Test-Value ("") # => False
+Test-Value [] # => True
+# *[] calls .NET class; creates '[]' string when passed to function
+Test-Value ({}) # => True
+Test-Value @() # => False
-Update-Help # Run as admin
-```
-The tutorial starts here:
+####################################################
+## 2. Variables and Collections
+####################################################
+
+# Powershell uses the "Write-Output" function to print
+Write-Output "I'm Posh. Nice to meet you!" # => I'm Posh. Nice to meet you!
+
+# Simple way to get input data from console
+$userInput = Read-Host "Enter some data: " # Returns the data as a string
+
+# There are no declarations, only assignments.
+# Convention is to use camelCase or PascalCase, whatever your team uses.
+$someVariable = 5
+$someVariable # => 5
+
+# Accessing a previously unassigned variable does not throw exception.
+# The value is $null by default
+
+# Ternary Operators exist in Powershell 7 and up
+0 ? 'yes' : 'no' # => no
+
+
+# The default array object in Powershell is an fixed length array.
+$defaultArray = "thing","thing2","thing3"
+# you can add objects with '+=', but cannot remove objects.
+$defaultArray.Add("thing4") # => Exception "Collection was of a fixed size."
+# To have a more workable array, you'll want the .NET [ArrayList] class
+# It is also worth noting that ArrayLists are significantly faster
+
+# ArrayLists store sequences
+[System.Collections.ArrayList]$array = @()
+# You can start with a prefilled ArrayList
+[System.Collections.ArrayList]$otherArray = @(4, 5, 6)
+
+# Add to the end of a list with 'Add' (Note: produces output, append to $null)
+$array.Add(1) > $null # $array is now [1]
+$array.Add(2) > $null # $array is now [1, 2]
+$array.Add(4) > $null # $array is now [1, 2, 4]
+$array.Add(3) > $null # $array is now [1, 2, 4, 3]
+# Remove from end with index of count of objects-1; array index starts at 0
+$array.RemoveAt($array.Count-1) # => 3 and array is now [1, 2, 4]
+# Let's put it back
+$array.Add(3) > $null # array is now [1, 2, 4, 3] again.
+
+# Access a list like you would any array
+$array[0] # => 1
+# Look at the last element
+$array[-1] # => 3
+
+# Looking out of bounds returns nothing
+$array[4] # blank line returned
+
+# You can look at ranges with slice syntax.
+# The start index is included, the end index is not
+# (It's a closed/open range for you mathy types.)
+$array[1..3] # Return array from index 1 to 3 => [2, 4]
+$array[2..-1] # Return array starting from index 2 => [4, 3]
+$array[0..3] # Return array from beginning until index 3 => [1, 2, 4]
+$array[0..2] # Return array selecting every second entry => [1, 4]
+$array.Reverse() # mutates array to reverse order => [3, 4, 2, 1]
+# Use any combination of these to make advanced slices
+
+# Remove arbitrary elements from a array with "del"
+$array.Remove($array[2]) # $array is now [1, 2, 3]
+
+# Insert an element at a specific index
+$array.Insert(1, 2) # $array is now [1, 2, 3] again
+
+# Get the index of the first item found matching the argument
+$array.IndexOf(2) # => 1
+$array.IndexOf(6) # Returns -1 as "outside array"
+
+# You can add arrays
+# Note: values for $array and for $otherArray are not modified.
+$array + $otherArray # => [1, 2, 3, 4, 5, 6]
+
+# Concatenate arrays with "AddRange()"
+$array.AddRange($otherArray) # Now $array is [1, 2, 3, 4, 5, 6]
+
+# Check for existence in a array with "in"
+1 -in $array # => True
+
+# Examine length with "Count" (Note: "Length" on arrayList = each items length)
+$array.Count # => 6
+
+
+# Tuples are like arrays but are immutable.
+# To use Tuples in powershell, you must use the .NET tuple class.
+$tuple = [System.Tuple]::Create(1, 2, 3)
+$tuple.Item(0) # => 1
+$tuple.Item(0) = 3 # Raises a TypeError
+
+# You can do some of the array methods on tuples, but they are limited.
+$tuple.Length # => 3
+$tuple + (4, 5, 6) # => Exception
+$tuple[0..2] # => $null
+2 -in $tuple # => False
+
+
+# Hashtables store mappings from keys to values, similar to Dictionaries.
+$emptyHash = @{}
+# Here is a prefilled dictionary
+$filledHash = @{"one"= 1
+ "two"= 2
+ "three"= 3}
+
+# Look up values with []
+$filledHash["one"] # => 1
+
+# Get all keys as an iterable with ".Keys".
+# items maintain the order at which they are inserted into the dictionary.
+$filledHash.Keys # => ["one", "two", "three"]
+
+# Get all values as an iterable with ".Values".
+$filledHash.Values # => [1, 2, 3]
+
+# Check for existence of keys or values in a hash with "-in"
+"one" -in $filledHash.Keys # => True
+1 -in $filledHash.Values # => False
+
+# Looking up a non-existing key returns $null
+$filledHash["four"] # $null
+
+# Adding to a dictionary
+$filledHash.Add("five",5) # $filledHash["five"] is set to 5
+$filledHash.Add("five",6) # exception "Item with key "five" has already been added"
+$filledHash["four"] = 4 # $filledHash["four"] is set to 4, running again does nothing
+
+# Remove keys from a dictionary with del
+$filledHash.Remove("one") # Removes the key "one" from filled dict
+
+
+####################################################
+## 3. Control Flow and Iterables
+####################################################
+
+# Let's just make a variable
+$someVar = 5
+
+# Here is an if statement.
+# This prints "$someVar is smaller than 10"
+if ($someVar -gt 10) {
+ Write-Output "$someVar is bigger than 10."
+}
+elseif ($someVar -lt 10) { # This elseif clause is optional.
+ Write-Output "$someVar is smaller than 10."
+}
+else { # This is optional too.
+ Write-Output "$someVar is indeed 10."
+}
-```powershell
-# As you already figured, comments start with #
<#
- Multi-line comments
- like so
+Foreach loops iterate over arrays
+prints:
+ dog is a mammal
+ cat is a mammal
+ mouse is a mammal
#>
+foreach ($animal in ("dog", "cat", "mouse")) {
+ # You can use -f to interpolate formatted strings
+ "{0} is a mammal" -f $animal
+}
+
+<#
+For loops iterate over arrays and you can specify indices
+prints:
+ 0 a
+ 1 b
+ 2 c
+ 3 d
+ 4 e
+ 5 f
+ 6 g
+ 7 h
+#>
+$letters = ('a','b','c','d','e','f','g','h')
+for($i=0; $i -le $letters.Count-1; $i++){
+ Write-Host $i, $letters[$i]
+}
-# Simple hello world example:
-echo Hello world!
-# echo is an alias for Write-Output (=cmdlet)
-# Most cmdlets and functions follow the Verb-Noun naming convention
-
-# Each command starts on a new line, or after a semicolon:
-echo 'This is the first line'; echo 'This is the second line'
-
-# Declaring a variable looks like this:
-$aString="Some string"
-# Or like this:
-$aNumber = 5 -as [double]
-$aList = 1,2,3,4,5
-# Reverse an array *Note this is a mutation on the existing array
-[array]::Reverse($aList)
-$anEmptyList = @()
-$aString = $aList -join '--' # yes, -split exists also
-$aHashtable = @{name1='val1'; name2='val2'}
-
-# Using variables:
-echo $aString
-echo "Interpolation: $aString"
-echo "$aString has length of $($aString.Length)"
-echo '$aString'
-echo @"
-This is a Here-String
-$aString
-"@
-# Note that ' (single quote) won't expand the variables!
-# Here-Strings also work with single quote
-
-# Builtin variables:
-# There are some useful builtin variables, like
-echo "Booleans: $TRUE and $FALSE"
-echo "Empty value: $NULL"
-echo "Last program's return value: $?"
-echo "Exit code of last run Windows-based program: $LastExitCode"
-echo "The last token in the last line received by the session: $$"
-echo "The first token: $^"
-echo "Script's PID: $PID"
-echo "Full path of current script directory: $PSScriptRoot"
-echo 'Full path of current script: ' + $MyInvocation.MyCommand.Path
-echo "FUll path of current directory: $Pwd"
-echo "Bound arguments in a function, script or code block: $PSBoundParameters"
-echo "Unbound arguments: $($Args -join ', ')."
-# More builtins: `help about_Automatic_Variables`
-
-# Find the datatype of variables or properties you're working with
-$true.GetType()
-$aHashtable.name2.GetType()
-
-# Inline another file (dot operator)
-. .\otherScriptName.ps1
-
-
-### Control Flow
-# We have the usual if structure:
-if ($Age -is [string]) {
- echo 'But.. $Age cannot be a string!'
-} elseif ($Age -lt 12 -and $Age -gt 0) {
- echo 'Child (Less than 12. Greater than 0)'
-} else {
- echo 'Adult'
+<#
+While loops go until a condition is no longer met.
+prints:
+ 0
+ 1
+ 2
+ 3
+#>
+$x = 0
+while ($x -lt 4) {
+ Write-Output $x
+ $x += 1 # Shorthand for x = x + 1
}
# Switch statements are more powerful compared to most languages
@@ -133,89 +392,53 @@ switch($val) {
{ $_ -like 's*' } { "Case insensitive"; break }
{ $_ -clike 's*'} { "clike, ceq, cne for case sensitive"; break }
{ $_ -notmatch '^.*$'} { "Regex matching. cnotmatch, cnotlike, ..."; break }
- { 'x' -contains 'x'} { "FALSE! -contains is for lists!"; break }
default { "Others" }
}
-# The classic for
-for($i = 1; $i -le 10; $i++) {
- "Loop number $i"
+# Handle exceptions with a try/catch block
+try {
+ # Use "throw" to raise an error
+ throw "This is an error"
}
-# Or shorter
-1..10 | % { "Loop number $_" }
-
-# PowerShell also offers
-foreach ($var in 'val1','val2','val3') { echo $var }
-# while () {}
-# do {} while ()
-# do {} until ()
-
-# Exception handling
-try {} catch {} finally {}
-try {} catch [System.NullReferenceException] {
- echo $_.Exception | Format-List -Force
+catch {
+ Write-Output $Error.ExceptionMessage
+}
+finally {
+ Write-Output "We can clean up resources here"
}
-### Providers
-# List files and directories in the current directory
-ls # or `dir`
-cd ~ # goto home
-
-Get-Alias ls # -> Get-ChildItem
-# Uh!? These cmdlets have generic names because unlike other scripting
-# languages, PowerShell does not only operate in the current directory.
-cd HKCU: # go to the HKEY_CURRENT_USER registry hive
-
-# Get all providers in your session
-Get-PSProvider
-
-
-### Pipeline
-# Cmdlets have parameters that control their execution:
-Get-ChildItem -Filter *.txt -Name # Get just the name of all txt files
-# Only need to type as much of a parameter name until it is no longer ambiguous
-ls -fi *.txt -n # -f is not possible because -Force also exists
-# Use `Get-Help Get-ChildItem -Full` for a complete overview
-
-# Results of the previous cmdlet can be passed to the next as input.
-# `$_` is the current object in the pipeline object.
-ls | Where-Object { $_.Name -match 'c' } | Export-CSV export.txt
-ls | ? { $_.Name -match 'c' } | ConvertTo-HTML | Out-File export.html
+# Writing to a file
+$contents = @{"aa"= 12
+ "bb"= 21}
+$contents | Export-CSV "$env:HOMEDRIVE\file.csv" # writes to a file
-# If you get confused in the pipeline use `Get-Member` for an overview
-# of the available methods and properties of the pipelined objects:
-ls | Get-Member
-Get-Date | gm
+$contents = "test string here"
+$contents | Out-File "$env:HOMEDRIVE\file.txt" # writes to another file
-# ` is the line continuation character. Or end the line with a |
-Get-Process | Sort-Object ID -Descending | Select-Object -First 10 Name,ID,VM `
- | Stop-Process -WhatIf
+# Read file contents and convert to json
+Get-Content "$env:HOMEDRIVE\file.csv" | ConvertTo-Json
-Get-EventLog Application -After (Get-Date).AddHours(-2) | Format-List
-# Use % as a shorthand for ForEach-Object
-('a','b','c') | ForEach-Object `
- -Begin { "Starting"; $counter = 0 } `
- -Process { "Processing $_"; $counter++ } `
- -End { "Finishing: $counter" }
+####################################################
+## 4. Functions
+####################################################
-# Get-Process as a table with three columns
-# The third column is the value of the VM property in MB and 2 decimal places
-# Computed columns can be written more verbose as:
-# `@{name='lbl';expression={$_}`
-ps | Format-Table ID,Name,@{n='VM(MB)';e={'{0:n2}' -f ($_.VM / 1MB)}} -autoSize
+# Use "function" to create new functions
+# Keep the Verb-Noun naming convention for functions
+function Add-Numbers {
+ $args[0] + $args[1]
+}
+Add-Numbers 1 2 # => 3
-### Functions
-# The [string] attribute is optional.
-# Function names should follow Verb-Noun convention
-function Get-Foo([string]$name) {
- echo "Hey $name, have a function"
+# Calling functions with parameters
+function Add-ParamNumbers {
+ param( [int]$firstNumber, [int]$secondNumber )
+ $firstNumber + $secondNumber
}
-# Calling your function
-Get-Foo "Say my name"
+Add-ParamNumbers -FirstNumber 1 -SecondNumber 2 # => 3
# Functions with named parameters, parameter attributes, parsable documentation
<#
@@ -232,116 +455,347 @@ New-Website siteName 2000 # ERROR! Port argument could not be validated
('name1','name2') | New-Website -Verbose
#>
function New-Website() {
- [CmdletBinding()]
- param (
- [Parameter(ValueFromPipeline=$true, Mandatory=$true)]
- [Alias('name')]
- [string]$siteName,
- [ValidateSet(3000,5000,8000)]
- [int]$port = 3000
- )
- BEGIN { Write-Verbose 'Creating new website(s)' }
- PROCESS { echo "name: $siteName, port: $port" }
- END { Write-Verbose 'Website(s) created' }
+ [CmdletBinding()]
+ param (
+ [Parameter(ValueFromPipeline=$true, Mandatory=$true)]
+ [Alias('name')]
+ [string]$siteName,
+ [ValidateSet(3000,5000,8000)]
+ [int]$port = 3000
+ )
+ BEGIN { Write-Output 'Creating new website(s)' }
+ PROCESS { Write-Output "name: $siteName, port: $port" }
+ END { Write-Output 'Website(s) created' }
+}
+
+
+####################################################
+## 5. Modules
+####################################################
+
+# You can import modules and install modules
+# The Install-Module is similar to pip or npm, pulls from Powershell Gallery
+Install-Module dbaTools
+Import-Module dbaTools
+
+$query = "SELECT * FROM dbo.sometable"
+$queryParams = @{
+ SqlInstance = 'testInstance'
+ Database = 'testDatabase'
+ Query = $query
+}
+Invoke-DbaQuery @queryParams
+
+# You can get specific functions from a module
+Import-Module -Function Invoke-DbaQuery
+
+
+# Powershell modules are just ordinary Posh files. You
+# can write your own, and import them. The name of the
+# module is the same as the name of the file.
+
+# You can find out which functions and attributes
+# are defined in a module.
+Get-Command -module dbaTools
+Get-Help dbaTools -Full
+
+
+####################################################
+## 6. Classes
+####################################################
+
+# We use the "class" statement to create a class
+class Instrument {
+ [string]$Type
+ [string]$Family
+}
+
+$instrument = [Instrument]::new()
+$instrument.Type = "String Instrument"
+$instrument.Family = "Plucked String"
+
+$instrument
+
+<# Output:
+Type Family
+---- ------
+String Instrument Plucked String
+#>
+
+
+####################################################
+## 6.1 Inheritance
+####################################################
+
+# Inheritance allows new child classes to be defined that inherit
+# methods and variables from their parent class.
+
+class Guitar : Instrument
+{
+ [string]$Brand
+ [string]$SubType
+ [string]$ModelType
+ [string]$ModelNumber
}
+$myGuitar = [Guitar]::new()
+$myGuitar.Brand = "Taylor"
+$myGuitar.SubType = "Acoustic"
+$myGuitar.ModelType = "Presentation"
+$myGuitar.ModelNumber = "PS14ce Blackwood"
+
+$myGuitar.GetType()
+
+<#
+IsPublic IsSerial Name BaseType
+-------- -------- ---- --------
+True False Guitar Instrument
+#>
+
+
+####################################################
+## 7. Advanced
+####################################################
+
+# The powershell pipeline allows things like High-Order Functions.
+
+# Group-Object is a handy cmdlet that does incredible things.
+# It works much like a GROUP BY in SQL.
+
+<#
+ The following will get all the running processes,
+ group them by Name,
+ and tell us how many instances of each process we have running.
+ Tip: Chrome and svcHost are usually big numbers in this regard.
+#>
+Get-Process | Foreach-Object ProcessName | Group-Object
+
+# Useful pipeline examples are iteration and filtering.
+1..10 | ForEach-Object { "Loop number $PSITEM" }
+1..10 | Where-Object { $PSITEM -gt 5 } | ConvertTo-Json
+
+# A notable pitfall of the pipeline is it's performance when
+# compared with other options.
+# Additionally, raw bytes are not passed through the pipeline,
+# so passing an image causes some issues.
+# See more on that in the link at the bottom.
+
+<#
+ Asynchronous functions exist in the form of jobs.
+ Typically a procedural language,
+ Powershell can operate non-blocking functions when invoked as Jobs.
+#>
+
+# This function is known to be non-optimized, and therefore slow.
+$installedApps = Get-CimInstance -ClassName Win32_Product
-### It's all .NET
-# A PS string is in fact a .NET System.String
-# All .NET methods and properties are thus available
-'string'.ToUpper().Replace('G', 'ggg')
-# Or more powershellish
-'string'.ToUpper() -replace 'G', 'ggg'
-
-# Unsure how that .NET method is called again?
-'string' | gm
-
-# Syntax for calling static .NET methods
-[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
-
-# Note that .NET functions MUST be called with parentheses
-# while PS functions CANNOT be called with parentheses.
-# If you do call a cmdlet/PS function with parentheses,
-# it is the same as passing a single parameter list
-$writer = New-Object System.IO.StreamWriter($path, $true)
-$writer.Write([Environment]::NewLine)
-$writer.Dispose()
-
-### IO
-# Reading a value from input:
-$Name = Read-Host "What's your name?"
-echo "Hello, $Name!"
-[int]$Age = Read-Host "What's your age?"
-
-# Test-Path, Split-Path, Join-Path, Resolve-Path
-# Get-Content filename # returns a string[]
-# Set-Content, Add-Content, Clear-Content
-Get-Command ConvertTo-*,ConvertFrom-*
-
-
-### Useful stuff
-# Refresh your PATH
-$env:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") +
- ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
-
-# Find Python in path
-$env:PATH.Split(";") | Where-Object { $_ -like "*python*"}
-
-# Change working directory without having to remember previous path
-Push-Location c:\temp # change working directory to c:\temp
-Pop-Location # change back to previous working directory
-# Aliases are: pushd and popd
-
-# Unblock a directory after download
-Get-ChildItem -Recurse | Unblock-File
-
-# You can also pass arguments to a Function with a hash table
-# This is called Splatting
-# Normal Command
-Export-Csv -InputObject $csv -Path 'c:\mypath' -Encoding UTF8 -NoTypeInformation
-# With Splatting
-$csvArguments = @{
- InputObject = $csv
- Path = 'c:\mypath'
- Encoding = 'UTF8'
- NoTypeInformation = $true
+# If we had a script, it would hang at this func for a period of time.
+$scriptBlock = {Get-CimInstance -ClassName Win32_Product}
+Start-Job -ScriptBlock $scriptBlock
+
+# This will start a background job that runs the command.
+# You can then obtain the status of jobs and their returned results.
+$allJobs = Get-Job
+$jobResponse = Get-Job | Receive-Job
+
+
+# Math is built in to powershell and has many functions.
+$r=2
+$pi=[math]::pi
+$r2=[math]::pow( $r, 2 )
+$area = $pi*$r2
+$area
+
+# To see all possibilities, check the members.
+[System.Math] | Get-Member -Static -MemberType All
+
+
+<#
+ This is a silly one:
+ You may one day be asked to create a func that could take $start and $end
+ and reverse anything in an array within the given range
+ based on an arbitrary array without mutating the original array.
+ Let's see one way to do that and introduce another data structure.
+#>
+
+$targetArray = 'a','b','c','d','e','f','g','h','i','j','k','l','m'
+
+function Format-Range ($start, $end, $array) {
+ [System.Collections.ArrayList]$firstSectionArray = @()
+ [System.Collections.ArrayList]$secondSectionArray = @()
+ [System.Collections.Stack]$stack = @()
+ for ($index = 0; $index -lt $array.Count; $index++) {
+ if ($index -lt $start) {
+ $firstSectionArray.Add($array[$index]) > $null
+ }
+ elseif ($index -ge $start -and $index -le $end) {
+ $stack.Push($array[$index])
+ }
+ else {
+ $secondSectionArray.Add($array[$index]) > $null
+ }
+ }
+ $finalArray = $firstSectionArray + $stack.ToArray() + $secondSectionArray
+ return $finalArray
+}
+
+Format-Range 2 6 $targetArray
+# => 'a','b','g','f','e','d','c','h','i','j','k','l','m'
+
+# The previous method works, but uses extra memory by allocating new arrays.
+# It's also kind of lengthy.
+# Let's see how we can do this without allocating a new array.
+# This is slightly faster as well.
+
+function Format-Range ($start, $end) {
+ while ($start -lt $end)
+ {
+ $temp = $targetArray[$start]
+ $targetArray[$start] = $targetArray[$end]
+ $targetArray[$end] = $temp
+ $start++
+ $end--
+ }
+ return $targetArray
}
-Export-Csv @csvArguments
-
-# Open Windows Explorer in working directory
-Invoke-Item .
-# Or the alias
-ii .
-
-# Any key to exit
-$host.UI.RawUI.ReadKey()
-return
-
-# Create a shortcut
-$WshShell = New-Object -comObject WScript.Shell
-$Shortcut = $WshShell.CreateShortcut($link)
-$Shortcut.TargetPath = $file
-$Shortcut.WorkingDirectory = Split-Path $file
-$Shortcut.Save()
+
+Format-Range 2 6 # => 'a','b','g','f','e','d','c','h','i','j','k','l','m'
```
+Powershell as a Tool:
+
+Getting Help:
+```Powershell
+# Find commands
+Get-Command about_* # alias: gcm
+Get-Command -Verb Add
+Get-Alias ps
+Get-Alias -Definition Get-Process
-Configuring your shell
+Get-Help ps | less # alias: help
+ps | Get-Member # alias: gm
-```powershell
-# $Profile is the full path for your `Microsoft.PowerShell_profile.ps1`
-# All code there will be executed when the PS session starts
-if (-not (Test-Path $Profile)) {
- New-Item -Type file -Path $Profile -Force
- notepad $Profile
+Show-Command Get-WinEvent # Display GUI to fill in the parameters
+
+Update-Help # Run as admin
+```
+
+If you are uncertain about your environment:
+
+```Powershell
+Get-ExecutionPolicy -List
+Set-ExecutionPolicy AllSigned
+# Execution policies include:
+# - Restricted: Scripts won't run.
+# - RemoteSigned: Downloaded scripts run only if signed by a trusted publisher.
+# - AllSigned: Scripts need to be signed by a trusted publisher.
+# - Unrestricted: Run all scripts.
+help about_Execution_Policies # for more info
+
+# Current PowerShell version:
+$PSVersionTable
+```
+
+```Powershell
+# Calling external commands, executables,
+# and functions with the call operator.
+# Exe paths with arguments passed or containing spaces can create issues.
+C:\Program Files\dotnet\dotnet.exe
+# The term 'C:\Program' is not recognized as a name of a cmdlet,
+# function, script file, or executable program.
+# Check the spelling of the name, or if a path was included,
+# verify that the path is correct and try again
+
+"C:\Program Files\dotnet\dotnet.exe"
+C:\Program Files\dotnet\dotnet.exe # returns string rather than execute
+
+&"C:\Program Files\dotnet\dotnet.exe --help" # fail
+&"C:\Program Files\dotnet\dotnet.exe" --help # success
+# Alternatively, you can use dot-sourcing here
+."C:\Program Files\dotnet\dotnet.exe" --help # success
+
+# the call operator (&) is similar to Invoke-Expression,
+# but IEX runs in current scope.
+# One usage of '&' would be to invoke a scriptblock inside of your script.
+# Notice the variables are scoped
+$i = 2
+$scriptBlock = { $i=5; Write-Output $i }
+& $scriptBlock # => 5
+$i # => 2
+
+invoke-expression ' $i=5; Write-Output $i ' # => 5
+$i # => 5
+
+# Alternatively, to preserve changes to public variables
+# you can use "Dot-Sourcing". This will run in the current scope.
+$x=1
+&{$x=2};$x # => 1
+
+.{$x=2};$x # => 2
+
+
+# Remoting into computers is easy.
+Enter-PSSession -ComputerName RemoteComputer
+
+# Once remoted in, you can run commands as if you're local.
+RemoteComputer\PS> Get-Process powershell
+
+<#
+Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
+------- ------ ----- ----- ------ -- -- -----------
+ 1096 44 156324 179068 29.92 11772 1 powershell
+ 545 25 49512 49852 25348 0 powershell
+#>
+RemoteComputer\PS> Exit-PSSession
+
+<#
+ Powershell is an incredible tool for Windows management and Automation.
+ Let's take the following scenario:
+ You have 10 servers.
+ You need to check whether a service is running on all of them.
+ You can RDP and log in, or PSSession to all of them, but why?
+ Check out the following
+#>
+
+$serverList = @(
+ 'server1',
+ 'server2',
+ 'server3',
+ 'server4',
+ 'server5',
+ 'server6',
+ 'server7',
+ 'server8',
+ 'server9',
+ 'server10'
+)
+
+[scriptblock]$script = {
+ Get-Service -DisplayName 'Task Scheduler'
+}
+
+foreach ($server in $serverList) {
+ $cmdSplat = @{
+ ComputerName = $server
+ JobName = 'checkService'
+ ScriptBlock = $script
+ AsJob = $true
+ ErrorAction = 'SilentlyContinue'
+ }
+ Invoke-Command @cmdSplat | Out-Null
}
-# More info: `help about_profiles`
-# For a more useful shell, be sure to check the project PSReadLine below
+
+<#
+ Here we've invoked jobs across many servers.
+ We can now Receive-Job and see if they're all running.
+ Now scale this up 100x as many servers :)
+#>
```
Interesting Projects
* [Channel9](https://channel9.msdn.com/Search?term=powershell%20pipeline#ch9Search&lang-en=en) PowerShell tutorials
+* [KevinMarquette's Powershell Blog](https://powershellexplained.com/) Excellent blog that goes into great detail on Powershell
* [PSGet](https://github.com/psget/psget) NuGet for PowerShell
* [PSReadLine](https://github.com/lzybkr/PSReadLine/) A bash inspired readline implementation for PowerShell (So good that it now ships with Windows10 by default!)
* [Posh-Git](https://github.com/dahlbyk/posh-git/) Fancy Git Prompt (Recommended!)
@@ -350,10 +804,4 @@ Interesting Projects
* [Pester](https://github.com/pester/Pester) BDD Testing Framework
* [Jump-Location](https://github.com/tkellogg/Jump-Location) Powershell `cd` that reads your mind
* [PowerShell Community Extensions](https://github.com/Pscx/Pscx)
-
-Not covered
-
-* WMI: Windows Management Intrumentation (Get-CimInstance)
-* Multitasking: Start-Job -scriptBlock {...},
-* Code Signing
-* Remoting (Enter-PSSession/Exit-PSSession; Invoke-Command)
+* [More on the Powershell Pipeline Issue](https://github.com/PowerShell/PowerShell/issues/1908)
diff --git a/pt-br/awk-pt.html.markdown b/pt-br/awk-pt.html.markdown
index 9bf770fd..70d0a01c 100644
--- a/pt-br/awk-pt.html.markdown
+++ b/pt-br/awk-pt.html.markdown
@@ -317,8 +317,8 @@ a > 0 {
# Aqui está um exemplo rápido de um script simples, o tipo de coisa que o AWK
# é perfeito para fazer. Ele irá ler um nome da entrada padrão e depois
-imprimirá a média de idade de todos com esse primeiro nome. Digamos que você
-forneça como argumento o nome de um arquivo com esses dados:
+# imprimirá a média de idade de todos com esse primeiro nome. Digamos que você
+# forneça como argumento o nome de um arquivo com esses dados:
# Bob Jones 32
# Jane Doe 22
diff --git a/pt-br/bash-pt.html.markdown b/pt-br/bash-pt.html.markdown
index 86d1a8ea..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.
@@ -47,7 +47,7 @@ Variavel = "Alguma string"
# Ou assim:
Variavel= 'Alguma string'
# Bash interpretará 'Alguma string' como um comando e tentará executar e lhe retornará
-# um erro porque o comando não pode ser encontrado. (Nesse caso a a parte 'Variavel='
+# um erro porque o comando não pôde ser encontrado. (Nesse caso a a parte 'Variavel='
# é vista com uma declaração de variável válida apenas para o escopo do comando 'Uma string').
# Usando a variável:
@@ -73,7 +73,7 @@ echo ${Foo:-"ValorPadraoSeFooNaoExistirOuEstiverVazia"}
# Note que isso apenas retornará o valor padrão e não mudará o valor da variável.
# Variáveis internas
-# Tem algumas variáveis internas bem uteis, como
+# Tem algumas variáveis internas bem úteis, como
echo "O ultimo retorno do programa: $?"
echo "PID do script: $$"
echo "Numero de argumentos passados para o script $#"
@@ -165,7 +165,7 @@ echo "#helloworld" | tee output.out > /dev/null
rm -v output.out error.err output-and-error.log
# Comando podem ser substituídos por outros comandos usando $( ):
-# O comando a seguir mostra o número de arquivos e diretórios no diretorio atual
+# O comando a seguir mostra o número de arquivos e diretórios no diretório atual
echo "Existem $(ls | wc -l) itens aqui."
# O mesmo pode ser feito usando crase `` mas elas não podem ser aninhadas - dá se
@@ -248,7 +248,7 @@ sed -i 's/okay/legal/g' file.txt
# exibe para o stdout todas as linhas do arquivo.txt que encaixam com o regex
# O exemplo exibe linhas que começam com "foo" e terminam com "bar"
grep "^foo.*bar$" arquivo.txt
-# passe a opção "-c" para ao invês de imprimir o numero da linha que bate com o regex
+# passe a opção "-c" para ao invés de imprimir o número da linha que bate com o regex
grep -c "^foo.*bar$" arquivo.txt
# se você quer literalmente procurar por uma string,
# e não pelo regex, use fgrep (ou grep -F)
diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown
index 38937894..e6dea5b8 100644
--- a/pt-br/css-pt.html.markdown
+++ b/pt-br/css-pt.html.markdown
@@ -14,7 +14,7 @@ translators:
lang: pt-br
---
-No início da web não havia elementos visuais, apenas texto puro. Mas com maior desenvolvimento de navegadores da web, páginas web totalmente visuais também se tornara comum.
+No início da web não havia elementos visuais, apenas texto puro. Mas com maior desenvolvimento de navegadores da web, páginas web totalmente visuais também se tornaram comuns.
CSS ajuda a manter a separação entre o conteúdo (HTML) e o visual de uma página web.
@@ -130,7 +130,7 @@ seletor::after {}
   os elementos */
* {} /* */ Todos os elementos
.parent * {} /* */ todos os descendentes
-.parent> * {} /* */ todas as crianças
+.parent> * {} /* */ todos os filhos
/* ####################
   ## PROPRIEDADES
@@ -141,7 +141,7 @@ seletor {
    /* Unidades de comprimento pode ser absoluta ou relativa. */
    /* Unidades relativas */
-    width: 50%; /* Percentagem de largura elemento pai */
+    width: 50%; /* Percentagem de largura do elemento pai */
    font-size: 2em; /* Múltiplos de font-size original de elemento */
    font-size: 2rem; /* Ou do elemento raiz font-size */
    font-size: 2vw; /* Múltiplos de 1% da largura da janela de exibição (CSS 3) */
@@ -200,7 +200,7 @@ Salvar uma folha de estilo CSS com a extensão `.css`.
## Precedência ou Cascata
-Um elemento pode ser alvo de vários seletores e pode ter um conjunto de propriedades em que mais de uma vez. Nestes casos, uma das regras tem precedência sobre os outros. Geralmente, uma regra em um seletor mais específico têm precedência sobre um menos específico, e uma regra que ocorre mais tarde na folha de estilo substitui uma anterior.
+Um elemento pode ser alvo de vários seletores e pode ter um conjunto de propriedades em que mais de uma vez. Nestes casos, uma das regras tem precedência sobre as outras. Geralmente, uma regra em um seletor mais específico têm precedência sobre um menos específico, e uma regra que ocorre mais tarde na folha de estilo substitui uma anterior.
Este processo é chamado de cascata, portanto, as Fichas de nome de estilo em cascata.
@@ -279,7 +279,7 @@ Muitos smartphones e tablets tentarão renderizar a página como se estivesse nu
## Compatibilidade
-A maior parte dos recursos do CSS 2 (e muitos em CSS 3) estão disponíveis em todos os navegadores e dispositivos. Mas é sempre boa prática para verificar antes de usar um novo recurso.
+A maior parte dos recursos do CSS 2 (e muitos em CSS 3) estão disponíveis em todos os navegadores e dispositivos. Mas é sempre boa prática verificar antes de usar um novo recurso.
## Recursos
diff --git a/pt-br/elixir-pt.html.markdown b/pt-br/elixir-pt.html.markdown
index f8c56101..4ba78f52 100644
--- a/pt-br/elixir-pt.html.markdown
+++ b/pt-br/elixir-pt.html.markdown
@@ -40,7 +40,7 @@ e muitos outros recursos.
# Tuplas que são guardadas contiguamente em memória.
{1,2,3} # tupla
-# Podemos acessar um elemento de uma tupla om a função `elem`:
+# Podemos acessar um elemento de uma tupla com a função `elem`:
elem({1, 2, 3}, 0) #=> 1
# Listas que são implementadas como listas ligadas.
diff --git a/pt-br/fsharp-pt.html.markdown b/pt-br/fsharp-pt.html.markdown
new file mode 100644
index 00000000..55966cda
--- /dev/null
+++ b/pt-br/fsharp-pt.html.markdown
@@ -0,0 +1,639 @@
+---
+language: F#
+filename: learnfsharp-pt.fs
+contributors:
+ - ["Scott Wlaschin", "http://fsharpforfunandprofit.com"]
+ - ["Adelar da Silva Queiróz", "https://adelarsq.github.io"]
+lang: pt-br
+---
+
+F# é uma linguagem de propósito geral funcional e orientada a objetos. É livre, de código aberto e executa em Linux, Mac, Windows e outros.
+
+Possui um sistema de tipagem poderoso que evita muitos erros em tempo de compilação. Para isto utilizando inferência de tipos, o que a faz se comportar como uma linguagem dinâmica.
+
+A sintaxe é diferente das linguagens do estilo C (C, C#, Java, etc):
+
+* Chaves não são usadas para delimitar blocos de código. Ao invés disso é utilizada indentação (semelhante ao Python).
+* Espaços em branco são usados para separar parâmetros, ao invés de vírgulas.
+
+Se você deseja executar o código abaixo, copie e cole em [https://try.fsharp.org](https://try.fsharp.org), que é um REPL online.
+
+```fsharp
+
+// comentários de linhas únicas usam barras duplas
+(* comentários de linhas múltiplas usam o par (* . . . *)
+
+-fim do comentário de linhas múltiplas- *)
+
+// ================================================
+// Sintaxe básica
+// ================================================
+
+// ------ "Variáveis" (mas não exatamente) ------
+// A palavra reservada "let" define um valor imutável
+let myInt = 5
+let myFloat = 3.14
+let myString = "hello" // note que nenhum tipo é necessário
+
+// ------ Listas ------
+let twoToFive = [2; 3; 4; 5] // Colchetes criam uma lista com
+ // ponto e vírgula como delimitadores
+let oneToFive = 1 :: twoToFive // :: cria uma lista com um novo primeiro elemento
+// O resultado é [1; 2; 3; 4; 5]
+let zeroToFive = [0; 1] @ twoToFive // @ concatena duas listas
+
+// IMPORTANTE: vírgulas nunca são usadas como delimitadores, somente ponto e vírgula!
+
+// ------ Funções ------
+// A palavra chave "let" também define nomes para funções.
+let square x = x * x // Note que não são usados parêntesis
+square 3 // Agora executando a função. Também sem parêntesis
+
+let add x y = x + y // Não use add (x,y)! Isto significa algo
+ // completamente diferente.
+add 2 3 // Agora execute a função.
+
+// para definir uma função de múltiplas linhas apenas use indentação. Nenhum ponto e vírgula é necessário
+let evens list =
+ let isEven x = x % 2 = 0 // Define "isEven"como uma sub função. Note
+ // que o operador de igualdade é um simples "=".
+ List.filter isEven list // List.filter é uma função da biblioteca padrão
+ // com dois parâmetros: uma função que retorna boolean
+ // e uma lista para verificar
+
+evens oneToFive // Agora executando a função
+
+// Usando parênteses é possível deixar mais clara a precedência. Neste exemplo,
+// "map" é usado primeiro, com dois argumentos, então executa "sum" no resultado.
+// Sem os parênteses, "List.map" seria passado como uma argumento para List.sum
+let sumOfSquaresTo100 =
+ List.sum ( List.map square [1..100] )
+
+// É possível redirecionar a saída de uma operação para a próxima usando pipe ("|>")
+// Redirecimento de dados é algo comum em F#, similar a pipes Unix.
+
+// Aqui é a mesma função sumOfSquares escrita com pipe
+let sumOfSquaresTo100piped =
+ [1..100] |> List.map square |> List.sum // "square" foi definido anteriormente
+
+// você pode definir lambdas (funções anônimas) usando a palavra reservada "fun"
+let sumOfSquaresTo100withFun =
+ [1..100] |> List.map (fun x -> x * x) |> List.sum
+
+// Em F# não há a palavra chave "return". Funções sempre
+// retornam o valor da última expressão usada.
+
+// ------ Casamento de padrões (Pattern Matching) ------
+// Match..with.. é um poderoso case/switch.
+let simplePatternMatch =
+ let x = "a"
+ match x with
+ | "a" -> printfn "x is a"
+ | "b" -> printfn "x is b"
+ | _ -> printfn "x is something else" // sublinhado combina com qualquer coisa
+
+// F# não permite null por padrão -- deve-se usar um Option
+// e então efetuar um casamento de padrão.
+// Some(..) e None são análogos a Nullable
+let validValue = Some(99)
+let invalidValue = None
+
+// Neste exemplo, match..with casa com "Some" e "None",
+// e também desconstrói o valor em "Some" ao mesmo tempo.
+let optionPatternMatch input =
+ match input with
+ | Some i -> printfn "input is an int=%d" i
+ | None -> printfn "input is missing"
+
+optionPatternMatch validValue
+optionPatternMatch invalidValue
+
+// ------ Escrevando na tela ------
+// As funções printf/printfn são similares às
+// Console.Write/WriteLine encontradas no C#.
+printfn "Printing an int %i, a float %f, a bool %b" 1 2.0 true
+printfn "A string %s, and something generic %A" "hello" [1; 2; 3; 4]
+
+// Exitem também as funções sprintf/sprintfn para formatação de dados
+// em uma string, semelhante à String.Format do C#.
+
+// ================================================
+// Mais sobre funções
+// ================================================
+
+// F# é uma liguagem verdadeiramente funcional -- funções fazem
+// parte das classes e podem ser combinadas facilmente para criar
+// poderosos construtores
+
+// Módulos podem usar um grupo de funções
+// É necessário usar indentação para defini-las.
+module FunctionExamples =
+
+ // define uma função de soma
+ let add x y = x + y
+
+ // básico uso de uma função
+ let a = add 1 2
+ printfn "1 + 2 = %i" a
+
+ // aplicação parcial de parâmetros
+ let add42 = add 42
+ let b = add42 1
+ printfn "42 + 1 = %i" b
+
+ // composição para combinar funções
+ let add1 = add 1
+ let add2 = add 2
+ let add3 = add1 >> add2
+ let c = add3 7
+ printfn "3 + 7 = %i" c
+
+ // funções de alta ordem
+ [1..10] |> List.map add3 |> printfn "new list is %A"
+
+ // listas de funções e mais
+ let add6 = [add1; add2; add3] |> List.reduce (>>)
+ let d = add6 7
+ printfn "1 + 2 + 3 + 7 = %i" d
+
+// ================================================
+// Listas e coleções
+// ================================================
+
+// Existem três tipos de coleções ordenadas:
+// * Listas são o tipo mais básico de coleção imutável;
+// * Arrays são mutáveis e mais eficientes;
+// * Sequences são lazy e infinitas (semelhante a enumerator).
+//
+// Outras coleções incluem maps e conjuntos imutáveis
+// mais todas as coleções padrões do .NET
+
+module ListExamples =
+
+ // listas usam colchetes
+ let list1 = ["a"; "b"]
+ let list2 = "c" :: list1 // :: é usado para adicionar um elemento no início da lista
+ let list3 = list1 @ list2 // @ é o operador de concatenação
+
+ // list comprehensions (generators)
+ let squares = [for i in 1..10 do yield i * i]
+
+ // Um gerador de números primos
+ // - este usa a notação custa para casamento de padrões
+ // - (p::xs) significa 'primeiro :: cauda' da lista, e pode ser escrito como p :: xs
+ // isto significa que casa 'p' (o primeiro item da lista), e xs recebe o resto da lista
+ // que é chamdo de 'cons pattern'
+ // - usa a palavra chave 'rec', que é necessária quando se usa recursão
+ let rec sieve = function
+ | (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ]
+ | [] -> []
+ let primes = sieve [2..50]
+ printfn "%A" primes
+
+ // casamento de padrões (pattern matching) com listas
+ let listMatcher aList =
+ match aList with
+ | [] -> printfn "the list is empty"
+ | [first] -> printfn "the list has one element %A " first
+ | [first; second] -> printfn "list is %A and %A" first second
+ | first :: _ -> printfn "the list has more than two elements, first element %A" first
+
+ listMatcher [1; 2; 3; 4]
+ listMatcher [1; 2]
+ listMatcher [1]
+ listMatcher []
+
+ // recursão usando listas
+ let rec sum aList =
+ match aList with
+ | [] -> 0
+ | x::xs -> x + sum xs
+ sum [1..10]
+
+ // -----------------------------------------
+ // Funções da biblioteca padrão
+ // -----------------------------------------
+
+ // mapas
+ let add3 x = x + 3
+ [1..10] |> List.map add3
+
+ // filtros
+ let even x = x % 2 = 0
+ [1..10] |> List.filter even
+
+ // muito mais -- veja a documentação
+
+module ArrayExamples =
+
+ // arrays usam colchetes com barra vertical
+ let array1 = [| "a"; "b" |]
+ let first = array1.[0] // acesso por índice usando ponto
+
+ // casamento de padrões (pattern matching) para arrays é feito da mesma forma que de listas
+ let arrayMatcher aList =
+ match aList with
+ | [| |] -> printfn "the array is empty"
+ | [| first |] -> printfn "the array has one element %A " first
+ | [| first; second |] -> printfn "array is %A and %A" first second
+ | _ -> printfn "the array has more than two elements"
+
+ arrayMatcher [| 1; 2; 3; 4 |]
+
+ // As funções da biblioteca padrão são as mesmas que para List
+
+ [| 1..10 |]
+ |> Array.map (fun i -> i + 3)
+ |> Array.filter (fun i -> i % 2 = 0)
+ |> Array.iter (printfn "value is %i. ")
+
+
+module SequenceExamples =
+
+ // sequências usam chaves
+ let seq1 = seq { yield "a"; yield "b" }
+
+ // sequências podem usar yield e
+ // podem conter subsequencias
+ let strange = seq {
+ // "yield" adiciona um elemento
+ yield 1; yield 2;
+
+ // "yield!" adiciona uma subsequencia
+ yield! [5..10]
+ yield! seq {
+ for i in 1..10 do
+ if i % 2 = 0 then yield i }}
+ // teste
+ strange |> Seq.toList
+
+ // Sequências podem ser criadas usando "unfold"
+ // Este é um exemplo da série de Fibonacci
+ let fib = Seq.unfold (fun (fst,snd) ->
+ Some(fst + snd, (snd, fst + snd))) (0,1)
+
+ // teste
+ let fib10 = fib |> Seq.take 10 |> Seq.toList
+ printf "first 10 fibs are %A" fib10
+
+
+// ================================================
+// Tipos de dados
+// ================================================
+
+module DataTypeExamples =
+
+ // Todos os dados são imutáveis por padrão
+
+ // Tuplas são uma forma rápida de reprentar n elementos de tipos anônimos
+ // -- Use a vírgula para criar uma tupla
+ let twoTuple = 1, 2
+ let threeTuple = "a", 2, true
+
+ // Casamento de padrões (pattern match) para desconstruir
+ let x, y = twoTuple // atribui x = 1, y = 2
+
+ // ------------------------------------
+ // O tipo registro possui nomes nos campos
+ // ------------------------------------
+
+ // Use "type" com chaves para definir um registro
+ type Person = {First:string; Last:string}
+
+ // Use "let" com chaves para criar um registro
+ let person1 = {First="John"; Last="Doe"}
+
+ // Casamento de padrões para desconstruir
+ let {First = first} = person1 // atribui first="John"
+
+ // ------------------------------------
+ // Tipos union (variantes) possuem um conjunto de escolhas
+ // Somente um caso pode ser válido por vez.
+ // ------------------------------------
+
+ // Use "type" com barra/pipe para definir um union
+ type Temp =
+ | DegreesC of float
+ | DegreesF of float
+
+ // Use qualquer dos tipos para criar um
+ let temp1 = DegreesF 98.6
+ let temp2 = DegreesC 37.0
+
+ // Casamento de padrões deve cobrir todos os tipos de definidos para desconstruir
+ let printTemp = function
+ | DegreesC t -> printfn "%f degC" t
+ | DegreesF t -> printfn "%f degF" t
+
+ printTemp temp1
+ printTemp temp2
+
+ // ------------------------------------
+ // Tipos recursivos
+ // ------------------------------------
+
+ // Tipos podem ser combinados recursivamente de formas complexas
+ // sem ter que criar subclasses
+ type Employee =
+ | Worker of Person
+ | Manager of Employee list
+
+ let jdoe = {First="John"; Last="Doe"}
+ let worker = Worker jdoe
+
+ // ------------------------------------
+ // Modelando com tipos
+ // ------------------------------------
+
+ // Tipos union são muito bons para modelagem de estados sem usar flags
+ type EmailAddress =
+ | ValidEmailAddress of string
+ | InvalidEmailAddress of string
+
+ let trySendEmail email =
+ match email with // casamento de padrões
+ | ValidEmailAddress address -> () // envia
+ | InvalidEmailAddress address -> () // não envia
+
+ // A combinação de tipos union e registros juntos
+ // provê uma grande fundação para DDD (Domain Driven Design).
+ // Você pode criar centenas de pequenos tipos que refletem
+ // exatamente o seu domínio.
+
+ type CartItem = { ProductCode: string; Qty: int }
+ type Payment = Payment of float
+ type ActiveCartData = { UnpaidItems: CartItem list }
+ type PaidCartData = { PaidItems: CartItem list; Payment: Payment}
+
+ type ShoppingCart =
+ | EmptyCart // nenhum dado
+ | ActiveCart of ActiveCartData
+ | PaidCart of PaidCartData
+
+ // ------------------------------------
+ // Comportamento padrão para tipos
+ // ------------------------------------
+
+ // Tipos padrões possuem um padrão já definido, não precisando de codificação nenhuma.
+ // * Imutáveis
+ // * Impressão formatada para depuração
+ // * Igualdade e comparação
+ // * Serialização
+
+ // Impressão formatada usando %A
+ printfn "twoTuple=%A,\nPerson=%A,\nTemp=%A,\nEmployee=%A"
+ twoTuple person1 temp1 worker
+
+ // Igualdade e comparação padrão.
+ // Um exemplo com cartas:
+ type Suit = Club | Diamond | Spade | Heart
+ type Rank = Two | Three | Four | Five | Six | Seven | Eight
+ | Nine | Ten | Jack | Queen | King | Ace
+
+ let hand = [ Club, Ace; Heart, Three; Heart, Ace;
+ Spade, Jack; Diamond, Two; Diamond, Ace ]
+
+ // ordenando
+ List.sort hand |> printfn "sorted hand is (low to high) %A"
+ List.max hand |> printfn "high card is %A"
+ List.min hand |> printfn "low card is %A"
+
+
+// ================================================
+// Padrões ativos (Active patterns)
+// ================================================
+
+module ActivePatternExamples =
+
+ // F# possui um tipo especial de casamento de padrões chamado "padrões ativos" ("active patterns")
+ // onde o padrão pode ser interpretado ou detectado dinamicamente.
+
+ // parêntesis e barra são a sintaxe para "padrões ativos"
+
+ // Você pode usar "elif" ao invés de "else if" em expressões condicionais.
+ // Elas são equivalentes em F#
+
+ // por exemplo, defina um "padrão ativo" para tratar tipos de caracteres...
+ let (|Digit|Letter|Whitespace|Other|) ch =
+ if System.Char.IsDigit(ch) then Digit
+ elif System.Char.IsLetter(ch) then Letter
+ elif System.Char.IsWhiteSpace(ch) then Whitespace
+ else Other
+
+ // ... e então use ele para interpretar de forma bem mais simples
+ let printChar ch =
+ match ch with
+ | Digit -> printfn "%c is a Digit" ch
+ | Letter -> printfn "%c is a Letter" ch
+ | Whitespace -> printfn "%c is a Whitespace" ch
+ | _ -> printfn "%c is something else" ch
+
+ // imprima a lista
+ ['a'; 'b'; '1'; ' '; '-'; 'c'] |> List.iter printChar
+
+ // ------------------------------------------------
+ // FizzBuzz usando padrões ativos (active patterns)
+ // ------------------------------------------------
+
+ // É possível criar casamento de padrões parcial também
+ // Apenas use sublinhado para a definição, e retorne Some se casado.
+ let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None
+ let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None
+
+ // a função principal
+ let fizzBuzz i =
+ match i with
+ | MultOf3 & MultOf5 -> printf "FizzBuzz, "
+ | MultOf3 -> printf "Fizz, "
+ | MultOf5 -> printf "Buzz, "
+ | _ -> printf "%i, " i
+
+ // teste
+ [1..20] |> List.iter fizzBuzz
+
+// ================================================
+// Expressividade
+// ================================================
+
+module AlgorithmExamples =
+
+ // F# possui uma alta razão sinais/ruídos, assim o código
+ // é lido praticamento como se descreve o algoritmo
+
+ // ------ Exemplo: defina uma função que faça soma dos quadrados ------
+ let sumOfSquares n =
+ [1..n] // 1) pega todos os números de 1 a n
+ |> List.map square // 2) eleva ao quadrado cada um
+ |> List.sum // 3) soma os resultados
+
+ // teste
+ sumOfSquares 100 |> printfn "Sum of squares = %A"
+
+ // ------ Examplo: defina uma função de ordenação ------
+ let rec sort list =
+ match list with
+ // Se a lista está vazia
+ | [] ->
+ [] // retorna a lista vazia
+ // Se a lista não está vazia
+ | firstElem::otherElements -> // pega o primeiro elemento
+ let smallerElements = // extrai os elementos menores
+ otherElements // dos restantes
+ |> List.filter (fun e -> e < firstElem)
+ |> sort // e ordena eles
+ let largerElements = // extrai os elementos maiores
+ otherElements // dos restantes
+ |> List.filter (fun e -> e >= firstElem)
+ |> sort // e ordena eles
+ // Combine as 3 partes em uma nova lista e retorne ela
+ List.concat [smallerElements; [firstElem]; largerElements]
+
+ // teste
+ sort [1; 5; 23; 18; 9; 1; 3] |> printfn "Sorted = %A"
+
+// ================================================
+// Código assíncrono
+// ================================================
+
+module AsyncExample =
+
+ // F# possui suporte a funcionalidades para ajudar a escrever código assíncrono
+ // sem tornar o código difícil de manter ("pyramid of doom")
+ //
+ // O seguinte exemplo efetua download de um conjunto de páginas em paralelo.
+
+ open System.Net
+ open System
+ open System.IO
+ open Microsoft.FSharp.Control.CommonExtensions
+
+ // Obtém o conteúdo de cara página de forma assíncrona
+ let fetchUrlAsync url =
+ async { // a palavra chave "async" e chaves
+ // criam um objeto assíncrono
+ let req = WebRequest.Create(Uri(url))
+ use! resp = req.AsyncGetResponse()
+ // use! é uma atribuição assíncrona
+ use stream = resp.GetResponseStream()
+ // "use" dispara automaticamente close()
+ // no recurso no fim do escopo
+ use reader = new IO.StreamReader(stream)
+ let html = reader.ReadToEnd()
+ printfn "finished downloading %s" url
+ }
+
+ // uma lista de sites para fazer download
+ let sites = ["http://www.bing.com";
+ "http://www.google.com";
+ "http://www.microsoft.com";
+ "http://www.amazon.com";
+ "http://www.yahoo.com"]
+
+ // efetue
+ sites
+ |> List.map fetchUrlAsync // cria uma lista de tarefas assíncronas
+ |> Async.Parallel // coloca as tarefas para executarem em paralelo
+ |> Async.RunSynchronously // inicia cada uma
+
+// ================================================
+// Compatibilidade com .NET
+// ================================================
+
+module NetCompatibilityExamples =
+
+ // F# pode pode fazer praticamente tudo que C# pode fazer, e integra
+ // de forma simples com bibliotecas .NET e Mono
+
+ // ------- usando uma função de uma biblioteca existente -------
+
+ let (i1success, i1) = System.Int32.TryParse("123");
+ if i1success then printfn "parsed as %i" i1 else printfn "parse failed"
+
+ // ------- Implementando interfaces de forma simples! -------
+
+ // cria um novo objeto que implementa IDisposable
+ let makeResource name =
+ { new System.IDisposable
+ with member this.Dispose() = printfn "%s disposed" name }
+
+ let useAndDisposeResources =
+ use r1 = makeResource "first resource"
+ printfn "using first resource"
+ for i in [1..3] do
+ let resourceName = sprintf "\tinner resource %d" i
+ use temp = makeResource resourceName
+ printfn "\tdo something with %s" resourceName
+ use r2 = makeResource "second resource"
+ printfn "using second resource"
+ printfn "done."
+
+ // ------- Código orientado a objetos -------
+
+ // F# também possui suporte a orientação a objetos.
+ // Possui suporte a classes, herança, métodos virtuais, etc.
+
+ // interface com tipo genérico
+ type IEnumerator<'a> =
+ abstract member Current : 'a
+ abstract MoveNext : unit -> bool
+
+ // classe base abstrata com métodos virtuais
+ [<AbstractClass>]
+ type Shape() =
+ // propriedades somente leitura
+ abstract member Width : int with get
+ abstract member Height : int with get
+ // método não virtual
+ member this.BoundingArea = this.Height * this.Width
+ // método virtual com implementação base
+ abstract member Print : unit -> unit
+ default this.Print () = printfn "I'm a shape"
+
+ // classe concreta que herda da classe base e sobrescreve
+ type Rectangle(x:int, y:int) =
+ inherit Shape()
+ override this.Width = x
+ override this.Height = y
+ override this.Print () = printfn "I'm a Rectangle"
+
+ // testes
+ let r = Rectangle(2, 3)
+ printfn "The width is %i" r.Width
+ printfn "The area is %i" r.BoundingArea
+ r.Print()
+
+ // ------- métodos de extensão -------
+
+ // Assim como em C#, F# pode extender classes já existentes com métodos de extensão.
+ type System.String with
+ member this.StartsWithA = this.StartsWith "A"
+
+ // testes
+ let s = "Alice"
+ printfn "'%s' starts with an 'A' = %A" s s.StartsWithA
+
+ // ------- eventos -------
+
+ type MyButton() =
+ let clickEvent = new Event<_>()
+
+ [<CLIEvent>]
+ member this.OnClick = clickEvent.Publish
+
+ member this.TestEvent(arg) =
+ clickEvent.Trigger(this, arg)
+
+ // teste
+ let myButton = new MyButton()
+ myButton.OnClick.Add(fun (sender, arg) ->
+ printfn "Click event with arg=%O" arg)
+
+ myButton.TestEvent("Hello World!")
+
+```
+
+## Mais Informações
+
+Para mais demonstrações de F# acesse [why use F#](http://fsharpforfunandprofit.com/why-use-fsharp/).
+
+Leia mais sobre F# em [fsharp.org](http://fsharp.org/) e [dotnet's F# page](https://dotnet.microsoft.com/languages/fsharp).
diff --git a/pt-br/groovy-pt.html.markdown b/pt-br/groovy-pt.html.markdown
index 1eab9cc3..3acfce21 100644
--- a/pt-br/groovy-pt.html.markdown
+++ b/pt-br/groovy-pt.html.markdown
@@ -14,7 +14,7 @@ Groovy - Uma linguagem dinâmica para a plataforma Java. [Leia mais aqui.](http:
```groovy
/*
- Prepara-se:
+ Prepare-se:
1) Instale a máquina virtual de Groovy - http://gvmtool.net/
2) Instale o Groovy: gvm install groovy
@@ -104,7 +104,7 @@ tecnologiasOrdenadas = tecnologias.sort( false )
/*** Manipulando listas ***/
-//Substitue todos os elementos da lista
+//Substitui todos os elementos da lista
Collections.replaceAll(tecnologias, 'Gradle', 'gradle')
//Desorganiza a lista
@@ -159,7 +159,7 @@ println devMap.values()
usará este campo.
* Se você quer uma propriedade private ou protected, você deve prover seus
- próprios getters e setter, que devem ser declarados como private ou protected.
+ próprios getters e setters, que devem ser declarados como private ou protected.
* Se você acessar uma propriedade dentro da classe e esta propriedade é definida
em tempo de compilação com 'this', implícito ou explícito (por exemplo,
@@ -236,7 +236,7 @@ assert x.equals("Roberto Grails Groovy ")
/*
Operadores
- Sobrecarregamento de Operadores para uma lsita dos operadores comuns que
+ Sobrecarga de Operadores para uma lista dos operadores comuns que
Grooby suporta:
http://www.groovy-lang.org/operators.html#Operator-Overloading
@@ -254,7 +254,7 @@ def nomeUsuario = usuario?.nomeUsuario
/*
Closures
- Um closure, em Grooby, é como um "bloco de código" ou um ponteiro para método.
+ Um closure, em Groovy, é como um "bloco de código" ou um ponteiro para método.
É um pedação de código que é definido e executado em um momento posterior.
Mais informação em: http://www.groovy-lang.org/closures.html
@@ -269,7 +269,7 @@ clos()
def soma = { a, b -> println a+b }
soma(2,4)
-//Closdures por referir-se a variáveis que não estão listadas em sua
+//Closures podem referir-se a variáveis que não estão listadas em sua
//lista de parêmetros.
def x = 5
def multiplicarPor = { num -> num * x }
@@ -309,7 +309,7 @@ chamaClosure(3, 4)
/*
Expando
- A classe Expando é um bean dinâmico que permite adicionar propriedade e
+ A classe Expando é um bean dinâmico que permite adicionar propriedades e
closures como métodos a uma instância desta classe
http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html
diff --git a/pt-br/julia-pt.html.markdown b/pt-br/julia-pt.html.markdown
index 11771d96..52675bf5 100644
--- a/pt-br/julia-pt.html.markdown
+++ b/pt-br/julia-pt.html.markdown
@@ -104,7 +104,7 @@ println("Eu sou Julia. Prazer em conhece-lo!")
## 2. Variáveis e coleções
####################################################
-#Você não declara variáveis antes de atribui-lás.
+#Você não declara variáveis antes de atribui-las.
some_var = 5 # => 5
some_var # => 5
diff --git a/pt-br/kotlin-pt.html.markdown b/pt-br/kotlin-pt.html.markdown
index 7c3313fc..bbe8c0d1 100644
--- a/pt-br/kotlin-pt.html.markdown
+++ b/pt-br/kotlin-pt.html.markdown
@@ -70,7 +70,7 @@ fun olaMundo(val nome : String) {
println(umaStringModelo)
/*
- Para uma variável receber null deve-se explicitamente declara-la
+ Para uma variável receber null deve-se explicitamente declará-la
como anulável.
A declaração de anulável é realizada incluindo uma "?" ao fim do tipo.
Pode-se acessar uma variável anulável usando o operador "?."
@@ -166,7 +166,7 @@ fun olaMundo(val nome : String) {
/*
Classes de dados são um modo sucinto de criar classes que servem apenas
- para guardas informações.
+ para guardar informações.
Os métodos "hashCode", "equals" e "toString" são gerados automaticamente.
*/
data class ExemploClasseDados (val x: Int, val y: Int, val z: Int)
diff --git a/pt-br/lua-pt.html.markdown b/pt-br/lua-pt.html.markdown
new file mode 100644
index 00000000..0c75da26
--- /dev/null
+++ b/pt-br/lua-pt.html.markdown
@@ -0,0 +1,423 @@
+---
+language: Lua
+contributors:
+ - ["Tyler Neylon", "http://tylerneylon.com/"]
+filename: learnlua.lua
+translators:
+ - ["Iaan Mesquita", "https://github.com/ianitow"]
+lang: pt-br
+---
+
+```lua
+-- Dois hífens começam um comentário de uma linha.
+
+--[[
+ Adicionar dois [ ] (colchetes) criam um comentário
+ de múltiplas linhas.
+--]]
+
+----------------------------------------------------
+-- 1. Variáveis e fluxo de controle.
+----------------------------------------------------
+
+num = 42 -- Todos os números são doubles.
+-- Não se preocupe, doubles de 64-bits contém 52 bits para
+-- armazenar corretamente valores int; a precisão da máquina
+-- não é um problema para ints que são < 52 bits.
+
+s = 'alternados' -- String são imutáveis, como em Python.
+t = "Aspas duplas também são válidas"
+u = [[ Dois colchetes
+ começam e terminam
+ strings de múltiplas linhas.]]
+t = nil -- Torna t undefined(indefinido); Lua tem um Garbage Collector.
+
+-- Blocos são representados com palavras do/end:
+while num < 50 do
+ num = num + 1 -- Sem operadores do tipo ++ ou +=
+end
+
+--Cláusula If :
+if num > 40 then
+ print('over 40')
+elseif s ~= 'walternate' then -- ~= signfica não é igual.
+ -- Para fazer checagem use == como em Python; Funciona para comparar strings também.
+ io.write('not over 40\n') -- Padrão para saídas.
+else
+ -- Variáveis são globais por padrão.
+ thisIsGlobal = 5 -- Camel case é o comum.
+
+ -- Como fazer variáveis locais:
+ local line = io.read() -- Leia a proxima linha de entrada.
+
+ -- Para concatenação de strings use o operador .. :
+ print('Winter is coming, ' .. line)
+end
+
+-- Variáveis indefinidas são do tipo nil.
+-- Isso não é um erro:
+foo = anUnknownVariable -- Agora foo = nil.
+
+aBoolValue = false
+
+-- Apenas nil e false são do tipo falso; 0 e '' são verdadeiros!
+if not aBoolValue then print('twas false') end
+
+-- 'or' e 'and' são operadores lógicos.
+-- Esse operador em C/JS a?b:c , em lua seria o mesmo que:
+ans = aBoolValue and 'yes' or 'no' --> 'no'
+
+karlSum = 0
+for i = 1, 100 do -- O intervalo inclui inicio e fim.
+ karlSum = karlSum + i
+end
+
+-- Use "100, 1, -1" para um intervalo que diminui:
+fredSum = 0
+for j = 100, 1, -1 do fredSum = fredSum + j end
+
+-- Em geral, o intervalo é começo, fim[, etapas].
+
+-- Outro construtor de loop:
+repeat
+ print('A estrada do futuro.')
+ num = num - 1
+until num == 0
+
+
+----------------------------------------------------
+-- 2. Funções.
+----------------------------------------------------
+
+function fib(n)
+ if n < 2 then return 1 end
+ return fib(n - 2) + fib(n - 1)
+end
+
+-- Closures e Funções anônimas são permitidas:
+function adder(x)
+ -- O retorno da função é criado quando adder é
+ -- chamado, e ele sabe o valor de x:
+ return function (y) return x + y end
+end
+a1 = adder(9)
+a2 = adder(36)
+print(a1(16)) --> 25
+print(a2(64)) --> 100
+
+-- Retornos, chamadas de funções e atribuições, todos eles trabalham
+-- com listas que podem ter tamanhos incompatíveis.
+-- Receptores incompatpiveis serão nil;
+-- Destinos incompatíveis serão descartados.
+
+x, y, z = 1, 2, 3, 4
+-- Agora x = 1, y = 2, z = 3, e 4 é jogado fora.
+
+function bar(a, b, c)
+ print(a, b, c)
+ return 4, 8, 15, 16, 23, 42
+end
+
+x, y = bar('zaphod') --> imprime "zaphod nil nil"
+-- Agora x = 4, y = 8, os valores 15...42 foram descartados.
+
+-- Funções são de primeira-classe, portanto podem ser local/global.
+-- Estes exemplos são equivalentes:
+function f(x) return x * x end
+f = function (x) return x * x end
+
+-- Logo, estes são equivalentes também:
+local function g(x) return math.sin(x) end
+local g; g = function (x) return math.sin(x) end
+-- 'local g' essa declaração de auto-referência é válida.
+
+-- A propósito, as funções de trigonometria trabalham em radianos.
+
+-- Chamadas de função com apenas um parâmetro de string não precisam de parênteses:
+print 'hello' -- Funciona perfeitamente.
+
+
+----------------------------------------------------
+-- 3. Tabelas.
+----------------------------------------------------
+
+-- Tabelas = A unica estrutura de dados composta em Lua;
+-- elas são matrizes associativas.
+-- Semelhantes aos arrays de PHP ou objetos de javascript, eles são:
+-- hash-lookup(chave:valor) que também podem ser usados como listas.
+
+-- Usando tabelas como dicionário / mapas:
+
+-- Dicionários literais tem strings como chaves por padrão:
+t = {key1 = 'value1', key2 = false}
+
+-- As chaves do tipo string podem usar notação de ponto,semelhante a javascript:
+print(t.key1) -- Imprime 'value1'.
+t.newKey = {} -- Adiciona um novo par chave/valor.
+t.key2 = nil -- Remove key2 da tabela.
+
+-- Qualquer notação literal (não-nulo) pode ser uma chave:
+u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
+print(u[6.28]) -- imprime "tau"
+
+-- A correspondência de chave é basicamente o valor para números
+-- e strings, mas por identidade para tabelas.
+a = u['@!#'] -- Agora a = 'qbert'.
+b = u[{}] -- Nós esperavamso o resultado 1729, mas ele é nil:
+-- b = nil já que a busca falha. Ela falha
+-- porque a chave que usamos não é a mesma que o objeto
+-- como aquele que usamos para guardar o valor original. Por isso
+-- strings & numeros são chaves mais recomendadas.
+
+-- Uma chamada de função de apenas um paramêtro de tabela, não precisa de parênteses:
+
+function h(x) print(x.key1) end
+h{key1 = 'Sonmi~451'} -- Imprime 'Sonmi~451'.
+
+for key, val in pairs(u) do -- Iteração de tabela.
+ print(key, val)
+end
+
+-- _G é uma tabela especial que guarda tudo que é global.
+print(_G['_G'] == _G) -- Imprime 'true'.
+
+-- Usando tabelas como listas / arrays:
+
+-- Listas literais com chaves int implícitas:
+v = {'value1', 'value2', 1.21, 'gigawatts'}
+for i = 1, #v do -- #v é o tamanho de v
+ print(v[i]) -- Índices começam em 1 !! MUITO LOCO!
+end
+-- Uma 'list' não é um tipo real. v é apenas uma tabela
+-- com chaves int consecutivas, tratando ela como uma lista.
+
+----------------------------------------------------
+-- 3.1 Metatabelas e metamétodos.
+----------------------------------------------------
+
+-- Uma tabela pode ter uma metatabela que fornece à tabela
+-- um compotamento de sobrecarga de operador. Depois veremos
+-- como metatabelas suportam o comportamento do Javascript-prototype.
+
+f1 = {a = 1, b = 2} -- Representa uma fração de a/b.
+f2 = {a = 2, b = 3}
+
+-- Isso falharia:
+-- s = f1 + f2
+
+metafraction = {}
+function metafraction.__add(f1, f2)
+ sum = {}
+ sum.b = f1.b * f2.b
+ sum.a = f1.a * f2.b + f2.a * f1.b
+ return sum
+end
+
+setmetatable(f1, metafraction)
+setmetatable(f2, metafraction)
+
+s = f1 + f2 -- chama __add(f1, f2) na metatabela de f1
+
+-- f1, f2 não tem chave para sua metatabela, ao contrário de
+-- prototypes em javascript, então você deve recuperá-lo com
+-- getmetatable(f1). A metatabela é uma tabela normal
+-- com chaves que Lua reconhece, como __add.
+
+-- Mas a proxima linha irá falhar porque s não tem uma metatabela:
+-- t = s + s
+-- O padrão de Classes abaixo consertam esse problema.
+
+-- Uma __index em uma metatable sobrecarrega pesquisas de ponto:
+defaultFavs = {animal = 'gru', food = 'donuts'}
+myFavs = {food = 'pizza'}
+setmetatable(myFavs, {__index = defaultFavs})
+eatenBy = myFavs.animal -- Funciona! obrigado, metatabela.
+
+-- As pesquisas diretas de tabela que falham tentarão pesquisar novamente usando
+-- o __index da metatabela, e isso é recursivo.
+
+-- Um valor de __index também pode ser uma function(tbl, key)
+-- para pesquisas mais personalizadas.
+
+-- Valores do tipo __index,add, .. são chamados de metamétodos.
+-- Uma lista completa com os metamétodos.
+
+-- __add(a, b) para a + b
+-- __sub(a, b) para a - b
+-- __mul(a, b) para a * b
+-- __div(a, b) para a / b
+-- __mod(a, b) para a % b
+-- __pow(a, b) para a ^ b
+-- __unm(a) para -a
+-- __concat(a, b) para a .. b
+-- __len(a) para #a
+-- __eq(a, b) para a == b
+-- __lt(a, b) para a < b
+-- __le(a, b) para a <= b
+-- __index(a, b) <fn or a table> para a.b
+-- __newindex(a, b, c) para a.b = c
+-- __call(a, ...) para a(...)
+
+----------------------------------------------------
+-- 3.2 Tabelas como Classes e sua herança.
+----------------------------------------------------
+
+-- Classes não são disseminadas; existem maneiras diferentes
+-- para fazer isso usando tabelas e metamétodos...
+
+-- A explicação para este exemplo está logo abaixo.
+
+Dog = {} -- 1.
+
+function Dog:new() -- 2.
+ newObj = {sound = 'woof'} -- 3.
+ self.__index = self -- 4.
+ return setmetatable(newObj, self) -- 5.
+end
+
+function Dog:makeSound() -- 6.
+ print('I say ' .. self.sound)
+end
+
+mrDog = Dog:new() -- 7.
+mrDog:makeSound() -- 'I say woof' -- 8.
+
+-- 1. Dog atua como uma classe; mas na verdade, é uma tabela.
+-- 2. function tablename:fn(...) é a mesma coisa que
+-- function tablename.fn(self, ...)
+-- O : apenas adiciona um primeiro argumento chamado self.
+-- Leia 7 & 8 abaixo para ver como self obtém seu valor.
+-- 3. newObj será uma instância da classe Dog.
+-- 4. self = a classe que que foi instanciada. Regularmente
+-- self = Dog, mas a herança pode mudar isso.
+-- newObj recebe as funções de self como se tivessimos definido em ambos
+-- a metatabela de newObj e self __index para self.
+-- 5. Lembre-se: setmetatable retorna seu primeiro argumento definido.
+-- 6. O : funciona como em 2, mas desta vez esperamos que
+-- self seja uma instância já instanciada da classe.
+-- 7. Igual a Dog.new(Dog), logo self = Dog no new().
+-- 8. Igual a mrDog.makeSound(mrDog); self = mrDog.
+
+----------------------------------------------------
+
+-- Heranças exemplos:
+
+LoudDog = Dog:new() -- 1.
+
+function LoudDog:makeSound()
+ s = self.sound .. ' ' -- 2.
+ print(s .. s .. s)
+end
+
+seymour = LoudDog:new() -- 3.
+seymour:makeSound() -- 'woof woof woof' -- 4.
+
+-- 1. LoudDog recebe os metodos e variáveis de Dog.
+-- 2. self tem uma chave 'sound' vindo de new(), veja o 3.
+-- 3. Mesma coisa que LoudDog.new(LoudDog), convertido para
+-- Dog.new(LoudDog) como LoudDog não tem uma chave 'new',
+-- mas tem uma chave __index = Dog na sua metatabela o
+-- resultado será: a metabela de seymour é a LoudDog, e
+-- LoudDog.__index = LoudDog. Então seymour.key será
+-- = seymour.key, LoudDog.key, Dog.key,seja qual for a primeira
+-- chave fornecida.
+-- 4. A chave 'makeSound' foi encontrada em LoudDog; isto
+-- é a mesma coisa que LoudDog.makeSound(seymour).
+
+-- Se precisar de, uma subclasse de new() como uma base:
+function LoudDog:new()
+ newObj = {}
+ -- define newObj
+ self.__index = self
+ return setmetatable(newObj, self)
+end
+
+----------------------------------------------------
+-- 4. Módulos.
+----------------------------------------------------
+
+
+--[[ Estou comentando esta seção, então o resto
+-- desse script é executável.
+```
+
+```lua
+-- Suponhamos que o arquivo mod.lua se pareça com isso:
+local M = {}
+
+local function sayMyName()
+ print('Hrunkner')
+end
+
+function M.sayHello()
+ print('Why hello there')
+ sayMyName()
+end
+
+return M
+
+-- Outro arquivo pode usar as funcionalidades de mod.lua:
+local mod = require('mod') -- Roda o arquivo mod.lua.
+
+-- require é a forma que usamos para incluir módulos.
+-- require atua como: (se não for cacheado; veja abaixo)
+local mod = (function ()
+ <contents of mod.lua>
+end)()
+-- É como se mod.lua fosse um corpo de uma função, então
+-- os locais dentro de mod.lua são invisíveis fora dele.
+
+-- Isso irá funcionar porque mod aqui = M dentro de mod.lua:
+mod.sayHello() -- Diz olá para Hrunkner.
+
+-- Isso aqui é errado; sayMyName existe apenas em mod.lua:
+mod.sayMyName() -- erro
+
+-- valores retornados de require são armazenados em cache para que um arquivo seja
+-- execute no máximo uma vez, mesmo quando é exigidos várias vezes.
+
+-- Suponhamos que mod2.lua contém "print('Hi!')".
+local a = require('mod2') -- Imprime Hi!
+local b = require('mod2') -- Não imprime;pois a=b.
+
+-- dofile é parecido com require, porém sem cacheamento:
+dofile('mod2.lua') --> Hi!
+dofile('mod2.lua') --> Hi! (roda novamente)
+
+-- loadfile carrega um arquivo lua, porém não o executa.
+f = loadfile('mod2.lua') -- Chame f() para executar.
+
+-- loadstring é um loadfile para strings.
+g = loadstring('print(343)') -- Retorna uma função.
+g() -- Imprime 343; nada foi impresso antes disso.
+
+--]]
+
+```
+
+## Referências
+
+Fiquei bastante animado para aprender Lua pois consegui fazer jogos
+com a <a href="http://love2d.org/">Love 2D engine de jogos</a>.
+
+Eu comecei com <a href="http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/">BlackBulletIV's para programadores LUA</a>.
+Em seguida, eu li a documentação oficial <a href="https://www.lua.org/manual/5.1/pt/index.html#contents">Programando em Lua</a>.
+É assim que se começa.
+
+Pode ser útil conferir <a href="http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf">Uma pequena referencia sobre LUA</a> em lua-users.org.
+
+Os principais tópicos não cobertos, são as bibliotecas padrões:
+
+- <a href="http://lua-users.org/wiki/StringLibraryTutorial">Biblioteca de strings</a>
+- <a href="http://lua-users.org/wiki/TableLibraryTutorial">Biblioteca de tabelas</a>
+- <a href="http://lua-users.org/wiki/MathLibraryTutorial">Biblioteca de matemática</a>
+- <a href="http://lua-users.org/wiki/IoLibraryTutorial">Biblioteca de entrada/saída</a>
+- <a href="http://lua-users.org/wiki/OsLibraryTutorial">Biblioteca do sistema operacional</a>
+
+A propósito, todo este arquivo é um código LUA válido, salve-o como
+aprenda.lua e rode-o com "lua aprenda.lua" !
+
+Este guia foi escrito pela primeira vez por tylerneylon.com, e agora
+também disponível em <a href="https://gist.github.com/tylerneylon/5853042">github gist</a>. E também em português.
+
+Se divirta com lua
diff --git a/pt-br/matlab-pt.html.markdown b/pt-br/matlab-pt.html.markdown
index 5ed6b7ba..fae17bca 100644
--- a/pt-br/matlab-pt.html.markdown
+++ b/pt-br/matlab-pt.html.markdown
@@ -356,7 +356,7 @@ disp(a) % Imprime o valor da variável a
disp('Olá Mundo') % Imprime a string
fprintf % Imprime na janela de comandos com mais controle
-% Estruturas Condicionais (os parênteses são opicionais, porém uma boa prática)
+% Estruturas Condicionais (os parênteses são opcionais, porém uma boa prática)
if (a > 15)
disp('Maior que 15')
elseif (a == 23)
diff --git a/pt-br/self-pt.html.markdown b/pt-br/self-pt.html.markdown
index 2fb2953b..eb821474 100644
--- a/pt-br/self-pt.html.markdown
+++ b/pt-br/self-pt.html.markdown
@@ -147,7 +147,7 @@ o objeto '10' no slot 'x' e retornará o objeto original"
# Protótipos
-Não existem classes em Self. A maneira de obter um objeto é encontrar um protótipo e copia-lo.
+Não existem classes em Self. A maneira de obter um objeto é encontrar um protótipo e copiá-lo.
```
| d |
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 6ece02ff..7d28bf53 100644
--- a/pt-br/typescript-pt.html.markdown
+++ b/pt-br/typescript-pt.html.markdown
@@ -10,11 +10,11 @@ lang: pt-br
Typescript é uma linguagem que visa facilitar o desenvolvimento de aplicações em grande escala escritos em JavaScript.
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.
+É 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 em texto datilografado sintaxe extra, 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 compilador do texto datilografado, de cabeça para o [Parque](http://www.typescriptlang.org/Playground), onde você vai ser capaz de escrever código, ter auto conclusão e ver diretamente o JavaScript emitida.
+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.
```js
// Existem 3 tipos básicos no TypeScript
@@ -44,13 +44,13 @@ function bigHorribleAlert(): void {
// Funções são cidadãos de primeira classe, apoiar a sintaxe lambda "seta gordura" e
// Tipo de uso inferência
-// A seguir são equivalentes, a mesma assinatura será inferido pelo
-// Compilador, e mesmo JavaScript será emitido
+// A seguir são equivalentes, a mesma assinatura será inferida pelo
+// Compilador, e o mesmo JavaScript será emitido
var f1 = function(i: number): number { return i * i; }
-// Tipo de retorno inferida
+// Tipo de retorno inferido
var f2 = function(i: number) { return i * i; }
var f3 = (i: number): number => { return i * i; }
-// Tipo de retorno inferida
+// Tipo de retorno inferido
var f4 = (i: number) => { return i * i; }
// Tipo de retorno inferido, one-liner significa nenhuma palavra-chave retorno necessário
var f5 = (i: number) => i * i;
@@ -88,7 +88,7 @@ class Point {
// Propriedades
x: number;
- // Construtor - the public/private keywords in this context will generate
+ // Construtor - as palavras-chave public/private nesse contexto irão gerar
// o código clichê para a propriedade e a inicialização no
// construtor.
// Neste exemplo, "y" será definida como "X" é, mas com menos código
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/purescript.html.markdown b/purescript.html.markdown
index 6b74ac64..c848c2a4 100644
--- a/purescript.html.markdown
+++ b/purescript.html.markdown
@@ -6,19 +6,20 @@ contributors:
- ["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 27b2b22a..39e60455 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -50,17 +50,19 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea
10.0 / 3 # => 3.3333333333333335
# Modulo operation
-7 % 3 # => 1
+7 % 3 # => 1
+# i % j have the same sign as j, unlike C
+-7 % 3 # => 2
# Exponentiation (x**y, x to the yth power)
2**3 # => 8
# Enforce precedence with parentheses
-1 + 3 * 2 # => 7
+1 + 3 * 2 # => 7
(1 + 3) * 2 # => 8
# Boolean values are primitives (Note: the capitalization)
-True # => True
+True # => True
False # => False
# negate with not
@@ -126,7 +128,7 @@ b == a # => True, a's and b's objects are equal
"This is a string."
'This is also a string.'
-# Strings can be added too! But try not to do this.
+# Strings can be added too
"Hello " + "world!" # => "Hello world!"
# String literals (but not variables) can be concatenated without using '+'
"Hello " "world!" # => "Hello world!"
@@ -140,10 +142,9 @@ len("This is a string") # => 16
# You can also format using f-strings or formatted string literals (in Python 3.6+)
name = "Reiko"
f"She said her name is {name}." # => "She said her name is Reiko"
-# You can basically put any Python statement inside the braces and it will be output in the string.
+# You can basically put any Python expression inside the braces and it will be output in the string.
f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long."
-
# None is an object
None # => None
@@ -173,7 +174,6 @@ print("Hello, World", end="!") # => Hello, World!
# Simple way to get input data from console
input_string_var = input("Enter some data: ") # Returns the data as a string
-# Note: In earlier versions of Python, input() method was named as raw_input()
# There are no declarations, only assignments.
# Convention is to use lower_case_with_underscores
@@ -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
@@ -506,7 +506,7 @@ print(contents)
with open('myfile2.txt', "r+") as file:
contents = json.load(file) # reads a json object from a file
-print(contents)
+print(contents)
# print: {"aa": 12, "bb": 21}
@@ -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):
@@ -773,9 +773,8 @@ if __name__ == '__main__':
# Call the static method
print(Human.grunt()) # => "*grunt*"
- # Cannot call static method with instance of object
- # because i.grunt() will automatically put "self" (the object i) as an argument
- print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given
+ # Static methods can be called by instances too
+ print(i.grunt()) # => "*grunt*"
# Update the property for this instance
i.age = 42
@@ -920,7 +919,7 @@ class Batman(Superhero, Bat):
def __init__(self, *args, **kwargs):
# Typically to inherit attributes you have to call super:
- # super(Batman, self).__init__(*args, **kwargs)
+ # super(Batman, self).__init__(*args, **kwargs)
# However we are dealing with multiple inheritance here, and super()
# only works with the next base class in the MRO list.
# So instead we explicitly call __init__ for all ancestors.
@@ -1030,15 +1029,15 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
* [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 Course](http://www.python-course.eu/index.php)
+* [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)
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
-* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
+* [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](http://cscircles.cemc.uwaterloo.ca/)
-* [Dive Into Python 3](http://www.diveintopython3.net/index.html)
-* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718)
+* [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/r.html.markdown b/r.html.markdown
index 3e855602..79af40ce 100644
--- a/r.html.markdown
+++ b/r.html.markdown
@@ -255,16 +255,16 @@ 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 childrens' 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"
levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs"
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/rst.html.markdown b/rst.html.markdown
index bdc73c7a..56d54501 100644
--- a/rst.html.markdown
+++ b/rst.html.markdown
@@ -6,9 +6,9 @@ contributors:
filename: restructuredtext.rst
---
-RST is a file format formely created by Python community to write documentation (and so, is part of Docutils).
+RST, Restructured Text, is a file format created by the Python community to write documentation. It is part of [Docutils](https://docutils.sourceforge.io/rst.html).
-RST files are simple text files with lightweight syntax (comparing to HTML).
+RST is a markdown language like HTML but is much more lightweight and easier to read.
## Installation
@@ -39,10 +39,10 @@ A simple example of the file syntax:
Main titles are written using equals signs over and under
=========================================================
-Note that there must be as many equals signs as title characters.
+Note that each character, including spaces, needs an equals sign above and below.
-Title are underlined with equals signs too
-==========================================
+Titles also use equals signs but are only underneath
+====================================================
Subtitles with dashes
---------------------
@@ -84,7 +84,7 @@ More complex tables can be done easily (merged columns and/or rows) but I sugges
There are multiple ways to make links:
-- By adding an underscore after a word : Github_ and by adding the target URL after the text (this way has the advantage to not insert unnecessary URLs inside readable text).
+- By adding an underscore after a word : Github_ and by adding the target URL after the text (this way has the advantage of not inserting unnecessary URLs in the visible text).
- By typing a full comprehensible URL : https://github.com/ (will be automatically converted to a link)
- By making a more Markdown-like link: `Github <https://github.com/>`_ .
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/nim-ru.html.markdown b/ru-ru/nim-ru.html.markdown
index d05583d7..0e08f1bf 100644
--- a/ru-ru/nim-ru.html.markdown
+++ b/ru-ru/nim-ru.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Dennis Felsing", "http://felsin9.de/nnis/"]
translators:
- ["Nomadic", "https://github.com/n0madic"]
+ - ["dvska", "https://github.com/dvska"]
lang: ru-ru
---
@@ -16,25 +17,25 @@ Nim (ранее известный, как Nimrod) — язык программ
Nim эффективный, выразительный и элегантный.
```nim
-var # Объявление (и присваивание) переменных,
- letter: char = 'n' # с указанием типа или без
- lang = "N" & "im"
- nLength : int = len(lang)
+var # Объявление (и присваивание) переменных,
+ буква: char = 'n' # с указанием типа или без
+ язык = "N" & "im"
+ nLength : int = len(язык)
boat: float
- truth: bool = false
+ правда: bool = false
-let # Используйте let *сразу* для объявления и связывания переменных.
- legs = 400 # legs неизменяемый.
- arms = 2_000 # Символ _ игнорируется и удобен для длинных чисел.
- aboutPi = 3.15
+let # Используйте let *сразу* для объявления и связывания переменных.
+ ноги = 400 # ноги неизменяемый.
+ руки = 2_000 # Символ _ игнорируется и удобен для длинных чисел.
+ почтиПи = 3.15
const # Константы вычисляются во время компиляции. Это обеспечивает
debug = true # производительность и полезно в выражениях этапа компиляции.
- compileBadCode = false
+ компилироватьПлохойКод = false
-when compileBadCode: # `when` это `if` этапа компиляции.
- legs = legs + 1 # Эта ошибка никогда не будет скомпилирована.
- const input = readline(stdin) # Значения констант должны быть известны во
+when компилироватьПлохойКод: # `when` это `if` этапа компиляции.
+ ноги = ноги + 1 # Эта ошибка никогда не будет скомпилирована.
+ const ввод = readline(stdin) # Значения констант должны быть известны во
# время компиляции.
discard 1 > 2 # Примечание. Компилятор будет жаловаться, если результат
@@ -52,27 +53,27 @@ discard """
# Кортежи
var
- child: tuple[name: string, age: int] # Кортежи определяют *как* имя поля
- today: tuple[sun: string, temp: float] # так *и* порядок полей.
+ дитя: tuple[имя: string, возраст: int] # Кортежи определяют *как* имя поля
+ сегодня: tuple[солнце: string, температура: float] # так *и* порядок полей.
-child = (name: "Rudiger", age: 2) # Присвоить все сразу литералом ()
-today.sun = "Overcast" # или отдельно по полям.
-today.temp = 70.1
+дитя = (имя: "Rudiger", возраст: 2) # Присвоить все сразу литералом ()
+сегодня.солнце = "Пасмурно" # или отдельно по полям.
+сегодня.температура = 20.1
# Последовательности
var
- drinks: seq[string]
+ напитки: seq[string]
-drinks = @["Water", "Juice", "Chocolate"] # @[V1,..,Vn] является литералом
- # последовательности
+напитки = @["Вода", "Сок", "Какао"] # @[V1,..,Vn] является литералом
+ # последовательности
-drinks.add("Milk")
+напитки.add("Молоко")
-if "Milk" in drinks:
- echo "We have Milk and ", drinks.len - 1, " other drinks"
+if "Молоко" in напитки:
+ echo "У нас тут Молоко и ещё", напитки.len - 1, " напиток(ов)"
-let myDrink = drinks[2]
+let мойНапиток = напитки[2]
#
# Определение типов
@@ -82,30 +83,30 @@ let myDrink = drinks[2]
# Это то, что делает статическую типизацию мощной и полезной.
type
- Name = string # Псевдоним типа дает вам новый тип, который равнозначен
- Age = int # старому типу, но более нагляден.
- Person = tuple[name: Name, age: Age] # Определение структур данных.
- AnotherSyntax = tuple
+ Имя = string # Псевдоним типа дает вам новый тип, который равнозначен
+ Возраст = int # старому типу, но более нагляден.
+ Человек = tuple[имя: Имя, возраст: Возраст] # Определение структур данных.
+ АльтернативныйСинтаксис = tuple
fieldOne: string
secondField: int
var
- john: Person = (name: "John B.", age: 17)
- newage: int = 18 # Было бы лучше использовать Age, чем int
+ джон: Человек = (имя: "John B.", возраст: 17)
+ новыйВозраст: int = 18 # Было бы лучше использовать Возраст, чем int
-john.age = newage # Но это все же работает, потому что int и Age синонимы.
+джон.возраст = новыйВозраст # Но это все же работает, потому что int и Возраст синонимы.
type
- Cash = distinct int # `distinct` делает новый тип несовместимым с его
- Desc = distinct string # базовым типом.
+ Нал = distinct int # `distinct` делает новый тип несовместимым с его
+ Описание = distinct string # базовым типом.
var
- money: Cash = 100.Cash # `.Cash` преобразует int в наш тип
- description: Desc = "Interesting".Desc
+ money: Нал = 100.Нал # `.Нал` преобразует int в наш тип
+ описание: Описание = "Interesting".Описание
-when compileBadCode:
- john.age = money # Error! age is of type int and money is Cash
- john.name = description # Компилятор говорит: "Нельзя!"
+when компилироватьПлохойКод:
+ джон.возраст = money # Error! возраст is of type int and money is Нал
+ джон.имя = описание # Компилятор говорит: "Нельзя!"
#
# Дополнительные типы и структуры данных
@@ -114,50 +115,50 @@ when compileBadCode:
# Перечисления позволяют типу иметь одно из ограниченного числа значений
type
- Color = enum cRed, cBlue, cGreen
- Direction = enum # Альтернативный формат
- dNorth
- dWest
- dEast
- dSouth
+ Цвет = enum цКрасный, цГолубой, цЗеленый
+ Направление = enum # Альтернативный формат
+ нСевер
+ нЗапад
+ нВосток
+ нЮг
var
- orient = dNorth # `orient` имеет тип Direction, со значением `dNorth`
- pixel = cGreen # `pixel` имеет тип Color, со значением `cGreen`
+ напр = нСевер # `напр` имеет тип Направление, со значением `нСевер`
+ точка = цЗеленый # `точка` имеет тип Цвет, со значением `цЗеленый`
-discard dNorth > dEast # Перечисления обычно являются "порядковыми" типами
+discard нСевер > нВосток # Перечисления обычно являются "порядковыми" типами
# Поддиапазоны определяют ограниченный допустимый диапазон
type
- DieFaces = range[1..20] # Допустимым значением являются только int от 1 до 20
+ Кости = range[1..20] # 🎲 Допустимым значением являются только int от 1 до 20
var
- my_roll: DieFaces = 13
+ мой_бросок: Кости = 13
-when compileBadCode:
- my_roll = 23 # Error!
+when компилироватьПлохойКод:
+ мой_бросок = 23 # Error!
-# Arrays
+# Массивы
type
- RollCounter = array[DieFaces, int] # Массивы фиксированной длины и
- DirNames = array[Direction, string] # индексируются любым порядковым типом.
- Truths = array[42..44, bool]
+ СчетчикБросков = array[Кости, int] # Массивы фиксированной длины и
+ ИменаНаправлений = array[Направление, string] # индексируются любым порядковым типом.
+ Истины = array[42..44, bool]
var
- counter: RollCounter
- directions: DirNames
- possible: Truths
+ счетчик: СчетчикБросков
+ направления: ИменаНаправлений
+ возможны: Истины
-possible = [false, false, false] # Массивы создаются литералом [V1,..,Vn]
-possible[42] = true
+возможны = [false, false, false] # Массивы создаются литералом [V1,..,Vn]
+возможны[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
+мой_бросок = 13
+счетчик[мой_бросок] += 1
+счетчик[мой_бросок] += 1
-var anotherArray = ["Default index", "starts at", "0"]
+var ещеМассив = ["Идекс по умолчанию", "начинается с", "0"]
# Доступны другие структуры данных, в том числе таблицы, множества,
# списки, очереди и crit-bit деревья.
@@ -169,89 +170,94 @@ var anotherArray = ["Default index", "starts at", "0"]
# `case`, `readLine()`
-echo "Read any good books lately?"
+echo "Читали какие-нибудь хорошие книги в последнее время?"
+
case readLine(stdin)
-of "no", "No":
- echo "Go to your local library."
-of "yes", "Yes":
- echo "Carry on, then."
+of "нет", "Нет":
+ echo "Пойдите в свою местную библиотеку."
+of "да", "Да":
+ echo "Тогда продолжим"
else:
- echo "That's great; I assume."
+ echo "Здорово!"
# `while`, `if`, `continue`, `break`
-import strutils as str # http://nim-lang.org/docs/strutils.html (EN)
-echo "I'm thinking of a number between 41 and 43. Guess which!"
-let number: int = 42
+import strutils as str # http://nim-lang.org/docs/strutils.html (EN)
+echo "Я загадало число между 41 и 43. Отгадай!"
+let число: 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:
+ ввод_догадка: string
+ догадка: int
+
+while догадка != число:
+ ввод_догадка = readLine(stdin)
+
+ if ввод_догадка == "": continue # Пропустить эту итерацию
+
+ догадка = str.parseInt(ввод_догадка)
+
+ if догадка == 1001:
echo("AAAAAAGGG!")
break
- elif guess > number:
- echo("Nope. Too high.")
- elif guess < number:
- echo(guess, " is too low")
+ elif догадка > число:
+ echo("Неа. Слишком большое.")
+ elif догадка < число:
+ echo(догадка, " это слишком мало")
else:
- echo("Yeeeeeehaw!")
+ echo("Точнооооо!")
#
# Итерации (циклы)
#
-for i, elem in ["Yes", "No", "Maybe so"]: # Или просто `for elem in`
- echo(elem, " is at index: ", i)
+for i, элем in ["Да", "Нет", "Может быть"]: # Или просто `for элем in`
+ echo(элем, " по индексу: ", i)
-for k, v in items(@[(person: "You", power: 100), (person: "Me", power: 9000)]):
- echo v
+for ключ, значение in items(@[(человек: "You", сила: 100), (человек: "Me", сила: 9000)]):
+ echo значение
-let myString = """
-an <example>
-`string` to
-play with
+let мояСтрока = """
+<пример>
+`строки` для
+тренировки
""" # Многострочная "сырая" строка
-for line in splitLines(myString):
- echo(line)
+for строка in splitLines(мояСтрока):
+ echo(строка)
-for i, c in myString: # Индекс и символ. Или `for j in` только для символов
- if i mod 2 == 0: continue # Компактная форма `if`
- elif c == 'X': break
- else: echo(c)
+for i, симв in мояСтрока: # Индекс и символ. Или `for j in` только для символов
+ if i mod 2 == 0: continue # Компактная форма `if`
+ elif симв == 'X': break
+ else: echo(симв)
#
# Процедуры
#
-type Answer = enum aYes, aNo
+type Ответ = enum оДа, оНет
-proc ask(question: string): Answer =
- echo(question, " (y/n)")
+proc спрос(вопрос: string): Ответ =
+ echo(вопрос, " (д/н)")
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) = # Значение поумолчанию 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`.
+ of "д", "Д", "да", "Да":
+ return Ответ.оДа # Перечисления могут быть квалифицированы
+ of "н", "Н", "нет", "Нет":
+ return Ответ.оНет
+ else: echo("Поточнее, да или нет")
+
+proc добавьСахар(количество: int = 2) = # Значение по умолчанию 2, ничего не возвращает
+ assert(количество > 0 and количество < 9000, "Диабет ☠")
+ for a in 1..количество:
+ echo(a, " кубик...")
+
+case спрос("Сахарку?")
+of оДа:
+ добавьСахар(3)
+of оНет:
+ echo "Ну немнооожко!"
+ добавьСахар()
+# Здесь нет необходимости в `else`. Возможны только `да` и `нет`.
#
# FFI (интерфейс внешних функций)
@@ -261,7 +267,7 @@ of aNo:
proc strcmp(a, b: cstring): cint {.importc: "strcmp", nodecl.}
-let cmp = strcmp("C?", "Easy!")
+let cmp = strcmp("C?", "Легко!")
```
Кроме того, Nim выделяется среди себе подобных метапрограммированием,
diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown
index 3baa15f8..092c3e2f 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.
diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown
index 9133549d..e0e53b9c 100644
--- a/ru-ru/python-ru.html.markdown
+++ b/ru-ru/python-ru.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Steven Basart", "http://github.com/xksteven"]
translators:
- ["Andre Polykanine", "https://github.com/Oire"]
+ - ["Anton Grouchtchak", "https://github.com/Teraskull"]
filename: learnpython-ru.py
---
@@ -20,8 +21,10 @@ filename: learnpython-ru.py
Если вы хотите изучить Python 2.7, обратитесь к другой статье.
```python
+
# Однострочные комментарии начинаются с символа решётки.
-""" Многострочный текст может быть
+
+""" Многострочный текст может быть
записан, используя 3 знака " и обычно используется
в качестве встроенной документации
"""
@@ -31,315 +34,397 @@ filename: learnpython-ru.py
####################################################
# У вас есть числа
-3 #=> 3
+3 # => 3
# Математика работает вполне ожидаемо
-1 + 1 #=> 2
-8 - 1 #=> 7
-10 * 2 #=> 20
-
-# Кроме деления, которое по умолчанию возвращает число с плавающей запятой
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
35 / 5 # => 7.0
# Результат целочисленного деления округляется в меньшую сторону
# как для положительных, так и для отрицательных чисел.
-5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # работает и для чисел с плавающей запятой
--5 // 3 # => -2
+5 // 3 # => 1
+-5 // 3 # => -2
+5.0 // 3.0 # => 1.0 # работает и для чисел с плавающей запятой
-5.0 // 3.0 # => -2.0
-# Когда вы используете числа с плавающей запятой,
-# результатом будет также число с плавающей запятой
-3 * 2.0 # => 6.0
+# # Результат деления возвращает число с плавающей запятой
+10.0 / 3 # => 3.3333333333333335
# Остаток от деления
-7 % 3 # => 1
+7 % 3 # => 1
# Возведение в степень
-2**4 # => 16
+2**3 # => 8
# Приоритет операций указывается скобками
-(1 + 3) * 2 #=> 8
+1 + 3 * 2 # => 7
+(1 + 3) * 2 # => 8
-# Для логических (булевых) значений существует отдельный примитивный тип
-True
-False
+# Булевы значения - примитивы (Обратите внимание на заглавную букву)
+True # => True
+False # => False
# Для отрицания используется ключевое слово not
-not True #=> False
-not False #=> True
-
-# Логические операторы
-# Обратите внимание: ключевые слова «and» и «or» чувствительны к регистру букв
-True and False #=> False
-False or True #=> True
-
-# Обратите внимание, что логические операторы используются и с целыми числами
-0 and 2 #=> 0
--5 or 0 #=> -5
-0 == False #=> True
-2 == True #=> False
-1 == True #=> True
+not True # => False
+not False # => True
+
+# Булевы операторы
+# Обратите внимание: ключевые слова "and" и "or" чувствительны к регистру букв
+True and False # => False
+False or True # => True
+
+# True и False на самом деле 1 и 0, но с разными ключевыми словами
+True + True # => 2
+True * 8 # => 8
+False - 5 # => -5
+
+# Операторы сравнения обращают внимание на числовое значение True и False
+0 == False # => True
+1 == True # => True
+2 == True # => False
+-5 != False # => True
+
+# Использование булевых логических операторов на типах int превращает их в булевы значения, но возвращаются оригинальные значения
+# Не путайте с bool(ints) и bitwise and/or (&,|)
+bool(0) # => False
+bool(4) # => True
+bool(-6) # => True
+0 and 2 # => 0
+-5 or 0 # => -5
# Равенство — это ==
-1 == 1 #=> True
-2 == 1 #=> False
+1 == 1 # => True
+2 == 1 # => False
# Неравенство — это !=
-1 != 1 #=> False
-2 != 1 #=> True
+1 != 1 # => False
+2 != 1 # => True
# Ещё немного сравнений
-1 < 10 #=> True
-1 > 10 #=> False
-2 <= 2 #=> True
-2 >= 2 #=> True
-
-# Сравнения могут быть записаны цепочкой:
-1 < 2 < 3 #=> True
-2 < 3 < 2 #=> False
+1 < 10 # => True
+1 > 10 # => False
+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 vs. ==) ключевое слово 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 равны
# Строки определяются символом " или '
"Это строка."
'Это тоже строка.'
# И строки тоже могут складываться! Хотя лучше не злоупотребляйте этим.
-"Привет " + "мир!" #=> "Привет мир!"
+"Привет " + "мир!" # => "Привет мир!"
-# Строки можно умножать.
-"aa" * 4 #=> "aaaaaaaa"
+# Строки (но не переменные) могут быть объединены без использования '+'
+"Привет " "мир!" # => "Привет мир!"
# Со строкой можно работать, как со списком символов
-"Это строка"[0] #=> 'Э'
+"Привет мир!"[0] # => 'П'
-# Метод format используется для форматирования строк:
-"{0} могут быть {1}".format("строки", "форматированы")
+# Вы можете найти длину строки
+len("Это строка") # => 10
-# Вы можете повторять аргументы форматирования, чтобы меньше печатать.
-"Ехал {0} через реку, видит {0} - в реке {1}! Сунул {0} руку в реку, {1} за руку греку цап!".format("грека", "рак")
-#=> "Ехал грека через реку, видит грека - в реке рак! Сунул грека руку в реку, рак за руку греку цап!"
-# Если вы не хотите считать, можете использовать ключевые слова.
-"{name} хочет есть {food}".format(name="Боб", food="лазанью")
+# Вы также можете форматировать, используя f-строки (в Python 3.6+)
+name = "Рейко"
+f"Она сказала, что ее зовут {name}." # => "Она сказала, что ее зовут Рейко"
+# Вы можете поместить любой оператор Python в фигурные скобки, и он будет выведен в строке.
+f"{name} состоит из {len(name)} символов." # => "Рэйко состоит из 5 символов."
-# Если ваш код на Python 3 нужно запускать также и под Python 2.5 и ниже,
-# вы также можете использовать старый способ форматирования:
-"%s можно %s %s способом" % ("строки", "интерполировать", "старым")
# None является объектом
-None #=> None
+None # => None
-# Не используйте оператор равенства '==' для сравнения
-# объектов с None. Используйте для этого 'is'
-"etc" is None #=> False
-None is None #=> True
+# Не используйте оператор равенства "==" для сравнения
+# объектов с None. Используйте для этого "is"
+"etc" is None # => False
+None is None # => True
-# Оператор «is» проверяет идентичность объектов. Он не
-# очень полезен при работе с примитивными типами, но
-# зато просто незаменим при работе с объектами.
-
-# None, 0 и пустые строки/списки/словари приводятся к False.
+# None, 0 и пустые строки/списки/словари/кортежи приводятся к False.
# Все остальные значения равны True
-bool(0) # => False
+bool(0) # => False
bool("") # => False
-bool([]) #=> False
-bool({}) #=> False
+bool([]) # => False
+bool({}) # => False
+bool(()) # => False
####################################################
-## 2. Переменные и коллекции
+## 2. Переменные и Коллекции
####################################################
# В Python есть функция Print
-print("Я Python. Приятно познакомиться!")
+print("Я Python. Приятно познакомиться!") # => Я Python. Приятно познакомиться!
+
+# По умолчанию функция, print() также выводит новую строку в конце.
+# Используйте необязательный аргумент end, чтобы изменить последнюю строку.
+print("Привет мир", end="!") # => Привет мир!
+
+# Простой способ получить входные данные из консоли
+input_string_var = input("Введите данные: ") # Возвращает данные в виде строки
+# Примечание: в более ранних версиях Python метод input() назывался raw_input()
# Объявлять переменные перед инициализацией не нужно.
# По соглашению используется нижний_регистр_с_подчёркиваниями
some_var = 5
-some_var #=> 5
+some_var # => 5
+
+# При попытке доступа к неинициализированной переменной выбрасывается исключение.
+# Об исключениях см. раздел "Поток управления и итерируемые объекты".
+some_unknown_var # Выбрасывает ошибку NameError
-# При попытке доступа к неинициализированной переменной
-# выбрасывается исключение.
-# Об исключениях см. раздел «Поток управления и итерируемые объекты».
-some_unknown_var # Выбрасывает ошибку именования
+# if можно использовать как выражение
+# Эквивалент тернарного оператора '?:' в C
+"да!" if 0 > 1 else "нет!" # => "нет!"
# Списки хранят последовательности
li = []
# Можно сразу начать с заполненного списка
other_li = [4, 5, 6]
-# Объекты добавляются в конец списка методом append
-li.append(1) # [1]
-li.append(2) # [1, 2]
-li.append(4) # [1, 2, 4]
-li.append(3) # [1, 2, 4, 3]
-# И удаляются с конца методом pop
-li.pop() #=> возвращает 3 и li становится равен [1, 2, 4]
+# Объекты добавляются в конец списка методом append()
+li.append(1) # [1]
+li.append(2) # [1, 2]
+li.append(4) # [1, 2, 4]
+li.append(3) # [1, 2, 4, 3]
+# И удаляются с конца методом pop()
+li.pop() # => возвращает 3 и li становится равен [1, 2, 4]
# Положим элемент обратно
-li.append(3) # [1, 2, 4, 3].
+li.append(3) # [1, 2, 4, 3].
# Обращайтесь со списком, как с обычным массивом
-li[0] #=> 1
+li[0] # => 1
+
# Обратимся к последнему элементу
-li[-1] #=> 3
+li[-1] # => 3
# Попытка выйти за границы массива приведёт к ошибке индекса
-li[4] # Выдаёт IndexError
+li[4] # Выбрасывает ошибку IndexError
# Можно обращаться к диапазону, используя так называемые срезы
# (Для тех, кто любит математику, это называется замкнуто-открытый интервал).
-li[1:3] #=> [2, 4]
-# Опускаем начало
-li[2:] #=> [4, 3]
-# Опускаем конец
-li[:3] #=> [1, 2, 4]
-# Выбираем каждый второй элемент
-li[::2] # =>[1, 4]
-# Переворачиваем список
-li[::-1] # => [3, 4, 2, 1]
+li[1:3] # Вернуть список из индекса с 1 по 3 => [2, 4]
+li[2:] # Вернуть список, начиная с индекса 2 => [4, 3]
+li[:3] # Вернуть список с начала до индекса 3 => [1, 2, 4]
+li[::2] # Вернуть список, выбирая каждую вторую запись => [1, 4]
+li[::-1] # Вернуть список в обратном порядке => [3, 4, 2, 1]
# Используйте сочетания всего вышеназванного для выделения более сложных срезов
# li[начало:конец:шаг]
+# Сделать однослойную глубокую копию, используя срезы
+li2 = li[:] # => li2 = [1, 2, 4, 3], но (li2 is li) вернет False.
+
# Удаляем произвольные элементы из списка оператором del
-del li[2] # [1, 2, 3]
+del li[2] # [1, 2, 3]
+
+# Удалить первое вхождение значения
+li.remove(2) # [1, 3]
+li.remove(2) # Выбрасывает ошибку ValueError поскольку 2 нет в списке
+
+# Вставить элемент по определенному индексу
+li.insert(1, 2) # [1, 2, 3]
+
+# Получить индекс первого найденного элемента, соответствующего аргументу
+li.index(2) # => 1
+li.index(4) # Выбрасывает ошибку ValueError поскольку 4 нет в списке
# Вы можете складывать, или, как ещё говорят, конкатенировать списки
# Обратите внимание: значения li и other_li при этом не изменились.
-li + other_li #=> [1, 2, 3, 4, 5, 6] — Замечание: li и other_li не изменяются
+li + other_li # => [1, 2, 3, 4, 5, 6]
-# Объединять списки можно методом extend
+# Объединять списки можно методом extend()
li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6]
-# Проверить элемент на вхождение в список можно оператором in
-1 in li #=> True
+# Проверить элемент на наличие в списке можно оператором in
+1 in li # => True
# Длина списка вычисляется функцией len
-len(li) #=> 6
+len(li) # => 6
-# Кортежи — это такие списки, только неизменяемые
+# Кортежи похожи на списки, только неизменяемые
tup = (1, 2, 3)
-tup[0] #=> 1
-tup[0] = 3 # Выдаёт TypeError
+tup[0] # => 1
+tup[0] = 3 # Выбрасывает ошибку TypeError
+
+# Обратите внимание, что кортеж длины 1 должен иметь запятую после последнего элемента, но кортежи другой длины, даже 0, не должны.
+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
+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
+# соответственно, d = 4, e = 5 и f = 6
# Обратите внимание, как легко поменять местами значения двух переменных
-e, d = d, e # теперь d == 5, а e == 4
+e, d = d, e # теперь d == 5, а e == 4
-# Словари содержат ассоциативные массивы
+# Словари содержат ассоциативные массивы
empty_dict = {}
# Вот так описывается предзаполненный словарь
filled_dict = {"one": 1, "two": 2, "three": 3}
-# Значения извлекаются так же, как из списка, с той лишь разницей,
-# что индекс — у словарей он называется ключом — не обязан быть числом
-filled_dict["one"] #=> 1
+# Обратите внимание, что ключи для словарей должны быть неизменяемыми типами. Это
+# сделано для того, чтобы ключ может быть преобразован в хеш для быстрого поиска.
+# Неизменяемые типы включают целые числа, числа с плавающей запятой, строки, кортежи.
+invalid_dict = {[1,2,3]: "123"} # => Выбрасывает ошибку TypeError: unhashable type: 'list'
+valid_dict = {(1,2,3):[1,2,3]} # Однако значения могут быть любого типа.
-# Все ключи в виде списка получаются с помощью метода keys().
+# Поиск значений с помощью []
+filled_dict["one"] # => 1
+
+# Все ключи в виде списка получаются с помощью метода keys().
# Его вызов нужно обернуть в list(), так как обратно мы получаем
-# итерируемый объект, о которых поговорим позднее.
-list(filled_dict.keys()) # => ["three", "two", "one"]
-# Замечание: сохранение порядка ключей в словаре не гарантируется
-# Ваши результаты могут не совпадать с этими.
+# итерируемый объект, о которых поговорим позднее. Примечание - для Python
+# версии <3.7, порядок словарных ключей не гарантируется. Ваши результаты могут
+# не точно соответствовать приведенному ниже примеру. Однако, начиная с Python 3.7
+# элементы в словаре сохраняют порядок, в котором они вставляются в словарь.
+list(filled_dict.keys()) # => ["three", "two", "one"] в Python <3.7
+list(filled_dict.keys()) # => ["one", "two", "three"] в Python 3.7+
+
# Все значения в виде списка можно получить с помощью values().
# И снова нам нужно обернуть вызов в 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
+# При помощи ключевого слова in можно проверять наличие ключей в словаре
+"one" in filled_dict # => True
+1 in filled_dict # => False
-# Попытка получить значение по несуществующему ключу выбросит ошибку ключа
-filled_dict["four"] # KeyError
+# Попытка получить значение по несуществующему ключу выбросит ошибку KeyError
+filled_dict["four"] # Выбрасывает ошибку KeyError
# Чтобы избежать этого, используйте метод get()
-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("one") # => 1
+filled_dict.get("four") # => None
+# Метод get поддерживает аргумент по умолчанию, когда значение отсутствует
+filled_dict.get("one", 4) # => 1
+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.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
+filled_dict["four"] = 4 # Другой способ добавления элементов
+
+# Удаляйте ключи из словаря с помощью ключевого слова del
+del filled_dict["one"] # Удаляет ключ "one" из словаря
+
+# После Python 3.5 вы также можете использовать дополнительные параметры распаковки
+{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2}
+{'a': 1, **{'a': 2}} # => {'a': 2}
-# Удаляйте ключи из словаря с помощью оператора del
-del filled_dict["one"] # Удаляет ключ «one» из словаря
# Множества содержат... ну, в общем, множества
empty_set = set()
# Инициализация множества набором значений.
-# Да, оно выглядит примерно как словарь… ну извините, так уж вышло.
-filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
+# Да, оно выглядит примерно как словарь. Ну извините, так уж вышло.
+filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
+
+# Similar to keys of a dictionary, elements of a set have to be immutable.
+# Как и ключи словаря, элементы множества должны быть неизменяемыми.
+invalid_set = {[1], 1} # => Выбрасывает ошибку 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) # {1, 2, 3, 4, 5}
+# В множествах нет повторяющихся элементов
+filled_set.add(5) # {1, 2, 3, 4, 5}
# Пересечение множеств: &
other_set = {3, 4, 5, 6}
-filled_set & other_set #=> {3, 4, 5}
+filled_set & other_set # => {3, 4, 5}
# Объединение множеств: |
-filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
+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}
+
+# Симметричная разница: ^
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# Проверить, является ли множество слева надмножеством множества справа
+{1, 2} >= {1, 2, 3} # => False
-# Проверка на вхождение во множество: in
-2 in filled_set #=> True
-10 in filled_set #=> False
+# Проверить, является ли множество слева подмножеством множества справа
+{1, 2} <= {1, 2, 3} # => True
+
+# Проверка на наличие в множестве: in
+2 in filled_set # => True
+10 in filled_set # => False
+
+# Сделать однослойную глубокую копию
+filled_set = some_set.copy() # {1, 2, 3, 4, 5}
+filled_set is some_set # => False
####################################################
## 3. Поток управления и итерируемые объекты
####################################################
-# Для начала заведём переменную
+# Для начала создадим переменную
some_var = 5
# Так выглядит выражение if. Отступы в python очень важны!
-# результат: «some_var меньше, чем 10»
+# Конвенция заключается в использовании четырех пробелов, а не табуляции.
+# Pезультат: "some_var меньше, чем 10"
if some_var > 10:
- print("some_var намного больше, чем 10.")
-elif some_var < 10: # Выражение elif необязательно.
+ print("some_var точно больше, чем 10.")
+elif some_var < 10: # Выражение elif необязательно.
print("some_var меньше, чем 10.")
-else: # Это тоже необязательно.
+else: # Это тоже необязательно.
print("some_var равно 10.")
-# Циклы For проходят по спискам. Результат:
- # собака — это млекопитающее
- # кошка — это млекопитающее
- # мышь — это млекопитающее
+"""
+Циклы For проходят по спискам.
+Выводит:
+ собака — это млекопитающее
+ кошка — это млекопитающее
+ мышь — это млекопитающее
+"""
for animal in ["собака", "кошка", "мышь"]:
# Можете использовать format() для интерполяции форматированных строк
print("{} — это млекопитающее".format(animal))
-
+
"""
-«range(число)» возвращает список чисел
+"range(число)" возвращает список чисел
от нуля до заданного числа
-Результат:
+Выводит:
0
1
2
@@ -349,8 +434,42 @@ for i in range(4):
print(i)
"""
+"range(нижнее, верхнее)" возвращает список чисел
+от нижнего числа к верхнему
+Выводит:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print(i)
+
+"""
+"range(нижнее, верхнее, шаг)" возвращает список чисел
+от нижнего числа к верхнему, от нижнего числа к верхнему, увеличивая
+шаг за шагом. Если шаг не указан, значение по умолчанию - 1.
+Выводит:
+ 4
+ 6
+"""
+for i in range(4, 8, 2):
+ print(i)
+
+"""
+Чтобы перебрать список и получить индекс и значение каждого элемента в списке
+Выводит:
+ 0 собака
+ 1 кошка
+ 2 мышь
+"""
+animals = ["собака", "кошка", "мышь"]
+for i, value in enumerate(animals):
+ print(i, value)
+
+"""
Циклы while продолжаются до тех пор, пока указанное условие не станет ложным.
-Результат:
+Выводит:
0
1
2
@@ -366,45 +485,77 @@ try:
# Чтобы выбросить ошибку, используется raise
raise IndexError("Это ошибка индекса")
except IndexError as e:
- # pass — это просто отсутствие оператора. Обычно здесь происходит
- # восстановление после ошибки.
- pass
+ pass # pass — это просто отсутствие оператора. Обычно здесь происходит восстановление после ошибки.
except (TypeError, NameError):
- pass # Несколько исключений можно обработать вместе, если нужно.
-else: # Необязательное выражение. Должно следовать за последним блоком except
- print("Всё хорошо!") # Выполнится, только если не было никаких исключений
+ pass # Несколько исключений можно обработать вместе, если нужно.
+else: # Необязательное выражение. Должно следовать за последним блоком except
+ print("Всё хорошо!") # Выполнится, только если не было никаких исключений
+finally: # Выполнить при любых обстоятельствах
+ print("Мы можем очистить ресурсы здесь")
+
+# Вместо try/finally чтобы очистить ресурсы, можно использовать оператор with
+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)) # Записывает объект в файл
+
+# Чтение из файла
+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}
+
# Python предоставляет фундаментальную абстракцию,
-# которая называется итерируемым объектом (an iterable).
+# которая называется итерируемым объектом (Iterable).
# Итерируемый объект — это объект, который воспринимается как последовательность.
# Объект, который возвратила функция range(), итерируемый.
+
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
-print(our_iterable) #=> dict_keys(['one', 'two', 'three']). Это объект, реализующий интерфейс iterable
+print(our_iterable) # => dict_keys(['one', 'two', 'three']). Это объект, реализующий интерфейс Iterable
# Мы можем проходить по нему циклом.
for i in our_iterable:
- print(i) # Выводит one, two, three
+ print(i) # Выводит one, two, three
# Но мы не можем обращаться к элементу по индексу.
-our_iterable[1] # Выбрасывает ошибку типа
+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"
# Возвратив все данные, итератор выбрасывает исключение StopIterator
-our_iterator.__next__() # Выбрасывает исключение остановки итератора
+next(our_iterator) # Выбрасывает исключение StopIteration
+
+# Мы можем проходить по нему циклом.
+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_iterable) # => Возвращает ["one", "two", "three"]
+list(our_iterator) # => Возвращает [] потому что состояние сохраняется
####################################################
@@ -414,19 +565,19 @@ list(filled_dict.keys()) #=> Возвращает ["one", "two", "three"]
# Используйте def для создания новых функций
def add(x, y):
print("x равен %s, а y равен %s" % (x, y))
- return x + y # Возвращайте результат с помощью ключевого слова return
+ return x + y # Возвращайте результат с помощью ключевого слова return
# Вызов функции с аргументами
-add(5, 6) #=> выводит «x равен 5, а y равен 6» и возвращает 11
+add(5, 6) # => Выводит "x равен 5, а y равен 6" и возвращает 11
# Другой способ вызова функции — вызов с именованными аргументами
-add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке.
+add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке.
# Вы можете определить функцию, принимающую переменное число аргументов
def varargs(*args):
return args
-varargs(1, 2, 3) #=> (1,2,3)
+varargs(1, 2, 3) # => (1,2,3)
# А также можете определить функцию, принимающую переменное число
@@ -435,7 +586,7 @@ def keyword_args(**kwargs):
return kwargs
# Вызовем эту функцию и посмотрим, что из этого получится
-keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
# Если хотите, можете использовать оба способа одновременно
def all_the_args(*args, **kwargs):
@@ -451,70 +602,135 @@ all_the_args(1, 2, a=3, b=4) выводит:
# Используйте символ * для распаковки кортежей и ** для распаковки словарей
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # эквивалентно foo(1, 2, 3, 4)
-all_the_args(**kwargs) # эквивалентно foo(a=3, b=4)
-all_the_args(*args, **kwargs) # эквивалентно foo(1, 2, 3, 4, a=3, b=4)
+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):
+def set_x(num):
# Локальная переменная x — это не то же самое, что глобальная переменная x
- x = num # => 43
- print (x) # => 43
-
-def setGlobalX(num):
+ x = num # => 43
+ print(x) # => 43
+
+def set_global_x(num):
global x
- print (x) # => 5
- x = num # Глобальная переменная x теперь равна 6
- print (x) # => 6
+ print(x) # => 5
+ x = num # Глобальная переменная x теперь равна 6
+ print(x) # => 6
-setX(43)
-setGlobalX(6)
+set_x(43)
+set_global_x(6)
-# В Python функции — «объекты первого класса»
+# Python имеет функции первого класса
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
-add_10(3) #=> 13
+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}
-# Для удобного отображения и фильтрации можно использовать списочные включения
-[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
-[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
####################################################
-## 5. Классы
+## 5. Модули
####################################################
-# Чтобы получить класс, мы наследуемся от object.
-class Human(object):
+# Вы можете импортировать модули
+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
- # Атрибут класса. Он разделяется всеми экземплярами этого класса
- species = "H. sapiens"
+# Модули Python - это обычные файлы Python. Вы
+# можете писать свои собственные и импортировать их. Имя
+# модуля совпадает с именем файла.
+
+# Вы можете узнать, какие функции и атрибуты
+# определены в модуле.
+import math
+dir(math)
+
+# Если у вас есть скрипт Python с именем math.py в той же папке,
+# что и ваш текущий скрипт, файл math.py будет
+# будет загружен вместо встроенного модуля Python.
+# Это происходит потому, что локальная папка имеет приоритет
+# над встроенными библиотеками Python.
+
+
+####################################################
+## 6. Классы
+####################################################
+
+# Мы используем оператор class для создания класса
+class Human:
+
+ # Атрибут класса. Он используется всеми экземплярами этого класса
+ species = "Гомосапиенс"
# Обычный конструктор, вызывается при инициализации экземпляра класса
# Обратите внимание, что двойное подчёркивание в начале и в конце имени
# означает объекты и атрибуты, которые используются Python, но находятся
# в пространствах имён, управляемых пользователем.
+ # Методы (или объекты или атрибуты), например:
+ # __init__, __str__, __repr__ и т. д. называются специальными методами.
# Не придумывайте им имена самостоятельно.
def __init__(self, name):
- # Присваивание значения аргумента атрибуту класса name
+ # Присваивание значения аргумента атрибуту
self.name = name
+ # Инициализация свойства
+ self._age = 0
+
# Метод экземпляра. Все методы принимают self в качестве первого аргумента
def say(self, msg):
return "{name}: {message}".format(name=self.name, message=msg)
+ # Другой метод экземпляра
+ def sing(self):
+ return 'йо... йо... проверка микрофона... раз, два... раз, два...'
+
# Метод класса разделяется между всеми экземплярами
# Они вызываются с указыванием вызывающего класса в качестве первого аргумента
@classmethod
@@ -526,55 +742,242 @@ class Human(object):
def grunt():
return "*grunt*"
+ # property похоже на геттер.
+ # Оно превращает метод age() в одноименный атрибут только для чтения.
+ # Однако нет необходимости писать тривиальные геттеры и сеттеры в Python.
+ @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="Иван")
+ i.say("привет") # Выводит: "Иван: привет"
+ j = Human("Пётр")
+ j.say("привет") # Выводит: "Пётр: привет"
+ # i и j являются экземплярами типа Human, или другими словами: они являются объектами Human
+
+ # Вызов метода класса
+ i.say(i.get_species()) # "Иван: Гомосапиенс"
+ # Изменение разделяемого атрибута
+ Human.species = "Неандертальец"
+ i.say(i.get_species()) # => "Иван: Неандертальец"
+ j.say(j.get_species()) # => "Пётр: Неандертальец"
+
+ # Вызов статического метода
+ print(Human.grunt()) # => "*grunt*"
+
+ # Невозможно вызвать статический метод с экземпляром объекта
+ # потому что i.grunt() автоматически поместит "self" (объект i) в качестве аргумента
+ print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given
+
+ # Обновить свойство для этого экземпляра
+ i.age = 42
+ # Получить свойство
+ i.say(i.age) # => "Иван: 42"
+ j.say(j.age) # => "Пётр: 0"
+ # Удалить свойство
+ del i.age
+ # i.age # => это выбрасило бы ошибку AttributeError
+
+
+####################################################
+## 6.1 Наследование
+####################################################
+
+# Наследование позволяет определять новые дочерние классы, которые наследуют методы и
+# переменные от своего родительского класса.
+
+# Используя класс Human, определенный выше как базовый или родительский класс, мы можем
+# определить дочерний класс Superhero, который наследует переменные класса, такие как
+# "species", "name" и "age", а также методы, такие как "sing" и "grunt" из класса Human,
+# но также может иметь свои уникальные свойства.
+
+# Чтобы воспользоваться преимуществами модульности по файлам, вы можете поместить
+# вышеперечисленные классы в их собственные файлы, например, human.py
+
+# Чтобы импортировать функции из других файлов, используйте следующий формат
+# from "имя-файла-без-расширения" import "функция-или-класс"
+
+from human import Human
+
+
+# Укажите родительский класс(ы) как параметры определения класса
+class Superhero(Human):
+
+ # Если дочерний класс должен наследовать все определения родителя без каких-либо
+ # изменений, вы можете просто использовать ключевое слово pass (и ничего больше),
+ # но в этом случае оно закомментировано, чтобы разрешить уникальный дочерний класс:
+ # pass
+
+ # Дочерние классы могут переопределять атрибуты своих родителей
+ species = 'Сверхчеловек'
+
+ # Дочерние классы автоматически наследуют конструктор родительского класса, включая
+ # его аргументы, но также могут определять дополнительные аргументы или определения
+ # и переопределять его методы, такие как конструктор класса.
+ # Этот конструктор наследует аргумент "name" от класса "Human"
+ # и добавляет аргументы "superpower" и "movie":
+ def __init__(self, name, movie=False,
+ superpowers=["сверхсила", "пуленепробиваемость"]):
+
+ # добавить дополнительные атрибуты класса:
+ self.fictional = True
+ self.movie = movie
+ # помните об изменяемых значениях по умолчанию,
+ # поскольку значения по умолчанию являются общими
+ self.superpowers = superpowers
+
+ # Функция "super" позволяет вам получить доступ к методам родительского класса,
+ # которые переопределяются дочерним, в данном случае, методом __init__.
+ # Это вызывает конструктор родительского класса:
+ super().__init__(name)
+
+ # переопределить метод sing
+ def sing(self):
+ return 'Бам, бам, БАМ!'
+
+ # добавить дополнительный метод экземпляра
+ def boast(self):
+ for power in self.superpowers:
+ print("Я обладаю силой '{pow}'!".format(pow=power))
+
+
+if __name__ == '__main__':
+ sup = Superhero(name="Тик")
-# Инициализация экземпляра класса
-i = Human(name="Иван")
-print(i.say("привет")) # Выводит: «Иван: привет»
+ # Проверка типа экземпляра
+ if isinstance(sup, Human):
+ print('Я человек')
+ if type(sup) is Superhero:
+ print('Я супергерой')
-j = Human("Пётр")
-print(j.say("Привет")) # Выводит: «Пётр: привет»
+ # Получить порядок поиска разрешения метода (MRO),
+ # используемый как getattr(), так и super()
+ # Этот атрибут является динамическим и может быть обновлен
+ print(Superhero.__mro__) # => (<class '__main__.Superhero'>,
+ # => <class 'human.Human'>, <class 'object'>)
-# Вызов метода класса
-i.get_species() #=> "H. sapiens"
+ # Вызывает родительский метод, но использует свой собственный атрибут класса
+ print(sup.get_species()) # => Сверхчеловек
-# Изменение разделяемого атрибута
-Human.species = "H. neanderthalensis"
-i.get_species() #=> "H. neanderthalensis"
-j.get_species() #=> "H. neanderthalensis"
+ # Вызов переопределенного метода
+ print(sup.sing()) # => Бам, бам, БАМ!
-# Вызов статического метода
-Human.grunt() #=> "*grunt*"
+ # Вызывает метод из Human
+ sup.say('Ложка') # => Тик: Ложка
+
+ # Метод вызова, существующий только в Superhero
+ sup.boast() # => Я обладаю силой 'сверхсила'!
+ # => Я обладаю силой 'пуленепробиваемость'!
+
+ # Атрибут унаследованного класса
+ sup.age = 31
+ print(sup.age) # => 31
+
+ # Атрибут, который существует только в Superhero
+ print('Достоин ли я Оскара? ' + str(sup.movie))
####################################################
-## 6. Модули
+## 6.2 Множественное наследование
####################################################
-# Вы можете импортировать модули
-import math
-print(math.sqrt(16)) #=> 4.0
+# Eще одно определение класса
+# bat.py
+class Bat:
-# Вы можете импортировать отдельные функции модуля
-from math import ceil, floor
-print(ceil(3.7)) #=> 4.0
-print(floor(3.7)) #=> 3.0
+ species = 'Летучая мышь'
-# Можете импортировать все функции модуля.
-# (Хотя это и не рекомендуется)
-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 '))) ... ((('
+
+if __name__ == '__main__':
+ b = Bat()
+ print(b.say('привет'))
+ 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, 'анонимный', movie=True,
+ superpowers=['Богатый'], *args, **kwargs)
+ Bat.__init__(self, *args, can_fly=False, **kwargs)
+ # переопределить значение атрибута name
+ self.name = 'Грустный Бен Аффлек'
+
+ def sing(self):
+ return 'на на на на на бэтмен!'
+
+
+if __name__ == '__main__':
+ sup = Batman()
+
+ # Получить порядок поиска разрешения метода (MRO),
+ # используемый как getattr(), так и super()
+ # Этот атрибут является динамическим и может быть обновлен
+ print(Batman.__mro__) # => (<class '__main__.Batman'>,
+ # => <class 'superhero.Superhero'>,
+ # => <class 'human.Human'>,
+ # => <class 'bat.Bat'>, <class 'object'>)
+
+ # Вызывает родительский метод, но использует свой собственный атрибут класса
+ print(sup.get_species()) # => Сверхчеловек
+
+ # Вызов переопределенного метода
+ print(sup.sing()) # => на на на на на бэтмен!
+
+ # Вызывает метод из Human, потому что порядок наследования имеет значение
+ sup.say('Я согласен') # => Грустный Бен Аффлек: Я согласен
+
+ # Вызов метода, существующий только во втором родителе
+ print(sup.sonar()) # => ))) ... (((
+
+ # Атрибут унаследованного класса
+ sup.age = 100
+ print(sup.age) # => 100
+
+ # Унаследованный атрибут от второго родителя,
+ # значение по умолчанию которого было переопределено.
+ print('Могу ли я летать? ' + str(sup.fly)) # => Могу ли я летать? False
-# Вы можете узнать, какие функции и атрибуты определены
-# в модуле
-import math
-dir(math)
####################################################
## 7. Дополнительно
@@ -585,27 +988,30 @@ def double_numbers(iterable):
for i in iterable:
yield i + i
-# Генератор создаёт значения на лету.
-# Он не возвращает все значения разом, а создаёт каждое из них при каждой
-# итерации. Это значит, что значения больше 15 в double_numbers
-# обработаны не будут.
-# Обратите внимание: range — это тоже генератор.
-# Создание списка чисел от 1 до 900000000 требует много места и времени.
-# Если нам нужно имя переменной, совпадающее с ключевым словом Python,
-# мы используем подчёркивание в конце
-range_ = range(1, 900000000)
-
-# Будет удваивать все числа, пока результат не превысит 30
-for i in double_numbers(range_):
+# Генераторы эффективны с точки зрения памяти, потому что они загружают только данные,
+# необходимые для обработки следующего значения в итерации.
+# Это позволяет им выполнять операции с недопустимо большими диапазонами значений.
+# ПРИМЕЧАНИЕ: "range" заменяет "xrange" в Python 3.
+for i in double_numbers(range(1, 900000000)): # "range" - генератор.
print(i)
if i >= 30:
break
+# Так же, как вы можете создать интерпретации списков, вы можете создать и
+# интерпретации генераторов.
+values = (-x for x in [1,2,3,4,5])
+for x in values:
+ print(x) # Выводит -1 -2 -3 -4 -5
+
+# Вы также можете преобразовать интерпретацию генератора непосредственно в список.
+values = (-x for x in [1,2,3,4,5])
+gen_to_list = list(values)
+print(gen_to_list) # => [-1, -2, -3, -4, -5]
+
# Декораторы
-# В этом примере beg оборачивает say
-# Метод beg вызовет say. Если say_please равно True,
-# он изменит возвращаемое сообщение
+# В этом примере "beg" оборачивает "say".
+# Если say_please равно True, он изменит возвращаемое сообщение.
from functools import wraps
@@ -614,7 +1020,7 @@ def beg(target_function):
def wrapper(*args, **kwargs):
msg, say_please = target_function(*args, **kwargs)
if say_please:
- return "{} {}".format(msg, " Пожалуйста! У меня нет денег :(")
+ return "{} {}".format(msg, "Пожалуйста! У меня нет денег :(")
return msg
return wrapper
@@ -626,8 +1032,8 @@ def say(say_please=False):
return msg, say_please
-print(say()) # Вы не купите мне пива?
-print(say(say_please=True)) # Вы не купите мне пива? Пожалуйста! У меня нет денег :(
+print(say()) # Вы не купите мне пива?
+print(say(say_please=True)) # Вы не купите мне пива? Пожалуйста! У меня нет денег :(
```
@@ -635,17 +1041,18 @@ print(say(say_please=True)) # Вы не купите мне пива? Пожал
### Бесплатные онлайн-материалы
-* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
-* [Dive Into Python](http://www.diveintopython.net/)
+* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
* [Ideas for Python Projects](http://pythonpracticeprojects.com)
* [Официальная документация](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)
-
-### Платные
-
-* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
-* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
-* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
+* [Python Course](http://www.python-course.eu/index.php)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
+* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
+* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/)
+* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/)
+* [Dive Into Python 3](http://www.diveintopython3.net/index.html)
+* [A Crash Course in Python for Scientists](http://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/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown
index f2b1fd36..b1931f9a 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+.
diff --git a/set-theory.html.markdown b/set-theory.html.markdown
index 6fb657ed..c6e72960 100644
--- a/set-theory.html.markdown
+++ b/set-theory.html.markdown
@@ -41,10 +41,10 @@ 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 1, i.e. `|∅| = 1`.
+* the cardinality of the empty set is 0, i.e. `|∅| = 0`.
## Representing sets
@@ -82,12 +82,12 @@ D = { 2x : x ∈ N } = { 0, 2, 4, 6, 8, ... }
* If two sets contain the same items then we say the sets are equal, e.g. `A = B`.
* Order does not matter when determining set equality, e.g. `{ 1, 2, 3, 4 } = { 2, 3, 1, 4 }`.
* Sets are disjoint, meaning elements cannot be repeated, e.g. `{ 1, 2, 2, 3, 4, 3, 4, 2 } = { 1, 2, 3, 4 }`.
-* Two sets `A` and `B` are equal if and only if `A ⊂ B` and `B ⊂ A`.
+* Two sets `A` and `B` are equal if and only if `A ⊆ B` and `B ⊆ A`.
## 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/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/smalltalk.html.markdown b/smalltalk.html.markdown
index 58dccae4..aaa592dc 100644
--- a/smalltalk.html.markdown
+++ b/smalltalk.html.markdown
@@ -22,7 +22,7 @@ Yes, everything. Integers are instances of one of the numeric classes. Classes a
- The system knows the class of the object receiving a message and looks up the message in that class's list of methods. If it is not found, the lookup continues in the super class until either it is found or the root of the classes is reached and there is still no relevant method.
- If a suitable method is found the code is run, and the same process keeps on going with all the methods sent by that method and so on forever.
- If no suitable method is found an exception is raised, which typically results in a user interface notifier to tell the user that the message was not understood. It is entirely possible to catch the exception and do something to fix the problem, which might range from 'ignore it' to 'load some new packages for this class and try again'.
-- A method (more strictly an instance of the class CompiledMethod) is a chunk of Smalltalk code that has been compiled into bytecodes. Executing methods start at the beginning and return to the sender when a return is encountered (we use ^ to signify 'return the follwing object') or the end of the code is reached, in which case the current object running the code is returned.
+- A method (more strictly an instance of the class CompiledMethod) is a chunk of Smalltalk code that has been compiled into bytecodes. Executing methods start at the beginning and return to the sender when a return is encountered (we use ^ to signify 'return the following object') or the end of the code is reached, in which case the current object running the code is returned.
### Simple syntax
Smalltalk has a simple syntax with very few rules.
@@ -41,7 +41,7 @@ We are sending the message 'doSomethingWith:' to myObject. This happens to be a
'myObject' is a 'MyExampleClass' instance so the system looks at the list of messages understood by MyExampleClass
- beClever
-- doWierdThing:
+- doWeirdThing:
- doSomethingWith
In searching we see what initially looks like a match - but no, it lacks the final colon. So we find the super class of MyExampleClass - BigExampleClass. Which has a list of known messages of its own
diff --git a/solidity.html.markdown b/solidity.html.markdown
index cc719ec7..251e9008 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);
@@ -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/sql.html.markdown b/sql.html.markdown
index 5edf0f7c..685e522d 100644
--- a/sql.html.markdown
+++ b/sql.html.markdown
@@ -5,7 +5,7 @@ contributors:
- ["Bob DuCharme", "http://bobdc.com/"]
---
-Structured Query Language (SQL) is an ISO standard language for creating and working with databases stored in a set of tables. Implementations usually add their own extensions to the language; [Comparison of different SQL implementations](http://troels.arvin.dk/db/rdbms/) is a good reference on product differences.
+Structured Query Language (SQL) is an [ISO/IEC 9075](https://www.iso.org/standard/63555.html) standard language for creating and working with databases stored in a set of tables. Implementations usually add their own extensions to the language; [Comparison of different SQL implementations](http://troels.arvin.dk/db/rdbms/) is a good reference on product differences.
Implementations typically provide a command line prompt where you can enter the commands shown here interactively, and they also offer a way to execute a series of these commands stored in a script file. (Showing that you’re done with the interactive prompt is a good example of something that isn’t standardized--most SQL implementations support the keywords QUIT, EXIT, or both.)
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 689c5191..39a5cc52 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.
@@ -822,6 +822,17 @@ for _ in 0..<10 {
See more here: https://docs.swift.org/swift-book/LanguageGuide/AccessControl.html
*/
+// MARK: Preventing Overrides
+
+// You can add keyword `final` before a class or instance method, or a property to prevent it from being overridden
+class Shape {
+ final var finalInteger = 10
+}
+
+// Prevent a class from being subclassed
+final class ViewManager {
+}
+
// MARK: Conditional Compilation, Compile-Time Diagnostics, & Availability Conditions
// Conditional Compilation
diff --git a/tcl.html.markdown b/tcl.html.markdown
index 3d23870b..1b577b49 100644
--- a/tcl.html.markdown
+++ b/tcl.html.markdown
@@ -273,7 +273,7 @@ namespace eval people::person1 {
###############################################################################
-## 4. Built-in Routines
+## 5. Built-in Routines
###############################################################################
# Math can be done with the "expr":
diff --git a/tr-tr/jquery-tr.html.markdown b/tr-tr/jquery-tr.html.markdown
new file mode 100644
index 00000000..4a4ebeae
--- /dev/null
+++ b/tr-tr/jquery-tr.html.markdown
@@ -0,0 +1,338 @@
+---
+category: tool
+tool: jquery
+contributors:
+ - ["Seçkin KÜKRER", "https://github.com/leavenha"]
+filename: jquery-tr-tr.js
+lang: tr-tr
+---
+
+# Tanım
+
+jQuery, (IPA: ˈd͡ʒeɪˌkwɪəɹiː).
+j + Query, olarak isimlendirilmiş, çünkü çoğunlukla HTML elementlerini sorgulamak ve onları manipüle etmek için kullanılır.
+
+jQuery, 2006 yılında geliştirilmiş ve günümüzde halen kullanımı yaygın, görece en popüler çapraz-platform JavaScript kütüphanelerinden birisidir. Şimdilerde jQuery ekibi tarafından gelişimi devam etmektedir. Dünyanın bir çok yerinden büyük şirketler ve bağımsız yazılım ekipleri tarafından kullanılmaktadır.
+
+Genel kullanım amacı animasyonlardır; Galeri, ek menü, sayfa geçişleri, ve diğer tüm gerçeklemelere sağladığı kolaylıkla birlikte Flash'ın alternatifi olarak yorumlanabilir. [Ajax][ajax-wikipedia-page] işlemleri de dahil olmak üzere olay-yönetimi, döküman manipülasyonu ve bir çok programlama görevini kolaylaştırır.
+
+Resmi sitesinden ([jQuery][jquery-official-website]) indirip web sitenize yükleyebilirsiniz. jQuery günümüz JavaScript kütüphaneleri gibi, küçültülmüş boyutlarda bulut tabanlı İçerik Dağıtım Ağı sistemleri sayesinde bağımsız olarak da sitenize eklenebilir.
+
+Kütüphanenin kullanımı ile, jQueryUI gibi ek paketlerle gelişmiş ve modern arayüzler gerçekleyebilirsiniz.
+
+Fakat, jQuery'ye giriş yapmadan önce elbetteki bu kütüphanenin üzerine kurulduğu teknoloji olan [JavaScript'i öğrenmelisiniz][javascript-learnxinyminutes-page].
+
+```js
+
+// Bu belgedeki değişken isimleri Türkçe,
+// ve [Lower Camel Case] notasyonu uygulamaktadır.
+// Bu belgedeki kod parçalarının çıktıları,
+// onları uyguladığınız dökümanın içeriğine bağlı olarak değişmektedir.
+
+// Döküman boyunca, aşağıdaki gösterimde
+// Kod - Çıktı ikilisi ile içeriğin anlamlandırılması
+// kolaylaştırılmaya çalışmıştır.
+// ornek_kod_parcasi();
+// => "ÖRNEK ÇIKTI"
+
+// *. Konsept
+// jQuery DOM nesnelerini seçmek için inovatif bir yol sunar.
+// `$` değişkeni, `jQuery` kütüphanesine işaret eder.
+// Fonksiyon notasyonu ile DOM nesnelerini elde eder
+// ve üzerinde işlemler gerçekleştirirsiniz.
+$(window)
+// => jQuery [Window] (1)
+// Bize tarayıcının belirlediği window nesnesini verir.
+
+// 1. Seçiciler
+// Tüm nesneleri seçmek için `*` çağırımı yapılır.
+const hepsi = $('*');
+// => jQuery [<html>, <head>, <meta>,
+// .... <meta>, <title>, <meta>, <meta>,
+// .... <meta>, <link>, <link>, …] (1134) = $1
+
+// Seçiciler, jQuery'de bir nesne seçmek için kullanılırlar,
+const sayfa = $(window);
+// => jQuery [window] (1)
+// Sayfa, açık döküman nesnesini seçer.
+
+// Elementler, kendileri için seçicidirler.
+const tumParagraflar = $('p');
+// => jQuery [<p>, <p>, <p>] (3)
+
+// Seçiciler aynı zamanda CSS seçicileri olabilir.
+const mavi = $('.mavi');
+// => jQuery [<p class='mavi'] (1)
+
+// Aynı zamanda element ile birlikte kullanılabilirler.
+const maviParagraf = $('p.mavi');
+// => jQuery [<p class='mavi'>] (1)
+
+// Özellik seçicileri de mevcuttur,
+// Elementin özelliği için seçim yaparlar.
+const isimSecicisi = $('input[name*="kayit.form"]');
+// => jQuery [<input name='kayit.form.sifre'>,
+// <input name='kayit.form.dogumtarihi'> ...] (10)
+
+// Diğer özellik seçiciler;
+/*
+- Özelliğin içinde arayan; *=
+- Özelliğin içinde verilen kelimeleri arayan; ~=
+ |-(kelimeler boşlukla ayrılmalı, *='den farkına dikkat ediniz.)
+- Özelliğin başlangıç verisini arayan; ^=
+- Özelliğin bitiş verisini arayan; $=
+- Özelliği tamamen karşılaştıran; =
+- Özelliğin eşitsizlik durumunu karşılaştıran; !=
+
+Diğer tüm seçiciler için resmi siteyi kontrol ediniz.
+*/
+
+// 2. Olaylar ve Efektler
+// - Olaylar
+// jQuery kullanıcı ile tarayıcı arasındaki etkileşimi olaylar ile ele alır.
+
+// En yaygın kullanımı tartışmasız ki Dökümanın Yüklenmesi olayıdır.
+
+// $.ready fonksiyonu, argüman olarak aldığı fonksiyonu,
+// seçilen eleman tamamen yüklendiğinde çağıracaktır.
+$(document).ready(function(){
+ // Dökümanın tamamı yüklendiğine göre, iş mantığımı çağırabiliriz.
+ console.info('Döküman yüklendi!');
+})
+// => jQuery [#document] (1)
+
+// Bir dökümanın tamamının yüklenmeden,
+// herhangi bir iş mantığı çalıştırmanın
+// neden kötü bir fikir olduğunu merak ediyorsanız,
+// ileri okuma kısmına danışabilirsiniz.
+
+// Önce Olay tanımlayalım.
+
+// Tıklama olayı için `$.click` olay tetikleyicisi kullanılıyor.
+$('.mavi').click(function(){
+ // Unutmayın ki, önceden tanımlanmış
+ // bir fonksiyonu da argüman olarak verebilirsiniz.
+ console.info('Mavi butona tıkladın!');
+})
+// => jQuery [<button>, <button>, <button>, <button>, <button>, …] (365)
+
+// Çift Tıklama olayı için `$.dblclick` olay tetikleyicisi kullanılıyor.
+$('.mavi').dblclick(function(){
+ console.info('Mavi butona çift tıkladın!');
+})
+// => jQuery [<button>, <button>, <button>, <button>, <button>, …] (365)
+
+// Seçilen Elemente birden fazla tetiklenecek fonksiyon tanımalamak
+// istersek, Olayları ve Fonksiyonları Anahtar-Değer yapısı sağlayan
+// Objeleri kullanarak da çağırabiliriz.
+
+// => tetiklenecekFonksiyon
+$('.mor').on({
+ click: () => console.info('Tek tıklama ile tetiklendim!'),
+ dblclick: () => console.info('Çift tıklama ile tetiklendim!'),
+ // ...
+});
+// => jQuery [<button>, <button>, <button>, <button>, <button>, …] (365)
+
+// Diğer olay tetikleyicileri;
+/*
+Elemente,
+- Fokus/Odaklanma; $.focus
+- Fokus/Odaklanmanın kaybedilmesi; $.blur
+- Farenin alanına girmesi; $.mouseenter
+- Farenin alanından çıkması; $.mouseleave
+
+Diğer tüm olay tetikleyicileri için resmi siteyi kontrol ediniz.
+*/
+
+// Tanımlanan olayları tetiklemek için,
+// Kullanıcı-Tarayıcı etkileşimi yerine elle çağrı yapmak da mümkün.
+// Tanımlama ile çağırım arasındaki fark sadece sağlanan argümanlardır.
+// Argümansız çağırım, olayı tetikler.
+
+// Tıklama olayını tetiklemek için.
+$('.mavi').click();
+// => Mavi butona tıkladın!
+// => jQuery [<button>] (1)
+
+// Çift Tıklama olayını tetiklemek için.
+$('.mavi').dblclick();
+// => Mavi butona çift tıkladın!
+// => jQuery [<button>] (1)
+
+// - Efektler
+// jQuery bir çok ön-tanımlı efekt sunmakta.
+// Bu efektler, belirli parametlerle, farklı iş mantıklarını
+// gerçeklemenize izin verebilir.
+// Önce parametresiz işlevlere göz atalım.
+
+// Elementleri saklayabilir,
+$('#slaytresmi').hide();
+// => jQuery [<img id='slaytresmi'>] (1)
+
+// Gizlenen elementleri tekrar görünür yapabilir,
+$('#slaytresmi').show();
+// => jQuery [<img id='slaytresmi'>] (1)
+
+// Yada dilediğiniz CSS niteliğini anime edebilirsiniz,
+
+// Bu parametre, anime etmek istediğiniz CSS özelliklerini
+// belirleyen Obje bilgisidir.
+// Yükseklik ve Genişlik bilgileri için değerler belirliyoruz.
+const animeEdilecekCSSOzellikleri =
+ {
+ weight: "300px",
+ height: "300px"
+ };
+
+// Diğer anime edilebilir CSS özellikleri;
+/*
+Elementin,
+- Opaklık; opacity
+- Dış çevre mesafesi; margin
+- Çerçeve yüksekliği; borderWidth
+- Satır yüksekliği; lineHeight
+
+Diğer tüm özellikler için resmi siteyi kontrol ediniz.
+*/
+
+// Bu parametre animasyonun süresini belirler.
+const milisaniyeCinsindenAnimasyonSuresi =
+ 1200;
+
+// Bu parametre, 'linear' yada 'swing' metin
+// bilgilerinden birini alır ve animasyonun
+// akıcılığını belirler.
+// x ∈ {'linear', 'swing'}
+const animasyonAkiciligi = 'linear';
+
+// Bu parametre, bir fonksiyondur ve
+// animasyondan sonra çağırılır.
+// Bir geri-çağırım (callback*) olarak değerlendirilebilir.
+const animasyonGeriCagirimFonksiyonu = function(){
+ console.info('Animasyon bitti!');
+};
+
+// Şimdi tanımlanan bilgilerimizle animasyonu çağırıyoruz.
+$('#slaytresmi').animate(animeEdilecekCSSOzellikleri,
+ milisaniyeCinsindenAnimasyonSuresi,
+ animasyonAkiciligi,
+ animasyonGeriCagirimFonksiyonu);
+// => jQuery [<img id='slaytresmi'>] (1)
+
+// Kütüphane `$.animate` fonksiyonu için, anime edeceğiniz
+// CSS özellikleri dışındaki tüm argümanlar için
+// ön tanımlı değerler sağlamaktadır.
+// Bu değerler için resmi siteyi kontrol ediniz.
+
+// Diğer ön tanımlı efektler;
+/*
+Elementi,
+- Yukarı kaydırır; $.slideUp
+- Verilen saydamlık değerine anime eder; $.fadeTo
+- Görünür yada görünmez yapar (geçerli durumuna bağlı); $.toggle
+
+Diğer tüm efektler için resmi siteyi kontrol ediniz.
+*/
+
+// 3. Manipülasyon
+
+// jQuery'de, HTML elementlerinin isteğiniz doğrultusunda
+// değiştirilmesi için araçlar sunulmakta.
+
+// Bir ön-tanımlı CSS sınıfımız olduğunu hayal edebilirsiniz.
+// Bu sınıfı istediğimiz elemente uygulamak için,
+$('#slaytresmi').addClass('inanilmaz-bir-cerceve-sinifi');
+// => jQuery [<img id='slaytresmi' class='inanilmaz-bir-cerceve-sinifi'>] (1)
+
+// Bu CSS sınıfını istediğimiz zaman silebiliriz,
+$('#slaytresmi').removeClass('inanilmaz-bir-cerceve-sinifi');
+// => jQuery [<img id='slaytresmi'>] (1)
+
+// Bu HTML elementini, istediğimiz başka bir element ile çevreleyebiliriz,
+$('#slaytresmi').wrap('<div class="farkli-bir-cerceve"></div>');
+// => jQuery [<img id='slaytresmi'>] (1)
+// Sonucun gözlemlenebilmesi için, elementin çevreleme işlemi sonrası
+// döküman üzerindeki yapısını temel bir seçici ile gözlemleyebiliriz;
+$('.farli-bir-cerceve')
+// => jQuery [<div class='farkli-bir-cerceve>] (1)
+// => <div class="farkli-bir-cerceve">
+// <img id='slaytresmi'>
+// </div>
+
+// Elemente içerik ekleyebiliriz,
+// Eklemeler döküman içeriğinin sonuna yapılacaktır.
+// Bu süreci daha iyi gözlemleyebilmek için içeriğine bakmamız yeterli,
+// Ekleme öncesinde;
+$('.farkli-bir-cerceve');
+// => jQuery [<div class='farkli-bir-cerceve>] (1)
+// => <div class="farkli-bir-cerceve">
+// <img id='slaytresmi'>
+// </div>
+
+// `$.append` fonksiyonu ile ekleme işlemini yapıyoruz.
+$('.farkli-bir-cerceve').append('<h1>Bu çerçeve farklı!</h1>');
+// => jQuery [<div class='farkli-bir-cerceve>] (1)
+// => <div class="farkli-bir-cerceve">
+// <img id='slaytresmi'>
+// <h1>Bu çerçeve farklı!</h1>
+// </div>
+
+// Dökümandan element silebiliriz,
+$('.farkli-bir-cerceve > h1').remove();
+// => jQuery [<h1>] (1)
+
+// Dökümanın güncel halini görmek için seçiciyi çağırıyoruz,
+$('.farkli-bir-cerceve');
+// => jQuery [<div class='farkli-bir-cerceve>] (1**
+// => <div class="farkli-bir-cerceve">
+// <img id='slaytresmi'>
+// </div>
+
+// Elementlerin özniteliklerini değiştirebilir yada
+// silebiliriz.
+// Öznitelik erişici ve değiştiricisi,
+// Bir fonksiyon notasyonuyla yapılanmış durumda.
+// Eğer bir öznitelik bilgisini almak istiyorsak, ilgili öznitelik
+// ismini;
+
+$('.farkli-bir-cerceve > img').attr('id');
+// => 'slaytresmi'
+
+// Eğer bir öznitelik bilgisini güncellemek istiyorsak,
+// ilgili öznitelik ismi ve sonrasında yeni değerini argüman
+// olarak $.attr fonksiyonuna iletiyoruz;
+
+$('.farkli-bir-cerceve > img').attr('id', 'cercevelislaytresmi');
+// => jQuery [<img id='cercevelislaytresmi'>] (1)
+
+// Diğer ön fonksiyonlar;
+/*
+Elementin,
+- Yükseklik değeri, $.height
+- HTML döküman içeriği, $.html
+- Girdi içeriği, $.val
+- Verilen CSS sınıfına sahipliği, $.hasClass
+
+Diğer tüm manipülasyon fonksiyonları için resmi siteyi kontrol ediniz.
+*/
+
+```
+
+## Notlar
+
+- Yaygın bir yanlış bilineni düzeltmek adına; jQuery bir çalışma-çatısı değil, bir *kütüphanedir*.
+- [Lower Camel Case][lower-camel-case-notasyonu] notasyonu için Wikipedia sayfası.
+
+## İleri Okuma
+
+### İngilizce
+
+- [jQuery][jquery-official-website] resmi sitesi.
+
+- [Jakob Jenkov | $(document).ready article](http://tutorials.jenkov.com/jquery/document-ready.html)
+
+[jquery-official-website]: https://jquery.com
+[ajax-wikipedia-page]: https://en.wikipedia.org/wiki/Ajax_(programming)
+[javascript-learnxinyminutes-page]: https://learnxinyminutes.com/docs/javascript/
+[lower-camel-case-notasyonu]: https://en.wikipedia.org/wiki/Camel_case#Programming_and_coding
diff --git a/tr-tr/ruby-tr.html.markdown b/tr-tr/ruby-tr.html.markdown
new file mode 100644
index 00000000..7bc21c83
--- /dev/null
+++ b/tr-tr/ruby-tr.html.markdown
@@ -0,0 +1,1598 @@
+---
+name: ruby
+language: ruby
+filename: learnruby-tr.rb
+contributors:
+ - ["Seçkin KÜKRER", "https://github.com/LeaveNhA"]
+lang: tr-tr
+---
+
+# Dile nazik bir giriş.
+
+## Ruby Nedir ?
+
+Ruby, doğrudan bir Google aramasıyla aklınızdakini bulmanız zor olabilir. İngilizce bu kelime, `Ruby` (IPA: ˈruːbi) "kırmızı taş" anlamına gelen Fransızca kökenli bir kelime olan `rubi`'den gelmektedir.
+
+Yaratıcısı tarafından, yine esinlenilen bir dil olarak ortaya çıkan `Ruby`, Perl, Smalltalk, Eiffel, Ada, Lisp programlama dillerinin en iyi özelliklerini almıştır. ! [İmperativ]() programlama mentalitesi üzerine kurmayı seçtiği bu teknoloji, günümüzde sektöründe öncü.
+
+
+## Tarihçe
+
+Ruby 1995’te halka duyurulduğundan beri, dünya çapında programcıların dikkatini çekmeye başlamıştır. 2006 Ruby’nin altın yılı olmuştur. Dünyanın en büyük şehirlerinde aktif kullanıcı grupları ve Ruby ile ilgili konferanslar gerçekleştirilmiştir.
+
+Daha sonraları `Ruby`, dünya çapında programlama dillerinin büyümesini ve popülaritesini ölçen dizinlerin (TIOBE dizini gibi) çoğunda ilk 10 içinde yer almıştır. Büyümenin çoğu, Ruby ile yazılmış yazılımların popülaritesiyle ilgilidir, özellikle de Ruby on Rails web çatısıyla.
+
+! [kaynak]()
+
+## Sektördeki Konumu ve Geleceği ?
+
+Çoğu uzmana göre, şu anda sadece `Rails` teknolojisi için bir betik dili olarak sıkışmış durumda.
+
+Bazıları ise, dilin kendi geleceğini, 2020 içinde yayınlanması planlanan `Ruby 3` ile sağlamlaştıracağını ve yeni imkanlar ve sektörek kullanım ve tercihler ile popüleritesinin artacağını düşünüyor.
+
+## Her Şey Nesne
+
+Matz'ın incelemiş olduğu diller sonucunda, teknik olarak en iyi sözdizimin kaynağını “Perl’den daha güçlü ama Python’dan daha nesneye yönelik bir betik dili” olarak tanımlamış.
+
+Her şeyin Nesne olarak görüldüğü bir programlama teknolojisi, bütünlük kavramı açısından herkese kucak açan bir pürüzsüzlük sunuyor. `Ruby`'nin neden tartışmasız, saf bir Nesne yönelimli bir programlama dili olduğuna dair örnekleri aşağıda vereceğim.
+
+## Diğer Gerçeklemeler
+
+- [JRuby](http://jruby.org/), JVM’in (Java Virtual Machine) üstünde çalışan Ruby’dir, JVM’in eniyileyen JIT derleyicisi, çöp toplayıcısı, eşzamanlı thread’leri, araç ekosistemi, ve muazzam sayıdaki kütüphanelerinden faydalanır.
+- [Rubinius](http://rubini.us/), ‘Ruby’da yazılmış Ruby’dir’. LLVM’in üstüne inşa edilmiştir ve ayrıca diğer dillerin üstüne inşa edebilecekleri şık bir sanal makine de sunar.
+- [TruffleRuby](https://github.com/oracle/truffleruby), GraalVM’in üstünde çalışan yüksek performanslı bir Ruby gerçeklemesidir.
+- [IronRuby](http://www.ironruby.net/), “.NET Web Çatısı’yla sıkı sıkıya bağlı” bir gerçeklemedir.
+
+Diğer gerçeklemeler için, lütfen ileri okumaya danışınız.
+
+```ruby
+# Bu karakter ile başlayan satırlar, yorum satırı olarak değerlendirilir.
+# Diğer yorum satırı tanımlamaları için tanımlamalar ve ifadeler kısmına danışın.
+
+## Örnek yapısı; bu örnek dosyadaki her Ruby ifadesi, Ruby yorumlayıcısı
+## tarafından yorumlanarak sonucu `=>` ifadesinin sağına yazılır.
+## örnek ifade #=> örnek sonuç
+## formatındadır.
+## Bazen satır aşımını önlemek için
+## örnek ifade
+## #=> örnek sonuç
+## şeklinde yer verilecektir.
+
+# --------------------------------
+# Veriler ve Temsilleri
+# --------------------------------
+
+## --
+## Sayılar:
+## --
+### Ruby, tamsayı veri tipini destekler. Sayısal değerlerin sisteminizdeki temsili
+### bu veri yapısıdır.
+
+# Tam sayı örneği.
+1453 #=> 1453
+
+## Okunabilirlik için, binlik ya da ondalık kısmını `_` ile
+## ayırmak mümkündür ve bu karakter tümüyle görmezden gelinir.
+3_14 #=> 314
+
+## Negatif sayılar `-` ile başlıyor.
+-3750 #=> -3750
+
+## Oktal sayılar
+03603 #=> 1923
+
+## Onaltılık sayılar
+0x23B #=> 571
+
+## İkilik sayılar
+0b11110000011 #=> 1923
+
+## Büyük sayılar temsili
+12345678901234567890 #=> 12345678901234567890
+
+## Kayan noktalı sayılar
+
+## Bir kayan-noktalı/Ondalıklı sayı.
+3.14 #=> 3.14
+
+## Bilimsel notasyon
+1.0e3 #=> 1000.0
+
+## Bir ipucu,
+## üsten önce işaret!
+3e+9 #=> 3000000000.0
+
+## --
+# Mantıksal Değerler
+## --
+
+## Mantıksal doğru ifadesi.
+true #=> true
+
+## Mantıksal yanlış ifadesi.
+false #=> false
+
+## --
+# Metinler
+## --
+
+## Metin sabitleri
+'Bu, bir metin ifadesi.'
+
+## Kaçışlar için
+'Kaçışlar için "\\"' #=> "Kaçışlar için \"\\\""
+
+## Alternatif ise çift tırnaklı ifadeler.
+"Bu da bir metin ifadesi."
+
+## Kaçışlarda farkı ise,
+"Kaçılar için '\\'" #=> "Kaçılar için '\\'"
+## bazı kaçış notasyonlarına gerek kalmaması.
+
+## Bazı notasyon karakterleri
+
+### Yeni Satır (New Line 0x0a)
+"\n" #=> "\n"
+
+### Boşluk (Space 0x20)
+"\s" #=> "\s"
+
+## --
+# Karakterler
+## --
+
+## Basitçe önlerine soru işareti getirilmiş
+## tek karakter sabitleridir.
+?a #=> "a"
+
+
+## --
+# Semboller
+## --
+## Ruby'de semboller, temsilleri bakımından
+## Clojure'daki semboller ile benzerlerdir.
+:sembol #=> :sembol
+
+## Kendileri, birinci sınıf değerdir.
+:türk.class #=> Symbol
+## Ve aynı zamanda Unicode desteği vardır. (1.9 sürümünden beri)
+
+
+## --
+# Diziler
+## --
+## Basitçe, Ruby dizileri birilerinden virgül ile ayrılmış,
+## değer veya değer sahibi referansların köşeli parantezler
+## ile çevrelenmesi ile oluşturulur. ([])
+[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+
+## Metinler için de durum aynı.
+["Mustafa", "Kemal", "ATATÜRK"] #=> ["Mustafa", "Kemal", "ATATÜRK"]
+
+## Aynı zamanda, Ruby dizileri tip bağımsız nesne ardışıklarıdır.
+[1881, "Mustafa", "Kemal", "ATATÜRK", 1923, "∞"]
+## Aynı zamanda Unicode destekler (1.9 sürümünden beri)
+
+## --
+# Eşlemeler
+## --
+## Ruby eşlemeleri, süslü parantezler içinde virgül ile ayrılan,
+## anahtar ve değer ikililieridir.
+
+## Bir tane de olabilir,
+{"izmir" => "kızları"} #=> {"izmir" => "kızları"}
+
+## Ya da, birden fazla...
+{"izmir" => "kızları", "paris" => "sokakları"} #=> {"izmir" => "kızları", "paris" => "sokakları"}
+
+## Aslında her değeri anahtar veya değer olarak
+## yerleştirmek mümkün.
+
+## Sembolleri,
+{:zafer => "30 Ağustos!"} #=> {:zafer=>"30 Ağustos!"}
+
+## Rakamları bile.
+{28101923 => "Efendiler, yarın Cumhuriyeti'i ilân edeceğiz!"}
+#=> {28101923=>"Efendiler, yarın Cumhuriyeti'i ilân edeceğiz!"}
+
+## Semboller için ufak bir sözdizimsel şekerleme mevcut ki,
+{istanbul: "beyefendi"} #=> {:istanbul=>"beyefendi"}
+## Bu kullanıma göre, sembol anahtarlar ile değerler arasına
+## `=>` yerine basitçe sembolün başına gelecek `:` sembolü
+## getiriliyor.
+
+
+## --
+# Aralıklar
+## --
+## Ruby aralıkları temeliyle başlangıç ve bitiş
+## değerleri arasındaki aralığın veriye dönüştürülmesi
+## için bir dil olanağıdır.
+
+## (başlangıç..bitiş) notasyonu kullanılabilir.
+(0..10) #=> 0..10
+## REPL'ın bize verdiği ifade sizi yanıltmasın, bu bir aralıktır.
+## Meraklılarıyla, dökümanın devamında içindeki değerleri
+## gezeceğiz.
+
+## Range.new notasyonu ile de ilklenebilirler.
+Range.new(0, 10) #=> 0..10
+
+## --
+# Düzenli İfadeler
+## --
+## İki / operatörünün ortasına tanımlanırlar.
+//.class #=> Regexp
+
+## Örnek bir düzenli ifade, a harfi için.
+/[a]/ #=> /[a]/
+
+# --------------------------------
+# Değelerin Manipüle edilmesi
+# --------------------------------
+
+## --
+## Rakamlar
+## --
+
+## Aritmatik, bildiğimiz şekilde.
+## !! infix notasyon
+
+235 + 1218 #=> 1453
+123 - 35 #=> 88
+2 * 2 #=> 4
+1 / 1 #=> 1
+
+## Bit tabanlı işlemler.
+2 & 5 #=> 0
+3 | 9 #=> 11
+2 ^ 5 #=> 7
+## Aslında C tipi ailesi dillerdeki gibi. Sezgisel bir yaklaşımla, hayatta kalınabilir.
+## Ama yine de dökümantasyona başvurulmasını tavsiye ederim.
+
+
+## --
+## Mantıksal
+## --
+
+## ! operatörü teklidir, ve aldığı değerin mantıksal tersini alır.
+!true #=> false
+!false #=> true
+
+
+## --
+## Metinler
+## --
+
+### Boş mu ?
+"".empty? #=> true
+
+### Bir bölümünü alalım.
+"Ölürüm TÜRKİYEM!".slice(7, 7) #=> "Türkiye"
+## Bir başka şekilde, indis notasyonu ile,
+"Ölürüm Türkiye'm!"[7, 7] #=> "Türkiye"
+
+## Küçük harfe dönüştürelim
+"LAY-LAY-LOM sana göre sevmeler...".downcase
+#=> "lay-lay-lom sana göre sevmeler..."
+
+## Büyük harfa dönüştürelim
+"beşiktaş".upcase #=> "BEŞIKTAŞ"
+
+## Karakterlerine ayıralım
+"BEŞİKTAŞ".chars #=> ["B", "E", "Ş", "İ", "K", "T", "A", "Ş"]
+
+## Çevrelemek için
+"Ahmet Mete IŞIKARA".center(30)
+#=> " Ahmet Mete IŞIKARA "
+
+## İçerik kontrolü için include metodu
+"aşk".include?(?a) #=> true
+## argümanı metin tipinde de verebilirdik, ama
+## yukarıdaki temsillerde gördüğümüz gibi,
+## yorumlayıcı, karakter sabitini metin olarak işliyor zaten.
+
+## Konumunu alalım.
+"Dayı".index("a") #=> 1
+## Elbette, tasarımında sağlıklı kararlar alınmış her
+## dil gibi, Ruby'de 0'dan saymaya başlıyor.
+
+## Metin yerleştirme yapalım
+"Ali Baba'nın x çiftliği var.".sub("x", "bir")
+#=> "Ali Baba'nın bir çiftliği var."
+
+## Birden fazla eşleşme için, değiştirme yapalım
+"Dal sarkar x kalkar, x kalkar dal sarkar.".gsub("x", "kartal")
+#=> "Dal sarkar kartal kalkar, kartal kalkar dal sarkar."
+
+## Düzenli ifadeler ile, cümledeki sesli harfleri değiştirelim.
+"Bir berber bir bere...".gsub(/[ie]/, "*")
+#=> "B*r b*rb*r b*r b*r*..."
+
+## Diğer işlevler için ileri okumadaki kaynağa başvurunuz.
+
+
+## --
+## Eşlemeler
+## --
+
+## basit bir eşleme ile başlayalım.
+{:boy => 1.74} #=> {:boy => 1.74}
+
+## Belirli bir anahtar, eşlememizde barınıyor mu diye
+## kontrol ediyoruz.
+{:boy => 1.74}.has_key? :boy
+#=> true
+## Parantezlerin yokluğu sizi yanıltmasın,
+## bu bir fonksiyon çağırısıdır.
+
+## Eşlemeden veri çekiyoruz
+{:boy => 1.74}.fetch :boy
+#=> 1.74
+
+## Eşlemelere veri ekliyoruz
+{:boy => 1.74}.merge!(kilo: 74)
+#=> {:boy=>1.74, :kilo=>74}
+
+## Anahtarlarımıza bakalım
+{:boy=>1.74, :kilo=>74}.keys
+#=> [:boy, :kilo]
+
+## Değerlerimize bakalım
+{:boy=>1.74, :kilo=>74}.values
+#=> [1.74, 74]
+
+## Dizi olarak almak istersek
+{:boy=>1.74, :kilo=>74}.to_a
+#=> [[:boy, 1.74], [:kilo, 74]]
+## Endişelenmeyin, dönüşümler için koca bir bölüm
+## ayırdım.
+
+
+## --
+## Diziler
+## --
+
+## Örnek bir dizi ile başlayalım.
+["Mustafa", "Kemal", "ATATÜRK"]
+#=> ["Mustafa", "Kemal", "ATATÜRK"]
+
+## İlk değeri alıyoruz
+["Mustafa", "Kemal", "ATATÜRK"].first
+#=> "Mustafa"
+
+## Son Değeri,
+["Mustafa", "Kemal", "ATATÜRK"].last
+#=> "ATATÜRK"
+
+## Indis araması için `fetch` metodu.
+["Mustafa", "Kemal", "ATATÜRK"].fetch 1
+#=> "Kemal"
+
+## Var olamyan bir indis ararsak hata alıyoruz.
+
+## Fakat seçimli ikinci argüman bize indisin
+## bulunamaması halinde döndürülecek değeri
+## belirleme imkanı veriyor.
+["Mustafa", "Kemal", "ATATÜRK"].fetch 20101927, "Nutuk"
+#=> "Nutuk"
+
+## Birden fazla değer almak için, slice metodunu
+## kullanabiliriz
+["Fatih", "Sultan", "Mehmet"].slice 1..2
+#=> ["Sultan", "Mehmet"]
+
+## Ya da, indis notasyonu da kullanılabilir.
+["Fatih", "Sultan", "Mehmet"][1..2]
+#=> ["Sultan", "Mehmet"]
+
+## Baştan n tane eleman almak için take metodunu kullanıyoruz
+["Fatih", "Sultan", "Mehmet"].take 2
+#=> ["Fatih", "Sultan"]
+
+## Rastgele bir dizi elemanı elde etmek için sample metodunu
+## kullanıyoruz
+["Fatih", "Sultan", "Mehmet"].sample
+#=> "Fatih"
+
+## `sample` metodu seçimli bir argüman kabul eder.
+## bu argüman rastgele istenen eleman sayısını temsil eder
+["Fatih", "Sultan", "Mehmet"].sample 2
+#=> ["Fatih", "Sultan"]
+
+## Aradığınız eleman, dizide var mı kontrolü için
+## include? metodu kullanılıyor
+["Fatih", "Sultan", "Mehmet"].include? "Fatih"
+#=> true
+
+## Dizinizdeki elemanları koşul dahilinde seçimlemek için
+## select metodunu kullanıyoruz
+["Fatih", "Sultan", "Mehmet"].select {|s| s.include? ?a}
+#=> ["Fatih", "Sultan"]
+## Süzme işleminin koşulu, a karakteri içeren nesneler için olumlu.
+## Not: filter metodu, select için bir takma addır.
+
+## Ters bir yöntem, süzgeçleme için ise;
+["Fatih", "Sultan", "Mehmet"].reject {|s| s.include? ?a}
+#=> ["Mehmet"]
+## koşulumuz aynıydı, seçimleme metodumuzu değiştirdik.
+
+### Yapısal düzenlemeler için:
+## Dizileri ters çevirmek,
+["Fatih", "Sultan", "Mehmet"].reverse
+#=> ["Mehmet", "Sultan", "Fatih"]
+
+## Sıralamak için sort metodu,
+["İş", "Aşk", "Para"].sort
+#=> ["Aşk", "Para", "İş"]
+
+## Ön koşulla sıralamak için,
+["İş", "Aşk", "Para"].sort {|a,b| b <=> a }
+#=> ["İş", "Para", "Aşk"]
+## Koşulumuz basitçe tersine sıralamak için bir tanımdır.
+## ileride karşılaştırma operatörlerini göreceğiz.
+
+## Tekrarlı elemanların temizlenmesi için
+[1,2,3,4,5,6,7,1,2,4,1,5,6,1,2,5].uniq
+#=> [1, 2, 3, 4, 5, 6, 7]
+
+## Dizilerin birleştirilmesi için
+[1,2] + [3,4]
+#=> [1, 2, 3, 4]
+## infix notasyon sizi yanıltmasın,
+## tasarımı gereği, her şey sınıflar ve metotlarına çağırım
+## olarak yürüyor.
+## Kanıtlayalım;
+[1,2].+([3,4])
+#=> [1, 2, 3, 4]
+
+## Peki ya aynı elemanları içerebilecek dizileri birleştirmek
+## istersek ?
+[1,2] | [2,3,4]
+#=> [1, 2, 3, 4]
+## | operatörü bizi, nihai sonuçtaki tekrarlı veriden koruyor.
+
+## Peki ya bir diziyi, eleman bazında diğeriyle
+## süzmek istersek ?
+[1,2] - [2,3,4]
+#=> [1]
+## Notasyon sizi yanıltmasın, Küme gibi davranan bir dizi işlevi.
+
+### Veri Dönüşümleri için:
+## Dizideki her elemana uygulamak istediğiniz bir
+## dönüşümü, map metodu ile uygulayabilirsiniz,
+["Kontak İsmi",
+ "Kontak Telefon Numarası"].map {|element| "<label>#{element}</label>"}
+#=> ["<label>Kontak İsmi</label>", "<label>Kontak Telefon Numarası</label>"]
+## HTML konusu için yine LearnXinYminutes'e danışabilirsiniz.
+
+## Son elde ettiğimiz veriyi birleştirmek için,
+["<label>Kontak İsmi</label>",
+ "<label>Kontak Telefon Numarası</label>"].join ""
+#=> "<label>Kontak İsmi</label><label>Kontak Telefon Numarası</label>"
+
+## Veriyi indirgemek için ise reduce metodu kullanırız,
+["<label>Kontak İsmi</label>",
+ "<label>Kontak Telefon Numarası</label>"]
+ .reduce("") {|akümülatör, veri| akümülatör + veri}
+#=> "<label>Kontak İsmi</label><label>Kontak Telefon Numarası</label>"
+## Akümülatör, her operasyondan dönen ara-geçici değer.
+## Bu değeri, parantez içinde ilkledik,
+## eğer vermeseydik, dizinin ilk elemanı olacaktı.
+
+## Tabi, daha kolay bir yolu var;
+["<label>Kontak İsmi</label>",
+ "<label>Kontak Telefon Numarası</label>"].reduce(:+)
+#=> "<label>Kontak İsmi</label><label>Kontak Telefon Numarası</label>"
+## reduce metodu, ikili bir operasyonu (akümülatör için metot!)
+## sembol olarak vermenize izin verir ve bu, reduce için
+## indirgeme fonksiyonu olarak kullanılır.
+
+## Nüansları olsa da, son üç Ruby çağırımı aynı sonucu vermektedir.
+
+
+## --
+## Semboller
+## --
+
+## Ruby sembolleri, çalışma zamanında değiştirilemezler.
+## Ama metinsel değerlerden semboller elde etmek mümkündür.
+## Bunu dönüşümler kısmında işlemek daha doğru olacak diye düşündüm.
+
+# --------------------------------
+# Dönüşümler
+# --------------------------------
+
+## --
+# Rakamlar
+## --
+
+## Sayısal değerlerin diğer tiplere dönüşümü;
+
+## Sayısal -> Metinsel
+1923.to_s #=> "1923"
+
+## Sayısal -> Mantıksal
+!1923 #=> false
+## Farkedebileceğiniz gibi,
+## sayısal değerler, mantıksal doğru'ya değerlendiriliyor.
+
+## Sayısal -> Sembol
+## Maalesef, Ruby bile Sayısal değerden Sembol değerlerine
+## doğrudan dönüşüm için metot barındırmıyor.
+## Bunu yine de başarmak istersek, değeri önce
+## Metinsel'e dönüştürerek Sembol dönüşümü için hazırlarız.
+1923.to_s.to_sym
+#=> :"1923"
+
+## Sayısal -> Dizi | bölümlenerek
+## Yine doğrudan bir dönüşüm yoktur.
+## Böyle bir doğrudan dönüşüm teşvik de edilmez.
+## Ama ihtiyaç olabilecek bir dönüşüm.
+1923.to_s.split('')
+#=> ["1", "9", "2", "3"]
+## Öncelikle Metinsel dönüşüm yapılır, sonra
+## her bir karakter için ayrılır.
+## Yine her bir rakamı sayısal bir şekilde elde etmek için
+## her birini Metinsel'den Sayısal değere dönüştürecek
+## ifade aşağıdaki gibidir.
+1923.to_s.split('').map { |i| i.to_i }
+#=> [1, 9, 2, 3]
+
+
+## --
+# Mantıksal
+## --
+
+## Mantıksal -> Metinsel
+true.to_s #=> "true"
+false.to_s #=> "false"
+
+## Mantıksal değeler için gerçeklenmiş başka bir dönüşüm
+## metodu olmadığı için, bu kısmı dilde ufak bir nüansa ayırmak
+## istedim.
+## Kaynak için ileri okumaya başvurunuz.
+
+## Hangi programlama dilinden gelirseniz gelin,
+## dilde doğruluk değerleri diye bir küme vardır.
+## Hangi değerlerin mantıksal doğru değerine dönüşeceği,
+## bu değer yerine geçebileceği
+## fikri üzerine kurulu bir küme.
+## Ve Ruby'de nil değeri, false dışında, mantıksal yanlış değerine çözümlenen tek şey.
+## Bu ön bilgi ile doyduysak, başlayalım.
+
+!!nil #=> false
+!!false #=> false
+!!0 #=> true
+!!"" #=> true
+## Şimdi ne oldu burada ?
+## `!!` ifadesi; değilinin değili, yani kendisi. Tek bir farkla.
+## Verinin türü değiştiriliyor. Mantıksal olarak yorumlanıyor.
+## Yukarıda, nil ve false ifadeleri mantıksal olarak yanlış olarak yorumlanıyor.
+## Diğerleri ise mantıksal doğru.
+
+
+## --
+# Metinsel
+## --
+
+## Metinsel -> Sayısal
+## Öncelikle dilde ufak bir tuzağa dikkat çekmek isterim.
+"".to_i #=> 0
+"asd".to_i #=> 0
+## Sayısal yorumlaması geçersiz ve boş her metinsel değer,
+## 0 rakamına değerlendirilir.
+
+## Başarılı bir dönüşüm,
+"1234".to_i #=> 1234
+
+## Sayı sistemini belirleyebileceğiniz seçimli bir argüman
+## kabul ediyor, to_i metodu.
+"1234".to_i 5 #=> 194
+## 1234 sayısının, beşlik tabandaki karşılığı.
+
+## Tam sayı dışında doğrudan dönüşümler
+## dil olanağı olarak sunulmuş durumda;
+
+## Kompleks sayı olarak,
+"1234".to_c #=> (1234+0i)
+
+## Ondalık (Kayan-noktalı) sayı olarak,
+"1234".to_f #=> 1234.0
+
+## Rasyonel sayı olarak,
+"1234".to_r #=> (1234/1)
+
+## Metinsel -> Mantıksal
+
+## Mantıksal değerin kendisi için tersinin, tersini alırız
+!!"seçkin" #=> true
+
+## Mantıksal tersi için ise tersini,
+!"seçkin" #=> false
+
+## Metinsel -> Sembol
+"cengiz".to_sym #=> :cengiz
+
+## Metinsel -> Dizi
+"Cengiz Han".split #=> ["Cengiz", "Han"]
+
+## split metodu, seçimli argümanının varsayılan değeri
+## boşluk karakteridir.
+
+## Metinsel -> Dizi | bölümlenerek
+"Cengiz Han".split ""
+#=> ["C", "e", "n", "g", "i", "z", " ", "H", "a", "n"]
+
+
+## --
+# Sembol
+## --
+
+## Sembol -> Metinsel
+:metin.to_s #=> "metin"
+## Başka bir dönüşüm için dilin bir teşviki yoktur.
+
+## --
+# Diziler
+## --
+
+## Dizi -> Metinsel
+[1,2,3,4,5].to_s #=> "[1, 2, 3, 4, 5]"
+
+
+## --
+# Eşlemeler
+## --
+
+## Eşleme -> Dizi
+{a: 1, b: 2, c: 3}.to_a
+#=> [[:a, 1], [:b, 2], [:c, 3]]
+## Her bir anahtar-değer çifti bir dizi olarak
+## değerlendirilir ve elemanları sırasıyla
+## anahtar ve değerdir.
+
+## Eşleme -> Metinsel
+{a: 1, b: 2, c: 3}.to_s
+#=> "{:a=>1, :b=>2, :c=>3}"
+## inspect metodu için bir takma addır.
+
+
+# --------------------------------
+# Tanımlamalar, ifadeler, yorumlama.
+# --------------------------------
+
+## --
+## Yorumlama
+## --
+
+## Dökümanın başından beri gördüğümüz bu tek satır yorumlama operatörü
+## (#)
+## kendinden sonra gelen her şeyin, satır boyunca yorumlama olarak
+## değerlendirilmesi gerektiğini Ruby yorumlayıcısına söyler.
+
+## Ruby, farklı yorumlama imkanları da sağlamaktadır.
+## Örneğin;
+=begin
+ Başlangıç ifadesi (=begin), sonlandırma ifadesi (=end)
+ ile arasında kalan her şeyi yorum satırı olarak ele alır.
+=end
+
+## --
+## Global değişkenler.
+## --
+
+## Ruby evrensel değişkenleri, kapsamı en geniş değişken türüdür.
+## Her yerden erişilebilir...
+
+## Basitçe dolar sembolü ( $ ) ile başlarlar.
+$evrensel_bir_değişken = 42 #=> 42
+
+## Bir çok metadoloji ve yöntem ve teknoloji, size
+## evrensel değişkenler kullanmanın projenizi karmaşıklaştıracağı
+## ve bakımını zorlaştıracağını söyler; Haklıdırlar...
+
+## --
+## Varlık değişkenleri.
+## --
+
+## At ( @ ) sembölü ile başlarlar ve isimlerinin de ifade ettiği
+## gibi, kendileri bir Sınıf'ın değeridir.
+
+class Varlık
+ def initialize()
+ @varlık_değişkeni = 101
+ end
+
+ def göster()
+ puts "Varlık değişkeni: #@varlık_değişkeni"
+ end
+end
+
+varlık1 = Varlık.new()
+
+varlık1.göster()
+#=> Varlık değişkeni: 101
+
+## Sınıf tanımı şimdilik kafanızı karıştırmasın.
+## İlgilenmemiz gereken kısım;
+## @varlık_değişkeni = 101
+## ifadesidir. Ve nesne özelinde tanımlama yapar.
+## Kapsamı sadece o nesnedir.
+
+## ! NOT: ilklenmemiş varlık değişkenleri nil ön değeri ile
+## yaşam döngüsüne başlar.
+
+## --
+## Sınıf değişkenleri.
+## --
+
+## Sınıf değişkenleri iki at ( @@ ) sembölü ile başlarlar.
+## Tanımlar, herhangi bir metot içinde
+## kullanılmadan önce ilklenmelidirler.
+## İlklenmemiş bir Sınıf Değişkenine referansta bulunmak,
+## bir hata oluşturur.
+
+class Sınıf
+ @@sınıf_nesne_sayısı = 0
+
+ def initialize()
+ @@sınıf_nesne_sayısı += 1
+ end
+
+ def göster()
+ puts "Sınıf sayısı: #@@sınıf_nesne_sayısı"
+ end
+end
+
+sınıf_varlığı1 = Sınıf.new()
+sınıf_varlığı2 = Sınıf.new()
+sınıf_varlığı3 = Sınıf.new()
+
+sınıf_varlığı1.göster()
+#=> Sınıf sayısı: 3
+
+
+## --
+## Yerel değişkenler.
+## --
+
+## Yerel değişkenlerin isimlendirmesi küçük harf
+## ya da alt çizgi ( _ ) ile başlar ve kapsamı tanımın
+## yapıldığı sınıf, modül, metot yada blok içinde kalır.
+
+## --
+## Sabitler.
+## --
+
+## Ruby sabitleri, büyük harf ile tanımlanırlar ve
+## kapsamları için iki senaryo mevcuttur;
+
+## - Sınıf ya da Modül içinde tanımlanırlarsa
+## Tanımın yapıldığı blok içinden erişilebilir.
+
+## - Sınıf ya da Modül dışında yapılan tanımlar ise
+## Evrensel bir kapsama sahiptir ve her yerden
+## erişilebilirler.
+
+## Örneğin:
+
+class Sabit
+ SABİT = 299_792_458
+
+ def göster
+ puts "Sabit değer: #{SABİT}"
+ end
+end
+
+# Create Objects
+sabit = Sabit.new()
+
+sabit.göster()
+#=> Sabit değer: 299792458
+
+## İfadenin tanımındaki alt çizgiler sizi yanıltmasın
+## binlik ayracı olarak kullandım ve Ruby yorumlayıcısı
+## tamamen görmezden geliyor.
+## Bknz: Veriler ve Temsiller: Sayılar.
+
+## --
+## Sözde Değişkenler.
+## --
+
+## Ruby özel bir dil.
+## Öyle ki, Bazı sözde-değişkenler ile
+## size, ihtiyacınız olabileceği erişimi sağlar.
+## Ama onlara atama yapamazsınız.
+
+## Sözde değişkenler ve kullanımları
+## ile ilgili İleri okumaya başvurunuz.
+
+
+# --------------------------------
+# Konvansiyonlar ve teşvikler.
+# --------------------------------
+
+## Konvansiyonlar:
+
+## --
+## İsimlendirme Konvansiyonları:
+## Döküman boyunca yaptığım gibi,
+## tanımlayıcılar ve erişilebilir tanımlanmış ifadeler
+## için lütfen önerildiği gibi İngilizce kullanın.
+## İsimlendirme, Bilgisayar bilimlerinde yeterince
+## ağır bir zemin ve dilin teşvik ettiği rehber
+## ve önerdiği konvansiyonları takip ederek
+## bakımı, okuması ve geliştirmesi kolay projeler
+## gerçeklemek mümkündür.
+
+## --
+## Semboller, Metotlar ve Değişkenler için
+##-Snake Case ( snake_case ) kullanılması önerilir.
+
+## --
+## Sınıflar için Camel Case (CamelCase):
+## Sınıf isimlendirmeleri için önerildiği gibi,
+## Camel Case isimlendirme notasyonuna sadık kalın.
+
+## --
+## Dosyalar ve Klasörler için Snake Case (snake_case):
+## Dosya ve klasörleri isimlendirmek için lütfen
+## Snake Case isimlendirme konvansiyonuna sadık kalın.
+
+## --
+## Dosya Başına Bir Sınıf:
+## Her dosyada bir sınıf barındırmaya özen gösterin.
+
+## ---
+## Bu kısımdaki teşvik içerikleri
+## rubocop-hq/ruby-style-guide'dan gelmektedir.
+
+## ! Rehbere göre bu dökümanı düzenle!
+
+## --
+## Girintileme:
+## Girintileme için TAB yerine, iki boşluk kullanın.
+
+def bir_metot
+ birşeyler_yap
+end
+## Yerine;
+def bir_metot
+ birşeyler_yap
+end
+
+## --
+## Satır Başına Karakter:
+## Satır başına maksimum 80 karakter olacak şekilde
+## dökümanı yapılandırın.
+
+## --
+## Satır Sonları:
+## Unix-Stili satır sonlarını kulanın.
+## Eğer Git kullanıyorsanız;
+## $ git config --global core.autocrlf true
+## ifadesi sizi bu zahmetten kurtaracaktır.
+
+## --
+## Satır Başına Bir İfade:
+## Satır başına bir ifade kullanın.
+
+puts 'test!'; puts 'test!'
+## Yerine;
+puts 'test!'
+puts 'test!'
+
+## --
+## Boşluklar ve Operatörler:
+## Operatörler, virgüller, ifade ayraçları
+## aralarında boşluk bırakın.
+
+toplam=1+2
+x,z=1,2
+class FooError<StandardError;end
+## Yerine;
+toplam = 1 + 2
+x , z = 1 , 2
+class FooError < StandardError; end
+## Bir kaç istisna hariç
+## - Üs operatörü
+## - Rasyonel sayı gösteriminde kullanılan eğik çizgi.
+## - Güvenli gösterim operatörü.
+
+
+### Daha fazlası için ileri okumadaki
+### bu rehbere danışabilirsiniz...
+
+# --------------------------------
+# Bloklar, Kontrol blokları ve örnekler.
+# --------------------------------
+
+## --
+## Ruby Blokları:
+## Süslü parantezler ya da `do`, `end` ile çevrelenen,
+## değişkenleri ortama bağlı işlevlerdir.
+## Diğer dillerde !{Closure} ( closure ) karşılığı
+## bulur.
+## Ruby'de bloklar, ifadeleri gruplamanın bir şeklidir.
+## Bloklar tanımlandıklarında çalıştırılmazlar,
+## Ruby, bu yönetimi akıllıca yapar.
+
+## Örneğin;
+
+## Tanımlamamız
+def selamla_sonra_çağır
+ puts 'Selamlar!'
+ yield ## tüm sihir burada!
+end
+
+## Şimdi tanımı çağıralım
+selamla_sonra_çağır {puts 'Çağrı, gerçekleşti!'}
+#= Selamlar!
+#= Çağrı, gerçekleşti!
+#=> nil
+## Çağırım, kendini çağıran kaynağa nil döndürmekte.
+## Değerlendirmenin sonucunda, Ruby yorumlayıcısı,
+## ifadenin değerini nil olarak çıktılar.
+## Fakat, puts çağrıları, girdi/çıktı işlevimizi
+## yerine getirir ve metinleri ekrana basar.
+
+## Blokların argüman almaları da mümkündür:
+def selamla_sonra_değer_ile_çağır
+ puts 'Selamlar!'
+ yield('Hain Kostok') ## tüm sihir burada!
+end
+
+selamla_sonra_değer_ile_çağır {|isim| puts "Sana da selam, #{isim}!"}
+#= Selamlar!
+#= Sana da selam, Hain Kostok!
+#=> nil
+
+## Detaylı bilgi için, ileri okumaya başvurunuz.
+
+## --
+## Eğer ( if ) kontrol ifadesi:
+## Algoritmanızda dallanma imkanı sağlar.
+## Şablonu:
+## if koşul_ifadesi [then]
+## yürütülecek_kod
+## [elsif bir_diğer_koşul [then]
+## yürütülecek_diğer_kod]
+## [else
+## yürütülecek_bir_diğer_kod]
+## end
+
+## Bu kalıba sadık kalarak, dallanmalarımızı kodlarız.
+## Köşeli parantezler, sezgisel olarak anlaşılacağı üzere
+## seçimli ifadelerdir.
+
+## Örnek:
+if true
+ puts 'Koşul ifadesi, buradan devam edecek!'
+else
+ puts 'Buradan değil.'
+end
+#= Koşul ifadesi, buradan devam edecek!
+#=> nil
+
+## --
+## Eğer ( if ) düzenleyicisi:
+## Kompak bir dil olanağıdır. Aynı şekilde, çalıştırılacak kod
+## ve bir koşul ifadesi alır. Ve koşul ifadesine bakarak
+## ifadenin yürütüleceğine karar verir.
+## Şablonu:
+## çalıştırılacak_kod if koşul_ifadesi
+
+## Örnek:
+
+puts 'Bu ifade yürütülecek!' if true
+#= Bu ifade yürütülecek!
+#=> nil
+
+
+## --
+## Durum ( case ) kontrol ifadesi:
+## Bir koşul ifadesi ve bir ya da daha fazla karşılaştırma ifadesi
+## alarak, eşleşen bloğu yürütür.
+## Şablonu:
+## case koşullanacak_ifade
+## [when karşılaştırma_ifadesi [, karşılaştırma_ifadeleri ...] [then]
+## yürütülecek_kod ]...
+## [else
+## eşleşme_olmazsa_yürütülecek_kod ]
+## end
+
+yaş = 27
+case yaş
+when 0 .. 2
+ puts "bebek"
+when 3 .. 6
+ puts "küçük çocuk"
+when 7 .. 12
+ puts "çocuk"
+when 13 .. 18
+ puts "genç"
+else
+ puts "yetişkin"
+end
+#= yetişkin
+#=> nil
+
+## --
+## .. Sürece ( while ) kontrol ifadesi:
+## Aldığı koşul ifadesini kontrol eder,
+## kontrol bloğunu çağırır ve tekrar kontrol eder.
+## Koşul ifadesi doğru olduğu sürece, kontrol bloğu
+## çağırılmaya devam eder.
+## Şablonu:
+## while koşul_ifadesi [do]
+## yürütülecek_kod
+## end
+
+## Örnek:
+
+$n = 0
+$sayı = 5
+
+while $n < $sayı do
+ puts("Döngü içinde n = #$n" )
+ $n +=1
+end
+#= Döngü içinde n = 0
+#= Döngü içinde n = 1
+#= Döngü içinde n = 2
+#= Döngü içinde n = 3
+#= Döngü içinde n = 4
+#=> nil
+
+## --
+## .. Sürece ( while ) düzenleyicisi:
+## Eğer düzenleyecisi gibi, kompak bir dil olanağıdur.
+## Kontrol ifadesinin işlevini yerine getirir,
+## ama satır içi kullanıma müsade ederek.
+## Şablonu:
+## çalıştırılacak_kod while koşul_ifadesi
+## Yada:
+## begin
+## çalıştırılacak_kod
+## end while koşul_ifadesi
+
+## --
+## İçin ( for ) kontrol ifadesi:
+## N kere, I kere, X kere gibi ifadelerin dildeki kontrol
+## karşılığıdır. Çoklu veri üzerinde iterasyonlar yapmanızı
+## veri üzerinde operasyonlar yürütmenizi sağlar.
+## Şablonu:
+## for değişken [, başka_değişken ...] in ifade [do]
+## yürütülecek_kod
+## end
+
+## Örnek:
+for i in 1..5
+ puts i
+end
+#= 0
+#= 1
+#= 2
+#= 3
+#= 4
+#= 5
+#=> 0..5
+
+## Ardışıkları itere etmek için tek yol bu değil tabii.
+## İlerleyen kısımda buna yer verilecektir.
+
+## --
+## Sonlandırıcı ( break ) kontrol ifadesi:
+## Bu kontrol ifadesi yürütüldüğünde, çalışma zamanını
+## en iç tekrarlı bloktan çıkarır.
+
+## Örnek:
+for i in 1..5
+ break if i > 2
+ puts i
+end
+#= 0
+#= 1
+#= 2
+#=> nil
+## break kontrol ifadesi, if düzenleyecisi ile çevrelenmiştir.
+## if i > 2
+## break
+## end
+## ifadesi ile eşdeğerdir.
+## ifade yürütüldüğü anda, en yakın tekrarlı blok terkedilir.
+## Yorumlayıcı, sonraki ifadeden yürütmeye devam eder.
+
+## Diğer kontrol ifadeleri ve kullanımları için ileri okumaya başvurunuz...
+
+
+# --------------------------------
+# Özel anahtar kelimeler; kullanımları ve örnekleri.
+# --------------------------------
+
+## --
+## __ENCODING__:
+## Bu anahtar kelime size yorumlayıcı kodlama türünü verecektir.
+
+__ENCODING__
+#=> "#<Encoding:UTF-8>"
+
+## Platform, araç ve çalışma zamanı yürütme
+## yönteminize bağlı olarak alacağınız çıktı
+## değişiklik gösterebilir.
+
+## --
+## __LINE__:
+## Geçerli dosyada, yürütme satır numarasını verir.
+
+__LINE__
+#=> 67
+
+## Platform, araç ve çalışma zamanı yürütme
+## yönteminize bağlı olarak alacağınız çıktı
+## değişiklik gösterebilir.
+
+## --
+## BEGIN ve END:
+## BEGIN:
+## Dosyadaki tüm içerikten önce yürütülür.
+## END:
+## Dosyadaki tüm içeriklerden sonra yürütülür.
+
+## --
+## alias:
+## Herhangi bir tanımlayıcı için takma ad tanımlamanıza
+## olanak sağlar.
+
+$eski = 0
+alias $yeni $eski
+
+$yeni
+#=> 0
+
+## --
+## and:
+## Düşük öncelikli bir Mantıksal VE operatörü.
+
+## --
+## begin / end ve rescue:
+## İstisnalar begin / end blokları
+## arasında ele alınır ve `rescue` anahtar kelimesi ile
+## işlenirler.
+## İstisnalar ve mantalitesine dair ön girişi
+## Teşvik edilen paradigma ve anlatımı kısmında bulabilirsiniz.
+
+## Hata yönetimi, Ruby'de de özenle işlenmiş bir konudur.
+
+## Örnek:
+
+begin
+ yanlış_bir_hesaplama = 2/0
+ puts "Hesaplama sonucu: #{yanlış_bir_hesaplama}"
+ rescue ZeroDivisionError => hata_nesnesi
+ puts "Sıfıra bölümle ilgili bir hata yakalandı: #{hata_nesnesi.message}"
+end
+#= Sıfıra bölümle ilgili bir hata yakalandı: divided by 0
+#=> nil
+
+## Örneğimizde matematiksel sistemimiz için hatalı bir
+## işlem gerçekleştiriyoruz. Sonrasında hatayı ilgili
+## hata durumu için belirlediğimi alanda yönetiyoruz.
+## Örnekte hatayı çıktılayarak yönettik, gerçek dünyada
+## biraz daha kompleks gerçekleşebilir.
+## Gerçek dünya örnekleri için ileri okumaya başvurabilirsiniz.
+
+
+## --
+## defined?:
+## defined?, argümanını metinsel olarak açıklayan bir dil olanağıdır.
+
+## Örnek:
+RUBY_VERSION
+#=> "2.4.0"
+
+defined? RUBY_VERSION
+#=> "constant"
+
+defined? nil
+#=> "nil"
+
+defined? puts
+#=> "method"
+
+
+## --
+## ensure:
+## Hata yönetiminin bir parçası olarak dilde görev atfedilen ensure,
+## blok içinde, hata olsun ya da olmasın yürütüleceği garanti edilen
+## dil ifadeleri için bir imkandır.
+
+## Örnek:
+
+begin
+ yanlış_bir_hesaplama = 2/0
+ puts "Hesaplama sonucu: #{yanlış_bir_hesaplama}"
+ rescue ZeroDivisionError => hata_nesnesi
+ puts "Sıfıra bölümle ilgili bir hata yakalandı: #{hata_nesnesi.message}"
+ ensure
+ puts "Hesaplama bloğu sonlandı!"
+end
+#= Sıfıra bölümle ilgili bir hata yakalandı: divided by 0
+#= Hesaplama bloğu sonlandı!
+#=> nil
+
+
+## --
+## self:
+## Nesnenin kendisine erişim sağlayan bir dil olanağı.
+
+## Örnek:
+
+dünya = "Dünya!"
+#=> "Dünya!"
+
+dünya
+#=> "Dünya!"
+
+dünya.class
+#=> String
+
+def dünya.selamla
+ "Merhaba, " + self
+end
+#=> :selamla
+
+dünya.selamla
+#=> "Merhaba, Dünya!"
+
+## Nesnenin kendisine bir metot tanımladık,
+## bunu yaparken de değerine erişim sağladık.
+
+## --
+## super:
+## Nesne yönelimli programlama (spesifik olarak, obje tabanlı)
+## paradigmasına göre, kalıtım konseptinde, türeyen sınıfın
+## türetildiği sınıfa erişimi (üst sınıfı, atası, hiyerarşik üstü)
+## bu anahtar kelime ile gerçekleşir.
+
+class A
+ def initialize(a)
+ @a = a
+ end
+end
+
+class B < A
+ def initialize(a, b)
+ @b = b
+ super a
+ end
+end
+
+b = B.new 1, 2
+#=> #<B:0x00007f852d04c7e8 @b=2, @a=1>
+## super ile üst sınıfın ilklenmesi gerçekleştirildi,
+## aldığımız çıktıda da @a=1 çıktısıyla gözlemlenebilir.
+
+## Bu konunun, dilin paradigma teşviği ile ilgili
+## olduğunu ve anlamazsanız, Paradigma başlığını bitirdikten
+## sonra tekrar bu örneği değerlendirmeniz gerektiğini hatırlatırım.
+
+## --
+## yield:
+## Ruby blokları kısmında anlattık, ama, burada da bir nüanstan
+## bahsetmeden geçemeyeceğim.
+## Çalıştırılabilir ifadeleri çalıştırmanın birden fazla yolu vardır.
+## Fakat yield, en performanslı dil olanağı olarak dökümanda işlenmiş.
+## Kaynak için ileri okumaya danışın.
+
+
+
+# --------------------------------
+# G/Ç ( I/O )
+# --------------------------------
+
+=begin
+ G/Ç, Girdi/Çıktı ( Input/Output ) kısaltmasıdır.
+ Temelde, sistemden girdi almak ve çıktı yaratmak amacıyla vardır.
+ Girdi örnekleri:
+ - Klavyeden bastığınız herhangi bir tuş.
+ - Fare hareketleriniz ya da tıklamalarınız.
+ - Mikrofonunuzun aldığı sesler.
+
+ Çıktı örnekleri:
+ - Herhangi bir dil ifadesinin sonucu.
+ - Dijital bir ses dosyasının sese dönüşmesi.
+ - Ekranda gördükleriniz.
+
+ Fakat endişelenmeyin, G/Ç derken, şu anda
+ biz sadece Ruby'de,
+ - Dosya okuma/yazma.
+ - Ekrana metin yazdırma / Bilgi okuma.
+ - Ağ soketleri. ( biraz da olsa )
+ işlerinden bahsediyor olacağız.
+=end
+
+defined? IO
+#=> "constant"
+
+IO.class
+#=> Class
+
+## IO sınıfı, File ve Socket gibi pratik kullanımı olan sınıfların atasıdır.
+## Septikler için;
+
+File.superclass
+#=> IO
+## Gözlemlediğiniz üzere, superclass metodu, üst sınıfı veriyor.
+
+## --
+## Dosya Okuma ve Yazma:
+## Ruby'de dosya okuma ve yazma işlemleri için, File
+## sınıfını kullanacağız.
+
+## Dosyaya yazmak için;
+File.write 'test.txt', "a,b,c"
+#=> 5
+## 5, ifadenin ürettiği dönüş değeridir.
+## ve, çıktılanan karakter sayısını verir.
+
+## Dosyadan okuma için;
+## Bu kısım, açıklayıcı olması açısından
+## ifadeleri teker teker işleyeceğiz.
+
+File
+#=> File
+## Sınıfımız.
+
+File.readlines 'test.txt'
+#=> ["a,b,c"]
+## readlines File sınıfının bir metodu ve aldığı argüman dosya yoludur.
+
+File.readlines('test.txt').first
+#=> "a,b,c"
+## Dönüş değeri bir diziydi, her bir satır bir eleman olacak şekilde.
+## Biz, kendi verilerimizi, kendi ayıracımızla kaydetmeyi seçtik.
+## Eğer, `\n` satır ifadesi ile ayırmayı seçseydik, readlines
+## metodu zaten işlevi gereği, bize değerleri ayrı ayrı verecekti.
+
+File.readlines('test.txt').first.split ','
+#=> ["a", "b", "c"]
+## verilerimizi aldık.
+
+## Eğer yeni satır karakterini ayıraç olarak kullansaydık;
+File.write 'ntest.txt', ['a', 'b', 'c'].join("\n")
+#=> 5
+
+File.readlines('ntest.txt').map(&:chomp)
+#=> ["a", "b", "c"]
+## Bu da genel kullanımlı bir yaklaşımdır.
+
+## --
+## Ekrana bilgi yazdırma ve Okuma:
+## Konsol'a bilgi çıktılamak için,
+## önceden tanımlanmış $stdout global nesnesini kullanacağız.
+## Pratik kullanımda, prints işlevinden bir farkı yoktur.
+## Aynı sonuca ikisi ile de ulaşabilirsiniz.
+
+$stdout.print "Bu bir çıktı.\n"
+#= Bu bir çıktı.
+#=> nil
+
+## Şimdi kullanıcıdan bilgi okuyalım:
+$stdin.gets
+#! Bu kısımda hiç bir çıktı verilmez ve aksine
+#! sizden girdi beklenir. Bir metin yazın ve onaylamak için
+#! enter tuşunu kullanın.
+#- Bu bir girdi metni!
+#=> "Bu bir girdi metni!\n"
+
+## Aldığımız veriyi temizlenin yolunu biliyoruz.
+## Dönüş değerine chomp metodunu uygulamak.
+$stdin.gets.chomp
+#- Bu bir girdi metni!
+#=> "Bu bir girdi metni!"
+
+
+## --
+## Ağ girdi/çıktı yönetimi
+## Ruby'de soketler (Socket)
+## haricen çalışma zamanına dahil edilir.
+
+require 'socket'
+#=> true
+
+soket = TCPSocket.new('google.com', 80)
+#=> #<TCPSocket:fd 13, AF_INET, 192.168.0.11, 63989>
+## Alacağınız çıktı değişiklik gösterebilir.
+## Soketi oluşturduk ve bir değişkene atadık.
+## Şimdi bunun üzerinden okuma ve yazma işlemlerini
+## gerçekleştireceğiz.
+
+soket.write "GET / HTTP/1.1"
+#=> 14
+
+soket.write "\r\n\r\n"
+#=> 4
+## İki write metodunun sonucu da, sokete yazılan verinin
+## uzunluğudur.
+
+## Şimdi okuma zamanı, soketi açtık, isteğimizi bildirdik.
+## Şimdi soket üzerinden aldığımız cevabı ekrana yazdıralım.
+
+soket.recv 80
+#=> "HTTP/1.1 200 OK\r\nDate: Thu, 03 Sep 2020 10:48:21 GMT\r\nExpires: -1\r\nCache-Control"
+## Alacağınız çıktı değişiklik gösterebilir.
+## Ancak, başarılı şekilde okuma yaptık.
+
+
+
+# --------------------------------
+# Teşviğinde bulunduğu paradigma ve derinlemesine anlatımı.
+# --------------------------------
+
+## --
+## Nesne Yönelimli Programlama Nedir?
+## Kısaca NYP, en basit anlatımıyla;
+## nesnelerle programlamadır.
+## Nesne paradigması, her programcıya doğal ve sezgisel gelir.
+## Bunun sebebi, zaten gerçekliği algılama şeklimize uygun olmasıdır.
+## Araba, onu bir araya getiren nesnelerden oluşur,
+## tekerlekleri, direksiyonu, kasası, ve diğer parçalarıyla.
+## Ama bu, tam tanım değildir. NYP'de, Nesneler,
+## Bilgilere ( evet, varlık olarak başka nesneler de sayılabilir )
+## ve bu bilgileri yönetecek ( hesaplamalar gerçekleştirecek
+## ya da aksiyonlar alacak -- G/Ç -- gibi ) metotlara sahiptir.
+
+## Bir nesnenin en net tanımı böyle yapılabilirken,
+## NYP, bir gerçek dünya problemi için bir araya getirilmiş
+## -- çoğunlukla birden fazla -- sınıfların yapıları,
+## ilişkileri ve işlevlerini ele alır.
+
+## Bir paradigma olarak NYP, bizlere her varlığı nesne olarak
+## modellemeyi ve problem uzayımızdaki nesnelerle olan ilişkilerini
+## Ruby'de NYP için sağlanan imkanlarla yönetmeyi öğütler.
+
+## Sınıf içerisinde saklanan bilgiye öznitelik ya da özellik,
+## işlevlere ise metot denilir.
+## NYP jargonu için ileri okumaya başvurabilirsiniz.
+
+## --
+## Ruby'de NYP teşviki:
+
+## Nesneler, Sınıfların gerçeklenmiş halleridir.
+## Tam tersi ile, Sınıflar ise, nesnelerin soyut kalıplarıdır.
+
+## Bir sınıf tanımı yapalım ve gerçekleyelim:
+
+class Araba
+end
+#=> nil
+## Evet, evet. Tanımımız hiç bir öznitelik ( attributes ) ya da
+## metot ( method ) içermiyor.
+
+## Şimdi bir özellik ekleyelim
+class Araba
+ def initialize(hız)
+ @hız = hız
+ end
+end
+
+araba = Araba.new 100
+#=> #<Araba:0x00007f7f300e59c8 @hız=100>
+
+## En naif haliyle, hız bilgisi saklayan bir araba sınıfı gerçekledik.
+## initialize metodu, Ruby imkanları ile, nesne yaşam döngünüzün ilk adımıdır.
+## Bu döngüyü aşağıdaki gibi betimlemek mümkündür.
+## İlkleme ( initialize ) -> [İşlevlerin çağırımı] -> Sonlandırma
+## İlkleme, initialize metodu ile ele alınır, alınacak tüm argümanlar,
+## sınıfın iş mantığı doğrultusuyla, bu ilk işlevde yönetilir ve nesne
+## kullanıma hazır hale getirilir.
+
+## Şimdi bir işlev ekleyelim.
+
+class Araba
+ def initialize(hız)
+ @hız = hız
+ end
+
+ def git!
+ puts 'Hınn, hınn!'
+ end
+end
+
+araba = Araba.new 100
+#=> #<Araba:0x00007f7f300e59c8 @hız=100>
+
+## Şimdi metodu çağırıyoruz.
+araba.git!
+#= Hınn, hınn!
+#=> nil
+
+## Başlığın amacı sadece Ruby'nin NYP olanaklarını ve
+## teşviğini işlemek değil. Paradigmaya bir giriş kazandırmak.
+## Bundan dolayı, etkileşim içinde birden fazla sınıf görmeliyiz.
+
+class Tekerlek
+ YERLİ = 5
+ İTHAL = 1
+
+ def initialize (tür)
+ @güç = tür
+ end
+
+ def döndür!
+ @güç -= 1
+ end
+end
+
+class Araba
+ def initialize (hız)
+ @hız = hız
+ @tekerlekler = (1..4).map {|| Tekerlek.new(Tekerlek::YERLİ)}
+ end
+
+ def git!
+ if @tekerlekler.map(&:döndür!).filter {|ömür| ömür < 0}.first then
+ puts 'Paat!'
+ else
+ puts 'Hınnn, hınnn!'
+ end
+ end
+end
+
+## nesnemizi oluşturuyoruz
+araba = Araba.new 100
+
+## altı sefer, araba nesnesinin git! metodunu çağırıyoruz.
+(0..6).map {|| araba.git! }
+#= Hınnn, hınnn!
+#= Hınnn, hınnn!
+#= Hınnn, hınnn!
+#= Hınnn, hınnn!
+#= Hınnn, hınnn!
+#= Paat!
+#= Paat!
+
+## İş mantığımıza göre, arabamızın dört tekeri ve ve Yerli olanlar
+## 5 birim dayanıklılığa sahip. ;)
+## Bu beş birim tükenince, araba gitmek yerine,
+## patlak teker çıktısı alıyoruz.
+
+
+## Şimdiye kadar gördüklerimizi bir analiz edelim;
+## Araba, sınıfın ismi. Her sınıf, tanımlamasak da, temel bir
+## kurucu metot içerecek şekilde dil işleyicisi tarafından
+## ele alınıyor.
+## Bizim bir tanımımız var ama.
+## Hız bilgisi alıyoruz.
+## bu bilgi, sınıf özniteliğidir. Sınıf, bu bilgiye kendi içinden erişebilir.
+## Bir de, binek araçların dört tekerleği olduğu fikriyle,
+## nesne içinde, kurucu metot içinde dört tane Tekerlek nesnesi gerçekliyor
+## ve saklıyoruz.
+## İş mantığımıza göre onlara erişmemiz gerekiyor.
+## git! metodu içinde, erişiyor ve kullanıyoruz.
+## metotların sonundaki ünlem işareti bir konvansiyondur,
+## metotların saf olmayan çağırımlar gerçeklediği anlamına gelmektedir.
+## Kendilerini ( ya da sahip olduğu diğer nesneleri ) değiştirdikleri,
+## bir girdi/çıktı gerçekleştirdikleri yada buna benzer yan etki içeren
+## bir ifade barındırdıkları anlamına gelir.
+
+## Sizi temin ederim ki, NYP, bu dökümanı ( hali hazırda ~1560 satır )
+## genel anlatımı için bile ikiye katlayabilir.
+## Lütfen detaylı bilgi için ileri okumaya başvurunuz.
+```
+
+# İleri okumalar.
+
+Tümüyle İngilizce olan bu ileri okumalara inat, bu detaylı özgün Türkçe içeriği üretmek istedim.
+Dilerim, benden sonra katkıda bulunanlar olur.
+
+- [Ruby Style Guide](https://rubystyle.guide), Ruby stil rehberi.
+- [Ruby-Doc üzerinde Proc](https://ruby-doc.org/core-2.4.0/Proc.html), Ruby Blokları ve Proc kavramı için.
+- [Ruby-Doc üzerinde String](https://ruby-doc.org/core-2.6/String.html) sınıfı, işlevleri, metotları.
+- [Ruby-Doc üzerinde TrueClass](https://ruby-doc.org/core-2.5.1/TrueClass.html#method-i-to_s) Dildeki mantıksal ifadelerin gerçeklemesi olan TrueClass (ve FalseClass için de aynı bağlantı üzerinden içeriğe ulaşılabilir) dönüşüm içeriği kaynağı.
+- [Ruby Gerçeklemeleri Listesi](https://github.com/codicoscepticos/ruby-implementations) Ruby'nin farklı platformlardaki gerçeklemeleri. Opal ve Topaz dikkat çekenleridir.
+- [The Object-Oriented Thought Process](https://www.amazon.com/Object-Oriented-Thought-Process-Developers-Library/dp/0321861272) kitap, bir paradigma olarak NYP ve düşünce yapısından bahsediyor. Bir paradigma olarak, NYP, türetildiği temel paradigmadan ne almış, başka paradigmalara ne kadar imkan sağlıyor ve paralel paradigma uyumu konusunda tüm sorularınıza cevap bulabilirsiniz. Yazar, belli etmese de, pragmatik bir yaklaşımda.
+- [Block Argument](https://docs.ruby-lang.org/en/2.4.0/syntax/methods_rdoc.html#label-Block+Argument) Ruby Blokları ve yield hakkındaki Ruby resmi döküman sayfası ve alt başlığı.
+- [A Theory of Objects]() Class-Based Languages başlığında inceleniyorlar.
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/xml.html.markdown b/xml.html.markdown
index b4b54330..2a258d94 100644
--- a/xml.html.markdown
+++ b/xml.html.markdown
@@ -100,8 +100,9 @@ This is what makes XML versatile. It is human readable too. The following docume
A XML document is *well-formed* if it is syntactically correct. However, it is possible to add more constraints to the document, using Document Type Definitions (DTDs). A document whose elements are attributes are declared in a DTD and which follows the grammar specified in that DTD is called *valid* with respect to that DTD, in addition to being well-formed.
+Declaring a DTD externally:
+
```xml
-<!-- Declaring a DTD externally: -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE bookstore SYSTEM "Bookstore.dtd">
<!-- Declares that bookstore is our root element and 'Bookstore.dtd' is the path
@@ -114,8 +115,11 @@ A XML document is *well-formed* if it is syntactically correct. However, it is p
<price>30.00</price>
</book>
</bookstore>
+```
-<!-- The DTD file: -->
+The DTD file (Bookstore.dtd):
+
+```
<!ELEMENT bookstore (book+)>
<!-- The bookstore element may contain one or more child book elements. -->
<!ELEMENT book (title, price)>
@@ -128,10 +132,11 @@ A XML document is *well-formed* if it is syntactically correct. However, it is p
only contain text which is read by the parser and must not contain children.
Compare with CDATA, or character data. -->
<!ELEMENT price (#PCDATA)>
-]>
+```
-<!-- The DTD could be declared inside the XML file itself.-->
+The DTD could be declared inside the XML file itself:
+```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE bookstore [
diff --git a/yaml.html.markdown b/yaml.html.markdown
index 4f10a128..6dc5905e 100644
--- a/yaml.html.markdown
+++ b/yaml.html.markdown
@@ -127,11 +127,11 @@ base: &base
# indicate that all the keys of one or more specified maps should be inserted
# into the current map.
-foo: &foo
+foo:
<<: *base
age: 10
-bar: &bar
+bar:
<<: *base
age: 20
@@ -184,5 +184,5 @@ set2:
### More Resources
-+ [YAML official website](http://yaml.org/)
++ [YAML official website](https://yaml.org/)
+ [Online YAML Validator](http://www.yamllint.com/)
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/go-cn.html.markdown b/zh-cn/go-cn.html.markdown
index 37b4b137..2953acf3 100644
--- a/zh-cn/go-cn.html.markdown
+++ b/zh-cn/go-cn.html.markdown
@@ -40,7 +40,7 @@ import (
func main() {
// 往标准输出打印一行。
// 用包名fmt限制打印函数。
- fmt.Println("天坑欢迎你!")
+ fmt.Println("你好世界")
// 调用当前包的另一个函数。
beyondHello()
diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown
index c854169e..d653c58c 100644
--- a/zh-cn/haskell-cn.html.markdown
+++ b/zh-cn/haskell-cn.html.markdown
@@ -128,7 +128,7 @@ snd ("haskell", 1) -- 1
-- 一个接受两个变量的简单函数
add a b = a + b
--- 注意,如果你使用 ghci (Hakell 解释器),你需要使用 `let`,也就是
+-- 注意,如果你使用 ghci (Haskell 解释器),你需要使用 `let`,也就是
-- let add a b = a + b
-- 调用函数
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..83888338
--- /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, $s1 # 否则 [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/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/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/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/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-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`