diff options
-rw-r--r-- | angularjs.html.markdown | 710 | ||||
-rw-r--r-- | binary-search.html.markdown | 63 | ||||
-rw-r--r-- | csharp.html.markdown | 4 | ||||
-rw-r--r-- | de-de/go-de.html.markdown | 4 | ||||
-rw-r--r-- | de-de/ruby-de.html.markdown | 33 | ||||
-rw-r--r-- | es-es/edn-es.html.markdown | 111 | ||||
-rw-r--r-- | es-es/sass-es.html.markdown (renamed from sass-es.html.markdown) | 1 | ||||
-rw-r--r-- | latex.html.markdown | 13 | ||||
-rw-r--r-- | logtalk.html.markdown | 77 | ||||
-rw-r--r-- | messagepack.html.markdown | 172 | ||||
-rw-r--r-- | perl6.html.markdown | 367 | ||||
-rw-r--r-- | pt-br/c-pt.html.markdown | 2 | ||||
-rw-r--r-- | pt-br/clojure-macros-pt.html.markdown | 2 | ||||
-rw-r--r-- | pt-br/git-pt.html.markdown | 2 | ||||
-rw-r--r-- | pt-br/php-composer-pt.html.markdown | 184 | ||||
-rw-r--r-- | pt-br/vim-pt.html.markdown | 239 | ||||
-rw-r--r-- | pt-pt/git-pt.html.markdown | 2 | ||||
-rw-r--r-- | python3.html.markdown | 15 | ||||
-rw-r--r-- | sk-sk/LearnGit-sk.txt | 208 |
19 files changed, 1748 insertions, 461 deletions
diff --git a/angularjs.html.markdown b/angularjs.html.markdown new file mode 100644 index 00000000..f4f6375f --- /dev/null +++ b/angularjs.html.markdown @@ -0,0 +1,710 @@ +--- +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/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/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/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/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/sass-es.html.markdown b/es-es/sass-es.html.markdown index 3719dfe9..89e56ba5 100644 --- a/sass-es.html.markdown +++ b/es-es/sass-es.html.markdown @@ -8,6 +8,7 @@ contributors: - ["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). 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/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/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/perl6.html.markdown b/perl6.html.markdown index b5a25a41..d31955f0 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -37,11 +37,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 +56,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 +96,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 +198,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 +242,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 +261,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 +356,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 +427,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 +453,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 +624,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 +720,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 +765,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 +780,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 +798,48 @@ 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 {} }`). +# You can access the last exception with the special variable `$!` +# (use `$_` in a `CATCH` block) Note: This has no relation to $!variables. + +# You can throw an exception using `die`: +open 'foo' or die 'Error!'; #=> Error! +# Or more explicitly: +die X::AdHoc.new(payload => 'Error!'); + +## Using `try` and `CATCH` +# By using `try` and `CATCH` you can contain and handle exceptions without +# disrupting the rest of the program. +# 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 {} }`). + +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,22 +859,26 @@ 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] - # 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: my $actions = JSON::Tiny::Actions.new; @@ -1088,10 +1187,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 @@ -1165,7 +1265,8 @@ say so 'a' ~~ / a /; # More readable with some spaces! # 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), 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/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/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/python3.html.markdown b/python3.html.markdown index 341f0a39..9ce7790b 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -38,7 +38,7 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea 8 - 1 # => 7 10 * 2 # => 20 -# Except division which returns floats, real numbers, by default +# Except division which defaults to rounding down 35 / 5 # => 7.0 # Result of integer division truncated down both for positive and negative. @@ -47,8 +47,12 @@ 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 +# When one of the inputs is a float, result is a float +10.0 / 3 # => 3.3333333333333335 + +# to force this behavior on integers, use +from __future__ import division +10 / 3 # => 3.3333333333333335 # Modulo operation 7 % 3 # => 1 @@ -761,8 +765,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/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 - - - - - - - - - |