summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--.gitattributes65
-rw-r--r--.travis.yml3
-rw-r--r--CHICKEN.html.markdown2
-rw-r--r--CONTRIBUTING.markdown3
-rw-r--r--Gemfile5
-rw-r--r--ISSUE_TEMPLATE.md6
-rw-r--r--PULL_REQUEST_TEMPLATE.md7
-rw-r--r--README.markdown2
-rw-r--r--Rakefile23
-rw-r--r--angularjs.html.markdown713
-rw-r--r--binary-search.html.markdown63
-rw-r--r--c++.html.markdown8
-rw-r--r--c.html.markdown16
-rw-r--r--clojure.html.markdown2
-rw-r--r--cs-cz/javascript.html.markdown2
-rw-r--r--csharp.html.markdown4
-rw-r--r--css.html.markdown6
-rw-r--r--de-de/go-de.html.markdown4
-rw-r--r--de-de/html-de.html.markdown120
-rw-r--r--de-de/ruby-de.html.markdown33
-rw-r--r--dynamic-programming.html.markdown2
-rw-r--r--el-gr/css-gr.html.markdown8
-rw-r--r--el-gr/java-gr.html.markdown6
-rw-r--r--es-es/edn-es.html.markdown111
-rw-r--r--es-es/jquery-es.html.markdown4
-rw-r--r--es-es/less-es.html.markdown393
-rw-r--r--es-es/powershell-es.html.markdown2
-rw-r--r--es-es/sass-es.html.markdown585
-rw-r--r--es-es/wolfram-es.html.markdown138
-rw-r--r--fr-fr/binary-search-fr.html.markdown67
-rw-r--r--fr-fr/dynamic-programming-fr.html.markdown55
-rw-r--r--fr-fr/jquery-fr.html.markdown142
-rw-r--r--fr-fr/vim.html.markdown239
-rw-r--r--fsharp.html.markdown7
-rw-r--r--go.html.markdown14
-rw-r--r--html.html.markdown2
-rw-r--r--it-it/c++-it.html.markdown283
-rw-r--r--it-it/python-it.html.markdown199
-rw-r--r--ja-jp/python3-jp.html.markdown898
-rw-r--r--java.html.markdown31
-rw-r--r--javascript.html.markdown11
-rw-r--r--jquery.html.markdown24
-rw-r--r--kdb+.html.markdown774
-rw-r--r--ko-kr/json-kr.html.markdown80
-rw-r--r--ko-kr/markdown-kr.html.markdown308
-rw-r--r--ko-kr/xml-kr.html.markdown168
-rw-r--r--ko-kr/yaml-kr.html.markdown172
-rw-r--r--latex.html.markdown13
-rw-r--r--less.html.markdown61
-rw-r--r--logtalk.html.markdown77
-rw-r--r--matlab.html.markdown6
-rw-r--r--messagepack.html.markdown172
-rw-r--r--nl-nl/xml-nl.html.markdown4
-rw-r--r--perl6.html.markdown527
-rw-r--r--php.html.markdown39
-rw-r--r--pl-pl/vim-pl.html.markdown236
-rw-r--r--powershell.html.markdown16
-rw-r--r--pt-br/asciidoc-pt.html.markdown129
-rw-r--r--pt-br/c-pt.html.markdown2
-rw-r--r--pt-br/clojure-macros-pt.html.markdown2
-rw-r--r--pt-br/git-pt.html.markdown2
-rw-r--r--pt-br/jquery-pt.html.markdown131
-rw-r--r--pt-br/php-composer-pt.html.markdown184
-rw-r--r--pt-br/ruby-pt.html.markdown58
-rw-r--r--pt-br/tmux-pt.html.markdown82
-rw-r--r--pt-br/vim-pt.html.markdown239
-rw-r--r--pt-pt/git-pt.html.markdown2
-rw-r--r--pyqt.html.markdown5
-rw-r--r--python.html.markdown2
-rw-r--r--python3.html.markdown17
-rw-r--r--racket.html.markdown11
-rw-r--r--red.html.markdown62
-rw-r--r--ru-ru/go-ru.html.markdown9
-rw-r--r--ru-ru/html-ru.html.markdown129
-rw-r--r--ru-ru/markdown-ru.html.markdown2
-rw-r--r--ru-ru/php-ru.html.markdown157
-rw-r--r--ru-ru/typescript-ru.html.markdown2
-rw-r--r--ru-ru/vim-ru.html.markdown241
-rw-r--r--ru-ru/xml-ru.html.markdown15
-rw-r--r--sass.html.markdown10
-rw-r--r--scala.html.markdown18
-rw-r--r--sk-sk/LearnGit-sk.txt208
-rw-r--r--sk-sk/elixir.html.markdown470
-rw-r--r--tcl.html.markdown35
-rw-r--r--tests/encoding.rb32
-rw-r--r--tests/yaml.rb21
-rw-r--r--typescript.html.markdown6
-rw-r--r--uk-ua/javascript-ua.html.markdown2
-rw-r--r--uk-ua/json-ua.html.markdown24
-rw-r--r--uk-ua/ruby-ua.html.markdown625
-rw-r--r--vim.html.markdown1
-rw-r--r--visualbasic.html.markdown8
-rw-r--r--yaml.html.markdown4
-rw-r--r--zh-cn/latex-cn.html.markdown277
-rw-r--r--zh-cn/less-cn.html.markdown387
-rw-r--r--zh-cn/ruby-cn.html.markdown2
-rw-r--r--zh-cn/vim-cn.html.markdown4
97 files changed, 9767 insertions, 811 deletions
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 00000000..183b7cdb
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,65 @@
+asciidoc*.html.markdown linguist-language=AsciiDoc
+angularjs*.html.markdown linguist-language=JavaScript
+bash*.html.markdown linguist-language=bash
+bf.html.markdown linguist-language=Brainfuck
+bf-*.html.markdown linguist-language=Brainfuck
+c-*.html.markdown linguist-language=C
+c.html.markdown linguist-language=C
+c++*.html.markdown linguist-language=C++
+chapel*.html.markdown linguist-language=Chapel
+clojure*.html.markdown linguist-language=Clojure
+cmake*.html.markdown linguist-language=CMake
+coffeescript*.html.markdown linguist-language=CoffeeScript
+coldfusion*.html.markdown linguist-language=ColdFusion
+common-lisp*.html.markdown linguist-language=lisp
+compojure*.html.markdown linguist-language=Clojure
+csharp*.html.markdown linguist-language=C#
+css*.html.markdown linguist-language=CSS
+d.html.markdown linguist-language=D
+d-*.html.markdown linguist-language=D
+dart*.html.markdown linguist-language=Dart
+edn*.html.markdown linguist-language=edn
+elisp*.html.markdown linguist-language=elisp
+elixir*.html.markdown linguist-language=Elixir
+elm*.html.markdown linguist-language=Elm
+erlang*.html.markdown linguist-language=Erlang
+factor*.html.markdown linguist-language=Factor
+forth*.html.markdown linguist-language=Forth
+fortran*.html.markdown linguist-language=FORTRAN
+fsharp*.html.markdown linguist-language=fsharp
+go.html.markdown linguist-language=Go
+go-*.html.markdown linguist-language=Go
+groovy*.html.markdown linguist-language=Groovy
+hack*.html.markdown linguist-language=Hack
+haml*.html.markdown linguist-language=Haml
+haskell*.html.markdown linguist-language=Haskell
+haxe*.html.markdown linguist-language=Haxe
+html*.html.markdown linguist-language=HTML
+hy.html.markdown linguist-language=Hy
+hy-*.html.markdown linguist-language=Hy
+inform7*.html.markdown linguist-language=inform7
+java.html.markdown linguist-language=Java
+java-*.html.markdown linguist-language=Java
+javascript*.html.markdown linguist-language=JavaScript
+jquery*.html.markdown linguist-language=JavaScript
+json*.html.markdown linguist-language=JSON
+julia*.html.markdown linguist-language=Julia
+kotlin*.html.markdown linguist-language=Kotlin
+latex*.html.markdown linguist-language=latex
+less*.html.markdown linguist-language=less
+livescript*.html.markdown linguist-language=LiveScript
+logtalk*.html.markdown linguist-language=Logtalk
+lua*.html.markdown linguist-language=Lua
+make*.html.markdown linguist-language=Makefile
+markdown*.html.markdown linguist-language=Markdown
+matlab*.html.markdown linguist-language=Matlab
+nim*.html.markdown linguist-language=Nimrod
+nix*.html.markdown linguist-language=Nix
+objective-c*.html.markdown linguist-language=Objective-C
+ocaml*.html.markdown linguist-language=OCaml
+paren*.html.markdown linguist-language=lisp
+pcre*.html.markdown linguist-language=Perl
+perl.html.markdown linguist-language=Perl
+perl-*.html.markdown linguist-language=Perl
+perl6*.html.markdown linguist-language=Perl6
+ruby*.html.markdown linguist-language=Ruby
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 00000000..ab89cb23
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,3 @@
+language: ruby
+rvm:
+ - 2.2
diff --git a/CHICKEN.html.markdown b/CHICKEN.html.markdown
index c6a3a914..080527a9 100644
--- a/CHICKEN.html.markdown
+++ b/CHICKEN.html.markdown
@@ -479,7 +479,7 @@ sqr ;; => #<procedure (sqr x)>
;; Functors
;; Functors are high level modules that can be parameterized by other modules
-;; Following functor requires another module named 'M' that provides a funtion called 'multiply'
+;; Following functor requires another module named 'M' that provides a function called 'multiply'
;; The functor itself exports a generic function 'square'
(functor (squaring-functor (M (multiply))) (square)
(import scheme M)
diff --git a/CONTRIBUTING.markdown b/CONTRIBUTING.markdown
index 9ee33ebc..5fa1d03d 100644
--- a/CONTRIBUTING.markdown
+++ b/CONTRIBUTING.markdown
@@ -33,6 +33,9 @@ review them more effectively and/or individually.
your file is UTF-8 encoded.
+ Try to leave out the byte-order-mark at the start of the file. (`:set nobomb`
in Vim)
+ + You can check if the file contains a BOM on Linux/Unix systems by running
+ `file language.html.markdown` You will see this if it uses a BOM:
+ `UTF-8 Unicode (with BOM) text`.
### Header configuration
diff --git a/Gemfile b/Gemfile
new file mode 100644
index 00000000..c30a6497
--- /dev/null
+++ b/Gemfile
@@ -0,0 +1,5 @@
+source 'http://rubygems.org'
+group :test do
+ gem 'rake'
+ gem 'charlock_holmes'
+end
diff --git a/ISSUE_TEMPLATE.md b/ISSUE_TEMPLATE.md
new file mode 100644
index 00000000..022dedab
--- /dev/null
+++ b/ISSUE_TEMPLATE.md
@@ -0,0 +1,6 @@
+Make sure the issue title is prepended with '[language/lang-code]' if the language is
+already on the site.
+If it's a request for a new language, use: '[Request] [language/lang-code]'
+
+Issues are always welcome. If you are able and willing, we welcome any pull requests
+as this is a community powered project.
diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md
index 3f55e3fb..6f1f000d 100644
--- a/PULL_REQUEST_TEMPLATE.md
+++ b/PULL_REQUEST_TEMPLATE.md
@@ -1,4 +1,5 @@
-- [ ] PR touches only one file (or a set of logically related files with similar changes made)
+- [ ] Pull request title is prepended with `[language/lang-code]`
+- [ ] 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)
-- [ ] YAML Frontmatter formatted according to [CONTRIBUTING.md](https://github.com/adambard/learnxinyminutes-docs/blob/master/CONTRIBUTING.markdown)
- - [ ] Seriously, look at it now. Watch for quotes and double-check field names.
+- [ ] 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)
+ - [ ] Yes, I have double-checked quotes and field names!
diff --git a/README.markdown b/README.markdown
index a71e85bd..9a8a3752 100644
--- a/README.markdown
+++ b/README.markdown
@@ -1,5 +1,7 @@
# [Learn X in Y minutes][1]
+[![Build Status](https://travis-ci.org/adambard/learnxinyminutes-docs.svg?branch=master)](https://travis-ci.org/adambard/learnxinyminutes-docs)
+
Whirlwind tours of (several, hopefully many someday) popular and
ought-to-be-more-popular programming languages, presented as valid, commented
code and explained as they go.
diff --git a/Rakefile b/Rakefile
new file mode 100644
index 00000000..6a31bd72
--- /dev/null
+++ b/Rakefile
@@ -0,0 +1,23 @@
+task default: %w[encoding yaml return_code]
+$failure = 0
+task :encoding do
+ begin
+ ruby 'tests/encoding.rb'
+ rescue Exception => msg
+ puts msg
+ $failure += 1
+ end
+end
+task :yaml do
+ begin
+ ruby 'tests/yaml.rb'
+ rescue Exception => msg
+ puts msg
+ $failure += 1
+ end
+end
+task :return_code do
+ if $failure != 0
+ raise "Failed #{$failure} tests!!"
+ end
+end
diff --git a/angularjs.html.markdown b/angularjs.html.markdown
new file mode 100644
index 00000000..89afa291
--- /dev/null
+++ b/angularjs.html.markdown
@@ -0,0 +1,713 @@
+---
+category: tool
+tool: AngularJS
+contributors:
+ - ["Walter Cordero", "http://waltercordero.com"]
+filename: learnangular.html
+---
+
+## AngularJS Tutorial.
+
+AngularJS version 1.0 was released in 2012.
+Miško Hevery, a Google employee, started to work with AngularJS in 2009.
+The idea turned out very well, and the project is now officially supported by Google.
+
+AngularJS is a JavaScript framework. It can be added to an HTML page with a "script" tag.
+AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.
+
+##What You Should Already Know
+
+Before you study AngularJS, you should have a basic understanding of:
+
+- HTML
+- CSS
+- JavaScript
+
+```html
+// AngularJS is a JavaScript framework. It is a library written in JavaScript.
+// AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:
+// <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
+
+///////////////////////////////////
+// AngularJS Extends HTML
+
+//AngularJS extends HTML with ng-directives.
+//The ng-app directive defines an AngularJS application.
+//The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
+//The ng-bind directive binds application data to the HTML view.
+<!DOCTYPE html>
+<html>
+ <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
+ <body>
+ <div ng-app="">
+ <p>Name: <input type="text" ng-model="name"></p>
+ <p ng-bind="name"></p>
+ </div>
+ </body>
+</html>
+
+/*
+ * Example explained:
+ * AngularJS starts automatically when the web page has loaded.
+ * The ng-app directive tells AngularJS that the <div> element is the "owner" of an AngularJS application.
+ * The ng-model directive binds the value of the input field to the application variable name.
+ * The ng-bind directive binds the innerHTML of the <p> element to the application variable name.
+*/
+<tag> Here are content to be intrepreted </tag>
+
+///////////////////////////////////
+// AngularJS Expressions
+
+// AngularJS expressions are written inside double braces: {{ expression }}.
+// AngularJS expressions binds data to HTML the same way as the ng-bind directive.
+// AngularJS will "output" data exactly where the expression is written.
+// AngularJS expressions are much like JavaScript expressions: They can contain literals, operators, and variables.
+// Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}
+<!DOCTYPE html>
+<html>
+ <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
+ <body>
+ <div ng-app="">
+ <p>My first expression: {{ 5 + 5 }}</p>
+ </div>
+ </body>
+</html>
+
+//If you remove the ng-app directive, HTML will display the expression as it is, without solving it:
+<!DOCTYPE html>
+<html>
+ <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
+ <body>
+ <div>
+ <p>My first expression: {{ 5 + 5 }}</p>
+ </div>
+ </body>
+</html>
+
+// AngularJS expressions bind AngularJS data to HTML the same way as the ng-bind directive.
+<!DOCTYPE html>
+<html>
+<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
+ <body>
+ <div ng-app="">
+ <p>Name: <input type="text" ng-model="name"></p>
+ <p>{{name}}</p>
+ </div>
+ </body>
+</html>
+
+// AngularJS numbers are like JavaScript numbers:
+<div ng-app="" ng-init="quantity=1;cost=5">
+ <p>Total in dollar: {{ quantity * cost }}</p>
+</div>
+
+//AngularJS strings are like JavaScript strings:
+<div ng-app="" ng-init="firstName='John';lastName='Doe'">
+ <p>The name is <span ng-bind="firstName + ' ' + lastName"></span></p>
+</div>
+
+//AngularJS objects are like JavaScript objects:
+<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
+ <p>The name is {{ person.lastName }}</p>
+</div>
+
+//AngularJS arrays are like JavaScript arrays:
+<div ng-app="" ng-init="points=[1,15,19,2,40]">
+ <p>The third result is {{ points[2] }}</p>
+</div>
+
+// Like JavaScript expressions, AngularJS expressions can contain literals, operators, and variables.
+// Unlike JavaScript expressions, AngularJS expressions can be written inside HTML.
+// AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do.
+// AngularJS expressions support filters, while JavaScript expressions do not.
+
+///////////////////////////////////
+// AngularJS Directives
+
+
+//AngularJS directives are extended HTML attributes with the prefix ng-.
+//The ng-app directive initializes an AngularJS application.
+//The ng-init directive initializes application data.
+//The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
+<div ng-app="" ng-init="firstName='John'">
+ <p>Name: <input type="text" ng-model="firstName"></p>
+ <p>You wrote: {{ firstName }}</p>
+</div>
+
+//Using ng-init is not very common. You will learn how to initialize data in the chapter about controllers.
+
+//The ng-repeat directive repeats an HTML element:
+<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
+ <ul>
+ <li ng-repeat="x in names">
+ {{ x }}
+ </li>
+ </ul>
+</div>
+
+//The ng-repeat directive used on an array of objects:
+<div ng-app="" ng-init="names=[
+{name:'Jani',country:'Norway'},
+{name:'Hege',country:'Sweden'},
+{name:'Kai',country:'Denmark'}]">
+ <ul>
+ <li ng-repeat="x in names">
+ {{ x.name + ', ' + x.country }}
+ </li>
+ </ul>
+</div>
+
+// AngularJS is perfect for database CRUD (Create Read Update Delete) applications.
+// Just imagine if these objects were records from a database.
+
+// The ng-app directive defines the root element of an AngularJS application.
+// The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is loaded.
+// Later you will learn how ng-app can have a value (like ng-app="myModule"), to connect code modules.
+
+// The ng-init directive defines initial values for an AngularJS application.
+// Normally, you will not use ng-init. You will use a controller or module instead.
+// You will learn more about controllers and modules later.
+
+//The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
+//The ng-model directive can also:
+//Provide type validation for application data (number, email, required).
+//Provide status for application data (invalid, dirty, touched, error).
+//Provide CSS classes for HTML elements.
+//Bind HTML elements to HTML forms.
+
+//The ng-repeat directive clones HTML elements once for each item in a collection (in an array).
+
+///////////////////////////////////
+// AngularJS Controllers
+
+// AngularJS controllers control the data of AngularJS applications.
+// AngularJS controllers are regular JavaScript Objects.
+
+// AngularJS applications are controlled by controllers.
+// The ng-controller directive defines the application controller.
+// A controller is a JavaScript Object, created by a standard JavaScript object constructor.
+
+<div ng-app="myApp" ng-controller="myCtrl">
+
+First Name: <input type="text" ng-model="firstName"><br>
+Last Name: <input type="text" ng-model="lastName"><br>
+<br>
+Full Name: {{firstName + " " + lastName}}
+
+</div>
+
+<script>
+var app = angular.module('myApp', []);
+app.controller('myCtrl', function($scope) {
+ $scope.firstName = "John";
+ $scope.lastName = "Doe";
+});
+</script>
+
+//Application explained:
+
+//The AngularJS application is defined by ng-app="myApp". The application runs inside the <div>.
+//The ng-controller="myCtrl" attribute is an AngularJS directive. It defines a controller.
+//The myCtrl function is a JavaScript function.
+//AngularJS will invoke the controller with a $scope object.
+//In AngularJS, $scope is the application object (the owner of application variables and functions).
+//The controller creates two properties (variables) in the scope (firstName and lastName).
+//The ng-model directives bind the input fields to the controller properties (firstName and lastName).
+
+//The example above demonstrated a controller object with two properties: lastName and firstName.
+//A controller can also have methods (variables as functions):
+<div ng-app="myApp" ng-controller="personCtrl">
+
+First Name: <input type="text" ng-model="firstName"><br>
+Last Name: <input type="text" ng-model="lastName"><br>
+<br>
+Full Name: {{fullName()}}
+
+</div>
+
+<script>
+var app = angular.module('myApp', []);
+app.controller('personCtrl', function($scope) {
+ $scope.firstName = "John";
+ $scope.lastName = "Doe";
+ $scope.fullName = function() {
+ return $scope.firstName + " " + $scope.lastName;
+ }
+});
+</script>
+
+//In larger applications, it is common to store controllers in external files.
+//Just copy the code between the <script> </script> tags into an external file named personController.js:
+
+<div ng-app="myApp" ng-controller="personCtrl">
+
+First Name: <input type="text" ng-model="firstName"><br>
+Last Name: <input type="text" ng-model="lastName"><br>
+<br>
+Full Name: {{firstName + " " + lastName}}
+
+</div>
+
+<script src="personController.js"></script>
+
+// For the next example we will create a new controller file:
+angular.module('myApp', []).controller('namesCtrl', function($scope) {
+ $scope.names = [
+ {name:'Jani',country:'Norway'},
+ {name:'Hege',country:'Sweden'},
+ {name:'Kai',country:'Denmark'}
+ ];
+});
+
+//Save the file as namesController.js:
+//And then use the controller file in an application:
+
+<div ng-app="myApp" ng-controller="namesCtrl">
+
+<ul>
+ <li ng-repeat="x in names">
+ {{ x.name + ', ' + x.country }}
+ </li>
+</ul>
+
+</div>
+
+<script src="namesController.js"></script>
+
+///////////////////////////////////
+// AngularJS Filers
+
+// Filters can be added to expressions and directives using a pipe character.
+// AngularJS filters can be used to transform data:
+
+- **currency**: Format a number to a currency format.
+- **filter**: Select a subset of items from an array.
+- **lowercase**: Format a string to lower case.
+- **orderBy**: Orders an array by an expression.
+- **uppercase**: Format a string to upper case.
+
+//A filter can be added to an expression with a pipe character (|) and a filter.
+//(For the next two examples we will use the person controller from the previous chapter)
+//The uppercase filter format strings to upper case:
+<div ng-app="myApp" ng-controller="personCtrl">
+
+<p>The name is {{ lastName | uppercase }}</p>
+
+</div>
+
+//The lowercase filter format strings to lower case:
+<div ng-app="myApp" ng-controller="personCtrl">
+
+<p>The name is {{ lastName | lowercase }}</p>
+
+</div>
+
+//The currency filter formats a number as currency:
+<div ng-app="myApp" ng-controller="costCtrl">
+
+<input type="number" ng-model="quantity">
+<input type="number" ng-model="price">
+
+<p>Total = {{ (quantity * price) | currency }}</p>
+
+</div>
+
+//A filter can be added to a directive with a pipe character (|) and a filter.
+//The orderBy filter orders an array by an expression:
+<div ng-app="myApp" ng-controller="namesCtrl">
+
+<ul>
+ <li ng-repeat="x in names | orderBy:'country'">
+ {{ x.name + ', ' + x.country }}
+ </li>
+</ul>
+
+<div>
+
+//An input filter can be added to a directive with a pipe character (|)
+//and filter followed by a colon and a model name.
+//The filter filter selects a subset of an array:
+
+<div ng-app="myApp" ng-controller="namesCtrl">
+
+<p><input type="text" ng-model="test"></p>
+
+<ul>
+ <li ng-repeat="x in names | filter:test | orderBy:'country'">
+ {{ (x.name | uppercase) + ', ' + x.country }}
+ </li>
+</ul>
+
+</div>
+
+///////////////////////////////////
+// AngularJS AJAX - $http
+
+//$http is an AngularJS service for reading data from remote servers.
+
+// The following data can be provided by a web server:
+// http://www.w3schools.com/angular/customers.php
+// **Check the URL to see the data format**
+
+// AngularJS $http is a core service for reading data from web servers.
+// $http.get(url) is the function to use for reading server data.
+<div ng-app="myApp" ng-controller="customersCtrl">
+
+<ul>
+ <li ng-repeat="x in names">
+ {{ x.Name + ', ' + x.Country }}
+ </li>
+</ul>
+
+</div>
+
+<script>
+var app = angular.module('myApp', []);
+app.controller('customersCtrl', function($scope, $http) {
+ $http.get("http://www.w3schools.com/angular/customers.php")
+ .success(function(response) {$scope.names = response.records;});
+});
+</script>
+
+Application explained:
+
+// The AngularJS application is defined by ng-app. The application runs inside a <div>.
+// The ng-controller directive names the controller object.
+// The customersCtrl function is a standard JavaScript object constructor.
+// AngularJS will invoke customersCtrl with a $scope and $http object.
+// $scope is the application object (the owner of application variables and functions).
+// $http is an XMLHttpRequest object for requesting external data.
+// $http.get() reads JSON data from http://www.w3schools.com/angular/customers.php.
+// If success, the controller creates a property (names) in the scope, with JSON data from the server.
+
+
+// Requests for data from a different server (than the requesting page), are called cross-site HTTP requests.
+// Cross-site requests are common on the web. Many pages load CSS, images, and scripts from different servers.
+// In modern browsers, cross-site HTTP requests from scripts are restricted to same site for security reasons.
+// The following line, in our PHP examples, has been added to allow cross-site access.
+header("Access-Control-Allow-Origin: *");
+
+
+///////////////////////////////////
+// AngularJS Tables
+
+// Displaying tables with angular is very simple:
+<div ng-app="myApp" ng-controller="customersCtrl">
+
+<table>
+ <tr ng-repeat="x in names">
+ <td>{{ x.Name }}</td>
+ <td>{{ x.Country }}</td>
+ </tr>
+</table>
+
+</div>
+
+<script>
+var app = angular.module('myApp', []);
+app.controller('customersCtrl', function($scope, $http) {
+ $http.get("http://www.w3schools.com/angular/customers.php")
+ .success(function (response) {$scope.names = response.records;});
+});
+</script>
+
+// To sort the table, add an orderBy filter:
+<table>
+ <tr ng-repeat="x in names | orderBy : 'Country'">
+ <td>{{ x.Name }}</td>
+ <td>{{ x.Country }}</td>
+ </tr>
+</table>
+
+// To display the table index, add a <td> with $index:
+<table>
+ <tr ng-repeat="x in names">
+ <td>{{ $index + 1 }}</td>
+ <td>{{ x.Name }}</td>
+ <td>{{ x.Country }}</td>
+ </tr>
+</table>
+
+// Using $even and $odd
+<table>
+ <tr ng-repeat="x in names">
+ <td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Name }}</td>
+ <td ng-if="$even">{{ x.Name }}</td>
+ <td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Country }}</td>
+ <td ng-if="$even">{{ x.Country }}</td>
+ </tr>
+</table>
+
+///////////////////////////////////
+// AngularJS HTML DOM
+
+//AngularJS has directives for binding application data to the attributes of HTML DOM elements.
+
+// The ng-disabled directive binds AngularJS application data to the disabled attribute of HTML elements.
+
+<div ng-app="" ng-init="mySwitch=true">
+
+<p>
+<button ng-disabled="mySwitch">Click Me!</button>
+</p>
+
+<p>
+<input type="checkbox" ng-model="mySwitch">Button
+</p>
+
+</div>
+
+//Application explained:
+
+// The ng-disabled directive binds the application data mySwitch to the HTML button's disabled attribute.
+// The ng-model directive binds the value of the HTML checkbox element to the value of mySwitch.
+// If the value of mySwitch evaluates to true, the button will be disabled:
+<p>
+<button disabled>Click Me!</button>
+</p>
+
+// If the value of mySwitch evaluates to false, the button will not be disabled:
+<p>
+ <button>Click Me!</button>
+</p>
+
+// The ng-show directive shows or hides an HTML element.
+
+<div ng-app="">
+
+<p ng-show="true">I am visible.</p>
+
+<p ng-show="false">I am not visible.</p>
+
+</div>
+
+// The ng-show directive shows (or hides) an HTML element based on the value of ng-show.
+// You can use any expression that evaluates to true or false:
+<div ng-app="">
+<p ng-show="hour > 12">I am visible.</p>
+</div>
+
+///////////////////////////////////
+// AngularJS Events
+
+// AngularJS has its own HTML events directives.
+
+// The ng-click directive defines an AngularJS click event.
+<div ng-app="myApp" ng-controller="myCtrl">
+
+<button ng-click="count = count + 1">Click me!</button>
+
+<p>{{ count }}</p>
+
+</div>
+<script>
+var app = angular.module('myApp', []);
+app.controller('myCtrl', function($scope) {
+ $scope.count = 0;
+});
+</script>
+
+// The ng-hide directive can be used to set the visibility of a part of an application.
+// The value ng-hide="true" makes an HTML element invisible.
+// The value ng-hide="false" makes the element visible.
+<div ng-app="myApp" ng-controller="personCtrl">
+
+<button ng-click="toggle()">Toggle</button>
+
+<p ng-hide="myVar">
+First Name: <input type="text" ng-model="firstName"><br>
+Last Name: <input type="text" ng-model="lastName"><br>
+<br>
+Full Name: {{firstName + " " + lastName}}
+</p>
+
+</div>
+
+<script>
+var app = angular.module('myApp', []);
+app.controller('personCtrl', function($scope) {
+ $scope.firstName = "John",
+ $scope.lastName = "Doe"
+ $scope.myVar = false;
+ $scope.toggle = function() {
+ $scope.myVar = !$scope.myVar;
+ };
+});
+</script>
+
+//Application explained:
+
+// The first part of the personController is the same as in the chapter about controllers.
+// The application has a default property (a variable): $scope.myVar = false;
+// The ng-hide directive sets the visibility, of a <p> element with two input fields,
+// according to the value (true or false) of myVar.
+// The function toggle() toggles myVar between true and false.
+// The value ng-hide="true" makes the element invisible.
+
+
+// The ng-show directive can also be used to set the visibility of a part of an application.
+// The value ng-show="false" makes an HTML element invisible.
+// The value ng-show="true" makes the element visible.
+// Here is the same example as above, using ng-show instead of ng-hide:
+<div ng-app="myApp" ng-controller="personCtrl">
+
+<button ng-click="toggle()">Toggle</button>
+
+<p ng-show="myVar">
+First Name: <input type="text" ng-model="firstName"><br>
+Last Name: <input type="text" ng-model="lastName"><br>
+<br>
+Full Name: {{firstName + " " + lastName}}
+</p>
+
+</div>
+
+<script>
+var app = angular.module('myApp', []);
+app.controller('personCtrl', function($scope) {
+ $scope.firstName = "John",
+ $scope.lastName = "Doe"
+ $scope.myVar = true;
+ $scope.toggle = function() {
+ $scope.myVar = !$scope.myVar;
+ }
+});
+</script>
+
+///////////////////////////////////
+// AngularJS Modules
+
+// An AngularJS module defines an application.
+// The module is a container for the different parts of an application.
+// The module is a container for the application controllers.
+// Controllers always belong to a module.
+
+// This application ("myApp") has one controller ("myCtrl"):
+
+<!DOCTYPE html>
+<html>
+<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
+<body>
+
+<div ng-app="myApp" ng-controller="myCtrl">
+{{ firstName + " " + lastName }}
+</div>
+
+<script>
+var app = angular.module("myApp", []);
+app.controller("myCtrl", function($scope) {
+ $scope.firstName = "John";
+ $scope.lastName = "Doe";
+});
+</script>
+
+</body>
+</html>
+
+// It is common in AngularJS applications to put the module and the controllers in JavaScript files.
+// In this example, "myApp.js" contains an application module definition, while "myCtrl.js" contains the controller:
+
+<!DOCTYPE html>
+<html>
+<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
+<body>
+
+<div ng-app="myApp" ng-controller="myCtrl">
+{{ firstName + " " + lastName }}
+</div>
+
+<script src="myApp.js"></script>
+<script src="myCtrl.js"></script>
+
+</body>
+</html>
+
+//myApp.js
+var app = angular.module("myApp", []);
+
+// The [] parameter in the module definition can be used to define dependent modules.
+
+// myCtrl.js
+app.controller("myCtrl", function($scope) {
+ $scope.firstName = "John";
+ $scope.lastName= "Doe";
+});
+
+// Global functions should be avoided in JavaScript. They can easily be overwritten
+// or destroyed by other scripts.
+
+// AngularJS modules reduces this problem, by keeping all functions local to the module.
+
+// While it is common in HTML applications to place scripts at the end of the
+// <body> element, it is recommended that you load the AngularJS library either
+// in the <head> or at the start of the <body>.
+
+// This is because calls to angular.module can only be compiled after the library has been loaded.
+
+<!DOCTYPE html>
+<html>
+<body>
+<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
+
+<div ng-app="myApp" ng-controller="myCtrl">
+{{ firstName + " " + lastName }}
+</div>
+
+<script>
+var app = angular.module("myApp", []);
+app.controller("myCtrl", function($scope) {
+ $scope.firstName = "John";
+ $scope.lastName = "Doe";
+});
+</script>
+
+</body>
+</html>
+
+
+///////////////////////////////////
+// AngularJS Applications
+
+// AngularJS modules define AngularJS applications.
+// AngularJS controllers control AngularJS applications.
+// The ng-app directive defines the application, the ng-controller directive defines the controller.
+<div ng-app="myApp" ng-controller="myCtrl">
+ First Name: <input type="text" ng-model="firstName"><br>
+ Last Name: <input type="text" ng-model="lastName"><br>
+ <br>
+ Full Name: {{firstName + " " + lastName}}
+</div>
+<script>
+ var app = angular.module('myApp', []);
+ app.controller('myCtrl', function($scope) {
+ $scope.firstName= "John";
+ $scope.lastName= "Doe";
+ });
+</script>
+
+// AngularJS modules define applications:
+var app = angular.module('myApp', []);
+
+// AngularJS controllers control applications:
+app.controller('myCtrl', function($scope) {
+ $scope.firstName= "John";
+ $scope.lastName= "Doe";
+});
+```
+
+## Source & References
+
+**Examples**
+
+- http://www.w3schools.com/angular/angular_examples.asp
+
+**References**
+
+- http://www.w3schools.com/angular/angular_ref_directives.asp
+- http://www.w3schools.com/angular/default.asp
+- https://teamtreehouse.com/library/angular-basics/
+
+Feedback is welcome! You can find me in:
+[@WalterC_87](https://twitter.com/WalterC_87), or
+[me@waltercordero.com](mailto:me@waltercordero.com).
+
diff --git a/binary-search.html.markdown b/binary-search.html.markdown
deleted file mode 100644
index ce436b44..00000000
--- a/binary-search.html.markdown
+++ /dev/null
@@ -1,63 +0,0 @@
----
-category: Algorithms & Data Structures
-name: Binary Search
-contributors:
- - ["Abhishek Jaisingh", "http://github.com/abhishekjiitr"]
----
-
-# Binary Search
-
-## Why Binary Search?
-
-Searching is one of the prime problems in the domain of Computer Science. Today there are more than 1 trillion searches per year, and we need algorithms that can do that very fastly. Binary search is one of the fundamental algorithms in computer science. In order to explore it, we’ll first build up a theoretical backbone, then use that to implement the algorithm properly.
-
-## Introduction
-
-A simple approach to implement search is to do a linear search, but this approach takes a lot of time and this time grows linearly with the amount or number of data points. i.e., start from the leftmost element of arr[] and one by one compare x with each element of arr[], if x matches with an element, return the index. If x doesn’t match with any of elements, return -1.
-
-```
-Linear Search: O (n) Linear Time
-
-Binary Search: O ( log(n) ) Logarithmic Time
-
-```
-```
-def search(arr, x):
-
- for i in range(len(arr)):
-
- if arr[i] == x:
- return i
-
- return -1
-
-```
-## Binary Search Algorithm
-
-The basic requirement for binary search to work is that the data to search should be sorted (in any order).
-### Algo
-
-```
-The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Logn). We basically ignore half of the elements just after one comparison.
-1) Compare x with the middle element.
-2) If x matches with middle element, we return the mid index.
-3) Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half.
-4) Else (x is smaller) recur for the left half.
-Following is Recursive implementation of Binary Search.
-
-```
-
-### Ending Notes
-
-There is another form of binary search that is very useful.
-
-## Books
-
-* [CLRS](https://mitpress.mit.edu/books/introduction-algorithms)
-* [Algorithms](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X)
-* [Algorithm Design](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651)
-
-## Online Resources
-
-* [GeeksforGeeks](http://www.geeksforgeeks.org/the-ubiquitous-binary-search-set-1/)
-* [Topcoder Tutorial](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/)
diff --git a/c++.html.markdown b/c++.html.markdown
index 5dc1af59..24d38df7 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -981,7 +981,7 @@ 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)
+// 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
@@ -1011,7 +1011,7 @@ for(int i=0; i<Vector_name.size(); i++)
// It will iterate through the vector from index '0' till last index
// Iterator
-vector<Data_Type>::iterator it; // initialize the iteartor for vector
+vector<Data_Type>::iterator it; // initialize the iterator for vector
for(it=vector_name.begin(); it!=vector_name.end();++it)
// For accessing the element of the vector
@@ -1057,7 +1057,7 @@ cout << ST.size(); // will print the size of set ST
// and a mapped value, following a specific order.
#include<map>
-map<char, int> mymap; // Will initalize the map with key as char and value as int
+map<char, int> mymap; // Will initialize the map with key as char and value as int
mymap.insert(pair<char,int>('A',1));
// Will insert value 1 for key A
@@ -1072,7 +1072,7 @@ for (it=mymap.begin(); it!=mymap.end(); ++it)
// A->1
// Z->26
-// To find the value correponsing to a key
+// To find the value corresponding to a key
it = mymap.find('Z');
cout << it->second;
diff --git a/c.html.markdown b/c.html.markdown
index ae87ca08..57ce72d2 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -202,7 +202,7 @@ int main (int argc, char** argv)
11 % 3; // => 2
// Comparison operators are probably familiar, but
- // there is no Boolean type in c. We use ints instead.
+ // there is no Boolean type in C. We use ints instead.
// (Or _Bool or bool in C99.)
// 0 is false, anything else is true. (The comparison
// operators always yield 0 or 1.)
@@ -715,14 +715,14 @@ typedef void (*my_fnp_type)(char *);
/******************************* Header Files **********************************
-Header files are an important part of c as they allow for the connection of c
+Header files are an important part of C as they allow for the connection of C
source files and can simplify code and definitions by separating them into
separate files.
-Header files are syntactically similar to c source files but reside in ".h"
-files. They can be included in your c source file by using the precompiler
+Header files are syntactically similar to C source files but reside in ".h"
+files. They can be included in your C source file by using the precompiler
command #include "example.h", given that example.h exists in the same directory
-as the c file.
+as the C file.
*/
/* A safe guard to prevent the header from being defined too many times. This */
@@ -753,12 +753,12 @@ enum traffic_light_state {GREEN, YELLOW, RED};
/* Function prototypes can also be defined here for use in multiple files, */
/* but it is bad practice to define the function in the header. Definitions */
-/* should instead be put in a c file. */
+/* should instead be put in a C file. */
Node createLinkedList(int *vals, int len);
-/* Beyond the above elements, other definitions should be left to a c source */
+/* Beyond the above elements, other definitions should be left to a C source */
/* file. Excessive includes or definitions should, also not be contained in */
-/* a header file but instead put into separate headers or a c file. */
+/* a header file but instead put into separate headers or a C file. */
#endif /* End of the if precompiler directive. */
diff --git a/clojure.html.markdown b/clojure.html.markdown
index bf9258f7..bfe8d79e 100644
--- a/clojure.html.markdown
+++ b/clojure.html.markdown
@@ -297,7 +297,7 @@ 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 4) ;=> and at the second position, in the same expression
+ (nth input 2) ;=> and at the second position, in the same expression
(conj [4 5 6] input [8 9 10])) ;=> or in the middle !
diff --git a/cs-cz/javascript.html.markdown b/cs-cz/javascript.html.markdown
index e781db3e..cbf7687e 100644
--- a/cs-cz/javascript.html.markdown
+++ b/cs-cz/javascript.html.markdown
@@ -1,4 +1,4 @@
----
+---
language: javascript
contributors:
- ["Adam Brenecki", "http://adam.brenecki.id.au"]
diff --git a/csharp.html.markdown b/csharp.html.markdown
index 2cacfc00..442700a6 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -671,6 +671,10 @@ on a new line! ""Wow!"", the masses cried";
int _speed; // Everything is private by default: Only accessible from within this class.
// can also use keyword private
public string Name { get; set; }
+
+ // Properties also have a special syntax for when you want a readonly property
+ // that simply returns the result of an expression
+ public string LongName => Name + " " + _speed + " speed";
// Enum is a value type that consists of a set of named constants
// It is really just mapping a name to a value (an int, unless specified otherwise).
diff --git a/css.html.markdown b/css.html.markdown
index 1c569d04..3b378d44 100644
--- a/css.html.markdown
+++ b/css.html.markdown
@@ -169,9 +169,9 @@ selector {
color: transparent; /* equivalent to setting the alpha to 0 */
color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */
color: hsla(0, 100%, 50%, 0.3); /* as hsl percentages with alpha */
-
+
/* Borders */
- border-width:5px;
+ border-width:5px;
border-style:solid;
border-color:red; /* similar to how background-color is set */
border: 5px solid red; /* this is a short hand approach for the same */
@@ -261,7 +261,7 @@ recommended that you avoid its usage.
## Media Queries
-CSS Media Queries are a feature in CSS 3 which allows you to specify when certain CSS rules should be applied, such as when printed, or when on a screen with certain dimensions or pixel density. They do not add to the selector's specifity.
+CSS Media Queries are a feature in CSS 3 which allows you to specify when certain CSS rules should be applied, such as when printed, or when on a screen with certain dimensions or pixel density. They do not add to the selector's specificity.
```css
/* A rule that will be used on all devices */
diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown
index dca88f01..817cb4ae 100644
--- a/de-de/go-de.html.markdown
+++ b/de-de/go-de.html.markdown
@@ -10,8 +10,8 @@ lang: de-de
---
Die Sprache Go (auch golang) wurde von Google entwickelt und wird seit 2007
benutzt. Go ähnelt in der Syntax der Sprache C, bietet darüber hinaus aber viele
-Vorteile. Einerseits verzichtet Gp auf Speicherarithmetik und
-benutzt einen Garbabe Collector. Andererseits enthält Go native Sprachelemente
+Vorteile. Einerseits verzichtet Go auf Speicherarithmetik und
+benutzt einen Garbage Collector. Andererseits enthält Go native Sprachelemente
für die Unterstützung von Nebenläufigkeit. Durch den Fokus auf einen schnellen
Kompilierprozess wird außerdem die Softwareentwicklung in Großprojekten
erleichtert.
diff --git a/de-de/html-de.html.markdown b/de-de/html-de.html.markdown
new file mode 100644
index 00000000..2ee18129
--- /dev/null
+++ b/de-de/html-de.html.markdown
@@ -0,0 +1,120 @@
+---
+language: html
+contributors:
+ - ["Christophe THOMAS", "https://github.com/WinChris"]
+translators:
+ - ["Dennis Keller", "https://github.com/denniskeller"]
+filename: learnhtml-de.html
+lang: de-de
+---
+
+HTML steht für HyperText Markup Language (Hypertext-Auszeichnungssprache).
+Sie ist eine Sprache, um Seiten für das World Wide Web zu schreiben..
+Es ist eine Auszeichnugssprache, die es uns ermöglicht Webseiten mithilfe des Codes zu schreiben, der kennzeichnet wie Text und Daten angezeigt werden sollen. Eigentlich sind HTML Dateien nur einfache Textdateien.
+Was sind das für Auszeichnungen? Es ist eine Methode, um die Daten der Website zu organisieren mithilfe von Start- und Endtags.
+Diese Auszeichnung dient dazu dem Text Bedeutung zu geben, welchen sie umschließt.
+Wie viele andere Computersprachen auch, besitzt HTML viele Versionen. Wir werden hier über HTML5 reden.
+
+**NOTE :** Du kannst die unterschiedlichen Tags und Elemente, während des Tutorials auf Seiten, wie [codepen](http://codepen.io/pen/) testen, um deren Effekte zu sehen und wie diese funktionieren. Auch kannst du dich damit besser mit der Sprache vertraut machen.
+Dieser Artikel ist bedacht darauf, nur HTML Syntax und nützliche Tipps zu geben.
+
+
+```html
+<!-- Kommentare werden wie in dieser Zeile geschrieben -->
+
+<!-- #################### Die Tags #################### -->
+
+<!-- Hier ist eine Beispiel HTML Datei, die wir analysieren werden -->
+
+<!doctype html>
+ <html>
+ <head>
+ <title>Meine Website</title>
+ </head>
+ <body>
+ <h1>Hallo Welt!</h1>
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Komm schau was das hier anzeigt</a>
+ <p>Das ist ein Paragraf.</p>
+ <p>Das ist ein weiterer Paragraf.</p>
+ <ul>
+ <li>Das ist eine Item mit einer nicht-nummerierten Liste (Aufzählungsliste)</li>
+ <li>Das ist ein weiteres Item</li>
+ <li>Und das ist das letzte Item in der Liste</li>
+ </ul>
+ </body>
+ </html>
+
+<!-- Jede HTML Datei startet damit dem Browser zu sagen, dass die Seite aus HTML besteht. -->
+<!doctype html>
+
+<!-- Danach startet sie mit einem Öffnungtag <html>. -->
+<html>
+
+<!-- Dieser wird am Ende der Datei mit</html> geschlossen. -->
+</html>
+
+<!-- Nichts sollte nach diesen finalen Tag erscheinen. -->
+
+<!-- Dazwischen (Zwischen dem Öffnungs- und Schließungstag <html></html>) finden wir: -->
+
+<!-- Ein Kopf wird definiert mit <head> (er muss mit </head> geschlossen werden). -->
+<!-- Der Header beinhaltet Beschreibungen und zusätzliche Informationen, welche nicht dargestellt werden. Das sind Metadaten. -->
+
+<head>
+ <title>Meine Seite</title><!-- Der <title> kennzeichnet dem Browser den Titel im Browserfenster und im Tabnamen anzuzeigen. -->
+</head>
+
+<!-- Nach dem <head> Bereich findet sich der <body> Tag -->
+<!-- Bis zu diesen Punkt wird nichts im Browerfenster angezeigt. -->
+<!-- Wir müssen den Body mit dem Inhalt füllen der angezeigt werden soll. -->
+
+<body>
+ <h1>Hallo, Welt!</h1> <!-- Der h1 Tag erstellt einen Titel. -->
+ <!-- Es gibt auch Untertitel für <h1> von den wichtigsten <h2> zu den Unwichtigsten (h6). -->
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Komm, schaue was das zeigt</a> <!-- Eine URL wird zum Hyperlink, wenn es das Attribut href="" -->
+ <p>Das ist ein Absatz.</p> <!-- Der Tag <p> lässt uns Text auf die HTML Seite hinzufügen. -->
+ <p>Das ist ein anderer Absatz.</p>
+ <ul> <!-- Der <ul> Tag erstellt eine Aufzählungsliste. -->
+ <!-- Für eine nummerierte Liste sollten wir stattdessen <ol> verwenden. Das erste Element bekommt 1., das zweite 2. usw. -->
+ <li>Das ist ein Element in einer nicht Aufzählungsliste</li>
+ <li>Das ist ein anderes Item</li>
+ <li>Und das ist das letzte Element in der List</li>
+ </ul>
+</body>
+
+<!-- Und das war es. Eine HTML Datei kann so simpel sein. -->
+
+<!-- Aber es ist möglich viele weitere zusätzliche HTML tags hinzuzufügen. -->
+
+<!-- Um ein Bild hinzuzufügen. -->
+<img src="http://i.imgur.com/XWG0O.gif"/> <!-- Die Quelle des Bildes wird gezeigt durch das Attribut src="" -->
+<!-- Die Quelle kann eine URL sein oder ein Pfad zu deinem Computer. -->
+
+<!-- Es ist ebenso möglich eine Tabelle zu erstellen. -->
+
+<table> <!-- Wir öffnen ein <table> Element. -->
+ <tr> <!-- <tr> erlaubt es uns Reihe zu erstellen. -->
+ <th>Erster Tabellenkopf</th> <!-- <th> erlaubt es uns der Tabelle einen Titel zu geben. -->
+ <th>Zweiter Tabllenkopf</th>
+ </tr>
+ <tr>
+ <td>Erste Zeile, erste Spalte</td> <!-- <td> erlaubt es eine Tabellenzelle zu erstellen. -->
+ <td>Erste Zeile, zweite Spalte</td>
+ </tr>
+ <tr>
+ <td>Zweite Zeile, erste Spalte</td>
+ <td>Zweite Zeile, zweite Spalte</td>
+ </tr>
+</table>
+
+```
+
+## Verwendung
+
+HTML Dateien enden mit `.html`.
+
+## Um mehr zu lernen
+
+* [wikipedia (EN)](https://en.wikipedia.org/wiki/HTML)
+* [HTML tutorial (EN)](https://developer.mozilla.org/en-US/docs/Web/HTML)
+* [W3School (EN)](http://www.w3schools.com/html/html_intro.asp)
diff --git a/de-de/ruby-de.html.markdown b/de-de/ruby-de.html.markdown
index bdeaa30b..e14603cd 100644
--- a/de-de/ruby-de.html.markdown
+++ b/de-de/ruby-de.html.markdown
@@ -13,6 +13,7 @@ contributors:
- ["Rahil Momin", "https://github.com/iamrahil"]
translators:
- ["Christian Albrecht", "https://github.com/coastalchief"]
+ - ["Dennis Keller", "https://github.com/denniskeller"]
filename: ruby-de.rb
lang: de-de
---
@@ -143,7 +144,7 @@ x #=> 10
y #=> 10
```
## Benennung
-### Konvention ist snake_case
+### Konvention ist snake_case
```
snake_case = true
```
@@ -153,9 +154,9 @@ path_to_project_root = '/good/name/'
path = '/bad/name/'
```
# Symbols (sind auch Objekte)
-Symbols sind unveränderliche, wiederverwendbare Konstanten, welche intern
-als integer repräsentiert werden. Sie werden häufig anstelle von Strings
-verwendet, um sinnvoll Werte zu übermitteln.
+Symbols sind unveränderliche, wiederverwendbare Konstanten, welche intern
+als integer repräsentiert werden. Sie werden häufig anstelle von Strings
+verwendet, um sinnvoll Werte zu übermitteln.
Symbols werden mit dem Doppelpunkt gekennzeichnet.
```
@@ -195,7 +196,7 @@ array[12] #=> nil
array[-1] #=> 5
```
-## Arrays können mit Stard Index und Länge indiziert werden
+## Arrays können mit Start Index und Länge indiziert werden
```
array[2, 3] #=> [3, 4, 5]
```
@@ -216,11 +217,9 @@ array.push(6) #=> [1, 2, 3, 4, 5, 6]
array.include?(1) #=> true
```
-# Hashes
+# Hashes
Hashes sind das Hauptfeature um Key/Values zu speichern
-```
-
## Ein Hash anlegen
```
hash = { 'color' => 'green', 'number' => 5 }
@@ -231,8 +230,8 @@ hash.keys #=> ['color', 'number']
```
hash['color'] #=> 'green'
hash['number'] #=> 5
-hash['nothing here'] #=> nil
-// Asking a hash for a key that doesn't exist returns nil:
+hash['nothing here'] #=> nil
+// Fragen an einen Hash nach einem Schlüssel, der nicht existiert, ruft nil hervor:
```
## Symbols können auch keys sein
@@ -247,7 +246,7 @@ new_hash.has_key?(:defcon) #=> true
new_hash.has_value?(3) #=> true
```
-### Tip: Arrays und Hashes sind Enumerable
+### Tipp: Arrays und Hashes sind Enumerable
### Und haben gemeinsame, hilfreiche Methoden wie:
### each, map, count, and more
@@ -269,8 +268,8 @@ for counter in 1..5
end
```
## Stattdessen: "each" Methode und einen Bloch übergeben
-Ein Block ist ein Codeteil, den man einer Methode übergeben kann
-Ähnelt stark lambdas, anonymen Funktionen oder Closures in anderen
+Ein Block ist ein Codeteil, den man einer Methode übergeben kann
+Ähnelt stark lambdas, anonymen Funktionen oder Closures in anderen
Programmiersprachen.
```
@@ -339,7 +338,7 @@ end
=> "OK job"
```
-# exception handling:
+# Exception handling:
```
begin
# code here that might raise an exception
@@ -360,13 +359,13 @@ def double(x)
x * 2
end
```
-## Funktionen (und Blocks)
+## Funktionen (und Blocks)
## geben implizit den Wert des letzten Statements zurück
```
double(2) #=> 4
```
-### Klammern sind optional wenn das Ergebnis nicht mehdeutig ist
+### Klammern sind optional wenn das Ergebnis nicht mehrdeutig ist
```
double 3 #=> 6
double double 3 #=> 12
@@ -604,7 +603,7 @@ Something.new.qux # => 'qux'
## Weiterführende Hinweise
-//EN
+//EN
- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.
- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/)
diff --git a/dynamic-programming.html.markdown b/dynamic-programming.html.markdown
index 94be22e9..7df367e7 100644
--- a/dynamic-programming.html.markdown
+++ b/dynamic-programming.html.markdown
@@ -9,7 +9,7 @@ contributors:
## Introduction
-Dynamic Programming is a powerful technique used for solving a particular class of problems as we will see.The idea is very simple, If you have solved a problem with the given input, then save the result for future reference, so as to avoid solving the same problem again.
+Dynamic Programming is a powerful technique used for solving a particular class of problems as we will see. The idea is very simple, If you have solved a problem with the given input, then save the result for future reference, so as to avoid solving the same problem again.
Always remember!
"Those who can't remember the past are condemned to repeat it"
diff --git a/el-gr/css-gr.html.markdown b/el-gr/css-gr.html.markdown
index 9404679c..31b30479 100644
--- a/el-gr/css-gr.html.markdown
+++ b/el-gr/css-gr.html.markdown
@@ -6,23 +6,23 @@ filename: css-gr.html.markdown
lang: el-gr
---
-Η αρχική μορφή του Παγκόσμιου Ιστού αποτελούταν απο καθαρό κείμενο, χωρίς οπτικά αντικείμενα. Με το πέρας
+Η αρχική μορφή του Παγκόσμιου Ιστού αποτελείτο απο καθαρό κείμενο, χωρίς οπτικά αντικείμενα. Με το πέρας
του χρόνου και την εξέλιξη των Φυλλομετρητών, οι πλούσιες σελίδες, σε οπτικά και πολυμεσικά αντικείμενα,
-γίναν καθημερινότητα.
+έγιναν καθημερινότητα.
Η CSS μας βοηθάει να διαχωρήσουμε το περιεχόμενο της σελίδας μας (HTML) απο την οπτική της περιγραφή.
Με την CSS ορίζουμε οπτικές ιδιότητες (χρώμα, μέγεθος, κλπ) σε HTML αντικείμενα (H1, div, κλπ).
```css
-/* Σχόλια εμφανίζονται εντός καθέτου-αστερίσκου, όπως εδώ.
+/* Τα σχόλια εμφανίζονται εντός καθέτου-αστερίσκου, όπως εδώ.
Δεν υπάρχουν σχόλια μια γραμμής και πολλών. */
/* ####################
## ΚΑΝΟΝΕΣ
#################### */
-/* ένας κανόνας χρησιμοποιείτε για να στοχεύσουμε ένα αντικείμενο (selector). */
+/* ένας κανόνας χρησιμοποιείται για να στοχεύσουμε ένα αντικείμενο (selector). */
selector { property: value; /* περισσότερες ιδιότητες...*/ }
/*
diff --git a/el-gr/java-gr.html.markdown b/el-gr/java-gr.html.markdown
index 21c4023b..5dad4a60 100644
--- a/el-gr/java-gr.html.markdown
+++ b/el-gr/java-gr.html.markdown
@@ -127,8 +127,8 @@ public class LearnJava {
// Char - Ένας μόνο χαρακτήρας 16-bit Unicode
char fooChar = 'A';
- // Οι μεταβλητές final δεν μπορούν να ανατεθούν ξανά σε άλλο
- // αντικείμενο,
+ // Οι μεταβλητές final δεν μπορούν να πάρουν άλλη τιμή
+ // μετά την αρχικοποίηση τους,
final int HOURS_I_WORK_PER_WEEK = 9001;
// αλλά μπορούν να αρχικοποιηθούν αργότερα.
final double E;
@@ -149,7 +149,7 @@ public class LearnJava {
// BigDecimal - Immutable, αυθαίρετης-ακρίβειας, εμπρόσημος (signed)
- // δεκαδικός αριθμός
+ // δεκαδικός αριθμός
//
// Ένας BigDecimal παίρνει δύο μέρη: Μία αυθαίρετης ακρίβειας,
// ακέραια, unscaled τιμή και μία κλιμάκωση(scale) ως ένα 32-bit
diff --git a/es-es/edn-es.html.markdown b/es-es/edn-es.html.markdown
new file mode 100644
index 00000000..32bba37d
--- /dev/null
+++ b/es-es/edn-es.html.markdown
@@ -0,0 +1,111 @@
+---
+language: edn
+filename: learnedn-es.edn
+contributors:
+ - ["Jason Yeo", "https://github.com/jsyeo"]
+translators:
+ - ["Gino Amaury", "https://github.com/ginoamaury"]
+lang: es-es
+---
+
+La notación de datos extensible (Extensible Data Notation (EDN)) es un formato para serializar los datos.
+
+La notación se utiliza internamente por Clojure para representar programas. También es
+utilizado como un formato de transferencia de datos como JSON. A pesar de que se utiliza más comúnmente en
+Clojure, existen implementaciones de EDN para muchos otros lenguajes.
+
+El principal beneficio de EDN sobre JSON y YAML es que es extensible.
+Vamos a ver cómo se extiende más adelante.
+
+```clojure
+; Los comentarios comienzan con un punto y coma.
+; Cualquier cosa después del punto y coma es ignorado.
+
+;;;;;;;;;;;;;;;;;;;
+;;;Tipos Básicos;;;
+;;;;;;;;;;;;;;;;;;;
+
+nil ; También conocido en otros lenguajes como nulo (null).
+
+; Booleanos
+true
+false
+
+; Las cadenas se encierran entre comillas dobles
+"desayuno húngaro"
+"tortilla de queso del granjero"
+
+; Los caracteres están precedidos por barras invertidas
+\g \r \a \c \e
+
+; Las palabras claves comienzan con dos puntos.Se comportan como las enumeraciones. Más o menos
+; Como símbolos en Ruby
+:huevos
+:queso
+:aceitunas
+
+; Los símbolos se utilizan para representar los identificadores.Estos empiezan con #.
+; puedes tener espacios usando el símbolo /. cualquier cosa precedida / es
+; un espacio en el nombre.
+#cuchara
+#cocina/cuchara ; no es lo mismo que #spoon
+#cocina/tenedor
+#github/tenedor ; no se puede comer con este.
+
+; Números enteros y flotantes
+42
+3.14159
+
+; Las listas son secuencias de valores.
+(:bollo :empanada-de-res 9 "yum!")
+
+; Vectores permiten acceso aleatorio
+[:helado 1 2 -2]
+
+; Los mapas son estructuras de datos asociativos que se asocian con la clave de su valor.
+{:huevos 2
+ :jugo-de-limon 3.5
+ :mantequilla 1}
+
+; Usted no está restringido a usar palabras clave como claves.
+{[1 2 3 4] "decirle a la gente lo que llevaba",
+ [5 6 7 8] "Entre mas tu ves, mas lo odias"}
+
+; Puede usar comas para facilitar la lectura. Se tratan como espacios en blanco.
+
+; Los conjuntos son colecciones que contienen elementos únicos.
+#{:a :b 88 "huat"}
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;;Elementos de etiqueta ;;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+; EDN puede ser extendido por elementos de etiqueta con el símbolo #.
+
+#MyYelpClone/MenuItem {:nombre "huevos-Benedict" :clasificacion 10}
+
+; Permíteme explicar esto con un ejemplo en colujre. Supongamos que quiero
+; transformar ese pedazo de EDN en un registro del Menú.
+
+(defrecord MenuItem [nombre clasificacion])
+
+; Para transformar EDN en valores clojure, necesitaremos usar el constructor en EDN
+; lectura, edn/read-string
+
+(edn/read-string "{:huevos 2 :mantequilla 1 :harina 5}")
+; -> {:huevos 2 :mantequilla 1 :harina 5}
+
+; Para transformar los elementos de etiqueta, definir la función de lectura y pasar un mapa
+; que asigna etiquetas a funciones del lector de edn/read-string al igual que.
+
+(edn/read-string {:lectores {'MyYelpClone/MenuItem map->menu-item}}
+ "#MyYelpClone/MenuItem {:nombre \"huevos-benedict\" :clasificacion 10}")
+; -> #user.MenuItem{:nombre "huevos-benedict", :clasificacion 10}
+
+```
+
+# Referencias
+
+- [EDN spec (EN)](https://github.com/edn-format/edn)
+- [Implementations (EN)](https://github.com/edn-format/edn/wiki/Implementations)
+- [Tagged Elements (EN)](http://www.compoundtheory.com/clojure-edn-walkthrough/)
diff --git a/es-es/jquery-es.html.markdown b/es-es/jquery-es.html.markdown
index d35e6f17..27ad48bb 100644
--- a/es-es/jquery-es.html.markdown
+++ b/es-es/jquery-es.html.markdown
@@ -79,7 +79,7 @@ $('#btn').on(
);
// Puede mover y ocultar elementos con algunos métodos de efecto
-$('.table').hide(); # Oculta el(los) elemento(s)
+$('.table').hide(); // Oculta el(los) elemento(s)
// Nota: llamar a una función en estos métodos aún oculta el elemento
$('.table').hide(function(){
@@ -134,7 +134,7 @@ $('p').height(); // Obtiene sólo la altura de la primera etiqueta 'p'
// Puedes utilizar 'each' para recorrer todos los elementos
var heights = [];
$('p').each(function() {
- heights.push($(this.height)); // Añade todas las alturas "p" de la etiqueta a la matriz
+ heights.push($(this).height()); // Añade todas las alturas "p" de la etiqueta a la matriz
});
diff --git a/es-es/less-es.html.markdown b/es-es/less-es.html.markdown
new file mode 100644
index 00000000..fa09db9f
--- /dev/null
+++ b/es-es/less-es.html.markdown
@@ -0,0 +1,393 @@
+---
+language: less
+filename: learnless-es.less
+lang: es-es
+contributors:
+ - ["Saravanan Ganesh", "http://srrvnn.me"]
+translators:
+ - ["César Suárez", "https://github.com/csuarez"]
+---
+
+Less es un pre-procesador CSS, que añade características como variables, anidación, mixins y más.
+Less (y otros pre-procesadores como [Sass](http://sass-lang.com/) ayudan a los desarrolladores a escribir código mantenible y DRY (Don't Repeat Yourself).
+
+```css
+
+
+//Los comentarios de una línea son borrados cuando Less es compilado a CSS.
+
+/* Los comentarios multi-línea se mantienen. */
+
+
+
+/*Variables
+==============================*/
+
+
+/* Puedes almacenar un valor CSS (como un color) en una variable.
+Usa el símbolo '@' para crear una variable. */
+
+@primary-color: #a3a4ff;
+@secondary-color: #51527f;
+@body-font: 'Roboto', sans-serif;
+
+/* Puedes usar las variables por toda tu hoja de estilos.
+Ahora, si quieres cambiar un color, sólo lo tienes que hacer una vez.*/
+
+body {
+ background-color: @primary-color;
+ color: @secondary-color;
+ font-family: @body-font;
+}
+
+/* Esto compilará en: */
+
+body {
+ background-color: #a3a4ff;
+ color: #51527F;
+ font-family: 'Roboto', sans-serif;
+}
+
+
+/* Esto es mucho más mantenible que tener que cambiar el color
+ cada vez que aparece en tu hoja de estilos. */
+
+
+
+/* Mixins
+==============================*/
+
+
+/* Si tienes el mismo código para más de un elemento, puede que
+ quieras reutilizarlo fácilmente. */
+
+.center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+/* Puedes usar un mixin simplemente añadiendo el selector como un estilo. */
+
+div {
+ .center;
+ background-color: @primary-color;
+}
+
+/* Esto compilará en: */
+
+.center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #a3a4ff;
+}
+
+/* Puedes omitir que se compile el código del mixin añadiendo un
+ paréntesis después del selector. */
+
+.center() {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+div {
+ .center;
+ background-color: @primary-color;
+}
+
+/* Esto compilará en: */
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #a3a4ff;
+}
+
+
+
+/* Anidación
+==============================*/
+
+
+/* Less te permite anidar selectores dentro de otros selectores. */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: #f00;
+ }
+}
+
+/* '&' es replazado por el selector padre. */
+/* También se pueden anidar seudo clases. */
+/* Ten en cuenta que anidar demasiado puede hacer tu código menos
+ mantenible. Las buenas prácticas recomiendan no tener más de 3 niveles de
+ anidación. Por ejemplo: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: red;
+
+ &:hover {
+ background-color: blue;
+ }
+
+ a {
+ color: white;
+ }
+ }
+}
+
+/* Compila en: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+}
+
+ul li {
+ background-color: red;
+}
+
+ul li:hover {
+ background-color: blue;
+}
+
+ul li a {
+ color: white;
+}
+
+
+
+/* Funciones
+==============================*/
+
+
+/* Less ofrece funciones que pueden ser usadas para cumplir una gran variedad
+ de tareas. Considera lo siguiente: */
+
+/* Las funciones pueden ser llamadas usando su nombre y pasándole los argumentos
+ requeridos. */
+
+body {
+ width: round(10.25px);
+}
+
+.header {
+ background-color: lighten(#000, 0.5);
+}
+
+.footer {
+ background-color: fadeout(#000, 0.25)
+}
+
+/* Compila en: */
+
+body {
+ width: 10px;
+}
+
+.header {
+ background-color: #010101;
+}
+
+.footer {
+ background-color: rgba(0, 0, 0, 0.75);
+}
+
+/* Puedes definir tus propias funciones. Las funciones son muy similares a
+ los mixins. Cuando tengas que elegir entre una función y un mixin, recuerda
+ que los mixins son mejores para generar CSS, mientras que las funciones son
+ mejores para la lógica que puedas necesitar en tu código Sass. Los ejemplos
+ de la sección 'Operadores matemáticos' son candidatos ideales para ser
+ usados como una función reusable. */
+
+/* Esta función calcula la media de dos números. */
+
+.average(@x, @y) {
+ @average-result: ((@x + @y) / 2);
+}
+
+div {
+ .average(16px, 50px); // aquí se llama a la función
+ padding: @average-result; // y aquí se usa el valor "devuelto"
+}
+
+/* Compila en: */
+
+div {
+ padding: 33px;
+}
+
+
+
+/* Extender (Herencia)
+==============================*/
+
+
+/* Extend es una manera de compartir propiedades de un selector con otro. */
+
+.display {
+ height: 50px;
+}
+
+.display-success {
+ &:extend(.display);
+ border-color: #22df56;
+}
+
+/* Compila en: */
+.display,
+.display-success {
+ height: 50px;
+}
+.display-success {
+ border-color: #22df56;
+}
+
+/* Extender una declaración CSS es preferible a crear un mixin
+ debido a la manera en la que Sass agrupa las clases que comparten
+ los mismos estilos base. Si esto fuese hecho con un mixin, el ancho,
+ alto y el borden aparecerían duplicados para cada una de las declaraciones
+ que usasen el mixin. Esto no afectará a tu workflow, pero infla
+ innecesariamente los ficheros generados por el compilador Less. */
+
+
+/*Partials and Imports
+==============================*/
+
+
+
+/* Less allows you to create partial files. This can help keep your Less
+ code modularized. Partial files conventionally begin with an '_',
+ e.g. _reset.less. and are imported into a main less file that gets
+ compiled into CSS */
+
+/* Consider the following CSS which we'll put in a file called _reset.less */
+
+html,
+body,
+ul,
+ol {
+ margin: 0;
+ padding: 0;
+}
+
+ /* Less ofrece @import para poder importar parciales a un fichero. Esto se
+ diferencia del @import de CSS en que no hace otra petición HTTP para
+ importar el fichero, sino que combina el código importado en el código
+ compilado. */
+
+@import 'reset';
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+/* Compila en: */
+
+html, body, ul, ol {
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+
+
+/* Operaciones matemáticas
+==============================*/
+
+
+/* Less ofrece los siguientes operadores: +, -, *, / y %. Estos son útiles
+ para calcular valores directamente en tu código Less en vez de usar valores
+ calculados a mano. Mira el siguiente ejemplo que prepara un sencillo diseño
+ de dos columnas. */
+
+@content-area: 960px;
+@main-content: 600px;
+@sidebar-content: 300px;
+
+@main-size: @main-content / @content-area * 100%;
+@sidebar-size: @sidebar-content / @content-area * 100%;
+@gutter: 100% - (@main-size + @sidebar-size);
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: @main-size;
+}
+
+.sidebar {
+ width: @sidebar-size;
+}
+
+.gutter {
+ width: @gutter;
+}
+
+/* Compila en: */
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+.gutter {
+ width: 6.25%;
+}
+
+
+```
+
+## Practica Less
+
+Si quieres probar Less en tu navegador, prueba:
+* [Codepen](http://codepen.io/)
+* [LESS2CSS](http://lesscss.org/less-preview/)
+
+## Compatibilidad
+
+Sass puede ser usado en cualquier proyecto mientras tengas un programa que lo compile en CSS. Quizás quieras comprobar si el CSS que estás usando es compatible con tus navegadores objetivo.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) y [CanIUse](http://caniuse.com) son buenos recursos para comprobar la compatibilidad de navegadores.
+
+## Más información
+* [Documentación oficial (EN)](http://lesscss.org/features/)
+* [Less CSS - Guía para principiantes (EN)](http://www.hongkiat.com/blog/less-basic/)
diff --git a/es-es/powershell-es.html.markdown b/es-es/powershell-es.html.markdown
index dd92eb97..9eb35967 100644
--- a/es-es/powershell-es.html.markdown
+++ b/es-es/powershell-es.html.markdown
@@ -18,7 +18,7 @@ Una diferencia clave con respecto a Bash es que en PowerShell casi todo son mani
Si no está seguro sobre el ambiente de ejecución en su sistema:
-```
+```powershell
Get-ExecutionPolicy -List
Set-ExecutionPolicy AllSigned
# Otras opciones de políticas de ejecución son:
diff --git a/es-es/sass-es.html.markdown b/es-es/sass-es.html.markdown
new file mode 100644
index 00000000..89e56ba5
--- /dev/null
+++ b/es-es/sass-es.html.markdown
@@ -0,0 +1,585 @@
+---
+language: sass
+filename: learnsass.scss
+contributors:
+ - ["Laura Kyle", "https://github.com/LauraNK"]
+ - ["Sean Corrales", "https://github.com/droidenator"]
+ - ["Kyle Mendes", "https://github.com/pink401k"]
+ - ["Keith Miyake", "https://github.com/kaymmm"]
+translators:
+ - ["César Suárez", "https://github.com/csuarez"]
+lang: es-es
+---
+
+Sass es un lenguaje que extiende CSS y que añade características tales como variables, anidación, mixins y más. Sass (y otros preprocesadores tales como [Less](http://lesscess.org/)) ayudan a los desarrolladores a escribir código mantenible y DRY (Don't Repeat Yourself).
+
+Sass tiene dos sintaxis para elegir: SCSS, que usa la misma que CSS pero con las características añadidas de Sass, y Sass (la sintaxis original) que usa identación en vez de llaves y puntos y comas. Este tutorial está escrito en SCSS.
+
+Si ya estás familiarizado con CSS3, vas a entender Sass relativamente rápido. Sass no ofrece nuevas propiedades de estilo, si no que añade herramientas para escribir tus CSS de manera más eficiente, haciendo su mantenimiento mucho más sencillo.
+
+```scss
+
+
+//Los comentarios en una sola línea son eliminados cuando Sass es compilado a CSS.
+
+/* Los comentarios multi-línea se mantienen. */
+
+
+
+/* Variables
+============================== */
+
+
+/* Puedes almacenar valores CSS (como un color) en una variable.
+Usa el símbolo '$' para crear una variable */
+
+$primary-color: #A3A4FF;
+$secondary-color: #51527F;
+$body-font: 'Roboto', sans-serif;
+
+/* Puedes usar las variables a lo largo de tu hoja de estilos.
+Ahora, si quieres cambiar el color, sólo lo tienes que hacer una vez. */
+
+body {
+ background-color: $primary-color;
+ color: $secondary-color;
+ font-family: $body-font;
+}
+
+/* Este código compilará en: */
+body {
+ background-color: #A3A4FF;
+ color: #51527F;
+ font-family: 'Roboto', sans-serif;
+}
+
+/* El resultado es mucho más mantenible que tener que cambiar el color
+cada vez que aparece en la hoja de estilos. */
+
+
+
+/* Directivas de control
+============================== */
+
+
+/* Sass permite usar @if, @else, @for, @while, y @each para controlar la
+ compilación de tu código en CSS. */
+
+/* Los bloques @if/@else se comportan tal como es de esperar */
+
+$debug: true !default;
+
+@mixin debugmode {
+ @if $debug {
+ @debug "Modo debug activado";
+
+ display: inline-block;
+ }
+ @else {
+ display: none;
+ }
+}
+
+.info {
+ @include debugmode;
+}
+
+/* Si $debug es true, .info es mostrado; si es false entonces
+no se muestra.
+
+Nota: @debug mostrará información de depuración en la consola.
+Es muy útil para ver el contenido de tus variables cuando estás depurando. */
+
+.info {
+ display: inline-block;
+}
+
+/* @for es un bucle que itera un conjunto de valores.
+Es particularmente útil para dar estilos a una colección de objetos.
+Hay dos formas "through" y "to". El primero incluye el último valor
+mientras que el segundo para antes del último valor. */
+
+@for $c from 1 to 4 {
+ div:nth-of-type(#{$c}) {
+ left: ($c - 1) * 900 / 3;
+ }
+}
+
+@for $c from 1 through 3 {
+ .myclass-#{$c} {
+ color: rgb($c * 255 / 3, $c * 255 / 3, $c * 255 / 3);
+ }
+}
+
+/* Esto compila en: */
+
+div:nth-of-type(1) {
+ left: 0;
+}
+
+div:nth-of-type(2) {
+ left: 300;
+}
+
+div:nth-of-type(3) {
+ left: 600;
+}
+
+.myclass-1 {
+ color: #555555;
+}
+
+.myclass-2 {
+ color: #aaaaaa;
+}
+
+.myclass-3 {
+ color: white;
+// SASS convierte automáticamente #FFFFFF a white
+}
+
+/* @while es bastante sencillo: */
+
+$columns: 4;
+$column-width: 80px;
+
+@while $columns > 0 {
+ .col-#{$columns} {
+ width: $column-width;
+ left: $column-width * ($columns - 1);
+ }
+
+ $columns: $columns - 1;
+}
+
+/* Esto se convierte en el siguiente CSS: */
+
+.col-4 {
+ width: 80px;
+ left: 240px;
+}
+
+.col-3 {
+ width: 80px;
+ left: 160px;
+}
+
+.col-2 {
+ width: 80px;
+ left: 80px;
+}
+
+.col-1 {
+ width: 80px;
+ left: 0px;
+}
+
+/* @each funciona parecido a @for, pero usa una lista en ver del valor ordinal
+Nota: puedes especificar listas como cualquier otra variable usando espacios
+como delimitadores. */
+
+$social-links: facebook twitter linkedin reddit;
+
+.social-links {
+ @each $sm in $social-links {
+ .icon-#{$sm} {
+ background-image: url("images/#{$sm}.png");
+ }
+ }
+}
+
+/* Esto resultará en: */
+
+.social-links .icon-facebook {
+ background-image: url("images/facebook.png");
+}
+
+.social-links .icon-twitter {
+ background-image: url("images/twitter.png");
+}
+
+.social-links .icon-linkedin {
+ background-image: url("images/linkedin.png");
+}
+
+.social-links .icon-reddit {
+ background-image: url("images/reddit.png");
+}
+
+
+
+/* Mixins
+==============================*/
+
+
+/* Si te encuentras con que estás escribiendo el mismo código en más de un
+elemento, puede que quieras almacenarlo en un mixin.
+
+Usa la directiva '@mixin', más un nombre para tu mixin. */
+
+@mixin center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+/* Puedes usarlo con '@include' y el nombre del mixin. */
+
+div {
+ @include center;
+ background-color: $primary-color;
+}
+
+/* Esto compilará en: */
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #A3A4FF;
+}
+
+/* Puedes usar mixins para crear una propiedad shorthand. */
+
+@mixin size($width, $height) {
+ width: $width;
+ height: $height;
+}
+
+/* La que puedes invocar pasándole los argumentos width y height. */
+
+.rectangle {
+ @include size(100px, 60px);
+}
+
+.square {
+ @include size(40px, 40px);
+}
+
+/* Compila en: */
+.rectangle {
+ width: 100px;
+ height: 60px;
+}
+
+.square {
+ width: 40px;
+ height: 40px;
+}
+
+
+
+/* Funciones
+============================== */
+
+
+/* Sass ofrece funciones que pueden ser usadas para realizar una gran variedad
+ de tareas. Por ejemplo: */
+
+/* Se pueden invocar funciones usando su nombre y pasándole los
+ argumentos requeridos. */
+body {
+ width: round(10.25px);
+}
+
+.footer {
+ background-color: fade_out(#000000, 0.25);
+}
+
+/* Compila en: */
+
+body {
+ width: 10px;
+}
+
+.footer {
+ background-color: rgba(0, 0, 0, 0.75);
+}
+
+/* Puedes definir tus propias funciones. Las funciones son muy similares a
+ los mixins. Cuando tengas que elegir entre una función y un mixin, recuerda
+ que los mixins son mejores para generar CSS, mientras que las funciones son
+ mejores para la lógica que puedas necesitar en tu código Sass. Los ejemplos
+ de la sección 'Operadores matemáticos' son candidatos ideales para ser
+ usados como una función reusable. */
+
+/* Esta función toma un tamaño objetivo y el tamaño de un padre y
+ devuelve el porcentaje. */
+
+@function calculate-percentage($target-size, $parent-size) {
+ @return $target-size / $parent-size * 100%;
+}
+
+$main-content: calculate-percentage(600px, 960px);
+
+.main-content {
+ width: $main-content;
+}
+
+.sidebar {
+ width: calculate-percentage(300px, 960px);
+}
+
+/* Compila en: */
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+
+
+/* Extender (Herencia)
+============================== */
+
+
+/* Extend es una manera de compartir propiedades de un selector con otro. */
+
+.display {
+ @include size(5em, 5em);
+ border: 5px solid $secondary-color;
+}
+
+.display-success {
+ @extend .display;
+ border-color: #22df56;
+}
+
+/* Compila en: */
+.display, .display-success {
+ width: 5em;
+ height: 5em;
+ border: 5px solid #51527F;
+}
+
+.display-success {
+ border-color: #22df56;
+}
+
+/* Extender una declaración CSS es preferible a crear un mixin
+ debido a la manera en la que Sass agrupa las clases que comparten
+ los mismos estilos base. Si esto fuese hecho con un mixin, el ancho,
+ alto y el borden aparecerían duplicados para cada una de las declaraciones
+ que usasen el mixin. Esto no afectará a tu workflow, pero infla
+ innecesariamente los ficheros generados por el compilador Sass. */
+
+
+
+/* Anidación
+============================== */
+
+
+/* Sass permite anidar selectores dentro de otros selectores. */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: #FF0000;
+ }
+}
+
+/* '&' será reemplazado por el selector del padre. */
+
+/* También puedes anidar seudo clases. */
+
+/* Ten en cuenta que anidar demasiado hará tu código menos mantenible.
+Como buena práctica, se recomienda no tener más de 3 niveles de anidación.
+Por ejemplo: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: red;
+
+ &:hover {
+ background-color: blue;
+ }
+
+ a {
+ color: white;
+ }
+ }
+}
+
+/* Compila en: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+}
+
+ul li {
+ background-color: red;
+}
+
+ul li:hover {
+ background-color: blue;
+}
+
+ul li a {
+ color: white;
+}
+
+
+
+/* Parciales e importaciones
+============================== */
+
+
+/* Sass permite que crees ficheros parciales. Esto te puede ayudar a mantener
+ tu código Sass modularizado. Los ficheros parciales deben comenzar por '_',
+ p.e. _reset.css.
+ Los parciales no son convertidos en CSS. */
+
+/* Mira este al que vamos a añadir un fichero llamado _reset.css */
+
+html,
+body,
+ul,
+ol {
+ margin: 0;
+ padding: 0;
+}
+
+/* Con @import puedes importar parciales a un fichero. Este se diferencia del
+ @import de CSS en que no hace otra petición HTTP para importar el fichero.
+ Sass, sino que combina el código importado en el código compilado. */
+
+@import 'reset';
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+/* Compila en: */
+
+html, body, ul, ol {
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+
+
+/* Placeholders
+============================== */
+
+
+/* Los placeholders son útiles cuando estás creando una declaración CSS a
+ extender. Si quieres crear una declaración que sólo va a ser usada con @extend,
+ puedes hacerlo mediante un placeholder. Los placeholders comienzan con '%'
+ en vez de '.' o '#'. Esto no aparecen en el código CSS compilado. */
+
+%content-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ @extend %content-window;
+ background-color: #0000ff;
+}
+
+/* Compila en: */
+
+.message-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ background-color: #0000ff;
+}
+
+
+
+/* Operaciones matemáticas
+============================== */
+
+
+/* Sass provee los siguientes operadores: +, -, *, / y %. Estos son útiles
+ para calcular valores directamente en tu código Sass en vez de usar valores
+ calculados a mano. Mira el siguiente ejemplo que prepara un sencillo diseño
+ de dos columnas. */
+
+$content-area: 960px;
+$main-content: 600px;
+$sidebar-content: 300px;
+
+$main-size: $main-content / $content-area * 100%;
+$sidebar-size: $sidebar-content / $content-area * 100%;
+$gutter: 100% - ($main-size + $sidebar-size);
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: $main-size;
+}
+
+.sidebar {
+ width: $sidebar-size;
+}
+
+.gutter {
+ width: $gutter;
+}
+
+/* Compila en: */
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+.gutter {
+ width: 6.25%;
+}
+
+```
+
+## ¿SASS o Sass?
+¿Alguna vez has pensado si Sass es un acrónimo o no? Seguramente no, pero te lo vamos a explicar de todas maneras. "Sass" es una palabra, no un acrónimo.
+Como todo el mundo lo escribe como "SASS", el creador del lenguaje lo ha llamado de broma "Syntactically Awesome StyleSheets" (Hojas de estilo sintácticamente increíbles).
+
+
+## Practica Sass
+Si quieres probar Sass en tu navegador, prueba [SassMeister](http://sassmeister.com/).
+Puedes usar cualquier sintaxis, o elegir en la configuración entre Sass y SCSS.
+
+## Compatibilidad
+Sass puede ser usado en cualquier proyecto mientras tengas un programa que lo compile en CSS. Quizás quieras comprobar si el CSS que estás usando es compatible con tus navegadores objetivo.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) y [CanIUse](http://caniuse.com) son buenos recursos para comprobar la compatibilidad de navegadores.
+
+
+## Más información
+* [Documentación oficial (EN)](http://sass-lang.com/documentation/file.SASS_REFERENCE.html)
+* [The Sass Way (EN)](http://thesassway.com/) tiene tutoriales (para principiantes y avanzandos) and artículos.
diff --git a/es-es/wolfram-es.html.markdown b/es-es/wolfram-es.html.markdown
new file mode 100644
index 00000000..44ec9e09
--- /dev/null
+++ b/es-es/wolfram-es.html.markdown
@@ -0,0 +1,138 @@
+---
+language: wolfram
+lang: es-es
+contributors:
+ - ["Daniel Caballero", "http://github.com/danielcaballero796/"]
+filename: learnwolfram-es.md
+---
+
+Wolfram es un lenguaje subyacente originalmente utilizado en Mathematica, pero ahora esta disponible para su uso en múltiples contextos.
+
+El lenguaje de Wolfram tiene varias interfaces:
+* La interfaz de línea de comandos kernel de Raspberry Pi (recién llamada _The Wolfram Language_) que se ejecuta interactivamente y no puede producir entrada gráfica.
+* _Mathematica_ que es un texto rico / editor de matemáticas con Wolfram interactivo construido: presionando shift + Return en una "celda de código" crea una celda de salida con el resultado, que no es dinámica
+* _Wolfram Workbench_ la cual es la interfaz de Eclipse del lenguaje Wolfram
+
+El código de este ejemplo se puede escribir en cualquier interfaz y editarlo con Wolfram Workbench. Cargar directamente en Matematica puede resultar incómodo porque el archivo no contiene información de formato de celda (lo que haría que el archivo sea un desastre enorme para ser leído como texto) - puede ser visto / editado pero tal vez requerira algún ajuste.
+
+```
+(* Esto es un comentario *)
+
+(* En Mathematica en lugar de utilizar estos comentarios, puede crear una celda de texto
+ Y anotar su código con texto e imágenes bien escritas *)
+
+(* Escribe una expresión devuelve el resultado *)
+2*2 (* 4 *)
+5+8 (* 13 *)
+
+(* Llamada de función *)
+(* Nota, los nombres de funciones (y todo lo demás) distingue entre mayúsculas y minúsculas *)
+Sin[Pi/2] (* 1 *)
+
+(* Sintaxis alternativa para la Llamada de una función con un parámetro *)
+Sin@(Pi/2) (* 1 *)
+(Pi/2) // Sin (* 1 *)
+
+(* Cada sintaxis en WL tiene algún equivalente como una llamada de función *)
+Veces[2, 2] (* 4 *)
+Mas[5, 8] (* 13 *)
+
+(* El uso de una variable por primera vez lo define y lo hace global *)
+x = 5 (* 5 *)
+x == 5 (* verdadero, Estilo-C asignación y pruebas de igualdad *)
+x (* 5 *)
+x = x + 5 (* 10 *)
+x (* 10 *)
+Modifique[x, 20] (* No estaba bromeando cuando dije que TODO tiene una función equivalente *)
+x (* 20 *)
+
+(* Debido a que WL se basa en un sistema de álgebra computacional, *)
+(* El uso de variables indefinidas está bien, simplemente obstruyen la evaluación *)
+cow + 5 (* 5 + cow, cow es indefinido por lo que no puede evaluar más *)
+cow + 5 + 10 (* 15 + cow, Va a evaluar lo que puede *)
+% (* 15 + cow, % Busca el último retorno *)
+% - cow (* 15, cow variable indefinida cancelada *)
+moo = cow + 5 (* Cuidado, moo ahora tiene una expresión, no un número! *)
+
+(* Definición de una función *)
+Double[x_] := x * 2 (* Nota: = para evitar la evaluación inmediata del RHS
+ y después de x para indicar que no hay restricciones de concordancia de patrones *)
+Double[10] (* 20 *)
+Double[Sin[Pi/2]] (* 2 *)
+Double @ Sin @ (Pi/2) (* 2, @-Sintaxis evita colas de paréntesis *)
+(Pi/2) // Sin // Double(* 2, //-Sintaxis lista las funciones en orden de ejecución *)
+
+(* Para un uso de programación de estilo imperativo; Para separar declaraciones *)
+(* Descarta cualquier salida de LHS y ejecuta RHS *)
+miPrimero[] := (Print@"Hola"; Print@"Mundo") (* Tenga en cuenta que los padres externos son críticos
+ ; La precedencia es menor que := *)
+miPrimero[] (* Hola Mundo *)
+
+(* Estilo-C para bucle *)
+PrintTo[x_] := For[y=0, y<x, y++, (Print[y])] (* Start, test, incr, body *)
+PrintTo[5] (* 0 1 2 3 4 *)
+
+(* bucle *)
+x = 0; While[x < 2, (Print@x; x++)] (* Ciclo con prueba y cuerpo *)
+
+(* Si y condicionales *)
+x = 8; If[x==8, Print@"Yes", Print@"No"] (* Condición, Caso verdadero, Caso distinto*)
+Switch[x, 2, Print@"Two", 8, Print@"Yes"] (* Interruptor de estilo de coincidencia de valor *)
+Which[x==2, Print@"No", x==8, Print@"Yes"] (* estilo de caso distinto *)
+
+(* Las variables distintas de los parámetros son globales por defecto, incluso dentro de las funciones *)
+y = 10 (* 10, Variable global y *)
+PrintTo[5] (* 0 1 2 3 4 *)
+y (* 5, Global por contador de bucle dentro de PrintTo *)
+x = 20 (* 20, Variable global x *)
+PrintTo[5] (* 0 1 2 3 4 *)
+x (* 20, x en PrintTo Es un parámetro y automáticamente local *)
+
+(* Las variables locales se declaran utilizando la metafunción del módulo *)
+(* Version con variable local*)
+BetterPrintTo[x_] := Module[{y}, (For[y=0, y<x, y++, (Print@y)])]
+y = 20 (* Variable global y *)
+BetterPrintTo[5] (* 0 1 2 3 4 *)
+y (* 20, eso es mejor *)
+
+(* El módulo realmente nos permite declarar cualquier ámbito que nos guste *)
+Module[{count}, count=0; (* Declare el alcance de este recuento de variables *)
+ (IncCount[] := ++count); (* Estas funciones están dentro de ese ámbito *)
+ (DecCount[] := --count)]
+count (* count - Variable global count no esta definida *)
+IncCount[] (* 1, usando count variable dentro del alcance *)
+IncCount[] (* 2, incCount lo actualiza *)
+DecCount[] (* 1, decCount tambien lo hace *)
+count (* count - Aún ninguna variable global con ese nombre*)
+
+(* listas *)
+miLista = {1, 2, 3, 4} (* {1, 2, 3, 4} *)
+miLista[[1]] (* 1 - Los índices de la lista de notas comienzan en 1, no 0 *)
+Map[Double, miLista] (* {2, 4, 6, 8} - Lista de estilo funcional mapa función *)
+Double /@ miLista (* {2, 4, 6, 8} - Sintaxis abreviada para arriba *)
+Scan[Print, miLista] (* 1 2 3 4 - Lista de bucle sobre estilo imperativo *)
+Fold[Plus, 0, miLista] (* 10 (0+1+2+3+4) *)
+FoldList[Plus, 0, miLista] (* {0, 1, 3, 6, 10} - Guardar los resultados intermedios *)
+Append[miLista, 5] (* {1, 2, 3, 4, 5} - Note que miLista no está actualizada *)
+Prepend[miLista, 5] (* {5, 1, 2, 3, 4} - añada "miLista = " Si quieres que lo sea *)
+Join[miLista, {3, 4}] (* {1, 2, 3, 4, 3, 4} *)
+miLista[[2]] = 5 (* {1, 5, 3, 4} - Esto actualiza miLista *)
+
+(* Asociaciones, aka Diccionarios /Hashes *)
+miHash = <|"Green" -> 2, "Red" -> 1|> (* crea una asociación *)
+miHash[["Green"]] (* 2, uselo *)
+miHash[["Green"]] := 5 (* 5, actualizalo *)
+miHash[["Puce"]] := 3.5 (* 3.5, extiendalo *)
+KeyDropFrom[miHash, "Verde"] (* Limpia la llave Verde *)
+Claves[miHash] (* {Rojo} *)
+Valores[miHash] (* {1} *)
+
+(* Y no puedes hacer ninguna demo de Wolfram sin mostrar esto *)
+Manipular[y^2, {y, 0, 20}] (* Devuelve una interfaz de usuario reactiva que muestra y ^ 2
+ Y permite ajustar y entre 0-20 con un deslizador.
+ Sólo funciona en interfaces gráficas *)
+```
+
+##Listo para mas?
+
+* [Centro de Documentación](http://reference.wolfram.com/language/)
diff --git a/fr-fr/binary-search-fr.html.markdown b/fr-fr/binary-search-fr.html.markdown
new file mode 100644
index 00000000..4c34da0f
--- /dev/null
+++ b/fr-fr/binary-search-fr.html.markdown
@@ -0,0 +1,67 @@
+---
+category: Algorithms & Data Structures
+name: Binary Search
+contributors:
+ - ["Abhishek Jaisingh", "http://github.com/abhishekjiitr"]
+translators:
+ - ["Hughes Perreault", "https://github.com/hperreault"]
+lang: fr-fr
+---
+
+# Recherche Binaire
+
+## Pourquoi la Recherche Binaire ?
+
+La recherche est un des principaux problèmes dans le domaine de l'informatique. De nos jours, il y a plus de 1 milliard de recherches par année, et nous avons besoin d'algorithmes pour faire cela rapidement. La recherche binaire est un des algorithmes les plus fondamentaux en informatique. Pour pouvoir l'explorer en détail, nous allons d'abord établir une base théorique, puis nous allons utiliser cette base pour implémenter l'algorithme en soi.
+
+## Introduction
+
+Une façon simple d'implémenter la recherche est de faire une recherche linéaire. Cependant, cette approche prend beaucoup de temps, et ce temps augmente linéairement avec la quantité de données. Par exemple, partons du premier élément d'un tableau t[], et un par un, comparons x avec chaque élément de t[]. Si x est égal à un élément, nous retournons l'index, si x n'égale aucun élément, nous retournons -1.
+
+```
+Recherche Linéaire: O (n) Temps Linéaire
+
+Recherche Binaire: O ( log(n) ) Temps Logarithmique
+
+```
+```
+def search(arr, x):
+
+ for i in range(len(arr)):
+
+ if arr[i] == x:
+ return i
+
+ return -1
+
+```
+## L'Algorithme de Recherche Binaire
+
+Le prérequis fondamental de la recherche binaire est que les éléments soient triés.
+
+### Algo
+
+```
+L'idée derrière la recherche binaire est d'utiliser le fait que le tableau est trié afin de réduire la complexité à O(Log(n)). Nous pouvons ignorer la moitié des éléments après la première comparaison.
+1) Comparons x avec l'élément du milieu.
+2) Si x est égal à cet élément, nous retournons l'index du milieu.
+3) Sinon, si x est plus grand que l'élément du milieu, alors x peut seulement être dans la dernière moitié du tableau. Donc, nous recommençons la procédure avec cette dernière moitié.
+4) Sinon (x est plus petit), nous recommençons la procédure avec la première moitié du tableau.
+Ensuite nous avons une implémentation récursive de la recherche binaire.
+
+```
+
+### Note de la fin
+
+Partie en construction.
+
+## Livre
+
+* [CLRS EN](https://mitpress.mit.edu/books/introduction-algorithms)
+* [Algorithmes EN](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X)
+* [Design d'Algorithmes EN](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651)
+
+## Ressources en ligne
+
+* [GeeksforGeeks EN](http://www.geeksforgeeks.org/the-ubiquitous-binary-search-set-1/)
+* [Topcoder Tutorial EN](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/)
diff --git a/fr-fr/dynamic-programming-fr.html.markdown b/fr-fr/dynamic-programming-fr.html.markdown
new file mode 100644
index 00000000..24e8c95f
--- /dev/null
+++ b/fr-fr/dynamic-programming-fr.html.markdown
@@ -0,0 +1,55 @@
+---
+category: Algorithms & Data Structures
+name: Dynamic Programming
+contributors:
+ - ["Akashdeep Goel", "http://github.com/akashdeepgoel"]
+translators:
+ - ["Hughes Perreault", "https://github.com/hperreault"]
+lang: fr-fr
+---
+
+
+# Programmation dynamique
+
+## Introduction
+
+La programmation dynamique est une technique très efficace pour résoudre une certaine classe de problèmes, comme nous allons le voir. L'idée est très simple, si nous avons résolu un problème avec une certaine entrée, alors nous sauvons le résultat pour pouvoir y accéder plus tard, pour éviter d'avoir à le calculer à nouveau.
+
+## Moyens de résoudre ces problèmes
+
+1.) *De haut en bas* : Commençons à résoudre le problème en le séparant en morceaux. Si nous voyons que le problème a déjà été résolu, alors nous retournons la réponse précédemment sauvegardée. Si le problème n'a pas été résolu, alors nous le résolvons et sauvegardons la réponse. C'est généralement facile et intuitif de réfléchir de cette façon. Cela s'appelle la Mémorisation.
+
+2.) *De bas en haut* : Il faut analyser le problème et trouver les sous-problèmes, et l'ordre dans lequel il faut les résoudre. Ensuite, nous devons résoudre les sous-problèmes et monter jusqu'au problème que nous voulons résoudre. De cette façon, nous sommes assurés que les sous-problèmes sont résolus avant de résoudre le vrai problème. Cela s'appelle la Programmation Dynamique.
+
+## Exemple de Programmation Dynamique
+
+Le problème de la plus grande sous-chaîne croissante est de trouver la plus grande sous-chaîne croissante dans une chaîne. Soit la chaîne `S = {a1, a2, a3, a4, ............., an-1, an}`, nous avons à trouver la plus grande chaîne telle que pour tout `j` et `i`, `j<i` dans la chaîne `aj<ai`.
+Premièrement, nous avons à trouver la valeur de la plus grande sous-chaîne (LSi) à chaque index `i`, avec le dernier élément de la sous-chaîne étant ai. Alors, la plus grande sous-chaîne sera le plus gros LSi. Pour commencer, LSi est égal à 1, car ai est le seul élément de la chaîne (le dernier). Ensuite, pour chaque `j` tel que `j<i` et `aj<ai`, nous trouvons le plus grand LSj et ajoutons le à LSi. L'algorithme fonctionne en temps *O(n2)*.
+
+Pseudo-code pour trouver la longueur de la plus grande sous-chaîne croissante :
+La complexité de cet algorithme peut être réduite en utilisant une meilleure structure de données qu'un tableau. Par exemple, si nous sauvegardions le tableau d'origine, ou une variable comme plus_grande_chaîne_jusqu'à_maintenant et son index, nous pourrions sauver beaucoup de temps.
+
+Le même concept peut être appliqué pour trouver le chemin le plus long dans un graphe acyclique orienté.
+
+```python
+ for i=0 to n-1
+ LS[i]=1
+ for j=0 to i-1
+ if (a[i] > a[j] and LS[i]<LS[j])
+ LS[i] = LS[j]+1
+ for i=0 to n-1
+ if (largest < LS[i])
+```
+
+### Problèmes classiques de programmation dynamique
+
+L'algorithme de Floyd Warshall(EN)) - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code
+
+Problème du sac à dos(EN) - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem
+
+
+Plus longue sous-chaîne commune(EN) - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence
+
+## Online Resources
+
+* [codechef EN](https://www.codechef.com/wiki/tutorial-dynamic-programming)
diff --git a/fr-fr/jquery-fr.html.markdown b/fr-fr/jquery-fr.html.markdown
new file mode 100644
index 00000000..1842e02b
--- /dev/null
+++ b/fr-fr/jquery-fr.html.markdown
@@ -0,0 +1,142 @@
+---
+category: tool
+tool: jquery
+contributors:
+ - ["Sawyer Charles", "https://github.com/xssc"]
+translators:
+ - ["Sylvain Vaure", "https://github.com/Gnomino"]
+filename: jquery-fr.js
+lang: fr-fr
+---
+
+jQuery est une bibliothèque JavaScript dont le but est de permettre de "faire plus en écrivant moins" (do more, write less). Elle facilite l'écriture de nombreuses fonctions, notamment au niveau d'AJAX, de la gestion d'événements, ou encore de la manipulation de documents.
+C'est pourquoi aujourd'hui, jQuery est utilisée par de nombreuses grandes entreprises et par des développeurs du monde entier.
+
+Étant donné que jQuery est une bibliothèque JavaScript, vous devriez d'abord [apprendre le JavaScript](https://learnxinyminutes.com/docs/fr-fr/javascript-fr/)
+```js
+
+
+///////////////////////////////////
+// 1. Les sélecteurs
+
+// On utilise les sélecteurs de jQuery pour sélectionner des éléments
+var page = $(window); // Sélectionne tout le viewport
+
+// On peut aussi utiliser des sélecteurs CSS
+var paragraph = $('p'); // Sélectionne tous les éléments paragraphes
+var table1 = $('#table1'); // Sélectionne l'élément qui a l'id 'table1'
+var squares = $('.square'); // Sélectionne tous les éléments avec la classe 'square'
+var square_p = $('p.square') // Sélectionne tous les paragraphes avec la classe 'square'
+
+
+///////////////////////////////////
+// 2. Événements et effets
+// jQuery gère très bien ce qui se passe lorsqu'un événement est déclenché
+// L'événement 'ready' est très souvent utilisé sur le document
+// On utilise la méthode 'ready' pour attendre que l'élément ait fini de se charger
+$(document).ready(function(){
+ // Ce code ne s'exécutera pas avant que le document soit chargé (prêt)
+});
+// On peut aussi utiliser des fonctions définies
+function onAction() {
+ // Ceci est exécuté quand l'événement est déclenché
+}
+$('#btn').click(onAction); // Appelle onAction à chaque clic
+
+function onAction() {
+ // Ceci est exécuté quand un évènement est déclenché
+}
+
+// D'autres évènements communs :
+$('#btn').dblclick(onAction); // Double clic
+$('#btn').hover(onAction); // Survol de la souris
+$('#btn').focus(onAction); // Gain du focus
+$('#btn').blur(onAction); // Perte du focus
+$('#btn').submit(onAction); // Envoi (d'un formulaire)
+$('#btn').select(onAction); // Quand un élement est sélectionné
+$('#btn').keydown(onAction); // Quand une touche est enfoncée
+$('#btn').keyup(onAction); // Quand une touche est relâchée
+$('#btn').keypress(onAction); // Quand on appuie sur un touche
+$('#btn').mousemove(onAction); // Quand la souris se déplace
+$('#btn').mouseenter(onAction); // La souris entre dans l'élément
+$('#btn').mouseleave(onAction); // La souris sort de l'élément
+
+// On peut aussi utiliser des fonctions lambdas
+$('#btn').hover(function(){
+ // exécuté lors d'un survol de la souris
+});
+
+// Il est possible de déclencher l'événement sans le gérer
+// simplement en ne passant aucun paramètre à la méthode
+$('#btn').dblclick(); // Simule un double clic sur l'élément
+
+// On peut gérer plusieurs événements en utilisant le sélecteur une seule fois
+$('#btn').on(
+ {dblclick: myFunction1} // Déclenché à chaque double clic
+ {blur: myFunction1} // Déclenché quand l'élément perd le focus
+);
+
+// On peut déplacer et cacher des éléments grâce à des fonctions d'effets
+$('.table').hide(); // Cache le(s) élément(s)
+
+// Note: même avec un appel à une fonction dans ces méthodes
+// cache quand même l'élément
+$('.table').hide(function(){
+ // L'élément est caché, puis la fonction est exécutée
+});
+
+// On peut stocker des sélecteurs dans des variables
+var tables = $('.table');
+
+// Des méthodes basique de manipulation de document :
+tables.hide(); // Cache un(des) élément(s)
+tables.show(); // Montre (dé-cache) un(des) élément(s)
+tables.toggle(); // Change le statut le statut caché/montré
+tables.fadeOut(); // Fait disparaître l'élément
+tables.fadeIn(); // Fait apparaître l'élément
+tables.fadeToggle(); // Fait apparaître ou disparaître
+tables.fadeTo(0.5); // Fondu jusqu'à une certaine opacité (entre 0 et 1)
+tables.slideUp(); // Cache l'élément avec un effet de glissement vers le haut
+tables.slideDown(); // Fait apparaître l'élément avec un glissement vers le bas
+tables.slideToggle(); // Cache/Montre l'élément avec un effet de glissement
+
+// Les méthodes ci-dessus prennent en arguments
+// une vitesse (millisecondes) et une function callback
+tables.hide(1000, myFunction); // Animation d'une seconde, puis appel à la fonction
+
+// fadeTo doit avoir une opacité entre 0 et 1 comme deuxième argument
+tables.fadeTo(2000, 0.1, myFunction); // 2 sec. fade to 0.1 opacity then function
+
+// La méthode animate permet des animations légèrement plus poussées
+tables.animate({margin-top:"+=50", height: "100px"}, 500, myFunction);
+// La méthode prend un objet de css et de valeurs finales,
+// des paramètres d'options facultatifs pour régler l'animation,
+// et bien sûr la fonction callback
+
+///////////////////////////////////
+// 3. Manipulation
+
+// Ces méthodes sont similaires aux effets mais permettent d'aller plus loin
+$('div').addClass('taming-slim-20'); // Ajoute la classe taming-slim-20 aux div
+
+// Méthodes ordinaires de manipulation
+$('p').append('Hello world'); // Ajoute à la fin de l'élément
+$('p').attr('class'); // Renvoie la valeur de l'attribut
+$('p').attr('class', 'content'); // Change la valeur de l'attribut
+$('p').hasClass('taming-slim-20'); // Renvoie vrai si l'élément est de la classe
+$('p').height(); // Renvoie la hauteur de l'élément ou la change
+
+
+// Pour beaucoup de méthodes de manipulation, récupérer des informations
+// d'un élément renverra SEULEMENT ceelles du premier
+$('p').height(); // Renvoie SEULEMENT la hauteur du premier élément 'p'
+
+// On peut utiliser 'each' pour parcourir tous les éléments
+var heights = [];
+$('p').each(function() {
+ heights.push($(this).height()); // Ajoute la hauteur de tous les éléments 'p' à la liste
+});
+
+
+``
+
diff --git a/fr-fr/vim.html.markdown b/fr-fr/vim.html.markdown
new file mode 100644
index 00000000..8e84bf33
--- /dev/null
+++ b/fr-fr/vim.html.markdown
@@ -0,0 +1,239 @@
+---
+category: tool
+tool: vim
+filename: LearnVim.txt
+contributors:
+ - ["RadhikaG", "https://github.com/RadhikaG"]
+translators:
+ - ["Thibault", "https://github.com/napnac"]
+lang: fr-fr
+---
+
+
+[Vim](www.vim.org)
+(Vi IMproved) est le clone le plus populaire de l'éditeur de texte vi sous Unix.
+Vim est un éditeur de texte omniprésent sur les systèmes de type Unix, et a pour
+objectif la rapidité ainsi que l'augmentation de la productivité. Il a de
+nombreux raccourcis claviers pour une navigation et une édition plus rapide.
+
+## Navigation basique avec Vim
+
+```
+ vim <ficher> # Ouvre <fichier> avec vim
+ :q # Quitte vim
+ :w # Sauvegarde le fichier actuel
+ :wq # Sauvegarde le fichier actuel et quitte vim
+ :q! # Quitte vim sans sauvegarder
+ # ! *force* l'exécution de :q, ce qui par conséquent
+ # oblige vim à quitter sans sauvegarder
+ :x # Sauvegarde le fichier et quitte vim (raccourcis de :wq)
+
+ u # Annuler
+ CTRL+R # Rétablir
+
+ h # Déplace le curseur vers la gauche
+ j # Déplace le curseur vers le bas
+ k # Déplace le curseur vers le haut
+ l # Déplace le curseur vers la droite
+
+ # Mouvements au sein d'une ligne
+
+ 0 # Va au début de la ligne
+ $ # Va à la fin de la ligne
+ ^ # Va au premier caractère non blanc de la ligne
+
+ # Rechercher dans un texte
+
+ /mot # Surligne toutes les occurrences du mot après le curseur
+ ?mot # Surligne toutes les occurrences du mot avant le curseur
+ n # Déplace le curseur sur la prochaine occurrence du mot recherché
+ N # Déplace le curseur sur la précédente occurrence du mot recherché
+
+ :%s/abc/def/g # Transforme les 'abc' en 'def' sur chaque ligne du texte
+ :s/abc/def/g # Transforme les 'abc' en 'def' sur la ligne actuelle
+
+ # Se déplacer vers un caractère
+
+ f<caractère> # Se déplace en avant jusqu'à <caractère>
+ t<caractère> # Se déplace en avant juste avant <caractère>
+
+ # Par exemple
+ f< # Se déplace en avant jusqu'à <
+ t< # Se déplace en avant juste avant <
+
+ # Se déplacer dans un mot
+
+ w # Avance d'un mot
+ b # Recule d'un mot
+ e # Se déplace jusqu'à la fin du mot actuel
+
+ # D'autres raccourcis pour se déplacer
+
+ gg # Va au début du fichier
+ G # Va à la fin du fichier
+ :NB # Va à la ligne numéro NB (où NB est un nombre)
+ H # Se déplace jusqu'en haut de l'écran
+ M # Se déplace jusqu'au milieu de l'écran
+ L # Se déplace jusqu'en bas de l'écran
+```
+
+## Modes
+
+Vim est basé sur le concept de **modes**.
+
+Mode Commande - pour se déplacer et exécuter des commandes (vim démarre dans ce mode)
+Mode Insertion - pour éditer le fichier
+Mode Visuel - pour sélectionner du texte et réaliser des opérations dessus
+Mode Ex - pour entrer des commandes avec ':'
+
+```
+ i # Mode insertion, avant le curseur
+ a # Mode insertion, après le curseur
+ v # Mode visuel
+ : # Mode ex
+ <esc> # 'Echap' permet de revenir dans le mode commande
+
+ # Copier/Coller du texte
+
+ y # Copie le texte sélectionné
+ yy # Copie la ligne actuelle
+ d # Supprime ce qui est sélectionné
+ dd # Supprime la ligne actuelle
+ p # Colle après le curseur
+ P # Colle avant le curseur
+ x # Supprime le caractère sous le curseur
+```
+
+## La "Grammaire" de Vim
+
+Vim peut être vu comme un ensemble de commande sous la forme
+'Verbe-Modificateur-Nom' :
+
+Verbe - notre action
+Modificateur - la manière de faire l'action
+Nom - l'objet désigné par l'action
+
+Quelques exemples importants de 'Verbes', 'Modificateurs', et de 'Noms' :
+
+```
+ # 'Verbes'
+
+ d # Supprime
+ c # Transforme
+ y # Copie
+ v # Sélectionne
+
+ # 'Modificateurs'
+
+ i # A l'intérieur
+ a # Autour
+ NB # Nombre
+ f # Cherche quelque chose et se déplace dessus
+ t # Cherche quelque chose et se déplace juste avant
+ / # Cherche une chaîne de caractères après le curseur
+ ? # Cherche une chaîne de caractères avant le curseur
+
+ # 'Noms'
+
+ w # Mot
+ s # Phrase
+ p # Paragraphe
+ b # Bloc
+
+ # Exemple de 'phrases' ou commandes
+
+ d2w # Supprime 2 mots
+ cis # Transforme l'intérieur de la phrase
+ yip # Copie l'intérieur du paragraphe
+ ct< # Transforme le texte du curseur jusqu'au caractère avant le <
+ d$ # Supprime jusqu'à la fin de la ligne
+```
+
+## Quelques raccourcis et astuces
+
+```
+ > # Indente la sélection d'un bloc
+ < # Dé-indente la sélection d'un bloc
+ :earlier 15m # Retrouve le document comme il était il y a 15 minutes
+ :later 15m # Inverse la commande précédente
+ ddp # Echange la position de deux lignes consécutives (dd puis p)
+ . # Répète la dernière action effectuée
+```
+
+## Macros
+
+Les macros sont des actions enregistrables.
+Quand on commence à enregistrer une macro, Vim enregistre **toutes** les actions
+et les commandes que vous utilisez, jusqu'à ce que vous arrêtiez d'enregistrer.
+Lorsque vous appelez une macro, elle applique exactement les mêmes actions et
+commandes sur le texte sélectionné.
+
+```
+ qa # Commence l'enregistrement de la macro 'a'
+ q # Arrête l'enregistrement
+ @a # Appelle la macro 'a'
+```
+
+### Configuration de ~/.vimrc
+
+Le fichier .vimrc est utilisé pour configurer Vim lors du démarrage.
+
+Voici un exemple de fichier ~/.vimrc :
+
+```
+" Exemple de ~/.vimrc
+" 2015.10
+
+" Nécessaire à Vim pour être 'iMproved'
+set nocompatible
+
+" Détermine l'extension du fichier à partir du nom pour permettre une indentation
+" automatique intelligente, etc.
+filetype indent plugin on
+
+" Active la coloration syntaxique
+syntax on
+
+" Une meilleure complétion de la ligne de commande
+set wildmenu
+
+" Utilise une recherche insensible à la case sauf quand on utilise des majuscules
+set ignorecase
+set smartcase
+
+" Quand on commence une nouvelle ligne et qu'aucun type d'indentation n'est activé
+" on utilise la même indentation que sur la ligne précédente
+set autoindent
+
+" Affiche le numéro de la ligne sur la gauche de l'écran
+set number
+
+" Options d'indentation, à changer en fonction des préférences personnelles
+
+" Nombre d'espaces visuels par tabulation
+set tabstop=4
+
+" Nombre d'espaces par tabulation
+set softtabstop=4
+
+" Nombre d'espaces indentés avec les opérations d'indentations (>> et <<)
+set shiftwidth=4
+
+" Convertis les tabulations en espaces
+set expandtab
+
+" Active des tabulations et des espaces intelligents pour l'indentation et l'alignement
+set smarttab
+```
+
+### Références
+
+[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/fsharp.html.markdown b/fsharp.html.markdown
index 69f4eb60..bbf477ba 100644
--- a/fsharp.html.markdown
+++ b/fsharp.html.markdown
@@ -408,11 +408,14 @@ module ActivePatternExamples =
// "banana clips" are the syntax for active patterns
+ // You can use "elif" instead of "else if" in conditional expressions.
+ // They are equivalent in F#
+
// for example, define an "active" pattern to match character types...
let (|Digit|Letter|Whitespace|Other|) ch =
if System.Char.IsDigit(ch) then Digit
- else if System.Char.IsLetter(ch) then Letter
- else if System.Char.IsWhiteSpace(ch) then Whitespace
+ elif System.Char.IsLetter(ch) then Letter
+ elif System.Char.IsWhiteSpace(ch) then Whitespace
else Other
// ... and then use it to make parsing logic much clearer
diff --git a/go.html.markdown b/go.html.markdown
index 7b007bab..f097caeb 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -11,6 +11,7 @@ contributors:
- ["Jose Donizetti", "https://github.com/josedonizetti"]
- ["Alexej Friesen", "https://github.com/heyalexej"]
- ["Clayton Walker", "https://github.com/cwalk"]
+ - ["Leonid Shevtsov", "https://github.com/leonid-shevtsov"]
---
Go was created out of the need to get work done. It's not the latest trend
@@ -39,6 +40,7 @@ import (
"io/ioutil" // Implements some I/O utility functions.
m "math" // Math library with local alias m.
"net/http" // Yes, a web server!
+ "os" // OS functions like working with the file system
"strconv" // String conversions.
)
@@ -133,6 +135,14 @@ can include line breaks.` // Same string type.
// Unused variables are an error in Go.
// The underscore lets you "use" a variable but discard its value.
_, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs
+ // Usually you use it to ignore one of the return values of a function
+ // For example, in a quick and dirty script you might ignore the
+ // error value returned from os.Create, and expect that the file
+ // will always be created.
+ file, _ := os.Create("output.txt")
+ fmt.Fprint(file, "This is how you write to a file, by the way")
+ file.Close()
+
// Output of course counts as using a variable.
fmt.Println(s, c, a4, s3, d2, m)
@@ -211,6 +221,10 @@ func learnFlowControl() {
// for each pair in the map, print key and value
fmt.Printf("key=%s, value=%d\n", key, value)
}
+ // If you only need the value, use the underscore as the key
+ for _, name := range []string{"Bob", "Bill", "Joe"} {
+ fmt.Printf("Hello, %s\n", name)
+ }
// As with for, := in an if statement means to declare and assign
// y first, then test y > x.
diff --git a/html.html.markdown b/html.html.markdown
index 904fa5c2..b64cec33 100644
--- a/html.html.markdown
+++ b/html.html.markdown
@@ -8,7 +8,7 @@ translators:
---
HTML stands for HyperText Markup Language.
-It is a language which use to write pages for the world wide web.
+It is a language which allows us to write pages for the world wide web.
It is a markup language, it enables us to write to write webpages using code to indicate how text and data should be displayed.
In fact, html files are simple text files.
What is this markup? It is a method of organising the page's data by surrounding it with opening tags and closing tags.
diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown
index 92ebc165..4af30176 100644
--- a/it-it/c++-it.html.markdown
+++ b/it-it/c++-it.html.markdown
@@ -8,6 +8,7 @@ contributors:
- ["Connor Waters", "http://github.com/connorwaters"]
translators:
- ["Robert Margelli", "http://github.com/sinkswim/"]
+ - ["Tommaso Pifferi", "http://github.com/neslinesli93/"]
lang: it-it
---
@@ -151,7 +152,7 @@ namespace Primo {
namespace Secondo {
void foo()
{
- printf("Questa è Secondo::foo\n")
+ printf("Questa è Secondo::foo\n");
}
}
@@ -805,6 +806,94 @@ void faiQualcosaConUnFile(const std::string& nomefile)
// sono tutti automaticamente distrutti con i loro contenuti quando escono dalla visibilità.
// - I mutex usano lock_guard e unique_lock
+// I contenitori che utilizzano chiavi non-primitive (classi personalizzate)
+// richiedono la funzione di confronto nell'oggetto stesso, o tramite un puntatore a funzione.
+// Le chiavi primitive hanno funzioni di confronto già definite, ma puoi sovrascriverle.
+class Foo {
+public:
+ int j;
+ Foo(int a) : j(a) {}
+};
+struct funzioneDiConfronto {
+ bool operator()(const Foo& a, const Foo& b) const {
+ return a.j < b.j;
+ }
+};
+// Questo non è permesso, anche se qualche compilatore potrebbe non dare problemi
+//std::map<Foo, int> fooMap;
+std::map<Foo, int, funzioneDiConfronto> fooMap;
+fooMap[Foo(1)] = 1;
+fooMap.find(Foo(1)); -- vero
+
+///////////////////////////////////////
+// Espressioni Lambda (C++11 e superiori)
+///////////////////////////////////////
+
+// Le espressioni lambda (più semplicemente "lambda") sono utilizzate
+// per definire una funzione anonima nel punto in cui viene invocata, o
+// dove viene passata come argomento ad una funzione
+
+// Ad esempio, consideriamo l'ordinamento di un vettore costituito da una
+// coppia di interi, utilizzando il secondo elemento per confrontare
+vector<pair<int, int> > tester;
+tester.push_back(make_pair(3, 6));
+tester.push_back(make_pair(1, 9));
+tester.push_back(make_pair(5, 0));
+
+// Passiamo una lambda come terzo argomento alla funzione di ordinamento
+// `sort` è contenuta nell'header <algorithm>
+sort(tester.begin(), tester.end(), [](const pair<int, int>& lhs, const pair<int, int>& rhs) {
+ return lhs.second < rhs.second;
+});
+
+// Nota bene la sintassi utilizzata nelle lambda:
+// [] serve per "catturare" le variabili.
+// La "Lista di Cattura" definisce tutte le variabili esterne che devono essere disponibili
+// all'interno della funzione, e in che modo.
+// La lista può contenere:
+// 1. un valore: [x]
+// 2. un riferimento: [&x]
+// 3. qualunque variabile nello scope corrente, per riferimento [&]
+// 4. qualunque variabile nello scope corrente, per valore [=]
+// Esempio:
+
+vector<int> id_cani;
+// numero_cani = 3;
+for(int i = 0; i < 3; i++) {
+ id_cani.push_back(i);
+}
+
+int pesi[3] = {30, 50, 10};
+
+// Mettiamo che vuoi ordinare id_cani in base al peso dei cani
+// Alla fine, id_cani sarà: [2, 0, 1]
+
+// Le lambda vengono in aiuto
+
+sort(id_cani.begin(), id_cani.end(), [&pesi](const int &lhs, const int &rhs) {
+ return pesi[lhs] < pesi[rhs];
+});
+// Nota come abbiamo catturato "pesi" per riferimento nell'esempio.
+// Altre informazioni sulle lambda in C++: http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11
+
+///////////////////////////////
+// Ciclo For semplificato(C++11 e superiori)
+///////////////////////////////
+
+// Puoi usare un ciclo for per iterare su un tipo di dato contenitore
+int arr[] = {1, 10, 3};
+
+for(int elem: arr) {
+ cout << elem << endl;
+}
+
+// Puoi usare "auto" senza preoccuparti del tipo degli elementi nel contenitore
+// Ad esempio:
+
+for(auto elem: arr) {
+ // Fai qualcosa con `elem`
+}
+
///////////////////////
// Roba divertente
//////////////////////
@@ -855,20 +944,188 @@ Foo f1;
f1 = f2;
-// Come deallocare realmente le risorse all'interno di un vettore:
-class Foo { ... };
-vector<Foo> v;
-for (int i = 0; i < 10; ++i)
- v.push_back(Foo());
+///////////////////////////////////////
+// Tuple (C++11 e superiori)
+///////////////////////////////////////
+
+#include<tuple>
+
+// Concettualmente le tuple sono simili alle strutture del C, ma invece di avere
+// i membri rappresentati con dei nomi, l'accesso agli elementi avviene tramite
+// il loro ordine all'interno della tupla.
+
+// Cominciamo costruendo una tupla.
+// Inserire i valori in una tupla
+auto prima = make_tuple(10, 'A');
+const int maxN = 1e9;
+const int maxL = 15;
+auto seconda = make_tuple(maxN, maxL);
+
+// Vediamo gli elementi contenuti nella tupla "prima"
+cout << get<0>(prima) << " " << get<1>(prima) << "\n"; // stampa : 10 A
+
+// Vediamo gli elementi contenuti nella tupla "seconda"
+cout << get<0>(seconda) << " " << get<1>(seconda) << "\n"; // stampa: 1000000000 15
+
+// Estrarre i valori dalla tupla, salvandoli nelle variabili
+int primo_intero;
+char primo_char;
+tie(primo_intero, primo_char) = prima;
+cout << primo_intero << " " << primo_char << "\n"; // stampa : 10 A
+
+// E' possibile creare tuple anche in questo modo
+tuple<int, char, double> terza(11, 'A', 3.14141);
+
+// tuple_size ritorna il numero di elementi in una tupla (come constexpr)
+cout << tuple_size<decltype(terza)>::value << "\n"; // stampa: 3
+
+// tuple_cat concatena gli elementi di tutte le tuple, nell'esatto ordine
+// in cui sono posizionati all'interno delle tuple stesse
+auto tupla_concatenata = tuple_cat(prima, seconda, terza);
+// tupla_concatenata diventa = (10, 'A', 1e9, 15, 11, 'A' ,3.14141)
+
+cout << get<0>(tupla_concatenata) << "\n"; // stampa: 10
+cout << get<3>(tupla_concatenata) << "\n"; // stampa: 15
+cout << get<5>(tupla_concatenata) << "\n"; // stampa: 'A'
+
+
+/////////////////////
+// Contenitori
+/////////////////////
+
+// I Contenitori della "Standard Template Library", ovvero la libreria standard
+// dei template contenuti nel C++, sono template predefiniti.
+// I Contenitori si occupano di come allocare lo spazio per gli elementi contenuti,
+// e forniscono funzioni per accedervi e manipolarli
+
+// Vediamo alcuni tipi di contenitori:
+
+// Vector (array dinamici/vettori)
+// Permettono di definire un vettore, o una lista di oggetti, a runtime
+#include<vector>
+vector<Tipo_Dato> nome_vettore; // usato per inizializzare un vettore
+cin >> val;
+nome_vettore.push_back(val); // inserisce il valore di "val" nel vettore
+
+// Per iterare in un vettore, abbiamo due possibilità:
+// Ciclo normale
+for(int i=0; i<nome_vettore.size(); i++)
+// Cicla dall'indice zero fino all'ultimo
+
+// Iteratore
+vector<Tipo_Dato>::iterator it; // inizializza l'iteratore per il vettore
+for(it=nome_vettore.begin(); it!=nome_vettore.end();++it)
+// Nota che adesso non cicla più sugli indici, ma direttamente sugli elementi!
+
+// Per accedere agli elementi del vettore
+// Operatore []
+var = nome_vettore[indice]; // Assegna a "var" il valore del vettore all'indice dato
+
+
+// Set (insiemi)
+// Gli insiemi sono contenitori che memorizzano elementi secondo uno specifico ordine.
+// Gli insiemi vengono per lo più utilizzati per memorizzare valori unici, secondo
+// un ordine, senza scrivere ulteriore codice.
+
+#include<set>
+set<int> insieme; // Inizializza un insieme di interi
+insieme.insert(30); // Inserisce il valore 30 nell'insieme
+insieme.insert(10); // Inserisce il valore 10 nell'insieme
+insieme.insert(20); // Inserisce il valore 20 nell'insieme
+insieme.insert(30); // Inserisce il valore 30 nell'insieme
+// Gli elementi dell'insieme sono:
+// 10 20 30
+
+// Per cancellare un elemento
+insieme.erase(20); // Cancella l'elemento con valore 20
+// L'insieme contiene adesso: 10 30
+
+// Per iterare su un insieme, usiamo gli iteratori
+set<int>::iterator it;
+for(it=insieme.begin();it<insieme.end();it++) {
+ cout << *it << endl;
+}
+// Stampa:
+// 10
+// 30
+
+// Per svuotare il contenitore usiamo il metodo "clear"
+insieme.clear();
+cout << insieme.size();
+// Stampa: 0
+
+// Nota: per permettere elementi duplicati, possiamo usare "multiset"
+
+// Map (mappa/tabella di hash)
+// Le mappe servono per memorizzare un elemento, detto chiave, a cui viene
+// associato un valore, il tutto secondo uno specifico ordine.
+
+#include<map>
+map<char, int> mia_mappa; // Inizializza una mappa che usa i char come chiave, e gli interi come valore
+
+mia_mappa.insert(pair<char,int>('A',1));
+// Inserisce il valore 1 per la chiave A
+mia_mappa.insert(pair<char,int>('Z',26));
+// Inserisce il valore 26 per la chiave Z
+
+// Per iterare
+map<char,int>::iterator it;
+for (it=mia_mappa.begin(); it!=mia_mappa.end(); ++it)
+ std::cout << it->first << "->" << it->second << '\n';
+// Stampa:
+// A->1
+// Z->26
+
+// Per trovare il valore corrispondente ad una data chiave
+it = mia_mappa.find('Z');
+cout << it->second;
+// Stampa: 26
+
+
+///////////////////////////////////
+// Operatori logici e bitwise(bit-a-bit)
+//////////////////////////////////
+
+// La maggior parte di questi operatori in C++ sono gli stessi degli altri linguaggi
+
+// Operatori logici
+
+// Il C++ usa la "Short-circuit evaluation" per le espressioni booleane. Cosa significa?
+// In pratica, in una condizione con due argomenti, il secondo viene considerato solo se
+// il primo non basta a determinate il valore finale dell'espresione.
+
+true && false // Effettua il **and logico** e ritorna falso
+true || false // Effettua il **or logico** e ritorna vero
+! true // Effettua il **not logico** e ritorna falso
+
+// Invece di usare i simboli, si possono usare le keyword equivalenti
+true and false // Effettua il **and logico** e ritorna falso
+true or false // Effettua il **or logico** e ritorna vero
+not true // Effettua il **not logico** e ritorna falso
+
+// Operatori bitwise(bit-a-bit)
+
+// **<<** Operatore di Shift a Sinistra
+// << sposta i bit a sinistra
+4 << 1 // Sposta a sinistra di 1 i bit di 4, ottenendo 8
+// x << n in pratica realizza x * 2^n
+
+
+// **>>** Operatore di Shift a Destra
+// >> sposta i bit a destra
+4 >> 1 // Sposta a destra di 1 i bit di 4, ottenendo 2
+// x >> n in pratica realizza x / 2^n
-// La riga seguente riduce la dimensione di v a 0, ma il distruttore non
-// viene chiamato e dunque le risorse non sono deallocate!
-v.empty();
-v.push_back(Foo()); // Il nuovo valore viene copiato nel primo Foo che abbiamo inserito
+~4 // Effettua il NOT bit-a-bit
+4 | 3 // Effettua il OR bit-a-bit
+4 & 3 // Effettua il AND bit-a-bit
+4 ^ 3 // Effettua il XOR bit-a-bit
-// Distrugge realmente tutti i valori dentro v. Vedi la sezione riguardante gli
-// oggetti temporanei per capire come mai funziona così.
-v.swap(vector<Foo>());
+// Le keyword equivalenti sono
+compl 4 // Effettua il NOT bit-a-bit
+4 bitor 3 // Effettua il OR bit-a-bit
+4 bitand 3 // Effettua il AND bit-a-bit
+4 xor 3 // Effettua il XOR bit-a-bit
```
Letture consigliate:
diff --git a/it-it/python-it.html.markdown b/it-it/python-it.html.markdown
index 3a4099e7..71f6dc1c 100644
--- a/it-it/python-it.html.markdown
+++ b/it-it/python-it.html.markdown
@@ -4,9 +4,11 @@ contributors:
- ["Louie Dinh", "http://ldinh.ca"]
- ["Amin Bandali", "http://aminbandali.com"]
- ["Andre Polykanine", "https://github.com/Oire"]
+ - ["evuez", "http://github.com/evuez"]
filename: learnpython.py
translators:
- ["Ale46", "http://github.com/Ale46/"]
+ - ["Tommaso Pifferi", "http://github.com/neslinesli93/"]
lang: it-it
---
Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari
@@ -15,8 +17,15 @@ pseudocodice eseguibile.
Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service]
-Nota: Questo articolo è valido solamente per Python 2.7, ma dovrebbe andar bene anche per
-Python 2.x. Per Python 3.x, dai un'occhiata a [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
+Nota: questo articolo è riferito a Python 2.7 in modo specifico, ma dovrebbe andar
+bene anche per Python 2.x. Python 2.7 sta raggiungendo il "fine vita", ovvero non sarà
+più supportato nel 2020. Quindi è consigliato imparare Python utilizzando Python 3.
+Per maggiori informazioni su Python 3.x, dai un'occhiata al [tutorial di Python 3](http://learnxinyminutes.com/docs/python3/).
+
+E' possibile anche scrivere codice compatibile sia con Python 2.7 che con Python 3.x,
+utilizzando [il modulo `__future__`](https://docs.python.org/2/library/__future__.html) di Python.
+Il modulo `__future__` permette di scrivere codice in Python 3, che può essere eseguito
+utilizzando Python 2: cosa aspetti a vedere il tutorial di Python 3?
```python
@@ -54,6 +63,12 @@ Python 2.x. Per Python 3.x, dai un'occhiata a [Python 3 tutorial](http://learnxi
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
+# E' possibile importare il modulo "division" (vedi la sezione 6 di questa guida, Moduli)
+# per effettuare la divisione normale usando solo '/'.
+from __future__ import division
+11/4 # => 2.75 ...divisione normale
+11//4 # => 2 ...divisione troncata
+
# Operazione Modulo
7 % 3 # => 1
@@ -112,11 +127,19 @@ not False # => True
# Una stringa può essere considerata come una lista di caratteri
"Questa è una stringa"[0] # => 'Q'
-# % può essere usato per formattare le stringhe, in questo modo:
-"%s possono essere %s" % ("le stringhe", "interpolate")
+# Per sapere la lunghezza di una stringa
+len("Questa è una stringa") # => 20
+
+# Formattazione delle stringhe con %
+# Anche se l'operatore % per le stringe sarà deprecato con Python 3.1, e verrà rimosso
+# successivamente, può comunque essere utile sapere come funziona
+x = 'mela'
+y = 'limone'
+z = "La cesta contiene una %s e un %s" % (x,y)
# Un nuovo modo per fomattare le stringhe è il metodo format.
# Questo metodo è quello consigliato
+"{} è un {}".format("Questo", "test")
"{0} possono essere {1}".format("le stringhe", "formattate")
# Puoi usare delle parole chiave se non vuoi contare
"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="lasagna")
@@ -132,9 +155,17 @@ None is None # => True
# L'operatore 'is' testa l'identità di un oggetto. Questo non è
# molto utile quando non hai a che fare con valori primitivi, ma lo è
# quando hai a che fare con oggetti.
-
-# None, 0, e stringhe/liste vuote sono tutte considerate a False.
-# Tutti gli altri valori sono True
+
+# Qualunque oggetto può essere usato nei test booleani
+# I seguenti valori sono considerati falsi:
+# - None
+# - Lo zero, come qualunque tipo numerico (quindi 0, 0L, 0.0, 0.j)
+# - Sequenze vuote (come '', (), [])
+# - Contenitori vuoti (tipo {}, set())
+# - Istanze di classi definite dall'utente, che soddisfano certi criteri
+# vedi: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
+#
+# Tutti gli altri valori sono considerati veri: la funzione bool() usata su di loro, ritorna True.
bool(0) # => False
bool("") # => False
@@ -144,7 +175,13 @@ bool("") # => False
####################################################
# Python ha una funzione di stampa
-print "Sono Python. Piacere di conoscerti!"
+print "Sono Python. Piacere di conoscerti!" # => Sono Python. Piacere di conoscerti!
+
+# Un modo semplice per ricevere dati in input dalla riga di comando
+variabile_stringa_input = raw_input("Inserisci del testo: ") # Ritorna i dati letti come stringa
+variabile_input = input("Inserisci del testo: ") # Interpreta i dati letti come codice python
+# Attenzione: bisogna stare attenti quando si usa input()
+# Nota: In python 3, input() è deprecato, e raw_input() si chiama input()
# Non c'è bisogno di dichiarare una variabile per assegnarle un valore
una_variabile = 5 # Convenzionalmente si usa caratteri_minuscoli_con_underscores
@@ -155,6 +192,7 @@ una_variabile # => 5
un_altra_variabile # Genera un errore di nome
# if può essere usato come un'espressione
+# E' l'equivalente dell'operatore ternario in C
"yahoo!" if 3 > 2 else 2 # => "yahoo!"
# Liste immagazzinano sequenze
@@ -207,6 +245,17 @@ li + altra_li # => [1, 2, 3, 4, 5, 6]
# Concatena liste con "extend()"
li.extend(altra_li) # Ora li è [1, 2, 3, 4, 5, 6]
+# Rimuove la prima occorrenza di un elemento
+li.remove(2) # Ora li è [1, 3, 4, 5, 6]
+li.remove(2) # Emette un ValueError, poichè 2 non è contenuto nella lista
+
+# Inserisce un elemento all'indice specificato
+li.insert(1, 2) # li è di nuovo [1, 2, 3, 4, 5, 6]
+
+# Ritorna l'indice della prima occorrenza dell'elemento fornito
+li.index(2) # => 1
+li.index(7) # Emette un ValueError, poichè 7 non è contenuto nella lista
+
# Controlla l'esistenza di un valore in una lista con "in"
1 in li # => True
@@ -227,8 +276,9 @@ tup[:2] # => (1, 2)
# Puoi scompattare le tuple (o liste) in variabili
a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 and c è ora 3
+d, e, f = 4, 5, 6 # puoi anche omettere le parentesi
# Le tuple sono create di default se non usi le parentesi
-d, e, f = 4, 5, 6
+g = 4, 5, 6 # => (4, 5, 6)
# Guarda come è facile scambiare due valori
e, d = d, e # d è ora 5 ed e è ora 4
@@ -250,6 +300,9 @@ filled_dict.keys() # => ["tre", "due", "uno"]
filled_dict.values() # => [3, 2, 1]
# Nota - Come sopra riguardo l'ordinamento delle chiavi.
+# Ottieni tutte le coppie chiave-valore, sotto forma di lista di tuple, utilizzando "items()"
+filled_dicts.items() # => [("uno", 1), ("due", 2), ("tre", 3)]
+
# Controlla l'esistenza delle chiavi in un dizionario con "in"
"uno" in filled_dict # => True
1 in filled_dict # => False
@@ -298,6 +351,15 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# Fai differenze su set con -
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+# Effettua la differenza simmetrica con ^
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# Controlla se il set a sinistra contiene quello a destra
+{1, 2} >= {1, 2, 3} # => False
+
+# Controlla se il set a sinistra è un sottoinsieme di quello a destra
+{1, 2} <= {1, 2, 3} # => True
+
# Controlla l'esistenza in un set con in
2 in filled_set # => True
10 in filled_set # => False
@@ -405,7 +467,7 @@ aggiungi(y=6, x=5) # Le parole chiave come argomenti possono arrivare in ogni
# Puoi definire funzioni che accettano un numero variabile di argomenti posizionali
-# che verranno interpretati come tuple se non usi il *
+# che verranno interpretati come tuple usando il *
def varargs(*args):
return args
@@ -413,7 +475,7 @@ varargs(1, 2, 3) # => (1, 2, 3)
# Puoi definire funzioni che accettano un numero variabile di parole chiave
-# come argomento, che saranno interpretati come un dizionario se non usi **
+# come argomento, che saranno interpretati come un dizionario usando **
def keyword_args(**kwargs):
return kwargs
@@ -449,19 +511,19 @@ def pass_all_the_args(*args, **kwargs):
# Funzioni Scope
x = 5
-def setX(num):
+def set_x(num):
# La variabile locale x non è uguale alla variabile globale x
x = num # => 43
print x # => 43
-def setGlobalX(num):
+def set_global_x(num):
global x
print x # => 5
x = num # la variabile globable x è ora 6
print x # => 6
-setX(43)
-setGlobalX(6)
+set_x(43)
+set_global_x(6)
# Python ha funzioni di prima classe
def create_adder(x):
@@ -474,15 +536,22 @@ add_10(3) # => 13
# Ci sono anche funzioni anonime
(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
# Esse sono incluse in funzioni di alto livello
map(add_10, [1, 2, 3]) # => [11, 12, 13]
+map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
+
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
# Possiamo usare la comprensione delle liste per mappe e filtri
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
+# Puoi fare anche la comprensione di set e dizionari
+{x for x in 'abcddeef' if x in 'abc'} # => {'d', 'e', 'f'}
+{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
+
####################################################
## 5. Classi
@@ -502,6 +571,9 @@ class Human(object):
# Assegna l'argomento all'attributo name dell'istanza
self.name = name
+ # Inizializza una proprietà
+ self.age = 0
+
# Un metodo dell'istanza. Tutti i metodi prendo "self" come primo argomento
def say(self, msg):
return "{0}: {1}".format(self.name, msg)
@@ -517,6 +589,21 @@ class Human(object):
def grunt():
return "*grunt*"
+ # Una proprietà è come un metodo getter.
+ # Trasforma il metodo age() in un attributo in sola lettura, che ha lo stesso nome
+ @property
+ def age(self):
+ return self._age
+
+ # Questo metodo permette di modificare la proprietà
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # Questo metodo permette di cancellare la proprietà
+ @age.deleter
+ def age(self):
+ del self._age
# Instanziare una classe
i = Human(name="Ian")
@@ -536,6 +623,16 @@ j.get_species() # => "H. neanderthalensis"
# Chiamare il metodo condiviso
Human.grunt() # => "*grunt*"
+# Aggiorna la proprietà
+i.age = 42
+
+# Ritorna il valore della proprietà
+i.age # => 42
+
+# Cancella la proprietà
+del i.age
+i.age # => Emette un AttributeError
+
####################################################
## 6. Moduli
@@ -570,34 +667,67 @@ math.sqrt == m.sqrt == sqrt # => True
import math
dir(math)
+# Se nella cartella corrente hai uno script chiamato math.py,
+# Python caricherà quello invece del modulo math.
+# Questo succede perchè la cartella corrente ha priorità
+# sulle librerie standard di Python
+
####################################################
## 7. Avanzate
####################################################
-# I generatori ti aiutano a fare codice pigro
+# Generatori
+# Un generatore appunto "genera" valori solo quando vengono richiesti,
+# invece di memorizzarli tutti subito fin dall'inizio
+
+# Il metodo seguente (che NON è un generatore) raddoppia tutti i valori e li memorizza
+# dentro `double_arr`. Se gli oggetti iterabili sono grandi, il vettore risultato
+# potrebbe diventare enorme!
def double_numbers(iterable):
+ double_arr = []
+ for i in iterable:
+ double_arr.append(i + i)
+
+# Eseguendo il seguente codice, noi andiamo a raddoppiare prima tutti i valori, e poi
+# li ritorniamo tutti e andiamo a controllare la condizione
+for value in double_numbers(range(1000000)): # `test_senza_generatore`
+ print value
+ if value > 5:
+ break
+
+# Invece, potremmo usare un generatore per "generare" il valore raddoppiato non
+# appena viene richiesto
+def double_numbers_generator(iterable):
for i in iterable:
yield i + i
-# Un generatore crea valori al volo.
-# Invece di generare e ritornare tutti i valori in una volta ne crea uno in ciascuna
-# iterazione. Ciò significa che i valori più grandi di 15 non saranno considerati in
-# double_numbers.
-# Nota xrange è un generatore che fa la stessa cosa di range.
-# Creare una lista 1-900000000 occuperebbe molto tempo e spazio.
-# xrange crea un oggetto generatore xrange invece di creare l'intera lista
-# come fa range.
-# Usiamo un underscore finale nel nome delle variabile quando vogliamo usare un nome
-# che normalmente colliderebbe con una parola chiave di python
-xrange_ = xrange(1, 900000000)
-
-# raddoppierà tutti i numeri fino a che result >=30 non sarà trovato
-for i in double_numbers(xrange_):
- print i
- if i >= 30:
+# Utilizzando lo stesso test di prima, stavolta però con un generatore, ci permette
+# di iterare sui valori e raddoppiarli uno alla volta, non appena vengono richiesti dalla
+# logica del programma. Per questo, non appena troviamo un valore > 5, usciamo dal ciclo senza
+# bisogno di raddoppiare la maggior parte dei valori del range (MOLTO PIU VELOCE!)
+for value in double_numbers_generator(xrange(1000000)): # `test_generatore`
+ print value
+ if value > 5:
break
+# Nota: hai notato l'uso di `range` in `test_senza_generatore` e `xrange` in `test_generatore`?
+# Proprio come `double_numbers_generator` è la versione col generatore di `double_numbers`
+# Abbiamo `xrange` come versione col generatore di `range`
+# `range` ritorna un array di 1000000 elementi
+# `xrange` invece genera 1000000 valori quando lo richiediamo/iteriamo su di essi
+
+# Allo stesso modo della comprensione delle liste, puoi creare la comprensione
+# dei generatori.
+values = (-x for x in [1,2,3,4,5])
+for x in values:
+ print(x) # stampa -1 -2 -3 -4 -5
+
+# Puoi anche fare il cast diretto di una comprensione di generatori ad una lista.
+values = (-x for x in [1,2,3,4,5])
+gen_to_list = list(values)
+print(gen_to_list) # => [-1, -2, -3, -4, -5]
+
# Decoratori
# in questo esempio beg include say
@@ -605,7 +735,6 @@ for i in double_numbers(xrange_):
# ritornato
from functools import wraps
-
def beg(target_function):
@wraps(target_function)
def wrapper(*args, **kwargs):
@@ -634,11 +763,13 @@ print say(say_please=True) # Puoi comprarmi una birra? Per favore! Sono povero
* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/)
-* [The Official Docs](http://docs.python.org/2.6/)
+* [The Official Docs](http://docs.python.org/2/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
* [Python Module of the Week](http://pymotw.com/2/)
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+* [LearnPython](http://www.learnpython.org/)
+* [Fullstack Python](https://www.fullstackpython.com/)
### Libri cartacei
diff --git a/ja-jp/python3-jp.html.markdown b/ja-jp/python3-jp.html.markdown
new file mode 100644
index 00000000..3b1a0d73
--- /dev/null
+++ b/ja-jp/python3-jp.html.markdown
@@ -0,0 +1,898 @@
+---
+language: python3
+contributors:
+ - ["Louie Dinh", "http://pythonpracticeprojects.com"]
+ - ["Steven Basart", "http://github.com/xksteven"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+ - ["Zachary Ferguson", "http://github.com/zfergus2"]
+ - ["evuez", "http://github.com/evuez"]
+translators:
+ - ["kakakaya", "https://github.com/kakakaya"]
+filename: learnpython3-jp.py
+lang: ja-jp
+---
+
+90年代の初め、Guido Van RossumによってPythonは作成されました。現在となっては、最も有名な言語の1つです。
+私は構文の明快さによって、Pythonと恋に落ちました。
+以下は基本的に実行可能な疑似コードです。
+
+フィードバッグは大歓迎です! [@louiedinh](http://twitter.com/louiedinh) または louiedinh [at] [google's email service] にご連絡下さい!
+
+Note: この記事はPython 3に内容を絞っています。もし古いPython 2.7を学習したいなら、 [こちら](http://learnxinyminutes.com/docs/python/) をご確認下さい。
+
+```python
+
+# 1行のコメントは番号記号(#)から始まります。
+
+""" 複数行の文字は、"を3つ繋げることで
+ 書くことができます。
+ また、これはコメントとしてもよく使われます。
+"""
+
+####################################################
+# 1. プリミティブ型と演算子
+####################################################
+
+# 数字です
+3 # => 3
+
+# 四則演算はあなたの期待通りに動きます。
+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.0 // 3.0 # => -2.0
+
+# 除算の結果は常に浮動小数点になります。
+10.0 / 3 # => 3.3333333333333335
+
+# 剰余の計算
+7 % 3 # => 1
+
+# 冪乗 (x**y, x の y 乗)
+2**4 # => 16
+
+# 括弧により、計算の順番を優先させられます。
+(1 + 3) * 2 # => 8
+
+# 真偽値はプリミティブ型です(大文字から始まっていることに注意!)
+True
+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
+
+# 値が等しいか確認するには ==
+1 == 1 # => True
+2 == 1 # => False
+
+# 値が等しくないか確認するには !=
+1 != 1 # => False
+2 != 1 # => True
+
+# 他の比較方法
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
+
+# 比較は連結させられます!
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
+
+# (is vs. ==)
+# "is" は、2つの変数が同一のオブジェクトを参照しているか確認します。
+# 一方 "==" は、それぞれが参照する2つのオブジェクトが同じ値を持つか確認します。
+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 が参照するオブジェクトの値は等しいです。
+
+# " または ' を使って文字列を作成します。
+"This is a string."
+'This is also a string.'
+
+# 文字列も加算をすることができます!でも、あまり行わないように。
+"Hello " + "world!" # => "Hello world!"
+# '+' を使わなくても連結はできます。
+"Hello " "world!" # => "Hello world!"
+
+# 文字列は文字のリストであるかのように扱うことができます。
+"This is a string"[0] # => 'T'
+
+# 文字列の長さを得るにはこのようにします。
+len("This is a string") # => 16
+
+# .format で文字列のフォーマットを行えます
+"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated"
+
+# 入力を減らすために、フォーマットするときに引数を繰り返し使うことができます。
+"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
+# => "Jack be nimble, Jack be quick, Jack jump over the candle stick"
+
+# 引数の順番を数えるのがお嫌い?キーワード引数をどうぞ。
+"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna"
+
+# もし Python 3 のコードを Python 2.5以下でも使う必要があるなら、
+# 旧式のフォーマット方法を使うこともできます。
+"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way"
+
+
+# None はオブジェクトです(大文字からです!)
+None # => None
+
+# オブジェクトがNoneであるか確認するのに "==" 演算子を使わないように。
+# 代わりに "is" を使いましょう。オブジェクトの素性を確認できます。
+"etc" is None # => False
+None is None # => True
+
+# None や 0 、空の 文字列/リスト/辞書/タプル は全て False として評価されます。
+# 他の全ての値は True になります。
+bool(0) # => False
+bool("") # => False
+bool([]) # => False
+bool({}) # => False
+bool(()) # => False
+
+####################################################
+# 2. Variables and Collections
+####################################################
+
+# Python にはprint関数があります。
+print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you!
+
+# 標準では、print関数は最後に改行を出力します。
+# この動作を変更するためには、オプション引数を利用します。
+print("Hello, World", end="!") # => Hello, World!
+
+# コンソールから入力を得るための簡単な例
+input_string_var = input("Enter some data: ") # 入力を文字列として返します
+# Note: Python の初期のバージョンでは、 input() は raw_input() という名前で存在します。
+
+# 変数に代入する前に宣言する必要はありません。
+# 慣例的に、小文字でアンダースコア区切り ( lower_case_with_underscores ) の変数が使われます。
+some_var = 5
+some_var # => 5
+
+# 代入されていない変数へのアクセスは例外を引き起こします。
+# 例外の取り扱いについては、3章の制御の流れをご確認ください。
+some_unknown_var # NameError を送出します
+
+# ifは式として使用できます。
+# C言語の「?:(三項演算子)」に対応する例:
+"yahoo!" if 3 > 2 else 2 # => "yahoo!"
+
+# リストは順序を保存します。
+li = []
+# 値の入っているリストも作成できます。
+other_li = [4, 5, 6]
+
+# append により、リストの末尾にものを入れられます。
+li.append(1) # li is now [1]
+li.append(2) # li is now [1, 2]
+li.append(4) # li is now [1, 2, 4]
+li.append(3) # li is now [1, 2, 4, 3]
+# pop でリストの末尾から取り除けます。
+li.pop() # => 3 and li is now [1, 2, 4]
+# 元に戻しましょう!
+li.append(3) # li is now [1, 2, 4, 3] again.
+
+# 配列のように、リストにアクセスできます。
+li[0] # => 1
+# 最後の要素を参照できます。
+li[-1] # => 3
+
+# 範囲外の要素を参照すると IndexError になります。
+li[4] # IndexError が発生します
+
+# スライス構文により範囲を参照できます。
+li[1:3] # => [2, 4]
+# 先端を取り除く
+li[2:] # => [4, 3]
+# 末尾を取り除く
+li[:3] # => [1, 2, 4]
+# 1つ飛ばしで選択する
+li[::2] # =>[1, 4]
+# 反転したリストを得る
+li[::-1] # => [3, 4, 2, 1]
+# これらの任意の組み合わせにより、より複雑なスライスを作ることができます。
+# li[start:end:step]
+
+# スライスにより、深いコピーを1階層分行うことができます。
+li2 = li[:] # => li2 = [1, 2, 4, 3] だが、 (li2 is li) はFalseになる。
+
+# "del"によりリストから任意の要素を削除できます。
+del li[2] # li は [1, 2, 3] になりました。
+
+# "remove"で最初に出現する要素を削除できます。
+li.remove(2) # li は [1, 3] になりました。
+li.remove(2) # 2はリストの中に存在しないので、 ValueError が発生します。
+
+# 要素を好きなところに挿入できます。
+li.insert(1, 2) # li は [1, 2, 3] に戻りました。
+
+# "index"で引数の要素が最初に出現する場所のインデックスを得られます。
+li.index(2) # => 1
+li.index(4) # 4はリストの中に存在しないので、 ValueError が発生します。
+
+# リスト同士を足すこともできます。
+# Note: li と other_li の値は変更されません。
+li + other_li # => [1, 2, 3, 4, 5, 6]
+
+# "extend()"で他のリストを連結することができます。
+li.extend(other_li) # li は [1, 2, 3, 4, 5, 6] になります。
+
+# リストの中に値が存在するか、 "in" で確認できます。
+1 in li # => True
+
+# 長さは "len()" で確認できます。
+len(li) # => 6
+
+
+# タプルはリストのようなものですが、不変であるという違いがあります。
+tup = (1, 2, 3)
+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
+
+# タプルやリストから複数の変数に代入することができます。
+a, b, c = (1, 2, 3) # a, b, c にはそれぞれ 1, 2, 3 が代入されました。
+# 拡張記法もあります。
+a, *b, c = (1, 2, 3, 4) # a は 1 、 b は [2, 3] 、c は4 になります。
+# 括弧を作成しなくてもデフォルトでタプルが作成されます。
+d, e, f = 4, 5, 6
+# 2つの変数を交換するのがどれほど簡単か見てみましょう。
+e, d = d, e # d は 5 、 e は e になります。
+
+
+# 辞書はマップ(キーと値の組み合わせ)を保存できます。
+empty_dict = {}
+# 値が入っている辞書を直接作成することもできます。
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# キーは不変の型である必要があります。
+# これは、高速化のため、キーを定数のハッシュ値に変換できるようにするためです。
+# 不変の型の例として、int、float、string、tupleなどが上げられます。
+invalid_dict = {[1, 2, 3]: "123"} # => list はハッシュ化できないので、 TypeError が発生します。
+valid_dict = {(1, 2, 3): [1, 2, 3]} # 一方、キーに対応する値はどのような型でも利用できます。
+
+# [] で 値を取り出せます。
+filled_dict["one"] # => 1
+
+# "keys()"により、全てのキーを反復可能な形式で取り出せます。
+# これをリストにするために、"list()"で囲んでいます。これについては後程解説します。
+# Note: 辞書のキーの順番は考慮されていません。実行した結果がこれと異なる場合があります。
+list(filled_dict.keys()) # => ["three", "two", "one"]
+
+# "values()"により、全ての値を反復可能な形式で取り出せます。
+# 前と同じように、これをリストにするために、"list()"で囲んでいます。
+# Note: 辞書の値の順番は考慮されていません。実行した結果がこれと異なる場合があります。
+list(filled_dict.values()) # => [3, 2, 1]
+
+
+# "in" により、辞書のキーが存在するか確認できます。
+"one" in filled_dict # => True
+1 in filled_dict # => False
+
+# 存在しないキーで辞書を参照すると KeyError になります。
+filled_dict["four"] # KeyError
+
+# "get()" メソッドを使うことで KeyError を回避できます。
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
+# get ではキーが存在しなかったときのデフォルト値を指定できます。
+filled_dict.get("one", 4) # => 1
+filled_dict.get("four", 4) # => 4
+
+# "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 # 辞書に追加する別の方法
+
+# del により辞書からキーを削除できます。
+del filled_dict["one"] # "one" キーを辞書から削除します。
+
+# Python 3.5 以降では、追加の値を取り出す方法があります。
+{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2}
+{'a': 1, **{'a': 2}} # => {'a': 2}
+
+
+# set では集合を表現できます。
+empty_set = set()
+# 集合を一連の値で初期化する例です。辞書に似ていますね?ごめんなさい。
+some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
+
+# 辞書のキーのように、集合の値は不変である必要があります。
+invalid_set = {[1], 1} # => list はハッシュ化できないので、 TypeError が送出されます。
+valid_set = {(1,), 1}
+
+# 新しい値を集合にセットできます。
+filled_set = some_set
+
+# 集合に新しい要素を追加できます。
+filled_set.add(5) # filled_set は {1, 2, 3, 4, 5} になりました。
+
+# & により、集合同士の共通部分が得られます。
+other_set = {3, 4, 5, 6}
+filled_set & other_set # => {3, 4, 5}
+
+# | により、集合同士の合併が得られます。
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+
+# - により、集合同士の差集合が得られます。
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+
+# ^ により、集合同士の対象差が得られます。
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# 左の集合が右の集合の上位集合であるか確認。
+{1, 2} >= {1, 2, 3} # => False
+
+# 左の集合が右の集合の部分集合であるか確認。
+{1, 2} <= {1, 2, 3} # => True
+
+# in により値が集合の中に存在するか確認できます。
+2 in filled_set # => True
+10 in filled_set # => False
+
+
+####################################################
+# 3. 制御の流れとiterable
+####################################################
+
+# まずは変数を作りましょう。
+some_var = 5
+
+# これはif文です。インデントがPythonでは特徴的ですね!
+# 以下の例では"some_var is smaller than 10"と出力されます。
+if some_var > 10:
+ print("some_var is totally bigger than 10.")
+elif some_var < 10: # この elif 節はオプションです。
+ print("some_var is smaller than 10.")
+else: # この else 節もオプションです。
+ print("some_var is indeed 10.")
+
+
+"""
+for ループはリストの要素を反復することができます。
+出力:
+ dog is a mammal
+ cat is a mammal
+ mouse is a mammal
+"""
+for animal in ["dog", "cat", "mouse"]:
+ # format() を使って文字列に変数を挿入して出力できます。
+ print("{} is a mammal".format(animal))
+
+"""
+"range(数値)" は、ゼロから与えられた数値までのiterableを返します。
+出力:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print(i)
+
+"""
+"range(lower, upper)" は、 lower の数値から upper の数値までのiterableを返します。
+upper の数値は含まれません。
+出力:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print(i)
+
+"""
+"range(lower, upper, step)" は、lower の数値から upper の数値までが、
+step 刻みで表現されるiterableを返します
+step が与えられない場合、デフォルトは1になります。
+出力:
+ 4
+ 6
+"""
+for i in range(4, 8, 2):
+ print(i)
+"""
+
+while によるループは条件が成立しなくなるまで実行されます。
+出力:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print(x)
+ x += 1 # x = x + 1 の省略記法
+
+# try/except ブロックにより、例外を扱う
+try:
+ # "raise" により例外を発生させます。
+ raise IndexError("This is an index error")
+except IndexError as e:
+ pass # pass は、何もしないという命令(no-op)に相当します。普通、ここで例外に対処します。
+except (TypeError, NameError):
+ pass # もし必要なら、複数の種類の例外を一緒に処理できます。
+else: # try/except ブロックへのオプションの節。他の全てのexceptブロックより後に置かなければなりません。
+ print("All good!") # tryで例外が発生しなかった場合のみ実行されます。
+finally: # 例外が発生したか、しなかったか、どのような例外だったかに関らず実行されます。
+ print("We can clean up resources here")
+
+# try/finallyでリソースの始末をする代わりに、 with 文を使うこともできます。
+with open("myfile.txt") as f:
+ for line in f:
+ print(line)
+
+# Pythonは、iterableと呼ばれる基本的な抽象化が提供しています。
+# iterableは、シーケンスとして取り扱えるオブジェクトです。
+# range関数で返されるオブジェクトもiterableの一種です。
+filled_dict = {"one": 1, "two": 2, "three": 3}
+our_iterable = filled_dict.keys()
+print(our_iterable) # => dict_keys(['one', 'two', 'three']). これはiterableインタフェースを実装するオブジェクトです。
+
+# iterableでループを行うことができます。
+for i in our_iterable:
+ print(i) # Prints one, two, three
+
+# しかし、インデックスで要素を参照することはできません。
+our_iterable[1] # TypeError が発生します。
+
+# iterableは、iteratorの作り方がわかるオブジェクトです。
+our_iterator = iter(our_iterable)
+
+# iterator は、要素を取り出したときの状態を覚えるオブジェクトです。
+# "next()"により次の要素を取り出せます。
+next(our_iterator) # => "one"
+
+# 反復(iterate)する度に、状態を更新します。
+next(our_iterator) # => "two"
+next(our_iterator) # => "three"
+
+# iteratorが自身の持つ全てのデータを返したあとは、 StopIteration 例外を発生させます。
+next(our_iterator) # StopIteration が発生します。
+
+# "list()"を呼ぶことにより、iteratorの全ての要素を得られます。
+list(filled_dict.keys()) # => ["one", "two", "three"]
+
+
+####################################################
+# 4. 関数
+####################################################
+
+# 新しい関数を作成するには "def" を使います。
+def add(x, y):
+ print("x is {} and y is {}".format(x, y))
+ return x + y # return 文で値を返します。
+
+# 引数付きで関数を呼んでみましょう。
+add(5, 6) # => "x is 5 and y is 6" と出力し、 11 を返します。
+
+# キーワード引数で関数を呼ぶこともできます。
+add(y=6, x=5) # キーワード引数を使うと任意の順番で引数を指定できます。
+
+
+# 可変数の位置引数を持つ関数を定義できます。
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) # => (1, 2, 3)
+
+
+# 可変数のキーワード引数を持つ関数を定義できます。
+def keyword_args(**kwargs):
+ return kwargs
+
+# 何が起こるか、試してみましょう
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+
+
+# お望みなら、両方一気にやることもできます。
+def all_the_args(*args, **kwargs):
+ print(args)
+ print(kwargs)
+"""
+all_the_args(1, 2, a=3, b=4) prints:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# 関数を呼ぶとき、 args/kwargs の逆のことをすることができます!
+# * を使ってタプルを展開したり、 ** を使って辞書を展開できます。
+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) に対応します。
+
+
+# タプルで複数の値を返す
+def swap(x, y): # 括弧を使わずに、複数の値をタプルとして返すことができます。
+ return y, x # (Note: 括弧は使わなくてもいいですが、使うこともできます。)
+
+
+x = 1
+y = 2
+x, y = swap(x, y) # => x = 2, y = 1
+# (x, y) = swap(x,y) # このように、括弧は使っても使わなくてもいいです。
+
+
+# 関数のスコープ
+x = 5
+
+
+def set_x(num):
+ # ローカル変数の x はグローバル変数の x とは異なります
+ x = num # => 43
+ print(x) # => 43
+
+
+def set_global_x(num):
+ global x
+ print(x) # => 5
+ x = num # グローバル変数の x に 6 が代入されました。
+ print(x) # => 6
+
+set_x(43)
+set_global_x(6)
+
+
+# Pythonは第一級関数をサポートします。
+def create_adder(x):
+ def adder(y):
+ return x + y
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) # => 13
+
+# 無名関数もサポートしています。
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
+
+# 高階関数も組込まれています。
+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]
+
+# map や filter の代わりに、リスト内包表記を使うことができます。
+# リスト内包表記は、出力を別のリスト内包表記にネストさせることができます。
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
+
+# 集合(set)や辞書も内包表記ができます。
+{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'}
+{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
+
+
+####################################################
+# 5. モジュール
+####################################################
+
+# Pythonではモジュールをインポートできます。
+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
+
+# 全部の関数をモジュールからインポートすることができます。
+# Warning: この方法は推奨されません。
+from math import *
+
+# 短い名前でモジュールをインポートすることができます。
+import math as m
+math.sqrt(16) == m.sqrt(16) # => True
+
+# Pythonのモジュールは実際には単なるPythonのファイルです。
+# 自分で書くことも、インポートすることもできます。
+# ファイル名がそのままモジュール名になります。
+
+# モジュールで定義されている関数と属性を調べることができます。
+import math
+dir(math)
+
+# もし、現在書いているスクリプトと同じフォルダに「math.py」という
+# Pythonのスクリプトが存在する場合、そのmath.pyが
+# 組み込みのPythonモジュールの代わりに読み込まれるでしょう。
+# これは、ローカルのフォルダはPythonの組み込みライブラリよりも
+# 優先度が高いため発生するのです。
+
+
+####################################################
+# 6. クラス
+####################################################
+
+# クラスを作成するために、"class"という演算子を使います。
+class Human:
+
+ # クラスの属性です。このクラスの全てのインスタンスで共有されます。
+ species = "H. sapiens"
+
+ # 標準的なイニシャライザで、このクラスがインスタンスを作成するときは毎回呼ばれます。
+ # 2つのアンダースコアがオブジェクトや属性の前後についているとき、これらはPythonによって利用され、
+ # ユーザーの名前空間には存在しないということに注意してください。
+ # __init__ や __str__ 、 __repr__ のようなメソッド(やオブジェクト、属性)は、
+ # magic methods (または dunder methods)と呼ばれます。
+ # このような名前を自分で発明しないほうがよいでしょう。
+ def __init__(self, name):
+ # 引数をインスタンスのname属性に設定します。
+ self.name = name
+
+ # プロパティの初期化
+ self.age = 0
+
+ # インスタンスメソッド。全てのメソッドは"self"を最初の引数に取ります。
+ def say(self, msg):
+ print("{name}: {message}".format(name=self.name, message=msg))
+
+ # 別のインスタンスメソッドの例。
+ def sing(self):
+ return 'yo... yo... microphone check... one two... one two...'
+
+ # クラスメソッドは全てのインスタンスで共有されます。
+ # クラスメソッドではクラスを最初の引数として呼ばれます。
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # スタティックメソッドはクラスやインスタンスを参照せずに呼ばれます。
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+ # プロパティはgetterのようなものです。
+ # age() メソッドを同名の読取専用属性に変換します。
+ @property
+ def age(self):
+ return self._age
+
+ # プロパティを設定できるようにします。
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # プロパティを削除できるようにします。
+ @age.deleter
+ def age(self):
+ del self._age
+
+
+# Pythonインタプリタがソースファイルを読み込んだとき、全てのコードを実行します。
+# この __name__ による確認により、このモジュールがメインのプログラムである場合にのみ、
+# このコードブロックが実行されるようにします。
+if __name__ == '__main__':
+ # クラスのインスタンスを作成します。
+ i = Human(name="Ian")
+ i.say("hi") # "Ian: hi"
+ j = Human("Joel")
+ j.say("hello") # "Joel: hello"
+ # i と j はHumanのインスタンスです。別の言葉で言うなら、これらはHumanのオブジェクトです。
+
+ # クラスメソッドを呼んでみましょう。
+ i.say(i.get_species()) # "Ian: H. sapiens"
+ # 共有属性を変更してみましょう。
+ Human.species = "H. neanderthalensis"
+ i.say(i.get_species()) # => "Ian: H. neanderthalensis"
+ j.say(j.get_species()) # => "Joel: H. neanderthalensis"
+
+ # スタティックメソッドを呼んでみましょう。
+ print(Human.grunt()) # => "*grunt*"
+ print(i.grunt()) # => "*grunt*"
+
+ # インスタンスのプロパティを更新してみましょう。
+ i.age = 42
+ # プロパティを取得してみましょう。
+ i.say(i.age) # => 42
+ j.say(j.age) # => 0
+ # プロパティを削除してみましょう。
+ del i.age
+ # i.age # => AttributeError が発生します。
+
+
+####################################################
+# 6.1 多重継承
+####################################################
+
+# 別のクラスを定義します。
+class Bat:
+
+ species = 'Baty'
+
+ def __init__(self, can_fly=True):
+ self.fly = can_fly
+
+ # このクラスも say メソッドを持ちます。
+ def say(self, msg):
+ msg = '... ... ...'
+ return msg
+
+ # 同様に、独自のメソッドも与えましょう。
+ def sonar(self):
+ return '))) ... ((('
+
+if __name__ == '__main__':
+ b = Bat()
+ print(b.say('hello'))
+ print(b.fly)
+
+# ファイル単位のモジュール化を利用するために、上記のクラスを別々のファイルに配置することができます。
+# ここでは、human.pyとbat.pyを作成してみましょう。
+
+# 他のファイルから関数をインポートするために、次のような形式を利用してください。
+# from "拡張子無しのファイル名" import "関数またはクラス"
+
+# superhero.py
+from human import Human
+from bat import Bat
+
+
+# BatmanはHumanとBatの両方を継承します。
+class Batman(Human, Bat):
+
+ # Batmanは species のクラス属性に独自の値を持ちます。
+ species = 'Superhero'
+
+ def __init__(self, *args, **kwargs):
+ # 通常、属性を継承するにはsuper()を呼び出します。
+ # super(Batman, self).__init__(*args, **kwargs)
+ # しかし、ここでは多重継承を行っているので、 super() はMRO(メソッド解決順序)の次の基本クラスにのみ動作します。
+ # なので、全ての祖先に対して明示的に __init__ を呼ぶことにします。
+ # *args と **kwargs を使うことで、それぞれの継承元が
+ # たまねぎの皮を剥がすごとく、引数を用いることができます。
+ Human.__init__(self, 'anonymous', *args, **kwargs)
+ Bat.__init__(self, *args, can_fly=False, **kwargs)
+ # 名前の属性の値を上書きします。
+ self.name = 'Sad Affleck'
+
+ def sing(self):
+ return 'nan nan nan nan nan batman!'
+
+
+if __name__ == '__main__':
+ sup = Batman()
+
+ # インスタンスの型を調べてみましょう。
+ if isinstance(sup, Human):
+ print('I am human')
+ if isinstance(sup, Bat):
+ print('I am bat')
+ if type(sup) is Batman:
+ print('I am Batman')
+
+ # getattr() や super() の両方で使われるMROを取得します。
+ # この属性は動的であり、更新が可能です。
+ print(Batman.__mro__) # => (<class '__main__.Batman'>, <class 'human.Human'>, <class 'bat.Bat'>, <class 'object'>)
+
+ # 親メソッドを呼び出しますが、独自のクラス属性を参照します。
+ print(sup.get_species()) # => Superhero
+
+ # オーバーロードされたメソッドを呼び出します。
+ print(sup.sing()) # => nan nan nan nan nan batman!
+
+ # 継承順により、Humanから継承されたメソッドを呼び出します。
+ sup.say('I agree') # => Sad Affleck: I agree
+
+ # 2番目の先祖にのみ存在するメソッドを呼び出してみます。
+ print(sup.sonar()) # => ))) ... (((
+
+ # 継承されたクラス属性
+ sup.age = 100
+ print(sup.age)
+
+ # デフォルト値が上書きされて、2番目の先祖から継承された属性
+ print('Can I fly? ' + str(sup.fly))
+
+
+####################################################
+# 7. 発展的内容
+####################################################
+
+# ジェネレータは遅延をするコードの作成に役立ちます。
+def double_numbers(iterable):
+ for i in iterable:
+ yield i + i
+
+# 次の値を処理するのに必要なデータしか読み込まないので、ジェネレータはメモリをあまり消費しません。
+# この性質により、他の方法では非常に多くのメモリを消費するような操作が可能になります。
+for i in double_numbers(range(1, 900000000)): # `range` もジェネレータの1つです。
+ print(i)
+ if i >= 30:
+ break
+
+# リスト内包表記のように、ジェネータ内包表記を作成することもできます。
+values = (-x for x in [1, 2, 3, 4, 5])
+for x in values:
+ print(x) # prints -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` を `wraps`します。
+# もし say_please が True なら、出力が変更されます。
+from functools import wraps
+
+
+def beg(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, "Please! I am poor :(")
+ return msg
+
+ return wrapper
+
+
+@beg
+def say(say_please=False):
+ msg = "Can you buy me a beer?"
+ return msg, say_please
+
+
+print(say()) # Can you buy me a beer?
+print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
+```
+
+## Ready For More?
+
+### Free Online
+
+* [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)
+* [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)
diff --git a/java.html.markdown b/java.html.markdown
index 6487d862..12de0c73 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -95,6 +95,12 @@ public class LearnJava {
// Byte - 8-bit signed two's complement integer
// (-128 <= byte <= 127)
byte fooByte = 100;
+
+ // If you would like to interpret a byte as an unsigned integer
+ // then this simple operation can help
+ int unsignedIntLessThan256 = 0xff & fooByte;
+ // this contrasts a cast which can be negative.
+ int signedInt = (int) fooByte;
// Short - 16-bit signed two's complement integer
// (-32,768 <= short <= 32,767)
@@ -102,7 +108,7 @@ public class LearnJava {
// Integer - 32-bit signed two's complement integer
// (-2,147,483,648 <= int <= 2,147,483,647)
- int fooInt = 1;
+ int bazInt = 1;
// Long - 64-bit signed two's complement integer
// (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
@@ -110,7 +116,9 @@ public class LearnJava {
// L is used to denote that this variable value is of type Long;
// anything without is treated as integer by default.
- // Note: Java has no unsigned types.
+ // Note: byte, short, int and long are signed. They can have positive and negative values.
+ // There are no unsigned variants.
+ // char, however, is 16-bit unsigned.
// Float - Single-precision 32-bit IEEE 754 Floating Point
// 2^-149 <= float <= (2-2^-23) * 2^127
@@ -190,7 +198,20 @@ public class LearnJava {
builderConcatenated.append("the StringBuilder class.");
System.out.println(builderConcatenated.toString()); // only now is the string built
// Output: You can use the StringBuilder class.
-
+
+ // StringBuilder is efficient when the fully constructed String is not required until the end of some processing.
+ StringBuilder stringBuilder = new StringBuilder();
+ String inefficientString = "";
+ for(int i = 0 ; i < 10; i++){
+ stringBuilder.append(i).append(" ");
+ inefficientString += i + " ";
+ }
+ System.out.println(inefficientString);
+ System.out.println(stringBuilder.toString());
+ // inefficientString requires a lot more work to produce, as it generates a String on every loop iteration.
+ // Simple concatenation with + is compiled to a StringBuilder and toString()
+ // Avoid string concatenation in loops.
+
// #3 - with String formatter
// Another alternative way to create strings. Fast and readable.
String.format("%s may prefer %s.", "Or you", "String.format()");
@@ -827,6 +848,10 @@ The links provided here below are just to get an understanding of the topic, fee
* [Java Code Conventions](https://www.oracle.com/technetwork/java/codeconvtoc-136057.html)
+* New features in 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)
+
**Online Practice and Tutorials**
* [Learneroo.com - Learn Java](http://www.learneroo.com)
diff --git a/javascript.html.markdown b/javascript.html.markdown
index 98261334..38119864 100644
--- a/javascript.html.markdown
+++ b/javascript.html.markdown
@@ -230,6 +230,17 @@ for (var i = 0; i < 5; i++){
// will run 5 times
}
+// Breaking out of labeled loops is similar to Java
+outer:
+for (var i = 0; i < 10; i++) {
+ for (var j = 0; j < 10; j++) {
+ if (i == 5 && j ==5) {
+ break outer;
+ // breaks out of outer loop instead of only the inner one
+ }
+ }
+}
+
// The for/in statement iterates over every property across the entire prototype chain.
var description = "";
var person = {fname:"Paul", lname:"Ken", age:18};
diff --git a/jquery.html.markdown b/jquery.html.markdown
index 013b75d7..d498733d 100644
--- a/jquery.html.markdown
+++ b/jquery.html.markdown
@@ -28,23 +28,17 @@ var square_p = $('p.square') // Selects paragraphs with the 'square' class
///////////////////////////////////
// 2. Events and Effects
-
+// jQuery is very good at handling what happens when an event is triggered
// A very common event used is the ready event on the document
// You can use the 'ready' method to wait until the element has finished loading
$(document).ready(function(){
// Code won't execute until the document is loaded
});
-
-// jQuery is very good at triggering events
-// and also handling what happens when an event is triggered
-$('#button').click(); // Fires a click event on $('#button')
-$('#button').click(function(){
- // Code here gets executed when the #button element is clicked
-});
-
+// You can also use defined functions
function onAction() {
// This is executed when the event is triggered
}
+$('#btn').click(onAction); // Invokes onAction on click
// Some other common events are:
$('#btn').dblclick(onAction); // Double click
@@ -60,10 +54,6 @@ $('#btn').mousemove(onAction); // When the mouse is moved
$('#btn').mouseenter(onAction); // Mouse enters the element
$('#btn').mouseleave(onAction); // Mouse leaves the element
-// You can also use an anonymous function
-$('#btn').hover(function(){
- // Executed on hover
-});
// These can all also trigger the event instead of handling it
// by simply not giving any parameters
@@ -76,7 +66,7 @@ $('#btn').on(
);
// You can move and hide elements with some effect methods
-$('.table').hide(); # Hides the element(s)
+$('.table').hide(); // Hides the element(s)
// Note: calling a function in these methods will still hide the element
$('.table').hide(function(){
@@ -114,13 +104,13 @@ tables.animate({margin-top:"+=50", height: "100px"}, 500, myFunction);
// 3. Manipulation
// These are similar to effects but can do more
-$('div').addClass('div') // Adds class div to all div taming-slim-20
+$('div').addClass('taming-slim-20'); // Adds class taming-slim-20 to all div
// Common manipulation methods
$('p').append('Hello world'); // Adds to end of element
$('p').attr('class'); // Gets attribute
$('p').attr('class', 'content'); // Sets attribute
-$('p').hasClass('div'); // Returns true if it has the class
+$('p').hasClass('taming-slim-20'); // Returns true if it has the class
$('p').height(); // Gets height of element or sets height
@@ -131,7 +121,7 @@ $('p').height(); // Gets only the first 'p' tag's height
// You can use each to loop through all the elements
var heights = [];
$('p').each(function() {
- heights.push($(this.height)); // Adds all 'p' tag heights to array
+ heights.push($(this).height()); // Adds all 'p' tag heights to array
});
diff --git a/kdb+.html.markdown b/kdb+.html.markdown
new file mode 100644
index 00000000..772c8a47
--- /dev/null
+++ b/kdb+.html.markdown
@@ -0,0 +1,774 @@
+---
+language: kdb+
+contributors:
+ - ["Matt Doherty", "https://github.com/picodoc"]
+ - ["Jonny Press", "jonny.press@aquaq.co.uk"]
+filename: learnkdb.q
+---
+
+The q langauge and its database component kdb+ were developed by Arthur Whitney
+and released by Kx systems in 2003. q is a descendant of APL and as such is
+very terse and a little strange looking for anyone from a "C heritage" language
+background. Its expressiveness and vector oriented nature make it well suited
+to performing complex calculations on large amounts of data (while also
+encouraging some amount of [code
+golf](https://en.wikipedia.org/wiki/Code_golf)). The fundamental structure in
+the language is not the object but instead the list, and tables are built as
+collections of lists. This means - unlike most traditional RDBMS systems -
+tables are column oriented. The language has both an in-memory and on-disk
+database built in, giving a large amount of flexibility. kdb+ is most widely
+used in the world of finance to store, analyze, process and retrieve large
+time-series data sets.
+
+The terms *q* and *kdb+* are usually used interchangeably, as the two are not
+separable so this distinction is not really useful.
+
+All Feedback welcome! You can reach me at matt.doherty@aquaq.co.uk, or Jonny
+at jonny.press@aquaq.co.uk
+
+```
+/ Single line comments start with a forward-slash
+/ These can also be used in-line, so long as at least one whitespace character
+/ separates it from text to the left
+/
+ A forward-slash on a line by itself starts a multiline comment
+ and a backward-slash on a line by itself terminates it
+\
+
+/ Run this file in an empty directory
+
+
+////////////////////////////////////
+// Basic Operators and Datatypes //
+////////////////////////////////////
+
+/ We have integers, which are 8 byte by default
+3 / => 3
+
+/ And floats, also 8 byte as standard. Trailing f distinguishes from int
+3.0 / => 3f
+
+/ 4 byte numerical types can also be specified with trailing chars
+3i / => 3i
+3.0e / => 3e
+
+/ Math is mostly what you would expect
+1+1 / => 2
+8-1 / => 7
+10*2 / => 20
+/ Except division, which uses percent (%) instead of forward-slash (/)
+35%5 / => 7f (the result of division is always a float)
+
+/ For integer division we have the keyword div
+4 div 3 / => 1
+
+/ Modulo also uses a keyword, since percent (%) is taken
+4 mod 3 / => 1
+
+/ And exponentiation...
+2 xexp 4 / => 16
+
+/ ...and truncating...
+floor 3.14159 / => 3
+
+/ ...getting the absolute value...
+abs -3.14159 / => 3.14159
+/ ...and many other things
+/ see http://code.kx.com/wiki/Reference for more
+
+/ q has no operator precedence, everything is evaluated right to left
+/ so results like this might take some getting used to
+2*1+1 / => 4 / (no operator precedence tables to remember!)
+
+/ Precedence can be modified with parentheses (restoring the 'normal' result)
+(2*1)+1 / => 3
+
+/ Assignment uses colon (:) instead of equals (=)
+/ No need to declare variables before assignment
+a:3
+a / => 3
+
+/ Variables can also be assigned in-line
+/ this does not affect the value passed on
+c:3+b:2+a:1 / (data "flows" from right to left)
+a / => 1
+b / => 3
+c / => 6
+
+/ In-place operations are also as you might expect
+a+:2
+a / => 3
+
+/ There are no "true" or "false" keywords in q
+/ boolean values are indicated by the bit value followed by b
+1b / => true value
+0b / => false value
+
+/ Equality comparisons use equals (=) (since we don't need it for assignment)
+1=1 / => 1b
+2=1 / => 0b
+
+/ Inequality uses <>
+1<>1 / => 0b
+2<>1 / => 1b
+
+/ The other comparisons are as you might expect
+1<2 / => 1b
+1>2 / => 0b
+2<=2 / => 1b
+2>=2 / => 1b
+
+/ Comparison is not strict with regard to types...
+42=42.0 / => 1b
+
+/ ...unless we use the match operator (~)
+/ which only returns true if entities are identical
+42~42.0 / => 0b
+
+/ The not operator returns true if the underlying value is zero
+not 0b / => 1b
+not 1b / => 0b
+not 42 / => 0b
+not 0.0 / => 1b
+
+/ The max operator (|) reduces to logical "or" for bools
+42|2.0 / => 42f
+1b|0b / => 1b
+
+/ The min operator (&) reduces to logical "and" for bools
+42&2.0 / => 2f
+1b&0b / => 0b
+
+/ q provides two ways to store character data
+/ Chars in q are stored in a single byte and use double-quotes (")
+ch:"a"
+/ Strings are simply lists of char (more on lists later)
+str:"This is a string"
+/ Escape characters work as normal
+str:"This is a string with \"quotes\""
+
+/ Char data can also be stored as symbols using backtick (`)
+symbol:`sym
+/ Symbols are NOT LISTS, they are an enumeration
+/ the q process stores internally a vector of strings
+/ symbols are enumerated against this vector
+/ this can be more space and speed efficient as these are constant width
+
+/ The string function converts to strings
+string `symbol / => "symbol"
+string 1.2345 / => "1.2345"
+
+/ q has a time type...
+t:01:00:00.000
+/ date type...
+d:2015.12.25
+/ and a datetime type (among other time types)
+dt:2015.12.25D12:00:00.000000000
+
+/ These support some arithmetic for easy manipulation
+dt + t / => 2015.12.25D13:00:00.000000000
+t - 00:10:00.000 / => 00:50:00.000
+/ and can be decomposed using dot notation
+d.year / => 2015i
+d.mm / => 12i
+d.dd / => 25i
+/ see http://code.kx.com/wiki/JB:QforMortals2/atoms#Temporal_Data for more
+
+/ q also has an infinity value so div by zero will not throw an error
+1%0 / => 0w
+-1%0 / => -0w
+
+/ And null types for representing missing values
+0N / => null int
+0n / => null float
+/ see http://code.kx.com/wiki/JB:QforMortals2/atoms#Null_Values for more
+
+/ q has standard control structures
+/ if is as you might expect (; separates the condition and instructions)
+if[1=1;a:"hi"]
+a / => "hi"
+/ if-else uses $ (and unlike if, returns a value)
+$[1=0;a:"hi";a:"bye"] / => "bye"
+a / => "bye"
+/ if-else can be extended to multiple clauses by adding args separated by ;
+$[1=0;a:"hi";0=1;a:"bye";a:"hello again"]
+a / => "hello again"
+
+
+////////////////////////////////////
+//// Data Structures ////
+////////////////////////////////////
+
+/ q is not an object oriented language
+/ instead complexity is built through ordered lists
+/ and mapping them into higher order structures: dictionaries and tables
+
+/ Lists (or arrays if you prefer) are simple ordered collections
+/ they are defined using parentheses () and semi-colons (;)
+(1;2;3) / => 1 2 3
+(-10.0;3.14159e;1b;`abc;"c")
+/ => -10f
+/ => 3.14159e
+/ => 1b
+/ => `abc
+/ => "c" (mixed type lists are displayed on multiple lines)
+((1;2;3);(4;5;6);(7;8;9))
+/ => 1 2 3
+/ => 4 5 6
+/ => 7 8 9
+
+/ Lists of uniform type can also be defined more concisely
+1 2 3 / => 1 2 3
+`list`of`syms / => `list`of`syms
+`list`of`syms ~ (`list;`of;`syms) / => 1b
+
+/ List length
+count (1;2;3) / => 3
+count "I am a string" / => 13 (string are lists of char)
+
+/ Empty lists are defined with parentheses
+l:()
+count l / => 0
+
+/ Simple variables and single item lists are not equivalent
+/ parentheses syntax cannot create a single item list (they indicate precedence)
+(1)~1 / => 1b
+/ single item lists can be created using enlist
+singleton:enlist 1
+/ or appending to an empty list
+singleton:(),1
+1~(),1 / => 0b
+
+/ Speaking of appending, comma (,) is used for this, not plus (+)
+1 2 3,4 5 6 / => 1 2 3 4 5 6
+"hello ","there" / => "hello there"
+
+/ Indexing uses square brackets []
+l:1 2 3 4
+l[0] / => 1
+l[1] / => 2
+/ indexing out of bounds returns a null value rather than an error
+l[5] / => 0N
+/ and indexed assignment
+l[0]:5
+l / => 5 2 3 4
+
+/ Lists can also be used for indexing and indexed assignment
+l[1 3] / => 2 4
+l[1 3]: 1 3
+l / => 5 1 3 3
+
+/ Lists can be untyped/mixed type
+l:(1;2;`hi)
+/ but once they are uniformly typed, q will enforce this
+l[2]:3
+l / => 1 2 3
+l[2]:`hi / throws a type error
+/ this makes sense in the context of lists as table columns (more later)
+
+/ For a nested list we can index at depth
+l:((1;2;3);(4;5;6);(7;8;9))
+l[1;1] / => 5
+
+/ We can elide the indexes to return entire rows or columns
+l[;1] / => 2 5 8
+l[1;] / => 4 5 6
+
+/ All the functions mentioned in the previous section work on lists natively
+1+(1;2;3) / => 2 3 4 (single variable and list)
+(1;2;3) - (3;2;1) / => -2 0 2 (list and list)
+
+/ And there are many more that are designed specifically for lists
+avg 1 2 3 / => 2f
+sum 1 2 3 / => 6
+sums 1 2 3 / => 1 3 6 (running sum)
+last 1 2 3 / => 3
+1 rotate 1 2 3 / => 2 3 1
+/ etc.
+/ Using and combining these functions to manipulate lists is where much of the
+/ power and expressiveness of the language comes from
+
+/ Take (#), drop (_) and find (?) are also useful working with lists
+l:1 2 3 4 5 6 7 8 9
+l:1+til 9 / til is a useful shortcut for generating ranges
+/ take the first 5 elements
+5#l / => 1 2 3 4 5
+/ drop the first 5
+5_l / => 6 7 8 9
+/ take the last 5
+-5#l / => 5 6 7 8 9
+/ drop the last 5
+-5_l / => 1 2 3 4
+/ find the first occurance of 4
+l?4 / => 3
+l[3] / => 4
+
+/ Dictionaries in q are a generalization of lists
+/ they map a list to another list (of equal length)
+/ the bang (!) symbol is used for defining a dictionary
+d:(`a;`b;`c)!(1;2;3)
+/ or more simply with concise list syntax
+d:`a`b`c!1 2 3
+/ the keyword key returns the first list
+key d / => `a`b`c
+/ and value the second
+value d / => 1 2 3
+
+/ Indexing is indentical to lists
+/ with the first list as a key instead of the position
+d[`a] / => 1
+d[`b] / => 2
+
+/ As is assignment
+d[`c]:4
+d
+/ => a| 1
+/ => b| 2
+/ => c| 4
+
+/ Arithmetic and comparison work natively, just like lists
+e:(`a;`b;`c)!(2;3;4)
+d+e
+/ => a| 3
+/ => b| 5
+/ => c| 8
+d-2
+/ => a| -1
+/ => b| 0
+/ => c| 2
+d > (1;1;1)
+/ => a| 0
+/ => b| 1
+/ => c| 1
+
+/ And the take, drop and find operators are remarkably similar too
+`a`b#d
+/ => a| 1
+/ => b| 2
+`a`b _ d
+/ => c| 4
+d?2
+/ => `b
+
+/ Tables in q are basically a subset of dictionaries
+/ a table is a dictionary where all values must be lists of the same length
+/ as such tables in q are column oriented (unlike most RDBMS)
+/ the flip keyword is used to convert a dictionary to a table
+/ i.e. flip the indices
+flip `c1`c2`c3!(1 2 3;4 5 6;7 8 9)
+/ => c1 c2 c3
+/ => --------
+/ => 1 4 7
+/ => 2 5 8
+/ => 3 6 9
+/ we can also define tables using this syntax
+t:([]c1:1 2 3;c2:4 5 6;c3:7 8 9)
+t
+/ => c1 c2 c3
+/ => --------
+/ => 1 4 7
+/ => 2 5 8
+/ => 3 6 9
+
+/ Tables can be indexed and manipulated in a similar way to dicts and lists
+t[`c1]
+/ => 1 2 3
+/ table rows are returned as dictionaries
+t[1]
+/ => c1| 2
+/ => c2| 5
+/ => c3| 8
+
+/ meta returns table type information
+meta t
+/ => c | t f a
+/ => --| -----
+/ => c1| j
+/ => c2| j
+/ => c3| j
+/ now we see why type is enforced in lists (to protect column types)
+t[1;`c1]:3
+t[1;`c1]:3.0 / throws a type error
+
+/ Most traditional databases have primary key columns
+/ in q we have keyed tables, where one table containing key columns
+/ is mapped to another table using bang (!)
+k:([]id:1 2 3)
+k!t
+/ => id| c1 c2 c3
+/ => --| --------
+/ => 1 | 1 4 7
+/ => 2 | 3 5 8
+/ => 3 | 3 6 9
+
+/ We can also use this shortcut for defining keyed tables
+kt:([id:1 2 3]c1:1 2 3;c2:4 5 6;c3:7 8 9)
+
+/ Records can then be retreived based on this key
+kt[1]
+/ => c1| 1
+/ => c2| 4
+/ => c3| 7
+kt[`id!1]
+/ => c1| 1
+/ => c2| 4
+/ => c3| 7
+
+
+////////////////////////////////////
+//////// Functions ////////
+////////////////////////////////////
+
+/ In q the function is similar to a mathematical map, mapping inputs to outputs
+/ curly braces {} are used for function definition
+/ and square brackets [] for calling functions (just like list indexing)
+/ a very minimal function
+f:{x+x}
+f[2] / => 4
+
+/ Functions can be annonymous and called at point of definition
+{x+x}[2] / => 4
+
+/ By default the last expression is returned
+/ colon (:) can be used to specify return
+{x+x}[2] / => 4
+{:x+x}[2] / => 4
+/ semi-colon (;) separates expressions
+{r:x+x;:r}[2] / => 4
+
+/ Function arguments can be specified explicitly (separated by ;)
+{[arg1;arg2] arg1+arg2}[1;2] / => 3
+/ or if ommited will default to x, y and z
+{x+y+z}[1;2;3] / => 6
+
+/ Built in functions are no different, and can be called the same way (with [])
++[1;2] / => 3
+<[1;2] / => 1b
+
+/ Functions are first class in q, so can be returned, stored in lists etc.
+{:{x+y}}[] / => {x+y}
+(1;"hi";{x+y})
+/ => 1
+/ => "hi"
+/ => {x+y}
+
+/ There is no overloading and no keyword arguments for custom q functions
+/ however using a dictionary as a single argument can overcome this
+/ allows for optional arguments or differing functionality
+d:`arg1`arg2`arg3!(1.0;2;"my function argument")
+{x[`arg1]+x[`arg2]}[d] / => 3f
+
+/ Functions in q see the global scope
+a:1
+{:a}[] / => 1
+
+/ However local scope obscures this
+a:1
+{a:2;:a}[] / => 2
+a / => 1
+
+/ Functions cannot see nested scopes (only local and global)
+{local:1;{:local}[]}[] / throws error as local is not defined in inner function
+
+/ A function can have one or more of it's arguments fixed (projection)
+f:+[4]
+f[4] / => 8
+f[5] / => 9
+f[6] / => 10
+
+
+////////////////////////////////////
+////////// q-sql //////////
+////////////////////////////////////
+
+/ q has it's own syntax for manipulating tables, similar to standard SQL
+/ This contains the usual suspects of select, insert, update etc.
+/ and some new functionality not typically available
+/ q-sql has two significant differences (other than syntax) to normal SQL:
+/ - q tables have well defined record orders
+/ - tables are stored as a collection of columns
+/ (so vectorized column operations are fast)
+/ a full description of q-sql is a little beyond the scope of this intro
+/ so we will just cover enough of the basics to get you going
+
+/ First define ourselves a table
+t:([]name:`Arthur`Thomas`Polly;age:35 32 52;height:180 175 160;sex:`m`m`f)
+
+/ equivalent of SELECT * FROM t
+select from t / (must be lower case, and the wildcard is not necessary)
+/ => name age height sex
+/ => ---------------------
+/ => Arthur 35 180 m
+/ => Thomas 32 175 m
+/ => Polly 52 160 f
+
+/ Select specific columns
+select name,age from t
+/ => name age
+/ => ----------
+/ => Arthur 35
+/ => Thomas 32
+/ => Polly 52
+
+/ And name them (equivalent of using AS in standard SQL)
+select charactername:name, currentage:age from t
+/ => charactername currentage
+/ => ------------------------
+/ => Arthur 35
+/ => Thomas 32
+/ => Polly 52
+
+/ This SQL syntax is integrated with the q language
+/ so q can be used seamlessly in SQL statements
+select name, feet:floor height*0.032, inches:12*(height*0.032) mod 1 from t
+/ => name feet inches
+/ => ------------------
+/ => Arthur 5 9.12
+/ => Thomas 5 7.2
+/ => Polly 5 1.44
+
+/ Including custom functions
+select name, growth:{[h;a]h%a}[height;age] from t
+/ => name growth
+/ => ---------------
+/ => Arthur 5.142857
+/ => Thomas 5.46875
+/ => Polly 3.076923
+
+/ The where clause can contain multiple statements separated by commas
+select from t where age>33,height>175
+/ => name age height sex
+/ => ---------------------
+/ => Arthur 35 180 m
+
+/ The where statements are executed sequentially (not the same as logical AND)
+select from t where age<40,height=min height
+/ => name age height sex
+/ => ---------------------
+/ => Thomas 32 175 m
+select from t where (age<40)&(height=min height)
+/ => name age height sex
+/ => -------------------
+
+/ The by clause falls between select and from
+/ and is equivalent to SQL's GROUP BY
+select avg height by sex from t
+/ => sex| height
+/ => ---| ------
+/ => f | 160
+/ => m | 177.5
+
+/ If no aggreation function is specified, last is assumed
+select by sex from t
+/ => sex| name age height
+/ => ---| -----------------
+/ => f | Polly 52 160
+/ => m | Thomas 32 175
+
+/ Update has the same basic form as select
+update sex:`male from t where sex=`m
+/ => name age height sex
+/ => ----------------------
+/ => Arthur 35 180 male
+/ => Thomas 32 175 male
+/ => Polly 52 160 f
+
+/ As does delete
+delete from t where sex=`m
+/ => name age height sex
+/ => --------------------
+/ => Polly 52 160 f
+
+/ None of these sql operations are carried out in place
+t
+/ => name age height sex
+/ => ---------------------
+/ => Arthur 35 180 m
+/ => Thomas 32 175 m
+/ => Polly 52 160 f
+
+/ Insert however is in place, it takes a table name, and new data
+`t insert (`John;25;178;`m) / => ,3
+t
+/ => name age height sex
+/ => ---------------------
+/ => Arthur 35 180 m
+/ => Thomas 32 175 m
+/ => Polly 52 160 f
+/ => John 25 178 m
+
+/ Upsert is similar (but doesn't have to be in-place)
+t upsert (`Chester;58;179;`m)
+/ => name age height sex
+/ => ----------------------
+/ => Arthur 35 180 m
+/ => Thomas 32 175 m
+/ => Polly 52 160 f
+/ => John 25 178 m
+/ => Chester 58 179 m
+
+/ it will also upsert dicts or tables
+t upsert `name`age`height`sex!(`Chester;58;179;`m)
+t upsert (`Chester;58;179;`m)
+/ => name age height sex
+/ => ----------------------
+/ => Arthur 35 180 m
+/ => Thomas 32 175 m
+/ => Polly 52 160 f
+/ => John 25 178 m
+/ => Chester 58 179 m
+
+/ And if our table is keyed
+kt:`name xkey t
+/ upsert will replace records where required
+kt upsert ([]name:`Thomas`Chester;age:33 58;height:175 179;sex:`f`m)
+/ => name | age height sex
+/ => -------| --------------
+/ => Arthur | 35 180 m
+/ => Thomas | 33 175 f
+/ => Polly | 52 160 f
+/ => John | 25 178 m
+/ => Chester| 58 179 m
+
+/ There is no ORDER BY clause in q-sql, instead use xasc/xdesc
+`name xasc t
+/ => name age height sex
+/ => ---------------------
+/ => Arthur 35 180 m
+/ => John 25 178 m
+/ => Polly 52 160 f
+/ => Thomas 32 175 m
+
+/ Most of the standard SQL joins are present in q-sql, plus a few new friends
+/ see http://code.kx.com/wiki/JB:QforMortals2/queries_q_sql#Joins
+/ the two most important (commonly used) are lj and aj
+
+/ lj is basically the same as SQL LEFT JOIN
+/ where the join is carried out on the key columns of the left table
+le:([sex:`m`f]lifeexpectancy:78 85)
+t lj le
+/ => name age height sex lifeexpectancy
+/ => ------------------------------------
+/ => Arthur 35 180 m 78
+/ => Thomas 32 175 m 78
+/ => Polly 52 160 f 85
+/ => John 25 178 m 78
+
+/ aj is an asof join. This is not a standard SQL join, and can be very powerful
+/ The canonical example of this is joining financial trades and quotes tables
+trades:([]time:10:01:01 10:01:03 10:01:04;sym:`msft`ibm`ge;qty:100 200 150)
+quotes:([]time:10:01:00 10:01:01 10:01:01 10:01:03;
+ sym:`ibm`msft`msft`ibm; px:100 99 101 98)
+aj[`time`sym;trades;quotes]
+/ => time sym qty px
+/ => ---------------------
+/ => 10:01:01 msft 100 101
+/ => 10:01:03 ibm 200 98
+/ => 10:01:04 ge 150
+/ for each row in the trade table, the last (prevailing) quote (px) for that sym
+/ is joined on.
+/ see http://code.kx.com/wiki/JB:QforMortals2/queries_q_sql#Asof_Join
+
+////////////////////////////////////
+///// Extra/Advanced //////
+////////////////////////////////////
+
+////// Adverbs //////
+/ You may have noticed the total lack of loops to this point
+/ This is not a mistake!
+/ q is a vector language so explicit loops (for, while etc.) are not encouraged
+/ where possible functionality should be vectorized (i.e. operations on lists)
+/ adverbs supplement this, modifying the behaviour of functions
+/ and providing loop type functionality when required
+/ (in q functions are sometimes refered to as verbs, hence adverbs)
+/ the "each" adverb modifies a function to treat a list as individual variables
+first each (1 2 3;4 5 6;7 8 9)
+/ => 1 4 7
+
+/ each-left (\:) and each-right (/:) modify a two-argument function
+/ to treat one of the arguments and individual variables instead of a list
+1 2 3 +\: 1 2 3
+/ => 2 3 4
+/ => 3 4 5
+/ => 4 5 6
+1 2 3 +/: 1 2 3
+/ => 2 3 4
+/ => 3 4 5
+/ => 4 5 6
+
+/ The true alternatives to loops in q are the adverbs scan (\) and over (/)
+/ their behaviour differs based on the number of arguments the function they
+/ are modifying receives. Here I'll summarise some of the most useful cases
+/ a single argument function modified by scan given 2 args behaves like "do"
+{x * 2}\[5;1] / => 1 2 4 8 16 32 (i.e. multiply by 2, 5 times)
+{x * 2}/[5;1] / => 32 (using over only the final result is shown)
+
+/ If the first argument is a function, we have the equivalent of "while"
+{x * 2}\[{x<100};1] / => 1 2 4 8 16 32 64 128 (iterates until returns 0b)
+{x * 2}/[{x<100};1] / => 128 (again returns only the final result)
+
+/ If the function takes two arguments, and we pass a list, we have "for"
+/ where the result of the previous execution is passed back into the next loop
+/ along with the next member of the list
+{x + y}\[1 2 3 4 5] / => 1 3 6 10 15 (i.e. the running sum)
+{x + y}/[1 2 3 4 5] / => 15 (only the final result)
+
+/ There are other adverbs and uses, this is only intended as quick overview
+/ http://code.kx.com/wiki/JB:QforMortals2/functions#Adverbs
+
+////// Scripts //////
+/ q scripts can be loaded from a q session using the "\l" command
+/ for example "\l learnkdb.q" will load this script
+/ or from the command prompt passing the script as an argument
+/ for example "q learnkdb.q"
+
+////// On-disk data //////
+/ Tables can be persisted to disk in several formats
+/ the two most fundamental are serialized and splayed
+t:([]a:1 2 3;b:1 2 3f)
+`:serialized set t / saves the table as a single serialized file
+`:splayed/ set t / saves the table splayed into a directory
+
+/ the dir structure will now look something like:
+/ db/
+/ ├── serialized
+/ └── splayed
+/ ├── a
+/ └── b
+
+/ Loading this directory (as if it was as script, see above)
+/ loads these tables into the q session
+\l .
+/ the serialized table will be loaded into memory
+/ however the splayed table will only be mapped, not loaded
+/ both tables can be queried using q-sql
+select from serialized
+/ => a b
+/ => ---
+/ => 1 1
+/ => 2 2
+/ => 3 3
+select from splayed / (the columns are read from disk on request)
+/ => a b
+/ => ---
+/ => 1 1
+/ => 2 2
+/ => 3 3
+/ see http://code.kx.com/wiki/JB:KdbplusForMortals/contents for more
+
+////// Frameworks //////
+/ kdb+ is typically used for data capture and analysis.
+/ This involves using an architecture with multiple processes
+/ working together. kdb+ frameworks are available to streamline the setup
+/ and configuration of this architecuture and add additional functionality
+/ such as disaster recovery, logging, access, load balancing etc.
+/ https://github.com/AquaQAnalytics/TorQ
+```
+
+## Want to know more?
+
+* [*q for mortals* q language tutorial](http://code.kx.com/wiki/JB:QforMortals2/contents)
+* [*kdb for mortals* on disk data tutorial](http://code.kx.com/wiki/JB:KdbplusForMortals/contents)
+* [q language reference](http://code.kx.com/wiki/Reference)
+* [Online training courses](http://training.aquaq.co.uk/)
+* [TorQ production framework](https://github.com/AquaQAnalytics/TorQ)
diff --git a/ko-kr/json-kr.html.markdown b/ko-kr/json-kr.html.markdown
new file mode 100644
index 00000000..462bf63a
--- /dev/null
+++ b/ko-kr/json-kr.html.markdown
@@ -0,0 +1,80 @@
+---
+language: json
+filename: learnjson-kr.json
+contributors:
+ - ["Anna Harren", "https://github.com/iirelu"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["himanshu", "https://github.com/himanshu81494"]
+ - ["Michael Neth", "https://github.com/infernocloud"]
+translators:
+ - ["Wooseop Kim", "https://github.com/linterpreteur"]
+lang: ko-kr
+---
+
+JSON은 아주 간단한 데이터 교환 포맷입니다. [json.org](http://json.org/json-ko.html)에 의하면, 사람이 읽고 쓰기 쉬우며 기계가 분석하고 생성하기 쉽습니다.
+
+JSON 한 개는 반드시 이하의 둘 중 하나를 나타내야 합니다.
+* 이름과 값 쌍의 모임(`{ }`). 이는 다양한 언어에서 객체, 레코드, 구조체, 딕셔너리, 해시 테이블, 키 리스트, 혹은 연관 배열로 구현됩니다.
+* 값에 순서가 있는 리스트 (`[ ]`). 이는 다양한 언어에서 배열, 벡터, 리스트, 시퀀스로 구현됩니다.
+
+순수한 JSON은 사실 주석이 없지만 대부분의 파서는 C 스타일의 주석(`//`, `/* */`)도 받아들일 겁니다. 일부 파서는 꼬리에 오는 쉼표, 즉 배열의 마지막 원소 혹은 객체의 마지막 속성 다음에 오는 쉼표도 인정하겠지만, 호환성을 위해 쓰지 않는 것이 좋습니다.
+
+이 튜토리얼의 목적에 따라 모든 것은 100% 유효한 JSON입니다. 다행스럽게도 JSON은 다소 자기서술적입니다.
+
+지원하는 데이터 형:
+
+* 문자열: `"안녕"`, `"\"따옴표.\""`, `"\u0abe"`, `"개행 문자.\n"`
+* 수: `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4`
+* 객체: `{ "키": "값" }`
+* 배열: `["값 값 값"]`
+* 기타: `true`, `false`, `null`
+
+```json
+{
+ "키": "값",
+
+ "키는": "반드시 큰따옴표 안에 있어야 합니다.",
+ "수": 0,
+ "문자열": "Hellø, wørld. 모든 유니코드와 \"탈출 문자\"가 지원됩니다.",
+ "부울도 있나?": true,
+ "아무 것도 없는 건": null,
+
+ "큰 수": 1.2e+100,
+
+ "객체": {
+ "주석": "문서 구조의 대부분은 객체가 될 것입니다.",
+
+ "배열": [0, 1, 2, 3, "배열 안에는 무엇이든 올 수 있습니다.", 5],
+
+ "다른 객체": {
+ "주석": "객체는 객체를 포함할 수 있습니다. 아주 유용하죠."
+ }
+ },
+
+ "장난이지롱": [
+ {
+ "칼륨이 풍부한": ["바나나"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "neo"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "다른 방식": {
+ "주석": "여기 보세요!"
+ , "쉼표의 위치는": "상관 없습니다. 다음 키 전에만 온다면 유효합니다."
+ , "다른 주석": "참 좋죠"
+ },
+
+ "공백은": "상관이 없습니다.",
+
+ "짧았죠": "끝입니다. JSON의 모든 것을 터득하셨습니다."
+}
+```
+
+## 더 읽기
+
+* [JSON.org](http://json.org/json-ko.html) 플로우차트와 같은 그래픽을 이용해 설명한 JSON의 모든 것.
diff --git a/ko-kr/markdown-kr.html.markdown b/ko-kr/markdown-kr.html.markdown
new file mode 100644
index 00000000..bfa2a877
--- /dev/null
+++ b/ko-kr/markdown-kr.html.markdown
@@ -0,0 +1,308 @@
+---
+language: markdown
+contributors:
+ - ["Dan Turkel", "http://danturkel.com/"]
+ - ["Jacob Ward", "http://github.com/JacobCWard/"]
+filename: markdown-kr.md
+lang: ko-kr
+---
+
+마크다운은 2004년에 존 그루버가 창시했습니다. HTML으로 (그리고 이제는 다른 다양한 형식으로도) 쉽게 변환되는 읽고 쓰기 쉬운 문법입니다.
+
+마크다운은 또한 파서마다 구현이 다양합니다. 본 문서는 어떤 기능이 보편적인지,
+혹은 어떤 기능이 특정 파서에 종속되어 있는지 명확히 하고자 합니다.
+
+- [HTML 요소](#html-elements)
+- [제목](#headings)
+- [간단한 텍스트 꾸미기](#simple-text-styles)
+- [문단](#paragraphs)
+- [목록](#lists)
+- [코드](#code-blocks)
+- [수평선](#horizontal-rule)
+- [링크](#links)
+- [이미지](#images)
+- [기타](#miscellany)
+
+## HTML 요소
+HTML은 마크다운의 수퍼셋입니다. 모든 HTML 파일은 유효한 마크다운이라는 것입니다.
+```markdown
+<!--따라서 주석과 같은 HTML 요소들을 마크다운에 사용할 수 있으며, 마크다운 파서에 영향을
+받지 않을 것입니다. 하지만 마크다운 파일에서 HTML 요소를 만든다면 그 요소의 안에서는
+마크다운 문법을 사용할 수 없습니다.-->
+```
+## 제목
+
+텍스트 앞에 붙이는 우물 정 기호(#)의 갯수에 따라 `<h1>`부터 `<h6>`까지의 HTML 요소를
+손쉽게 작성할 수 있습니다.
+```markdown
+# <h1>입니다.
+## <h2>입니다.
+### <h3>입니다.
+#### <h4>입니다.
+##### <h5>입니다.
+###### <h6>입니다.
+```
+또한 h1과 h2를 나타내는 다른 방법이 있습니다.
+```markdown
+h1입니다.
+=============
+
+h2입니다.
+-------------
+```
+## 간단한 텍스트 꾸미기
+
+마크다운으로 쉽게 텍스트를 기울이거나 굵게 할 수 있습니다.
+```markdown
+*기울인 텍스트입니다.*
+_이 텍스트도 같습니다._
+
+**굵은 텍스트입니다.**
+__이 텍스트도 같습니다.__
+
+***기울인 굵은 텍스트입니다.***
+**_이 텍스트도 같습니다._**
+*__이것도 같습니다.__*
+```
+깃헙 전용 마크다운에는 취소선도 있습니다.
+```markdown
+~~이 텍스트에는 취소선이 그려집니다.~~
+```
+## 문단
+
+문단은 하나 이상의 빈 줄로 구분되는, 한 줄 이상의 인접한 텍스트입니다.
+
+```markdown
+문단입니다. 문단에 글을 쓰다니 재밌지 않나요?
+
+이제 두 번째 문단입니다.
+아직도 두 번째 문단입니다.
+
+나는 세 번째 문단!
+```
+HTML `<br />` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어쓰기로 문단을 끝내고
+새 문단을 시작할 수 있습니다.
+
+```markdown
+띄어쓰기 두 개로 끝나는 문단 (마우스로 긁어 보세요).
+
+이 위에는 `<br />` 태그가 있습니다.
+```
+
+인용문은 > 문자로 쉽게 쓸 수 있습니다.
+
+```markdown
+> 인용문입니다. 수동으로 개행하고서
+> 줄마다 `>`를 칠 수도 있고 줄을 길게 쓴 다음에 저절로 개행되게 내버려 둘 수도 있습니다.
+> `>`로 시작하기만 한다면 차이가 없습니다.
+
+> 한 단계 이상의 들여쓰기를
+>> 사용할 수도 있습니다.
+> 깔끔하죠?
+```
+
+## 목록
+순서가 없는 목록은 별표, 더하기, 하이픈을 이용해 만들 수 있습니다.
+```markdown
+* 이거
+* 저거
+* 그거
+```
+
+또는
+
+```markdown
++ 이거
++ 저거
++ 그거
+```
+
+또는
+
+```markdown
+- 이거
+- 저거
+- 그거
+```
+
+순서가 있는 목록은 숫자와 마침표입니다.
+
+```markdown
+1. 하나
+2. 둘
+3. 셋
+```
+
+숫자를 정확히 붙이지 않더라도 제대로 된 순서로 보여주겠지만, 좋은 생각은 아닙니다.
+
+```markdown
+1. 하나
+1. 둘
+1. 셋
+```
+(위의 예시와 똑같이 나타납니다.)
+
+목록 안에 목록이 올 수도 있습니다.
+
+```markdown
+1. 하나
+2. 둘
+3. 셋
+ * 이거
+ * 저거
+4. 넷
+```
+
+심지어 할 일 목록도 있습니다. HTML 체크박스가 만들어집니다.
+
+```markdown
+x가 없는 박스들은 체크되지 않은 HTML 체크박스입니다.
+- [ ] 첫 번째 할 일
+- [ ] 두 번째 할 일
+이 체크박스는 체크된 HTML 체크박스입니다.
+- [x] 완료된 일
+```
+
+## 코드
+
+띄어쓰기 네 개 혹은 탭 한 개로 줄을 들여씀으로서 (`<code> 요소를 사용하여`) 코드를
+나타낼 수 있습니다.
+
+```markdown
+ puts "Hello, world!"
+```
+
+탭을 더 치거나 띄어쓰기를 네 번 더 함으로써 코드를 들여쓸 수 있습니다.
+
+```markdown
+ my_array.each do |item|
+ puts item
+ end
+```
+
+인라인 코드는 백틱 문자를 이용하여 나타냅니다. `
+
+```markdown
+철수는 `go_to()` 함수가 뭘 했는지도 몰랐어!
+```
+
+깃헙 전용 마크다운에서는 코드를 나타내기 위해 특별한 문법을 쓸 수 있습니다.
+
+<pre>
+<code class="highlight">&#x60;&#x60;&#x60;ruby
+def foobar
+ puts "Hello world!"
+end
+&#x60;&#x60;&#x60;</code></pre>
+
+위의 경우에 들여쓰기가 필요없을 뿐 아니라 \`\`\` 뒤에 특정해 준 언어의 문법에 따라
+색을 입혀줄 것입니다.
+
+## 수평선
+
+수평선(`<hr/>`)은 셋 이상의 별표나 하이픈을 이용해 쉽게 나타낼 수 있습니다.
+띄어쓰기가 포함될 수 있습니다.
+```markdown
+***
+---
+- - -
+****************
+```
+## 링크
+
+마크다운의 장점 중 하나는 링크를 만들기 쉽다는 것입니다. 대괄호 안에 나타낼 텍스트를 쓰고
+괄호 안에 URL을 쓰면 됩니다.
+
+```markdown
+[클릭](http://test.com/)
+```
+
+괄호 안에 따옴표를 이용해 링크에 제목을 달 수도 있습니다.
+
+```markdown
+[클릭](http://test.com/ "test.com으로 가기")
+```
+
+상대 경로도 유효합니다.
+
+```markdown
+[music으로 가기](/music/).
+```
+
+참조하는 식으로 링크를 걸 수도 있습니다.
+
+<pre><code class="highlight">&#x5b;<span class="nv">이 </span>][<span class="ss">링크</span>]에서 더 알아보세요!
+&#x5b;<span class="nv">원하신다면 </span>][<span class="ss">foobar</span>]도 참고하세요.
+
+&#x5b;<span class="nv">링크</span>]: <span class="sx">http://test.com/</span> <span class="nn">"좋아!"</span>
+&#x5b;<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"됐다!"</span></code></pre>
+
+제목은 작은 따옴표나 괄호에 들어갈 수도 있고, 완전히 생략할 수도 있습니다. 참조는 문서의
+어느 곳에든 올 수 있고 참조 ID는 유일하다면 무엇이든 될 수 있습니다.
+
+링크 텍스트를 ID로 사용하는 "묵시적 이름"도 있습니다.
+
+<pre><code class="highlight">&#x5b;<span class="nv">이것</span>][]은 링크입니다.
+
+&#x5b;<span class="nv">이것</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
+
+하지만 보통 그렇게 추천하지는 않습니다.
+
+## 이미지
+이미지는 링크와 같지만 앞에 느낌표가 붙습니다.
+
+```markdown
+![이미지의 alt 속성](http://imgur.com/myimage.jpg "제목")
+```
+
+참조 방식도 가능합니다.
+
+<pre><code class="highlight">!&#x5b;<span class="nv">alt 속성</span>][<span class="ss">이미지</span>]
+
+&#x5b;<span class="nv">이미지</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"제목이 필요하다면 여기에"</span></code></pre>
+
+## 기타
+### 자동 링크
+
+```markdown
+<http://testwebsite.com/>와
+[http://testwebsite.com/](http://testwebsite.com/)는 동일합니다.
+```
+
+### 이메일 자동 링크
+```markdown
+<foo@bar.com>
+```
+### 탈출 문자
+
+```markdown
+*별표 사이에 이 텍스트*를 치고 싶지만 기울이고 싶지는 않다면
+이렇게 하시면 됩니다. \*별표 사이에 이 텍스트\*.
+```
+
+### 키보드 키
+
+깃헙 전용 마크다운에서는 `<kbd>` 태그를 이용해 키보드 키를 나타낼 수 있습니다.
+
+```markdown
+컴퓨터가 멈췄다면 눌러보세요.
+<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
+```
+
+### 표
+
+표는 깃헙 전용 마크다운에서만 쓸 수 있고 다소 복잡하지만, 정말 쓰고 싶으시다면
+```markdown
+| 1열 | 2열 | 3열 |
+| :--------| :-------: | --------: |
+| 왼쪽 정렬 | 가운데 정렬 | 오른쪽 정렬 |
+| 머시기 | 머시기 | 머시기 |
+```
+혹은
+```markdown
+1열 | 2열 | 3열
+:-- | :-: | --:
+으악 너무 못생겼어 | 그만 | 둬
+```
+---
+추가 정보를 위해, 존 그루버의 공식 문법 [(영어) 문서](http://daringfireball.net/projects/markdown/syntax)와 애덤 프릿차드의 훌륭한 [(영어) 치트싯](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)을 확인하세요.
diff --git a/ko-kr/xml-kr.html.markdown b/ko-kr/xml-kr.html.markdown
new file mode 100644
index 00000000..9beef581
--- /dev/null
+++ b/ko-kr/xml-kr.html.markdown
@@ -0,0 +1,168 @@
+---
+language: xml
+filename: learnxml-kr.xml
+contributors:
+ - ["João Farias", "https://github.com/JoaoGFarias"]
+ - ["Rachel Stiyer", "https://github.com/rstiyer"]
+ - ["Deepanshu Utkarsh", "https://github.com/duci9y"]
+translators:
+ - ["Wooseop Kim", "https://github.com/linterpreteur"]
+lang: ko-kr
+---
+
+XML은 데이터를 저장하고 전송하기 위해 설계된 마크업 언어입니다. 인간과 기계 모두가 읽을 수 있도록 만들어졌습니다.
+
+XML은 HTML과는 달리 데이터를 보여주는 방법이나 그 형식을 특정하지 않습니다. 단지 데이터를 담을 뿐입니다.
+
+차이는 **내용**과 **마크업**에 있습니다. 내용은 무엇이든 될 수 있지만, 마크업은 정의되어 있습니다.
+
+## 기초 정의 및 도입
+
+XML 문서는 기본적으로 자신을 설명하는 *속성*을 가질 수 있으며 자식으로서 텍스트 혹은 다른 요소를 가질 수 있는 *요소*들로 이루어집니다. 모든 XML 문서는 반드시 루트 요소를 가져야 합니다. 루트 요소는 문서에 있는 모든 다른 요소들의 조상입니다.
+
+XML 파서는 매우 엄격하게 설계되어 있으므로 문서의 형식이 틀렸다면 파싱을 멈출 것입니다. 그러므로 모든 XML 문서는 [(영어) XML 문법 규칙](http://www.w3schools.com/xml/xml_syntax.asp)을 따른다고 보장할 수 있습니다.
+
+```xml
+<!-- 주석에는 두 개의 연속된 하이픈(-)이 들어갈 수 없습니다. -->
+<!-- 주석은 여러 줄로
+ 이어질 수 있습니다. -->
+
+<!-- 요소 -->
+<!-- 요소는 XML의 기본적 구성품입니다. 요소에는 두 개의 유형이 있습니다. -->
+<element1 attribute="value" /> <!-- 빈 요소는 내용을 담지 않습니다. -->
+<!-- 그리고 비지 않은 요소가 있습니다. -->
+<element2 attribute="value">내용</element2>
+<!-- 요소 이름에는 알파벳과 숫자만이 허용됩니다. -->
+
+<empty /> <!-- 요소는 어떠한 내용도 없이 순수한 마크업인 -->
+<!-- 빈 요소 태그로 구성될 수 있습니다. -->
+
+<notempty> <!-- 혹은 여는 태그와 -->
+ <!-- 내용, -->
+</notempty> <!-- 그리고 닫는 태그로 구성될 수도 잇습니다. -->
+
+<!-- 요소 이름은 대소문자를 구별합니다. -->
+<element />
+<eLEMENT />
+<!-- 둘은 같지 않습니다. -->
+
+<!-- 속성 -->
+<!-- 속성은 요소 안에 존재하는 키와 값의 쌍입니다. -->
+<element attribute="value" another="anotherValue" many="space-separated list" />
+<!-- 속성은 원소에서 단 한 번만 나타날 수 있습니다. 속성은 단 하나의 값만 갖습니다.
+ 이에 대한 흔한 해결책은 공백으로 구분된 리스트를 포함하는 것입니다. -->
+
+<!-- 중첩 요소 -->
+<!-- 한 요소의 내용은 다른 요소들을 포함할 수 있습니다. -->
+<parent>
+ <child>Text</child>
+ <emptysibling />
+</parent>
+<!-- 표준적인 트리 명칭이 사용됩니다. 각각의 요소는 노드라고 부릅니다.
+ 한 단계 위의 조상은 부모이며, 한 단계 아래의 후손은 자식입니다.
+ 같은 부모 요소를 가진 요소들은 자매입니다. -->
+
+<!-- XML은 공백을 보존합니다. -->
+<child>
+ Text
+</child>
+<child>Text</child>
+<!-- 둘은 같지 않습니다. -->
+```
+
+## XML 문서
+
+XML이 유용한 것은 인간도 읽을 수 있다는 것입니다. 다음의 문서는 에릭 레이의 XML 배우기를 포함해 세 권의 책을 파는 서점을 정의한다는 것을 알 수 있습니다. XML 파서 없이도 이렇게 쉽습니다.
+
+```xml
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- XML 프롤로그라는 것입니다. 필수는 아니지만, 권장됩니다. -->
+<bookstore>
+ <book category="COOKING">
+ <title lang="ko">매일 이탈리아 요리</title>
+ <author>지아다 데 라우렌티스</author>
+ <year>2005</year>
+ <price>30.00</price>
+ </book>
+ <book category="CHILDREN">
+ <title lang="ko">해리 포터</title>
+ <author>J K 롤링</author>
+ <year>2005</year>
+ <price>29.99</price>
+ </book>
+ <book category="WEB">
+ <title lang="ko">XML 배우기</title>
+ <author>에릭 레이</author>
+ <year>2003</year>
+ <price>39.95</price>
+ </book>
+</bookstore>
+```
+
+## 적격성과 유효성
+
+XML 문서는 문법적으로 정확할 경우 *적격*합니다. 하지만 문서 유형 정의(DTD)를 이용하여 문서에 제약을 더 추가할 수 있습니다. 한 문서의 요소와 속성이 DTD 안에 정의되어 있고 그 파일에 특정된 문법을 따른다면 *적격*할 뿐만 아니라 그 DTD에 대하여 *유효*하다고 말합니다.
+
+```xml
+<!-- DTD를 외부에 선언: -->
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE bookstore SYSTEM "Bookstore.dtd">
+<!-- bookstore가 루트 요소이며 'Bookstore.dtd'가 DTD 파일의
+ 경로임을 선언합니다. -->
+<bookstore>
+ <book category="COOKING">
+ <title lang="en">Everyday Italian</title>
+ <author>Giada De Laurentiis</author>
+ <year>2005</year>
+ <price>30.00</price>
+ </book>
+</bookstore>
+
+<!-- DTD 파일 -->
+<!ELEMENT bookstore (book+)>
+<!-- bookstore 요소는 하나 이상의 book 요소를 자식으로 가질 수 있습니다. -->
+<!ELEMENT book (title, price)>
+<!-- 각각의 book은 title과 price를 자식으로 반드시 갖습니다. -->
+<!ATTLIST book category CDATA "Literature">
+<!-- book은 category 속성을 가져야 합니다. 그렇지 않다면 그 기본값은 'Literature'입니다. -->
+<!ELEMENT title (#PCDATA)>
+<!-- title 요소는 반드시 PCDATA만 포함해야 합니다. 즉,
+ 파서가 읽을 텍스트만을 포함해야 하며 자식을 포함할 수 없습니다.
+ CDATA와 비교해 보세요. -->
+<!ELEMENT price (#PCDATA)>
+]>
+
+<!-- DTD는 XML 파일 안에 선언될 수도 있습니다. -->
+
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!DOCTYPE bookstore [
+<!ELEMENT bookstore (book+)>
+<!ELEMENT book (title, price)>
+<!ATTLIST book category CDATA "Literature">
+<!ELEMENT title (#PCDATA)>
+<!ELEMENT price (#PCDATA)>
+]>
+
+<bookstore>
+ <book category="COOKING">
+ <title>Everyday Italian</title>
+ <price>30.00</price>
+ </book>
+</bookstore>
+```
+
+## DTD 호환성과 XML 스키마 정의
+
+DTD는 오래되었기 때문에 지원이 광범위합니다. 불행히도 네임스페이스와 같은 현대적 XML 기능은 DTD에서 지원하지 않습니다. XML 스키마 정의(XSD)가 XML 문서의 문법을 정의하기 위한 DTD의 대체재입니다.
+
+## Resources
+
+* [(영어) Validate your XML](http://www.xmlvalidation.com)
+
+## Further Reading
+
+* [(영어) XML 스키마 정의 튜토리얼](http://www.w3schools.com/xml/xml_schema.asp)
+* [(영어) DTD 튜토리얼](http://www.w3schools.com/xml/xml_dtd_intro.asp)
+* [(영어) XML 튜토리얼](http://www.w3schools.com/xml/default.asp)
+* [(영어) XPath 쿼리로 XML 파싱하기](http://www.w3schools.com/xml/xml_xpath.asp)
diff --git a/ko-kr/yaml-kr.html.markdown b/ko-kr/yaml-kr.html.markdown
new file mode 100644
index 00000000..b6d1de41
--- /dev/null
+++ b/ko-kr/yaml-kr.html.markdown
@@ -0,0 +1,172 @@
+---
+language: yaml
+filename: learnyaml-kr.yaml
+contributors:
+ - ["Adam Brenecki", "https://github.com/adambrenecki"]
+ - ["Suhas SG", "https://github.com/jargnar"]
+translators:
+ - ["Wooseop Kim", "https://github.com/linterpreteur"]
+lang: ko-kr
+---
+
+YAML은 인간이 직접 쓰고 읽을 수 있도록 설계된 데이터 직렬화 언어입니다.
+
+YAML은 마치 파이썬처럼 개행과 들여쓰기에 문법적으로 의미를 준 JSON의 엄격한 수퍼셋입니다.
+하지만 파이썬과는 달리 YAML은 탭 문자를 전혀 허용하지 않습니다.
+
+```yaml
+# YAML의 주석은 이런 식입니다.
+
+############
+# 스칼라 형 #
+############
+
+# 문서 내내 이어질 루트 객체는 맵입니다.
+# 맵은 다른 언어의 딕셔너리, 해시, 혹은 객체에 해당됩니다.
+키: 값
+다른_키: 다른 값이 여기 옵니다.
+숫자_값: 100
+# 숫자 1을 값으로 가지기 위해서는 따옴표에 담아야 합니다.
+# 그러지 않는다면 YAML 파서는 그것을 참 값을 가지는 불리언으로 해석할 것입니다.
+과학적_표기법: 1e+12
+불리언: true
+널_값: null
+띄어서 쓴 키: 값
+# 문자열에 따옴표를 칠 필요는 없습니다. 하지만 칠 수도 있습니다.
+하지만: "따옴표에 담은 문자열"
+"키도 따옴표에 담을 수 있습니다.": "키에 ':'을 넣고 싶다면 유용합니다."
+
+# 여러 줄의 문자열은 (|을 이용한) '리터럴 블락' 혹은 (>을 이용한) '접은 블락'으로
+# 쓸 수 있습니다.
+리터럴_블락: |
+ 개행을 포함한 이 모든 덩어리가 '리터럴_블락' 키에 대응하는 값이 될 것입니다.
+
+ 리터럴 값은 들여쓰기가 끝날 때까지 계속되며 들여쓰기는 문자열에 포함되지
+ 않습니다.
+
+ '들여쓰기를 더 한' 줄은 나머지 들여쓰기를 유지합니다.
+ 이 줄은 띄어쓰기 4개만큼 들여쓰기 됩니다.
+접는_방식: >
+ 이 텍스트 덩어리가 전부 '접는_방식' 키의 값이 되지만, 이번에는 모든 개행 문자가
+ 띄어쓰기 하나로 대체됩니다.
+
+ 위와 같이 텅 빈 줄은 개행 문자로 바뀝니다.
+
+ '더 들여쓴' 줄 역시 개행 문자를 유지합니다.
+ 이 텍스트는 두 줄에 걸쳐 나타날 것입니다.
+
+##########
+# 모임 형 #
+##########
+
+# 중첩은 들여쓰기로 가능합니다.
+중첩된_맵:
+ 키: 값
+ 다른_키: 다른 값
+ 다른_중첩된_맵:
+ 안녕: 안녕
+
+# 맵은 반드시 문자열 키를 가지는 것은 아닙니다.
+0.25: 실수형 키
+
+# 키는 여러 줄에 걸친 객체와 같이 복합적일 수도 있습니다.
+# ?와 그 뒤의 띄어쓰기로 복합 키의 시작을 나타냅니다.
+? |
+ 여러 줄짜리
+ 키
+: 그리고 그 값
+
+# YAML은 복합 키 문법으로 연속열 간의 매핑을 지원합니다.
+# 일부 파서는 지원하지 않을 수 있습니다.
+# 예시
+? - 맨체스터 유나이티드
+ - 레알 마드리드
+: [ 2001-01-01, 2002-02-02 ]
+
+# 리스트 혹은 배열에 대응되는 연속열은 다음과 같습니다.
+연속열:
+ - 하나
+ - 둘
+ - 0.5 # 연속열은 다른 형을 포함 가능
+ - 넷
+ - 키: 값
+ 다른_키: 다른_값
+ -
+ - 연속열 안의
+ - 또 다른 연속열
+
+# YAML은 JSON의 수퍼셋이기 때문에, JSON식으로 맵과 연속열을 작성할 수도
+# 있습니다.
+제이슨_맵: {"키": "값"}
+제이슨_열: [3, 2, 1, "발사"]
+
+#################
+# 기타 YAML 기능 #
+#################
+
+# YAML은 '앵커'라는 편리한 기능이 있습니다. 앵커를 이용하면 문서에서
+# 손쉽게 내용을 복제할 수 있습니다. 이 키들은 같은 값을 갖습니다.
+앵커된_내용: &앵커_이름 이 문자열은 두 키의 값으로 나타납니다.
+다른_앵커: *앵커_이름
+
+# 앵커는 속성을 복제하거나 상속할 수 있습니다.
+기반: &기반
+ 이름: 모두 이름이 같다
+
+멍멍: &멍멍
+ <<: *기반
+ 나이: 10
+
+야옹: &야옹
+ <<: *기반
+ 나이: 20
+
+# 멍멍이와 야옹이는 같은 이름, '모두 이름이 같다'를 같습니다.
+
+# 또한 YAML에는 명시적으로 형을 선언할 수 있는 태그가 있습니다.
+명시적_문자열: !!str 0.5
+# 파이썬의 복소수 형을 나타내는 다음 태그처럼, 일부 파서는 언어에 종속된 태그를
+# 구현합니다.
+파이썬_복소수: !!python/complex 1+2j
+
+# YAML 복합 키를 언어 종속 태그와 함께 사용할 수도 있습니다.
+? !!python/tuple [5, 7]
+: 오십칠
+# 파이썬에서의 {(5, 7): '오십칠'} 객체
+
+###############
+# 기타 YAML 형 #
+###############
+
+# Strings and numbers aren't the only scalars that YAML can understand.
+# YAML이 이해할 수 있는 스칼라는 문자열과 수만 있는 것은 아닙니다.
+# ISO 형식 날짜와 시간 리터럴 또한 해석됩니다.
+시간: 2001-12-15T02:59:43.1Z
+띄어쓰기_한_시간: 2001-12-14 21:59:43.10 -5
+날짜: 2002-12-14
+
+# !!binary 태그는 문자열이 실제로는 base64로 인코딩된
+# 이진수 객체(BLOB)라는 것을 나타냅니다.
+이미지_파일: !!binary |
+ R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
+ OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+ +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
+ AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
+
+# YAML에는 다음과 같은 집합도 있습니다.
+집합:
+ ? 하나
+ ? 둘
+ ? 셋
+
+# 파이썬과 마찬가지로 집합은 단지 널 값을 갖는 맵입니다. 위는 다음과 같습니다.
+집합2:
+ 하나: null
+ 둘: null
+ 셋: null
+```
+
+### 더 읽기
+
++ [(영어) YAML 공식 사이트](http://yaml.org/)
++ [(영어) 온라인 YAML 검사기](http://codebeautify.org/yaml-validator)
diff --git a/latex.html.markdown b/latex.html.markdown
index bb84a6d9..a3866892 100644
--- a/latex.html.markdown
+++ b/latex.html.markdown
@@ -117,7 +117,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 y that belong to X, $\forall$ x $\in$ X. \\
+Here's how you state all x that belong to X, $\forall$ x $\in$ X. \\
% Notice how I needed to add $ signs before and after the symbols. This is
% because when writing, we are in text-mode.
% However, the math symbols only exist in math-mode.
@@ -128,7 +128,7 @@ Here's how you state all y that belong to X, $\forall$ x $\in$ X. \\
\[a^2 + b^2 = c^2 \]
My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$.
-I haven't found a Greek letter that yet that \LaTeX \hspace{1pt} doesn't know
+I haven't found a Greek letter yet that \LaTeX \hspace{1pt} doesn't know
about! \\
Operators are essential parts of a mathematical document:
@@ -148,7 +148,7 @@ $$ ^{10}/_{7} $$
% \frac{numerator}{denominator}
$$ \frac{n!}{k!(n - k)!} $$ \\
-We can also insert equations in an "equation environment".
+We can also insert equations in an ``equation environment''.
% Display math with the equation 'environment'
\begin{equation} % enters math-mode
@@ -223,7 +223,7 @@ and look at the glorious glory that is a \LaTeX \hspace{1pt} pdf.
Getting to the final document using \LaTeX \hspace{1pt} consists of the following
steps:
\begin{enumerate}
- \item Write the document in plain text (the "source code").
+ \item Write the document in plain text (the ``source code'').
\item Compile source code to produce a pdf.
The compilation step looks like this (in Linux): \\
\begin{verbatim}
@@ -233,7 +233,10 @@ steps:
A number of \LaTeX \hspace{1pt}editors combine both Step 1 and Step 2 in the
same piece of software. So, you get to see Step 1, but not Step 2 completely.
-Step 2 is still happening behind the scenes.
+Step 2 is still happening behind the scenes\footnote{In cases, where you use
+references (like Eqn.~\ref{eq:pythagoras}), you may need to run Step 2
+multiple times, to generate an intermediary *.aux file.}.
+% Also, this is how you add footnotes to your document!
You write all your formatting information in plain text in Step 1.
The compilation part in Step 2 takes care of producing the document in the
diff --git a/less.html.markdown b/less.html.markdown
index d88b6ee9..1b26eb99 100644
--- a/less.html.markdown
+++ b/less.html.markdown
@@ -6,7 +6,7 @@ contributors:
---
Less is a CSS pre-processor, that adds features such as variables, nesting, mixins and more.
-Less (and other preprocessors, such as [Sass](http://sass-lang.com/) help developers to write maintainable and DRY (Don't Repeat Yourself) code.
+Less (and other preprocessors, such as [Sass](http://sass-lang.com/)) help developers to write maintainable and DRY (Don't Repeat Yourself) code.
```css
@@ -16,20 +16,20 @@ Less (and other preprocessors, such as [Sass](http://sass-lang.com/) help develo
/*Multi line comments are preserved. */
-/*Variables
-==============================*/
+/* Variables
+==============================*/
/* You can store a CSS value (such as a color) in a variable.
-Use the '@' symbol to create a variable. */
+ Use the '@' symbol to create a variable. */
@primary-color: #a3a4ff;
@secondary-color: #51527f;
@body-font: 'Roboto', sans-serif;
/* You can use the variables throughout your stylesheet.
-Now if you want to change a color, you only have to make the change once.*/
+ Now if you want to change a color, you only have to make the change once.*/
body {
background-color: @primary-color;
@@ -38,6 +38,7 @@ body {
}
/* This would compile to: */
+
body {
background-color: #a3a4ff;
color: #51527F;
@@ -46,16 +47,16 @@ body {
/* This is much more maintainable than having to change the color
-each time it appears throughout your stylesheet. */
+ each time it appears throughout your stylesheet. */
-/*Mixins
-==============================*/
+/* Mixins
+==============================*/
/* If you find you are writing the same code for more than one
-element, you might want to reuse that easily.*/
+ element, you might want to reuse that easily.*/
.center {
display: block;
@@ -72,7 +73,8 @@ div {
background-color: @primary-color;
}
-/*Which would compile to: */
+/* Which would compile to: */
+
.center {
display: block;
margin-left: auto;
@@ -105,7 +107,7 @@ div {
background-color: @primary-color;
}
-/*Which would compile to: */
+/* Which would compile to: */
div {
display: block;
margin-left: auto;
@@ -116,12 +118,12 @@ div {
}
-/*Nesting
-==============================*/
+/* Nesting
+==============================*/
-/*Less allows you to nest selectors within selectors */
+/* Less allows you to nest selectors within selectors */
ul {
list-style-type: none;
@@ -135,8 +137,8 @@ ul {
/* '&' will be replaced by the parent selector. */
/* You can also nest pseudo-classes. */
/* Keep in mind that over-nesting will make your code less maintainable.
-Best practices recommend going no more than 3 levels deep when nesting.
-For example: */
+ Best practices recommend going no more than 3 levels deep when nesting.
+ For example: */
ul {
list-style-type: none;
@@ -175,16 +177,17 @@ ul li a {
}
-/*Functions
-==============================*/
+/* Functions
+==============================*/
/* Less provides functions that can be used to accomplish a variety of
- tasks. Consider the following */
+ tasks. Consider the following: */
/* Functions can be invoked by using their name and passing in the
- required arguments */
+ required arguments. */
+
body {
width: round(10.25px);
}
@@ -215,11 +218,10 @@ body {
mixins. When trying to choose between a function or a mixin, remember
that mixins are best for generating CSS while functions are better for
logic that might be used throughout your Less code. The examples in
- the Math Operators' section are ideal candidates for becoming a reusable
+ the 'Math Operators' section are ideal candidates for becoming a reusable
function. */
-/* This function will take a target size and the parent size and calculate
- and return the percentage */
+/* This function calculates the average of two numbers: */
.average(@x, @y) {
@average-result: ((@x + @y) / 2);
@@ -236,11 +238,12 @@ div {
padding: 33px;
}
+
+
/*Extend (Inheritance)
==============================*/
-
/*Extend is a way to share the properties of one selector with another. */
.display {
@@ -269,11 +272,11 @@ div {
add unnecessary bloat to the files created by the Less compiler. */
+
/*Partials and Imports
==============================*/
-
/* Less allows you to create partial files. This can help keep your Less
code modularized. Partial files conventionally begin with an '_',
e.g. _reset.less. and are imported into a main less file that gets
@@ -314,9 +317,9 @@ body {
}
-/*Math Operations
-==============================*/
+/* Math Operations
+==============================*/
/* Less provides the following operators: +, -, *, /, and %. These can
@@ -377,9 +380,7 @@ If you want to play with Less in your browser, check out:
## Compatibility
-Less can be used in any project as long as you have a program to compile it
-into CSS. You'll want to verify that the CSS you're using is compatible
-with your target browsers.
+Less can be used in any project as long as you have a program to compile it into CSS. You'll want to verify that the CSS you're using is compatible with your target browsers.
[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility.
diff --git a/logtalk.html.markdown b/logtalk.html.markdown
index 4f7a207b..385e38f9 100644
--- a/logtalk.html.markdown
+++ b/logtalk.html.markdown
@@ -13,14 +13,12 @@ To keep its size reasonable, this tutorial necessarily assumes that the reader h
Logtalk uses standard Prolog syntax with the addition of a few operators and directives for a smooth learning curve and wide portability. One important consequence is that Prolog code can be easily encapsulated in objects with little or no changes. Moreover, Logtalk can transparently interpret most Prolog modules as Logtalk objects.
-Some of the most important operators are:
+The main operators are:
* `::/2` - sending a message to an object
* `::/1` - sending a message to _self_ (i.e. to the object that received the message being processed)
* `^^/1` - _super_ call (of an inherited or imported predicate)
-* `<</2` - debugging context switch call (allows calling a predicate from within an object)
-
Some of the most important entity and predicate directives will be introduced in the next sections.
# Entities and roles
@@ -29,7 +27,7 @@ Logtalk provides _objects_, _protocols_, and _categories_ as first-class entitie
# Defining an object
-An object encapsulates predicate declarations and definitions. Objects can be created dynamically but are usually static and defined in source files. A single source file can contain any number of entity definitions. A simple object, defining a list member public predicate:
+An object encapsulates predicate declarations and definitions. Objects can be created dynamically but are usually static and defined in source files. A single source file can contain any number of entity definitions. A simple object, defining a list member public predicate:
```
:- object(list).
@@ -44,7 +42,7 @@ An object encapsulates predicate declarations and definitions. Objects can be cr
# Compiling source files
-Assuming that the code above for the `list` object is saved in a `list.lgt` file, it can be compiled and loaded using the `logtalk_load/1` built-in predicates or its abbreviation, `{}/1`, with the file path as argument (the extension can be omitted):
+Assuming that the code above for the `list` object is saved in a `list.lgt` file, it can be compiled and loaded using the `logtalk_load/1` built-in predicate or its abbreviation, `{}/1`, with the file path as argument (the extension can be omitted):
```
?- {list}.
@@ -82,23 +80,37 @@ Assuming the object is saved in a `scopes.lgt` file:
?- {scopes}.
yes
-?- scopes::bar.
-error(permission_error(access,private_predicate,bar/0),logtalk(scopes::bar,user))
+?- catch(scopes::bar, Error, true).
+Error = error(
+ permission_error(access, private_predicate, bar/0),
+ logtalk(scopes::bar, user)
+)
+yes
-?- scopes::local.
-error(existence_error(predicate_declaration,local/0),logtalk(scopes::local,user))
+?- catch(scopes::local, Error, true).
+Error = error(
+ existence_error(predicate_declaration, local/0),
+ logtalk(scopes::local, user)
+)
+yes
```
When the predicate in a message is unknown for the object (the role it plays determines the lookup procedures), we also get an error. For example:
```
-?- scopes::unknown.
-error(existence_error(predicate_declaration,unknown/0),logtalk(scopes::unknown,user))
+?- catch(scopes::unknown, Error, true).
+Error = error(
+ existence_error(predicate_declaration, unknown/0),
+ logtalk(scopes::unknown, user)
+)
+yes
```
+A subtle point is that predicate scope directives specify predicate _calling_ semantics, not _definitions_ semantics. For example, if an object playing the role of a class declares a predicate private, the predicate can be defined in subclasses and instances *but* can only be called in its instances _from_ the class.
+
# Defining and implementing a protocol
-Protocols contain predicate declarations that can be implemented by objects and categories:
+Protocols contain predicate declarations that can be implemented by any number of objects and categories:
```
:- protocol(listp).
@@ -126,11 +138,11 @@ The scope of the protocol predicates can be restricted using protected or privat
:- end_object.
```
-In fact, all entity relations can be qualified as public (the default), protected, or private.
+In fact, all entity relations (in an entity opening directive) can be qualified as public (the default), protected, or private.
# Prototypes
-An object without an _instantiation_ or _specialization_ relation with another object plays the role of a prototype. A prototype can _extend_ another object, its parent prototype.
+An object without an _instantiation_ or _specialization_ relation with another object plays the role of a prototype. A prototype can _extend_ another object, its parent prototype.
```
% clyde, our prototypical elephant
@@ -186,8 +198,10 @@ no
?- catch(foo::baz, Error, true).
Error = error(
- existence_error(predicate_declaration,baz/0), logtalk(foo::baz,user)
-).
+ existence_error(predicate_declaration, baz/0),
+ logtalk(foo::baz, user)
+)
+yes
```
# Classes and instances
@@ -195,9 +209,9 @@ Error = error(
In order to define objects playing the role of classes and/or instances, an object must have at least an instantiation or a specialization relation with another object. Objects playing the role of meta-classes can be used when we need to see a class also as an instance. We use the following example to also illustrate how to dynamically create new objects at runtime:
```
-% a simple, generic, meta-class defining a new/2 predicate for its instances
-:- object(class,
- instantiates(class)).
+% a simple, generic, metaclass defining a new/2 predicate for its instances
+:- object(metaclass,
+ instantiates(metaclass)).
:- public(new/2).
new(Instance, Clauses) :-
@@ -208,7 +222,7 @@ In order to define objects playing the role of classes and/or instances, an obje
% a simple class defining age/1 and name/1 predicate for its instances
:- object(person,
- instantiates(class)).
+ instantiates(metaclass)).
:- public([
age/1, name/1
@@ -251,7 +265,7 @@ yes
# Categories
-A category is a fine grained unit of code reuse, used to encapsulate a _cohesive_ set of predicate declarations and definitions, implementing a _single_ functionality, that can be imported into any object. A category can thus be seen as the dual concept of a protocol. In the following example, we define categories representing car engines and then import them into car objects:
+A category is a fine grained unit of code reuse, used to encapsulate a _cohesive_ set of predicate declarations and definitions, implementing a _single_ functionality, that can be imported into any object. A category can thus be seen as the dual concept of a protocol. In the following example, we define categories representing car engines and then import them into car objects:
```
% a protocol describing engine characteristics
@@ -305,7 +319,7 @@ A category is a fine grained unit of code reuse, used to encapsulate a _cohesive
:- end_object.
```
-Categories are independently compiled and thus allow importing objects to be updated by simple updating the imported categories without requiring object recompilation. Categories also provide _runtime transparency_:
+Categories are independently compiled and thus allow importing objects to be updated by simple updating the imported categories without requiring object recompilation. Categories also provide _runtime transparency_. I.e. the category protocol adds to the protocol of the objects importing the category:
```
?- sedan::current_predicate(Predicate).
@@ -365,6 +379,8 @@ bar
yes
```
+As hot-patching forcefully breaks encapsulation, there is a `complements` compiler flag that can be set (globally or on a per-object basis) to allow, restrict, or prevent it.
+
# Parametric objects and categories
Objects and categories can be parameterized by using as identifier a compound term instead of an atom. Object and category parameters are _logical variables_ shared with all encapsulated predicates. An example with geometric circles:
@@ -395,7 +411,7 @@ Area = 4.75291
yes
```
-Parametric objects also provide a simple way of associating a set of predicates with a Prolog predicate. Prolog facts can be interpreted as _parametric object proxies_ when they have the same functor and arity as the identifiers of parametric objects. Handy syntax is provided to for working with proxies. For example, assuming the following clauses for a `circle/2` predicate:
+Parametric objects also provide a simple way of associating a set of predicates with a plain Prolog predicate. Prolog facts can be interpreted as _parametric object proxies_ when they have the same functor and arity as the identifiers of parametric objects. Handy syntax is provided to for working with proxies. For example, assuming the following clauses for a `circle/2` predicate:
```
circle(1.23, blue).
@@ -413,6 +429,8 @@ Areas = [4.75291, 43.2412, 0.477836, 103.508, 217.468]
yes
```
+The `{Goal}::Message` construct proves `Goal`, possibly instantiating any variables in it, and sends `Message` to the resulting term.
+
# Events and monitors
Logtalk supports _event-driven programming_ by allowing defining events and monitors for those events. An event is simply the sending of a message to an object. Interpreting message sending as an atomic activity, a _before_ event and an _after_ event are recognized. Event monitors define event handler predicates, `before/3` and `after/3`, and can query, register, and delete a system-wide event registry that associates events with monitors. For example, a simple tracer for any message being sent using the `::/2` control construct can be defined as:
@@ -449,6 +467,10 @@ X = 3
yes
```
+Events can be set and deleted dynamically at runtime by calling the `define_events/5` and `abolish_events/5` built-in predicates.
+
+Event-driven programming can be seen as a form of _computational reflection_. But note that events are only generated when using the `::/2` message-sending control construct.
+
# Lambda expressions
Logtalk supports lambda expressions. Lambda parameters are represented using a list with the `(>>)/2` infix operator connecting them to the lambda. Some simple examples using library meta-predicates:
@@ -470,6 +492,7 @@ Ys = [2,4,6]
yes
```
+Lambda free variables can be expressed using the extended syntax `{Free1, ...}/[Parameter1, ...]>>Lambda`.
# Macros
@@ -486,21 +509,21 @@ Terms and goals in source files can be _expanded_ at compile time by specifying
:- end_object.
```
-Let's define an hook object, saved in a `my_macros.lgt` file, that changes clauses and calls to the `foo/1` local predicate:
+Assume the following hook object, saved in a `my_macros.lgt` file, that expands clauses and calls to the `foo/1` local predicate:
```
:- object(my_macros,
- implements(expanding)). % built-in protocol for expanding predicates
+ implements(expanding)). % built-in protocol for expanding predicates
term_expansion(foo(Char), baz(Code)) :-
- char_code(Char, Code). % standard built-in predicate
+ char_code(Char, Code). % standard built-in predicate
goal_expansion(foo(X), baz(X)).
:- end_object.
```
-After loading the macros file, we can then expand our source file with it:
+After loading the macros file, we can then expand our source file with it using the `hook` compiler flag:
```
?- logtalk_load(my_macros), logtalk_load(source, [hook(my_macros)]).
diff --git a/matlab.html.markdown b/matlab.html.markdown
index 51b7bd4e..86b116c6 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -557,6 +557,8 @@ c = a + b
## More on Matlab
-* The official website [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/)
-* The official MATLAB Answers forum: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/)
+* [The official website](http://www.mathworks.com/products/matlab/)
+* [The official MATLAB Answers forum](http://www.mathworks.com/matlabcentral/answers/)
+* [Loren on the Art of MATLAB](http://blogs.mathworks.com/loren/)
+* [Cleve's Corner](http://blogs.mathworks.com/cleve/)
diff --git a/messagepack.html.markdown b/messagepack.html.markdown
new file mode 100644
index 00000000..9234332f
--- /dev/null
+++ b/messagepack.html.markdown
@@ -0,0 +1,172 @@
+---
+category: tool
+tool: messagepack
+filename: learnmessagepack.mpac
+contributors:
+ - ["Gabriel Chuan", "https://github.com/gczh"]
+---
+
+MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. The benefits over other formats is that it's faster and smaller.
+
+In MessagePack, small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves. This makes MessagePack useful for efficient transmission over wire.
+
+```
+
+# 0. Understanding The Structure ====
+
+JSON, 40 Bytes UTF-8
+
+----------------------------------------------
+| {"name":"John Doe","age":12} |
+----------------------------------------------
+| {" | 7B 22 |
+| name | 6E 61 6D 65 |
+| ":" | 22 3A 22 |
+| John Doe | 4A 6F 68 6E 20 44 6F 65 |
+| "," | 22 2C 22 |
+| age | 61 67 65 |
+| ": | 22 3A 20 |
+| 12 | 31 32 |
+| } | 7D |
+----------------------------------------------
+
+
+MessagePack, 27 Bytes UTF-8
+
+----------------------------------------------
+| ‚¤name¨John Doe£age.12 |
+----------------------------------------------
+| ‚¤ | 82 84 |
+| name | 6E 61 6D 65 |
+| ¨ | A8 |
+| John Doe | 4A 6F 68 6E 20 44 6F 65 |
+| £ | A3 |
+| age | 61 67 65 |
+| . | 0C |
+| 12 | 31 32 |
+----------------------------------------------
+
+# 1. JAVA ====
+
+""" Installing with Maven
+"""
+
+<dependencies>
+ ...
+ <dependency>
+ <groupId>org.msgpack</groupId>
+ <artifactId>msgpack</artifactId>
+ <version>${msgpack.version}</version>
+ </dependency>
+ ...
+</dependencies>
+
+
+""" Simple Serialization/Deserialization
+"""
+
+// Create serialize objects.
+List<String> src = new ArrayList<String>();
+src.add("msgpack");
+src.add("kumofs");
+
+MessagePack msgpack = new MessagePack();
+// Serialize
+byte[] raw = msgpack.write(src);
+
+// Deserialize directly using a template
+List<String> dst1 = msgpack.read(raw, Templates.tList(Templates.TString));
+System.out.println(dst1.get(0));
+System.out.println(dst1.get(1));
+
+// Or, Deserialze to Value then convert type.
+Value dynamic = msgpack.read(raw);
+List<String> dst2 = new Converter(dynamic)
+ .read(Templates.tList(Templates.TString));
+System.out.println(dst2.get(0));
+System.out.println(dst2.get(1));
+
+
+# 2. RUBY ====
+
+""" Installing the Gem
+"""
+
+gem install msgpack
+
+""" Streaming API
+"""
+
+# serialize a 2-element array [e1, e2]
+pk = MessagePack::Packer.new(io)
+pk.write_array_header(2).write(e1).write(e2).flush
+
+# deserialize objects from an IO
+u = MessagePack::Unpacker.new(io)
+u.each { |obj| ... }
+
+# event-driven deserialization
+def on_read(data)
+ @u ||= MessagePack::Unpacker.new
+ @u.feed_each(data) { |obj| ... }
+end
+
+# 3. NODE.JS ====
+
+""" Installing with NPM
+"""
+
+npm install msgpack5 --save
+
+""" Using in Node
+"""
+
+var msgpack = require('msgpack5')() // namespace our extensions
+ , a = new MyType(2, 'a')
+ , encode = msgpack.encode
+ , decode = msgpack.decode
+
+msgpack.register(0x42, MyType, mytipeEncode, mytipeDecode)
+
+console.log(encode({ 'hello': 'world' }).toString('hex'))
+// 81a568656c6c6fa5776f726c64
+console.log(decode(encode({ 'hello': 'world' })))
+// { hello: 'world' }
+console.log(encode(a).toString('hex'))
+// d5426161
+console.log(decode(encode(a)) instanceof MyType)
+// true
+console.log(decode(encode(a)))
+// { value: 'a', size: 2 }
+
+function MyType(size, value) {
+ this.value = value
+ this.size = size
+}
+
+function mytipeEncode(obj) {
+ var buf = new Buffer(obj.size)
+ buf.fill(obj.value)
+ return buf
+}
+
+function mytipeDecode(data) {
+ var result = new MyType(data.length, data.toString('utf8', 0, 1))
+ , i
+
+ for (i = 0; i < data.length; i++) {
+ if (data.readUInt8(0) != data.readUInt8(i)) {
+ throw new Error('should all be the same')
+ }
+ }
+
+ return result
+}
+
+```
+
+
+# References
+
+- [MessagePack](http://msgpack.org/index.html)
+- [MsgPack vs. JSON: Cut your client-server exchange traffic by 50% with one line of code](http://indiegamr.com/cut-your-data-exchange-traffic-by-up-to-50-with-one-line-of-code-msgpack-vs-json/)
diff --git a/nl-nl/xml-nl.html.markdown b/nl-nl/xml-nl.html.markdown
index 930f7cf4..832de821 100644
--- a/nl-nl/xml-nl.html.markdown
+++ b/nl-nl/xml-nl.html.markdown
@@ -2,7 +2,7 @@
language: xml
filename: learnxml-nl.xml
contributors:
- - ["Joo Farias", "https://github.com/JoaoGFarias"]
+ - ["João Farias", "https://github.com/JoaoGFarias"]
translators:
- ["Frank van Gemeren", "https://github.com/frvge"]
lang: nl-nl
@@ -131,4 +131,4 @@ controleren.
<prijs>30.00</prijs>
</boek>
</boekenwinkel>
-``` \ No newline at end of file
+```
diff --git a/perl6.html.markdown b/perl6.html.markdown
index b5a25a41..34ad70b7 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -1,9 +1,10 @@
---
category: language
language: perl6
-filename: learnperl6.pl
+filename: learnperl6.p6
contributors:
- ["vendethiel", "http://github.com/vendethiel"]
+ - ["Samantha McVey", "https://cry.nu"]
---
Perl 6 is a highly capable, feature-rich programming language made for at
@@ -37,11 +38,11 @@ my $str = 'String';
# double quotes allow for interpolation (which we'll see later):
my $str2 = "String";
-# variable names can contain but not end with simple quotes and dashes,
-# and can contain (and end with) underscores :
+# Variable names can contain but not end with simple quotes and dashes,
+# and can contain (and end with) underscores :
# my $weird'variable-name_ = 5; # works !
-my $bool = True; # `True` and `False` are Perl 6's boolean
+my $bool = True; # `True` and `False` are Perl 6's boolean values.
my $inverse = !$bool; # You can invert a bool with the prefix `!` operator
my $forced-bool = so $str; # And you can use the prefix `so` operator
# which turns its operand into a Bool
@@ -56,28 +57,32 @@ my @array = 1, 2, 3;
say @array[2]; # Array indices start at 0 -- This is the third element
-say "Interpolate an array using [] : @array[]";
-#=> Interpolate an array using [] : 1 2 3
+say "Interpolate all elements of an array using [] : @array[]";
+#=> Interpolate all elements of an array using [] : 1 2 3
@array[0] = -1; # Assign a new value to an array index
@array[0, 1] = 5, 6; # Assign multiple values
my @keys = 0, 2;
-@array[@keys] = @letters; # Assign using an array
+@array[@keys] = @letters; # Assignment using an array containing index values
say @array; #=> a 6 b
## * Hashes, or key-value Pairs.
-# Hashes are actually arrays of Pairs
-# (you can construct a Pair object using the syntax `Key => Value`),
-# except they get "flattened" (hash context), removing duplicated keys.
+# Hashes are pairs of keys and values.
+# You can construct a Pair object using the syntax `Key => Value`.
+# Hash tables are very fast for lookup, and are stored unordered.
+# Keep in mind that keys get "flattened" in hash context, and any duplicated
+# keys are deduplicated.
my %hash = 1 => 2,
3 => 4;
my %hash = foo => "bar", # keys get auto-quoted
"some other" => "value", # trailing commas are okay
;
-my %hash = <key1 value1 key2 value2>; # you can also create a hash
- # from an even-numbered array
-my %hash = key1 => 'value1', key2 => 'value2'; # same as this
+# Even though hashes are internally stored differently than arrays,
+# Perl 6 allows you to easily create a hash from an even numbered array:
+my %hash = <key1 value1 key2 value2>;
+
+my %hash = key1 => 'value1', key2 => 'value2'; # same result as above
# You can also use the "colon pair" syntax:
# (especially handy for named parameters that you'll see later)
@@ -92,7 +97,8 @@ say %hash{'key1'}; # You can use {} to get the value from a key
say %hash<key2>; # If it's a string, you can actually use <>
# (`{key1}` doesn't work, as Perl6 doesn't have barewords)
-## * Subs (subroutines, or functions in most other languages).
+## * Subs: subroutines or functions as most other languages call them are
+# created with the `sub` keyword.
sub say-hello { say "Hello, world" }
sub say-hello-to(Str $name) { # You can provide the type of an argument
@@ -193,6 +199,15 @@ sub mutate($n is rw) {
say "\$n is now $n !";
}
+my $m = 42;
+mutate $m; # $n is now 43 !
+
+# This works because we are passing the container $m to mutate. If we try
+# to just pass a number instead of passing a variable it won't work because
+# there is no container being passed and integers are immutable by themselves:
+
+mutate 42; # Parameter '$n' expected a writable container, but got Int value
+
# If what you want a copy instead, use `is copy`.
# A sub itself returns a container, which means it can be marked as rw:
@@ -228,10 +243,15 @@ unless False {
say "Quite truthy" if True;
# - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages)
-my $a = $condition ?? $value-if-true !! $value-if-false;
+# returns $value-if-true if the condition is true and $value-if-false
+# if it is false.
+# my $result = $value condition ?? $value-if-true !! $value-if-false;
-# - `given`-`when` looks like other languages' `switch`, but much more
-# powerful thanks to smart matching and thanks to Perl 6's "topic variable", $_.
+my $age = 30;
+say $age > 18 ?? "You are an adult" !! "You are under 18";
+
+# - `given`-`when` looks like other languages' `switch`, but is much more
+# powerful thanks to smart matching and Perl 6's "topic variable", $_.
#
# This variable contains the default argument of a block,
# a loop's current iteration (unless explicitly named), etc.
@@ -242,6 +262,7 @@ my $a = $condition ?? $value-if-true !! $value-if-false;
# Since other Perl 6 constructs use this variable (as said before, like `for`,
# blocks, etc), this means the powerful `when` is not only applicable along with
# a `given`, but instead anywhere a `$_` exists.
+
given "foo bar" {
say $_; #=> foo bar
when /foo/ { # Don't worry about smart matching yet – just know `when` uses it.
@@ -336,16 +357,37 @@ if long-computation() -> $result {
# - `eqv` is canonical equivalence (or "deep equality")
(1, 2) eqv (1, 3);
-# - `~~` is smart matching
+# - Smart Match Operator: `~~`
+# Aliases the left hand side to $_ and then evaluates the right hand side.
+# Here are some common comparison semantics:
+
+# String or Numeric Equality
+
+'Foo' ~~ 'Foo'; # True if strings are equal.
+12.5 ~~ 12.50; # True if numbers are equal.
+
+# Regex - For matching a regular expression against the left side.
+# Returns a (Match) object, which evaluates as True if regexp matches.
+
+my $obj = 'abc' ~~ /a/;
+say $obj; # 「a」
+say $obj.WHAT; # (Match)
+
+# Hashes
+'key' ~~ %hash; # True if key exists in hash
+
+# Type - Checks if left side "has type" (can check superclasses and roles)
+
+1 ~~ Int; # True
+
+# Smart-matching against a boolean always returns that boolean (and will warn).
+
+1 ~~ True; # True
+False ~~ True; # True
+
+# # General syntax is $arg ~~ &bool-returning-function;
# For a complete list of combinations, use this table:
# http://perlcabal.org/syn/S03.html#Smart_matching
-'a' ~~ /a/; # true if matches regexp
-'key' ~~ %hash; # true if key exists in hash
-$arg ~~ &bool-returning-function; # `True` if the function, passed `$arg`
- # as an argument, returns `True`.
-1 ~~ Int; # "has type" (check superclasses and roles)
-1 ~~ True; # smart-matching against a boolean always returns that boolean
- # (and will warn).
# You also, of course, have `<`, `<=`, `>`, `>=`.
# Their string equivalent are also avaiable : `lt`, `le`, `gt`, `ge`.
@@ -386,18 +428,22 @@ my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99;
say @numbers; #=> 0 1 2 3 4 3 9 15 21 [...] 81 87
# (only 20 values)
-## * And, Or
+## * And &&, Or ||
3 && 4; # 4, which is Truthy. Calls `.Bool` on `4` and gets `True`.
0 || False; # False. Calls `.Bool` on `0`
## * Short-circuit (and tight) versions of the above
-$a && $b && $c; # Returns the first argument that evaluates to False,
- # or the last argument.
-$a || $b;
+# Returns the first argument that evaluates to False, or the last argument.
+
+my ( $a, $b, $c ) = 1, 0, 2;
+$a && $b && $c; # Returns 0, the first False value
+
+# || Returns the first argument that evaluates to True
+$b || $a; # 1
# And because you're going to want them,
# you also have compound assignment operators:
-$a *= 2; # multiply and assignment
+$a *= 2; # multiply and assignment. Equivalent to $a = $a * 2;
$b %%= 5; # divisible by and assignment
@array .= sort; # calls the `sort` method and assigns the result back
@@ -408,19 +454,19 @@ $b %%= 5; # divisible by and assignment
## Unpacking !
# It's the ability to "extract" arrays and keys (AKA "destructuring").
# It'll work in `my`s and in parameter lists.
-my ($a, $b) = 1, 2;
-say $a; #=> 1
-my ($, $, $c) = 1, 2, 3; # keep the non-interesting anonymous
-say $c; #=> 3
+my ($f, $g) = 1, 2;
+say $f; #=> 1
+my ($, $, $h) = 1, 2, 3; # keep the non-interesting anonymous
+say $h; #=> 3
my ($head, *@tail) = 1, 2, 3; # Yes, it's the same as with "slurpy subs"
my (*@small) = 1;
-sub foo(@array [$fst, $snd]) {
+sub unpack_array(@array [$fst, $snd]) {
say "My first is $fst, my second is $snd ! All in all, I'm @array[].";
# (^ remember the `[]` to interpolate the array)
}
-foo(@tail); #=> My first is 2, my second is 3 ! All in all, I'm 2 3
+unpack_array(@tail); #=> My first is 2, my second is 3 ! All in all, I'm 2 3
# If you're not using the array itself, you can also keep it anonymous,
@@ -579,66 +625,95 @@ multi with-or-without-you {
### Scoping
-# In Perl 6, contrarily to many scripting languages (like Python, Ruby, PHP),
-# you are to declare your variables before using them. You know `my`.
-# (there are other declarators, `our`, `state`, ..., which we'll see later).
+# In Perl 6, unlike many scripting languages, (such as Python, Ruby, PHP),
+# you must declare your variables before using them. The `my` declarator
+# you have learned uses "lexical scoping". There are a few other declarators,
+# (`our`, `state`, ..., ) which we'll see later.
# This is called "lexical scoping", where in inner blocks,
# you can access variables from outer blocks.
-my $foo = 'Foo';
-sub foo {
- my $bar = 'Bar';
- sub bar {
- say "$foo $bar";
+my $file_scoped = 'Foo';
+sub outer {
+ my $outer_scoped = 'Bar';
+ sub inner {
+ say "$file_scoped $outer_scoped";
}
- &bar; # return the function
+ &inner; # return the function
}
-foo()(); #=> 'Foo Bar'
+outer()(); #=> 'Foo Bar'
-# As you can see, `$foo` and `$bar` were captured.
+# As you can see, `$file_scoped` and `$outer_scoped` were captured.
# But if we were to try and use `$bar` outside of `foo`,
# the variable would be undefined (and you'd get a compile time error).
-# Perl 6 has another kind of scope : dynamic scope.
-# They use the twigil (composed sigil) `*` to mark dynamically-scoped variables:
-my $*a = 1;
-# Dyamically-scoped variables depend on the current call stack,
-# instead of the current block depth.
-sub foo {
- my $*foo = 1;
- bar(); # call `bar` in-place
+### Twigils
+
+# There are many special `twigils` (composed sigil's) in Perl 6.
+# Twigils define the variables' scope.
+# The * and ? twigils work on standard variables:
+# * Dynamic variable
+# ? Compile-time variable
+# The ! and the . twigils are used with Perl 6's objects:
+# ! Attribute (class member)
+# . Method (not really a variable)
+
+# `*` Twigil: Dynamic Scope
+# These variables use the`*` twigil to mark dynamically-scoped variables.
+# Dynamically-scoped variables are looked up through the caller, not through
+# the outer scope
+
+my $*dyn_scoped_1 = 1;
+my $*dyn_scoped_2 = 10;
+
+sub say_dyn {
+ say "$*dyn_scoped_1 $*dyn_scoped_2";
}
-sub bar {
- say $*foo; # `$*foo` will be looked in the call stack, and find `foo`'s,
- # even though the blocks aren't nested (they're call-nested).
- #=> 1
+
+sub call_say_dyn {
+ my $*dyn_scoped_1 = 25; # Defines $*dyn_scoped_1 only for this sub.
+ $*dyn_scoped_2 = 100; # Will change the value of the file scoped variable.
+ say_dyn(); #=> 25 100 $*dyn_scoped 1 and 2 will be looked for in the call.
+ # It uses he value of $*dyn_scoped_1 from inside this sub's lexical
+ # scope even though the blocks aren't nested (they're call-nested).
}
+say_dyn(); #=> 1 10
+call_say_dyn(); #=> 25 100
+ # Uses $*dyn_scoped_1 as defined in call_say_dyn even though
+ # we are calling it from outside.
+say_dyn(); #=> 1 100 We changed the value of $*dyn_scoped_2 in call_say_dyn
+ # so now its value has changed.
### Object Model
-# You declare a class with the keyword `class`, fields with `has`,
-# methods with `method`. Every attribute that is private is named `$!attr`.
-# Immutable public attributes are named `$.attr`
+# To call a method on an object, add a dot followed by the method name:
+# => $object.method
+# Classes are declared with the `class` keyword. Attributes are declared
+# with the `has` keyword, and methods declared with `method`.
+# Every attribute that is private uses the ! twigil for example: `$!attr`.
+# Immutable public attributes use the `.` twigil.
# (you can make them mutable with `is rw`)
+# The easiest way to remember the `$.` twigil is comparing it to how methods
+# are called.
# Perl 6's object model ("SixModel") is very flexible,
# and allows you to dynamically add methods, change semantics, etc ...
-# (this will not be covered here, and you should refer to the Synopsis).
+# (these will not all be covered here, and you should refer to:
+# https://docs.perl6.org/language/objects.html.
-class A {
- has $.field; # `$.field` is immutable.
- # From inside the class, use `$!field` to modify it.
- has $.other-field is rw; # You can mark a public attribute `rw`.
- has Int $!private-field = 10;
+class Attrib-Class {
+ has $.attrib; # `$.attrib` is immutable.
+ # From inside the class, use `$!attrib` to modify it.
+ has $.other-attrib is rw; # You can mark a public attribute `rw`.
+ has Int $!private-attrib = 10;
method get-value {
- $.field + $!private-field;
+ $.attrib + $!private-attrib;
}
- method set-value($n) {
- # $.field = $n; # As stated before, you can't use the `$.` immutable version.
- $!field = $n; # This works, because `$!` is always mutable.
+ method set-value($param) { # Methods can take parameters
+ $!attrib = $param; # This works, because `$!` is always mutable.
+ # $.attrib = $param; # Wrong: You can't use the `$.` immutable version.
- $.other-field = 5; # This works, because `$.other-field` is `rw`.
+ $.other-attrib = 5; # This works, because `$.other-attrib` is `rw`.
}
method !private-method {
@@ -646,33 +721,44 @@ class A {
}
};
-# Create a new instance of A with $.field set to 5 :
-# Note: you can't set private-field from here (more later on).
-my $a = A.new(field => 5);
-$a.get-value; #=> 15
-#$a.field = 5; # This fails, because the `has $.field` is immutable
-$a.other-field = 10; # This, however, works, because the public field
- # is mutable (`rw`).
-
-## Perl 6 also has inheritance (along with multiple inheritance)
-
-class A {
- has $.val;
-
- submethod not-inherited {
- say "This method won't be available on B.";
- say "This is most useful for BUILD, which we'll see later";
+# Create a new instance of Attrib-Class with $.attrib set to 5 :
+# Note: you can't set private-attribute from here (more later on).
+my $class-obj = Attrib-Class.new(attrib => 5);
+say $class-obj.get-value; #=> 15
+#$class-obj.attrib = 5; # This fails, because the `has $.attrib` is immutable
+$class-obj.other-attrib = 10; # This, however, works, because the public
+ # attribute is mutable (`rw`).
+
+## Object Inheritance
+# Perl 6 also has inheritance (along with multiple inheritance)
+# While `method`'s are inherited, `submethod`'s are not.
+# Submethods are useful for object construction and destruction tasks,
+# such as BUILD, or methods that must be overriden by subtypes.
+# We will learn about BUILD later on.
+
+class Parent {
+ has $.age;
+ has $.name;
+ # This submethod won't be inherited by Child.
+ submethod favorite-color {
+ say "My favorite color is Blue";
}
-
- method bar { $.val * 5 }
+ # This method is inherited
+ method talk { say "Hi, my name is $!name" }
}
-class B is A { # inheritance uses `is`
- method foo {
- say $.val;
- }
-
- method bar { $.val * 10 } # this shadows A's `bar`
+# Inheritance uses the `is` keyword
+class Child is Parent {
+ method talk { say "Goo goo ga ga" }
+ # This shadows Parent's `talk` method, This child hasn't learned to speak yet!
}
+my Parent $Richard .= new(age => 40, name => 'Richard');
+$Richard.favorite-color; #=> "My favorite color is Blue"
+$Richard.talk; #=> "Hi, my name is Richard"
+# # $Richard is able to access the submethod, he knows how to say his name.
+
+my Child $Madison .= new(age => 1, name => 'Madison');
+$Madison.talk; # prints "Goo goo ga ga" due to the overrided method.
+# $Madison.favorite-color does not work since it is not inherited
# When you use `my T $var`, `$var` starts off with `T` itself in it,
# so you can call `new` on it.
@@ -680,11 +766,7 @@ class B is A { # inheritance uses `is`
# `$a .= b` is the same as `$a = $a.b`)
# Also note that `BUILD` (the method called inside `new`)
# will set parent properties too, so you can pass `val => 5`.
-my B $b .= new(val => 5);
-# $b.not-inherited; # This won't work, for reasons explained above
-$b.foo; # prints 5
-$b.bar; #=> 50, since it calls B's `bar`
## Roles are supported too (also called Mixins in other languages)
role PrintableVal {
@@ -699,8 +781,8 @@ class Item does PrintableVal {
has $.val;
# When `does`-ed, a `role` literally "mixes in" the class:
- # the methods and fields are put together, which means a class can access
- # the private fields/methods of its roles (but not the inverse !):
+ # the methods and attributes are put together, which means a class can access
+ # the private attributes/methods of its roles (but not the inverse !):
method access {
say $!counter++;
}
@@ -717,34 +799,76 @@ class Item does PrintableVal {
### Exceptions
# Exceptions are built on top of classes, in the package `X` (like `X::IO`).
-# Unlike many other languages, in Perl 6, you put the `CATCH` block *within* the
-# block to `try`. By default, a `try` has a `CATCH` block that catches
-# any exception (`CATCH { default {} }`).
+# In Perl6 exceptions are automatically 'thrown'
+open 'foo'; #> Failed to open file foo: no such file or directory
+# It will also print out what line the error was thrown at and other error info
+
+# You can throw an exception using `die`:
+die 'Error!'; #=> Error!
+# Or more explicitly:
+die X::AdHoc.new(payload => 'Error!');
+
+# In Perl 6, `orelse` is similar to the `or` operator, except it only matches
+# undefined variables instead of anything evaluating as false.
+# Undefined values include: `Nil`, `Mu` and `Failure` as well as `Int`, `Str`
+# and other types that have not been initialized to any value yet.
+# You can check if something is defined or not using the defined method:
+my $uninitialized;
+say $uninitiazilzed.defined; #> False
+# When using `orelse` it will disarm the exception and alias $_ to that failure
+# This will avoid it being automatically handled and printing lots of scary
+# error messages to the screen.
+# We can use the exception method on $_ to access the exception
+open 'foo' orelse say "Something happened {.exception}";
+# This also works:
+open 'foo' orelse say "Something happened $_"; #> Something happened
+ #> Failed to open file foo: no such file or directory
+# Both of those above work but in case we get an object from the left side that
+# is not a failure we will probably get a warning. We see below how we can use
+# `try` and `CATCH` to be more specific with the exceptions we catch.
+
+## Using `try` and `CATCH`
+# By using `try` and `CATCH` you can contain and handle exceptions without
+# disrupting the rest of the program. `try` will set the last exception to
+# the special variable `$!` Note: This has no relation to $!variables.
+try open 'foo';
+say "Well, I tried! $!" if defined $!; #> Well, I tried! Failed to open file
+ #foo: no such file or directory
+# Now, what if we want more control over handling the exception?
+# Unlike many other languages, in Perl 6, you put the `CATCH` block *within*
+# the block to `try`. Similar to how $_ was set when we 'disarmed' the
+# exception with orelse, we also use $_ in the CATCH block.
+# Note: ($! is only set *after* the `try` block)
+# By default, a `try` has a `CATCH` block that catches
+# any exception (`CATCH { default {} }`).
+
+try { my $a = (0 %% 0); CATCH { say "Something happened: $_" } }
+ #=> Something happened: Attempt to divide by zero using infix:<%%>
+
# You can redefine it using `when`s (and `default`)
-# to handle the exceptions you want:
+# to handle the exceptions you want:
try {
open 'foo';
- CATCH {
- when X::AdHoc { say "unable to open file !" }
+ CATCH { # In the `CATCH` block, the exception is set to $_
+ when X::AdHoc { say "Error: $_" }
+ #=>Error: Failed to open file /dir/foo: no such file or directory
+
# Any other exception will be re-raised, since we don't have a `default`
- # Basically, if a `when` matches (or there's a `default`) marks the exception as
- # "handled" so that it doesn't get re-thrown from the `CATCH`.
+ # Basically, if a `when` matches (or there's a `default`) marks the
+ # exception as
+ # "handled" so that it doesn't get re-thrown from the `CATCH`.
# You still can re-throw the exception (see below) by hand.
}
}
-# You can throw an exception using `die`:
-die X::AdHoc.new(payload => 'Error !');
-
-# You can access the last exception with `$!` (use `$_` in a `CATCH` block)
-
-# There are also some subtelties to exceptions. Some Perl 6 subs return a `Failure`,
-# which is a kind of "unthrown exception". They're not thrown until you tried to look
-# at their content, unless you call `.Bool`/`.defined` on them - then they're handled.
-# (the `.handled` method is `rw`, so you can mark it as `False` back yourself)
+# There are also some subtleties to exceptions. Some Perl 6 subs return a
+# `Failure`, which is a kind of "unthrown exception". They're not thrown until
+# you tried to look at their content, unless you call `.Bool`/`.defined` on
+# them - then they're handled.
+# (the `.handled` method is `rw`, so you can mark it as `False` back yourself)
#
-# You can throw a `Failure` using `fail`. Note that if the pragma `use fatal` is on,
-# `fail` will throw an exception (like `die`).
+# You can throw a `Failure` using `fail`. Note that if the pragma `use fatal`
+# is on, `fail` will throw an exception (like `die`).
fail "foo"; # We're not trying to access the value, so no problem.
try {
fail "foo";
@@ -764,21 +888,25 @@ try {
# and `enum`) are actually packages. (Packages are the lowest common denominator)
# Packages are important - especially as Perl is well-known for CPAN,
# the Comprehensive Perl Archive Network.
-# You're not supposed to use the package keyword, usually:
-# you use `class Package::Name::Here;` to declare a class,
-# or if you only want to export variables/subs, you can use `module`:
+
+# You can use a module (bring its declarations into scope) with `use`
+use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module
+say from-json('[1]').perl; #=> [1]
+
+# Declare your own packages like this:
+# `class Package::Name::Here;` to declare a class, or if you only want to
+# export variables/subs, you can use `module`. If you're coming from Perl 5
+# please note you're not usually supposed to use the `package` keyword.
+
module Hello::World { # Bracketed form
# If `Hello` doesn't exist yet, it'll just be a "stub",
# that can be redeclared as something else later.
# ... declarations here ...
}
unit module Parse::Text; # file-scoped form
-grammar Parse::Text::Grammar { # A grammar is a package, which you could `use`
-}
-# You can use a module (bring its declarations into scope) with `use`
-use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module
-say from-json('[1]').perl; #=> [1]
+grammar Parse::Text::Grammar { # A grammar is a package, which you could `use`
+} # You will learn more about grammars in the regex section
# As said before, any part of the six model is also a package.
# Since `JSON::Tiny` uses (its own) `JSON::Tiny::Actions` class, you can use it:
@@ -790,25 +918,33 @@ my $actions = JSON::Tiny::Actions.new;
# In Perl 6, you get different behaviors based on how you declare a variable.
# You've already seen `my` and `has`, we'll now explore the others.
-## * `our` (happens at `INIT` time -- see "Phasers" below)
+## * `our` declarations happen at `INIT` time -- (see "Phasers" below)
# It's like `my`, but it also creates a package variable.
# (All packagish things (`class`, `role`, etc) are `our` by default)
-module Foo::Bar {
- our $n = 1; # note: you can't put a type constraint on an `our` variable
- our sub inc {
+module Var::Increment {
+ our $our-var = 1; # Note: you can't put a type constraint like Int on an
+ my $my-var = 22; # `our` variable.
+ our sub Inc {
+
our sub available { # If you try to make inner `sub`s `our`...
# Better know what you're doing (Don't !).
- say "Don't do that. Seriously. You'd get burned.";
+ say "Don't do that. Seriously. You'll get burned.";
}
+
my sub unavailable { # `my sub` is the default
- say "Can't access me from outside, I'm my !";
+ say "Can't access me from outside, I'm 'my'!";
}
- say ++$n; # increment the package variable and output its value
+ say ++$our-var; # Increment the package variable and output its value
}
+
}
-say $Foo::Bar::n; #=> 1
-Foo::Bar::inc; #=> 2
-Foo::Bar::inc; #=> 3
+say $Var::Increment::our-var; #=> 1 This works
+say $Var::Increment::my-var; #=> (Any) This will not work.
+
+Var::Increment::Inc; #=> 2
+Var::Increment::Inc; #=> 3 # Notice how the value of $our-var was
+ # retained.
+Var::Increment::unavailable; #> Could not find symbol '&unavailable'
## * `constant` (happens at `BEGIN` time)
# You can use the `constant` keyword to declare a compile-time variable/symbol:
@@ -845,10 +981,11 @@ for ^5 -> $a {
### Phasers
# Phasers in Perl 6 are blocks that happen at determined points of time in your
-# program. When the program is compiled, when a for loop runs, when you leave a
-# block, when an exception gets thrown ... (`CATCH` is actually a phaser !)
+# program. They are called phasers because they mark a change in the phase
+# of a program. For example, when the program is compiled, a for loop runs,
+# you leave a block, or an exception gets thrown. (`CATCH` is actually a phaser !)
# Some of them can be used for their return values, some of them can't
-# (those that can have a "[*]" in the beginning of their explanation text).
+# (those that can have a "[*]" in the beginning of their explanation text).
# Let's have a look !
## * Compile-time phasers
@@ -947,15 +1084,25 @@ constant thrice = gather for ^3 { say take $_ }; # Doesn't print anything
# versus:
constant thrice = eager gather for ^3 { say take $_ }; #=> 0 1 2
-# - `lazy` - Defer actual evaluation until value is fetched (forces lazy context)
-# Not yet implemented !!
+### Iterables
+# Iterables are objects that can be iterated similar to the `for` construct
+# `flat`, flattens iterables:
+say (1, 10, (20, 10) ); #> (1 10 (20 10)) Notice how grouping is maintained
+say (1, 10, (20, 10) ).flat; #> (1 10 20 10) Now the iterable is flat
+# - `lazy` - Defer actual evaluation until value is fetched (forces lazy context)
+my @lazy-array = (1..100).lazy;
+say @lazy-array.is-lazy; #> True # Check for lazyness with the `is-lazy` method.
+say @lazy-array; #> [...] List has not been iterated on!
+my @lazy-array { .print }; # This works and will only do as much work as is
+# needed.
+[//]: # ( TODO explain that gather/take and map are all lazy)
# - `sink` - An `eager` that discards the results (forces sink context)
constant nilthingie = sink for ^3 { .say } #=> 0 1 2
say nilthingie.perl; #=> Nil
-# - `quietly` - Supresses warnings
-# Not yet implemented !
+# - `quietly` blocks will suppress warnings:
+quietly { warn 'This is a warning!' }; #=> No output
# - `contend` - Attempts side effects under STM
# Not yet implemented !
@@ -965,7 +1112,7 @@ say nilthingie.perl; #=> Nil
## Everybody loves operators ! Let's get more of them
# The precedence list can be found here:
-# http://perlcabal.org/syn/S03.html#Operator_precedence
+# https://docs.perl6.org/language/operators#Operator_Precedence
# But first, we need a little explanation about associativity:
# * Binary operators:
@@ -1088,10 +1235,11 @@ sub add($a, $b) { $a + $b }
say [[&add]] 1, 2, 3; #=> 6
## * Zip meta-operator
-# This one is an infix meta-operator than also can be used as a "normal" operator.
-# It takes an optional binary function (by default, it just creates a pair),
-# and will pop one value off of each array and call its binary function on these
-# until it runs out of elements. It returns an array with all of these new elements.
+# This one is an infix meta-operator than also can be used as a "normal"
+# operator. It takes an optional binary function (by default, it just creates
+# a pair), and will pop one value off of each array and call its binary function
+# on these until it runs out of elements. It returns an array with all of these
+# new elements.
(1, 2) Z (3, 4); # ((1, 3), (2, 4)), since by default, the function makes an array
1..3 Z+ 4..6; # (5, 7, 9), using the custom infix:<+> function
@@ -1158,14 +1306,15 @@ say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55
# (grammars are actually classes)
# - Earliest declaration wins
say so 'a' ~~ /a/; #=> True
-say so 'a' ~~ / a /; # More readable with some spaces!
+say so 'a' ~~ / a /; #=> True # More readable with some spaces!
# In all our examples, we're going to use the smart-matching operator against
# a regexp. We're converting the result using `so`, but in fact, it's
# returning a `Match` object. They know how to respond to list indexing,
# hash indexing, and return the matched string.
# The results of the match are available as `$/` (implicitly lexically-scoped).
-# You can also use the capture variables (`$0`, `$1`, ... starting at 0, not 1 !).
+# You can also use the capture variables which start at 0:
+# `$0`, `$1', `$2`...
#
# You can also note that `~~` does not perform start/end checking
# (meaning the regexp can be matched with just one char of the string),
@@ -1173,50 +1322,63 @@ say so 'a' ~~ / a /; # More readable with some spaces!
# In Perl 6, you can have any alphanumeric as a literal,
# everything else has to be escaped, using a backslash or quotes.
-say so 'a|b' ~~ / a '|' b /; # `True`. Wouln't mean the same if `|` wasn't escaped
+say so 'a|b' ~~ / a '|' b /; # `True`. Wouldn't mean the same if `|` wasn't escaped
say so 'a|b' ~~ / a \| b /; # `True`. Another way to escape it.
# The whitespace in a regexp is actually not significant,
-# unless you use the `:s` (`:sigspace`, significant space) modifier.
-say so 'a b c' ~~ / a b c /; # `False`. Space is not significant here
-say so 'a b c' ~~ /:s a b c /; # `True`. We added the modifier `:s` here.
-
+# unless you use the `:s` (`:sigspace`, significant space) adverb.
+say so 'a b c' ~~ / a b c /; #> `False`. Space is not significant here
+say so 'a b c' ~~ /:s a b c /; #> `True`. We added the modifier `:s` here.
+# If we use only one space between strings in a regex, Perl 6 will warn us:
+say so 'a b c' ~~ / a b c /; #> 'False' #> Space is not significant here; please
+# use quotes or :s (:sigspace) modifier (or, to suppress this warning, omit the
+# space, or otherwise change the spacing)
+# To fix this and make the spaces less ambiguous, either use at least two
+# spaces between strings or use the `:s` adverb.
+
+# As we saw before, we can embed the `:s` inside the slash delimiters, but we can
+# also put it outside of them if we specify `m` for 'match':
+say so 'a b c' ~~ m:s/a b c/; #> `True`
+# By using `m` to specify 'match' we can also use delimiters other than slashes:
+say so 'abc' ~~ m{a b c}; #> `True`
+# Use the :i adverb to specify case insensitivity:
+say so 'ABC' ~~ m:i{a b c}; #> `True`
# It is, however, important as for how modifiers (that you're gonna see just below)
# are applied ...
## Quantifying - `?`, `+`, `*` and `**`.
# - `?` - 0 or 1
-so 'ac' ~~ / a b c /; # `False`
-so 'ac' ~~ / a b? c /; # `True`, the "b" matched 0 times.
-so 'abc' ~~ / a b? c /; # `True`, the "b" matched 1 time.
+so 'ac' ~~ / a b c /; # `False`
+so 'ac' ~~ / a b? c /; # `True`, the "b" matched 0 times.
+so 'abc' ~~ / a b? c /; # `True`, the "b" matched 1 time.
# ... As you read just before, whitespace is important because it determines
# which part of the regexp is the target of the modifier:
-so 'def' ~~ / a b c? /; # `False`. Only the `c` is optional
-so 'def' ~~ / ab?c /; # `False`. Whitespace is not significant
+so 'def' ~~ / a b c? /; # `False`. Only the `c` is optional
+so 'def' ~~ / a b? c /; # `False`. Whitespace is not significant
so 'def' ~~ / 'abc'? /; # `True`. The whole "abc" group is optional.
# Here (and below) the quantifier applies only to the `b`
# - `+` - 1 or more
-so 'ac' ~~ / a b+ c /; # `False`; `+` wants at least one matching
-so 'abc' ~~ / a b+ c /; # `True`; one is enough
-so 'abbbbc' ~~ / a b+ c /; # `True`, matched 4 "b"s
+so 'ac' ~~ / a b+ c /; # `False`; `+` wants at least one matching
+so 'abc' ~~ / a b+ c /; # `True`; one is enough
+so 'abbbbc' ~~ / a b+ c /; # `True`, matched 4 "b"s
# - `*` - 0 or more
-so 'ac' ~~ / a b* c /; # `True`, they're all optional.
-so 'abc' ~~ / a b* c /; # `True`
-so 'abbbbc' ~~ / a b* c /; # `True`
-so 'aec' ~~ / a b* c /; # `False`. "b"(s) are optional, not replaceable.
+so 'ac' ~~ / a b* c /; # `True`, they're all optional.
+so 'abc' ~~ / a b* c /; # `True`
+so 'abbbbc' ~~ / a b* c /; # `True`
+so 'aec' ~~ / a b* c /; # `False`. "b"(s) are optional, not replaceable.
# - `**` - (Unbound) Quantifier
# If you squint hard enough, you might understand
# why exponentation is used for quantity.
-so 'abc' ~~ / a b ** 1 c /; # `True` (exactly one time)
-so 'abc' ~~ / a b ** 1..3 c /; # `True` (one to three times)
-so 'abbbc' ~~ / a b ** 1..3 c /; # `True`
-so 'abbbbbbc' ~~ / a b ** 1..3 c /; # `False` (too much)
-so 'abbbbbbc' ~~ / a b ** 3..* c /; # `True` (infinite ranges are okay)
+so 'abc' ~~ / a b**1 c /; # `True` (exactly one time)
+so 'abc' ~~ / a b**1..3 c /; # `True` (one to three times)
+so 'abbbc' ~~ / a b**1..3 c /; # `True`
+so 'abbbbbbc' ~~ / a b**1..3 c /; # `False` (too much)
+so 'abbbbbbc' ~~ / a b**3..* c /; # `True` (infinite ranges are okay)
# - `<[]>` - Character classes
# Character classes are the equivalent of PCRE's `[]` classes, but
@@ -1460,7 +1622,18 @@ for <a b c> {
If you want to go further, you can:
- - Read the [Perl 6 Advent Calendar](http://perl6advent.wordpress.com/). This is probably the greatest source of Perl 6 information, snippets and such.
+ - Read the [Perl 6 Docs](https://docs.perl6.org/). This is a great
+ resource on Perl6. If you are looking for something, use the search bar.
+ This will give you a dropdown menu of all the pages referencing your search
+ term (Much better than using Google to find Perl 6 documents!)
+ - Read the [Perl 6 Advent Calendar](http://perl6advent.wordpress.com/). This
+ is a great source of Perl 6 snippets and explainations. If the docs don't
+ describe something well enough, you may find more detailed information here.
+ This information may be a bit older but there are many great examples and
+ explainations. Posts stopped at the end of 2015 when the language was declared
+ stable and Perl 6.c was released.
- Come along on `#perl6` at `irc.freenode.net`. The folks here are always helpful.
- Check the [source of Perl 6's functions and classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset easier to implement and optimize).
- Read [the language design documents](http://design.perl6.org). They explain P6 from an implementor point-of-view, but it's still very interesting.
+
+ [//]: # ( vim: set filetype=perl softtabstop=2 shiftwidth=2 expandtab cc=80 : )
diff --git a/php.html.markdown b/php.html.markdown
index 24d656fa..ddf38226 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -283,7 +283,7 @@ if (false) {
if (false) {
print 'Does not get printed';
-} elseif(true) {
+} elseif (true) {
print 'Does';
}
@@ -305,7 +305,7 @@ echo $b ?? 'b is not set'; // prints 'Does print'
$x = 0;
if ($x === '0') {
print 'Does not print';
-} elseif($x == '1') {
+} elseif ($x == '1') {
print 'Does not print';
} else {
print 'Does print';
@@ -467,7 +467,7 @@ function variable($word, ...$list) {
}
}
-variable("Separate", "Hello", "World") // Separate || Hello | World |
+variable("Separate", "Hello", "World"); // Separate || Hello | World |
/********************************
* Includes
@@ -530,7 +530,8 @@ class MyClass
private $priv = 'private'; // Accessible within the class only
// Create a constructor with __construct
- public function __construct($instanceProp) {
+ public function __construct($instanceProp)
+ {
// Access instance variables with $this
$this->instanceProp = $instanceProp;
}
@@ -545,17 +546,19 @@ class MyClass
final function youCannotOverrideMe()
{
}
-
+
// Magic Methods
-
+
// what to do if Object is treated as a String
- public function __toString() {
+ public function __toString()
+ {
return $property;
}
-
+
// opposite to __construct()
// called when object is no longer referenced
- public function __destruct() {
+ public function __destruct()
+ {
print "Destroying";
}
@@ -755,11 +758,15 @@ $cls = new SomeOtherNamespace\MyClass();
*
*/
-class ParentClass {
- public static function who() {
+class ParentClass
+{
+ public static function who()
+ {
echo "I'm a " . __CLASS__ . "\n";
}
- public static function test() {
+
+ public static function test()
+ {
// self references the class the method is defined within
self::who();
// static references the class the method was invoked on
@@ -773,8 +780,10 @@ I'm a ParentClass
I'm a ParentClass
*/
-class ChildClass extends ParentClass {
- public static function who() {
+class ChildClass extends ParentClass
+{
+ public static function who()
+ {
echo "But I'm " . __CLASS__ . "\n";
}
}
@@ -815,7 +824,7 @@ echo "Current method is " . __METHOD__;
echo "Current namespace is " . __NAMESPACE__;
// Get the name of the current trait. Only returns a value when used inside a trait or object declaration.
-echo "Current namespace is " . __TRAIT__;
+echo "Current trait is " . __TRAIT__;
/**********************
* Error Handling
diff --git a/pl-pl/vim-pl.html.markdown b/pl-pl/vim-pl.html.markdown
new file mode 100644
index 00000000..21c8c152
--- /dev/null
+++ b/pl-pl/vim-pl.html.markdown
@@ -0,0 +1,236 @@
+---
+category: tool
+tool: vim
+contributors:
+ - ["RadhikaG", "https://github.com/RadhikaG"]
+translators:
+ - ["Adam Bobowski", "https://github.com/Bobowski"]
+lang: pl-pl
+filename: LearnVim-pl.txt
+---
+
+
+[Vim](www.vim.org)
+(Vi IMproved) jest klonem popularnego edytora vi dla systemów Unix.
+Zaprojektowany z myślą o prędkości edycji i zwiększeniu produktywności jest
+wszechobecny na systemach UNIXopodobnych. Posiada wiele skrótów klawiszowych
+do szybkiej nawigacji do wybranych miejsc w plikach oraz szybkiej edycji
+danych fragmentów.
+
+## Podstawy nawigacji w Vim
+
+```
+ vim <nazwapliku> # Otwórz <nazwapliku> w vim
+ :q # Zamknij vim
+ :w # Zapisz aktualny plik
+ :wq # Zapisz i wyjdź z vim
+ :q! # Wyjdź bez zapisywania
+ # ! *wymusza* wykonanie :q, dlatego nie wykonuje zapisu
+ :x # Zapisz i wyjdź, krótszy odpowiednik :wq
+
+ u # Cofnij operację
+ CTRL+R # Powtórz operację
+
+ h # Przesuń kursor w lewo
+ j # Przesuń kursor w dół
+ k # Przesuń kursor w górę
+ l # Przesuń kursor w prawo
+
+ # Poruszanie w obrębie jednej lini
+
+ 0 # Skocz do początku linii
+ $ # Skocz do końca linii
+ ^ # Skocz do pierwszego niebiałego znaku
+
+ # Wyszukiwanie w tekście
+
+ /slowo # Zaznacza wszystkie wystąpienia słowa za kursorem
+ ?slowo # Zaznacza wszystkie wystąpienia słowa przed kursorem
+ n # Przemieszcza kursor do następnego wystąpienia słowa
+ N # Przemieszcza kursor do poprzedniego wystąpenia słowa
+
+ :%s/foo/bar/g # Zamień 'foo' na 'bar' w każdej linii tekstu
+ :s/foo/bar/g # Zamień 'foo' na 'bar' w aktualnej linii
+
+ # Skoki do znaków
+
+ f<znak> # Skocz do przodu i zatrzymaj się na <znak>
+ t<znak> # Skocz do przodu i zatrzymaj się przed <znak>
+
+ # Na przykład,
+ f< # Skocz do przodu i zatrzymaj się na <
+ t< # Skocz do przodu i zatrzymaj się przed <
+
+ # Moving by word
+
+ w # Przesuń kursor do przodu o jedno słowo
+ b # Przesuń kursor do tyłu o jedno słowo
+ e # Przesuń kursor do końca aktualnego słowa
+
+ # Inne znaki do przemieszczania się
+
+ gg # Skocz na początek pliku
+ G # Skocz na koniec pliku
+ :NUM # Skocz do linii o numerze NUM
+ H # Skocz na górę ekranu
+ M # Skocz na środek ekranu
+ L # Skocz na dół ekranu
+```
+
+## Tryby:
+
+Vim oparty jest na koncepcji **trybów**.
+
+Command Mode - (Tryb komend) vim zaczyna w tym trybie, używany do nawigacji i wpisywania komend
+Insert Mode - (Tryb wprowadzania) używany do wprowadzania zmian w pliku
+Visual Mode - (Tryb wizualny) używany do zaznaczania tekstu i wykonywania komend na nim
+Ex Mode - (Tryb Ex)
+
+```
+ i # Przechodzi to trybu wprowadzania, przed pozycją kursora
+ a # Przechodzi do trybu wprowadzania, za pozycją kursora
+ v # Przechodzi do trybu wizualnego
+ : # Przechodzi do trybu ex
+ <esc> # Wychodzi z dowolnego aktywnego trybu do trybu komend
+
+ # Kopiowanie i wklejanie tekstu
+
+ y # Skopiuj zaznaczony tekst
+ yy # Skopiuj aktualną linię
+ d # Usuń zaznaczony tekst
+ dd # Usuń aktualną linię
+ p # Wklej skopiowany tekst za kursorem
+ P # Wklej skopiowany tekst przed kursorem
+ x # Usuń znak pod kursorem
+```
+
+## 'Gramatyka' vim'a
+
+Vim można traktować jako zbiór komend w formacie 'Akcja-Modyfikator-Obiekt', gdzie:
+
+Akcja - jedna z dostępnych akcji
+Modyfikator - w jaki sposób wykonywana jest akcja
+Obiekt - obiekt na którym wykonywana jest akcja
+
+Kilka ważnych przykładów Akcji, Modyfikatorów i Obiektów:
+
+```
+ # 'Akcje'
+
+ d # Usuń
+ c # Zmień
+ y # Skopiuj
+ v # Zaznacz
+
+ # 'Modyfikatory'
+
+ i # W środku
+ a # Dookoła
+ NUM # Liczba
+ f # Szuka czegoś i zatrzymuje się na tym
+ t # Szuka czegoś i zatrzymuje się przed tym
+ / # Znajduje napis od kursora naprzód
+ ? # Znajduje napis przed kursorem
+
+ # 'Obiekty'
+
+ w # Słowo
+ s # Zdanie
+ p # Paragraf
+ b # Blok
+
+ # Przykładowe 'zdania'
+
+ d2w # Usuń 2 słowa
+ cis # Zmień w zdaniu
+ yip # Skopiuj paragraf w którym jest kursor
+ ct< # Zamień na <
+ d$ # Usuń tekst do końca linii
+```
+
+## Pewne skróty i triki
+
+ <!--TODO: Dodać więcej!-->
+```
+ > # Zrób wcięcie zaznaczonego bloku
+ < # Usuń wcięcie zaznaczonego bloku
+ :earlier 15m # Przywróć dokument do stanu z przed 15 minut
+ :later 15m # Odwróć efekt poprzedniej komendy
+ ddp # Zamień kolejnością kolejne linie, dd potem p
+ . # Powtórz poprzednią komendę
+```
+
+## Makra
+
+Makra są właściwie nagrywanymi akcjami. Gdy zaczynasz nagrywać makro, nagrywa ono
+**każdą** akcję i komendę jaką wykonasz do momentu przerwania nagrywania.
+Wywołanie makra wykonuje dokładnie te same operacje w tej samej kolejności.
+
+```
+ qa # Zacznij nagrywać makro 'a'
+ q # Przerwij nagrywanie
+ @a # Odtwórz makro 'a'
+```
+
+### Konfiguracja ~/.vimrc
+
+Plik .vimrc może być użyty do skonfigurowania Vim'a przy jego starcie
+
+Poniżej zamieszczono przykładowy plik ~/.vimrc:
+
+```
+" Przykładowy ~/.vimrc
+" 2016.10
+
+" Wymagane aby korzystać z opcji iMproved
+set nocompatible
+
+" Na podstawie typu pliku włącza inteligentne wcięcia i inne.
+filetype indent plugin on
+
+" Włącz podkreślanie składni
+syntax on
+
+" Lepsze uzupełnianie składni komend
+set wildmenu
+
+" Wyszukiwanie będzie ignorować wielkość liter poza przypadkami gdy użyjemy wielkich liter
+set ignorecase
+set smartcase
+
+" Po otwarciu pliku gdzie nie jest zdefiniowane zachowanie wcięć
+" zostanie zachowane wcięcie takie samo jak w aktualnej linii
+set autoindent
+
+" Wyświetlaj numer lini
+set number
+
+" Opcje wcięć, zmień w zależności od osobistych upodobań
+
+" Szerokość TAB w spacjach
+set tabstop=4
+
+" Liczba spacji w TAB podczas edycji
+set softtabstop=4
+
+" Liczba spacji gdy wykonywane są operacje wcięcia (>> i <<)
+set shiftwidth=4
+
+" Zamieniaj tabulatory na spacje
+set expandtab
+
+" Aktywuj inteligentne tabulatory i spacje do wcięć i wyrównań
+set smarttab
+```
+
+### Odniesienia [ENG]
+
+[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/powershell.html.markdown b/powershell.html.markdown
index fc944b85..bd46051c 100644
--- a/powershell.html.markdown
+++ b/powershell.html.markdown
@@ -19,7 +19,7 @@ rather than plain text.
If you are uncertain about your environment:
-```
+```powershell
Get-ExecutionPolicy -List
Set-ExecutionPolicy AllSigned
# Execution policies include:
@@ -35,7 +35,7 @@ $PSVersionTable
Getting help:
-```
+```powershell
# Find commands
Get-Command about_* # alias: gcm
Get-Command -Verb Add
@@ -52,7 +52,7 @@ Update-Help # Run as admin
The tutorial starts here:
-```
+```powershell
# As you already figured, comments start with #
# Simple hello world example:
@@ -74,7 +74,7 @@ $aHashtable = @{name1='val1'; name2='val2'}
# Using variables:
echo $aString
echo "Interpolation: $aString"
-echo "`$aString has length of $($aString.Length)"
+echo "$aString has length of $($aString.Length)"
echo '$aString'
echo @"
This is a Here-String
@@ -113,7 +113,7 @@ if ($Age -is [string]) {
echo 'Adult'
}
-# Switch statements are more powerfull compared to most languages
+# Switch statements are more powerful compared to most languages
$val = "20"
switch($val) {
{ $_ -eq 42 } { "The answer equals 42"; break }
@@ -204,7 +204,7 @@ function foo([string]$name) {
# Calling your function
foo "Say my name"
-# Functions with named parameters, parameter attributes, parsable documention
+# Functions with named parameters, parameter attributes, parsable documentation
<#
.SYNOPSIS
Setup a new website
@@ -300,7 +300,7 @@ $Shortcut.Save()
Configuring your shell
-```
+```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)) {
@@ -308,7 +308,7 @@ if (-not (Test-Path $Profile)) {
notepad $Profile
}
# More info: `help about_profiles`
-# For a more usefull shell, be sure to check the project PSReadLine below
+# For a more useful shell, be sure to check the project PSReadLine below
```
Interesting Projects
diff --git a/pt-br/asciidoc-pt.html.markdown b/pt-br/asciidoc-pt.html.markdown
new file mode 100644
index 00000000..75b3c268
--- /dev/null
+++ b/pt-br/asciidoc-pt.html.markdown
@@ -0,0 +1,129 @@
+---
+language: asciidoc
+contributors:
+ - ["Ryan Mavilia", "http://unoriginality.rocks/"]
+translators:
+ - ["David Lima", "https://github.com/davelima"]
+lang: pt-br
+filename: asciidoc-pt.md
+---
+
+AsciiDoc é uma linguagem de marcação similar ao Markdown e pode ser
+usada para qualquer coisa, de livros até blogs. Criada em 2002 por
+Stuart Rackham, a linguagem é simples mas facilita muito a customização.
+
+Cabeçalho do documento
+
+Cabeçalhos são opcionais e não podem conter linhas em branco.
+Devem estar separados do conteúdo com pelo menos uma linha em branco.
+
+Apenas Título
+
+```
+= Título do documento
+
+Primeira sentência do documento.
+```
+
+Título e Autor
+
+```
+= Título do Documento
+Nome Sobrenome <nome.sobrenome@learnxinyminutes.com>
+
+Início do documento.
+```
+
+Múltiplos Autores
+
+```
+= Título do Documento
+John Doe <john@go.com>; Jane Doe<jane@yo.com>; Black Beard <beardy@pirate.com>
+
+Início do documento com múltiplos autores.
+```
+
+Linhas de revisão (requer uma linha de autor)
+
+```
+= Documento V1
+Potato Man <chip@crunchy.com>
+v1.0, 2016-01-13
+
+Este artigo sobre batatas será divertido.
+```
+
+Parágrafos
+
+```
+Você não precisa fazer nada especial para criar um parágrafo.
+
+Adicione uma linha em branco entre os parágrafos para separá-los.
+
+Para criar uma linha em branco adicione um +
+e você terá uma quebra de linha!
+```
+
+Formatando texto
+
+```
+_underscore é itálico_
+*asterisco é negrito*
+*_você pode combinar efeitos_*
+`use crase para fonte monoespaçada`
+`*fonte monoespaçada em negrito*`
+```
+
+Título de seções
+
+```
+= Nível 0 (Use apenas no cabeçalho do documento)
+
+== Nível 1 <h2>
+
+=== Nível 2 <h3>
+
+==== Nível 3 <h4>
+
+===== Nível 4 <h5>
+
+====== Nível 5 <h6>
+
+======= Nível 6 <h7>
+
+```
+
+Listas
+
+Para criar uma lista com marcadores use asteriscos.
+
+```
+* foo
+* bar
+* baz
+```
+
+Para criar uma lista númerada use pontos.
+
+```
+. item 1
+. item 2
+. item 3
+```
+
+Você pode criar listas dentro de listas adicionando
+asteriscos ou pontos extras em até 5 níveis.
+
+```
+* foo 1
+** foo 2
+*** foo 3
+**** foo 4
+***** foo 5
+
+. foo 1
+.. foo 2
+... foo 3
+.... foo 4
+..... foo 5
+```
diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown
index 2c274f12..0af553c8 100644
--- a/pt-br/c-pt.html.markdown
+++ b/pt-br/c-pt.html.markdown
@@ -28,7 +28,7 @@ Funcionam no C89 também.
*/
// Constantes: #define <palavra-chave>
-#definie DAY_IN_YEAR 365
+#define DAY_IN_YEAR 365
//enumerações também são modos de definir constantes.
enum day {DOM = 1, SEG, TER, QUA, QUI, SEX, SAB};
diff --git a/pt-br/clojure-macros-pt.html.markdown b/pt-br/clojure-macros-pt.html.markdown
index dbc0c25c..d56840e0 100644
--- a/pt-br/clojure-macros-pt.html.markdown
+++ b/pt-br/clojure-macros-pt.html.markdown
@@ -142,6 +142,8 @@ Você vai querer estar familiarizado com Clojure. Certifique-se de entender tudo
(inline-2 (1 + (3 / 2) - (1 / 2) + 1))
; -> 3 (Na verdade, 3N, desde que o numero ficou convertido em uma fração racional com /
+```
+
### Leitura adicional
Escrevendo Macros de [Clojure para o Brave e True](http://www.braveclojure.com/)
diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown
index 907892b1..e59ba901 100644
--- a/pt-br/git-pt.html.markdown
+++ b/pt-br/git-pt.html.markdown
@@ -2,7 +2,7 @@
category: tool
tool: git
lang: pt-br
-filename: LearnGit.txt
+filename: LearnGit-br.txt
contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
- ["Leo Rudberg" , "http://github.com/LOZORD"]
diff --git a/pt-br/jquery-pt.html.markdown b/pt-br/jquery-pt.html.markdown
new file mode 100644
index 00000000..d49bea0f
--- /dev/null
+++ b/pt-br/jquery-pt.html.markdown
@@ -0,0 +1,131 @@
+---
+category: tool
+tool: jquery
+contributors:
+ - ["Sawyer Charles", "https://github.com/xssc"]
+translators:
+ - ["Nikolas Silva", "https://github.com/nikolassilva"]
+filename: jquery-pt.js
+lang: pt-br
+---
+
+jQuery é uma biblioteca JavaScript que te ajuda a "fazer mais, escrevendo menos". Ela faz com que muitas tarefas comuns em JavaScript sejam mais simples de escrever. jQuery é usado por grandes empresas e desenvolvedores do mundo todo. Ela torna o AJAX, manipulação de eventos, manipulação do DOM, entre outros, mais fácil e rápido.
+
+Pelo jQuery ser uma biblioteca JavaScript você deve [aprende-lo primeiro](https://learnxinyminutes.com/docs/pt-br/javascript-pt/)
+
+```js
+
+
+///////////////////////////////////
+// 1. Seletores
+
+// Seletores no jQuery são usados para selecionar um elemento
+var page = $(window); // Seleciona toda a viewport
+
+// Seletores também podem ser na forma do CSS
+var paragraph = $('p'); // Seleciona todos elementos de parágrafo
+var table1 = $('#table1'); // Seleciona o elemento com id 'table1'
+var squares = $('.square'); // Seleciona todos elementos com classe 'square'
+var square_p = $('p.square') // Seleciona todos elementos de parágrafo com a classe 'square'
+
+
+///////////////////////////////////
+// 2. Eventos e Efeitos
+// jQuery é muito bom em manipular o que acontece quando um evento é disparado
+// Um evento muito usado é o 'ready'
+// Você pode usar o método ready para esperar até que um elemento tenha terminado de carregar
+$(document).ready(function(){
+ // O código não será executado até que o documento carregue
+});
+// Você também pode usar funções declaradas
+function onAction() {
+ // Isso será executado quando um evento for disparado
+}
+$('#btn').click(onAction); // Chama 'onAction' quando o elemento receber um clique
+
+// Outros eventos comuns são:
+$('#btn').dblclick(onAction); // Clique duplo
+$('#btn').hover(onAction); // Mouse sobre elemento
+$('#btn').focus(onAction); // Elemento recebe foco
+$('#btn').blur(onAction); // Elemento perde foco
+$('#btn').submit(onAction); // Envio de formulário
+$('#btn').select(onAction); // Quando o elemento é selecionado
+$('#btn').keydown(onAction); // Quando uma tecla é segurada
+$('#btn').keyup(onAction); // Quando uma tecla é solta
+$('#btn').keypress(onAction); // Quando uma tecla é pressionada
+$('#btn').mousemove(onAction); // Quando o mouse é movido
+$('#btn').mouseenter(onAction); // Quando o mouse entra no elemento
+$('#btn').mouseleave(onAction); // Quando o mouse sai do elemento
+
+
+// Eles também podem disparar os eventos em vez de manipulá-los,
+// simplesmente deixando de passar os parâmetros
+$('#btn').dblclick(); // Dispara um clique duplo no elemento
+
+// Você pode manipular múltiplos eventos usando o seletor apenas uma vez
+$('#btn').on(
+ {dblclick: myFunction1} // Disparado num clique duplo
+ {blur: myFunction1} // Disparado quando perder o foco
+);
+
+// Você pode mover e esconder elementos com alguns métodos de efeito
+$('.table').hide(); // Esconde o elemento
+
+// Nota: chamar uma função nesse método ainda irá esconder o elemento
+$('.table').hide(function(){
+ // Elemento é escondido e a função é executada
+});
+
+// Você pode guardar seletores em variáveis
+var tables = $('.table');
+
+// Alguns métodos básicos de manipulação do DOM:
+tables.hide(); // Esconde elemento(s)
+tables.show(); // Exibe elemento(s)
+tables.toggle(); // Alterna entre esconder/exibir
+tables.fadeOut(); // Efeito fade out
+tables.fadeIn(); // Efeito fade in
+tables.fadeToggle(); // Alterna entre fade out/in
+tables.fadeTo(0.5); // Efeito fade com opacidade específica (entre 0 e 1)
+tables.slideUp(); // Efeito de deslize pra cima
+tables.slideDown(); // Efeito de deslize pra baixo
+tables.slideToggle(); // Alterna entre deslizar pra cima/baixo
+
+// Todos os métodos acima levam velocidade (em milissegundos) e uma função callback
+tables.hide(1000, myFunction); // Esconde o elemento em 1 segundo e chama a função
+
+// No fadeTo é obrigatório definir a opacidade como segundo parâmetro
+tables.fadeTo(2000, 0.1, myFunction); // 2 segundos de fade para 0.1 de opacidade e chama a função
+
+// Você pode fazer animações mais avançadas com o método animate
+tables.animate({'margin-top':"+=50", height: "100px"}, 500, myFunction);
+// O método animate leva um objeto com valores CSS,
+// um parâmetro de opções para melhorar a animação
+// e uma função callback, como de costume
+
+///////////////////////////////////
+// 3. Manipulação
+
+// São similares aos efeitos, mas podem fazer mais
+$('div').addClass('taming-slim-20'); // Adiciona a classe taming-slim-20 em todas as divs
+
+// Métodos comuns de manipulação
+$('p').append('Hello world'); // Adiciona ao final do elemento
+$('p').attr('class'); // Obtém o valor de um atributo
+$('p').attr('class', 'content'); // Define o valor de um atributo
+$('p').hasClass('taming-slim-20'); // Retorna true se tiver a classe
+$('p').height(); // Obtém/define a altura do elemento
+
+
+// Pra maioria dos métodos de manipulação, pegar o valor de um
+// elemento só afetará o primeiro deles
+$('p').height(); // Obtém a altura da primeira tag 'p'
+
+// Você pode usar o método each pra percorrer os elementos
+var heights = [];
+$('p').each(function() {
+ heights.push($(this).height()); // Adiciona a altura das tags 'p' na array
+});
+
+
+```
diff --git a/pt-br/php-composer-pt.html.markdown b/pt-br/php-composer-pt.html.markdown
new file mode 100644
index 00000000..145f5cab
--- /dev/null
+++ b/pt-br/php-composer-pt.html.markdown
@@ -0,0 +1,184 @@
+---
+category: tool
+tool: composer
+contributors:
+ - ["Brett Taylor", "https://github.com/glutnix"]
+translators:
+ - ["David Lima", "https://github.com/davelima"]
+lang: pt-br
+filename: LearnComposer-pt.sh
+---
+
+[Composer](https://getcomposer.org/) é uma ferramenta de gerenciamento de dependências para PHP. Ele permite que você defina as bibliotecas que seu projeto precisa, e então ele as gerencia (instala/atualiza) para você.
+
+# Instalando
+
+```sh
+# Instala o binário composer.phar no diretório atual
+curl -sS https://getcomposer.org/installer | php
+# Se você fizer desta forma, você precisará chamar o composer assim:
+php composer.phar about
+
+# Instala o binário em ~/bin/composer
+# Nota: certifique-se de que ~/bin está na variável de ambiente PATH do seu shell
+curl -sS https://getcomposer.org/installer | php -- --install-dir=~/bin --filename=composer
+```
+
+Usuários Windows devem seguir as Instruções de instalação para Windows:
+https://getcomposer.org/doc/00-intro.md#installation-windows (EN)
+
+## Confirmando a instalação
+
+```sh
+# Verifica a versão e lista as opções
+composer
+
+# Para obter ajuda com os comandos
+composer help require
+
+# Verifica se o Composer tem as permissões necessárias e se está atualizado
+composer diagnose
+composer diag # atalho
+
+# Atualiza o binário do Composer para a última versão
+composer self-update
+composer self # atalho
+```
+
+# Modo de uso
+
+O Composer armazena as dependências do seu projeto em `composer.json`.
+Você pode editar este arquivo, mas é recomendável deixar que o Composer faça isso.
+
+```sh
+# Cria um novo projeto na pasta atual
+composer init
+# Executa um questionário interativo, te pedindo detalhes sobre o projeto.
+# Você pode deixar o questionário em branco, desde que não haja outros projetos dependendo deste.
+
+# Se um arquivo composer.json já existir, baixa as dependências
+composer install
+
+# Para baixar apenas as dependências de produção, excluindo as de desenvolvimento
+composer install --no-dev
+
+# Adiciona uma dependência de produção ao projeto
+composer require guzzlehttp/guzzle
+# O Composer se encarrega de verificar qual é a última versão de
+# guzzlehttp/guzzle, baixar e adicionar a nova dependência no
+# campo 'require' do composer.json
+
+composer require guzzlehttp/guzzle:6.0.*
+# O composer baixa a última versão que combine com o padrão informado (6.0.2, por exemplo)
+# e adiciona essa dependência ao campo 'require' do arquivo composer.json
+
+composer require --dev phpunit/phpunit:~4.5.0
+# O composer irá baixar a dependencia como desenvolvimento,
+# usando a versão mais recente >= 4.5.0 e < 4.6.0
+
+composer require-dev phpunit/phpunit:^4.5.0
+# O composer irá baixar a dependencia como desenvolvimento,
+# usando a versão mais recente >= 4.5.0 e < 5.0
+
+# Para mais informações sobre os padrões de versões, veja a
+# Documentação sobre Versões do Composer: https://getcomposer.org/doc/articles/versions.md (EN)
+
+# Para ver quais pacotes estão disopníveis e quais estão instalados
+composer show
+
+# Para ver quais pacotes estão instalados
+composer show --installed
+
+# Para encontrar um pacote que tenha 'mailgun' no nome ou descrição
+composer search mailgun
+```
+
+[Packagist.org](https://packagist.org/) é o repositório principal para pacotes Composer. Pesquise aqui por pacotes existentes.
+
+## `composer.json` vs `composer.lock`
+
+O arquivo `composer.json` armazena as preferências de de versão de cada dependência, além de outras informações
+
+O arquivo `composer.lock` armazena exatamente qual versão foi baixada para cada dependência. Nunca altere este arquivo.
+
+Se você incluir o arquivo `composer.lock` no seu repositório git, todos os desenvolvedores irão instalar a mesma versão das dependências que você.
+Mesmo se uma nova versão for lançada, o Composer baixará apenas a versão salva no arquivo de lock.
+
+```sh
+# Atualizar todas as dependências para a versão mais recente (ainda dentro das preferências definidas)
+composer update
+
+# Para atualizar a versão de uma dependência específica:
+composer update phpunit/phpunit
+
+# Para migrar um pacote para uma nova preferência de versão, você pode precisar
+# remover o pacote antigo e suas dependências primeiro
+composer remove --dev phpunit/phpunit
+composer require --dev phpunit/phpunit:^5.0
+
+```
+
+## Autoloader
+
+O Composer cria uma classe autoloader que você pode usar na sua aplicação.
+Você pode instanciar as classes pelos seus namespaces.
+
+```php
+require __DIR__ . '/vendor/autoload.php';
+
+$mailgun = new Mailgun\Mailgun("key");
+```
+
+### Autoloader da PSR-4
+
+Você pode adicionar seus próprios namespaces ao autoloader.
+
+No `composer.json`, adicione um campo 'autoload':
+
+```json
+{
+ "autoload": {
+ "psr-4": {"Acme\\": "src/"}
+ }
+}
+```
+Isso irá dizer ao autoloader para buscar na pasta `src` tudo o que estiver no namespace `\Acme\`.
+
+Você também pode [usar a PSR-0, um mapa de classes ou apenas listar os arquivos para incluir](https://getcomposer.org/doc/04-schema.md#autoload),
+e pode usar o campo `autoload-dev` para namespaces de desenvolvimento.
+
+Ao adicionar ou alterar alguma chave de autoload, você precisará recriar o autoloader
+
+```sh
+composer dump-autoload
+composer dump # shorthand
+
+# Otimiza pacotes PSR-0 e PSR-4 para carregar com mapas de classes também.
+# É mais demorado, mas melhora a performance em produção.
+composer dump-autoload --optimize --no-dev
+```
+
+# O cache do Composer
+
+```sh
+# O Composer irá evitar baixar pacotes caso eles estejam no cache. Para limpar o cache:
+composer clear-cache
+```
+
+# Resolução de problemas
+
+```sh
+composer diagnose
+composer self-update
+composer clear-cache
+```
+
+## Tópicos (ainda) não falados neste tutorial
+
+* Criando e distribuindo seus próprios pacotes no Packagist.org ou qualquer lugar
+* Hooks Pré- e Pós-: rodar tarefas específicas em determinados eventos do Composer
+
+### Referências
+
+* [Composer - O gerenciador de dependências do PHP](https://getcomposer.org/) (EN)
+* [Packagist.org](https://packagist.org/) (EN)
diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown
index eeb51bec..1078f6c5 100644
--- a/pt-br/ruby-pt.html.markdown
+++ b/pt-br/ruby-pt.html.markdown
@@ -7,6 +7,7 @@ contributors:
- ["Jean Matheus Souto", "http://jeanmatheussouto.github.io"]
translators:
- ["Katyanna Moura", "https://twitter.com/amelie_kn"]
+ - ["Alan Peterson Carvalho Silva", "https://twitter.com/DemonKart"]
---
```ruby
@@ -382,12 +383,65 @@ end
Humano.bar # 0
Doutor.bar # nil
+---
+
+module ModuloDeExemplo
+ def foo
+ 'foo'
+ end
+end
+
+# Incluir (include) módulos conecta seus métodos às instâncias da classe
+# Herdar (extend) módulos conecta seus métodos à classe em si
+
+class Pessoa
+ include ExemploDeModulo
+end
+
+class Livro
+ extend ExemploDeModulo
+end
+
+Pessoa.foo # => NoMethodError: undefined method `foo' for Pessoa:Class
+Pessoa.new.foo # => 'foo'
+Livro.foo # => 'foo'
+Livro.new.foo # => NoMethodError: undefined method `foo'
+
+# Callbacks são executados ao incluir e herdar um módulo
+
+module ExemploDeConceito
+ def self.included(base)
+ base.extend(MetodosDeClasse)
+ base.send(:include, MetodosDeInstancia)
+ end
+
+ module MetodosDeClasse
+ def bar
+ 'bar'
+ end
+ end
+
+ module MetodosDeInstancia
+ def qux
+ 'qux'
+ end
+ end
+end
+
+class Algo
+ include ExemploDeConceito
+end
+
+Algo.bar # => 'bar'
+Algo.qux # => NoMethodError: undefined method `qux'
+Algo.new.bar # => NoMethodError: undefined method `bar'
+Algo.new.qux # => 'qux'
```
-## Mais sobre Ruby
+## Recursos adicionais
-- [Documentação oficial](http://www.ruby-doc.org/core-2.1.1/)
- [Aprenda Ruby com desafios](http://www.learneroo.com/modules/61/nodes/338) - Uma coleção de desafios para testar a linguagem.
+- [Documentação oficial](http://www.ruby-doc.org/core-2.1.1/)
- [Ruby a partir de outras linguagens](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/)- Um mais antigo [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) e tambem uma versão online disponível.
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Uma versão colaborativa de um *style-guide*
diff --git a/pt-br/tmux-pt.html.markdown b/pt-br/tmux-pt.html.markdown
index 9d5bf292..ce3be407 100644
--- a/pt-br/tmux-pt.html.markdown
+++ b/pt-br/tmux-pt.html.markdown
@@ -9,11 +9,9 @@ lang: pt-br
filename: LearnTmux-pt.txt
---
-O [tmux](http://tmux.sourceforge.net)
-é um multiplexador de terminal, ele permite que terminais sejam criados,
-acessados e controlados a partir de uma unica instância. tmux pode ser separado
-de uma tela e continuar rodando no plano de fundo e depois ser reacoplado à
-instância (ou tela original).
+O [tmux](http://tmux.sourceforge.net) é um multiplexador de terminal,
+ele permite criar vários terminais e gerenciar tudo na mesma interface.
+tmux pode também rodar em background e depois ser recuperado(exibido) novamente.
```
@@ -25,9 +23,9 @@ instância (ou tela original).
-n "Janela" # Cria uma janela com o nome "Janela"
-c "/dir" # Inícia em uma pasta específica
- attach # Reacopla a última seção disponível
- -t "#" # Reacopla a seção com nome "#"
- -d # Separa (Desacopla) a sessaão de outras instâncias.
+ attach # Acopla a última seção disponível
+ -t "#" # Acopla a seção com nome "#"
+ -d # Separa (Desacopla) a seção de outras instâncias.
ls # Lista todas as seções
-a # Lista todas as seções abertas
@@ -39,56 +37,54 @@ instância (ou tela original).
lsp # Lista os painéis
-a # Lista todos os painéis
-s # Lista todos os painéis em uma seção
- -t "#" # Lista os painéis baseado no nome "#"
+ -t "#" # Lista os painéis chamados "#"
- kill-window # Encerrar a janela corrente
- -t "#" # Encerrar a janela baseado no nome "#"
+ kill-window # Encerrar a janela atual
+ -t "#" # Encerrar a janela chamada "#"
-a # Encerrar todas as janelas
- -a -t "#" # Encerrar todas as janelas exceto a com nome "#"
+ -a -t "#" # Encerrar todas as janelas exceto a "#"
- kill-session # Encerrar seção corrente
+ kill-session # Encerrar seção atual
-t "#" # Encerrar seção com nome "#"
-a # Encerrar todas as seções
- -a -t "#" # Encerrar todas as seções exceto a com nome "#"
+ -a -t "#" # Encerrar todas as seções exceto a "#"
```
-
### Teclas de atalhos (comandos)
-A maneira de controllar uma seção tmux acoplada é através de uma
-combinação de teclas de prefixo.
+As seções tmux acopladas são controladas através de teclas de atalho. (prefix key)
```
----------------------------------------------------------------------
- (C-b) = Ctrl + b # Combinação de prefixos para usar comandos(atalhos).
+ (C-b) = Ctrl + b # Abre a opção de receber comandos(atalhos).
(M-1) = Meta + 1 -or- Alt + 1
----------------------------------------------------------------------
? # Lista todos os comandos.
- : # Acessa o lugar (prompt command) para receber comandos do tmux
- r # Força a redefiniçao do cliente acoplado.
+ : # Acessa o prompt command do tmux
+ r # Força a reinicialização do cliente acoplado.
c # Cria uma nova janela.
- ! # Retira o painel corrente da janela.
- % # Divide o painel corrente em dois para a esquerda e direita.
- " # Divide o painel corrente em dois para cima e para baixo.
+ ! # Retira o painel atual da janela.
+ % # Divide o painel atual em dois. Esquerda e direita.
+ " # Divide o painel atual em dois. Para cima e para baixo.
- n # Move para a próxima janela.
- p # Move para a janela anterior.
- { # Troca o painel corrente pelo anterior.
+ n # Muda para a próxima janela.
+ p # Muda para a janela anterior.
+ { # Troca o painel atual pelo anterior.
} # Troca o painel corrent pelo posterior.
s # Seleciona uma nova seção para o cliente acoplado iterativamente.
- w # Seleciona a janela corrente iterativamente.
+ w # Seleciona a janela atual iterativamente.
0 to 9 # Seleciona a janela de 0 à 9.
d # Separa o cliente atual.
D # Seleciona um cliente a ser separado.
- & # Encerra a janela corrente.
- x # Encerra o painel corrente.
+ & # Encerra a janela atual.
+ x # Encerra o painel atual.
Up, Down # Move para o painel acima, abaixo, a esquerda ou a direita.
Left, Right
@@ -100,10 +96,10 @@ combinação de teclas de prefixo.
# 4) Principal verticamente.
# 5) Mosaico
- C-Up, C-Down # Altera o tamanho do painel corrente baseado em uma célula.
+ C-Up, C-Down # Altera o tamanho do painel atual em uma célula.
C-Left, C-Right
- M-Up, M-Down # Altera o tamanho do painel corrente baseado em cinco células.
+ M-Up, M-Down # Altera o tamanho do painel atual em cinco células.
M-Left, M-Right
```
@@ -116,17 +112,13 @@ Existe um arquivo chamado tmux.conf, ele pode ser usado para definir opções no
```
-# Exemplo de tmux.conf
-# 2014.10
+# Exemplo tmux.conf
+# 2015.12
### General
###########################################################################
-# Habilita UTF-8
-setw -g utf8 on
-set-option -g status-utf8 on
-
# Limite da história de comandos
set -g history-limit 2048
@@ -134,14 +126,14 @@ set -g history-limit 2048
set -g base-index 1
# Mouse
-set-option -g mouse-select-pane on
+set-option -g -q mouse on
# Recarregar o arquivo de configuração sem a necessidade de reiniciar o programa
unbind r
bind r source-file ~/.tmux.conf
-### Teclas de atalho
+### Keybinds / Comandos
###########################################################################
# Desvincular C-b como prefixo padrão.
@@ -150,7 +142,7 @@ unbind C-b
# Define um novo prefixo padrão.
set-option -g prefix `
-# Definir prefixos que podem ser usados para voltar para a janela anterior.
+# Voltar janela anterior quando comando for usado duas vezes.
bind C-a last-window
bind ` last-window
@@ -158,11 +150,11 @@ bind ` last-window
bind F11 set-option -g prefix C-a
bind F12 set-option -g prefix `
-# Preferencia de teclas de atalho
+# Preferencia de comandos
setw -g mode-keys vi
set-option -g status-keys vi
-# Mover enter paineis com teclas de orientaçao do vim
+# Alternar enter painéis com teclas de orientaçao do vim
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
@@ -174,7 +166,7 @@ bind f next-window
bind E swap-window -t -1
bind F swap-window -t +1
-# Iterar entre os painéis
+# Dividir painéis
bind = split-window -h
bind - split-window -v
unbind '"'
@@ -184,7 +176,7 @@ unbind %
bind a send-prefix
-### Theme
+### Theme // Estilo
###########################################################################
# Paleta de cores para a barra de status
@@ -209,8 +201,6 @@ setw -g window-status-bg black
setw -g window-status-current-fg green
setw -g window-status-bell-attr default
setw -g window-status-bell-fg red
-setw -g window-status-content-attr default
-setw -g window-status-content-fg yellow
setw -g window-status-activity-attr default
setw -g window-status-activity-fg yellow
diff --git a/pt-br/vim-pt.html.markdown b/pt-br/vim-pt.html.markdown
new file mode 100644
index 00000000..4f70079a
--- /dev/null
+++ b/pt-br/vim-pt.html.markdown
@@ -0,0 +1,239 @@
+---
+category: tool
+tool: vim
+contributors:
+ - ["RadhikaG", "https://github.com/RadhikaG"]
+translators:
+ - ["David Lima", "https://github.com/davelima"]
+lang: pt-br
+filename: LearnVim-pt.txt
+---
+
+
+[Vim](www.vim.org)
+(Vi IMproved - Vi Melhorado) é um clone do editor vi para Unix. Ele é um
+editor de texto projetado para ter velocidade e produtividade, e está presente
+na maioria dos systemas UNIX. O editor tem um grande número de atalhos de teclado
+para agilizar a navegação para pontos específicos no arquivo, além de edição rápida.
+
+## Navegação do Vim: o básico
+
+```
+ vim <nome-do-arquivo> # Abre <nome-do-arquivo> no vim
+ :q # Fecha o vim
+ :w # Salva o arquivo atual
+ :wq # Salva o arquivo e fecha o vim
+ :q! # Fecha o vim e descarta as alterações no arquivo
+ # ! *força* :q a executar, fechando o vim sem salvar antes
+ :x # Salvar o arquivo e fechao vim (atalho para :wq)
+
+ u # Desfazer
+ CTRL+R # Refazer
+
+ h # Move o cursor para a esquerda
+ j # Move o cursor para baixo
+ k # Move o cursor para cima
+ l # Move o cursor para a direita
+
+ # Movendo o cursor dentro da linha
+
+ 0 # Move para o início da linha
+ $ # Move para o final da linha
+ ^ # Move para o primeiro caractere da linha (ignora caracteres em branco)
+
+ # Pesquisa no texto
+
+ /palavra # Destaca todas as ocorrências de 'palavra' após o cursor
+ ?palavra # Destaca todas as ocorrências de 'palavra' antes do cursor
+ n # Move o cursor para a próxima ocorrência após a pesquisa
+ N # Move o cursor para a ocorrência anterior após a pesquisa
+
+ :%s/foo/bar/g # Substitui 'foo' por 'bar' no arquivo inteiro
+ :s/foo/bar/g # Substitui 'foo' por 'bar' na linha atual
+
+ # Pulando para caracteres específicos
+
+ f<caracter> # Posiciona o cursor no próximo <caracter>
+ t<character> # Posiciona o cursor antes do próximo <caracter>
+
+ # Por exemplo,
+ f< # Posiciona o cursor no <
+ t< # Posiciona o cursor logo antes do <
+
+ # Movendo por palavras
+
+ w # Move o cursor uma palavra a diante
+ b # Move o cursor uma palavra atrás
+ e # Move o cursor ao fim da palavra atual
+
+ # Outros caracteres para mover o cursor no arquivo
+
+ gg # Move para o topo do arquivo
+ G # Move para o final do arquivo
+ :NUM # Move para a linha NUM (NUM é qualquer número)
+ H # Move para o topo da tela visível
+ M # Move para o meio da tela visível
+ L # Move para o final da tela visível
+```
+
+## Modos:
+
+O Vim é baseado no conceito de **modos**.
+
+Modo Comando - usado para navegar e escrever comandos - o Vim já inicia nesse modo
+Modo Inserção - usado para fazer alterações no arquivo
+Modo Visual - usado para destacar textos e executar comandos neles
+Modo Ex - usado para ir a linha com ':' no final da tela para executar comandos
+
+```
+ i # Coloca o Vim no Modo Inserção, logo antes do cursor
+ a # Coloca o Vim no Modo Inserção, logo após o cursor
+ v # Coloca o Vim no Modo Visual
+ : # Coloca o Vim no Modo Ex
+ <esc> # Sai de qualquer modo que você estiver, e coloca o Vim no Modo Comando
+
+ # Copiando e colando texto
+
+ y # Coloca a seleção atual na área de transferência
+ yy # Coloca a linha atual na área de transferência
+ d # Deleta a seleção tual
+ dd # Deleta a linha atual
+ p # Cola o texto copiado após a posição do cursor
+ P # Cola o texto copiado antes da posição do cursor
+ x # Deleta o caractere que está na posição do cursor
+```
+
+## A 'Gramática' do Vim
+
+Podemos pensar no Vim como uma série de comendos
+em um formato 'Verbo-Modificador-Nome', onde:
+
+Verbo - sua ação
+Modificador - como você executará sua ação
+Nome - o objeto onde você vai executar sua acão
+
+Alguns exemplos importantes de 'Verbos', 'Modificadores' e 'Nomes':
+
+```
+ # 'Verbos'
+
+ d # Apagar (Delete)
+ c # Alterar (Change)
+ y # Copiar (Yank)
+ v # Seleção Visual
+
+ # 'Modificadores'
+
+ i # Dentro (Inside)
+ a # Em torno de (Around)
+ NUM # Número (NUM qualquer número)
+ f # Pesquisa algo e posiciona o cursor acima do resultado
+ t # Pesquisa algo e posiciona o cursor logo antes do resultado
+ / # Encontra algo a frente do cursor
+ ? # Encontra algo antes do cursor
+
+ # 'Nomes'
+
+ w # Palavra (word)
+ s # Sentência
+ p # Parágrafo
+ b # Bloco
+
+ # Exemplos de comandos
+
+ d2w # Apaga 2 palavras
+ cis # Altera dentro de uma sentência
+ yip # Coloca o parágrafo atual da área de transferência)
+ ct< # Altera para '<'
+ # Altera todo o texto a partir da posição do cursor até o próximo '<'
+ d$ # Apaga tudo da posição do cursor até o final da linha
+```
+
+## Alguns atalhos e dicas
+
+ <!--TODO: Adicionar mais!-->
+```
+ > # Adiciona um bloco de indentação
+ < # Remove um bloco de indentação
+ :earlier 15m # Reverte o documento para como ele estava há 15 minutos atrás
+ :later 15m # Reverte o comando acima
+ ddp # Troca linhas consecutivas de posição, dd e depois p
+ . # Repete a última ação
+```
+
+## Macros
+
+Macros, basicamente, são ações graváveis.
+Quando você começa a gravar uma macro, ele salva **toda** ação e comando
+que você usar, até que você pare de gravar. Ao executar uma macro, ele aplica
+exatamente a mesma sequencia de ações e comandos na seleção atual.
+
+```
+ qa # Inicia a gravação de uma macro chamado 'a'
+ q # Para a gravação
+ @a # Executa a macro
+```
+
+### Configurando o ~/.vimrc
+
+O arquivo .vimrc pode ser usado para configurar o Vim no seu início.
+
+Exemplo de arquivo ~/.vimrc
+
+```
+" Exemplo de ~/.vimrc
+" 2015.10
+
+" Obrigatório para rodar apenas no Vim (Vi Improved)
+set nocompatible
+
+" Determina o tipo de arquivo pelo nome para habilitar indentação automática, etc
+filetype indent plugin on
+
+" Habilita sintaxe colorida
+syntax on
+
+" Ativa um 'auto-completar' melhor para a linha de comando
+set wildmenu
+
+" Faz as buscas não diferenciarem maiúsculas-minúsculas (case insensitive)
+" Exceto quando você usar letras maiúsculas
+set ignorecase
+set smartcase
+
+" Quando criar uma nova linha e a indentação por tipo de arquivo estiver
+" desabilitada, mantem a mesma indentação da linha atual
+set autoindent
+
+" Mostra o número das linhas à esquerda
+set number
+
+" Opções de indentação, aqui você pode mudar como preferir
+
+" Número de espaços visíveis por TAB
+set tabstop=4
+
+" Número de espaços por TAB ao editar um arquivo
+set softtabstop=4
+
+" Número de espaços usados nas funções de indentação (>> e <<)
+set shiftwidth=4
+
+" Converte TABs em espaços
+set expandtab
+
+" Habilita indentação/alinhamento inteligente
+set smarttab
+```
+
+### Referências
+
+[Vim | Home](http://www.vim.org/index.php) (EN)
+
+`$ vimtutor pt`
+
+[Vim: um tutorial/cartilha](https://danielmiessler.com/study/vim/) (EN)
+
+[O que são as partes sombrias do Vim que sua mãe nunca te explicou? (tópico no Stack Overflow)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about) (EN)
+
+[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim) (EN)
diff --git a/pt-pt/git-pt.html.markdown b/pt-pt/git-pt.html.markdown
index a85c9704..bd0f0fc5 100644
--- a/pt-pt/git-pt.html.markdown
+++ b/pt-pt/git-pt.html.markdown
@@ -2,7 +2,7 @@
category: tool
tool: git
lang: pt-pt
-filename: LearnGit.txt
+filename: LearnGit-pt.txt
contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
translators:
diff --git a/pyqt.html.markdown b/pyqt.html.markdown
index 7ce71d96..6bdb6488 100644
--- a/pyqt.html.markdown
+++ b/pyqt.html.markdown
@@ -1,10 +1,9 @@
---
category: tool
tool: PyQT
-filename: learnqt.py
+filename: learnpyqt.py
contributors:
- ["Nathan Hughes", "https://github.com/sirsharpest"]
-lang: en
---
**Qt** is a widely-known framework for developing cross-platform software that can be run on various software and hardware platforms with little or no change in the code, while having the power and speed of native applications. Though **Qt** was originally written in *C++*.
@@ -14,7 +13,7 @@ This is an adaption on the C++ intro to QT by [Aleksey Kholovchuk](https://githu
), some of the code examples should result in the same functionality
this version just having been done using pyqt!
-```Python
+```python
import sys
from PyQt4 import QtGui
diff --git a/python.html.markdown b/python.html.markdown
index 55f56071..050503c3 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -550,7 +550,7 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
# You can construct set and dict comprehensions as well.
-{x for x in 'abcddeef' if x in 'abc'} # => {'d', 'e', 'f'}
+{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'}
{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
diff --git a/python3.html.markdown b/python3.html.markdown
index 341f0a39..3821d84f 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -37,8 +37,6 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea
1 + 1 # => 2
8 - 1 # => 7
10 * 2 # => 20
-
-# Except division which returns floats, real numbers, by default
35 / 5 # => 7.0
# Result of integer division truncated down both for positive and negative.
@@ -47,8 +45,8 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
-# When you use a float, results are floats
-3 * 2.0 # => 6.0
+# The result of division is always a float
+10.0 / 3 # => 3.3333333333333335
# Modulo operation
7 % 3 # => 1
@@ -145,13 +143,13 @@ None # => None
"etc" is None # => False
None is None # => True
-# None, 0, and empty strings/lists/dicts all evaluate to False.
+# None, 0, and empty strings/lists/dicts/tuples all evaluate to False.
# All other values are True
bool(0) # => False
bool("") # => False
bool([]) # => False
bool({}) # => False
-
+bool(()) # => False
####################################################
## 2. Variables and Collections
@@ -493,7 +491,7 @@ next(our_iterator) # => "one"
next(our_iterator) # => "two"
next(our_iterator) # => "three"
-# After the iterator has returned all of its data, it gives you a StopIterator Exception
+# After the iterator has returned all of its data, it gives you a StopIteration Exception
next(our_iterator) # Raises StopIteration
# You can grab all the elements of an iterator by calling list() on it.
@@ -761,8 +759,13 @@ if __name__ == '__main__':
print(b.say('hello'))
print(b.fly)
+# To take advantage of modularization by file you could place the classes above in their own files,
+# say, human.py and bat.py
+# to import functions from other files use the following format
# from "filename-without-extension" import "function-or-class"
+
+# superhero.py
from human import Human
from bat import Bat
diff --git a/racket.html.markdown b/racket.html.markdown
index 96dcaf25..38335bc1 100644
--- a/racket.html.markdown
+++ b/racket.html.markdown
@@ -164,10 +164,17 @@ my-pet ; => #<dog>
(cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3)
;; `list' is a convenience variadic constructor for lists
(list 1 2 3) ; => '(1 2 3)
-;; and a quote can also be used for a literal list value
+;; a quote can also be used for a literal list value
'(1 2 3) ; => '(1 2 3)
+;; a quasiquote (represented by the backtick character) with commas
+;; can be used to evaluate functions
+`(1 ,(+ 1 1) 3) ; => '(1 2 3)
-;; Racket has predefined functions on top of car and cdr, to extract parts of a list
+;; With lists, car/cdr work slightly differently
+(car '(1 2 3)) ; => 1
+(cdr '(1 2 3)) ; => '(2 3)
+
+;; Racket also has predefined functions on top of car and cdr, to extract parts of a list
(cadr (list 1 2 3)) ; => 2
(car (cdr (list 1 2 3))) ; => 2
diff --git a/red.html.markdown b/red.html.markdown
index 05da3c3f..6d10fe8f 100644
--- a/red.html.markdown
+++ b/red.html.markdown
@@ -23,17 +23,17 @@ from any platform to any other platform. And it will do this all from a binary e
Ready to learn your first Red?
```
-All text before the header will be treated as comment, as long as you avoid using the
-word "red" starting with a capital "R" in this pre-header text. This is a temporary
-shortcoming of the used lexer but most of the time you start your script or program
-with the header itself.
+All text before the header will be treated as comment, as long as you avoid
+using the word "red" starting with a capital "R" in this pre-header text.
+This is a temporary shortcoming of the used lexer but most of the time you
+start your script or program with the header itself.
+
The header of a red script is the capitalized word "red" followed by a
-whitespace character followed by a block of square brackets [].
-The block of brackets can be filled with useful information about this script or
-program: the author's name, the filename, the version, the license, a summary of
-what the program does or any other files it needs.
-The red/System header is just like the red header, only saying "red/System" and
-not "red".
+whitespace character followed by a block of square brackets []. The block of
+brackets can be filled with useful information about this script or program:
+the author's name, the filename, the version, the license, a summary of what
+the program does or any other files it needs. The red/System header is just
+like the red header, only saying "red/System" and not "red".
Red []
@@ -50,9 +50,9 @@ comment {
; no need to restrict this to a 'main' function.
; Valid variable names start with a letter and can contain numbers,
-; variables containing only capital A thru F and numbers and ending with 'h' are
-; forbidden, because that is how hexadecimal numbers are expressed in Red and
-; Red/System.
+; variables containing only capital A thru F and numbers and ending with 'h'
+; are forbidden, because that is how hexadecimal numbers are expressed in Red
+; and Red/System.
; assign a value to a variable using a colon ":"
my-name: "Red"
@@ -63,8 +63,8 @@ reason-for-using-the-colon: {Assigning values using the colon makes
}
is-this-name-valid?: true
-; print output using print, or prin for printing without a newline or linefeed at the
-; end of the printed text.
+; print output using print, or prin for printing without a newline or linefeed
+; at the end of the printed text.
prin " My name is " print my-name
My name is Red
@@ -72,7 +72,7 @@ My name is Red
print ["My name is " my-name lf]
My name is Red
-; In case you haven't already noticed: statements do NOT end with a semicolon ;-)
+; If you haven't already noticed: statements do NOT end with a semicolon ;-)
;
; Datatypes
@@ -85,13 +85,13 @@ My name is Red
; Some of the available types are integer! string! block!
; Declaring variables before using them?
-; Red knows by itself what variable is best to use for the data you want to use it
-; for.
+; Red knows by itself what variable is best to use for the data you want to
+; use it for.
; A variable declaration is not always necessary.
; It is considered good coding practise to declare your variables,
; but it is not forced upon you by Red.
-; You can declare a variable and specify its type. a variable's type determines its
-; size in bytes.
+; You can declare a variable and specify its type. a variable's type
+; determines its size in bytes.
; Variables of integer! type are usually 4 bytes or 32 bits
my-integer: 0
@@ -111,10 +111,10 @@ i2 - i1 ; result 1
i2 * i1 ; result 2
i1 / i2 ; result 0 (0.5, but truncated towards 0)
-; Comparison operators are probably familiar, and unlike in other languages you
-; only need a single '=' sign for comparison.
-; There is a boolean like type in Red. It has values true and false, but also the
-; values on/off or yes/no can be used
+; Comparison operators are probably familiar, and unlike in other languages
+; you only need a single '=' sign for comparison.
+; There is a boolean like type in Red. It has values true and false, but also
+; the values on/off or yes/no can be used
3 = 2 ; result false
3 != 2 ; result true
@@ -127,14 +127,14 @@ i1 / i2 ; result 0 (0.5, but truncated towards 0)
; Control Structures
;
; if
-; Evaluate a block of code if a given condition is true. IF does not return any value,
-; so cannot be used in an expression.
+; Evaluate a block of code if a given condition is true. IF does not return
+; any value, so cannot be used in an expression.
if a < 0 [print "a is negative"]
; either
-; Evaluate a block of code if a given condition is true, else evaluate an alternative
-; block of code. If the last expressions in both blocks have the same type, EITHER can
-; be used inside an expression.
+; Evaluate a block of code if a given condition is true, else evaluate an
+; alternative block of code. If the last expressions in both blocks have the
+; same type, EITHER can be used inside an expression.
either a < 0 [
either a = 0 [
msg: "zero"
@@ -172,8 +172,8 @@ until [
]
; will output:
ooooo
-; Note that the loop will always be evaluated at least once, even if the condition is
-; not met from the beginning.
+; Note that the loop will always be evaluated at least once, even if the
+; condition is not met from the beginning.
; while
; While a given condition is met, evaluate a block of code.
diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown
index e06ae9bd..6c8622cc 100644
--- a/ru-ru/go-ru.html.markdown
+++ b/ru-ru/go-ru.html.markdown
@@ -35,6 +35,7 @@ package main
// Import предназначен для указания зависимостей этого файла.
import (
"fmt" // Пакет в стандартной библиотеке Go
+ "io/ioutil" // Реализация функций ввод/ввывода.
"net/http" // Да, это веб-сервер!
"strconv" // Конвертирование типов в строки и обратно
m "math" // Импортировать math под локальным именем m.
@@ -321,6 +322,14 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Обработка запроса и отправка данных методом из http.ResponseWriter
w.Write([]byte("You learned Go in Y minutes!"))
}
+
+func requestServer() {
+ resp, err := http.Get("http://localhost:8080")
+ fmt.Println(err)
+ defer resp.Body.Close()
+ body, err := ioutil.ReadAll(resp.Body)
+ fmt.Printf("\nWebserver said: `%s`", string(body))
+}
```
## Что дальше
diff --git a/ru-ru/html-ru.html.markdown b/ru-ru/html-ru.html.markdown
new file mode 100644
index 00000000..5069d77f
--- /dev/null
+++ b/ru-ru/html-ru.html.markdown
@@ -0,0 +1,129 @@
+---
+language: html
+filename: learnhtml.html
+contributors:
+ - ["Christophe THOMAS", "https://github.com/WinChris"]
+translators:
+ - ["Lana Tim", "https://github.com/LanaTim"]
+lang: ru-ru
+---
+
+HTML расшифровывается как Hypertext Markup Language(гипертекстовый язык разметки).
+Это язык используют для написания страниц для World Wide Web(всемирной паутины).
+Это язык разметки позволяет писать веб-страниц с помощью кода, чтобы определять,
+как должны быть отображены текст и данные.
+На самом деле, HTML файлы представляют собой простые текстовые файлы.
+Что такое разметка? Это способ организации данных страницы,
+путем открытия и закрытия тегов(помещая данные внутрь этих тегов).
+Эта разметка служит, чтобы придать значение тексту, который он окружает.
+Как и в других языках программирования, HTML имеет много версий. Здесь мы будем говорить о HTML5.
+
+
+**Примечание:** Вы можете тестировать различные теги и элементы по мере продвижения
+через учебник на сайте, как [codepen](http://codepen.io/pen/) для того, чтобы увидеть
+их влияние, понять, как они работают и ознакомиться с языком.
+В данной статье рассматривается в основном HTML синтаксис и некоторые полезные советы.
+
+```html
+<!-- Комментарии заключаются как эта лини\! -->
+
+<!-- #################### Теги #################### -->
+
+<!-- Ниже приведен пример HTML-файл, который мы будем анализировать. -->
+
+<!doctype html>
+ <html>
+ <head>
+ <title>Мой сайт</title>
+ </head>
+ <body>
+ <h1>Привет, мир!</h1>
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">
+ Переходите сюда, чтоб посмотреть как это выглядит.
+ </a>
+ <p>Это параграф.</p>
+ <p>Это другой параграф.</p>
+ <ul>
+ <li>Это элемент не нумерованного списка (маркированный список)</li>
+ <li>Это другой элемент</li>
+ <li>Это последний элемент в списке</li>
+ </ul>
+ </body>
+ </html>
+
+<!-- HTML-файл всегда начинается с указанием браузеру, что страница это HTML. -->
+<!doctype html>
+
+<!-- После этого, страница начинается с <html> тега. -->
+<html>
+
+<!-- страница будет закрыта в конце с помощью тега </html>. -->
+</html>
+
+<!-- Ничто не должно появиться после этого заключительного тега. -->
+
+<!-- Внутри (между открывающим и закрывающим тегами <html> </ html>), мы находим: -->
+
+<!-- Заголовок определяется <head> (it он должен быть закрыт </head>). -->
+<!-- Заголовок содержит описание и дополнительную информацию, которая не отображается; это метаданные. -->
+
+<head>
+ <title>Мой сайт</title><!-- Тег <title> указывает браузеру заголовок, чтобы показать в строке заголовка названия и вкладки браузера окна. -->
+</head>
+
+<!-- После секция <head>, находится секция - <body> -->
+<!-- До этого момента, ничего описаное не будет отображаться в окне браузера. -->
+<!-- Мы должны наполнить <body> содержанием, которое будет отображаться. -->
+
+<body>
+ <h1>Hello, world!</h1> <!-- Тег h1 создает заголовок. -->
+ <!-- Так же существуют другие заголовки от имеющего большее значение <h1> по убыванию к <h6>. -->
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Переходите сюда, чтоб посмотреть как это выглядит.</a>
+ <!--гиперссылка на URL, заданнf атрибутом href="" -->
+ <p>Это параграф.</p> <!-- Тег <p> позволяет нам добавдять текст на странице HTML. -->
+ <p>Это другой параграф.</p>
+ <ul> <!-- Тег <ul> создает маркированный список. -->
+ <!-- Для того, чтобы иметь пронумерованный список лучше использовать <ol>
+ тогда первый элемент будет иметь значение 1. для второго элемента, 2. и так далее. -->
+ <li>Это элемент в не нумерованном списке (маркированный список)</li>
+ <li>Это еще один элемент</li>
+ <li>И это последний пункт в списке</li>
+ </ul>
+</body>
+
+<!-- Вот так просто можно создать HTML страницу. -->
+
+<!--Но можно добавить множество дополнительных типов HTML тегов. -->
+
+<!-- Для вставки картинки -->
+<img src="http://i.imgur.com/XWG0O.gif"/> <!-- Источник изображения указывается с помощью атрибута src="" -->
+<!-- Источником может быть URL или даже путь к файлу на вашем компьютере. -->
+
+<!-- Кроме того, можно создать таблицу. -->
+
+<table> <!-- Мы открыли <table> элемент. -->
+ <tr> <!-- <tr> позволяет создать ряд. -->
+ <th>Первый заголовок</th> <!-- <th> позволяет дать название для столбца таблицы. -->
+ <th>Второй заголовок</th>
+ </tr>
+ <tr>
+ <td>Первый ряд, первая колонка</td> <!-- <td> позволяет нам создать ячейку таблицы. -->
+ <td>Первый ряд, вторая колонка</td>
+ </tr>
+ <tr>
+ <td>Второй ряв, первая колонка</td>
+ <td>Второй ряд, вторая колонка</td>
+ </tr>
+</table>
+
+```
+
+## Применение
+
+HTML файлы имеют окончание(расширение) `.html`.
+
+## Узнать больше
+
+* [википедиа](https://ru.wikipedia.org/wiki/HTML)
+* [HTML учебник](https://developer.mozilla.org/ru/docs/Web/HTML)
+* [htmlbook](http://htmlbook.ru/)
diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown
index f71435ea..ff7a0cc3 100644
--- a/ru-ru/markdown-ru.html.markdown
+++ b/ru-ru/markdown-ru.html.markdown
@@ -5,7 +5,7 @@ contributors:
- ["Jacob Ward", "http://github.com/JacobCWard/"]
translators:
- ["Pirogov Alexey", "http://twitter.com/alex_pir"]
- - ["Andre Polykanine", https://github.com/Oire"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
filename: markdown-ru.md
lang: ru-ru
---
diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown
index b5feb105..181368de 100644
--- a/ru-ru/php-ru.html.markdown
+++ b/ru-ru/php-ru.html.markdown
@@ -58,8 +58,10 @@ $int1 = 12; // => 12
$int2 = -12; // => -12
$int3 = 012; // => 10 (ведущий 0 обозначает восьмеричное число)
$int4 = 0x0F; // => 15 (ведущие символы 0x означают шестнадцатеричное число)
+
// Двоичная запись integer доступна начиная с PHP 5.4.0.
$int5 = 0b11111111; // 255 (0b в начале означает двоичное число)
+
// Дробные числа
$float = 1.234;
$float = 1.2e3;
@@ -87,6 +89,7 @@ $dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.'
// Специальные (escape) символы работают только в двойных кавычках
$escaped = "This contains a \t tab character.";
$unescaped = 'This just contains a slash and a t: \t';
+
// Заключайте переменные в фигурные скобки, если это необходимо
$apples = "I have {$number} apples to eat.";
$oranges = "I have ${number} oranges to eat.";
@@ -684,8 +687,160 @@ use My\Namespace as SomeOtherNamespace;
$cls = new SomeOtherNamespace\MyClass();
+*//**********************
+* Позднее статическое связывание.
+*
+*/
+
+class ParentClass
+{
+ public static function who()
+ {
+ echo "I'm a " . __CLASS__ . "\n";
+ }
+
+ public static function test()
+ {
+ // self ссылается на класс в котором определен метод.
+ self::who();
+ // static ссылается на класс в котором метод вызван.
+ static::who();
+ }
+}
+
+ParentClass::test();
+/*
+I'm a ParentClass
+I'm a ParentClass
+*/
+
+class ChildClass extends ParentClass
+{
+ public static function who()
+ {
+ echo "But I'm " . __CLASS__ . "\n";
+ }
+}
+
+ChildClass::test();
+/*
+I'm a ParentClass
+But I'm ChildClass
+
+/**********************
+* Позднее статическое связывание.
+*
+*/
+
+class ParentClass
+{
+ public static function who()
+ {
+ echo "I'm a " . __CLASS__ . "\n";
+ }
+
+ public static function test()
+ {
+ // self ссылается на класс в котором определен метод.
+ self::who();
+ // static ссылается на класс в котором метод вызван.
+ static::who();
+ }
+}
+
+ParentClass::test();
+/*
+I'm a ParentClass
+I'm a ParentClass
*/
+class ChildClass extends ParentClass
+{
+ public static function who()
+ {
+ echo "But I'm " . __CLASS__ . "\n";
+ }
+}
+
+ChildClass::test();
+/*
+I'm a ParentClass
+But I'm ChildClass
+*/
+
+
+/**********************
+* Магические константы
+*
+*/
+
+// Возвращает имя текущего класса. Должно быть использовано внутри класса.
+echo "Current class name is " . __CLASS__;
+
+// Возвращает полный путь текущей папки из которой вызван файл.
+echo "Current directory is " . __DIR__;
+
+ // Обычно используют в таких случаях:
+ require __DIR__ . '/vendor/autoload.php';
+
+// Возвращает полный путь к текущему файлу.
+echo "Current file path is " . __FILE__;
+
+// Возвращает имя текущей функции.
+echo "Current function name is " . __FUNCTION__;
+
+// Возвращает номер текущей линии.
+echo "Current line number is " . __LINE__;
+
+// Возвращает имя текущего метода. Возвращает только если вызван внутри метода.
+echo "Current method is " . __METHOD__;
+
+// Возвращает имя текущего пространства имен.
+echo "Current namespace is " . __NAMESPACE__;
+
+// Возвращает имя текущего трейта.
+// Возвращает только если испольщуется внутри трейта.
+echo "Current namespace is " . __TRAIT__;
+
+
+/**********************
+* Обработка ошибок
+*
+*/
+
+// Простую обработку ошибок можно произвести спомощью try catch блока.
+
+try {
+ // Выполняем что-то
+} catch (Exception $e) {
+ // Обработка исключения
+}
+
+// При использовании try catch блока в области вилимости, стоит использовать
+// следующий подход:
+
+try {
+ // Do something
+} catch (\Exception $e) {
+ // Обработка исключения
+}
+
+// Специальное(кастомное) исключение - exceptions
+
+class MyException extends Exception {}
+
+try {
+
+ $condition = true;
+
+ if ($condition) {
+ throw new MyException('Something just happend');
+ }
+
+} catch (MyException $e) {
+ // Обработка исключения
+}
+
```
## Смотрите также:
@@ -695,4 +850,4 @@ $cls = new SomeOtherNamespace\MyClass();
Если вы раньше пользовались языком с хорошей организацией пакетов, посмотрите [Composer](http://getcomposer.org/).
-Для изучения стандартов использования языка посетите PHP Framework Interoperability Group's [PSR standards](https://github.com/php-fig/fig-standards).
+Для изучения стандартов использования языка посетите PHP Framework Interoperability Group's [PSR standards](https://github.com/php-fig/fig-standards).
diff --git a/ru-ru/typescript-ru.html.markdown b/ru-ru/typescript-ru.html.markdown
index 67b58a38..09bbb2d1 100644
--- a/ru-ru/typescript-ru.html.markdown
+++ b/ru-ru/typescript-ru.html.markdown
@@ -5,7 +5,7 @@ contributors:
- ["Philippe Vlérick", "https://github.com/pvlerick"]
translators:
- ["Fadil Mamedov", "https://github.com/fadilmamedov"]
- - "Andre Polykanine", "https://github.com/Oire"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
filename: learntypescript-ru.ts
---
diff --git a/ru-ru/vim-ru.html.markdown b/ru-ru/vim-ru.html.markdown
new file mode 100644
index 00000000..6f62fd49
--- /dev/null
+++ b/ru-ru/vim-ru.html.markdown
@@ -0,0 +1,241 @@
+---
+category: tool
+tool: vim
+contributors:
+ - ["RadhikaG", "https://github.com/RadhikaG"]
+translators:
+ - ["Anton Slukovskiy", "https://github.com/slukovskiy"]
+filename: LearnVim-ru.txt
+lang: ru-ru
+---
+
+[Vim](www.vim.org)
+(Vi IMproved) это клон полулярного текстового редактора для Unix. Он разработан
+с целью повышения скорости и продуктивности и повсеместно используется в
+большинство Юникс-подобных систем. В нем имеется множество клавиатурных
+сочетаний для быстрой навигации к определенным точкам в файле и быстрого
+редактирования.
+
+## Основы навигации в vim
+
+```
+ vim <filename> # Открыть <filename> в vim
+ :q # Выйти из vim
+ :w # Сохранить текущий файл
+ :wq # Сохранить и выйти
+ :q! # Выйти из vim не сохраняя файл
+
+ :x # Сохранить файл и выйти из vim, короткая версия :wq
+
+ u # Отмена последней команды
+ CTRL+R # Отмена отмены
+
+ h # Переместить курсор на один символ влево
+ j # Переместить курсор на один символ вниз
+ k # Переместить курсор на один символ вверх
+ l # Переместить курсор на один символ вправо
+
+ # Перемещение по строке
+
+ 0 # Переместить курсор к началу строки
+ $ # Переместить курсор к концу строки
+ ^ # Переместить курсор к первому непустому символу в строке
+
+ # Поиск в тексте
+
+ /<word> # Подсветить все вхождения <word> в тексте после курсора
+ ?<word> # Подсветить все вхождения <word> в тексте до курсора
+ n # Передвигает курсор к следующему вхождения искомого слова
+ N # Передвигает курсор к предыдущему вхождения искомого слова
+
+ :%s/foo/bar/g # Меняет «foo» на «bar» во всем файле
+ :s/foo/bar/g # Меняет «foo» на «bar» на текущей строке
+
+ # Переходы к символу
+
+ f<character> # Перенести курсор к <character>
+ t<character> # Перенести курсор вперед и остановиться прямо
+ # перед <character>
+
+ # Например,
+ f< # Перести курсор и остановиться на <
+ t< # Перенсти курсор и остановиться прямо перед <
+
+ # Перемещение по словам
+
+ w # Переместиться вперед на одно слово
+ b # Перенеститься назад на одно слово
+ e # Перейти к концу текущего слова
+
+ # Другие команды для передвижения по тексту
+
+ gg # Перейти к началу файла
+ G # Перейти к концу файла
+ :NUM # Перейти к строке под номером NUM
+ # (NUM может быть любым числом)
+ H # Переместить курсор к верхнему краю экрана
+ M # Переместить курсор к середине экрана
+ L # Переместить курсор к нижнему краю экрана
+```
+
+## Режимы:
+
+Vim основывается на концепте **режимов**.
+
+Командный режим - vim запускается в этом режиме по-умолчанию, используется для
+навигации и ввода команд.
+Режим ввода - используется для внесения изменений в файле.
+Визуальный режим - используется для подсветки текста и выполнения операций над ним.
+Режим командной строки - используется для ввода команд в нижнем углу экрана после символа «:».
+
+```
+ i # Переводит vim в режим вставки перед позицией курсора
+ a # Переводит vim в режим вставки после позиции курсора
+ v # Переводит vim в визуальный режим
+ : # Переводит vim в режим командной строки
+ <esc> # Выходит из любого режима в котором вы находитесь
+ # в командный режим
+
+ # Копирование и вставка текста
+
+ y # Скопировать выделенное
+ yy # Скопировать текущую строку
+ d # Удалить выделенное
+ dd # Удалить текущую строку
+ p # Вставить скопированный текст после текущей позиции курсора
+ P # Вставить скопированный текст перед текущей позицией курсора
+ x # Удалить символ под текущей позицией курсора
+```
+
+## «Грамматика» vim
+
+Vim можно рассматривать как набор команд в формате «Глагол-Модификатор-Существительное», где:
+
+Глагол - ваше действие.
+Модификатор - то как вы его выполняете.
+Существительное - объект над которым вы его выполняете.
+
+Несколько важных пример «Глаголов», «Модификаторов», и «Существительных»:
+
+```
+ # «Глаголы»
+
+ d # Удалить
+ c # Изменить
+ y # Скопировать
+ v # Визуально выделить
+
+ # «Модификаторы»
+
+ i # Внутри
+ a # Снаружи
+ NUM # Число
+ f # Ищет что-то и останавливается на нем
+ t # Ищет что-то и останавливается перед ним
+ / # Ищет строку после курсора
+ ? # Ищет строку перед курсором
+
+ # «Существительные»
+
+ w # Слово
+ s # Предложение
+ p # Параграф
+ b # Блок
+
+ # Образцы «предложений» или команд
+
+ d2w # Удалить 2 слова
+ cis # Изменить объемлющее предложение
+ yip # Скопировать объемлющий параграф
+ ct< # Изменяет текст от курсора до следующей открывающей скобки
+ d$ # Удалить все от положения курсора до конца строки
+```
+
+## Некоторые сокращения и хитрости
+
+ <!--TODO: Add more!-->
+```
+ > # Сдвинуть выделенное на один отступ вправо
+ < # Сдвинуть выделенное на один отступ влево
+ :earlier 15m # Возвращает документ к состоянию в котором он был
+ # 15 минут назад
+ :later 15m # Отменяет предыдущую команду
+ ddp # Меняет позиции последовательных строк, сначала dd затем p
+ . # Повторяет предыдущее действие
+```
+
+## Макросы
+
+Макросы это просто записываемые действия.
+Во время записи макросы запоминают **все** действия и команды до тех пор пока
+запись не будет остановлена.При вызове макрос применяет ту же самую последовательность
+действий и команд на выделенном тексте.
+
+```
+ qa # Начать запись макроса под именем «a»
+ q # Закончить запись
+ @a # Выполнить макрос
+```
+
+### Настройка ~/.vimrc
+
+Файл .vimrc может использоваться для настройки Vim при запуске.
+
+Вот пример файла ~/.vimrc:
+
+```
+" Пример ~/.vimrc
+" 2015.10
+
+" Отключает совместимость со старым vi
+set nocompatible
+
+" Определяет тип файла по его имени для разрешения автоматических отступов и т. д.
+filetype indent plugin on
+
+" Включает подсветку синтаксиса
+syntax on
+
+" Улучшенное автодополнение команд
+set wildmenu
+
+" Использовать поиск не чувствительный к регистру
+" за исключением использования заглавный букв
+set ignorecase
+set smartcase
+
+" Копирует отступы с текущей строки при добавлении новой
+set autoindent
+
+" Показывать номера строк
+set number
+
+" Настройки отступов, изменяйте по собственному вкусу
+
+" Количество видимых пробелов на один символ табуляции
+set tabstop=4
+
+" Количество пробелов в символе табуляции при редактировании
+set softtabstop=4
+
+" Количество пробелов в отступе при использовании операций >> и <<
+set shiftwidth=4
+
+" Конвертировать символы табуляции в пробелы
+set expandtab
+
+" Включить умную табуляцию и пробелы для отступов и выравнивания
+set smarttab
+```
+
+### Ссылки
+
+[Vim | Home (EN)](http://www.vim.org/index.php)
+
+`$ vimtutor`
+
+[A vim Tutorial and Primer (EN)](https://danielmiessler.com/study/vim/)
+
+[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread) (EN)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about)
+
+[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim_%28%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9%29)
diff --git a/ru-ru/xml-ru.html.markdown b/ru-ru/xml-ru.html.markdown
index b0096b75..bf3f22b0 100644
--- a/ru-ru/xml-ru.html.markdown
+++ b/ru-ru/xml-ru.html.markdown
@@ -128,3 +128,18 @@ XML-документ, который следует описанию докум
</book>
</bookstore>
```
+
+## DTD совместимость и определение XML Schema(схем/структуры)
+
+Поддержка DTDs является повсеместным, потому что это довольно старая технология. К сожалению, современные функции XML как пространств имен(namespaces) не поддерживаются DTDs. Определения XML-схемы (XSDs) предназначены для замены DTDs которая в свою очередь предназначена для определения грамматики XML-документа.
+
+## Ресурсы
+
+* [Валидатор XML (ссылка на английском языке)](http://www.xmlvalidation.com)
+
+## Для будущего прочтения
+
+* [XML Schema Definitions Tutorial (ссылка на английском языке)](http://www.w3schools.com/schema/)
+* [DTD руководство (ссылка на английском языке)](http://www.w3schools.com/xml/xml_dtd_intro.asp)
+* [XML руководство (ссылка на английском языке)](http://www.w3schools.com/xml/default.asp)
+* [использование XPath запросов для парсинга XML (ссылка на английском языке)](http://www.w3schools.com/xml/xml_xpath.asp)
diff --git a/sass.html.markdown b/sass.html.markdown
index 802b40f4..860e550a 100644
--- a/sass.html.markdown
+++ b/sass.html.markdown
@@ -95,7 +95,7 @@ Useful for checking variables while debugging your SCSS. */
/* @for is a control loop that iterates through a range of values.
Particularly useful for setting styles on a collection of items.
-There are two forms, "through" and "to." The former includes the last value,
+There are two forms, "through" and "to". The former includes the last value,
the latter stops at the last value. */
@for $c from 1 to 4 {
@@ -206,7 +206,7 @@ $social-links: facebook twitter linkedin reddit;
}
-/*Mixins
+/* Mixins
==============================*/
/* If you find you are writing the same code for more than one
@@ -301,7 +301,7 @@ body {
mixins. When trying to choose between a function or a mixin, remember
that mixins are best for generating CSS while functions are better for
logic that might be used throughout your Sass code. The examples in
- the Math Operators' section are ideal candidates for becoming a reusable
+ the 'Math Operators' section are ideal candidates for becoming a reusable
function. */
/* This function will take a target size and the parent size and calculate
@@ -577,9 +577,7 @@ You can use either syntax, just go into the settings and select either Sass or S
## Compatibility
-Sass can be used in any project as long as you have a program to compile it
-into CSS. You'll want to verify that the CSS you're using is compatible
-with your target browsers.
+Sass can be used in any project as long as you have a program to compile it into CSS. You'll want to verify that the CSS you're using is compatible with your target browsers.
[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility.
diff --git a/scala.html.markdown b/scala.html.markdown
index 5e3ece2d..d33b6234 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -19,20 +19,20 @@ Scala - the scalable language
Setup Scala:
1) Download Scala - http://www.scala-lang.org/downloads
- 2) Unzip/untar to your favourite location and put the bin subdir in your `PATH` environment variable
+ 2) Unzip/untar to your favorite location and put the bin subdir in your `PATH` environment variable
*/
/*
Try the REPL
-
- Scala has a tool called the REPL (Read-Eval-Print Loop) that is anologus to
+
+ Scala has a tool called the REPL (Read-Eval-Print Loop) that is anologus to
commandline interpreters in many other languages. You may type any Scala
expression, and the result will be evaluated and printed.
-
- The REPL is a very handy tool to test and verify code. Use it as you read
+
+ The REPL is a very handy tool to test and verify code. Use it as you read
this tutorial to quickly explore concepts on your own.
*/
-
+
// Start a Scala REPL by running `scala`. You should see the prompt:
$ scala
scala>
@@ -50,7 +50,7 @@ res1: Int = 6
scala> :type (true, 2.0)
(Boolean, Double)
-// REPL sessions can be saved
+// REPL sessions can be saved
scala> :save /sites/repl-test.scala
// Files can be loaded into the REPL
@@ -59,7 +59,7 @@ Loading /sites/repl-test.scala...
res2: Int = 4
res3: Int = 6
-// You can search your recent history
+// You can search your recent history
scala> :h?
1 2 + 2
2 res0 + 2
@@ -594,7 +594,7 @@ for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared
* best practices around them. We only include this section in the tutorial
* because they are so commonplace in Scala libraries that it is impossible to
* do anything meaningful without using a library that has implicits. This is
- * meant for you to understand and work with implicts, not declare your own.
+ * meant for you to understand and work with implicits, not declare your own.
*/
// Any value (vals, functions, objects, etc) can be declared to be implicit by
diff --git a/sk-sk/LearnGit-sk.txt b/sk-sk/LearnGit-sk.txt
deleted file mode 100644
index 070a0489..00000000
--- a/sk-sk/LearnGit-sk.txt
+++ /dev/null
@@ -1,208 +0,0 @@
-$ git init
-
-# Zobraz a Nastav Základné Konfiguračné Premenné (Globálne)
-$ git config --global user.email "MôjEmail@Zoho.com"
-$ git config --global user.name "Moje Meno
-
-# Rýchlo zobraz všetky dostupné príkazy
-$ git help
-
-# Zobraz všetky dostupné príkazy
-$ git help -a
-
-# Zobraz konkrétnu pomoc - použivateľský manuál
-# git help <príkaz_tu>
-$ git help add
-$ git help commit
-$ git help init
-# alebo git <príkaz_tu> --help
-$ git add --help
-$ git commit --help
-$ git init --help
-
-# Zobrazí vetvu, nesledované súbory, zmeny a ostatné rozdiely
-$ git status
-# Zistí iné vychytávky o git statuse
-$ git help status
-
-# pridá súbor z tvojho pracovného adresára
-$ git add HelloWorld.java
-
-# pridá súbor z iného adresára
-$ git add /cesta/k/súboru/HelloWorld.c
-
-# Môžeš použiť regulárne výrazy!
-$ git add ./*.java
-
-# zobraz existujúce vetvy a vzdialené repozitáre
-$ git branch -a
-
-# vytvor novú vetvu
-$ git branch myNewBranch
-
-# vymaž vetvu
-$ git branch -d myBranch
-
-# premenuj vetvu
-# git branch -m <starémeno> <novémeno>
-$ git branch -m mojaStaraVetva mojaNovaVetva
-
-# zmeň opis vetvy
-$ git branch myBranchName --edit-description
-
-# Zobrazí tagy
-$ git tag
-# Vytvorí tag so správou
-# -m špecifikuje správu, ktorá bude s tagom uložená.
-# Ak nešpeficikuješ správu pri tagu so správou,
-# Git spustí tvoj editor, aby si ju napísal.
-$ git tag -a v2.0 -m 'moja verzia 2.0'
-
-# Ukáž informácie o tagu
-# Zobrazí zadané informácie, dátum tagnutia commitu
-# a správu pred zobrazením informácií o commite.
-$ git show v2.0
-
-# Zverejní (pushne) jediný tag do vzdialeného repozitára
-$ git push origin v2.0
-
-# Zverejní viacero tagov do vzdialeného repozitára
-$ git push origin --tags
-
-# Aktualizuj strom, aby odpovedal (predvolene)
-# hlavnej vetve repozitáru (master branch)
-$ git checkout
-
-# Aktualizuj strom, aby odpovedal konrkétnej vetve
-$ git checkout menoVetvy
-
-# Vytvor novú vetvu & prepni sa na ňu
-# ekvivalentný príkaz: "git branch <meno>; git checkout <meno>"
-$ git checkout -b nováVetva
-
-# Naklonuj learnxinyminutes-docs
-$ git clone https://github.com/adambard/learnxinyminutes-docs.git
-
-# povrchné klonovanie - rýchlejšie, uloží iba najnovšiu snímku
-$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git
-
-# naklonuj iba konkrétnu vetvu
-$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch
-
-# commitni so správou
-$ git commit -m "Pridal som multiplyNumbers() funkciu do HelloWorld.c"
-
-# automaticky pridaj zmenené a vymazané súbory do staging indexu, potom ich commitni.
-$ git commit -a -m "Zmenil som foo.php a vymazal bar.php"
-
-# zmeň posledný commit (toto nahradí predchádzajúci commit novým)
-$ git commit --amend -m "Správna správa"
-
-# Ukáž rozdiel medzi pracovným repozitárom a indexom.
-$ git diff
-
-# Ukáž rozdiely medzi indexom a najnovším commitom.
-$ git diff --cached
-
-# Ukáž rozdiely medzi pracovným adresárom a najnovším commitom.
-$ git diff HEAD
-
-# Nastav, aby sa vo výsledkoch vyhľadávania zobrazovalo číslo riadku
-$ git config --global grep.lineNumber true
-
-# Urob výsledky vyhľadávania čitateľnejšie, vrátane zoskupovania
-$ git config --global alias.g "grep --break --heading --line-number"
-
-# Vďaka Travisovi Jefferymu za túto sekciu
-# Hľadaj "názovPremennej" vo všetkých java súboroch
-$ git grep 'názovPremennej' -- '*.java'
-
-# Hľadaj riadok, ktorý obsahuje "názovPoľa" a "add" alebo "remove"
-$ git grep -e 'arrayListName' --and \( -e add -e remove \)
-
-# Zobraz všetky commity
-$ git log
-
-# Zobraz iba správy a referencie commitov
-$ git log --oneline
-
-# Zobraz zlúčené (merged) commity
-$ git log --merges
-
-# Zobraz všetky commity vo forme ASCII grafu
-$ git log --graph
-
-# Zlúč vybranú vetvu do aktuálnej.
-$ git merge názovVetvy
-
-# Vždy vytvor zlučovací commit
-$ git merge --no-ff názovVetvy
-
-# Premenuj súbor
-$ git mv HelloWorld.c HelloNewWorld.c
-
-# Presuň súbor
-$ git mv HelloWorld.c ./nová/cesta/HelloWorld.c
-
-# "Nasilu" premenuj, alebo presuň
-# "existujúciSúbor" už v adresári existuje, bude prepísaný
-$ git mv -f môjSúbor existujúciSúbor
-
-# Aktualizuje tvoj lokálny repozitár zlúčením nových zmien
-# zo vzdialených "origin" a "master" vetiev.
-# git pull <alias-vzdialeného-repo> <vetva>
-$ git pull origin master
-
-# Predvolene, git pull aktualizuje tvoju aktuálnu vetvu
-# zlúčením nových zmien zo vzdialenej vetvy
-$ git pull
-
-# Zlúč zmeny zo vzdialenej vetvy a presuň vetvu do nového základného commitu (rebase)
-# vetva commitne na tvoj lokálny repozitár, ekvivalentný príkaz: "git pull <alias-vzdialeného-repo> <vrstva>, git rebase <branch>"
-$ git pull origin master --rebase
-
-# Zverejni a zlúč zmeny z lokálneho repozitára do
-# vzdialených vetiev s názvom "origin" a "master".
-# git push <vzdialené> <vetvy>
-$ git push origin master
-
-# Predvolene git zverejní a zlúči zmeny z
-# aktuálnej vetvy do vzdialenej vetvy s ňou spojenej
-$ git push
-
-# Na spojenie lokálnej vetvy so vzdialenou pridaj -u:
-$ git push -u origin master
-# Kedykoľvek budeš chcieť zverejniť z rovnakej lokálnej vetvy, použi príkaz:
-$ git push
-
-# Aplikuj commity z experimentálnej vetvy na master
-# git rebase <základnáVetva> <ináVetva>
-$ git rebase master experimentBranch
-
-# Resetni index (vrstvu medzi pracovným stromom a Git repozitárom), aby odpovedal najnovšiemu commitu (adresár ostane nezmenený)
-$ git reset
-
-# Resetni index, aby odpovedal najnovšiemu commitu (adresár sa prepíše)
-$ git reset --hard
-
-# Presunie vrchol aktuálnuej vetvy do konkrétneho commitu (adresár ostane nezmenený)
-# všetky zmeny sú zachované v adresári.
-$ git reset 31f2bb1
-
-# Vezmi späť konkrétny commit
-$ git revert <commit>
-
-# odstráň HelloWorld.c
-$ git rm HelloWorld.c
-
-# Odstráň súbor z vnoreného adresára
-$ git rm /pather/to/the/file/HelloWorld.c
-
-
-
-
-
-
-
-
-
diff --git a/sk-sk/elixir.html.markdown b/sk-sk/elixir.html.markdown
new file mode 100644
index 00000000..2401f92e
--- /dev/null
+++ b/sk-sk/elixir.html.markdown
@@ -0,0 +1,470 @@
+---
+language: elixir
+contributors:
+ - ["Joao Marques", "http://github.com/mrshankly"]
+ - ["Dzianis Dashkevich", "https://github.com/dskecse"]
+ - ["Ryan Plant", "https://github.com/ryanplant-au"]
+translators:
+ - ["Peter Szatmary", "https://github.com/peterszatmary"]
+lang: sk-sk
+filename: learnelixir-sk.ex
+---
+
+Elixir je moderný funkcionálny jazyk vytvorený nad Erlang VM (virtuálnym
+strojom). Je plne kompatibilný s Erlangom, ale ponúka viac štandardnú syntax
+a množstvo funkcií.
+
+```Elixir
+
+# Jednoriadkový komentár začína symbolom #
+
+# Neexistuje viacriadkový komentár, avšak je možné vyskladať za sebou viac
+# jednoriadkových komentárov.
+
+# Pre spustenie Elixir shellu zadajte príkaz `iex`
+# Kompiláciu zdrojových kódov vykonáte príkazom `elixirc`
+
+# Obe príkazy by sa už mali nachádzať v path pokiaľ ste nainštalovali elixir
+# správne.
+
+## ---------------------------
+## -- Základné typy
+## ---------------------------
+
+# Čísla
+3 # integer
+0x1F # integer
+3.0 # float
+
+# Atómy, sú literály, konštanty s rovnakým menom. Začínajú s `:`.
+:ahoj # atom
+
+# Tzv. Tuples sú v pamäti uložené súvisle.
+{1,2,3} # tuple
+
+# Pristúpiť k tuple elementu vieme pomocou funkcie `elem`:
+elem({1, 2, 3}, 0) #=> 1
+
+# Zoznamy sú implementované ako linkované zoznamy.
+[1,2,3] # zoznam
+
+# Vieme pristúpiť k hlavičke (head) a chvostu (tail) zoznamu:
+[head | tail] = [1,2,3]
+head #=> 1
+tail #=> [2,3]
+
+# V Elixire, rovnako ako v Erlangu, `=` znamená pattern matching a nie
+# klasické priradenie.
+#
+# To znamená, že ľavá strana (pattern / vzor) je postavená oproti pravej
+# strane.
+#
+# Takto funguje aj príklad vyššie s čítaním hlavičky a chvosta zoznamu.
+
+# Pattern match končí chybou ak sa obe strany nezhodujú, v tomto príklade majú
+# tuples rôznu veľkosť.
+# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2}
+
+# Binárne typy
+<<1,2,3>> # binary
+
+# Reťazce a zoznamy znakov
+"ahoj" # reťazec
+'ahoj' # zoznam znakov
+
+# Viacriadkový reťazec
+"""
+Ja som viacriadkový
+reťazec.
+"""
+#=> "Ja som viacriadkový\nreťazec.\n"
+
+# Reťazce sú kódované v UTF-8:
+"héllò" #=> "héllò"
+
+# Reťazce sú skutočne iba binárne typy, a zoznamy znakov sú iba zoznamy.
+<<?a, ?b, ?c>> #=> "abc"
+[?a, ?b, ?c] #=> 'abc'
+
+# `?a` v elixire vráti ASCII číselnú reprezentáciu pre znak `a`
+?a #=> 97
+
+# Pre spájanie zoznamov sa používa `++`, pre binárne typy `<>`
+[1,2,3] ++ [4,5] #=> [1,2,3,4,5]
+'ahoj ' ++ 'svet' #=> 'ahoj svet'
+
+<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>>
+"Ahoj " <> "svet" #=> "ahoj svet"
+
+# Rozsahy sú reprezentované ako `začiatok..koniec` (obe inkluzívne)
+1..10 #=> 1..10
+dolna..horna = 1..10 # Na rozsahy možno použiť rovnako pattern matching
+[dolna, horna] #=> [1, 10]
+
+# Mapy sú páry kľúč-hodnota
+pohlavia = %{"david" => "muž", "gillian" => "žena"}
+pohlavia["david"] #=> "muž"
+
+# Mapy s kľúčmi reprezentovanými atómami môžu byť použité takto
+pohlavia = %{david: "muž", gillian: "žena"}
+pohlavia.gillian #=> "žena"
+
+## ---------------------------
+## -- Operátory
+## ---------------------------
+
+# Trošku matematiky
+1 + 1 #=> 2
+10 - 5 #=> 5
+5 * 2 #=> 10
+10 / 2 #=> 5.0
+
+# V elixire operátor `/` vždy vráti float (reálne číslo).
+
+# Pre celočíselné delenie sa používa `div`
+div(10, 2) #=> 5
+
+# Pre celočíselné delenie so zvyškom `rem`
+rem(10, 3) #=> 1
+
+# Boolean operátory: `or`, `and` a `not`.
+# Tieto operátori očakávajú ako svoj prvý argument boolean.
+true and true #=> true
+false or true #=> true
+# 1 and true #=> ** (ArgumentError) argument error
+
+# Elixir tiež poskytuje `||`, `&&` a `!` , ktoré akceptujú argumenty
+# ľubovoľného typu.
+# Všetky hodnoty okrem `false` a `nil` budú vyhodnotené ako true.
+1 || true #=> 1
+false && 1 #=> false
+nil && 20 #=> nil
+!true #=> false
+
+# Pre porovnávanie máme: `==`, `!=`, `===`, `!==`, `<=`,
+`>=`, `<` a `>`
+1 == 1 #=> true
+1 != 1 #=> false
+1 < 2 #=> true
+
+# `===` a `!==` sú viac striktné pri porovnávaní celých čísel (integer) a
+# desatinných čísel (float).
+1 == 1.0 #=> true
+1 === 1.0 #=> false
+
+# Vieme porovnať dokonca dva rôzne údajové typy:
+1 < :ahoj #=> true
+
+# Celkové poradie triedenia:
+#
+# číslo < atom < referencia < funkcia < port < pid < tuple < zoznam < bitový
+# string
+
+# Výrok Joe Armstronga: "Aktuálne poradie nie je dôležité, ale
+# dôležité je to, že celkové poradie je dobre definované."
+
+## ---------------------------
+## -- Riadenie toku
+## ---------------------------
+
+# `if` výraz
+if false do
+ "Toto nebude nikdy videné"
+else
+ "Toto bude"
+end
+
+# Existuje aj `unless`
+unless true do
+ "Toto nebude nikdy videné"
+else
+ "Toto bude"
+end
+
+# Pamätáte sa na pattern matching? Mnoho štruktúr pre riadenie toku v
+# elixire sa spoliehajú práve na pattern matching.
+
+# `case` dovolí nám porovnať hodnotu oproti mnohým vzorom:
+case {:one, :two} do
+ {:four, :five} ->
+ "Toto nebude zhodné"
+ {:one, x} ->
+ "Toto bude zhodné a nastaví `x` na hodnotu `:two` "
+ _ ->
+ "Toto bude zhodné z ľubovoľnou hodnotou."
+end
+
+# Je zvyčajné nastaviť hodnotu do `_` ak ju nepotrebujete.
+# Napríklad, ak je pre nás potrebná iba hlavička zoznamu (head):
+[head | _] = [1,2,3]
+head #=> 1
+
+# Pre lepšiu čitateľnosť môžme urobiť nasledovné:
+[head | _tail] = [:a, :b, :c]
+head #=> :a
+
+# `cond` dovoľuje kontrolovať viac podmienok naraz.
+# Použite `cond` namiesto vnorovania mnohých `if` výrazov.
+cond do
+ 1 + 1 == 3 ->
+ "Nebudem nikdy videný"
+ 2 * 5 == 12 ->
+ "Ani ja"
+ 1 + 2 == 3 ->
+ "Ja budem"
+end
+
+# Je bežné nastaviť poslednú podmienku rovnajúcu sa `true` , ktorá bude vždy
+# zodpovedať.
+cond do
+ 1 + 1 == 3 ->
+ "Nebudem nikdy videný"
+ 2 * 5 == 12 ->
+ "Ani ja"
+ true ->
+ "Ale ja budem (je to v podstate vetva else)"
+end
+
+# `try/catch` sa používa na zachytenie hodnôt, ktoré boli vyhodené, takisto
+# podporuje `after` klauzulu, ktorá je zavolaná vždy, či bola hodnota
+# zachytená alebo nie.
+try do
+ throw(:ahoj)
+catch
+ message -> "Mám #{message}."
+after
+ IO.puts("Som after klauzula.")
+end
+#=> Som after klauzula
+# "Mám :ahoj"
+
+## ---------------------------
+## -- Moduly a funkcie
+## ---------------------------
+
+# Anonymné funkcie (všimnite si bodku)
+stvorec = fn(x) -> x * x end
+stvorec.(5) #=> 25
+
+# Takisto akceptujú viax klauzúl a tzv. stráže (guards).
+# Stráže vám umožnia pattern matching ešte viac zlepšiť, tieto časti sú
+# označené kľúčovým slovom `when`:
+f = fn
+ x, y when x > 0 -> x + y
+ x, y -> x * y
+end
+
+f.(1, 3) #=> 4
+f.(-1, 3) #=> -3
+
+# Elixir tiež poskytuje množstvo vstavaných funkcií.
+# Tie sú dostupné v aktuálnom scope (viditeľnej oblasti).
+is_number(10) #=> true
+is_list("hello") #=> false
+elem({1,2,3}, 0) #=> 1
+
+# Možno zgrupovať viac funkcií do jedného modulu. V module použite `def`
+# na definíciu funkcie.
+defmodule Matematika do
+ def sucet(a, b) do
+ a + b
+ end
+
+ def na_druhu(x) do
+ x * x
+ end
+end
+
+Matematika.sucet(1, 2) #=> 3
+Matematika.na_druhu(3) #=> 9
+
+# Na zkompilovanie našeho Matematika modulu ho uložte ako `math.ex` a použite
+# `elixirc` v termináli: elixirc math.ex
+
+# V module môžme definovať funkcie s `def` a privátne funkcie s `defp`.
+# Funkcia definovaná s `def` je možné volať z iných modulov, privátne funkcie
+# môžu byť volané iba lokálne.
+defmodule SukromnaMatematika do
+ def sucet(a, b) do
+ rob_sucet(a, b)
+ end
+
+ defp rob_sucet(a, b) do
+ a + b
+ end
+end
+
+SukromnaMatematika.sucet(1, 2) #=> 3
+# SukromnaMatematika.rob_sucet(1, 2) #=> ** (UndefinedFunctionError)
+
+# Deklarácie funkcií tiež podporujú stráže (guards) a viacnásobné klauzuly:
+
+defmodule Geometria do
+ def oblast({:obdlznik, w, h}) do
+ w * h
+ end
+
+ def oblast({:kruh, r}) when is_number(r) do
+ 3.14 * r * r
+ end
+end
+
+Geometria.oblast({:obdlznik, 2, 3}) #=> 6
+Geometria.oblast({:kruh, 3}) #=> 28.25999999999999801048
+# Geometria.oblast({:kruh, "nie_je_cislo"})
+#=> ** (FunctionClauseError) no function clause matching in Geometria.oblast/1
+
+# Vďaka nemeniteľnosti (immutability) je rekurzia významnou časťou elixiru
+defmodule Rekurzia do
+ def sumuj_zoznam([hlavicka | schvost], acc) do
+ sumuj_zoznam(chvost, acc + hlavicka)
+ end
+
+ def sumuj_zoznam([], acc) do
+ acc
+ end
+end
+
+Rekurzia.sumuj_zoznam([1,2,3], 0) #=> 6
+
+# Elixir moduly podporujú atribúty, existujú vstavané atribúty a takisto
+# môžte pridávať vlastné.
+defmodule MojModul do
+ @moduledoc """
+ Toto je vstavaný atribút v príkladovom module.
+ """
+
+ @moj_udaj 100 # Toto je vlastný atribút.
+ IO.inspect(@moj_udaj) #=> 100
+end
+
+# Pipe operátor (rúra) |> umožnuje predať výsledok výrazu ako prvý parameter
+# do ďalšej funkcie.
+
+Range.new(1,10)
+|> Enum.map(fn x -> x * x end)
+|> Enum.filter(fn x -> rem(x, 2) == 0 end)
+#=> [4, 16, 36, 64, 100]
+
+## ---------------------------
+## -- Štruktúry a výnimky
+## ---------------------------
+
+# Štruktúry sú rozšírenia postavené na mapách, ktoré prinášajú defaultné
+# hodnoty, garancie v čase kompilácie a polymorfizmus do Elixiru.
+defmodule Osoba do
+ defstruct meno: nil, vek: 0, vyska: 0
+end
+
+joe_info = %Osoba{ meno: "Joe", vek: 30, vyska: 180 }
+#=> %Osoba{vek: 30, vyska: 180, meno: "Joe"}
+
+# Prístup k hodnote mena
+joe_info.meno #=> "Joe"
+
+# Zmena hodnoty veku
+starsi_joe_info = %{ joe_info | vek: 31 }
+#=> %Osoba{vek: 31, vyska: 180, meno: "Joe"}
+
+# `try` blok s kľúčovým slovom `rescue` sa používa na riadenie výnimiek
+try do
+ raise "nejaký error"
+rescue
+ RuntimeError -> "zachytí runtime error"
+ _error -> "zachytí ľubovoľný iný error"
+end
+#=> "zachytí runtime error"
+
+# Každá výnimka má správu
+try do
+ raise "nejaký error"
+rescue
+ x in [RuntimeError] ->
+ x.message
+end
+#=> "nejaký error"
+
+## ---------------------------
+## -- Konkurencia
+## ---------------------------
+
+# Elixir sa pri konkurencii spolieha na Actor model. Všetko čo je
+# potrebné na písanie konkuretných programov v elixire sú tri primitívy:
+# spawning procesy, posielanie a prijímanie správ.
+
+# Na spustnenie nového procesu použijeme `spawn` funkciu, ktorá má ako
+# parameter funkciu.
+f = fn -> 2 * 2 end #=> #Function<erl_eval.20.80484245>
+spawn(f) #=> #PID<0.40.0>
+
+# `spawn` vracia pid (identifikátor procesu), tento pid možno použiť na
+# posielanie správ procesu. Správu pošleme `send` operatorátorom.
+# Aby všetko fungovalo ako má, potrebujeme byť schopný správu prijať. To
+# dosiahneme s `receive` mechanizmom:
+
+# `receive do` blok sa používa na počúvanie správ a ich spracúvavanie v čase
+# prijatia. `receive do` blok spracuje iba jednu prijatú správu. Pre
+# spracovanie viacerých správ, musí funkcia s `receive do` blokom rekurzívne
+# volať samu seba, aby sa dostala opäť do `receive do` bloku.
+
+defmodule Geometria do
+ def slucka_oblasti do
+ receive do
+ {:obdlznik, w, h} ->
+ IO.puts("Oblast = #{w * h}")
+ slucka_oblasti()
+ {:kruh, r} ->
+ IO.puts("Oblast = #{3.14 * r * r}")
+ slucka_oblasti()
+ end
+ end
+end
+
+# Kompiluj modul a vytvor proces, ktorý vyhodnotí `slucka_oblasti` v shelli
+
+pid = spawn(fn -> Geometria.slucka_oblasti() end) #=> #PID<0.40.0>
+# Alternatívne
+pid = spawn(Geometria, :slucka_oblasti, [])
+
+# Pošli správu ku `pid`, ktorá bude v zhode so vzorom v receive časti
+send pid, {:obdlznik, 2, 3}
+#=> Oblast = 6
+# {:obdlznik,2,3}
+
+send pid, {:kruh, 2}
+#=> Oblast = 12.56000000000000049738
+# {:kruh,2}
+
+# Shell je takisto proces, môžete použiť `self` pre zistenie aktuálneho pid-u
+self() #=> #PID<0.27.0>
+
+## ---------------------------
+## -- Agenti
+## ---------------------------
+
+# Agent je proces, ktorý udržuje informácie o meniacej sa hodnote
+
+# Vytvor agenta s `Agent.start_link` parametrom, ktorého je funkcia
+# Iniciálny stav agenta bude čokoľvek, čo daná funkcia vráti
+{ok, moj_agent} = Agent.start_link(fn -> ["cervena, zelena"] end)
+
+# `Agent.get` vezme meno agenta a `fn` , ktorej je odovzdaný aktuálny stav
+# Čokoľvek čo `fn` vráti je to, čo dostanete späť
+Agent.get(moj_agent, fn farby -> farby end) #=> ["cervena, "zelena"]
+
+# Zmena stavu agenta rovnakým spôsobom
+Agent.update(moj_agent, fn farby -> ["modra" | farby] end)
+```
+
+## Referencie
+
+* [Začíname](http://elixir-lang.org/getting-started/introduction.html) z
+[Elixir stránky](http://elixir-lang.org)
+* [Elixir dokumentácia](http://elixir-lang.org/docs/master/)
+* [Elixir programovanie](https://pragprog.com/book/elixir/programming-elixir)
+ od Dave Thomasa
+* [Elixir ťahák](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf)
+* [Nauč sa kúsok Erlangu pre veľké dobro!](http://learnyousomeerlang.com/) od
+Freda Heberta
+* [Erlang programovanie: Softvér pre konkurentný svet](https://pragprog
+.com/book/jaerlang2/programming-erlang) od Joe Armstronga
diff --git a/tcl.html.markdown b/tcl.html.markdown
index 9118081d..d3e80f87 100644
--- a/tcl.html.markdown
+++ b/tcl.html.markdown
@@ -57,9 +57,9 @@ lighter that that of Lisp, just gets out of the way.
```tcl
#! /bin/env tclsh
-################################################################################
+###############################################################################
## 1. Guidelines
-################################################################################
+###############################################################################
# Tcl is not Bash or C! This needs to be said because standard shell quoting
# habits almost work in Tcl and it is common for people to pick up Tcl and try
@@ -72,9 +72,9 @@ lighter that that of Lisp, just gets out of the way.
# are formatted as lists.
-################################################################################
+###############################################################################
## 2. Syntax
-################################################################################
+###############################################################################
# Every line is a command. The first word is the name of the command, and
# subsequent words are arguments to the command. Words are delimited by
@@ -151,6 +151,8 @@ set greeting "Hello, [set {first name}]"
# To promote the words within a word to individual words of the current
# command, use the expansion operator, "{*}".
+```
+```tcl
set {*}{name Neo}
# is equivalent to
@@ -171,14 +173,15 @@ namespace eval people {
}
-#The full name of a variable includes its enclosing namespace(s), delimited by two colons:
+# The full name of a variable includes its enclosing namespace(s), delimited by
+# two colons:
set greeting "Hello $people::person1::name"
-################################################################################
+###############################################################################
## 3. A Few Notes
-################################################################################
+###############################################################################
# All other functionality is implemented via commands. From this point on,
# there is no new syntax. Everything else there is to learn about Tcl is about
@@ -192,10 +195,11 @@ set greeting "Hello $people::person1::name"
namespace delete ::
-# Because of name resolution behaviour, it's safer to use the "variable" command to
-# declare or to assign a value to a namespace. If a variable called "name" already
-# exists in the global namespace, using "set" here will assign a value to the global variable
-# instead of creating a new variable in the local namespace.
+# Because of name resolution behaviour, it's safer to use the "variable"
+# command to declare or to assign a value to a namespace. If a variable called
+# "name" already exists in the global namespace, using "set" here will assign
+# a value to the global variable instead of creating a new variable in the
+# local namespace.
namespace eval people {
namespace eval person1 {
variable name Neo
@@ -208,9 +212,9 @@ set people::person1::name Neo
-################################################################################
+###############################################################################
## 4. Commands
-################################################################################
+###############################################################################
# Math can be done with the "expr" command.
set a 3
@@ -294,7 +298,8 @@ while {$i < 10} {
}
-# A list is a specially-formatted string. In the simple case, whitespace is sufficient to delimit values
+# A list is a specially-formatted string. In the simple case, whitespace is
+# sufficient to delimit values
set amounts 10\ 33\ 18
set amount [lindex $amounts 1]
@@ -406,7 +411,7 @@ proc set_double {varname value} {
}
-#get rid of the built-in "while" command.
+# Get rid of the built-in "while" command.
rename ::while {}
diff --git a/tests/encoding.rb b/tests/encoding.rb
new file mode 100644
index 00000000..a0b3b184
--- /dev/null
+++ b/tests/encoding.rb
@@ -0,0 +1,32 @@
+#!/usr/bin/env ruby
+require 'charlock_holmes'
+$file_count = 0;
+markdown_files = Dir["./**/*.html.markdown"]
+markdown_files.each do |file|
+ begin
+ contents = File.read(file)
+ detection = CharlockHolmes::EncodingDetector.detect(contents)
+ case detection[:encoding]
+ when 'UTF-8'
+ $file_count = $file_count + 1
+ when 'ISO-8859-1'
+ $file_count = $file_count + 1
+ when /ISO-8859/
+ puts "Notice: #{file} was detected as #{detection[:encoding]} encoding. Everything is probably fine."
+ $file_count = $file_count + 1
+ else
+ puts "WARNING #{file} was detected as #{detection[:encoding]} encoding. Please save the file in UTF-8!"
+ end
+ rescue Exception => msg
+ puts msg
+ end
+end
+files_failed = markdown_files.length - $file_count
+if files_failed != 0
+ puts "FAILURE!!! #{files_failed} files were unable to be validated as UTF-8!"
+ puts "Please resave the file as UTF-8."
+ exit 1
+else
+ puts "Success. All #{$file_count} files passed UTF-8 validity checks."
+ exit 0
+end
diff --git a/tests/yaml.rb b/tests/yaml.rb
new file mode 100644
index 00000000..0ed918e0
--- /dev/null
+++ b/tests/yaml.rb
@@ -0,0 +1,21 @@
+#!/usr/bin/env ruby
+require 'yaml';
+$file_count = 0;
+markdown_files = Dir["./**/*.html.markdown"]
+markdown_files.each do |file|
+ begin
+ YAML.load_file(file)
+ $file_count = $file_count + 1
+ rescue Exception => msg
+ puts msg
+ end
+end
+files_failed = markdown_files.length - $file_count
+if files_failed != 0
+ puts "FAILURE!!! #{files_failed} files were unable to be parsed!"
+ puts "Please check the YAML headers for the documents that failed!"
+ exit 1
+else
+ puts "All #{$file_count} files were verified valid YAML"
+ exit 0
+end
diff --git a/typescript.html.markdown b/typescript.html.markdown
index 1d712369..23e0bab4 100644
--- a/typescript.html.markdown
+++ b/typescript.html.markdown
@@ -46,10 +46,12 @@ function bigHorribleAlert(): void {
var f1 = function(i: number): number { return i * i; }
// Return type inferred
var f2 = function(i: number) { return i * i; }
+// "Fat arrow" syntax
var f3 = (i: number): number => { return i * i; }
-// Return type inferred
+// "Fat arrow" syntax with return type inferred
var f4 = (i: number) => { return i * i; }
-// Return type inferred, one-liner means no return keyword needed
+// "Fat arrow" syntax with return type inferred, braceless means no return
+// keyword needed
var f5 = (i: number) => i * i;
// Interfaces are structural, anything that has the properties is compliant with
diff --git a/uk-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown
index a84eba67..ac6a2bde 100644
--- a/uk-ua/javascript-ua.html.markdown
+++ b/uk-ua/javascript-ua.html.markdown
@@ -11,7 +11,7 @@ translators:
lang: uk-ua
---
-JavaScript було створено в 1995 році Бренданом Айком, який працював у копаніх Netscape.
+JavaScript було створено в 1995 році Бренданом Айком, який працював у компанії Netscape.
Він був задуманий як проста мова сценаріїв для веб-сайтів, який би доповнював Java
для більш складних веб-застосунків. Але тісна інтеграція з веб-сторінками і
вбудована підтримка браузерами призвела до того, що JavaScript став популярніший
diff --git a/uk-ua/json-ua.html.markdown b/uk-ua/json-ua.html.markdown
index a860e9a7..c9a3d3fb 100644
--- a/uk-ua/json-ua.html.markdown
+++ b/uk-ua/json-ua.html.markdown
@@ -1,24 +1,30 @@
---
language: json
-filename: learnjson-ru.json
+filename: learnjson-ua.json
contributors:
- ["Anna Harren", "https://github.com/iirelu"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
translators:
- ["Ehreshi Ivan", "https://github.com/IvanEh"]
+ - ["Serhii Maksymchuk", "https://github.com/Serg-Maximchuk"]
lang: uk-ua
---
-JSON - це надзвичайно простий формат обміну даними. Це мабуть буде найлегшим курсом
-"Learn X in Y Minutes".
+JSON - це надзвичайно простий формат обміну даними. Згідно з [json.org](http://json.org), для людей він легкий в написанні і читанні, а для комп’ютерів в розборі та генерації.
-В загальному випадку в JSON немає коментарів, але більшість парсерів дозволяють
-використовувати коментарі в С-стилі(//, /\* \*/). Можна залишити кому після останнього
-поля, але все-таки краще такого уникати для кращої сумісності
+JSON підтримує наступні структури даних:
+
+* Колекція пар ключ/значення (`{ "ключ": "значення" }`). У різних мовах програмування реалізується як об’єкт, запис, структура, словник, хеш-таблиця, іменований список або асоціативний масив.
+* Впорядкований список значень (`[ "елемент0", "елемент1" ]`). У різних мовах програмування реалізується як масив, вектор, список або послідовність.
+* Рядки: `"привіт"`, `"\"Лапки\""`, `"\u0abe"`, `"Новий рядок.\n"`
+* Числа: `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4`
+* Інші: `true`, `false`, `null`
+
+JSON в чистій формі не містить коментарів, але більшість парсерів підтримують коментарі в C-стилі (`//`, `/* */`). Деякі парсери також не звертають уваги на кому після останнього поля, але їх варто уникати для кращої сумісності.
```json
{
- "ключ": "значеннь",
+ "ключ": "значення",
"ключі": "завжди мають бути обгорнуті в подвійні лапки",
"числа": 0,
@@ -50,9 +56,9 @@ JSON - це надзвичайно простий формат обміну да
]
],
- "альтернативнтй стиль": {
+ "альтернативний стиль": {
"коментар": "Гляньте!"
- , "позиція коми": "неважлива, поки вона знаходиться до наступного поля"
+ , "позиція коми": "неважлива, коректно якщо вона знаходиться перед наступним полем"
, "інший коментар": "класно"
},
diff --git a/uk-ua/ruby-ua.html.markdown b/uk-ua/ruby-ua.html.markdown
new file mode 100644
index 00000000..74346dfe
--- /dev/null
+++ b/uk-ua/ruby-ua.html.markdown
@@ -0,0 +1,625 @@
+---
+language: ruby
+filename: learnruby-ua.rb
+contributors:
+ - ["David Underwood", "http://theflyingdeveloper.com"]
+ - ["Joel Walden", "http://joelwalden.net"]
+ - ["Luke Holder", "http://twitter.com/lukeholder"]
+ - ["Tristan Hume", "http://thume.ca/"]
+ - ["Nick LaMuro", "https://github.com/NickLaMuro"]
+ - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
+ - ["Dzianis Dashkevich", "https://github.com/dskecse"]
+ - ["Levi Bostian", "https://github.com/levibostian"]
+ - ["Rahil Momin", "https://github.com/iamrahil"]
+ - ["Gabriel Halley", "https://github.com/ghalley"]
+ - ["Persa Zula", "http://persazula.com"]
+ - ["Jake Faris", "https://github.com/farisj"]
+translators:
+ - ["Serhii Maksymchuk", "https://github.com/Serg-Maximchuk"]
+lang: uk-ua
+---
+
+Rubi — це інтерпретована, повністю об'єктно-орієнтована мова програмування з чіткою динамічною типізацією.
+
+```ruby
+# Це коментар
+
+=begin
+Це багаторядковий коментар
+Ніхто їх не використовує
+Тобі теж не варто
+=end
+
+# В першу чергу: все являється об’єктом.
+
+# Числа це об’єкти
+
+3.class #=> Fixnum
+
+3.to_s #=> "3"
+
+
+# Базова арифметика
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+2**5 #=> 32
+5 % 3 #=> 2
+
+# Побітові оператори
+3 & 5 #=> 1
+3 | 5 #=> 7
+3 ^ 5 #=> 6
+
+# Арифметика це просто синтаксичний цукор
+# для виклику методу об’єкта
+1.+(3) #=> 4
+10.* 5 #=> 50
+
+# Спеціальні значення теж об’єкти
+nil # еквівалентно null в інших мовах
+true # істина
+false # хиба
+
+nil.class #=> NilClass
+true.class #=> TrueClass
+false.class #=> FalseClass
+
+# Рівність
+1 == 1 #=> true
+2 == 1 #=> false
+
+# Нерівність
+1 != 1 #=> false
+2 != 1 #=> true
+
+# Окрім власне false, nil це ще одне "хибне" значення
+
+!nil #=> true
+!false #=> true
+!0 #=> false
+
+# Інші порівняння
+1 < 10 #=> true
+1 > 10 #=> false
+2 <= 2 #=> true
+2 >= 2 #=> true
+
+# Комбінований оператор порівняння
+1 <=> 10 #=> -1
+10 <=> 1 #=> 1
+1 <=> 1 #=> 0
+
+# Логічні оператори
+true && false #=> false
+true || false #=> true
+!true #=> false
+
+# Є альтернативні версії логічних операторів з набагато меншим
+# прецедентом. Вони використовуються в конструкціях з контролем
+# виконання ланцюга виразів які повертають булевий результат.
+
+# `do_something_else` викликається лише якщо `do_something` повертає true.
+do_something() and do_something_else()
+# `log_error` викликається лише якщо `do_something` повертає false.
+do_something() or log_error()
+
+
+# Strings це об’єкти
+
+'Я — рядок'.class #=> String
+"Я теж рядок".class #=> String
+
+placeholder = 'використовувати інтерполяцію рядків'
+"Я можу #{placeholder} коли користуюсь рядками в подвійних лапках"
+#=> "Я можу використовувати інтерполяцію рядків коли користуюсь рядками в подвійних лапках"
+
+# Варто надавати перевагу рядкам в одинарних лапках де це можливо
+# Рядки в подвійних лапках викликають додаткові внутрішні обчислення
+
+# Об’єднуйте рядки, але не з числами
+'hello ' + 'world' #=> "hello world"
+'hello ' + 3 #=> TypeError: can't convert Fixnum into String
+'hello ' + 3.to_s #=> "hello 3"
+
+# Об’єднуйте рядки з операторами
+'hello ' * 3 #=> "hello hello hello "
+
+# Додавання до рядка
+'hello' << ' world' #=> "hello world"
+
+# Вивести рядок з переходом на новий рядок вкінці
+puts "Я надрукований!"
+#=> Я надрукований!
+#=> nil
+
+# Вивести рядок без переходу на новий
+print "Я надрукований!"
+#=> Я надрукований! => nil
+
+# Змінні
+x = 25 #=> 25
+x #=> 25
+
+# Зверніть увагу, оператор присвоєння повертає присвоєне значення
+# Отже можна робити одночасне присвоєння кількох змінних:
+x = y = 10 #=> 10
+x #=> 10
+y #=> 10
+
+# Для назв змінних використовується зміїний_регістр
+snake_case = true
+
+# Використовуйте назви змінних які їх характеризують
+path_to_project_root = '/good/name/'
+path = '/bad/name/'
+
+# Символи (теж об’єкти)
+# Символи є незмінними константами багаторазового використання, внутрішньо
+# представлені цілочисельним значенням. Вони часто використовуються замість
+# рядків щоб ефективно передати конкретні, значущі значення.
+
+:pending.class #=> Symbol
+
+status = :pending
+
+status == :pending #=> true
+
+status == 'pending' #=> false
+
+status == :approved #=> false
+
+# Масиви
+
+# Ось масив
+array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+
+# Масиви можуть містити елементи різних типів
+[1, 'hello', false] #=> [1, "hello", false]
+
+# Масиви можуть бути проіндексовані
+# З початку
+array[0] #=> 1
+array.first #=> 1
+array[12] #=> nil
+
+# Як і арифметика, доступ до елемента масиву у вигляді [індекс] — це лише
+# синтаксичний цукор виклику методу [] об’єкта
+array.[] 0 #=> 1
+array.[] 12 #=> nil
+
+# З кінця
+array[-1] #=> 5
+array.last #=> 5
+
+# З початковим індексом та довжиною
+array[2, 3] #=> [3, 4, 5]
+
+# Реверс масиву
+a=[1,2,3]
+a.reverse! #=> [3,2,1]
+
+# Елементи масиву за діапазоном індексів
+array[1..3] #=> [2, 3, 4]
+
+# Додавати елементи в масив можна так:
+array << 6 #=> [1, 2, 3, 4, 5, 6]
+# Або так:
+array.push(6) #=> [1, 2, 3, 4, 5, 6]
+
+# Перевірити чи масив містить елемент
+array.include?(1) #=> true
+
+# Хеш — це масив пар ключ/значення.
+# Хеш оголошується з використанням фігурних дужок:
+hash = { 'color' => 'green', 'number' => 5 }
+
+hash.keys #=> ['color', 'number']
+
+# Значення в хеші може бути швидко знайдене за ключем:
+hash['color'] #=> 'green'
+hash['number'] #=> 5
+
+# Запит значення за неіснуючим ключем повертає nil:
+hash['nothing here'] #=> nil
+
+# Починаючи з Ruby 1.9 з’явився спеціальний синтаксис при використанні
+# символів в якості ключів:
+new_hash = { defcon: 3, action: true }
+
+new_hash.keys #=> [:defcon, :action]
+
+# Перевірка наявності ключів та значень в хеші
+new_hash.key?(:defcon) #=> true
+new_hash.value?(3) #=> true
+
+# Хеші та масиви — перелічувальні типи даних
+# Вони мають багато корисних методів, такі як each, map, count, та інші.
+
+# Оператор вибору "if"
+if true
+ 'якщо'
+elsif false
+ 'інакше якщо, опціонально'
+else
+ 'інакше, також опціонально'
+end
+
+# Оператор циклу "for"
+for counter in 1..5
+ puts "ітерація #{counter}"
+end
+#=> ітерація 1
+#=> ітерація 2
+#=> ітерація 3
+#=> ітерація 4
+#=> ітерація 5
+
+# Проте, ніхто не використовує "for" в циклах.
+# Замість цього варто використовувати метод "each" і передати йому блок.
+# Блок — це відокремлений код який можна передати в метод, наприклад в "each".
+# Це аналог лямбда-виразів, анонімних функцій або замикань в інших мовах програмування.
+
+# Метод "each" для діапазону запускає блок один раз для кожного елементу діапазону.
+# Лічильник передається блоку в якості аргументу.
+
+# Виклик методу "each" з блоком виглядає наступним чином:
+(1..5).each do |counter|
+ puts "ітерація #{counter}"
+end
+#=> ітерація 1
+#=> ітерація 2
+#=> ітерація 3
+#=> ітерація 4
+#=> ітерація 5
+
+# Також можна загорнути блок в фігурні дужки:
+(1..5).each { |counter| puts "ітерація #{counter}" }
+
+# Вміст структур даних також може бути ітерований використовуючи метод "each":
+array.each do |element|
+ puts "#{element} є елементом масиву"
+end
+hash.each do |key, value|
+ puts "#{key} є #{value}"
+end
+
+# Якщо є необхідність індексувати ітерацію, можна використати метод "each_with_index":
+array.each_with_index do |element, index|
+ puts "#{element} під номером #{index} в масиві"
+end
+
+# Оператор циклу "while"
+counter = 1
+while counter <= 5 do
+ puts "ітерація #{counter}"
+ counter += 1
+end
+#=> ітерація 1
+#=> ітерація 2
+#=> ітерація 3
+#=> ітерація 4
+#=> ітерація 5
+
+# Є й інші корисні функції для циклів, такі як "map", "reduce",
+# "inject" та інші. Наприклад "map" в циклі проходить по масиву,
+# виконує над елементами операцію(-ї) в блоці і повертає абсолютно
+# новий масив.
+array = [1,2,3,4,5]
+doubled = array.map do |element|
+ element * 2
+end
+puts doubled
+#=> [2,4,6,8,10]
+puts array
+#=> [1,2,3,4,5]
+
+# Оператор множинного вибору
+grade = 'B'
+
+case grade
+when 'A'
+ puts 'Відмінно!'
+when 'B'
+ puts 'Пощастить наступного разу'
+when 'C'
+ puts 'Ти можеш краще'
+when 'D'
+ puts 'Майже четвірка'
+when 'E'
+ puts 'Випросив'
+when 'F'
+ puts 'Не здав!'
+else
+ puts 'Інша система оцінювання, так?'
+end
+#=> "Пощастить наступного разу"
+
+# Оператор "case" також може використовувати діапазон:
+grade = 82
+case grade
+when 90..100
+ puts 'Ура!'
+when 80...90
+ puts 'Хороша робота'
+when 60...80
+ puts 'Ну, хоч щось'
+else
+ puts 'Не здав!'
+end
+#=> "Хороша робота"
+
+# Обробка вийнятків:
+begin
+ # код з можливим вийнятком
+ raise NoMemoryError, 'Ви використали всю пам’ять.'
+rescue NoMemoryError => exception_variable
+ puts 'Помилка NoMemoryError', exception_variable
+rescue RuntimeError => other_exception_variable
+ puts 'Помилка RuntimeError'
+else
+ puts 'Цей код запуститься якщо вийнятків не було взагалі'
+ensure
+ puts 'Цей код запуститься в будь-якому випадку'
+end
+
+# Функції
+
+def double(x)
+ x * 2
+end
+
+# Функції (і всі блоки) неявно повертають значення останнього виразу
+double(2) #=> 4
+
+# Дужки не є обов’язковими якщо результат недвозначний
+double 3 #=> 6
+
+double double 3 #=> 12
+
+def sum(x, y)
+ x + y
+end
+
+# Аргументи методів розділяються комою
+sum 3, 4 #=> 7
+
+sum sum(3, 4), 5 #=> 12
+
+# yield
+# Всі методи мають неявний, опціональний параметр, який
+# можна викликат за допомогою ключового слова 'yield'
+def surround
+ puts '{'
+ yield
+ puts '}'
+end
+
+surround { puts 'привіт світ' }
+
+# {
+# привіт світ
+# }
+
+
+# Ви можете передати блок у функцію
+# "&" позначає посилання на блок
+def guests(&block)
+ block.call 'some_argument'
+end
+
+# Ви можете передати список аргументів, вони будуть перетворені в масив
+# Для цього існує оператор ("*")
+def guests(*array)
+ array.each { |guest| puts guest }
+end
+
+# Якщо метод повертає масив, ви можете використати деструктуризацію
+def foods
+ ['млинці', 'бутерброд', 'лазанья']
+end
+breakfast, lunch, dinner = foods
+breakfast #=> 'млинці'
+dinner #=> 'лазанья'
+
+# Зазвичай методи які повертають булевий результат закінчуються знаком питання
+5.even? # false
+5.odd? # true
+
+# І якщо метод закінчується знаком оклику, то він робить щось деструктивне
+# типу зміни отриманого аргументу. Багато методів мають версію з "!" які
+# змінюють аргумент, та без "!" що повертають новий об’єкт
+company_name = "Дандер Міфлін"
+company_name.upcase #=> "ДАНДЕР МІФЛІН"
+company_name #=> "Дандер Міфлін"
+company_name.upcase! # змінна company_name зміниться цього разу!
+company_name #=> "ДАНДЕР МІФЛІН"
+
+
+# Клас оголошується ключовим словом class
+class Human
+
+ # Змінна класу. Вона поширюється на всі екземпляри цього класу.
+ @@species = 'Homo sapiens'
+
+ # Основний ініціалізатор
+ def initialize(name, age = 0)
+ # Призначення аргументу "name" до однойменної змінної екземпляру
+ @name = name
+ # Якщо аргумент "age" не заданий, то йому буде присвоєно дефолтне значення
+ # зі списку аргументів
+ @age = age
+ end
+
+ # Метод-сетер
+ def name=(name)
+ @name = name
+ end
+
+ # Метод-ґетер
+ def name
+ @name
+ end
+
+ # Функціональність вище може бути інкапсульована використовуючи метод attr_accessor:
+ attr_accessor :name
+
+ # Ґетери і сетери можуть бути створені індивідуально, наприклад:
+ attr_reader :name
+ attr_writer :name
+
+ # Метод класу позначається ключовим словом "self", щоб відрізнити від
+ # методів екземпляра класу.
+ # Він може бути викликаний лише в класі, але не в екземплярі.
+ def self.say(msg)
+ puts msg
+ end
+
+ def species
+ @@species
+ end
+end
+
+
+# Ініціалізуємо клас
+jim = Human.new('Джим Галперт')
+
+dwight = Human.new('Дуайт Шрут')
+
+# Викличемо кілька методів
+jim.species #=> "Homo sapiens"
+jim.name #=> "Джим Галперт"
+jim.name = "Джим Галперт II" #=> "Джим Галперт II"
+jim.name #=> "Джим Галперт II"
+dwight.species #=> "Homo sapiens"
+dwight.name #=> "Дуайт Шрут"
+
+# Викликати метод класу
+Human.say('Привіт') #=> "Привіт"
+
+# Область видимості змінних визначається способом оголошення імені змінної.
+# Змінні, що починаються на "$" мають глобальну область видимості.
+$var = "Я глобальна змінна"
+defined? $var #=> "global-variable"
+
+# Зміннні, що опчинають на "@" мають область видимості екзкмпляра
+@var = "Я змінна екземпляра"
+defined? @var #=> "instance-variable"
+
+# Змінні, що починаються на "@@" мають область видимості класу
+@@var = "Я змінна класу"
+defined? @@var #=> "class variable"
+
+# Змінні, що починаються з великої букви, є константами
+Var = "Я константа"
+defined? Var #=> "constant"
+
+# Клас теж об’єкт. Тому клас може мати змінні екземпляра.
+# Змінна класу поширюється між класом і всіма його нащадками.
+
+# Базовий клас
+class Human
+ @@foo = 0
+
+ def self.foo
+ @@foo
+ end
+
+ def self.foo=(value)
+ @@foo = value
+ end
+end
+
+# Похідний клас (нащадок)
+class Worker < Human
+end
+
+Human.foo # 0
+Worker.foo # 0
+
+Human.foo = 2 # 2
+Worker.foo # 2
+
+# Змінна екземпляра класу не поширюється між класами-нащадками.
+class Human
+ @bar = 0
+
+ def self.bar
+ @bar
+ end
+
+ def self.bar=(value)
+ @bar = value
+ end
+end
+
+class Doctor < Human
+end
+
+Human.bar # 0
+Doctor.bar # nil
+
+module ModuleExample
+ def foo
+ 'foo'
+ end
+end
+
+# Включення модулів додає їхні методи до екземплярів класу
+# Розширення модулів додає їхні методи в сам клас
+
+class Person
+ include ModuleExample
+end
+
+class Book
+ extend ModuleExample
+end
+
+Person.foo # => NoMethodError: undefined method `foo' for Person:Class
+Person.new.foo # => 'foo'
+Book.foo # => 'foo'
+Book.new.foo # => NoMethodError: undefined method `foo'
+
+# Колбек виконується при включенні і розширенні модуля
+
+module ConcernExample
+ def self.included(base)
+ base.extend(ClassMethods)
+ base.send(:include, InstanceMethods)
+ end
+
+ module ClassMethods
+ def bar
+ 'bar'
+ end
+ end
+
+ module InstanceMethods
+ def qux
+ 'qux'
+ end
+ end
+end
+
+class Something
+ include ConcernExample
+end
+
+Something.bar # => 'bar'
+Something.qux # => NoMethodError: undefined method `qux'
+Something.new.bar # => NoMethodError: undefined method `bar'
+Something.new.qux # => 'qux'
+```
+
+## Додаткові ресурси
+
+- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.
+- [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Learn Ruby through a series of interactive tutorials.
+- [Official Documentation](http://ruby-doc.org/core)
+- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
+- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
+- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
+- [Try Ruby](http://tryruby.org) - Learn the basic of Ruby programming language, interactive in the browser.
diff --git a/vim.html.markdown b/vim.html.markdown
index edbc3da7..96cc20cb 100644
--- a/vim.html.markdown
+++ b/vim.html.markdown
@@ -156,6 +156,7 @@ A few important examples of 'Verbs', 'Modifiers', and 'Nouns':
:later 15m # Reverse above command
ddp # Swap position of consecutive lines, dd then p
. # Repeat previous action
+ :w !sudo tee % # Save the current file as root
```
## Macros
diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown
index 0371e6f6..f081b907 100644
--- a/visualbasic.html.markdown
+++ b/visualbasic.html.markdown
@@ -272,11 +272,3 @@ Module Module1
End Module
```
-
-## References
-
-I learnt Visual Basic in the console application. It allowed me to understand the principles of computer programming to go on to learn other programming languages easily.
-
-I created a more indepth <a href="http://www.vbbootcamp.co.uk/" Title="Visual Basic Tutorial">Visual Basic tutorial</a> for those who would like to learn more.
-
-The entire syntax is valid. Copy the and paste in to the Visual Basic compiler and run (F5) the program.
diff --git a/yaml.html.markdown b/yaml.html.markdown
index a1ef0d38..95adbd83 100644
--- a/yaml.html.markdown
+++ b/yaml.html.markdown
@@ -25,9 +25,9 @@ YAML doesn't allow literal tab characters at all.
key: value
another_key: Another value goes here.
a_number_value: 100
-# If you want to use number 1 as a value, you have to enclose it in quotes,
-# otherwise, YAML parser will assume that it is a boolean value of true.
scientific_notation: 1e+12
+# The number 1 will be interpreted as a number, not a boolean. if you want
+# it to be intepreted as a boolean, use true
boolean: true
null_value: null
key with spaces: value
diff --git a/zh-cn/latex-cn.html.markdown b/zh-cn/latex-cn.html.markdown
new file mode 100644
index 00000000..83491acd
--- /dev/null
+++ b/zh-cn/latex-cn.html.markdown
@@ -0,0 +1,277 @@
+---
+language: latex
+contributors:
+ - ["Chaitanya Krishna Ande", "http://icymist.github.io"]
+ - ["Colton Kohnke", "http://github.com/voltnor"]
+ - ["Sricharan Chiruvolu", "http://sricharan.xyz"]
+ - ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"]
+ - ["Svetlana Golubeva", "https://attillax.github.io/"]
+translators:
+ - ["Dp Leo", "https://github.com/minoriwww"]
+filename: learn-latex-cn.tex
+lang: zh-cn
+---
+
+```tex
+% 所有的注释行以 % 开头
+% 没有多行注释语法
+
+% LaTeX 不是一个“所见即所得” 的文字处理软件
+% 这与 MS Word,和 OpenOffice Writer 不同
+
+% 每一个LaTeX命令由反斜线 (\) 开始
+
+% LaTeX 文档以对编译对象文档的定义开始
+% 这些文档包括书籍,报告,演示等
+% 文档的选项出现在中括号里
+% 下例中,我们设定文章字体为12pt
+\documentclass[12pt]{article}
+
+% 之后我们定义该文档所用的库
+% 如果想要引入图片,彩色字,或是其他语言的源码在您的文档中
+% 您需要增强 LaTeX 的功能。这将通过添加库来实现
+% 下例中将要为展示数据引入 float 和 caption 库
+% 为超链接引入 hyperref 库
+\usepackage{caption}
+\usepackage{float}
+\usepackage{hyperref}
+
+% 我们还可以定义其他文档属性!
+\author{Chaitanya Krishna Ande, Colton Kohnke, Sricharan Chiruvolu \& \\
+Svetlana Golubeva}
+\date{\today}
+\title{Learn \LaTeX \hspace{1pt} in Y Minutes!}
+
+% 现在我们开始正文
+% 这一行之前都是“序章”
+\begin{document}
+% 如果想设定作者,时间,标题字段我们可使用 LaTeX 来建立标题页
+\maketitle
+
+% 分章节时,可以建立目录
+% 我们需要编译文档两次来保证他们顺序正确
+% 使用目录来分开文档是很好的做法
+% 这里我们使用 \newpage 操作符
+\newpage
+\tableofcontents
+
+\newpage
+
+% 许多研究论文有摘要部分。这可以使用预定义的指令来实现
+% 它应被放在逻辑上正确的位置,即顶部标题等的下面和文章主体的上面
+% 该指令可以再报告和文章中使用
+\begin{abstract}
+ \LaTeX \hspace{1pt} documentation written as \LaTeX! How novel and totally not
+ my idea!
+\end{abstract}
+
+% 章节指令非常直观
+% 所有章节标题会自动地添加到目录中
+\section{Introduction}
+Hello, my name is Colton and together we're going to explore \LaTeX!
+
+\section{Another section}
+This is the text for another section. I think it needs a subsection.
+
+\subsection{This is a subsection} % 子章节同样非常直观
+I think we need another one
+
+\subsubsection{Pythagoras}
+Much better now.
+\label{subsec:pythagoras}
+
+% 使用型号我们可以借助 LaTeX 内置的编号功能
+% 这一技巧也在其他指令中有效
+\section*{This is an unnumbered section}
+然而并不是所有章节都要被标序号
+
+\section{Some Text notes}
+%\section{Spacing} % 需要增加有关空白间隔的信息
+\LaTeX \hspace{1pt} is generally pretty good about placing text where it should
+go. If
+a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash
+\hspace{1pt} to the source code. \\
+
+\section{Lists}
+Lists are one of the easiest things to create in \LaTeX! I need to go shopping
+tomorrow, so let's make a grocery list.
+\begin{enumerate} % 此处创建了一个“枚举”环境
+ % \item 使枚举增加一个单位
+ \item Salad.
+ \item 27 watermelon.
+ \item A single jackrabbit.
+ % 我们甚至可以通过使用 [] 覆盖美剧的数量
+ \item[how many?] Medium sized squirt guns.
+
+ Not a list item, but still part of the enumerate.
+
+\end{enumerate} % 所有环境都有终止符
+
+\section{Math}
+
+使用 \LaTeX \hspace{1pt} 的一个最主要的方面是学术论文和技术文章
+通常在数学和科学的领域
+因此我们需要在文章中插入特殊符号! \\
+
+数学符号极多,远超出你能在键盘上找到的那些;
+集合关系符,箭头,操作符,希腊字符等等 \\
+
+集合与关系在数学文章中很重要
+如声明所有 x 属于 X $\forall$ x $\in$ X. \\
+% 注意我们需要在这些符号之前和之后增加 $ 符号
+% 因为在编写时我们处于 text-mode,然而数学符号只在 math-mode 中存在
+% text mode 进入 math-mode 使用 $ 操作符
+% 反之亦然,变量同时会在 math-mode 中被渲染。
+% 我们也可以使用 \[\] 来进入 math mode
+
+\[a^2 + b^2 = c^2 \]
+
+My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$.
+I haven't found a Greek letter yet that \LaTeX \hspace{1pt} doesn't know
+about! \\
+
+常用函数操作符同样很重要:
+trigonometric functions ($\sin$, $\cos$, $\tan$),
+logarithms 和 exponentials ($\log$, $\exp$),
+limits ($\lim$), etc.
+在 LaTeX 指令中预定义
+让我们写一个等式看看发生了什么:
+$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ \\
+
+分数可以写成以下形式:
+
+% 10 / 7
+$$ ^{10}/_{7} $$
+
+% 相对比较复杂的分数可以写成
+% \frac{numerator}{denominator}
+$$ \frac{n!}{k!(n - k)!} $$ \\
+
+我们同样可以插入公式(equations)在环境 ``equation environment'' 下。
+
+% 展示数学相关时,使用方程式环境
+\begin{equation} % 进入 math-mode
+ c^2 = a^2 + b^2.
+ \label{eq:pythagoras} % 为了下一步引用
+\end{equation} % 所有 \begin 语句必须有end语句对应
+
+引用我们的新等式!
+Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also
+the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled:
+figures, equations, sections, etc.
+
+求和(Summations)与整合(Integrals)写作 sum 和 int :
+
+% 一些编译器会提醒在等式环境中的空行
+
+\begin{equation}
+ \sum_{i=0}^{5} f_{i}
+\end{equation}
+\begin{equation}
+ \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
+\end{equation}
+
+\section{Figures}
+
+让我们插入图片。图片的放置非常微妙。
+我在每次使用时都会查找可用选项。
+
+\begin{figure}[H] % H 是放置选项的符号
+ \centering % 图片在本页居中
+ % 宽度放缩为页面的0.8倍
+ %\includegraphics[width=0.8\linewidth]{right-triangle.png}
+ % 需要使用想象力决定是否语句超出编译预期
+ \caption{Right triangle with sides $a$, $b$, $c$}
+ \label{fig:right-triangle}
+\end{figure}
+
+\subsection{Table}
+插入表格与插入图片方式相同
+
+\begin{table}[H]
+ \caption{Caption for the Table.}
+ % 下方的 {} 描述了表格中每一行的绘制方式
+ % 同样,我在每次使用时都会查找可用选项。
+ \begin{tabular}{c|cc}
+ Number & Last Name & First Name \\ % 每一列被 & 分开
+ \hline % 水平线
+ 1 & Biggus & Dickus \\
+ 2 & Monty & Python
+ \end{tabular}
+\end{table}
+
+\section{Getting \LaTeX \hspace{1pt} to not compile something (i.e. Source Code)}
+现在增加一些源代码在 \LaTeX \hspace{1pt} 文档中,
+我们之后需要 \LaTeX \hspace{1pt} 不翻译这些内容而仅仅是把他们打印出来
+这里使用 verbatim environment。
+
+% 也有其他库存在 (如. minty, lstlisting, 等)
+% 但是 verbatim 是最基础和简单的一个
+\begin{verbatim}
+ print("Hello World!")
+ a%b; % 在这一环境下我们可以使用 %
+ random = 4; #decided by fair random dice roll
+\end{verbatim}
+
+\section{Compiling}
+
+现在你大概想了解如何编译这个美妙的文档
+然后得到饱受称赞的 \LaTeX \hspace{1pt} pdf文档
+(这个文档确实被编译了)。 \\
+得到最终文档,使用 \LaTeX \hspace{1pt} 组合步骤:
+ \begin{enumerate}
+ \item Write the document in plain text (the ``source code'').
+ \item Compile source code to produce a pdf.
+ The compilation step looks like this (in Linux): \\
+ \begin{verbatim}
+ > pdflatex learn-latex.tex
+ \end{verbatim}
+ \end{enumerate}
+
+许多 \LaTeX \hspace{1pt}编译器把步骤1和2在同一个软件中进行了整合
+所以你可以只看步骤1完全不看步骤2
+步骤2同样在以下情境中使用情景 \footnote{以防万一,当你使用引用时
+ (如 Eqn.~\ref{eq:pythagoras}),你将需要多次运行步骤2
+来生成一个媒介文件 *.aux 。}.
+% 同时这也是在文档中增加脚标的方式
+
+在步骤1中,用普通文本写入格式化信息
+步骤2的编译阶段则注意在步骤1 中定义的格式信息。
+
+\section{Hyperlinks}
+同样可以在文档中加入超链接
+使用如下命令在序言中引入库:
+\begin{verbatim}
+ \usepackage{hyperref}
+\end{verbatim}
+
+有两种主要的超链接方式 \\
+\url{https://learnxinyminutes.com/docs/latex/}, 或
+\href{https://learnxinyminutes.com/docs/latex/}{shadowed by text}
+% 你不可以增加特殊空格和符号,因为这将会造成编译错误
+
+这个库同样在输出PDF文档时制造略缩的列表,或在目录中激活链接
+
+
+\section{End}
+
+这就是全部内容了!
+
+% 通常,你会希望文章中有个引用部分
+% 最简单的建立方式是使用书目提要章节
+\begin{thebibliography}{1}
+ % 与其他列表相同, \bibitem 命令被用来列出条目
+ % 每个记录可以直接被文章主体引用
+ \bibitem{latexwiki} The amazing \LaTeX \hspace{1pt} wikibook: {\em
+https://en.wikibooks.org/wiki/LaTeX}
+ \bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com}
+\end{thebibliography}
+
+% 结束文档
+\end{document}
+```
+
+## LaTeX 进阶
+
+* The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX)
+* An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
diff --git a/zh-cn/less-cn.html.markdown b/zh-cn/less-cn.html.markdown
new file mode 100644
index 00000000..365a0287
--- /dev/null
+++ b/zh-cn/less-cn.html.markdown
@@ -0,0 +1,387 @@
+---
+language: less
+filename: learnless-cn.less
+contributors:
+ - ["Saravanan Ganesh", "http://srrvnn.me"]
+translators:
+ - ["Jiang Haiyun", "http://www.atjiang.com"]
+lang: zh-cn
+---
+
+
+Less是一种CSS预处理器,它增加了诸如变量、嵌套、mixin等功能。
+Less(以及其它预处理器,如[Sass](http://sass-lang.com/))能帮助开发人员编写易维护,DRY (Don't Repeat Yourself) 的代码。
+
+```css
+
+
+//单行注释在编译成CSS后会被删除。
+
+/* 多行注释将保留. */
+
+
+
+/* 变量
+==============================*/
+
+
+/* 你可以将一个CSS值(如一个颜色值)保存到变量中。
+ 使用'@'符号来创建一个变量。*/
+
+@primary-color: #a3a4ff;
+@secondary-color: #51527f;
+@body-font: 'Roboto', sans-serif;
+
+/* 你可以在你的样式文件中使用这些变量。
+ 现在假如你想修改颜色,你只需修改一次即可。*/
+
+body {
+ background-color: @primary-color;
+ color: @secondary-color;
+ font-family: @body-font;
+}
+
+/* 以上将编译成: */
+
+body {
+ background-color: #a3a4ff;
+ color: #51527F;
+ font-family: 'Roboto', sans-serif;
+}
+
+
+/* 相比于在你的样式文件中逐个修改,这种方式维护性更好。 */
+
+
+
+/* Mixins
+==============================*/
+
+
+/* 如果你要为多个元素编写同样的代码,
+ 你可能想实现轻松地重用。*/
+
+.center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+/* 你只需简单地将选择子作为样式添加进来就能使用mixin了 */
+
+div {
+ .center;
+ background-color: @primary-color;
+}
+
+/* 它将编译成: */
+
+.center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #a3a4ff;
+}
+
+/* 通过在选择子后添加括号,可以使这些mixin代码不被编译 */
+
+.center() {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+div {
+ .center;
+ background-color: @primary-color;
+}
+
+/* 将编译成: */
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #a3a4ff;
+}
+
+
+
+/* 嵌套
+==============================*/
+
+
+/* Less允许你在选择子中嵌套选择子 */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: #f00;
+ }
+}
+
+/* '&'将被替换成父选择子。*/
+/* 你也可以嵌套伪类。 */
+/* 注意过度嵌套将会导致代码难以维护。
+ 最佳实践推荐在嵌套时不超过3层。
+ 例如: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: red;
+
+ &:hover {
+ background-color: blue;
+ }
+
+ a {
+ color: white;
+ }
+ }
+}
+
+/* 编译成: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+}
+
+ul li {
+ background-color: red;
+}
+
+ul li:hover {
+ background-color: blue;
+}
+
+ul li a {
+ color: white;
+}
+
+
+
+/* 函数
+==============================*/
+
+
+/* Less提供的函数可以用来完成多种任务。
+ 考虑以下情况: */
+
+/* 函数可以通过其名称及传入其所需的参数来调用。 */
+
+body {
+ width: round(10.25px);
+}
+
+.header {
+ background-color: lighten(#000, 0.5);
+}
+
+.footer {
+ background-color: fadeout(#000, 0.25)
+}
+
+/* 编译成: */
+
+body {
+ width: 10px;
+}
+
+.header {
+ background-color: #010101;
+}
+
+.footer {
+ background-color: rgba(0, 0, 0, 0.75);
+}
+
+/* 你也可以定义自己的函数。函数非常类似于mixin。
+ 当你在函数和mixin之间抉择时,
+ 记住mixin最适合用来创建CSS而函数更适合于
+ 处理那些可能在你的Less代码中使用的逻辑。
+ '数学运算符'部分的例子是转成可重用函数的最佳选择。*/
+
+/* 该函数计算两数的平均值: */
+
+.average(@x, @y) {
+ @average-result: ((@x + @y) / 2);
+}
+
+div {
+ .average(16px, 50px); // "调用"mixin
+ padding: @average-result; // 使用它的"返回"值
+}
+
+/* 编译成: */
+
+div {
+ padding: 33px;
+}
+
+
+
+/* 扩展 (继承)
+==============================*/
+
+
+/* 扩展是在选择子间共享属性的一种方法。 */
+
+.display {
+ height: 50px;
+}
+
+.display-success {
+ &:extend(.display);
+ border-color: #22df56;
+}
+
+/* 编译成: */
+.display,
+.display-success {
+ height: 50px;
+}
+.display-success {
+ border-color: #22df56;
+}
+
+/* 扩展一条CSS语句优于创建一个mixin,
+ 这是由其组合所有共享相同基样式的类的方式决定的。
+ 如果使用mixin完成,其属性将会在调用了该mixin的每条语句中重复。
+ 虽然它不至会影响你的工作流,但它会在由Less编译器
+ 生成的的文件中添加不必要的代码。*/
+
+
+
+/* 片段与导入
+==============================*/
+
+
+/* Less允许你创建片段文件。它有助于你的Less代码保持模块化。
+ 片段文件习惯上以'_'开头,例如 _reset.css,并被导入到
+ 一个将会被编译成CSS的主less文件中。*/
+
+/* 考虑以下的CSS,我们将把它们放入一个叫_reset.css的文件中 */
+
+html,
+body,
+ul,
+ol {
+ margin: 0;
+ padding: 0;
+}
+
+/* Less提供的@import能用来将片段导入到文件中。
+ 它与传统的CSS @import语句不同,无需通过
+ HTTP请求获取导入文件。Less提取导入文件
+ 并将它们与编译后的代码结合起来。 */
+
+@import 'reset';
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+/* 编译成: */
+
+html, body, ul, ol {
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+
+
+/* 数学运算符
+==============================*/
+
+
+/* Less提供以下的运算符: +, -, *, /, 和 %。
+ 相比于使用你事先手工计算好了的数值,它们
+ 对于直接在你的Less文件中计算数值很有用。
+ 以下是设置一个两列设计的例子。*/
+
+@content-area: 960px;
+@main-content: 600px;
+@sidebar-content: 300px;
+
+@main-size: @main-content / @content-area * 100%;
+@sidebar-size: @sidebar-content / @content-area * 100%;
+@gutter: 100% - (@main-size + @sidebar-size);
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: @main-size;
+}
+
+.sidebar {
+ width: @sidebar-size;
+}
+
+.gutter {
+ width: @gutter;
+}
+
+/* 编译成: */
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+.gutter {
+ width: 6.25%;
+}
+
+
+```
+
+## 实践Less
+
+如果你想在你的浏览器中尝试LESS,参阅:
+* [Codepen](http://codepen.io/)
+* [LESS2CSS](http://lesscss.org/less-preview/)
+
+## 兼容性
+
+Less可以用于任何项目中,只要你有程序能将它编译成CSS即可。你还需要验证你所使用的CSS是否与你的目标浏览器兼容。
+
+[QuirksMode CSS](http://www.quirksmode.org/css/)和[CanIUse](http://caniuse.com) 对于检查兼容性来说都是不错的资源。
+
+## 延伸阅读资料
+* [Official Documentation](http://lesscss.org/features/)
+* [Less CSS - Beginner's Guide](http://www.hongkiat.com/blog/less-basic/)
diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown
index 2d181de0..657a913d 100644
--- a/zh-cn/ruby-cn.html.markdown
+++ b/zh-cn/ruby-cn.html.markdown
@@ -214,7 +214,7 @@ hash.keys #=> ['color', 'number']
hash['color'] #=> 'green'
hash['number'] #=> 5
-# 查询一个不存在地键将会返回nil
+# 查询一个不存在的键将会返回nil
hash['nothing here'] #=> nil
# 从Ruby 1.9开始,用符号作为键的时候有特别的记号表示:
diff --git a/zh-cn/vim-cn.html.markdown b/zh-cn/vim-cn.html.markdown
index 0c3f6043..5298351a 100644
--- a/zh-cn/vim-cn.html.markdown
+++ b/zh-cn/vim-cn.html.markdown
@@ -3,9 +3,9 @@ category: tool
tool: vim
filename: LearnVim-cn.txt
contributors:
- - ["RadhikaG", "https://github.com/RadhikaG"]
+ - ["RadhikaG", "https://github.com/RadhikaG"]
translators:
- - ["Jiang Haiyun", "https://github.com/haiiiiiyun"]
+ - ["Jiang Haiyun", "https://github.com/haiiiiiyun"]
lang: zh-cn
---